From 564608de0324a6bddb35b652869faca247259ab7 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 17 May 2025 14:14:21 -0700 Subject: [PATCH 1/5] chore: :recycle: lift changes from #5694 to fetch package so I can build on top of them --- packages/fetch/src/fetch.ts | 35 +++++++++++++++++++++------------ packages/fetch/src/stream.ts | 38 +++++++++++++++++++++++------------- 2 files changed, 47 insertions(+), 26 deletions(-) diff --git a/packages/fetch/src/fetch.ts b/packages/fetch/src/fetch.ts index 4f9c60b10..4e0d60a2f 100644 --- a/packages/fetch/src/fetch.ts +++ b/packages/fetch/src/fetch.ts @@ -107,19 +107,30 @@ export async function fetchwithRequestOptions( } // fetch the request with the provided options - const resp = await fetch(url, { - ...init, - body: updatedBody ?? init?.body, - headers: headers, - agent: agent, - }); + try { + const resp = await fetch(url, { + ...init, + body: updatedBody ?? init?.body, + headers: headers, + agent: agent, + }); - if (!resp.ok) { - const requestId = resp.headers.get("x-request-id"); - if (requestId) { - console.log(`Request ID: ${requestId}, Status: ${resp.status}`); + if (!resp.ok) { + const requestId = resp.headers.get("x-request-id"); + if (requestId) { + console.log(`Request ID: ${requestId}, Status: ${resp.status}`); + } } - } - return resp; + return resp; + } catch (error) { + if (error instanceof Error && error.name === "AbortError") { + // Return a Response object that streamResponse etc can handle + return new Response(null, { + status: 499, // Client Closed Request + statusText: "Client Closed Request", + }); + } + throw error; + } } diff --git a/packages/fetch/src/stream.ts b/packages/fetch/src/stream.ts index 7f33e377d..8181a0a53 100644 --- a/packages/fetch/src/stream.ts +++ b/packages/fetch/src/stream.ts @@ -10,6 +10,9 @@ export async function* toAsyncIterable( export async function* streamResponse( response: Response, ): AsyncGenerator { + if (response.status === 499) { + return; // In case of client-side cancellation, just return + } if (response.status !== 200) { throw new Error(await response.text()); } @@ -21,22 +24,29 @@ export async function* streamResponse( // Get the major version of Node.js const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10); - if (nodeMajorVersion >= 20) { - // Use the new API for Node 20 and above - const stream = (ReadableStream as any).from(response.body); - for await (const chunk of stream.pipeThrough( - new TextDecoderStream("utf-8"), - )) { - yield chunk; + try { + if (nodeMajorVersion >= 20) { + // Use the new API for Node 20 and above + const stream = (ReadableStream as any).from(response.body); + for await (const chunk of stream.pipeThrough( + new TextDecoderStream("utf-8"), + )) { + yield chunk; + } + } else { + // Fallback for Node versions below 20 + // Streaming with this method doesn't work as version 20+ does + const decoder = new TextDecoder("utf-8"); + const nodeStream = response.body as unknown as NodeJS.ReadableStream; + for await (const chunk of toAsyncIterable(nodeStream)) { + yield decoder.decode(chunk, { stream: true }); + } } - } else { - // Fallback for Node versions below 20 - // Streaming with this method doesn't work as version 20+ does - const decoder = new TextDecoder("utf-8"); - const nodeStream = response.body as unknown as NodeJS.ReadableStream; - for await (const chunk of toAsyncIterable(nodeStream)) { - yield decoder.decode(chunk, { stream: true }); + } catch (e) { + if (e instanceof Error && e.name.startsWith("AbortError")) { + return; // In case of client-side cancellation, just return } + throw e; } } From 97700804446d12702a05cc217f3b3b29788f7332 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 17 May 2025 14:26:17 -0700 Subject: [PATCH 2/5] set up testing for continuedev/fetch package --- packages/fetch/jest.config.d.ts | 7 - packages/fetch/jest.config.js | 143 ------------ packages/fetch/jest.config.mjs | 20 ++ packages/fetch/jest.config.ts | 199 ---------------- packages/fetch/package-lock.json | 363 +++++++++++++++++++++++++++++- packages/fetch/package.json | 8 +- packages/fetch/src/stream.test.ts | 49 ++++ packages/fetch/src/stream.ts | 11 +- packages/fetch/tsconfig.json | 2 +- 9 files changed, 448 insertions(+), 354 deletions(-) delete mode 100644 packages/fetch/jest.config.d.ts delete mode 100644 packages/fetch/jest.config.js create mode 100644 packages/fetch/jest.config.mjs delete mode 100644 packages/fetch/jest.config.ts create mode 100644 packages/fetch/src/stream.test.ts diff --git a/packages/fetch/jest.config.d.ts b/packages/fetch/jest.config.d.ts deleted file mode 100644 index fb09cd361..000000000 --- a/packages/fetch/jest.config.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * For a detailed explanation regarding each configuration property, visit: - * https://jestjs.io/docs/configuration - */ -import type { Config } from 'jest'; -declare const config: Config; -export default config; diff --git a/packages/fetch/jest.config.js b/packages/fetch/jest.config.js deleted file mode 100644 index 841db2c58..000000000 --- a/packages/fetch/jest.config.js +++ /dev/null @@ -1,143 +0,0 @@ -/** - * For a detailed explanation regarding each configuration property, visit: - * https://jestjs.io/docs/configuration - */ -const config = { - // All imported modules in your tests should be mocked automatically - // automock: false, - // Stop running tests after `n` failures - // bail: 0, - // The directory where Jest should store its cached dependency information - // cacheDirectory: "/private/var/folders/n_/c3r8w0s95xl271j98y2lzhz80000gn/T/jest_dx", - // Automatically clear mock calls, instances, contexts and results before every test - clearMocks: true, - // Indicates whether the coverage information should be collected while executing the test - collectCoverage: true, - // An array of glob patterns indicating a set of files for which coverage information should be collected - // collectCoverageFrom: undefined, - // The directory where Jest should output its coverage files - coverageDirectory: "coverage", - // An array of regexp pattern strings used to skip coverage collection - // coveragePathIgnorePatterns: [ - // "/node_modules/" - // ], - // Indicates which provider should be used to instrument code for coverage - coverageProvider: "v8", - // A list of reporter names that Jest uses when writing coverage reports - // coverageReporters: [ - // "json", - // "text", - // "lcov", - // "clover" - // ], - // An object that configures minimum threshold enforcement for coverage results - // coverageThreshold: undefined, - // A path to a custom dependency extractor - // dependencyExtractor: undefined, - // Make calling deprecated APIs throw helpful error messages - // errorOnDeprecated: false, - // The default configuration for fake timers - // fakeTimers: { - // "enableGlobally": false - // }, - // Force coverage collection from ignored files using an array of glob patterns - // forceCoverageMatch: [], - // A path to a module which exports an async function that is triggered once before all test suites - // globalSetup: undefined, - // A path to a module which exports an async function that is triggered once after all test suites - // globalTeardown: undefined, - // A set of global variables that need to be available in all test environments - // globals: {}, - // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. - // maxWorkers: "50%", - // An array of directory names to be searched recursively up from the requiring module's location - // moduleDirectories: [ - // "node_modules" - // ], - // An array of file extensions your modules use - // moduleFileExtensions: [ - // "js", - // "mjs", - // "cjs", - // "jsx", - // "ts", - // "tsx", - // "json", - // "node" - // ], - // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module - // moduleNameMapper: {}, - // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader - // modulePathIgnorePatterns: [], - // Activates notifications for test results - // notify: false, - // An enum that specifies notification mode. Requires { notify: true } - // notifyMode: "failure-change", - // A preset that is used as a base for Jest's configuration - // preset: undefined, - // Run tests from one or more projects - // projects: undefined, - // Use this configuration option to add custom reporters to Jest - // reporters: undefined, - // Automatically reset mock state before every test - // resetMocks: false, - // Reset the module registry before running each individual test - // resetModules: false, - // A path to a custom resolver - // resolver: undefined, - // Automatically restore mock state and implementation before every test - // restoreMocks: false, - // The root directory that Jest should scan for tests and modules within - // rootDir: undefined, - // A list of paths to directories that Jest should use to search for files in - // roots: [ - // "" - // ], - // Allows you to use a custom runner instead of Jest's default test runner - // runner: "jest-runner", - // The paths to modules that run some code to configure or set up the testing environment before each test - // setupFiles: [], - // A list of paths to modules that run some code to configure or set up the testing framework before each test - // setupFilesAfterEnv: [], - // The number of seconds after which a test is considered as slow and reported as such in the results. - // slowTestThreshold: 5, - // A list of paths to snapshot serializer modules Jest should use for snapshot testing - // snapshotSerializers: [], - // The test environment that will be used for testing - // testEnvironment: "jest-environment-node", - // Options that will be passed to the testEnvironment - // testEnvironmentOptions: {}, - // Adds a location field to test results - // testLocationInResults: false, - // The glob patterns Jest uses to detect test files - // testMatch: [ - // "**/__tests__/**/*.[jt]s?(x)", - // "**/?(*.)+(spec|test).[tj]s?(x)" - // ], - // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped - // testPathIgnorePatterns: [ - // "/node_modules/" - // ], - // The regexp pattern or array of patterns that Jest uses to detect test files - // testRegex: [], - // This option allows the use of a custom results processor - // testResultsProcessor: undefined, - // This option allows use of a custom test runner - // testRunner: "jest-circus/runner", - // A map from regular expressions to paths to transformers - // transform: undefined, - // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation - // transformIgnorePatterns: [ - // "/node_modules/", - // "\\.pnp\\.[^\\/]+$" - // ], - // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them - // unmockedModulePathPatterns: undefined, - // Indicates whether each individual test should be reported during the run - // verbose: undefined, - // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode - // watchPathIgnorePatterns: [], - // Whether to use watchman for file crawling - // watchman: true, -}; -export default config; diff --git a/packages/fetch/jest.config.mjs b/packages/fetch/jest.config.mjs new file mode 100644 index 000000000..2592f3834 --- /dev/null +++ b/packages/fetch/jest.config.mjs @@ -0,0 +1,20 @@ +import path from "path"; +import { fileURLToPath } from "url"; + +export default { + transform: { + "\\.[jt]sx?$": ["ts-jest", { useESM: true }], + }, + + moduleNameMapper: { + "(.+)\\.js": "$1", + }, + extensionsToTreatAsEsm: [".ts"], + preset: "ts-jest/presets/default-esm", + testTimeout: 10000, + testEnvironment: "node", + globals: { + __dirname: path.dirname(fileURLToPath(import.meta.url)), + __filename: path.resolve(fileURLToPath(import.meta.url)), + }, +}; diff --git a/packages/fetch/jest.config.ts b/packages/fetch/jest.config.ts deleted file mode 100644 index 9d9d5daf9..000000000 --- a/packages/fetch/jest.config.ts +++ /dev/null @@ -1,199 +0,0 @@ -/** - * For a detailed explanation regarding each configuration property, visit: - * https://jestjs.io/docs/configuration - */ - -import type {Config} from 'jest'; - -const config: Config = { - // All imported modules in your tests should be mocked automatically - // automock: false, - - // Stop running tests after `n` failures - // bail: 0, - - // The directory where Jest should store its cached dependency information - // cacheDirectory: "/private/var/folders/n_/c3r8w0s95xl271j98y2lzhz80000gn/T/jest_dx", - - // Automatically clear mock calls, instances, contexts and results before every test - clearMocks: true, - - // Indicates whether the coverage information should be collected while executing the test - collectCoverage: true, - - // An array of glob patterns indicating a set of files for which coverage information should be collected - // collectCoverageFrom: undefined, - - // The directory where Jest should output its coverage files - coverageDirectory: "coverage", - - // An array of regexp pattern strings used to skip coverage collection - // coveragePathIgnorePatterns: [ - // "/node_modules/" - // ], - - // Indicates which provider should be used to instrument code for coverage - coverageProvider: "v8", - - // A list of reporter names that Jest uses when writing coverage reports - // coverageReporters: [ - // "json", - // "text", - // "lcov", - // "clover" - // ], - - // An object that configures minimum threshold enforcement for coverage results - // coverageThreshold: undefined, - - // A path to a custom dependency extractor - // dependencyExtractor: undefined, - - // Make calling deprecated APIs throw helpful error messages - // errorOnDeprecated: false, - - // The default configuration for fake timers - // fakeTimers: { - // "enableGlobally": false - // }, - - // Force coverage collection from ignored files using an array of glob patterns - // forceCoverageMatch: [], - - // A path to a module which exports an async function that is triggered once before all test suites - // globalSetup: undefined, - - // A path to a module which exports an async function that is triggered once after all test suites - // globalTeardown: undefined, - - // A set of global variables that need to be available in all test environments - // globals: {}, - - // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. - // maxWorkers: "50%", - - // An array of directory names to be searched recursively up from the requiring module's location - // moduleDirectories: [ - // "node_modules" - // ], - - // An array of file extensions your modules use - // moduleFileExtensions: [ - // "js", - // "mjs", - // "cjs", - // "jsx", - // "ts", - // "tsx", - // "json", - // "node" - // ], - - // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module - // moduleNameMapper: {}, - - // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader - // modulePathIgnorePatterns: [], - - // Activates notifications for test results - // notify: false, - - // An enum that specifies notification mode. Requires { notify: true } - // notifyMode: "failure-change", - - // A preset that is used as a base for Jest's configuration - // preset: undefined, - - // Run tests from one or more projects - // projects: undefined, - - // Use this configuration option to add custom reporters to Jest - // reporters: undefined, - - // Automatically reset mock state before every test - // resetMocks: false, - - // Reset the module registry before running each individual test - // resetModules: false, - - // A path to a custom resolver - // resolver: undefined, - - // Automatically restore mock state and implementation before every test - // restoreMocks: false, - - // The root directory that Jest should scan for tests and modules within - // rootDir: undefined, - - // A list of paths to directories that Jest should use to search for files in - // roots: [ - // "" - // ], - - // Allows you to use a custom runner instead of Jest's default test runner - // runner: "jest-runner", - - // The paths to modules that run some code to configure or set up the testing environment before each test - // setupFiles: [], - - // A list of paths to modules that run some code to configure or set up the testing framework before each test - // setupFilesAfterEnv: [], - - // The number of seconds after which a test is considered as slow and reported as such in the results. - // slowTestThreshold: 5, - - // A list of paths to snapshot serializer modules Jest should use for snapshot testing - // snapshotSerializers: [], - - // The test environment that will be used for testing - // testEnvironment: "jest-environment-node", - - // Options that will be passed to the testEnvironment - // testEnvironmentOptions: {}, - - // Adds a location field to test results - // testLocationInResults: false, - - // The glob patterns Jest uses to detect test files - // testMatch: [ - // "**/__tests__/**/*.[jt]s?(x)", - // "**/?(*.)+(spec|test).[tj]s?(x)" - // ], - - // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped - // testPathIgnorePatterns: [ - // "/node_modules/" - // ], - - // The regexp pattern or array of patterns that Jest uses to detect test files - // testRegex: [], - - // This option allows the use of a custom results processor - // testResultsProcessor: undefined, - - // This option allows use of a custom test runner - // testRunner: "jest-circus/runner", - - // A map from regular expressions to paths to transformers - // transform: undefined, - - // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation - // transformIgnorePatterns: [ - // "/node_modules/", - // "\\.pnp\\.[^\\/]+$" - // ], - - // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them - // unmockedModulePathPatterns: undefined, - - // Indicates whether each individual test should be reported during the run - // verbose: undefined, - - // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode - // watchPathIgnorePatterns: [], - - // Whether to use watchman for file crawling - // watchman: true, -}; - -export default config; diff --git a/packages/fetch/package-lock.json b/packages/fetch/package-lock.json index bb318db1f..6cae4bd06 100644 --- a/packages/fetch/package-lock.json +++ b/packages/fetch/package-lock.json @@ -17,7 +17,11 @@ }, "devDependencies": { "@types/follow-redirects": "^1.14.4", - "jest": "^29.7.0" + "@types/jest": "^29.5.14", + "cross-env": "^7.0.3", + "jest": "^29.7.0", + "ts-jest": "^29.3.4", + "ts-node": "^10.9.2" } }, "node_modules/@ampproject/remapping": { @@ -597,6 +601,28 @@ "zod": "^3.23.8" } }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, "node_modules/@istanbuljs/load-nyc-config": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", @@ -972,6 +998,30 @@ "@sinonjs/commons": "^3.0.0" } }, + "node_modules/@tsconfig/node10": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz", + "integrity": "sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==", + "dev": true + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", + "dev": true + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", + "dev": true + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", + "dev": true + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -1055,6 +1105,16 @@ "@types/istanbul-lib-report": "*" } }, + "node_modules/@types/jest": { + "version": "29.5.14", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.14.tgz", + "integrity": "sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==", + "dev": true, + "dependencies": { + "expect": "^29.0.0", + "pretty-format": "^29.0.0" + } + }, "node_modules/@types/node": { "version": "20.14.10", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.10.tgz", @@ -1085,6 +1145,30 @@ "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", "dev": true }, + "node_modules/acorn": { + "version": "8.14.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.1.tgz", + "integrity": "sha512-OvQ/2pUDKmgfCg++xsTX1wGxfTaszcHVcTctW4UJB4hibJx2HXxxO5UmVgyjMa+ZDsiaf5wWLXYpRWMmBI0QHg==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.4", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz", + "integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==", + "dev": true, + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/agent-base": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", @@ -1148,6 +1232,12 @@ "node": ">= 8" } }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true + }, "node_modules/argparse": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", @@ -1157,6 +1247,12 @@ "sprintf-js": "~1.0.2" } }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "dev": true + }, "node_modules/babel-jest": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", @@ -1324,6 +1420,18 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, + "node_modules/bs-logger": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", + "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", + "dev": true, + "dependencies": { + "fast-json-stable-stringify": "2.x" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/bser": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", @@ -1504,6 +1612,30 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "dev": true + }, + "node_modules/cross-env": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz", + "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.1" + }, + "bin": { + "cross-env": "src/bin/cross-env.js", + "cross-env-shell": "src/bin/cross-env-shell.js" + }, + "engines": { + "node": ">=10.14", + "npm": ">=6", + "yarn": ">=1" + } + }, "node_modules/cross-spawn": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", @@ -1574,6 +1706,15 @@ "node": ">=8" } }, + "node_modules/diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "dev": true, + "engines": { + "node": ">=0.3.1" + } + }, "node_modules/diff-sequences": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", @@ -1583,6 +1724,21 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/ejs": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", + "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==", + "dev": true, + "dependencies": { + "jake": "^10.8.5" + }, + "bin": { + "ejs": "bin/cli.js" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/electron-to-chromium": { "version": "1.4.824", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.824.tgz", @@ -1732,6 +1888,36 @@ "node": "^12.20 || >= 14.13" } }, + "node_modules/filelist": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz", + "integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==", + "dev": true, + "dependencies": { + "minimatch": "^5.0.1" + } + }, + "node_modules/filelist/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/filelist/node_modules/minimatch": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", + "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", + "dev": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/fill-range": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", @@ -2140,6 +2326,24 @@ "node": ">=8" } }, + "node_modules/jake": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.2.tgz", + "integrity": "sha512-2P4SQ0HrLQ+fw6llpLnOaGAvN2Zu6778SJMrCUwns4fOoG9ayrTiZk3VV8sCPkVZF8ab0zksVpS8FDY5pRCNBA==", + "dev": true, + "dependencies": { + "async": "^3.2.3", + "chalk": "^4.0.2", + "filelist": "^1.0.4", + "minimatch": "^3.1.2" + }, + "bin": { + "jake": "bin/cli.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/jest": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", @@ -2792,6 +2996,12 @@ "node": ">=8" } }, + "node_modules/lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", + "dev": true + }, "node_modules/lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", @@ -2828,6 +3038,12 @@ "node": ">=10" } }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true + }, "node_modules/makeerror": { "version": "1.0.12", "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", @@ -3460,6 +3676,122 @@ "node": ">=8.0" } }, + "node_modules/ts-jest": { + "version": "29.3.4", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.3.4.tgz", + "integrity": "sha512-Iqbrm8IXOmV+ggWHOTEbjwyCf2xZlUMv5npExksXohL+tk8va4Fjhb+X2+Rt9NBmgO7bJ8WpnMLOwih/DnMlFA==", + "dev": true, + "dependencies": { + "bs-logger": "^0.2.6", + "ejs": "^3.1.10", + "fast-json-stable-stringify": "^2.1.0", + "jest-util": "^29.0.0", + "json5": "^2.2.3", + "lodash.memoize": "^4.1.2", + "make-error": "^1.3.6", + "semver": "^7.7.2", + "type-fest": "^4.41.0", + "yargs-parser": "^21.1.1" + }, + "bin": { + "ts-jest": "cli.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0" + }, + "peerDependencies": { + "@babel/core": ">=7.0.0-beta.0 <8", + "@jest/transform": "^29.0.0", + "@jest/types": "^29.0.0", + "babel-jest": "^29.0.0", + "jest": "^29.0.0", + "typescript": ">=4.3 <6" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "@jest/transform": { + "optional": true + }, + "@jest/types": { + "optional": true + }, + "babel-jest": { + "optional": true + }, + "esbuild": { + "optional": true + } + } + }, + "node_modules/ts-jest/node_modules/semver": { + "version": "7.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/ts-jest/node_modules/type-fest": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", + "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", + "dev": true, + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ts-node": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", + "dev": true, + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } + }, "node_modules/type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", @@ -3481,6 +3813,20 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/typescript": { + "version": "5.8.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz", + "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", + "dev": true, + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, "node_modules/undici-types": { "version": "5.26.5", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", @@ -3517,6 +3863,12 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "dev": true + }, "node_modules/v8-to-istanbul": { "version": "9.3.0", "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz", @@ -3641,6 +3993,15 @@ "node": ">=12" } }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true, + "engines": { + "node": ">=6" + } + }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/packages/fetch/package.json b/packages/fetch/package.json index 9531fb128..0e6570760 100644 --- a/packages/fetch/package.json +++ b/packages/fetch/package.json @@ -6,7 +6,7 @@ "types": "dist/index.d.ts", "type": "module", "scripts": { - "test": "jest", + "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest", "build": "tsc" }, "author": "Nate Sesti and Ty Dunn", @@ -20,6 +20,10 @@ }, "devDependencies": { "@types/follow-redirects": "^1.14.4", - "jest": "^29.7.0" + "@types/jest": "^29.5.14", + "cross-env": "^7.0.3", + "jest": "^29.7.0", + "ts-jest": "^29.3.4", + "ts-node": "^10.9.2" } } diff --git a/packages/fetch/src/stream.test.ts b/packages/fetch/src/stream.test.ts new file mode 100644 index 000000000..d9950fa48 --- /dev/null +++ b/packages/fetch/src/stream.test.ts @@ -0,0 +1,49 @@ +// The parseDataLine function is not exported, so we need to import it +// indirectly by re-exporting it for testing purposes +import { parseDataLine } from "./stream.js"; + +describe("parseDataLine", () => { + test("parseDataLine should parse valid JSON data with 'data: ' prefix", () => { + const line = 'data: {"message":"hello","status":"ok"}'; + const result = parseDataLine(line); + expect(result).toEqual({ message: "hello", status: "ok" }); + }); + + test("parseDataLine should parse valid JSON data with 'data:' prefix (no space)", () => { + const line = 'data:{"message":"hello","status":"ok"}'; + const result = parseDataLine(line); + expect(result).toEqual({ message: "hello", status: "ok" }); + }); + + test("parseDataLine should throw error for malformed JSON", () => { + const line = "data: {invalid json}"; + expect(() => parseDataLine(line)).toThrow( + "Malformed JSON sent from server", + ); + }); + + test("parseDataLine should throw error when data contains error field", () => { + const line = 'data: {"error":"something went wrong"}'; + expect(() => parseDataLine(line)).toThrow( + "Error streaming response: something went wrong", + ); + }); + + test("parseDataLine should handle empty objects", () => { + const line = "data: {}"; + const result = parseDataLine(line); + expect(result).toEqual({}); + }); + + test("parseDataLine should handle arrays", () => { + const line = "data: [1,2,3]"; + const result = parseDataLine(line); + expect(result).toEqual([1, 2, 3]); + }); + + test("parseDataLine should handle nested objects", () => { + const line = 'data: {"user":{"name":"John","age":30}}'; + const result = parseDataLine(line); + expect(result).toEqual({ user: { name: "John", age: 30 } }); + }); +}); diff --git a/packages/fetch/src/stream.ts b/packages/fetch/src/stream.ts index 8181a0a53..385455827 100644 --- a/packages/fetch/src/stream.ts +++ b/packages/fetch/src/stream.ts @@ -50,7 +50,8 @@ export async function* streamResponse( } } -function parseDataLine(line: string): any { +// Export for testing purposes +export function parseDataLine(line: string): any { const json = line.startsWith("data: ") ? line.slice("data: ".length) : line.slice("data:".length); @@ -63,6 +64,14 @@ function parseDataLine(line: string): any { return data; } catch (e) { + // If the error was thrown by our error check, rethrow it + if ( + e instanceof Error && + e.message.startsWith("Error streaming response:") + ) { + throw e; + } + // Otherwise it's a JSON parsing error throw new Error(`Malformed JSON sent from server: ${json}`); } } diff --git a/packages/fetch/tsconfig.json b/packages/fetch/tsconfig.json index f21949f4b..132ebc03a 100644 --- a/packages/fetch/tsconfig.json +++ b/packages/fetch/tsconfig.json @@ -14,7 +14,7 @@ "resolveJsonModule": true, "isolatedModules": true, "noEmitOnError": false, - "types": ["node"], + "types": ["node", "jest"], "outDir": "dist", "declaration": true // "sourceMap": true From bf92579688bdc4539829dae25f1c58bfa9b84613 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 17 May 2025 16:01:27 -0700 Subject: [PATCH 3/5] separate file for getAgentOptions, with tests --- packages/fetch/src/fetch.test.ts | 172 ++++++++++++++++++++++++++ packages/fetch/src/fetch.ts | 53 +------- packages/fetch/src/getAgentOptions.ts | 62 ++++++++++ 3 files changed, 236 insertions(+), 51 deletions(-) create mode 100644 packages/fetch/src/fetch.test.ts create mode 100644 packages/fetch/src/getAgentOptions.ts diff --git a/packages/fetch/src/fetch.test.ts b/packages/fetch/src/fetch.test.ts new file mode 100644 index 000000000..7ef85871c --- /dev/null +++ b/packages/fetch/src/fetch.test.ts @@ -0,0 +1,172 @@ +import { globalAgent } from "https"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { getAgentOptions } from "./getAgentOptions.js"; + +// Store original env +const originalEnv = process.env; +const originalGlobalAgentOptions = { ...globalAgent.options }; + +// Temporary directory for test certificate files +let tempDir: string; + +beforeEach(() => { + // Create a temporary directory for test files + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "fetch-test-")); + + process.env = { ...originalEnv }; + + // Reset globalAgent for each test + globalAgent.options = { ...originalGlobalAgentOptions }; +}); + +afterEach(() => { + process.env = originalEnv; + globalAgent.options = originalGlobalAgentOptions; + + // Clean up temporary directory + try { + fs.rmSync(tempDir, { recursive: true, force: true }); + } catch (error) { + console.error(`Failed to remove temp directory: ${error}`); + } +}); + +// Helper function to create test certificate files +function createTestCertFile(filename: string, content: string): string { + const filePath = path.join(tempDir, filename); + fs.writeFileSync(filePath, content, "utf8"); + return filePath; +} + +test("getAgentOptions returns basic configuration with default values", () => { + const options = getAgentOptions(); + + // Check default timeout (7200 seconds = 2 hours = 7,200,000 ms) + expect(options.timeout).toBe(7200000); + expect(options.sessionTimeout).toBe(7200000); + expect(options.keepAliveMsecs).toBe(7200000); + expect(options.keepAlive).toBe(true); + + // Verify certificates array exists and contains items + expect(options.ca).toBeInstanceOf(Array); + expect(options.ca.length).toBeGreaterThan(0); + + // Verify at least one of the real TLS root certificates is included + // This assumes there's at least one certificate with "CERTIFICATE" in it + expect(options.ca.some((cert: any) => cert.includes("CERTIFICATE"))).toBe( + true, + ); +}); + +test("getAgentOptions respects custom timeout", () => { + const customTimeout = 300; // 5 minutes + const options = getAgentOptions({ timeout: customTimeout }); + + // Check timeout values (300 seconds = 300,000 ms) + expect(options.timeout).toBe(300000); + expect(options.sessionTimeout).toBe(300000); + expect(options.keepAliveMsecs).toBe(300000); +}); + +test("getAgentOptions uses verifySsl setting", () => { + // With verifySsl true + let options = getAgentOptions({ verifySsl: true }); + expect(options.rejectUnauthorized).toBe(true); + + // With verifySsl false + options = getAgentOptions({ verifySsl: false }); + expect(options.rejectUnauthorized).toBe(false); +}); + +test("getAgentOptions incorporates custom CA bundle paths", () => { + // Create a test CA bundle file + const caBundleContent = + "-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIJAMcuSp7chAYdMA==\n-----END CERTIFICATE-----"; + const caBundlePath = createTestCertFile("ca-bundle.pem", caBundleContent); + + // Single string path + let options = getAgentOptions({ caBundlePath }); + + // Verify that our test certificate is included in the CA list + expect(options.ca).toContain(caBundleContent); + + // Create multiple test CA bundle files + const caContent1 = + "-----BEGIN CERTIFICATE-----\nABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\n-----END CERTIFICATE-----"; + const caContent2 = + "-----BEGIN CERTIFICATE-----\n0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\n-----END CERTIFICATE-----"; + const caPath1 = createTestCertFile("ca1.pem", caContent1); + const caPath2 = createTestCertFile("ca2.pem", caContent2); + + // Array of paths + options = getAgentOptions({ + caBundlePath: [caPath1, caPath2], + }); + + // Verify that both test certificates are included in the CA list + expect(options.ca).toContain(caContent1); + expect(options.ca).toContain(caContent2); +}); + +test("getAgentOptions includes global certs when running as binary", () => { + // Set up test certs in globalAgent + globalAgent.options.ca = ["global-cert-1", "global-cert-2"]; + + // Set IS_BINARY environment variable + process.env.IS_BINARY = "true"; + + const options = getAgentOptions(); + + // Test for global certs + expect(options.ca).toContain("global-cert-1"); + expect(options.ca).toContain("global-cert-2"); +}); + +test("getAgentOptions handles client certificate configuration", () => { + // Create test certificate files + const clientCertContent = + "-----BEGIN CERTIFICATE-----\nCLIENTCERT\n-----END CERTIFICATE-----"; + const clientKeyContent = + "-----BEGIN PRIVATE KEY-----\nCLIENTKEY\n-----END PRIVATE KEY-----"; + const certPath = createTestCertFile("client.cert", clientCertContent); + const keyPath = createTestCertFile("client.key", clientKeyContent); + + const clientCertOptions = { + clientCertificate: { + cert: certPath, + key: keyPath, + passphrase: "secret-passphrase", + }, + }; + + const options = getAgentOptions(clientCertOptions); + + expect(options.cert).toBe(clientCertContent); + expect(options.key).toBe(clientKeyContent); + expect(options.passphrase).toBe("secret-passphrase"); +}); + +test("getAgentOptions handles client certificate without passphrase", () => { + // Create test certificate files + const clientCertContent = + "-----BEGIN CERTIFICATE-----\nCLIENTCERT2\n-----END CERTIFICATE-----"; + const clientKeyContent = + "-----BEGIN PRIVATE KEY-----\nCLIENTKEY2\n-----END PRIVATE KEY-----"; + const certPath = createTestCertFile("client2.cert", clientCertContent); + const keyPath = createTestCertFile("client2.key", clientKeyContent); + + const clientCertOptions = { + clientCertificate: { + cert: certPath, + key: keyPath, + }, + }; + + const options = getAgentOptions(clientCertOptions); + + expect(options.cert).toBe(clientCertContent); + expect(options.key).toBe(clientKeyContent); + expect(options.passphrase).toBeUndefined(); +}); diff --git a/packages/fetch/src/fetch.ts b/packages/fetch/src/fetch.ts index 4e0d60a2f..b481e806c 100644 --- a/packages/fetch/src/fetch.ts +++ b/packages/fetch/src/fetch.ts @@ -1,12 +1,9 @@ -import { globalAgent } from "https"; -import * as fs from "node:fs"; -import tls from "node:tls"; - import { RequestOptions } from "@continuedev/config-types"; import * as followRedirects from "follow-redirects"; import { HttpProxyAgent } from "http-proxy-agent"; import { HttpsProxyAgent } from "https-proxy-agent"; import fetch, { RequestInit, Response } from "node-fetch"; +import { getAgentOptions } from "./getAgentOptions.js"; const { http, https } = (followRedirects as any).default; @@ -20,53 +17,7 @@ export async function fetchwithRequestOptions( url.host = "127.0.0.1"; } - const TIMEOUT = 7200; // 7200 seconds = 2 hours - - let globalCerts: string[] = []; - if (process.env.IS_BINARY) { - if (Array.isArray(globalAgent.options.ca)) { - globalCerts = [...globalAgent.options.ca.map((cert) => cert.toString())]; - } else if (typeof globalAgent.options.ca !== "undefined") { - globalCerts.push(globalAgent.options.ca.toString()); - } - } - const ca = Array.from(new Set([...tls.rootCertificates, ...globalCerts])); - const customCerts = - typeof requestOptions?.caBundlePath === "string" - ? [requestOptions?.caBundlePath] - : requestOptions?.caBundlePath; - if (customCerts) { - ca.push( - ...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")), - ); - } - - const timeout = (requestOptions?.timeout ?? TIMEOUT) * 1000; // measured in ms - - const agentOptions: { [key: string]: any } = { - ca, - rejectUnauthorized: requestOptions?.verifySsl, - timeout, - sessionTimeout: timeout, - keepAlive: true, - keepAliveMsecs: timeout, - }; - - // Handle ClientCertificateOptions - if (requestOptions?.clientCertificate) { - agentOptions.cert = fs.readFileSync( - requestOptions.clientCertificate.cert, - "utf8", - ); - agentOptions.key = fs.readFileSync( - requestOptions.clientCertificate.key, - "utf8", - ); - if (requestOptions.clientCertificate.passphrase) { - agentOptions.passphrase = requestOptions.clientCertificate.passphrase; - } - } - + const agentOptions = getAgentOptions(requestOptions); const proxy = requestOptions?.proxy; // Create agent diff --git a/packages/fetch/src/getAgentOptions.ts b/packages/fetch/src/getAgentOptions.ts new file mode 100644 index 000000000..d86cad4e8 --- /dev/null +++ b/packages/fetch/src/getAgentOptions.ts @@ -0,0 +1,62 @@ +import { globalAgent } from "https"; +import * as fs from "node:fs"; +import tls from "node:tls"; + +import { RequestOptions } from "@continuedev/config-types"; + +/** + * Prepares agent options based on request options and certificates + */ +export function getAgentOptions(requestOptions?: RequestOptions): { + [key: string]: any; +} { + const TIMEOUT = 7200; // 7200 seconds = 2 hours + const timeout = (requestOptions?.timeout ?? TIMEOUT) * 1000; // measured in ms + + // Get root certificates + let globalCerts: string[] = []; + if (process.env.IS_BINARY) { + if (Array.isArray(globalAgent.options.ca)) { + globalCerts = [...globalAgent.options.ca.map((cert) => cert.toString())]; + } else if (typeof globalAgent.options.ca !== "undefined") { + globalCerts.push(globalAgent.options.ca.toString()); + } + } + + const ca = Array.from(new Set([...tls.rootCertificates, ...globalCerts])); + const customCerts = + typeof requestOptions?.caBundlePath === "string" + ? [requestOptions?.caBundlePath] + : requestOptions?.caBundlePath; + if (customCerts) { + ca.push( + ...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")), + ); + } + + const agentOptions: { [key: string]: any } = { + ca, + rejectUnauthorized: requestOptions?.verifySsl, + timeout, + sessionTimeout: timeout, + keepAlive: true, + keepAliveMsecs: timeout, + }; + + // Handle ClientCertificateOptions + if (requestOptions?.clientCertificate) { + agentOptions.cert = fs.readFileSync( + requestOptions.clientCertificate.cert, + "utf8", + ); + agentOptions.key = fs.readFileSync( + requestOptions.clientCertificate.key, + "utf8", + ); + if (requestOptions.clientCertificate.passphrase) { + agentOptions.passphrase = requestOptions.clientCertificate.passphrase; + } + } + + return agentOptions; +} From 367634f7d35fefbaeabeb302a0eb2a25dfb5cd76 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 17 May 2025 16:16:22 -0700 Subject: [PATCH 4/5] break out and test other utils --- packages/fetch/src/fetch.ts | 15 ++++- packages/fetch/src/util.test.ts | 102 ++++++++++++++++++++++++++++++++ packages/fetch/src/util.ts | 43 ++++++++++++++ 3 files changed, 158 insertions(+), 2 deletions(-) create mode 100644 packages/fetch/src/util.test.ts create mode 100644 packages/fetch/src/util.ts diff --git a/packages/fetch/src/fetch.ts b/packages/fetch/src/fetch.ts index b481e806c..59e0a887c 100644 --- a/packages/fetch/src/fetch.ts +++ b/packages/fetch/src/fetch.ts @@ -4,6 +4,7 @@ import { HttpProxyAgent } from "http-proxy-agent"; import { HttpsProxyAgent } from "https-proxy-agent"; import fetch, { RequestInit, Response } from "node-fetch"; import { getAgentOptions } from "./getAgentOptions.js"; +import { getProxyFromEnv, shouldBypassProxy } from "./util.js"; const { http, https } = (followRedirects as any).default; @@ -18,12 +19,22 @@ export async function fetchwithRequestOptions( } const agentOptions = getAgentOptions(requestOptions); - const proxy = requestOptions?.proxy; + + // Get proxy from options or environment variables + let proxy = requestOptions?.proxy; + if (!proxy) { + proxy = getProxyFromEnv(url.protocol); + } + + // Check if should bypass proxy based on requestOptions or NO_PROXY env var + const shouldBypass = + requestOptions?.noProxy?.includes(url.hostname) || + shouldBypassProxy(url.hostname); // Create agent const protocol = url.protocol === "https:" ? https : http; const agent = - proxy && !requestOptions?.noProxy?.includes(url.hostname) + proxy && !shouldBypass ? protocol === https ? new HttpsProxyAgent(proxy, agentOptions) : new HttpProxyAgent(proxy, agentOptions) diff --git a/packages/fetch/src/util.test.ts b/packages/fetch/src/util.test.ts new file mode 100644 index 000000000..b823a7d91 --- /dev/null +++ b/packages/fetch/src/util.test.ts @@ -0,0 +1,102 @@ +import { jest } from "@jest/globals"; +import { getProxyFromEnv, shouldBypassProxy } from "./util.js"; + +// Reset environment variables after each test +afterEach(() => { + jest.resetModules(); + process.env = {}; +}); + +// Tests for getProxyFromEnv +test("getProxyFromEnv returns undefined when no proxy is set", () => { + expect(getProxyFromEnv("http:")).toBeUndefined(); + expect(getProxyFromEnv("https:")).toBeUndefined(); +}); + +test("getProxyFromEnv returns HTTP_PROXY for http protocol", () => { + process.env.HTTP_PROXY = "http://proxy.example.com"; + expect(getProxyFromEnv("http:")).toBe("http://proxy.example.com"); +}); + +test("getProxyFromEnv returns lowercase http_proxy for http protocol", () => { + process.env.http_proxy = "http://proxy.example.com"; + expect(getProxyFromEnv("http:")).toBe("http://proxy.example.com"); +}); + +test("getProxyFromEnv prefers HTTP_PROXY over http_proxy for http protocol", () => { + process.env.HTTP_PROXY = "http://upper.example.com"; + process.env.http_proxy = "http://lower.example.com"; + expect(getProxyFromEnv("http:")).toBe("http://upper.example.com"); +}); + +test("getProxyFromEnv returns HTTPS_PROXY for https protocol", () => { + process.env.HTTPS_PROXY = "https://secure.example.com"; + expect(getProxyFromEnv("https:")).toBe("https://secure.example.com"); +}); + +test("getProxyFromEnv returns lowercase https_proxy for https protocol", () => { + process.env.https_proxy = "https://secure.example.com"; + expect(getProxyFromEnv("https:")).toBe("https://secure.example.com"); +}); + +test("getProxyFromEnv falls back to HTTP_PROXY for https protocol when HTTPS_PROXY is not set", () => { + process.env.HTTP_PROXY = "http://fallback.example.com"; + expect(getProxyFromEnv("https:")).toBe("http://fallback.example.com"); +}); + +test("getProxyFromEnv prefers HTTPS_PROXY over other env vars for https protocol", () => { + process.env.HTTPS_PROXY = "https://preferred.example.com"; + process.env.https_proxy = "https://notused1.example.com"; + process.env.HTTP_PROXY = "http://notused2.example.com"; + process.env.http_proxy = "http://notused3.example.com"; + expect(getProxyFromEnv("https:")).toBe("https://preferred.example.com"); +}); + +// Tests for shouldBypassProxy +test("shouldBypassProxy returns false when NO_PROXY is not set", () => { + expect(shouldBypassProxy("example.com")).toBe(false); +}); + +test("shouldBypassProxy returns true for exact hostname match", () => { + process.env.NO_PROXY = "example.com,another.com"; + expect(shouldBypassProxy("example.com")).toBe(true); +}); + +test("shouldBypassProxy returns false when hostname doesn't match any NO_PROXY entry", () => { + process.env.NO_PROXY = "example.com,another.com"; + expect(shouldBypassProxy("different.com")).toBe(false); +}); + +test("shouldBypassProxy handles lowercase no_proxy", () => { + process.env.no_proxy = "example.com"; + expect(shouldBypassProxy("example.com")).toBe(true); +}); + +test("shouldBypassProxy works with wildcard domains", () => { + process.env.NO_PROXY = "*.example.com"; + expect(shouldBypassProxy("sub.example.com")).toBe(true); + expect(shouldBypassProxy("example.com")).toBe(false); + expect(shouldBypassProxy("different.com")).toBe(false); +}); + +test("shouldBypassProxy works with domain suffix", () => { + process.env.NO_PROXY = ".example.com"; + expect(shouldBypassProxy("sub.example.com")).toBe(true); + expect(shouldBypassProxy("example.com")).toBe(true); + expect(shouldBypassProxy("different.com")).toBe(false); +}); + +test("shouldBypassProxy handles multiple entries with different patterns", () => { + process.env.NO_PROXY = "internal.local,*.example.com,.test.com"; + expect(shouldBypassProxy("internal.local")).toBe(true); + expect(shouldBypassProxy("sub.example.com")).toBe(true); + expect(shouldBypassProxy("sub.test.com")).toBe(true); + expect(shouldBypassProxy("test.com")).toBe(true); + expect(shouldBypassProxy("example.org")).toBe(false); +}); + +test("shouldBypassProxy ignores whitespace in NO_PROXY", () => { + process.env.NO_PROXY = " example.com , *.test.org "; + expect(shouldBypassProxy("example.com")).toBe(true); + expect(shouldBypassProxy("subdomain.test.org")).toBe(true); +}); diff --git a/packages/fetch/src/util.ts b/packages/fetch/src/util.ts new file mode 100644 index 000000000..20e3c1181 --- /dev/null +++ b/packages/fetch/src/util.ts @@ -0,0 +1,43 @@ +/** + * Gets the proxy settings from environment variables + * @param protocol The URL protocol (http: or https:) + * @returns The proxy URL if available, otherwise undefined + */ +export function getProxyFromEnv(protocol: string): string | undefined { + if (protocol === "https:") { + return ( + process.env.HTTPS_PROXY || + process.env.https_proxy || + process.env.HTTP_PROXY || + process.env.http_proxy + ); + } else { + return process.env.HTTP_PROXY || process.env.http_proxy; + } +} + +/** + * Checks if a hostname should bypass proxy based on NO_PROXY environment variable + * @param hostname The hostname to check + * @returns True if the hostname should bypass proxy + */ +export function shouldBypassProxy(hostname: string): boolean { + const noProxy = process.env.NO_PROXY || process.env.no_proxy; + if (!noProxy) return false; + + const noProxyItems = noProxy.split(",").map((item) => item.trim()); + + return noProxyItems.some((item) => { + // Exact match + if (item === hostname) return true; + + // Wildcard domain match (*.example.com) + if (item.startsWith("*.") && hostname.endsWith(item.substring(1))) + return true; + + // Domain suffix match (.example.com) + if (item.startsWith(".") && hostname.endsWith(item.slice(1))) return true; + + return false; + }); +} From 689308b8d62d162674ec919d7f80ad2a8dcb9e60 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 17 May 2025 16:17:18 -0700 Subject: [PATCH 5/5] bump version --- packages/fetch/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/fetch/package.json b/packages/fetch/package.json index 0e6570760..d22fe5b46 100644 --- a/packages/fetch/package.json +++ b/packages/fetch/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/fetch", - "version": "1.0.6", + "version": "1.0.9", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts",