Harden retry
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent be60db5 · Browse files · 14 files·+878 added−86 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+878 added−86 removed
- tests:+612 added−1 removed
- other:+266 added−85 removed
Provenance
- Commit
c426f19- Tree
4b95535- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
be60db5
14 files changed+878 added−86 removed
modified:.github/security.md+3 added-1 removed
123345# Security Policy
To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.To report a security vulnerability, please submit it [here](https://github.com/sindresorhus/ky/security/advisories/new).
No AI slop will be accepted.modified:source/core/Ky.ts+124 added-55 removed
46 unmodified lines47 48 const maxErrorResponseBodySize = 10 * 1024 * 1024;49 const prefixUrlRenamedErrorMessage = 'The `prefixUrl` option has been renamed `prefix` in v2 and enhanced to allow slashes in input. See also the new `baseUrl` option for improved flexibility with standard URL resolution: https://github.com/sindresorhus/ky#baseurl';50 const timedOutResponseData = Symbol('timedOutResponseData');51+const timedOutOperation = Symbol('timedOutOperation');52 53 type ErrorDataTimeout = {54 milliseconds: number;55 fromTotalTimeout: boolean;13 unmodified lines69 70 const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';71 72 const cloneRetryOptions = (retry: RetryOptions | number): RetryOptions | number => {72- if (typeof retry !== 'object') {73- return retry;73+ if (retry === null || typeof retry !== 'object' || Array.isArray(retry)) {74+ return retry as RetryOptions | number;75 }76 77+ const clonedRetry = {...retry};78+79 // Clone nested arrays too so init hooks can mutate retry config without leaking state across requests.77- return {78- ...retry,79- ...(retry.methods && {methods: [...retry.methods]}),80- ...(retry.statusCodes && {statusCodes: [...retry.statusCodes]}),81- ...(retry.afterStatusCodes && {afterStatusCodes: [...retry.afterStatusCodes]}),82- };80+ if (Array.isArray(clonedRetry.methods)) {81+ clonedRetry.methods = [...clonedRetry.methods];82+ }83+84+ if (Array.isArray(clonedRetry.statusCodes)) {85+ clonedRetry.statusCodes = [...clonedRetry.statusCodes];86+ }87+88+ if (Array.isArray(clonedRetry.afterStatusCodes)) {89+ clonedRetry.afterStatusCodes = [...clonedRetry.afterStatusCodes];90+ }91+92+ return clonedRetry;93 };94 95 const objectToString = Object.prototype.toString;96 const leadingC0ControlOrSpacePattern = /^[\0-\u0020]+/g;93 unmodified lines190 191 // Delay the fetch so that body method shortcuts can set the Accept header192 await Promise.resolve();193 const beforeRequestResponse = await ky.#runBeforeRequestHooks();194+ if (beforeRequestResponse !== undefined) {195+ ky.#retryLimit = normalizeRetryOptions(ky.#options.retry).limit;196+ }197+198 let response = beforeRequestResponse ?? await ky.#retry(async () => ky.#fetch());199 let responseFromHook = beforeRequestResponse !== undefined200 || ky.#consumeReturnedResponseFromBeforeRetryHook();201 120 unmodified lines322 }323 324 const text = await ky.#raceBodyRead(async () => response.text(), response) as string;325 const request = ky.#getResponseRequest(response);312- return ky.#raceWithTotalTimeout(async () => {326+ const parsedResult = await ky.#raceWithTotalTimeout(async () => {327 if (text === '') {328 if (schema !== undefined) {329 return validateJsonWithSchema(undefined, schema);330 }5 unmodified lines336 ? await initHookOptions.parseJson(text, {request, response})337 : JSON.parse(text);338 339 return schema === undefined ? jsonValue : validateJsonWithSchema(jsonValue, schema);326- }, request);340+ });341+342+ if (parsedResult === timedOutOperation) {343+ await ky.#throwProcessedError(new TimeoutError(request));344+ }345+346+ return parsedResult;347 };348 }349 350 return result;11 unmodified lines362 363 public request: Request;364 #abortController?: AbortController;365 #retryCount = 0;366+ #retryLimit: number;367 readonly #input: Input;368 readonly #options: InternalOptions;369 #originalRequest?: Request;370 readonly #userProvidedAbortSignal?: AbortSignal;23 unmodified lines394 totalTimeout: options.totalTimeout ?? false,395 fetch: options.fetch ?? globalThis.fetch.bind(globalThis),396 context: options.context ?? {},397 };398+ this.#retryLimit = this.#options.retry.limit;399 400 if (typeof this.#input !== 'string' && !(this.#input instanceof URL || this.#input instanceof globalThis.Request)) {401 throw new TypeError('`input` must be a string, URL, or Request');402 }96 unmodified lines499 // Ky's internal scheduling and user hook time before the first fetch attempt.500 this.#startTime = typeof this.#options.totalTimeout === 'number' ? this.#getCurrentTime() : undefined;501 }502 481- #calculateDelay(): number {482- const retryDelay = this.#options.retry.delay(this.#retryCount + 1);503+ #calculateDelay(retry: InternalOptions['retry']): number {504+ const retryDelay = retry.delay(this.#retryCount + 1);505 506 let jitteredDelay = retryDelay;485- if (this.#options.retry.jitter === true) {507+ if (retry.jitter === true) {508 jitteredDelay = Math.random() * retryDelay;487- } else if (typeof this.#options.retry.jitter === 'function') {488- jitteredDelay = this.#options.retry.jitter(retryDelay);509+ } else if (typeof retry.jitter === 'function') {510+ jitteredDelay = retry.jitter(retryDelay);511 512 if (!Number.isFinite(jitteredDelay) || jitteredDelay < 0) {513 jitteredDelay = retryDelay;514 }515 }516 495- return Math.min(this.#options.retry.backoffLimit, jitteredDelay);517+ return Math.min(retry.backoffLimit, jitteredDelay);518 }519 520 async #calculateRetryDelay(error: unknown) {499- if (this.#retryCount >= this.#options.retry.limit) {521+ const retry = normalizeRetryOptions(this.#options.retry);522+ if (this.#retryCount >= Math.min(retry.limit, this.#retryLimit)) {523 throw error;524 }525 526 // Wrap non-Error throws to ensure consistent error handling527 const errorObject = error instanceof Error ? error : new NonError(error);528 529 // Handle forced retry from afterResponse hook - skip method check and shouldRetry530 if (errorObject instanceof ForceRetryError) {508- return errorObject.customDelay ?? this.#calculateDelay();531+ return errorObject.customDelay ?? this.#calculateDelay(retry);532 }533 534 // Check if method is retriable for non-forced retries512- if (!this.#options.retry.methods.includes(this.request.method.toLowerCase())) {535+ if (!retry.methods.includes(this.request.method.toLowerCase())) {536 throw error;537 }538 516- if (this.#options.retry.shouldRetry !== undefined) {517- const result = await this.#options.retry.shouldRetry({error: errorObject, retryCount: this.#retryCount + 1});539+ const {shouldRetry} = retry;540+ if (shouldRetry !== undefined) {541+ const result = await this.#raceWithTotalTimeout(async () => shouldRetry({error: errorObject, retryCount: this.#retryCount + 1}));542+ if (result === timedOutOperation) {543+ throw new TimeoutError(this.request);544+ }545 546 // Only exact booleans override the default retry checks.547 if (result === false) {548 throw error;549 }550 551 if (result === true) {525- return this.#calculateDelay();552+ return this.#calculateDelay(retry);553 }554 }555 556 // Default timeout behavior557 if (isTimeoutError(error)) {531- if (!this.#options.retry.retryOnTimeout) {558+ if (!retry.retryOnTimeout) {559 throw error;560 }561 535- return this.#calculateDelay();562+ return this.#calculateDelay(retry);563 }564 565 if (isHTTPError(error)) {539- if (!this.#options.retry.statusCodes.includes(error.response.status)) {566+ if (!retry.statusCodes.includes(error.response.status)) {567 throw error;568 }569 570 const retryTimingHeader = getRetryTimingHeader(error.response.headers);544- if (retryTimingHeader && this.#options.retry.afterStatusCodes.includes(error.response.status)) {571+ if (retryTimingHeader && retry.afterStatusCodes.includes(error.response.status)) {572 const after = calculateRetryTimingDelay(retryTimingHeader);573 if (after === undefined) {574 // Malformed retry timing headers should not disable retries; they only lose their server-provided timing.548- return this.#calculateDelay();575+ return this.#calculateDelay(retry);576 }577 578 // Don't apply jitter when server provides explicit retry timing552- return Math.min(this.#options.retry.maxRetryAfter, after);579+ return Math.min(retry.maxRetryAfter, after);580 }581 582 if (error.response.status === 413) {583 throw error;584 }585 559- return this.#calculateDelay();586+ return this.#calculateDelay(retry);587 }588 589 // Only retry known retriable error types. Unknown errors (e.g., programming bugs) are not retried.590 if (!isNetworkError(error)) {591 throw error;592 }593 567- return this.#calculateDelay();594+ return this.#calculateDelay(retry);595 }596 597 #decorateResponse(response: Response): Response {598 const request = this.#getResponseRequest(response);152 unmodified lines751 752 return result;753 }754 728- async #raceWithTotalTimeout<T>(operation: () => Promise<T>, request: Request): Promise<T> {755+ async #raceWithTotalTimeout<T>(operation: () => Promise<T>): Promise<T | typeof timedOutOperation> {756 const remainingTotal = this.#getRemainingTotalTimeout();757 if (remainingTotal === undefined) {758 return operation();759 }760 761 if (remainingTotal <= 0) {735- await this.#throwProcessedError(new TimeoutError(request));762+ this.#abortController?.abort();763+ return timedOutOperation;764 }765 738- const operationPromise = operation();739- const result = await Promise.race<T | typeof timedOutResponseData>([740- operationPromise,741- new Promise<typeof timedOutResponseData>(resolve => {742- const timeoutId = setTimeout(() => {743- resolve(timedOutResponseData);766+ let timeoutId: ReturnType<typeof setTimeout> | undefined;767+ try {768+ const timeoutPromise = new Promise<typeof timedOutOperation>(resolve => {769+ timeoutId = setTimeout(() => {770+ resolve(timedOutOperation);771 }, remainingTotal);745- void operationPromise.finally(() => {746- clearTimeout(timeoutId);747- }).catch(() => undefined);748- }),749- ]);772+ });773+ const operationResult = Promise.resolve()774+ .then(operation)775+ .then(value => ({status: 'fulfilled', value} as const))776+ .catch((error: unknown) => ({status: 'rejected', error} as const));777+ const result = await Promise.race([operationResult, timeoutPromise]);778+ const remainingAfterOperation = this.#getRemainingTotalTimeout();779+ const didTimeOut = result === timedOutOperation || (remainingAfterOperation !== undefined && remainingAfterOperation <= 0);780+ if (didTimeOut) {781+ this.#abortController?.abort();782 751- if (result === timedOutResponseData) {752- await this.#throwProcessedError(new TimeoutError(request));753- }783+ if (result === timedOutOperation) {784+ void operationResult.then(result => {785+ if (result.status === 'fulfilled') {786+ this.#cancelReturnedBody(result.value);787+ }788+ });789+ } else if (result.status === 'fulfilled') {790+ this.#cancelReturnedBody(result.value);791+ }792 755- return result as T;793+ return timedOutOperation;794+ }795+796+ if (result.status === 'rejected') {797+ throw result.error;798+ }799+800+ return result.value;801+ } finally {802+ clearTimeout(timeoutId);803+ }804 }805 806 #isJsonContentType(contentType: string): boolean {807 // Match JSON subtypes like `json`, `problem+json`, and `vnd.api+json`.99 unmodified lines907 // Ignore cancellation failures from already-locked or already-consumed streams.908 this.#cancelBody(response.body ?? undefined);909 }910 911+ #cancelReturnedBody(value: unknown): void {912+ if (isResponseInstance(value)) {913+ this.#cancelResponseBody(value);914+ } else if (isRequestInstance(value)) {915+ this.#cancelBody(value.body ?? undefined);916+ }917+ }918+919 #createManagedSignal(): AbortSignal {920 return this.#userProvidedAbortSignal921 ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController!.signal])922 : this.#abortController!.signal;8 unmodified lines931 932 async #runBeforeRequestHooks(): Promise<Response | undefined> {933 for (const hook of this.#options.hooks.beforeRequest) {934 // eslint-disable-next-line no-await-in-loop879- const result = await hook({935+ const result = await this.#raceWithTotalTimeout(async () => hook({936 request: this.request,937 options: this.#getNormalizedOptions(),938 retryCount: 0,883- });939+ }));940 941+ if (result === timedOutOperation) {942+ throw new TimeoutError(this.request);943+ }944+945 if (isRequestInstance(result)) {946 this.#assignRequest(result);947 } else if (isResponseInstance(result)) {948 return result;12 unmodified lines961 962 let modifiedResponse;963 try {964 // eslint-disable-next-line no-await-in-loop905- modifiedResponse = await hook({965+ modifiedResponse = await this.#raceWithTotalTimeout(async () => hook({966 request: this.request,967 options: this.#getNormalizedOptions(),968 response: hookResponse,969 retryCount: this.#retryCount,910- });970+ }));971+972+ if (modifiedResponse === timedOutOperation) {973+ throw new TimeoutError(this.request);974+ }975 } catch (error) {976 // Cancel both responses to prevent memory leaks when hook throws977 if (hookResponse !== response) {978 this.#cancelResponseBody(hookResponse);77 unmodified lines1056 this.#assignRequest(customRequest);1057 }1058 1059 for (const hook of this.#options.hooks.beforeRetry) {996- let hookResult: Awaited<ReturnType<typeof hook>>;1060+ let hookResult: Awaited<ReturnType<typeof hook>> | typeof timedOutOperation;1061 try {1062 // eslint-disable-next-line no-await-in-loop999- hookResult = await hook({1063+ hookResult = await this.#raceWithTotalTimeout(async () => hook({1064 request: this.request,1065 options: this.#getNormalizedOptions(),1066 error: error as Error,1067 retryCount: this.#retryCount + 1,1004- });1068+ }));1069 } catch (hookError) {1070 // Preserve the original request error path (`throw error`) so beforeError hooks can still run.1071 if (hookError instanceof Error && hookError !== error) {1072 this.#beforeRetryHookErrors.add(hookError);1 unmodified line1074 1075 throw hookError;1076 }1077 1078+ if (hookResult === timedOutOperation) {1079+ throw new TimeoutError(this.request);1080+ }1081+1082 if (isRequestInstance(hookResult)) {1083 // Same contract as `ky.retry({request})`: a Request returned from `beforeRetry`1084 // is used as-is rather than being sanitized or otherwise rewritten by Ky.1085 this.#assignRequest(hookResult);33 unmodified lines1119 this.request = new globalThis.Request(this.request, {signal: this.#options.signal});1120 }1121 1122 const nonRequestOptions = findUnknownOptions(this.#options);1123+ this.#retryLimit = normalizeRetryOptions(this.#options.retry).limit;1055- const retryRequest = this.#options.retry.limit > 0 ? this.request.clone() : undefined;1124+ const retryRequest = this.#retryLimit > 0 ? this.request.clone() : undefined;1125 const request = this.#wrapRequestWithUploadProgress(this.request, this.#options.body ?? undefined);1126 1127 // Cloning is done here to prepare in advance for retries.1128 // Skip cloning when retries are disabled - cloning a streaming body calls ReadableStream#tee()92 unmodified linesmodified:source/errors/HTTPError.ts+2 added-2 removed
14 unmodified lines15 export class HTTPError<T = unknown> extends KyError {16 override name = 'HTTPError' as const;17 response: KyResponse<T>;18 request: KyRequest;19- options: NormalizedOptions;19+ options: Readonly<NormalizedOptions>;20 data: T | string | undefined;21 22- constructor(response: Response, request: Request, options: NormalizedOptions) {22+ constructor(response: Response, request: Request, options: Readonly<NormalizedOptions>) {23 const code = (response.status || response.status === 0) ? response.status : '';24 const title = response.statusText ?? '';25 const status = `${code} ${title}`.trim();26 const reason = status ? `status code ${status}` : 'an unknown error';8 unmodified linesmodified:source/types/hooks.ts+4 added-4 removed
27 unmodified lines28 export type InitHook = (options: Options) => void;29 30 export type BeforeRequestState = {31 request: KyRequest;32- options: NormalizedOptions;32+ options: Readonly<NormalizedOptions>;33 34 /**35 The number of retries attempted. Always `0`, since `beforeRequest` hooks run once before retry handling begins.36 */3 unmodified lines40 export type BeforeRequestHook = (state: BeforeRequestState) => Request | Response | void | Promise<Request | Response | void>;41 42 export type BeforeRetryState = {43 request: KyRequest;44- options: NormalizedOptions;44+ options: Readonly<NormalizedOptions>;45 error: Error;46 47 /**48 The number of retries attempted. Always `>= 1`, since this hook is only called during retries, not on the initial request.4 unmodified lines53 export type BeforeRetryHook = (state: BeforeRetryState) => Request | Response | typeof stop | void | Promise<Request | Response | typeof stop | void>;54 55 export type BeforeErrorState = {56 request: KyRequest;57- options: NormalizedOptions;57+ options: Readonly<NormalizedOptions>;58 59 // `Error` (not `KyError`) because this receives all errors, including non-Ky ones.60 error: Error;61 9 unmodified lines71 export type BeforeErrorHook = (state: BeforeErrorState) => Error | Promise<Error>;72 73 export type AfterResponseState = {74 request: KyRequest;75- options: NormalizedOptions;75+ options: Readonly<NormalizedOptions>;76 response: KyResponse;77 78 /**79 The number of retries attempted. `0` for the initial request, increments with each retry.286 unmodified linesmodified:source/types/options.ts+18 added-11 removed
170 unmodified lines171 Controls retry behavior. Each field is documented in the `RetryOptions` type.172 173 If `retry` is a number, it will be used as `limit` and other defaults will remain in place.174 175+ `retry.limit`, including numeric shorthand, must be a finite, non-negative integer.176+177 Network errors (e.g., DNS failures, connection refused, offline) are automatically retried for retriable methods. Only errors recognized as network errors are retried; other errors (e.g., programming bugs) are thrown immediately. Use `shouldRetry` to customize this behavior.178 179 `413 Payload Too Large` is only retried when the response includes a retry timing header.180 27 unmodified lines208 209 /**210 Overall timeout in milliseconds for the entire operation, including retries and delays. Throws a `TimeoutError` if exceeded. Cannot be greater than 2147483647.211 212+ `beforeError` hooks run after an error is produced and are not bounded by `totalTimeout`.213+214 If set to `false` or not specified, there is no overall timeout.215 216 @default false217 229 unmodified lines447 */448 headers?: KyHeadersInit;449 }450 451+type NormalizedRetryOptions = Required<Omit<RetryOptions, 'shouldRetry'>> & Pick<RetryOptions, 'shouldRetry'>;452+453 export type InternalOptions = Required<454 Omit<Options, 'hooks' | 'retry' | 'context' | 'throwHttpErrors'>,449-'fetch' | 'prefix' | 'timeout' | 'totalTimeout'455+ 'fetch' | 'prefix' | 'timeout' | 'totalTimeout'456 > & {457 headers: Required<Headers>;458 hooks: Required<Hooks>;453- retry: Required<Omit<RetryOptions, 'shouldRetry'>> & Pick<RetryOptions, 'shouldRetry'>;459+ retry: NormalizedRetryOptions;460 prefix: string;461 context: Record<string, unknown>;462 throwHttpErrors: boolean | ((status: number) => boolean);463 };464 465 /**466 Normalized options passed to the `fetch` call and hooks.467 */462-export interface NormalizedOptions extends RequestInit { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- This must stay an interface so that it can be extended outside of Ky for use in `ky.create`.468+export interface NormalizedOptions extends Readonly<RequestInit> { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- This must stay an interface so that it can be extended outside of Ky for use in `ky.create`.469 // Extended from `RequestInit`, but ensured to be set (not optional).464- method: NonNullable<RequestInit['method']>;465- credentials?: NonNullable<RequestInit['credentials']>;470+ readonly method: NonNullable<RequestInit['method']>;471+ readonly credentials?: NonNullable<RequestInit['credentials']>;472+ readonly headers: Headers;473 474 // Extended from custom `KyOptions`, but ensured to be set (not optional).468- retry: RetryOptions;469- baseUrl?: Options['baseUrl'];470- prefix: string;471- onDownloadProgress: Options['onDownloadProgress'];472- onUploadProgress: Options['onUploadProgress'];473- context: Record<string, unknown>;475+ readonly retry: NormalizedRetryOptions;476+ readonly baseUrl?: Options['baseUrl'];477+ readonly prefix: string;478+ readonly onDownloadProgress?: NonNullable<Options['onDownloadProgress']>;479+ readonly onUploadProgress?: NonNullable<Options['onUploadProgress']>;480+ readonly context: Record<string, unknown>;481 }482 483 export type {RetryOptions, ShouldRetryState} from './retry.js';modified:source/types/retry.ts+1 added
13 unmodified lines141516171819202122156 unmodified linesExpand all13 unmodified lines
export type RetryOptions = { /** The number of times to retry failed requests. Must be a finite, non-negative integer.
@default 2 */ limit?: number;156 unmodified linesExpand allmodified:source/utils/normalize.ts+53 added-11 removed
1 import {requestMethods} from '../core/constants.js';2 import type {RetryOptions} from '../types/retry.js';3-import type {HttpMethod, RequestHttpMethod} from '../types/options.js';3+import type {HttpMethod, InternalOptions, RequestHttpMethod} from '../types/options.js';4 5 export const normalizeRequestMethod = (input: string): string =>6 requestMethods.includes(input as RequestHttpMethod) ? input.toUpperCase() : input;7 1 unmodified line9 10 const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];11 12 const retryAfterStatusCodes = [413, 429, 503];13+const invalidRetryLimitErrorMessage = '`retry.limit` must be a finite, non-negative integer';14 14-type InternalRetryOptions = Required<Omit<RetryOptions, 'shouldRetry'>> & Pick<RetryOptions, 'shouldRetry'>;15+type InternalRetryOptions = InternalOptions['retry'];16 17 const defaultRetryOptions: InternalRetryOptions = {18 limit: 2,19 methods: retryMethods,5 unmodified lines25 jitter: undefined,26 retryOnTimeout: false,27 };28 29+const getDefaultRetryOptions = (): InternalRetryOptions => ({30+ ...defaultRetryOptions,31+ methods: [...defaultRetryOptions.methods],32+ statusCodes: [...defaultRetryOptions.statusCodes],33+ afterStatusCodes: [...defaultRetryOptions.afterStatusCodes],34+});35+36+/**37+Normalizes an omitted retry limit or validates a supplied one.38+*/39+const normalizeRetryLimit = (retryLimit: unknown): number => {40+ if (retryLimit === undefined) {41+ return defaultRetryOptions.limit;42+ }43+44+ if (typeof retryLimit !== 'number' || !Number.isInteger(retryLimit) || retryLimit < 0) {45+ throw new TypeError(invalidRetryLimitErrorMessage);46+ }47+48+ return retryLimit;49+};50+51 export const normalizeRetryOptions = (retry: number | RetryOptions = {}): InternalRetryOptions => {52 if (typeof retry === 'number') {53 return {31- ...defaultRetryOptions,32- limit: retry,54+ ...getDefaultRetryOptions(),55+ limit: normalizeRetryLimit(retry),56 };57 }58 36- if (retry.methods && !Array.isArray(retry.methods)) {59+ if (retry === null || typeof retry !== 'object' || Array.isArray(retry)) {60+ throw new TypeError('`retry` must be a number or an object');61+ }62+63+ const normalizedRetry = Object.fromEntries(Object.entries(retry).filter(([, value]) => value !== undefined)) as RetryOptions;64+ const retryLimit = normalizeRetryLimit(normalizedRetry.limit);65+66+ if (normalizedRetry.methods !== undefined && !Array.isArray(normalizedRetry.methods)) {67 throw new Error('retry.methods must be an array');68 }69 40- if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {70+ if (normalizedRetry.statusCodes !== undefined && !Array.isArray(normalizedRetry.statusCodes)) {71 throw new Error('retry.statusCodes must be an array');72 }73 44- const normalizedRetry = Object.fromEntries(Object.entries({45- ...retry,46- methods: retry.methods?.map(method => method.toLowerCase()),47- }).filter(([, value]) => value !== undefined)) as RetryOptions;74+ if (normalizedRetry.afterStatusCodes !== undefined && !Array.isArray(normalizedRetry.afterStatusCodes)) {75+ throw new Error('retry.afterStatusCodes must be an array');76+ }77 78+ if (normalizedRetry.methods !== undefined) {79+ normalizedRetry.methods = normalizedRetry.methods.map(method => method.toLowerCase());80+ }81+82+ if (normalizedRetry.statusCodes !== undefined) {83+ normalizedRetry.statusCodes = [...normalizedRetry.statusCodes];84+ }85+86+ if (normalizedRetry.afterStatusCodes !== undefined) {87+ normalizedRetry.afterStatusCodes = [...normalizedRetry.afterStatusCodes];88+ }89+90 return {50- ...defaultRetryOptions,91+ ...getDefaultRetryOptions(),92 ...normalizedRetry,93+ limit: retryLimit,94 };95 };modified:test/hooks.ts+184 added
747 unmodified lines748 t.true(error instanceof TimeoutError);749 t.is(fetchCallCount, 0);750 });751 752+test('totalTimeout bounds a never-ending beforeRequest hook', async t => {753+ let markHookStarted: () => void;754+ const hookStarted = new Promise<void>(resolve => {755+ markHookStarted = resolve;756+ });757+ const neverSettlingPromise = new Promise<never>(() => {758+ void 0;759+ });760+761+ const request = ky('https://example.com', {762+ fetch: async () => new Response('ok'),763+ totalTimeout: 500,764+ hooks: {765+ beforeRequest: [766+ async () => {767+ markHookStarted();768+ await neverSettlingPromise;769+ },770+ ],771+ },772+ }).text();773+774+ await hookStarted;775+776+ const result = await Promise.race([777+ request.catch((error: unknown) => error),778+ delay(2000).then(() => 'still pending'),779+ ]);780+781+ t.true(result instanceof TimeoutError);782+});783+784+test.serial('totalTimeout rejects a hook result produced after the deadline', async t => {785+ const originalPerformanceNow = globalThis.performance.now;786+ let currentTime = 0;787+ let didCancelBody = false;788+ globalThis.performance.now = () => currentTime;789+790+ t.teardown(() => {791+ globalThis.performance.now = originalPerformanceNow;792+ });793+794+ await t.throwsAsync(795+ ky('https://example.com', {796+ totalTimeout: 500,797+ hooks: {798+ beforeRequest: [799+ () => {800+ currentTime = 501;801+ return new Response(new ReadableStream({802+ cancel() {803+ didCancelBody = true;804+ },805+ }));806+ },807+ ],808+ },809+ }),810+ {811+ instanceOf: TimeoutError,812+ },813+ );814+815+ await delay(0);816+ t.true(didCancelBody);817+});818+819+test.serial('totalTimeout takes precedence over a hook error produced after the deadline', async t => {820+ const originalPerformanceNow = globalThis.performance.now;821+ let currentTime = 0;822+ globalThis.performance.now = () => currentTime;823+824+ t.teardown(() => {825+ globalThis.performance.now = originalPerformanceNow;826+ });827+828+ await t.throwsAsync(829+ ky('https://example.com', {830+ totalTimeout: 500,831+ hooks: {832+ beforeRequest: [833+ () => {834+ currentTime = 501;835+ throw new Error('late hook error');836+ },837+ ],838+ },839+ }),840+ {841+ instanceOf: TimeoutError,842+ },843+ );844+});845+846+test('totalTimeout bounds a never-ending afterResponse hook', async t => {847+ let markHookStarted: () => void;848+ let didAbort = false;849+ const hookStarted = new Promise<void>(resolve => {850+ markHookStarted = resolve;851+ });852+ const neverSettlingPromise = new Promise<never>(() => {853+ void 0;854+ });855+856+ const request = ky('https://example.com', {857+ async fetch(request) {858+ request.signal.addEventListener('abort', () => {859+ didAbort = true;860+ }, {once: true});861+862+ return new Response('ok');863+ },864+ totalTimeout: 500,865+ hooks: {866+ afterResponse: [867+ async () => {868+ markHookStarted();869+ await neverSettlingPromise;870+ },871+ ],872+ },873+ }).text();874+875+ await hookStarted;876+877+ const result = await Promise.race([878+ request.catch((error: unknown) => error),879+ delay(2000).then(() => 'still pending'),880+ ]);881+882+ t.true(result instanceof TimeoutError);883+ t.true(didAbort);884+});885+886 test('beforeRequest hook runs only once and does not run again on retry', async t => {887 let fetchCallCount = 0;888 let beforeRequestCallCount = 0;889 const beforeRequestRetryCounts: number[] = [];322 unmodified lines1212 t.is(beforeRetryCallCount, 1);1213 t.is(fetchCallCount, 1);1214 });1215 1216+test('totalTimeout bounds a never-ending beforeRetry hook', async t => {1217+ let markHookStarted: () => void;1218+ let beforeErrorCallCount = 0;1219+ const hookStarted = new Promise<void>(resolve => {1220+ markHookStarted = resolve;1221+ });1222+ const neverSettlingPromise = new Promise<never>(() => {1223+ void 0;1224+ });1225+1226+ const request = ky('https://example.com', {1227+ fetch: async () => new Response('error', {status: 500}),1228+ totalTimeout: 500,1229+ retry: {1230+ limit: 1,1231+ delay: () => 0,1232+ },1233+ hooks: {1234+ beforeRetry: [1235+ async () => {1236+ markHookStarted();1237+ await neverSettlingPromise;1238+ },1239+ ],1240+ beforeError: [1241+ ({error}) => {1242+ beforeErrorCallCount++;1243+ return error;1244+ },1245+ ],1246+ },1247+ }).text();1248+1249+ await hookStarted;1250+1251+ const result = await Promise.race([1252+ request.catch((error: unknown) => error),1253+ delay(2000).then(() => 'still pending'),1254+ ]);1255+1256+ t.true(result instanceof TimeoutError);1257+ t.is(beforeErrorCallCount, 1);1258+});1259+1260 test('catches beforeRetry thrown errors', async t => {1261 let requestCount = 0;1262 let beforeErrorHookCalled = false;1263 524 unmodified lines1788 t.false('searchParams' in options);1789 t.false('timeout' in options);1790 t.false('throwHttpErrors' in options);1791 t.false('fetch' in options);1792+ t.false(Object.hasOwn(options, 'onDownloadProgress'));1793+ t.false(Object.hasOwn(options, 'onUploadProgress'));1794 1795 // Verify options object is frozen (can't add/modify properties)1796 t.throws(() => {1797 // @ts-expect-error - Testing freeze behavior1798 options.newProperty = 'test';1799 });1800 1801+ t.throws(() => {1802+ Object.assign(options, {retry: options.retry});1803+ });1804+1805 // Verify nested objects like headers are still mutable1806 t.notThrows(() => {1807 options.headers.set('X-Test', 'value');1808 });3672 unmodified linesmodified:test/main.ts+1 added-1 removed
914 unmodified lines915 const start = Date.now();916 await t.throwsAsync(ky('https://example.com', {917 fetch: customFetch,918 timeout: false,919- totalTimeout: 50,919+ totalTimeout: 500,920 }).text(), {921 instanceOf: TimeoutError,922 });923 t.true(didStartBodyRead);1933 unmodified linesmodified:test/retry.ts+417 added
793 unmodified lines794 );795 t.is(requestCount, 4);796 });797 798+test('rejects invalid retry limits', t => {799+ for (const limit of [Number.NaN, Number.POSITIVE_INFINITY, -1, 1.5]) {800+ t.throws(() => {801+ void ky('https://example.com', {802+ retry: {803+ limit,804+ },805+ });806+ }, {807+ instanceOf: TypeError,808+ message: '`retry.limit` must be a finite, non-negative integer',809+ });810+811+ t.throws(() => {812+ void ky('https://example.com', {retry: limit});813+ }, {814+ instanceOf: TypeError,815+ message: '`retry.limit` must be a finite, non-negative integer',816+ });817+ }818+});819+820+test('rejects non-number retry limits', t => {821+ for (const limit of ['NaN', true, null]) {822+ t.throws(() => {823+ void ky('https://example.com', {824+ retry: {825+ limit: limit as never,826+ },827+ });828+ }, {829+ instanceOf: TypeError,830+ message: '`retry.limit` must be a finite, non-negative integer',831+ });832+ }833+});834+835+test('does not enable retries after sending an uncloned request body', async t => {836+ let requestCount = 0;837+838+ await t.throwsAsync(839+ ky('https://example.com', {840+ method: 'put',841+ body: 'body',842+ async fetch(input) {843+ requestCount++;844+ await (input as Request).text();845+ return new Response(null, {status: 500});846+ },847+ retry: {848+ limit: 0,849+ methods: ['put'],850+ },851+ hooks: {852+ afterResponse: [({options}) => {853+ options.retry.limit = 1;854+ }],855+ },856+ }).text(),857+ {858+ message: /status code 500/,859+ },860+ );861+862+ t.is(requestCount, 1);863+});864+865+test('allows response hooks to disable retries', async t => {866+ let requestCount = 0;867+868+ await t.throwsAsync(869+ ky('https://example.com', {870+ async fetch() {871+ requestCount++;872+ return new Response(null, {status: 500});873+ },874+ retry: {875+ limit: 1,876+ delay: () => 0,877+ },878+ hooks: {879+ afterResponse: [({options}) => {880+ options.retry.limit = 0;881+ }],882+ },883+ }).text(),884+ {885+ message: /status code 500/,886+ },887+ );888+889+ t.is(requestCount, 1);890+});891+892+test('uses the retry limit set by a beforeRequest hook that returns a response', async t => {893+ let requestCount = 0;894+895+ const response = await ky('https://example.com', {896+ async fetch() {897+ requestCount++;898+ return new Response('ok');899+ },900+ retry: {901+ limit: 0,902+ delay: () => 0,903+ },904+ hooks: {905+ beforeRequest: [({options}) => {906+ options.retry.limit = 1;907+ return new Response(null, {status: 500});908+ }],909+ afterResponse: [({response, retryCount}) => {910+ if (retryCount === 0 && response.status === 500) {911+ return ky.retry();912+ }913+ }],914+ },915+ }).text();916+917+ t.is(response, 'ok');918+ t.is(requestCount, 1);919+});920+921+test('uses the normalized retry limit when cloning request bodies', async t => {922+ let requestCount = 0;923+924+ await t.throwsAsync(925+ ky('https://example.com', {926+ method: 'put',927+ body: 'body',928+ async fetch(input) {929+ requestCount++;930+ await (input as Request).text();931+ return new Response(null, {status: 500});932+ },933+ retry: {934+ limit: 1,935+ methods: ['put'],936+ delay: () => 0,937+ },938+ hooks: {939+ init: [options => {940+ options.retry = {941+ limit: undefined,942+ methods: ['put'],943+ delay: () => 0,944+ };945+ }],946+ },947+ }).text(),948+ {949+ message: /status code 500/,950+ },951+ );952+953+ t.is(requestCount, 3);954+});955+956+test('rejects invalid retry option values', t => {957+ for (const retry of [true, 'NaN', []]) {958+ t.throws(() => {959+ void ky('https://example.com', {retry: retry as never});960+ }, {961+ instanceOf: TypeError,962+ message: '`retry` must be a number or an object',963+ });964+965+ t.throws(() => {966+ void ky('https://example.com', {967+ retry: retry as never,968+ hooks: {969+ init: [() => undefined],970+ },971+ });972+ }, {973+ instanceOf: TypeError,974+ message: '`retry` must be a number or an object',975+ });976+ }977+});978+979+test('init hooks can sanitize retry options before validation', async t => {980+ let requestCount = 0;981+982+ await t.throwsAsync(983+ ky('https://example.com', {984+ async fetch() {985+ requestCount++;986+ return new Response(null, {status: 500});987+ },988+ retry: {989+ limit: Number.NaN,990+ },991+ hooks: {992+ init: [options => {993+ options.retry = 0;994+ }],995+ },996+ }).text(),997+ );998+ t.is(requestCount, 1);999+});1000+1001 test('respect retry methods', async t => {1002 let requestCount = 0;1003 1004 const server = await createHttpTestServer(t);449 unmodified lines1454 methods: 'get',1455 },1456 });1457 });1458+1459+ t.throws(() => {1460+ void ky(server.url, {1461+ retry: {1462+ // @ts-expect-error1463+ methods: 'get',1464+ },1465+ hooks: {1466+ init: [() => undefined],1467+ },1468+ });1469+ });1470 });1471 1472 test('throws when retry.statusCodes is not an array', async t => {1473 const server = await createHttpTestServer(t);5 unmodified lines1479 statusCodes: 403,1480 },1481 });1482 });1483+1484+ t.throws(() => {1485+ void ky(server.url, {1486+ retry: {1487+ // @ts-expect-error1488+ statusCodes: 403,1489+ },1490+ hooks: {1491+ init: [() => undefined],1492+ },1493+ });1494+ });1495 });1496 1497+test('throws when retry.afterStatusCodes is not an array', async t => {1498+ const server = await createHttpTestServer(t);1499+1500+ t.throws(() => {1501+ void ky(server.url, {1502+ retry: {1503+ // @ts-expect-error1504+ afterStatusCodes: 503,1505+ },1506+ });1507+ });1508+1509+ t.throws(() => {1510+ void ky(server.url, {1511+ retry: {1512+ // @ts-expect-error1513+ afterStatusCodes: 503,1514+ },1515+ hooks: {1516+ init: [() => undefined],1517+ },1518+ });1519+ });1520+});1521+1522+test('throws when retry array options are falsy non-arrays', t => {1523+ for (const [key, value] of [1524+ ['methods', 0],1525+ ['statusCodes', false],1526+ ['afterStatusCodes', null],1527+ ] as const) {1528+ const retry = {[key]: value};1529+1530+ t.throws(() => {1531+ void ky('https://example.com', {1532+ retry: retry as never,1533+ });1534+ });1535+1536+ t.throws(() => {1537+ void ky('https://example.com', {1538+ retry: retry as never,1539+ hooks: {1540+ init: [() => undefined],1541+ },1542+ });1543+ });1544+ }1545+});1546+1547+test('request hooks cannot mutate default retry status codes', async t => {1548+ await ky('https://example.com', {1549+ async fetch() {1550+ return new Response('ok');1551+ },1552+ hooks: {1553+ beforeRequest: [({options}) => {1554+ options.retry.statusCodes!.push(418);1555+ }],1556+ },1557+ }).text();1558+1559+ let requestCount = 0;1560+ await t.throwsAsync(1561+ ky('https://example.com', {1562+ async fetch() {1563+ requestCount++;1564+ return new Response(null, {status: 418});1565+ },1566+ }).text(),1567+ {1568+ message: /status code 418/,1569+ },1570+ );1571+1572+ t.is(requestCount, 1);1573+});1574+1575+test('request hooks cannot mutate custom retry arrays', async t => {1576+ const retry = {1577+ limit: 1,1578+ statusCodes: [500],1579+ afterStatusCodes: [500],1580+ delay: () => 0,1581+ };1582+1583+ await ky('https://example.com', {1584+ retry,1585+ async fetch() {1586+ return new Response('ok');1587+ },1588+ hooks: {1589+ beforeRequest: [({options}) => {1590+ options.retry.statusCodes.push(418);1591+ options.retry.afterStatusCodes.push(418);1592+ }],1593+ },1594+ }).text();1595+1596+ t.deepEqual(retry.statusCodes, [500]);1597+ t.deepEqual(retry.afterStatusCodes, [500]);1598+1599+ let requestCount = 0;1600+ await t.throwsAsync(1601+ ky('https://example.com', {1602+ retry,1603+ async fetch() {1604+ requestCount++;1605+ return new Response(null, {status: 418});1606+ },1607+ }).text(),1608+ {1609+ message: /status code 418/,1610+ },1611+ );1612+1613+ t.is(requestCount, 1);1614+});1615+1616+test('validates retry array mutations from response hooks', async t => {1617+ await t.throwsAsync(1618+ ky('https://example.com', {1619+ async fetch() {1620+ return new Response(null, {status: 500});1621+ },1622+ hooks: {1623+ afterResponse: [({options}) => {1624+ options.retry.statusCodes = null as never;1625+ }],1626+ },1627+ }).text(),1628+ {1629+ message: 'retry.statusCodes must be an array',1630+ },1631+ );1632+});1633+1634+test('validates retry array mutations before sending the request', async t => {1635+ let requestCount = 0;1636+1637+ await t.throwsAsync(1638+ ky('https://example.com', {1639+ async fetch() {1640+ requestCount++;1641+ return new Response('ok');1642+ },1643+ hooks: {1644+ beforeRequest: [({options}) => {1645+ options.retry.statusCodes = null as never;1646+ }],1647+ },1648+ }).text(),1649+ {1650+ message: 'retry.statusCodes must be an array',1651+ },1652+ );1653+1654+ t.is(requestCount, 0);1655+});1656+1657 test('retry options ignore undefined overrides and keep defaults', async t => {1658 let requestCount = 0;1659 1660 const server = await createHttpTestServer(t);446 unmodified lines2107 // At most 1-2 attempts fit within the 500ms totalTimeout (each takes ~300ms)2108 t.true(requestCount >= 1 && requestCount <= 2);2109 });2110 2111+test('totalTimeout bounds a never-ending shouldRetry callback', async t => {2112+ let markCallbackStarted: () => void;2113+ const callbackStarted = new Promise<void>(resolve => {2114+ markCallbackStarted = resolve;2115+ });2116+ const neverSettlingPromise = new Promise<never>(() => {2117+ void 0;2118+ });2119+2120+ const request = ky('https://example.com', {2121+ fetch: async () => new Response('error', {status: 500}),2122+ totalTimeout: 500,2123+ retry: {2124+ async shouldRetry() {2125+ markCallbackStarted();2126+ await neverSettlingPromise;2127+ },2128+ },2129+ }).text();2130+2131+ await callbackStarted;2132+2133+ const result = await Promise.race([2134+ request.catch((error: unknown) => error),2135+ delay(2000).then(() => 'still pending'),2136+ ]);2137+2138+ t.true(result instanceof TimeoutError);2139+});2140+2141 test('shouldRetry: returns false - prevents retry', async t => {2142 let requestCount = 0;2143 2144 const server = await createHttpTestServer(t);1130 unmodified linesadded:test-d/normalized-options.ts+56 added
1+import {expectTypeOf} from 'expect-type';2+import type {3+ BeforeRequestState,4+ HTTPError,5+ NormalizedOptions,6+ Options,7+ RetryOptions,8+} from 'ky';9+10+declare module 'ky' {11+ interface Options { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- Declaration merging requires an interface.12+ customOption?: string;13+ }14+15+ interface NormalizedOptions { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- Declaration merging requires an interface.16+ customOption?: string;17+ }18+}19+20+type ExpectedNormalizedRetryOptions = Required<Omit<RetryOptions, 'shouldRetry'>> & Pick<RetryOptions, 'shouldRetry'>;21+type ExpectedProgressCallbacks = {22+ readonly onDownloadProgress?: NonNullable<Options['onDownloadProgress']>;23+ readonly onUploadProgress?: NonNullable<Options['onUploadProgress']>;24+};25+26+declare const options: NormalizedOptions;27+declare const beforeRequestState: BeforeRequestState;28+declare const httpError: HTTPError;29+const contextKey = 'test';30+31+expectTypeOf(options.headers).toEqualTypeOf<Headers>();32+expectTypeOf(options.retry).branded.toEqualTypeOf<ExpectedNormalizedRetryOptions>();33+expectTypeOf<Readonly<Pick<NormalizedOptions, keyof ExpectedProgressCallbacks>>>().branded.toEqualTypeOf<ExpectedProgressCallbacks>();34+35+options.headers.set('x-test', 'value');36+options.context[contextKey] = true;37+options.retry.limit = 0;38+options.retry.statusCodes.push(500);39+40+// @ts-expect-error - The normalized options object is frozen.41+options.method = 'POST';42+43+// @ts-expect-error - Inherited request options are frozen too.44+options.cache = 'no-store';45+46+// @ts-expect-error - The normalized options object is frozen.47+options.context = {};48+49+// @ts-expect-error - The normalized options object is frozen.50+options.retry = {...options.retry};51+52+// @ts-expect-error - Module-augmented options passed to hooks are frozen too.53+beforeRequestState.options.customOption = 'value';54+55+// @ts-expect-error - Module-augmented options attached to errors are frozen too.56+httpError.options.customOption = 'value';modified:package.json+1 added-1 removed
20 unmodified lines21 "engines": {22 "node": ">=22"23 },24 "scripts": {25- "test": "xo && npm run build && ava",25+ "test": "xo && npm run build && tsc --project tsconfig.test.json && ava",26 "debug": "PWDEBUG=1 ava --timeout=2m",27 "release": "np",28 "build": "del-cli distribution && tsc --project tsconfig.dist.json",29 "prepare": "npm run build"70 unmodified linesmodified:readme.md+4 added
290 unmodified lines291 Controls retry behavior. Each field is documented individually below.292 293 If `retry` is a number, it will be used as `limit` and other defaults will remain in place.294 295+`retry.limit`, including numeric shorthand, must be a finite, non-negative integer.296+297 Network errors (e.g., DNS failures, connection refused, offline) are automatically retried for retriable methods. Only errors recognized as network errors are retried; other errors (e.g., programming bugs) are thrown immediately. Use `shouldRetry` to customize this behavior.298 299 `413 Payload Too Large` is only retried when the response includes a retry timing header.300 126 unmodified lines427 Default: `false`428 429 Overall timeout in milliseconds for the entire operation, including retries and delays. Throws a `TimeoutError` if exceeded. Cannot be greater than 2147483647.430 431+`beforeError` hooks run after an error is produced and are not bounded by `totalTimeout`.432+433 If set to `false` or not specified, there is no overall timeout.434 435 ```js436 import ky from 'ky';1438 unmodified linesadded:tsconfig.test.json+10 added
1+{2+ "extends": "./tsconfig.json",3+ "compilerOptions": {4+ "noEmit": true,5+ "rootDir": "."6+ },7+ "include": [8+ "test-d"9+ ]10+}