Fix hook state leaks and fetch option forwarding
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Clone nested retry options before init hooks run so hook mutations do not leak across requests. Avoid canceling shared response bodies when an `afterResponse` hook wraps an existing body in a new `Response`. Forward all non-standard, non-Ky options directly to `fetch()` instead of filtering against `Request`, which removes the obsolete vendor allowlist and preserves fetch-only extensions like dispatcher and Next.js next.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 7f2eade · Browse files · 7 files·+249 added−24 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+249 added−24 removed
- tests:+212 added−0 removed
- other:+37 added−24 removed
Provenance
- Commit
2df9b7e- Tree
896b799- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
7f2eade
7 files changed+249 added−24 removed
modified:source/core/constants.ts-7 removed
257 unmodified lines258 fetch: true,259 context: true,260 };261 262-// Vendor-specific fetch options that should always be passed to fetch()263-// even if they appear on the Request object due to vendor patching.264-// See: https://github.com/sindresorhus/ky/issues/541265-export const vendorSpecificOptions = {266- next: true, // Next.js cache revalidation (revalidate, tags)267-} as const;268-262 // Standard RequestInit options that should NOT be passed separately to fetch()263 // because they're already applied to the Request object.264 // Note: `dispatcher` and `priority` are NOT included here - they're fetch-only265 // options that the Request constructor doesn't accept, so they need to be passed17 unmodified linesmodified:source/core/Ky.ts+26 added-5 removed
19 unmodified lines20 mergeHeaders,21 mergeHooks,22 deletedParametersSymbol,23 } from '../utils/merge.js';24+import type {RetryOptions} from '../types/retry.js';25 import {normalizeRequestMethod, normalizeRetryOptions} from '../utils/normalize.js';26 import timeout from '../utils/timeout.js';27 import delay from '../utils/delay.js';28 import {type ObjectEntries} from '../utils/types.js';29 unmodified lines58 };59 60 const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';61 62+const cloneRetryOptions = (retry: RetryOptions | number): RetryOptions | number => {63+ if (typeof retry !== 'object') {64+ return retry;65+ }66+67+ // Clone nested arrays too so init hooks can mutate retry config without leaking state across requests.68+ return {69+ ...retry,70+ ...(retry.methods && {methods: [...retry.methods]}),71+ ...(retry.statusCodes && {statusCodes: [...retry.statusCodes]}),72+ ...(retry.afterStatusCodes && {afterStatusCodes: [...retry.afterStatusCodes]}),73+ };74+};75+76 // Shallow-clone mutable option properties so init hook mutations don't leak across requests.77 function cloneInitHookOptions(options: Options): Options {63- return {78+ const clonedOptions: Options = {79 ...options,80 json: cloneShallow(options.json),66- retry: cloneShallow(options.retry)!,81 context: cloneShallow(options.context)!,82 headers: cloneShallow(options.headers)!,83 searchParams: cloneShallow(options.searchParams) as SearchParamsOption | undefined,84 };85+86+ if (options.retry !== undefined) {87+ clonedOptions.retry = cloneRetryOptions(options.retry);88+ }89+90+ return clonedOptions;91 }92 93 const validateJsonWithSchema = async (jsonValue: unknown, schema: StandardSchemaV1): Promise<unknown> => {94 if (695 unmodified lines790 );791 792 // Cancel any response bodies we won't use to prevent memory leaks.793 // Uses fire-and-forget since hooks may have cloned the response, creating tee branches that block cancellation.774- if (clonedResponse !== nextResponse) {794+ // If the hook wrapped an existing body into a new Response, both Response objects can still point at the same stream.795+ if (clonedResponse !== nextResponse && clonedResponse.body !== nextResponse.body) {796 this.#cancelResponseBody(clonedResponse);797 }798 778- if (response !== nextResponse) {799+ if (response !== nextResponse && response.body !== nextResponse.body) {800 this.#cancelResponseBody(response);801 }802 803 response = nextResponse;97 unmodified lines901 // Recreate request with new signal902 this.request = new globalThis.Request(this.request, {signal: this.#options.signal});903 }904 884- const nonRequestOptions = findUnknownOptions(this.request, this.#options);905+ const nonRequestOptions = findUnknownOptions(this.#options);906 const retryRequest = this.#options.retry.limit > 0 ? this.request.clone() : undefined;907 const request = this.#wrapRequestWithUploadProgress(this.request, this.#options.body ?? undefined);908 909 // Cloning is done here to prepare in advance for retries.93 unmodified linesmodified:source/utils/normalize.ts+4 added-3 removed
35 unmodified lines363738394041404142434644454647484950512 unmodified lines35 unmodified lines if (retry.methods && !Array.isArray(retry.methods)) { throw new Error('retry.methods must be an array'); }
retry.methods &&= retry.methods.map(method => method.toLowerCase());
if (retry.statusCodes && !Array.isArray(retry.statusCodes)) { throw new Error('retry.statusCodes must be an array'); }
const normalizedRetry = Object.fromEntries(Object.entries(retry).filter(([, value]) => value !== undefined)) as RetryOptions; const normalizedRetry = Object.fromEntries(Object.entries({ ...retry, methods: retry.methods?.map(method => method.toLowerCase()), }).filter(([, value]) => value !== undefined)) as RetryOptions;
return { ...defaultRetryOptions, ...normalizedRetry,2 unmodified linesmodified:source/utils/options.ts+7 added-9 removed
112345667892 unmodified lines12131415171819202122231617181920212223242528 unmodified linesimport {kyOptionKeys, requestOptionsRegistry, vendorSpecificOptions} from '../core/constants.js';import {kyOptionKeys, requestOptionsRegistry} from '../core/constants.js';import type {SearchParamsOption} from '../types/options.js';import {deletedParametersSymbol} from './merge.js';
export const findUnknownOptions = ( request: Request, options: Record<string, unknown>,): Record<string, unknown> => { const unknownOptions: Record<string, unknown> = {};
2 unmodified lines if (!Object.hasOwn(options, key)) { continue; }
// An option is passed to fetch() if: // 1. It's not a standard RequestInit option (not in requestOptionsRegistry) // 2. It's not a ky-specific option (not in kyOptionKeys) // 3. Either: // a. It's not on the Request object, OR // b. It's a vendor-specific option that should always be passed (in vendorSpecificOptions) if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys) && (!(key in request) || key in vendorSpecificOptions)) { // Forward every non-standard, non-Ky option to fetch(). // We intentionally do not check whether the key also exists on `Request`, because some runtimes // patch `Request.prototype` with fetch-only extensions. For example, Next.js adds `next`, and the // old `key in request` heuristic dropped it unless Ky kept a special-case allowlist. // Passing all non-standard keys makes that allowlist unnecessary and preserves future fetch extensions too. if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys)) { unknownOptions[key] = options[key]; } }
28 unmodified linesmodified:test/fetch.ts+57 added
133 unmodified lines134 135 await ky(fixture, {...options, fetch: customFetch}).text();136 });137 138+test('unknown options with falsy values are passed to fetch', async t => {139+ t.plan(3);140+141+ const customFetch: typeof fetch = async (request, init) => {142+ t.is(init.customNull, null);143+ t.is(init.customFalse, false);144+ t.is(init.customZero, 0);145+ return new Response(request.url);146+ };147+148+ await ky(fixture, {149+ customNull: null, customFalse: false, customZero: 0, fetch: customFetch,150+ }).text();151+});152+153+test('ky-specific options are not passed to fetch', async t => {154+ const customFetch: typeof fetch = async (request, init) => {155+ t.is(init.retry, undefined);156+ t.is(init.timeout, undefined);157+ t.is(init.hooks, undefined);158+ t.is(init.throwHttpErrors, undefined);159+ t.is(init.json, undefined);160+ return new Response(request.url);161+ };162+163+ await ky(fixture, {retry: 3, timeout: 5000, fetch: customFetch}).text();164+});165+166 test('fetch-only options like dispatcher are passed to fetch', async t => {167 t.plan(1);168 169 const mockDispatcher = {name: 'custom-agent'};5 unmodified lines175 176 await ky(fixture, {dispatcher: mockDispatcher, fetch: customFetch}).text();177 });178 179+test.serial('fetch-only options like dispatcher are passed to fetch even when Request is patched', async t => {180+ t.plan(1);181+182+ const mockDispatcher = {name: 'custom-agent'};183+ const originalDescriptor = Object.getOwnPropertyDescriptor(Request.prototype, 'dispatcher');184+185+ try {186+ Object.defineProperty(Request.prototype, 'dispatcher', {187+ value: undefined,188+ writable: true,189+ enumerable: true,190+ configurable: true,191+ });192+193+ const customFetch: typeof fetch = async (request, init) => {194+ t.is(init.dispatcher, mockDispatcher);195+ return new Response(request.url);196+ };197+198+ await ky(fixture, {dispatcher: mockDispatcher, fetch: customFetch}).text();199+ } finally {200+ if (originalDescriptor) {201+ Object.defineProperty(Request.prototype, 'dispatcher', originalDescriptor);202+ } else {203+ delete (Request.prototype as any).dispatcher;204+ }205+ }206+});207+208 test('priority option is passed to fetch', async t => {209 t.plan(1);210 211 const customFetch: typeof fetch = async (request, init) => {40 unmodified linesmodified:test/hooks.ts+140 added
212 unmodified lines213 t.is(responseText, 'ok');214 t.true(originalResponse?.bodyUsed);215 });216 217+test('afterResponse hook can wrap the provided body in a new response', async t => {218+ const responseText = await ky('https://example.com', {219+ fetch: async () => new Response('ok', {220+ headers: {221+ 'content-type': 'text/plain',222+ },223+ }),224+ hooks: {225+ afterResponse: [226+ ({response}) => new Response(response.body, {227+ headers: response.headers,228+ }),229+ ],230+ },231+ }).text();232+233+ t.is(responseText, 'ok');234+});235+236+test('afterResponse hook can wrap a streaming body in a new response', async t => {237+ const customFetch = createStreamFetch({text: 'streamed'});238+239+ const responseText = await ky('https://example.com', {240+ fetch: customFetch,241+ hooks: {242+ afterResponse: [243+ ({response}) => new Response(response.body, {244+ headers: response.headers,245+ }),246+ ],247+ },248+ }).text();249+250+ t.is(responseText, 'streamed');251+});252+253+test('afterResponse hook chain can forward the same body through multiple hooks', async t => {254+ let originalResponse: Response | undefined;255+256+ const customFetch = createStreamFetch({257+ text: 'chained',258+ onResponse(response) {259+ originalResponse = response;260+ },261+ });262+263+ const responseText = await ky('https://example.com', {264+ fetch: customFetch,265+ hooks: {266+ afterResponse: [267+ ({response}) => new Response(response.body, {268+ headers: response.headers,269+ }),270+ ({response}) => new Response(response.body, {271+ headers: response.headers,272+ }),273+ ],274+ },275+ }).text();276+277+ t.is(responseText, 'chained');278+ // The original fetch response body should be cancelled since hooks created new wrappers279+ t.true(originalResponse?.bodyUsed);280+});281+282 test('afterResponse hook with multiple hooks cancels all unused clones', async t => {283 let originalResponse: Response | undefined;284 const clones: Response[] = [];285 4503 unmodified lines4789 4790 t.deepEqual(seenLimits, [2, 2]);4791 });4792 4793+test('init hook nested retry mutations do not leak across requests', async t => {4794+ const seenMethods: string[][] = [];4795+4796+ const api = ky.extend({4797+ retry: {4798+ methods: ['get'],4799+ },4800+ hooks: {4801+ init: [4802+ options => {4803+ seenMethods.push([...options.retry.methods]);4804+ options.retry.methods.push('post');4805+ },4806+ ],4807+ },4808+ });4809+4810+ const fetch: typeof globalThis.fetch = async () => new Response('ok');4811+4812+ await api.get('https://example.com', {fetch});4813+ await api.get('https://example.com', {fetch});4814+4815+ t.deepEqual(seenMethods, [['get'], ['get']]);4816+});4817+4818+test('init hook nested retry statusCodes mutations do not leak across requests', async t => {4819+ const seenStatusCodes: number[][] = [];4820+4821+ const api = ky.extend({4822+ retry: {4823+ statusCodes: [500],4824+ },4825+ hooks: {4826+ init: [4827+ options => {4828+ seenStatusCodes.push([...options.retry.statusCodes]);4829+ options.retry.statusCodes.push(502);4830+ },4831+ ],4832+ },4833+ });4834+4835+ const fetch: typeof globalThis.fetch = async () => new Response('ok');4836+4837+ await api.get('https://example.com', {fetch});4838+ await api.get('https://example.com', {fetch});4839+4840+ t.deepEqual(seenStatusCodes, [[500], [500]]);4841+});4842+4843+test('init hook nested retry afterStatusCodes mutations do not leak across requests', async t => {4844+ const seenAfterStatusCodes: number[][] = [];4845+4846+ const api = ky.extend({4847+ retry: {4848+ afterStatusCodes: [429],4849+ },4850+ hooks: {4851+ init: [4852+ options => {4853+ seenAfterStatusCodes.push([...options.retry.afterStatusCodes]);4854+ options.retry.afterStatusCodes.push(503);4855+ },4856+ ],4857+ },4858+ });4859+4860+ const fetch: typeof globalThis.fetch = async () => new Response('ok');4861+4862+ await api.get('https://example.com', {fetch});4863+ await api.get('https://example.com', {fetch});4864+4865+ t.deepEqual(seenAfterStatusCodes, [[429], [429]]);4866+});4867+4868 test('init hook in-place json mutations do not leak across requests', async t => {4869 let requestIdentifier = 0;4870 const seenRequestIdentifiers: string[] = [];4871 259 unmodified linesmodified:test/main.ts+15 added
776 unmodified lines777 778 t.true(duration < 10);779 });780 781+test('normalizing retry options does not mutate the caller retry object', async t => {782+ const retry = {783+ methods: ['GET'],784+ };785+786+ await ky('https://example.com', {787+ fetch: async () => new Response('ok'),788+ retry,789+ }).text();790+791+ t.deepEqual(retry, {792+ methods: ['GET'],793+ });794+});795+796 test('searchParams option', async t => {797 const server = await createHttpTestServer(t);798 799 server.get('/', (request, response) => {1613 unmodified lines