Skip to content
Myr

Ky.ts

This file

Path

source/core/Ky.ts

1,376 lines · 52.2 KiB · TypeScript

Last changed by

Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327

History of this file

Take it

The walk stopped after 200 commits: lines older than 37fc250 point at it.

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1why, one step back
1import {HTTPError} from '../errors/HTTPError.js';

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

line 2why, one step back
2import {NetworkError} from '../errors/NetworkError.js';

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

line 3why, one step back
3import {NonError} from '../errors/NonError.js';

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

line 4why, one step back
4import {ForceRetryError} from '../errors/ForceRetryError.js';

Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9

line 5why, one step back
5import {SchemaValidationError} from '../errors/SchemaValidationError.js';

Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa

line 6why, one step back
6import {TimeoutError} from '../errors/TimeoutError.js';

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 7–8why, one step back
7import type {
8 Input,

Support readonly inputs and explicit undefined in TypeScript optionsSindre Sorhusbefore adoption51b3177

line 9why, one step back
9 InitOptions,

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 10–13why, one step back
10 InternalOptions,
11 NormalizedOptions,12 Options,13 SearchParamsInit,

Code styleSindre Sorhusbefore adoption333afbe

line 14why, one step back
14 SearchParamsOption,

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 15–16why, one step back
15} from '../types/options.js';
16import {type ResponsePromise} from '../types/ResponsePromise.js';

Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9

line 17why, one step back
17import type {StandardSchemaV1} from '../types/standard-schema.js';

Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe

line 18why, one step back
18import {

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 19–24why, one step back
19 cancelBody,
20 limitResponseSize,21 streamRequest,22 streamResponse,23} from '../utils/body.js';24import {

Fix `init` hook mutations to nested `json` and `context` values leaking across requestsSindre Sorhusbefore adoption88e2432

line 25why, one step back
25 cloneDeep,

RefactorSindre Sorhusbefore adoptiona5ed57b

line 26why, one step back
26 cloneSearchParameters,

Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe

line 27why, one step back
27 mergeHeaders,

Normalize mutable init hook optionsSindre Sorhusbefore adoptionff0155d

line 28why, one step back
28 mergeHeaderContainers,

Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe

lines 29–30why, one step back
29 mergeHooks,
30 deletedParametersSymbol,

RefactorSindre Sorhusbefore adoptiona5ed57b

line 31why, one step back
31 type MarkedSearchParameters,

Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe

line 32why, one step back
32} from '../utils/merge.js';

Respect custom HTTP method case when matching retriesSindre Sorhusbefore adoptione4269f0

line 33why, one step back
33import {normalizeRequestMethod, normalizeRetryMethod, normalizeRetryOptions} from '../utils/normalize.js';

Various tweaksSindre Sorhusbefore adoption0dd9522

line 34why, one step back
34import timeout from '../utils/timeout.js';

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 35–36why, one step back
35import delay from '../utils/delay.js';
36import {findUnknownOptions, hasSearchParameters} from '../utils/options.js';

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

line 37why, one step back
37import isRawNetworkError from '../utils/is-network-error.js';

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 38why, one step back
38import {

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 39–41why, one step back
39 isError, isNonArrayObject, isNonNegativeNumber, isObject, isRequest, isResponse,
40} from '../utils/is.js';41import {

TweaksSindre Sorhusbefore adoption3ded2aa

line 42why, one step back
42 isHTTPError, isNetworkError, isTimeoutError, isResponseSizeError, isForceRetryError,

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

lines 43–44why, one step back
43} from '../utils/type-guards.js';
44import {

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 45–48why, one step back
45 calculateRetryTimingDelay,
46 getRetryTimingHeader,47} from './retry-timing.js';48import {

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 49–50why, one step back
49 maxSafeTimeout,
50 responseTypes,

RefactorSindre Sorhusbefore adoptiona5ed57b

line 51why, one step back
51 getSupportedResponseTypes,

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 52why, one step back
52 stop,

Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327

line 53why, one step back
53 beforeRetryOptionKeys,

TweaksSindre Sorhusbefore adoption3ded2aa

line 54why, one step back
54 isRetryMarker,

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 55–61why, one step back
55 supportsAbortController,
56 supportsAbortSignal,57 supportsFormData,58 supportsResponseStreams,59 supportsRequestStreams,60} from './constants.js';61

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

line 62why, one step back
62const maxErrorResponseBodySize = 10 * 1024 * 1024;

Minor tweaksSindre Sorhusbefore adoption4b37c96

line 63why, one step back
63const 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';

RefactorSindre Sorhusbefore adoptiona5ed57b

line 64why, one step back
64const timedOut = Symbol('timedOut');

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

line 65why, one step back
65

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 66–95why, one step back
66const getCurrentTime = (): number => globalThis.performance?.now() ?? Date.now();
6768// Settles like `promise`, or resolves with `timedOut` once `milliseconds` pass first. The timer is cleared as soon as `promise` settles.69// eslint-disable-next-line @typescript-eslint/promise-function-async70const raceWithTimeout = <T>(promise: Promise<T>, milliseconds: number): Promise<T | typeof timedOut> => Promise.race([71 promise,72 new Promise<typeof timedOut>(resolve => {73 const timeoutId = setTimeout(() => {74 resolve(timedOut);75 }, milliseconds);76 void promise.finally(() => {77 clearTimeout(timeoutId);78 }).catch(() => undefined);79 }),80]);8182// Only a returned request or response has a body to release.83const cancelReturnedBody = (value: unknown): void => {84 if (isResponse(value) || isRequest(value)) {85 cancelBody(value);86 }87};8889// Releases the body of a value whose owner already gave up on it, once the operation settles with something. The promise is abandoned on purpose, so its rejection is swallowed rather than surfacing as an unhandled rejection.90const releaseWhenSettled = (operationPromise: Promise<unknown>): void => {91 void operationPromise.then(value => {92 cancelReturnedBody(value);93 }).catch(() => undefined);94};95

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 96–100why, one step back
96type ErrorDataTimeout = {
97 milliseconds: number;98 fromTotalTimeout: boolean;99};100

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

lines 101–112why, one step back
101const createTextDecoder = (contentType: string): TextDecoder => {
102 const match = /;\s*charset\s*=\s*(?:"([^"]+)"|([^;,\s]+))/i.exec(contentType);103 const charset = match?.[1] ?? match?.[2];104 if (charset) {105 try {106 return new TextDecoder(charset);107 } catch {}108 }109110 return new TextDecoder();111};112

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 113–196why, one step back
113const isJsonContentType = (contentType: string): boolean => {
114 // Match JSON subtypes like `json`, `problem+json`, and `vnd.api+json`.115 // Written out rather than matched with a pattern like `/\/(?:.*[.+-])?json$/`, which backtracks quadratically on a `Content-Type` full of slashes. The header comes from the server, so this must stay linear.116 const mimeType = (contentType.split(';', 1)[0] ?? '').trim().toLowerCase();117118 if (!mimeType.endsWith('json')) {119 return false;120 }121122 const separator = mimeType.at(-5);123 if (separator === '/') {124 return true;125 }126127 if (separator !== '.' && separator !== '+' && separator !== '-') {128 return false;129 }130131 // The separator is not the slash, so any slash in the type comes before it.132 return mimeType.includes('/');133};134135// Reads an error body as text. Returns `undefined` when the body cannot be read or is larger than `maxErrorResponseBodySize`, and `timedOut` when the read takes longer than `milliseconds`.136const readResponseText = async (response: Response, milliseconds: number): Promise<string | typeof timedOut | undefined> => {137 const {body} = response;138 if (!body) {139 try {140 return await response.text();141 } catch {142 return undefined;143 }144 }145146 let reader: ReadableStreamDefaultReader<Uint8Array>;147 try {148 reader = body.getReader();149 } catch {150 // Another consumer already locked the stream.151 return undefined;152 }153154 const contentType = response.headers.get('content-type') ?? '';155 // JSON uses UTF-8 regardless of the charset parameter (RFC 8259).156 const decoder = isJsonContentType(contentType) ? new TextDecoder() : createTextDecoder(contentType);157 const chunks: string[] = [];158 let totalBytes = 0;159160 const readAll = (async (): Promise<string | undefined> => {161 try {162 for (;;) {163 // eslint-disable-next-line no-await-in-loop164 const {done, value} = await reader.read();165 if (done) {166 break;167 }168169 totalBytes += value.byteLength;170 if (totalBytes > maxErrorResponseBodySize) {171 void reader.cancel().catch(() => undefined);172 return undefined;173 }174175 chunks.push(decoder.decode(value, {stream: true}));176 }177 } catch (error) {178 if (isResponseSizeError(error)) {179 throw error;180 }181182 return undefined;183 }184185 chunks.push(decoder.decode());186 return chunks.join('');187 })();188189 const result = await raceWithTimeout(readAll, milliseconds);190 if (result === timedOut) {191 void reader.cancel().catch(() => undefined);192 }193194 return result;195};196

Various tweaksSindre Sorhusbefore adoption0dd9522

line 197why, one step back
197const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';

TweaksSindre Sorhusbefore adoption3ded2aa

lines 198–199why, one step back
198const missingResponseMessage = 'The request resolved without a response, so there is no body to read.'
199 + ' This happens when a `beforeRetry` hook returns `ky.stop`. Throw from the hook instead of returning `ky.stop`.';

Various tweaksSindre Sorhusbefore adoption0dd9522

line 200why, one step back
200

TweaksSindre Sorhusbefore adoption3ded2aa

lines 201–206why, one step back
201// Both timeout options are milliseconds or `false`. A `NaN` or negative value used to reach `setTimeout()`, which silently clamps it to ~1ms, or to be ignored entirely when `totalTimeout` was not a number.
202const validateTimeoutOption = (value: unknown, name: 'timeout' | 'totalTimeout'): void => {203 if (value === false) {204 return;205 }206

RefactorSindre Sorhusbefore adoptiona5ed57b

line 207why, one step back
207 if (!isNonNegativeNumber(value)) {

TweaksSindre Sorhusbefore adoption3ded2aa

lines 208–216why, one step back
208 throw new TypeError(`The \`${name}\` option must be a non-negative number or \`false\``);
209 }210211 // `Infinity` lands here too, since it is not a usable delay either.212 if (value > maxSafeTimeout) {213 throw new RangeError(`The \`${name}\` option cannot be greater than ${maxSafeTimeout}`);214 }215};216

Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327

lines 217–219why, one step back
217// Defaults only replace `undefined`, so a `null` reaches the validation and is reported instead of silently becoming the default.
218const withAttemptDefaults = ({throwHttpErrors = true, timeout = 10_000, fetch = globalThis.fetch.bind(globalThis)}: Options) => ({throwHttpErrors, timeout, fetch});219

Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8

line 220why, one step back
220// These callbacks are called directly, so a non-function value otherwise surfaces as a runtime error naming Ky's own internals rather than the option the caller set.

TweaksSindre Sorhusbefore adoption3ded2aa

line 221why, one step back
221const validateCallbackOptions = (options: Record<string, unknown>): void => {

Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8

line 222why, one step back
222 for (const key of ['parseJson', 'stringifyJson', 'fetch', 'onDownloadProgress', 'onUploadProgress'] as const) {

TweaksSindre Sorhusbefore adoption3ded2aa

lines 223–233why, one step back
223 if (options[key] !== undefined && typeof options[key] !== 'function') {
224 throw new TypeError(`The \`${key}\` option must be a function`);225 }226 }227228 const {throwHttpErrors} = options;229 if (typeof throwHttpErrors !== 'boolean' && typeof throwHttpErrors !== 'function') {230 throw new TypeError('The `throwHttpErrors` option must be a boolean or a function');231 }232};233

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 234–237why, one step back
234const leadingC0ControlOrSpacePattern = /^[\0-\u0020]+/g;
235const asciiTabOrNewLinePattern = /[\t\n\r]/g;236const schemePattern = /^[a-z][\d+.a-z-]*:/i;237const malformedHttpProtocolPattern = /^https?:(?!\/\/)/i;

Fix hook state leaks and fetch option forwardingSindre Sorhusbefore adoption2df9b7e

line 238why, one step back
238

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 239–240why, one step back
239const isAbsoluteInput = (input: string): boolean =>
240 schemePattern.test(input);

Harden retrySindre Sorhusbefore adoptionc426f19

line 241why, one step back
241

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 242–243why, one step back
242const normalizeInputForProtocolCheck = (input: string): string =>
243 input.replaceAll(leadingC0ControlOrSpacePattern, '').replaceAll(asciiTabOrNewLinePattern, '');

Harden retrySindre Sorhusbefore adoptionc426f19

line 244why, one step back
244

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 245–248why, one step back
245// Joins a string input to `prefix`, then resolves it against `baseUrl`. A `URL` or `Request` input is used as-is.
246const resolveInput = (input: Input, prefix: string, baseUrl: Options['baseUrl']): Input => {247 if (typeof input !== 'string') {248 return input;

Harden retrySindre Sorhusbefore adoptionc426f19

lines 249–250why, one step back
249 }
250

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 251–254why, one step back
251 if (prefix) {
252 const normalizedPrefix = prefix.replace(/\/+$/, '');253 const normalizedInput = input.replace(/^\/+/, '');254 input = `${normalizedPrefix}/${normalizedInput}`;

Harden retrySindre Sorhusbefore adoptionc426f19

lines 255–256why, one step back
255 }
256

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 257–258why, one step back
257 if (baseUrl) {
258 const normalizedInput = normalizeInputForProtocolCheck(input);

Fix hook state leaks and fetch option forwardingSindre Sorhusbefore adoption2df9b7e

line 259why, one step back
259

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 260–262why, one step back
260 if (malformedHttpProtocolPattern.test(normalizedInput)) {
261 throw new TypeError('`input` url protocol must be followed by `//` when using `baseUrl`');262 }

Improve compatibility with custom `fetch` implementations (#858)Sindre Sorhusbefore adoption2971991

line 263why, one step back
263

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 264–267why, one step back
264 if (!isAbsoluteInput(normalizedInput)) {
265 return new URL(input, (new Request(baseUrl)).url);266 }267 }

Improve compatibility with custom `fetch` implementations (#858)Sindre Sorhusbefore adoption2971991

line 268why, one step back
268

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 269–270why, one step back
269 return input;
270};

Improve compatibility with custom `fetch` implementations (#858)Sindre Sorhusbefore adoption2971991

line 271why, one step back
271

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 272–277why, one step back
272// `URLSearchParams#delete()` serializes the whole query again even when the key is missing, which would rewrite an input URL that has nothing to remove, for example `%20` as `+`.
273const deleteSearchParameter = (url: URL, key: string): void => {274 if (url.searchParams.has(key)) {275 url.searchParams.delete(key);276 }277};

Reject malformed HTTP URLs with `baseUrl`Sindre Sorhusbefore adoptionbe60db5

line 278why, one step back
278

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 279–281why, one step back
279// Adds the `searchParams` option to the search parameters already in `url`.
280const applySearchParameters = (url: URL, searchParameters: SearchParamsOption): void => {281 const deleted = (searchParameters as MarkedSearchParameters | undefined)?.[deletedParametersSymbol];

Reject malformed HTTP URLs with `baseUrl`Sindre Sorhusbefore adoptionbe60db5

line 282why, one step back
282

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 283–287why, one step back
283 if (deleted) {
284 // Remove keys from the input URL first so later searchParams entries can intentionally re-add them.285 for (const key of deleted) {286 deleteSearchParameter(url, key);287 }

Fix tuple `searchParams` mutations leaking across init-hook requests (#861)Atharva Singhbefore adoption346f898

lines 288–289why, one step back
288 }
289

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 290–308why, one step back
290 if (typeof searchParameters === 'string') {
291 const stringSearchParameters = searchParameters.replace(/^\?/, '');292 if (stringSearchParameters !== '') {293 url.search = url.search ? `${url.search}&${stringSearchParameters}` : `?${stringSearchParameters}`;294 }295 } else if (isNonArrayObject(searchParameters) && !(searchParameters instanceof URLSearchParams)) {296 // Filter out undefined values from plain objects. An `undefined` value removes the key from the input URL instead.297 for (const [key, value] of Object.entries(searchParameters)) {298 if (value === undefined) {299 deleteSearchParameter(url, key);300 } else {301 url.searchParams.append(key, value as string);302 }303 }304 } else {305 for (const [key, value] of new URLSearchParams(searchParameters as SearchParamsInit)) {306 url.searchParams.append(key, value);307 }308 }

Fix tuple `searchParams` mutations leaking across init-hook requests (#861)Atharva Singhbefore adoption346f898

lines 309–310why, one step back
309};
310

TweaksSindre Sorhusbefore adoption3ded2aa

line 311why, one step back
311// Clone mutable option properties so init hook mutations don't leak across requests. Non-plain values (functions, class instances) are kept by reference, matching how option merging treats them as whole values. A value a hook assigns is used as-is.

Support readonly inputs and explicit undefined in TypeScript optionsSindre Sorhusbefore adoption51b3177

line 312why, one step back
312function cloneInitHookOptions(options: Options): InitOptions {

Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435

lines 313–314why, one step back
313 const clonedOptions: Options = {
314 ...options,

TweaksSindre Sorhusbefore adoption3ded2aa

lines 315–316why, one step back
315 // `headers` starts as a plain object with lowercase names in `init` hooks, so hooks can add headers in place even when none were provided.
316 headers: mergeHeaderContainers({}, options.headers ?? {}),

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

lines 317–318why, one step back
317 // `context` starts as an object in `init` hooks, the same as in every other hook. The copy is shallow like the per-request copy, so nested values stay shared, for example a cache kept in `context`.
318 context: {...options.context},

TweaksSindre Sorhusbefore adoption3ded2aa

line 319why, one step back
319 // Deep-clone so init-hook mutations to nested values do not leak across requests, matching the nested `retry` cloning below.

Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435

line 320why, one step back
320 json: cloneDeep(options.json),

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 321–323why, one step back
321 searchParams: cloneSearchParameters(options.searchParams),
322 // Clone nested arrays too so init hooks can mutate retry config without leaking state across requests.323 retry: cloneDeep(options.retry),

Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435

line 324why, one step back
324 };

Normalize mutable init hook optionsSindre Sorhusbefore adoptionff0155d

line 325why, one step back
325

Support readonly inputs and explicit undefined in TypeScript optionsSindre Sorhusbefore adoption51b3177

line 326why, one step back
326 return clonedOptions as InitOptions;

Various tweaksSindre Sorhusbefore adoption0dd9522

lines 327–328why, one step back
327}
328

Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9

line 329why, one step back
329const validateJsonWithSchema = async (jsonValue: unknown, schema: StandardSchemaV1): Promise<unknown> => {

RefactorSindre Sorhusbefore adoptiona5ed57b

line 330why, one step back
330 const standardSchema = isObject(schema) || typeof schema === 'function' ? schema['~standard'] : undefined;

Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9

lines 331–332why, one step back
331
332 if (

RefactorSindre Sorhusbefore adoptiona5ed57b

line 333why, one step back
333 !isObject(standardSchema)

Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9

lines 334–335why, one step back
334 || typeof standardSchema.validate !== 'function'
335 ) {

Various tweaksSindre Sorhusbefore adoption0dd9522

line 336why, one step back
336 throw new TypeError(invalidSchemaMessage);

Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9

lines 337–347why, one step back
337 }
338339 const validationResult = await standardSchema.validate(jsonValue);340341 if (validationResult.issues) {342 throw new SchemaValidationError(validationResult.issues);343 }344345 return validationResult.value;346};347

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 348–349why, one step back
348export class Ky {
349 static create(input: Input, options: Options): ResponsePromise {

Various tweaksSindre Sorhusbefore adoption0dd9522

lines 350–353why, one step back
350 const initHooks = options.hooks?.init ?? [];
351 const initHookOptions = initHooks.length > 0 ? cloneInitHookOptions(options) : options;352353 for (const hook of initHooks) {

Support readonly inputs and explicit undefined in TypeScript optionsSindre Sorhusbefore adoption51b3177

line 354why, one step back
354 hook(initHookOptions as InitOptions);

Add `init` hook (#841)Sindre Sorhusbefore adoption87c6740

lines 355–356why, one step back
355 }
356

Various tweaksSindre Sorhusbefore adoption0dd9522

line 357why, one step back
357 const ky = new Ky(input, initHookOptions);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 358why, one step back
358

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

line 359why, one step back
359 const result = (async () => {

Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f

line 360why, one step back
360 let response: Response | undefined;

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

line 361why, one step back
361 try {

RefactorSindre Sorhusbefore adoptiona5ed57b

line 362why, one step back
362 response = await ky.#run();

Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f

line 363why, one step back
363 return response;

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

line 364why, one step back
364 } catch (error: unknown) {

Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f

line 365why, one step back
365 return await ky.#throwProcessedError(error);

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

line 366why, one step back
366 } finally {

Code styleSindre Sorhusbefore adoption333afbe

line 367why, one step back
367 const originalRequest = ky.#originalRequest;

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 368why, one step back
368

Fix response body cleanup after hooks (#809)Sindre Sorhusbefore adoption2bdbd59

line 369why, one step back
369 // Ignore cancellation errors from already-locked or already-consumed streams.

Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f

line 370why, one step back
370 // A custom fetch or hook can return the request body as its response body; ownership then belongs to the caller.

RefactorSindre Sorhusbefore adoptiona5ed57b

line 371why, one step back
371 cancelBody(originalRequest, response);

Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f

line 372why, one step back
372

TweaksSindre Sorhusbefore adoption3ded2aa

line 373why, one step back
373 // Only cancel the current request body if it's distinct from the original (i.e. it was cloned for retries). `#originalRequest` is only set once a request is handed to fetch, so a pipeline that never started, for example one where a `beforeRequest` hook threw or returned a `Response`, leaves the caller's own body alone.

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 374–375why, one step back
374 if (originalRequest && ky.request !== originalRequest) {
375 cancelBody(ky.request, response);

Skip request cloning when retries are disabled to prevent buffering large streaming bodiesSindre Sorhusbefore adoption6f3d1bd

line 376why, one step back
376 }

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

lines 377–378why, one step back
377 }
378 })() as ResponsePromise;

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 379why, one step back
379

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 380–382why, one step back
380 // Only expose `.bytes()` when the environment implements it.
381 for (const type of getSupportedResponseTypes()) {382 const mimeType = responseTypes[type];

Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9

line 383why, one step back
383 result[type] = async (schema?: StandardSchemaV1) => {

TweaksSindre Sorhusbefore adoption3ded2aa

lines 384–388why, one step back
384 // Before dispatch, `ky.request` is the request that will be sent. After dispatch, `#fetch()` has replaced it with the clone it prepares for a possible retry, so a late shortcut only affects later attempts. A request that was already sent is never changed, because `error.request` would then report a header that never went over the wire.
385 if (ky.request !== ky.#originalRequest) {386 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing387 ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);388 }

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 389–391why, one step back
389
390 const response = await result;391

TweaksSindre Sorhusbefore adoption3ded2aa

lines 392–396why, one step back
392 // `ky.stop` from a `beforeRetry` hook resolves the request with no response at all. Reading a body method would otherwise crash deep inside Ky with a TypeError that names Ky internals.
393 if (response === undefined) {394 throw new TypeError(missingResponseMessage);395 }396

Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9

line 397why, one step back
397 if (type !== 'json') {

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 398why, one step back
398 return ky.#raceBodyRead(async () => response[type](), response);

Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9

line 399why, one step back
399 }

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 400why, one step back
400

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 401–402why, one step back
401 const text = await ky.#raceBodyRead(async () => response.text(), response) as string;
402 const request = ky.#getResponseRequest(response);

HardenSindre Sorhusbefore adoption8d8e7a4

lines 403–406why, one step back
403 // This implementation is shared by every body method, so its return type has to satisfy all of them. The parsed value is whatever `parseJson` or `JSON.parse` produced, which is `any` at this boundary.
404 let parsedResult: any;405 try {406 parsedResult = await ky.#raceWithTotalTimeout(async () => {

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 407–409why, one step back
407 const jsonValue = text === '' && schema !== undefined && !ky.#options.parseJson
408 ? undefined409 : await ky.#parseJson(text, request, response);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 410why, one step back
410

HardenSindre Sorhusbefore adoption8d8e7a4

lines 411–416why, one step back
411 if (schema === undefined) {
412 return jsonValue;413 }414415 // eslint-disable-next-line no-return-await, @typescript-eslint/return-await -- Awaiting here preserves the caller's async stack when schema validation fails.416 return await validateJsonWithSchema(jsonValue, schema);

RefactorSindre Sorhusbefore adoptiona5ed57b

line 417why, one step back
417 });

HardenSindre Sorhusbefore adoption8d8e7a4

lines 418–420why, one step back
418 } catch (error: unknown) {
419 // A cancellation is part of the request lifecycle, so it reaches `beforeError` like every other abort. Other failures, such as invalid JSON, stay as they are.420 if (ky.#userProvidedAbortSignal?.aborted) {

TweaksSindre Sorhusbefore adoption3ded2aa

line 421why, one step back
421 await ky.#throwProcessedError(ky.#userProvidedAbortSignal.reason, request);

Preserve caller stack for schema validation errors (#883)Sindre Sorhusbefore adoptione68ea7a

lines 422–423why, one step back
422 }
423

HardenSindre Sorhusbefore adoption8d8e7a4

lines 424–425why, one step back
424 throw error;
425 }

Harden retrySindre Sorhusbefore adoptionc426f19

line 426why, one step back
426

RefactorSindre Sorhusbefore adoptiona5ed57b

line 427why, one step back
427 if (parsedResult === timedOut) {

TweaksSindre Sorhusbefore adoption3ded2aa

line 428why, one step back
428 await ky.#throwProcessedError(new TimeoutError(request), request);

Harden retrySindre Sorhusbefore adoptionc426f19

lines 429–431why, one step back
429 }
430431 return parsedResult;

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 432–438why, one step back
432 };
433 }434435 return result;436 }437438 public request: Request;

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

line 439why, one step back
439 #abortController?: AbortController;

Code styleSindre Sorhusbefore adoption333afbe

line 440why, one step back
440 #retryCount = 0;

Harden retrySindre Sorhusbefore adoptionc426f19

line 441why, one step back
441 #retryLimit: number;

Code styleSindre Sorhusbefore adoption333afbe

line 442why, one step back
442 readonly #options: InternalOptions;

Preserve Request input abort signalsSindre Sorhusbefore adoption071a9b9

lines 443–444why, one step back
443 // Keep the input Request alive because Node.js stops forwarding its signal when the Request is garbage-collected.
444 readonly #requestInput: Request | undefined;

Code styleSindre Sorhusbefore adoption333afbe

line 445why, one step back
445 #originalRequest?: Request;

Improve docsSindre Sorhusbefore adoption8778439

line 446why, one step back
446 #requestBodyCanBeCancelled = false;

Preserve Request input abort signalsSindre Sorhusbefore adoption071a9b9

line 447why, one step back
447 readonly #userProvidedAbortSignal: AbortSignal | undefined;

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

line 448why, one step back
448 readonly #beforeRetryHookErrors = new WeakSet<Error>();

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

line 449why, one step back
449 #cachedNormalizedOptions: NormalizedOptions | undefined;

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 450–453why, one step back
450 // When the `totalTimeout` budget runs out, or `Infinity` without a `totalTimeout`.
451 readonly #deadline: number;452 // Responses returned by a `beforeRequest` or `beforeRetry` hook. They are used as-is, so a failing status throws instead of being retried.453 readonly #hookResponses = new WeakSet<Response>();

Various tweaksSindre Sorhusbefore adoption0dd9522

line 454why, one step back
454 readonly #responseRequests = new WeakMap<Response, Request>();

Fix `parseJson` being ignored by `response.clone().json()`Sindre Sorhusbefore adoptionc6c5dbf

line 455why, one step back
455 readonly #decoratedResponses = new WeakSet<Response>();

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 456–458why, one step back
456
457 // eslint-disable-next-line complexity458 constructor(input: Input, options: Options = {}) {

TweaksSindre Sorhusbefore adoption3ded2aa

lines 459–468why, one step back
459 // Checked before the options are built, since building them reads `input.headers`.
460 if (typeof input !== 'string' && !(input instanceof URL || input instanceof globalThis.Request)) {461 throw new TypeError('`input` must be a string, URL, or Request');462 }463464 // Defaults only replace `undefined`, so a `null` reaches the validation below and is reported instead of silently becoming the default.465 const {466 maxResponseSize = Number.POSITIVE_INFINITY,467 totalTimeout = false,468 } = options;

Minor tweaksSindre Sorhusbefore adoption4b37c96

lines 469–471why, one step back
469 if (Object.hasOwn(options, 'prefixUrl')) {
470 throw new Error(prefixUrlRenamedErrorMessage);471 }

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 472why, one step back
472

Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d

lines 473–474why, one step back
473 // An `init` hook assigns straight onto the options object, so these are checked here, after every merge and hook. The defaults below would otherwise quietly turn a `null` into `GET`, no prefix, or the referrer of a `Request` input.
474 for (const key of ['headers', 'method', 'prefix', 'baseUrl', 'referrer', 'referrerPolicy'] as const) {

TweaksSindre Sorhusbefore adoption3ded2aa

lines 475–479why, one step back
475 if (options[key] === null) {
476 throw new TypeError(`The \`${key}\` option must not be \`null\`. Use \`undefined\` to clear it.`);477 }478 }479

RefactorSindre Sorhusbefore adoptiona5ed57b

line 480why, one step back
480 if (options.context !== undefined && !isNonArrayObject(options.context)) {

TweaksSindre Sorhusbefore adoption3ded2aa

lines 481–483why, one step back
481 throw new TypeError('The `context` option must be an object');
482 }483

Code styleSindre Sorhusbefore adoption333afbe

line 484why, one step back
484 this.#options = {

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 485why, one step back
485 ...options,

Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90

line 486why, one step back
486 headers: mergeHeaders((input as Request).headers, options.headers),

Various tweaksSindre Sorhusbefore adoption0dd9522

line 487why, one step back
487 hooks: mergeHooks({}, options.hooks),

Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90

lines 488–490why, one step back
488 method: normalizeRequestMethod(options.method ?? (input as Request).method ?? 'GET'),
489 referrer: options.referrer ?? (input as Request).referrer,490 referrerPolicy: options.referrerPolicy ?? (input as Request).referrerPolicy,

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 491why, one step back
491 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing

Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f

line 492why, one step back
492 prefix: String(options.prefix || ''),

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 493why, one step back
493 retry: normalizeRetryOptions(options.retry),

Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327

line 494why, one step back
494 ...withAttemptDefaults(options),

TweaksSindre Sorhusbefore adoption3ded2aa

line 495why, one step back
495 totalTimeout,

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

line 496why, one step back
496 maxResponseSize,

TweaksSindre Sorhusbefore adoption3ded2aa

line 497why, one step back
497 context: options.context ?? {},

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 498why, one step back
498 };

TweaksSindre Sorhusbefore adoption3ded2aa

lines 499–500why, one step back
499 // Checked here rather than on the way out, because the constructor already calls `stringifyJson`.
500 validateCallbackOptions(this.#options);

Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327

line 501why, one step back
501 validateTimeoutOption(this.#options.timeout, 'timeout');

TweaksSindre Sorhusbefore adoption3ded2aa

line 502why, one step back
502 validateTimeoutOption(totalTimeout, 'totalTimeout');

Harden retrySindre Sorhusbefore adoptionc426f19

line 503why, one step back
503 this.#retryLimit = this.#options.retry.limit;

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 504why, one step back
504

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

lines 505–508why, one step back
505 if (maxResponseSize !== Number.POSITIVE_INFINITY && (!Number.isSafeInteger(maxResponseSize) || maxResponseSize < 0)) {
506 throw new TypeError('The `maxResponseSize` option must be a non-negative safe integer or Infinity');507 }508

Preserve Request input abort signalsSindre Sorhusbefore adoption071a9b9

lines 509–510why, one step back
509 this.#requestInput = input instanceof globalThis.Request ? input : undefined;
510

RefactorSindre Sorhusbefore adoptiona5ed57b

line 511why, one step back
511 input = resolveInput(input, this.#options.prefix, this.#options.baseUrl);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 512–513why, one step back
512
513 if (supportsAbortController && supportsAbortSignal) {

Preserve Request input abort signalsSindre Sorhusbefore adoption071a9b9

line 514why, one step back
514 this.#userProvidedAbortSignal = this.#options.signal ?? this.#requestInput?.signal;

Code styleSindre Sorhusbefore adoption333afbe

line 515why, one step back
515 this.#abortController = new globalThis.AbortController();

Various tweaksSindre Sorhusbefore adoption0dd9522

line 516why, one step back
516 this.#options.signal = this.#createManagedSignal();

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 517–520why, one step back
517 }
518519 if (supportsRequestStreams) {520 // @ts-expect-error - Types are outdated.

Code styleSindre Sorhusbefore adoption333afbe

line 521why, one step back
521 this.#options.duplex = 'half';

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 522–523why, one step back
522 }
523

Fix `json` option keeping the content-type inherited from a `Request` input bodySindre Sorhusbefore adoption0f2de47

line 524why, one step back
524 // A `Request` input's headers are already merged in, so only a content-type from `options.headers` counts as user-provided.

Fix headers set to `undefined` in `init` hooks being sent as the string `"undefined"`Sindre Sorhusbefore adoption224034d

line 525why, one step back
525 const userProvidedContentType = options.headers !== undefined && mergeHeaders({}, options.headers).has('content-type');

Fix `json` option keeping the content-type inherited from a `Request` input bodySindre Sorhusbefore adoption0f2de47

line 526why, one step back
526

Code styleSindre Sorhusbefore adoption333afbe

lines 527–528why, one step back
527 if (this.#options.json !== undefined) {
528 this.#options.body = this.#options.stringifyJson?.(this.#options.json) ?? JSON.stringify(this.#options.json);

Fix `json` option keeping the content-type inherited from a `Request` input bodySindre Sorhusbefore adoption0f2de47

lines 529–531why, one step back
529 if (!userProvidedContentType) {
530 this.#options.headers.set('content-type', 'application/json');531 }

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 532–536why, one step back
532 }
533534 // To provide correct form boundary, Content-Type header should be deleted when creating Request from another Request with FormData/URLSearchParams body535 // Only delete if user didn't explicitly provide a custom content-type536 if (

Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90

line 537why, one step back
537 input instanceof globalThis.Request

Code styleSindre Sorhusbefore adoption333afbe

line 538why, one step back
538 && ((supportsFormData && this.#options.body instanceof globalThis.FormData) || this.#options.body instanceof URLSearchParams)

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 539–540why, one step back
539 && !userProvidedContentType
540 ) {

Code styleSindre Sorhusbefore adoption333afbe

line 541why, one step back
541 this.#options.headers.delete('content-type');

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 542–543why, one step back
542 }
543

Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90

line 544why, one step back
544 this.request = new globalThis.Request(input, this.#options as RequestInit);

Improve docsSindre Sorhusbefore adoption8778439

line 545why, one step back
545 this.#requestBodyCanBeCancelled = typeof globalThis.ReadableStream === 'function' && this.#options.body instanceof globalThis.ReadableStream;

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 546why, one step back
546

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 547–548why, one step back
547 const {searchParams} = this.#options;
548 if (hasSearchParameters(searchParams)) {

Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe

line 549why, one step back
549 const url = new URL(this.request.url);

RefactorSindre Sorhusbefore adoptiona5ed57b

line 550why, one step back
550 applySearchParameters(url, searchParams);

Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe

line 551why, one step back
551

Remove unnecessary double Request wrapping in searchParams handling (#773)Sindre Sorhusbefore adoption836feb4

line 552why, one step back
552 // Recreate request with the updated URL. We already have all options in this.#options, including duplex.

Skip a needless request rebuild, report an unknown total as zero, and fix two stale testsSindre Sorhusbefore adoptionfa0eac4

lines 553–582why, one step back
553 // Rebuilding is also what drops an inherited `Request` body, so it is skipped when the search parameters leave the URL unchanged.
554 if (url.href !== this.request.url) {555 // Request options are read back from the current request so values inherited from a `Request` input (like `credentials`) survive, while explicit options already won when that request was built.556 // A `Request` input's body is only available as a stream, so keeping it requires request stream support.557 const {558 body: inheritedBody,559 cache,560 credentials,561 integrity,562 keepalive,563 mode,564 redirect,565 referrer,566 referrerPolicy,567 } = this.request;568 const canUseInheritedBody = supportsRequestStreams && !keepalive && mode !== 'no-cors';569570 this.request = new globalThis.Request(url, {571 ...this.#options,572 cache,573 credentials,574 integrity,575 keepalive,576 mode,577 redirect,578 referrer,579 referrerPolicy,580 body: this.#options.body ?? (canUseInheritedBody ? inheritedBody : undefined),581 } as RequestInit);582 }

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 583–584why, one step back
583 }
584

Fix flaky testSindre Sorhusbefore adoption4ba8c15

lines 585–586why, one step back
585 // `totalTimeout` starts when the request pipeline is created, so it also includes
586 // Ky's internal scheduling and user hook time before the first fetch attempt.

RefactorSindre Sorhusbefore adoptiona5ed57b

line 587why, one step back
587 this.#deadline = typeof totalTimeout === 'number' ? getCurrentTime() + totalTimeout : Number.POSITIVE_INFINITY;

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 588–589why, one step back
588 }
589

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 590–664why, one step back
590 async #run(): Promise<Response | undefined> {
591 // Delay the fetch so that body method shortcuts can set the Accept header592 await Promise.resolve();593 const beforeRequestResponse = await this.#runBeforeRequestHooks();594 if (beforeRequestResponse !== undefined) {595 this.#retryLimit = normalizeRetryOptions(this.#options.retry).limit;596 }597598 let response = beforeRequestResponse ?? await this.#retry();599600 for (;;) {601 // `undefined` means a hook stopped the flow.602 if (response === undefined) {603 return undefined;604 }605606 // Read before the `afterResponse` hooks run, since they can replace the response.607 const responseFromHook = this.#hookResponses.has(response);608609 let retryError: Error | undefined;610 try {611 // eslint-disable-next-line no-await-in-loop612 response = await this.#runAfterResponseHooks(response);613 } catch (error) {614 if (!isForceRetryError(error)) {615 throw error;616 }617618 retryError = error;619 }620621 if (retryError === undefined) {622 const currentResponse: Response = response;623624 // Opaque responses (`response.type === 'opaque'`) from `no-cors` requests always have `status: 0` and `ok: false`, but this is not a failure - the actual status is hidden by the browser.625 if (currentResponse.ok || currentResponse.type === 'opaque' || !this.#shouldThrowHttpErrors(currentResponse)) {626 break;627 }628629 // `request` must reflect the request that actually failed, but `options` stays as Ky's630 // normalized options snapshot. Replacement `Request` instances do not preserve the631 // original `BodyInit`, so trying to make `options` mirror arbitrary requests would be lossy.632 const httpError: HTTPError = new HTTPError(currentResponse, this.#getResponseRequest(currentResponse), this.#getNormalizedOptions());633 // eslint-disable-next-line no-await-in-loop634 httpError.data = await this.#getResponseData(currentResponse);635 this.#throwIfAbortedByUser();636 this.#throwIfTotalTimeoutExhausted();637638 if (responseFromHook) {639 throw httpError;640 }641642 retryError = httpError;643 }644645 // eslint-disable-next-line no-await-in-loop646 response = await this.#retryFromError(retryError);647 }648649 this.#decorateResponse(response);650651 // If `onDownloadProgress` is passed, it uses the stream API internally652 if (this.#options.onDownloadProgress) {653 if (!supportsResponseStreams) {654 throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');655 }656657 const progressResponse = streamResponse(response, this.#options.onDownloadProgress);658 this.#setResponseRequest(progressResponse, this.#getResponseRequest(response));659 return this.#decorateResponse(progressResponse);660 }661662 return response;663 }664

TweaksSindre Sorhusbefore adoption3ded2aa

line 665why, one step back
665 #calculateDelay(retry: InternalOptions['retry'], error: unknown): number {

Harden retrySindre Sorhusbefore adoptionc426f19

line 666why, one step back
666 const retryDelay = retry.delay(this.#retryCount + 1);

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

line 667why, one step back
667

TweaksSindre Sorhusbefore adoption3ded2aa

line 668why, one step back
668 // A `retry.delay` that does not return a usable number would turn every delay into `NaN`, which `setTimeout()` clamps to 1ms, silently disabling the configured backoff. The `jitter` function form already guards its own result, so the input is checked here for every jitter form.

RefactorSindre Sorhusbefore adoptiona5ed57b

line 669why, one step back
669 if (!isNonNegativeNumber(retryDelay)) {

TweaksSindre Sorhusbefore adoption3ded2aa

lines 670–673why, one step back
670 // The failure that was being retried is chained as the cause, so `beforeError` can still inspect it instead of losing the response and data to this configuration mistake.
671 throw new TypeError('`retry.delay` must return a non-negative number or `Infinity`', {cause: error});672 }673

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

line 674why, one step back
674 let jitteredDelay = retryDelay;

Harden retrySindre Sorhusbefore adoptionc426f19

line 675why, one step back
675 if (retry.jitter === true) {

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

line 676why, one step back
676 jitteredDelay = Math.random() * retryDelay;

Harden retrySindre Sorhusbefore adoptionc426f19

lines 677–678why, one step back
677 } else if (typeof retry.jitter === 'function') {
678 jitteredDelay = retry.jitter(retryDelay);

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

lines 679–684why, one step back
679
680 if (!Number.isFinite(jitteredDelay) || jitteredDelay < 0) {681 jitteredDelay = retryDelay;682 }683 }684

Harden retrySindre Sorhusbefore adoptionc426f19

line 685why, one step back
685 return Math.min(retry.backoffLimit, jitteredDelay);

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

lines 686–688why, one step back
686 }
687688 async #calculateRetryDelay(error: unknown) {

Harden retrySindre Sorhusbefore adoptionc426f19

lines 689–690why, one step back
689 const retry = normalizeRetryOptions(this.#options.retry);
690 if (this.#retryCount >= Math.min(retry.limit, this.#retryLimit)) {

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 691–693why, one step back
691 throw error;
692 }693

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 694–695why, one step back
694 // Wrap non-Error throws to ensure consistent error handling. `NonError.wrap()` checks with `isError` rather than `instanceof`, so a cross-realm error reaches `shouldRetry` as itself, the same way it reaches `beforeError`.
695 const errorObject = NonError.wrap(error);

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

line 696why, one step back
696

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

line 697why, one step back
697 // Handle forced retry from afterResponse hook - skip method check and shouldRetry

TweaksSindre Sorhusbefore adoption3ded2aa

lines 698–699why, one step back
698 if (isForceRetryError(errorObject)) {
699 return errorObject.customDelay ?? this.#calculateDelay(retry, error);

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

lines 700–702why, one step back
700 }
701702 // Check if method is retriable for non-forced retries

Respect custom HTTP method case when matching retriesSindre Sorhusbefore adoptione4269f0

line 703why, one step back
703 if (!retry.methods.includes(normalizeRetryMethod(this.request.method))) {

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

lines 704–706why, one step back
704 throw error;
705 }706

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

line 707why, one step back
707 let shouldRetryOverride = false;

Harden retrySindre Sorhusbefore adoptionc426f19

lines 708–709why, one step back
708 const {shouldRetry} = retry;
709 if (shouldRetry !== undefined) {

RefactorSindre Sorhusbefore adoptiona5ed57b

line 710why, one step back
710 const result = await this.#raceWithTotalTimeout(async () => shouldRetry({error: errorObject, retryCount: this.#retryCount + 1}));

Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae

line 711why, one step back
711 this.#throwIfAbortedByUser();

RefactorSindre Sorhusbefore adoptiona5ed57b

line 712why, one step back
712 if (result === timedOut) {

TweaksSindre Sorhusbefore adoption3ded2aa

line 713why, one step back
713 throw new TimeoutError(this.#sentRequest);

Harden retrySindre Sorhusbefore adoptionc426f19

line 714why, one step back
714 }

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

line 715why, one step back
715

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 716why, one step back
716 // Only exact booleans override the default retry checks.

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

lines 717–720why, one step back
717 if (result === false) {
718 throw error;719 }720

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

line 721why, one step back
721 shouldRetryOverride = result === true;

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

lines 722–724why, one step back
722 }
723724 // Default timeout behavior

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

line 725why, one step back
725 if (isTimeoutError(error)) {

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

line 726why, one step back
726 if (!shouldRetryOverride && !retry.retryOnTimeout) {

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

lines 727–729why, one step back
727 throw error;
728 }729

TweaksSindre Sorhusbefore adoption3ded2aa

line 730why, one step back
730 return this.#calculateDelay(retry, error);

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

lines 731–732why, one step back
731 }
732

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

line 733why, one step back
733 if (isHTTPError(error)) {

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

line 734why, one step back
734 if (!shouldRetryOverride && !retry.statusCodes.includes(error.response.status)) {

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 735–737why, one step back
735 throw error;
736 }737

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 738why, one step back
738 const retryTimingHeader = getRetryTimingHeader(error.response.headers);

Harden retrySindre Sorhusbefore adoptionc426f19

line 739why, one step back
739 if (retryTimingHeader && retry.afterStatusCodes.includes(error.response.status)) {

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 740–742why, one step back
740 const after = calculateRetryTimingDelay(retryTimingHeader);
741 if (after === undefined) {742 // Malformed retry timing headers should not disable retries; they only lose their server-provided timing.

TweaksSindre Sorhusbefore adoption3ded2aa

line 743why, one step back
743 return this.#calculateDelay(retry, error);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 744–745why, one step back
744 }
745

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

line 746why, one step back
746 // Don't apply jitter when server provides explicit retry timing

Harden retrySindre Sorhusbefore adoptionc426f19

line 747why, one step back
747 return Math.min(retry.maxRetryAfter, after);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 748–749why, one step back
748 }
749

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

line 750why, one step back
750 if (!shouldRetryOverride && error.response.status === 413) {

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 751–752why, one step back
751 throw error;
752 }

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

line 753why, one step back
753

TweaksSindre Sorhusbefore adoption3ded2aa

line 754why, one step back
754 return this.#calculateDelay(retry, error);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 755–756why, one step back
755 }
756

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

line 757why, one step back
757 // Only retry known retriable error types. Unknown errors (e.g., programming bugs) are not retried.

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

line 758why, one step back
758 if (!shouldRetryOverride && !isNetworkError(error)) {

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

lines 759–761why, one step back
759 throw error;
760 }761

TweaksSindre Sorhusbefore adoption3ded2aa

line 762why, one step back
762 return this.#calculateDelay(retry, error);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 763–764why, one step back
763 }
764

Code styleSindre Sorhusbefore adoption333afbe

line 765why, one step back
765 #decorateResponse(response: Response): Response {

Fix `parseJson` being ignored by `response.clone().json()`Sindre Sorhusbefore adoptionc6c5dbf

lines 766–770why, one step back
766 if (!this.#options.parseJson || this.#decoratedResponses.has(response)) {
767 return response;768 }769770 this.#decoratedResponses.add(response);

Various tweaksSindre Sorhusbefore adoption0dd9522

lines 771–772why, one step back
771 const request = this.#getResponseRequest(response);
772

RefactorSindre Sorhusbefore adoptiona5ed57b

line 773why, one step back
773 response.json = async () => this.#parseJson(await response.text(), request, response);

Fix `parseJson` being ignored by `response.clone().json()`Sindre Sorhusbefore adoptionc6c5dbf

line 774why, one step back
774

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

lines 775–777why, one step back
775 // `clone()` returns a fresh `Response` that would otherwise fall back to the native `json()`.
776 const nativeClone = response.clone.bind(response);777 response.clone = () => this.#decorateResponse(this.#setResponseRequest(nativeClone(), request));

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 778–779why, one step back
778
779 return response;

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

lines 780–781why, one step back
780 }
781

TweaksSindre Sorhusbefore adoption3ded2aa

lines 782–785why, one step back
782 // Defaults to the last request that was actually sent, because `this.request` is the clone `#fetch()` prepares for a possible retry and may never be sent at all.
783 async #throwProcessedError(error: unknown, request: Request = this.#sentRequest): Promise<never> {784 // Non-Error throws (e.g., thrown strings) pass through unchanged. `isError` reads the internal brand, so an error from another realm still runs the hooks, the same way the Ky type guards accept branded errors.785 if (!isError(error)) {

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 786–795why, one step back
786 throw error;
787 }788789 // Errors thrown by beforeRetry hooks must propagate unchanged.790 if (this.#beforeRetryHookErrors.has(error)) {791 throw error;792 }793794 let processedError: Error = error;795 for (const hook of this.#options.hooks.beforeError) {

TweaksSindre Sorhusbefore adoption3ded2aa

line 796why, one step back
796 // `options` intentionally remains the stable normalized Ky options snapshot for the same reason as `HTTPError` above.

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 797–798why, one step back
797 // eslint-disable-next-line no-await-in-loop
798 const hookResult: unknown = await hook({

TweaksSindre Sorhusbefore adoption3ded2aa

line 799why, one step back
799 request,

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 800–804why, one step back
800 options: this.#getNormalizedOptions(),
801 error: processedError,802 retryCount: this.#retryCount,803 });804

TweaksSindre Sorhusbefore adoption3ded2aa

lines 805–806why, one step back
805 // Only overwrite if the hook returns a valid Error, including one from another realm.
806 if (isError(hookResult)) {

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 807–813why, one step back
807 processedError = hookResult;
808 }809 }810811 throw processedError;812 }813

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

line 814why, one step back
814 async #getResponseData(response: Response): Promise<unknown> {

HardenSindre Sorhusbefore adoption8d8e7a4

lines 815–817why, one step back
815 // `request` is the request that actually produced this response, which is not `this.request` once a retry clone has been prepared.
816 const request = this.#getResponseRequest(response);817

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 818–820why, one step back
818 // A timed-out read or parse gives up on the data, but an exhausted `totalTimeout` still fails the request.
819 const throwIfTotalTimeoutReached = ({fromTotalTimeout}: ErrorDataTimeout): void => {820 if (fromTotalTimeout) {

HardenSindre Sorhusbefore adoption8d8e7a4

line 821why, one step back
821 throw new TimeoutError(request);

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 822–823why, one step back
822 }
823

HardenSindre Sorhusbefore adoption8d8e7a4

line 824why, one step back
824 this.#throwIfTotalTimeoutExhausted(request);

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 825–832why, one step back
825 };
826827 // Even with request timeouts disabled, bound error-body reads so retries and error propagation828 // cannot be stalled indefinitely by never-ending response streams.829 const readTimeout = this.#getErrorDataTimeout(request);830 const text = await readResponseText(response, readTimeout.milliseconds);831 if (text === timedOut) {832 throwIfTotalTimeoutReached(readTimeout);

Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7

lines 833–835why, one step back
833 return undefined;
834 }835

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

lines 836–839why, one step back
836 if (!text) {
837 return undefined;838 }839

RefactorSindre Sorhusbefore adoptiona5ed57b

line 840why, one step back
840 if (!isJsonContentType(response.headers.get('content-type') ?? '')) {

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

lines 841–843why, one step back
841 return text;
842 }843

HardenSindre Sorhusbefore adoption8d8e7a4

line 844why, one step back
844 const parseTimeout = this.#getErrorDataTimeout(request);

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 845–848why, one step back
845 // Unparsable error data is given up on, like unreadable error data.
846 const data = await raceWithTimeout(Promise.resolve().then(() => this.#parseJson(text, request, response)), parseTimeout.milliseconds).catch(() => undefined);847 if (data === timedOut) {848 throwIfTotalTimeoutReached(parseTimeout);

Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7

lines 849–852why, one step back
849 return undefined;
850 }851852 return data;

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

lines 853–854why, one step back
853 }
854

RefactorSindre Sorhusbefore adoptiona5ed57b

line 855why, one step back
855 #getErrorDataTimeout(request: Request): ErrorDataTimeout {

Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7

lines 856–857why, one step back
856 const errorDataTimeout = this.#options.timeout === false ? 10_000 : this.#options.timeout;
857 const remainingTotal = this.#getRemainingTotalTimeout();

RefactorSindre Sorhusbefore adoptiona5ed57b

line 858why, one step back
858 if (remainingTotal === 0) {

HardenSindre Sorhusbefore adoption8d8e7a4

line 859why, one step back
859 throw new TimeoutError(request);

Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7

lines 860–861why, one step back
860 }
861

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 862–867why, one step back
862 return {
863 milliseconds: Math.min(errorDataTimeout, remainingTotal),864 fromTotalTimeout: remainingTotal <= errorDataTimeout,865 };866 }867

RefactorSindre Sorhusbefore adoptiona5ed57b

line 868why, one step back
868 // The smaller of `timeout` and the `totalTimeout` budget left, or `undefined` when neither applies, since `setTimeout()` cannot wait forever.

Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90

line 869why, one step back
869 #getEffectiveTimeout(): number | undefined {

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 870why, one step back
870 const remainingTotal = this.#getRemainingTotalTimeout();

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 871–872why, one step back
871 if (remainingTotal === 0) {
872 throw new TimeoutError(this.#sentRequest);

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 873–874why, one step back
873 }
874

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 875–876why, one step back
875 const effectiveTimeout = Math.min(this.#options.timeout === false ? Number.POSITIVE_INFINITY : this.#options.timeout, remainingTotal);
876 return effectiveTimeout === Number.POSITIVE_INFINITY ? undefined : effectiveTimeout;

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 877–881why, one step back
877 }
878879 // Unlike error bodies (`#getResponseData`), a successful body read has no fallback value to return -880 // the caller's `.json()`/`.text()`/etc. promise must settle, so a timeout here always rejects.881 async #raceBodyRead(createBodyPromise: () => Promise<unknown>, response: Response): Promise<unknown> {

TweaksSindre Sorhusbefore adoption3ded2aa

line 882why, one step back
882 const failedRequest = this.#getResponseRequest(response);

RefactorSindre Sorhusbefore adoptiona5ed57b

line 883why, one step back
883 let timeoutMilliseconds: number | undefined;

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 884why, one step back
884 try {

RefactorSindre Sorhusbefore adoptiona5ed57b

line 885why, one step back
885 timeoutMilliseconds = this.#getEffectiveTimeout();

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 886why, one step back
886 } catch (error: unknown) {

TweaksSindre Sorhusbefore adoption3ded2aa

line 887why, one step back
887 await this.#throwProcessedError(error, failedRequest);

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 888–889why, one step back
888 }
889

Fix `beforeError` hooks running again when a body fails after the body read timed outSindre Sorhusbefore adoptione087b0c

lines 890–893why, one step back
890 const bodyPromise = createBodyPromise();
891892 let result: unknown;893 try {

RefactorSindre Sorhusbefore adoptiona5ed57b

line 894why, one step back
894 result = timeoutMilliseconds === undefined

Fix `beforeError` hooks running again when a body fails after the body read timed outSindre Sorhusbefore adoptione087b0c

line 895why, one step back
895 ? await bodyPromise

RefactorSindre Sorhusbefore adoptiona5ed57b

line 896why, one step back
896 : await raceWithTimeout(bodyPromise, timeoutMilliseconds);

Fix `beforeError` hooks running again when a body fails after the body read timed outSindre Sorhusbefore adoptione087b0c

line 897why, one step back
897 } catch (error: unknown) {

Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f

line 898why, one step back
898 if (this.#userProvidedAbortSignal?.aborted) {

TweaksSindre Sorhusbefore adoption3ded2aa

line 899why, one step back
899 await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);

Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f

lines 900–901why, one step back
900 }
901

Enforce total timeout after fetch and body processingSindre Sorhusbefore adoption82fa84c

lines 902–905why, one step back
902 if (this.#getRemainingTotalTimeout() !== 0) {
903 // A connection dropped while streaming the body surfaces as a raw runtime `TypeError`. Wrap it like fetch-phase network errors so it is recognizable and runs `beforeError` hooks.904 // This only happens on the awaited path, so a body that fails after the timeout already won does not run the hooks again.905 if (isRawNetworkError(error)) {

TweaksSindre Sorhusbefore adoption3ded2aa

line 906why, one step back
906 await this.#throwProcessedError(new NetworkError(failedRequest, {cause: error as Error}), failedRequest);

Enforce total timeout after fetch and body processingSindre Sorhusbefore adoption82fa84c

lines 907–908why, one step back
907 }
908

TweaksSindre Sorhusbefore adoption3ded2aa

line 909why, one step back
909 await this.#throwProcessedError(error, failedRequest);

Fix `beforeError` hooks running again when a body fails after the body read timed outSindre Sorhusbefore adoptione087b0c

lines 910–911why, one step back
910 }
911

RefactorSindre Sorhusbefore adoptiona5ed57b

line 912why, one step back
912 result = timedOut;

Fix `beforeError` hooks running again when a body fails after the body read timed outSindre Sorhusbefore adoptione087b0c

line 913why, one step back
913 }

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 914why, one step back
914

TweaksSindre Sorhusbefore adoption3ded2aa

lines 915–919why, one step back
915 // A cancellation is part of the request lifecycle, so it must not resolve as a successful body read just because the bytes happened to arrive first. `.json()` already gets this check for free through `#raceWithTotalTimeout()`, which is why the shortcuts used to disagree here.
916 if (this.#userProvidedAbortSignal?.aborted) {917 await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);918 }919

RefactorSindre Sorhusbefore adoptiona5ed57b

line 920why, one step back
920 if (result === timedOut || this.#getRemainingTotalTimeout() === 0) {

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 921–924why, one step back
921 // The stream is locked by the native body method's own reader by this point, so
922 // `response.body.cancel()` would reject as "already locked". Aborting the request's923 // signal is what actually interrupts the underlying network read.924 this.#abortController?.abort();

TweaksSindre Sorhusbefore adoption3ded2aa

line 925why, one step back
925 await this.#throwProcessedError(new TimeoutError(failedRequest), failedRequest);

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 926–930why, one step back
926 }
927928 return result;929 }930

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 931–932why, one step back
931 async #raceWithTotalTimeout<T>(operation: () => Promise<T>): Promise<T | typeof timedOut> {
932 const abortSignal = this.#userProvidedAbortSignal;

Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae

line 933why, one step back
933 abortSignal?.throwIfAborted();

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 934why, one step back
934

Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae

line 935why, one step back
935 const remainingTotal = this.#getRemainingTotalTimeout();

RefactorSindre Sorhusbefore adoptiona5ed57b

line 936why, one step back
936 if (remainingTotal === 0) {

Harden retrySindre Sorhusbefore adoptionc426f19

line 937why, one step back
937 this.#abortController?.abort();

RefactorSindre Sorhusbefore adoptiona5ed57b

line 938why, one step back
938 return timedOut;

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 939–940why, one step back
939 }
940

Harden retrySindre Sorhusbefore adoptionc426f19

line 941why, one step back
941 let timeoutId: ReturnType<typeof setTimeout> | undefined;

Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae

line 942why, one step back
942 let abortListener: (() => void) | undefined;

TweaksSindre Sorhusbefore adoption3ded2aa

line 943why, one step back
943 let operationPromise: Promise<T> | undefined;

Harden retrySindre Sorhusbefore adoptionc426f19

line 944why, one step back
944 try {

Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae

lines 945–954why, one step back
945 const abortPromise = new Promise<never>((_resolve, reject) => {
946 if (!abortSignal) {947 return;948 }949950 abortListener = () => {951 // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- AbortSignal reasons can be any value and must be preserved exactly.952 reject(abortSignal.reason);953 };954

RefactorSindre Sorhusbefore adoptiona5ed57b

line 955why, one step back
955 // The signal was checked above, and nothing ran since, so it cannot have aborted before the listener is added.

Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae

lines 956–957why, one step back
956 abortSignal.addEventListener('abort', abortListener, {once: true});
957 });

TweaksSindre Sorhusbefore adoption3ded2aa

line 958why, one step back
958 operationPromise = operation();

Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae

line 959why, one step back
959

RefactorSindre Sorhusbefore adoptiona5ed57b

line 960why, one step back
960 if (remainingTotal === Number.POSITIVE_INFINITY) {

Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae

lines 961–963why, one step back
961 return await Promise.race([operationPromise, abortPromise]);
962 }963

RefactorSindre Sorhusbefore adoptiona5ed57b

line 964why, one step back
964 const timeoutPromise = new Promise<typeof timedOut>(resolve => {

Harden retrySindre Sorhusbefore adoptionc426f19

line 965why, one step back
965 timeoutId = setTimeout(() => {

RefactorSindre Sorhusbefore adoptiona5ed57b

line 966why, one step back
966 resolve(timedOut);

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 967why, one step back
967 }, remainingTotal);

Harden retrySindre Sorhusbefore adoptionc426f19

line 968why, one step back
968 });

Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae

line 969why, one step back
969 const result = await Promise.race([operationPromise, timeoutPromise, abortPromise]);

RefactorSindre Sorhusbefore adoptiona5ed57b

line 970why, one step back
970 if (result === timedOut || this.#getRemainingTotalTimeout() === 0) {

Harden retrySindre Sorhusbefore adoptionc426f19

line 971why, one step back
971 this.#abortController?.abort();

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 972why, one step back
972

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 973–974why, one step back
973 if (result === timedOut) {
974 releaseWhenSettled(operationPromise);

Preserve caller stack for schema validation errors (#883)Sindre Sorhusbefore adoptione68ea7a

line 975why, one step back
975 } else {

RefactorSindre Sorhusbefore adoptiona5ed57b

line 976why, one step back
976 cancelReturnedBody(result);

Harden retrySindre Sorhusbefore adoptionc426f19

line 977why, one step back
977 }

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 978why, one step back
978

RefactorSindre Sorhusbefore adoptiona5ed57b

line 979why, one step back
979 return timedOut;

Harden retrySindre Sorhusbefore adoptionc426f19

lines 980–981why, one step back
980 }
981

Preserve caller stack for schema validation errors (#883)Sindre Sorhusbefore adoptione68ea7a

lines 982–983why, one step back
982 return result;
983 } catch (error: unknown) {

TweaksSindre Sorhusbefore adoption3ded2aa

line 984why, one step back
984 if (abortSignal?.aborted) {

RefactorSindre Sorhusbefore adoptiona5ed57b

line 985why, one step back
985 // The abort won the race, so whatever the operation eventually returns is discarded. Release its body, the same way the timeout path above does for a value it never consumed.

TweaksSindre Sorhusbefore adoption3ded2aa

line 986why, one step back
986 if (operationPromise) {

RefactorSindre Sorhusbefore adoptiona5ed57b

line 987why, one step back
987 releaseWhenSettled(operationPromise);

TweaksSindre Sorhusbefore adoption3ded2aa

line 988why, one step back
988 }

Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae

line 989why, one step back
989

TweaksSindre Sorhusbefore adoption3ded2aa

lines 990–992why, one step back
990 abortSignal.throwIfAborted();
991 }992

RefactorSindre Sorhusbefore adoptiona5ed57b

line 993why, one step back
993 if (this.#getRemainingTotalTimeout() === 0) {

Preserve caller stack for schema validation errors (#883)Sindre Sorhusbefore adoptione68ea7a

line 994why, one step back
994 this.#abortController?.abort();

RefactorSindre Sorhusbefore adoptiona5ed57b

line 995why, one step back
995 return timedOut;

Harden retrySindre Sorhusbefore adoptionc426f19

lines 996–997why, one step back
996 }
997

Preserve caller stack for schema validation errors (#883)Sindre Sorhusbefore adoptione68ea7a

line 998why, one step back
998 throw error;

Harden retrySindre Sorhusbefore adoptionc426f19

lines 999–1000why, one step back
999 } finally {
1000 clearTimeout(timeoutId);

Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae

lines 1001–1003why, one step back
1001 if (abortListener) {
1002 abortSignal?.removeEventListener('abort', abortListener);1003 }

Harden retrySindre Sorhusbefore adoptionc426f19

line 1004why, one step back
1004 }

Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7

lines 1005–1006why, one step back
1005 }
1006

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 1007–1010why, one step back
1007 // Uses `parseJson` when it is set, and `JSON.parse()` otherwise.
1008 #parseJson(text: string, request: Request, response: Response): unknown {1009 const {parseJson} = this.#options;1010 return parseJson ? parseJson(text, {request, response}) : JSON.parse(text);

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

lines 1011–1012why, one step back
1011 }
1012

Various tweaksSindre Sorhusbefore adoption0dd9522

lines 1013–1016why, one step back
1013 #createManagedSignal(): AbortSignal {
1014 return this.#userProvidedAbortSignal1015 ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController!.signal])1016 : this.#abortController!.signal;

Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33

lines 1017–1018why, one step back
1017 }
1018

TweaksSindre Sorhusbefore adoption3ded2aa

lines 1019–1024why, one step back
1019 // A `throwHttpErrors` predicate that throws used to escape from the `if` condition, before the body was read or released, leaving the caller with an error and no handle on the response to release it with.
1020 #shouldThrowHttpErrors(response: Response): boolean {1021 const {throwHttpErrors} = this.#options;1022 try {1023 return typeof throwHttpErrors === 'function' ? throwHttpErrors(response.status) : throwHttpErrors;1024 } catch (error: unknown) {

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1025why, one step back
1025 cancelBody(response);

TweaksSindre Sorhusbefore adoption3ded2aa

lines 1026–1035why, one step back
1026 throw error;
1027 }1028 }10291030 // `#fetch()` replaces `this.request` with the clone it prepares for a possible retry, so anything reporting the request that produced a response or failed has to use the one that was actually sent.1031 get #sentRequest(): Request {1032 return this.#originalRequest ?? this.request;1033 }10341035 #throwIfTotalTimeoutExhausted(request: Request = this.#sentRequest): void {

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1036why, one step back
1036 if (this.#getRemainingTotalTimeout() === 0) {

HardenSindre Sorhusbefore adoption8d8e7a4

line 1037why, one step back
1037 throw new TimeoutError(request);

Various tweaksSindre Sorhusbefore adoption0dd9522

lines 1038–1040why, one step back
1038 }
1039 }1040

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1041–1043why, one step back
1041 async #runBeforeRequestHooks(): Promise<Response | undefined> {
1042 for (const hook of this.#options.hooks.beforeRequest) {1043 // eslint-disable-next-line no-await-in-loop

Harden retrySindre Sorhusbefore adoptionc426f19

line 1044why, one step back
1044 const result = await this.#raceWithTotalTimeout(async () => hook({

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1045–1047why, one step back
1045 request: this.request,
1046 options: this.#getNormalizedOptions(),1047 retryCount: 0,

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1048why, one step back
1048 }));

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 1049why, one step back
1049

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1050why, one step back
1050 if (result === timedOut) {

TweaksSindre Sorhusbefore adoption3ded2aa

line 1051why, one step back
1051 throw new TimeoutError(this.#sentRequest);

Harden retrySindre Sorhusbefore adoptionc426f19

lines 1052–1053why, one step back
1052 }
1053

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1054why, one step back
1054 if (isRequest(result)) {

Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooksSindre Sorhusbefore adoptione1b088e

line 1055why, one step back
1055 this.#assignRequest(this.#withManagedSignal(result));

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 1056–1057why, one step back
1056 } else if (isResponse(result)) {
1057 this.#hookResponses.add(result);

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1058–1065why, one step back
1058 return result;
1059 }1060 }10611062 return undefined;1063 }10641065 async #runAfterResponseHooks(response: Response): Promise<Response> {

Various tweaksSindre Sorhusbefore adoption0dd9522

line 1066why, one step back
1066 const responseRequest = this.#getResponseRequest(response);

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

line 1067why, one step back
1067 response = this.#limitResponseSize(response);

Various tweaksSindre Sorhusbefore adoption0dd9522

line 1068why, one step back
1068

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 1069why, one step back
1069 for (const hook of this.#options.hooks.afterResponse) {

Improve compatibility with custom `fetch` implementations (#858)Sindre Sorhusbefore adoption2971991

lines 1070–1071why, one step back
1070 const hookResponse = this.#setResponseRequest(response.clone(), responseRequest);
1071 this.#decorateResponse(hookResponse);

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1072–1075why, one step back
1072
1073 let modifiedResponse;1074 try {1075 // eslint-disable-next-line no-await-in-loop

Harden retrySindre Sorhusbefore adoptionc426f19

line 1076why, one step back
1076 modifiedResponse = await this.#raceWithTotalTimeout(async () => hook({

TweaksSindre Sorhusbefore adoption3ded2aa

line 1077why, one step back
1077 // Deliberately `this.request`, which `#fetch()` has already replaced with the clone prepared for a retry, so its body is still unread. A hook that forces a retry with `ky.retry({request: new Request(request)})` depends on being able to copy an unconsumed request from here.

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1078–1079why, one step back
1078 request: this.request,
1079 options: this.#getNormalizedOptions(),

Improve compatibility with custom `fetch` implementations (#858)Sindre Sorhusbefore adoption2971991

line 1080why, one step back
1080 response: hookResponse,

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 1081why, one step back
1081 retryCount: this.#retryCount,

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1082why, one step back
1082 }));

Harden retrySindre Sorhusbefore adoptionc426f19

line 1083why, one step back
1083

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1084why, one step back
1084 if (modifiedResponse === timedOut) {

TweaksSindre Sorhusbefore adoption3ded2aa

line 1085why, one step back
1085 throw new TimeoutError(this.#sentRequest);

Harden retrySindre Sorhusbefore adoptionc426f19

line 1086why, one step back
1086 }

Improve compatibility with custom `fetch` implementations (#858)Sindre Sorhusbefore adoption2971991

line 1087why, one step back
1087

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 1088–1095why, one step back
1088 if (isRetryMarker(modifiedResponse)) {
1089 throw new ForceRetryError(modifiedResponse.options);1090 }1091 } catch (error) {1092 // Cancel both the cloned response passed to the hook and the current response to prevent memory leaks when a hook throws, times out, or forces a retry (especially important in Deno/Bun).1093 // Do not await cancellation since hooks can clone the response, leaving extra tee branches that keep cancel promises pending per the Streams spec.1094 cancelBody(hookResponse);1095 cancelBody(response);

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1096–1098why, one step back
1096 throw error;
1097 }1098

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1099why, one step back
1099 const nextResponse = isResponse(modifiedResponse)

Improve compatibility with custom `fetch` implementations (#858)Sindre Sorhusbefore adoption2971991

lines 1100–1101why, one step back
1100 ? this.#setResponseRequest(modifiedResponse, responseRequest)
1101 : response;

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1102–1104why, one step back
1102
1103 // Cancel any response bodies we won't use to prevent memory leaks.1104 // Uses fire-and-forget since hooks may have cloned the response, creating tee branches that block cancellation.

Fix hook state leaks and fetch option forwardingSindre Sorhusbefore adoption2df9b7e

line 1105why, one step back
1105 // If the hook wrapped an existing body into a new Response, both Response objects can still point at the same stream.

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 1106–1107why, one step back
1106 cancelBody(hookResponse, nextResponse);
1107 cancelBody(response, nextResponse);

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 1108why, one step back
1108

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

lines 1109–1111why, one step back
1109 if (nextResponse !== response) {
1110 response = this.#limitResponseSize(nextResponse);1111 }

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1112–1116why, one step back
1112 }
11131114 return response;1115 }1116

Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90

line 1117why, one step back
1117 async #retry(): Promise<Response | void> {

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1118why, one step back
1118 try {

Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90

line 1119why, one step back
1119 return await this.#fetch();

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1120why, one step back
1120 } catch (error) {

Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90

line 1121why, one step back
1121 return this.#retryFromError(error);

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1122–1123why, one step back
1122 }
1123 }

Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa

line 1124why, one step back
1124

Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90

line 1125why, one step back
1125 async #retryFromError(error: unknown): Promise<Response | void> {

Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae

line 1126why, one step back
1126 this.#throwIfAbortedByUser();

Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa

line 1127why, one step back
1127

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 1128why, one step back
1128 const retryDelay = Math.min(await this.#calculateRetryDelay(error), maxSafeTimeout);

Various tweaksSindre Sorhusbefore adoption0dd9522

line 1129why, one step back
1129 const delayOptions = {signal: this.#userProvidedAbortSignal};

Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa

line 1130why, one step back
1130

Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7

line 1131why, one step back
1131 const remainingTimeout = this.#getRemainingTotalTimeout();

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 1132–1134why, one step back
1132 if (remainingTimeout === 0) {
1133 throw new TimeoutError(this.#sentRequest);1134 }

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1135why, one step back
1135

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 1136–1139why, one step back
1136 // If waiting would consume all remaining budget, time out without starting another request.
1137 if (retryDelay >= remainingTimeout) {1138 await delay(remainingTimeout, delayOptions);1139 throw new TimeoutError(this.#sentRequest);

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 1140why, one step back
1140 }

Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa

line 1141why, one step back
1141

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1142–1143why, one step back
1142 // Only use user-provided signal for delay, not our internal abortController
1143 await delay(retryDelay, delayOptions);

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

line 1144why, one step back
1144

Various tweaksSindre Sorhusbefore adoption0dd9522

line 1145why, one step back
1145 this.#throwIfTotalTimeoutExhausted();

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

line 1146why, one step back
1146

Fix hooks receiving an aborted `signal` after retrying a timeoutSindre Sorhusbefore adoption2f0a3fb

lines 1147–1150why, one step back
1147 // Reset abortController if it was aborted (happens on timeout retry) so hooks and the retried request get a fresh signal
1148 if (this.#abortController?.signal.aborted) {1149 this.#abortController = new globalThis.AbortController();1150 this.#options.signal = this.#createManagedSignal();

Improve docsSindre Sorhusbefore adoption8778439

line 1151why, one step back
1151 this.#assignRequest(this.#withManagedSignal(this.request), this.#requestBodyCanBeCancelled);

Fix hooks receiving an aborted `signal` after retrying a timeoutSindre Sorhusbefore adoption2f0a3fb

lines 1152–1153why, one step back
1152 }
1153

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1154–1155why, one step back
1154 // Apply custom request from forced retry before beforeRetry hooks
1155 // Ensure the custom request has the correct managed signal for timeouts and user aborts

TweaksSindre Sorhusbefore adoption3ded2aa

line 1156why, one step back
1156 if (isForceRetryError(error) && error.customRequest) {

TweaksSindre Sorhusbefore adoption8f28eac

lines 1157–1159why, one step back
1157 // Replacement Requests are authoritative by design. Do not rewrite headers here,
1158 // even for cross-origin retries. Callers using `ky.retry({request})` explicitly1159 // opted into the exact Request they constructed.

Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooksSindre Sorhusbefore adoptione1b088e

line 1160why, one step back
1160 this.#assignRequest(this.#withManagedSignal(error.customRequest));

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 1161why, one step back
1161 }

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

line 1162why, one step back
1162

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 1163why, one step back
1163 for (const hook of this.#options.hooks.beforeRetry) {

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1164why, one step back
1164 let hookResult: Awaited<ReturnType<typeof hook>> | typeof timedOut;

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1165–1166why, one step back
1165 try {
1166 // eslint-disable-next-line no-await-in-loop

Harden retrySindre Sorhusbefore adoptionc426f19

line 1167why, one step back
1167 hookResult = await this.#raceWithTotalTimeout(async () => hook({

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1168–1169why, one step back
1168 request: this.request,
1169 options: this.#getNormalizedOptions(),

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1170why, one step back
1170 error: NonError.wrap(error),

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 1171why, one step back
1171 retryCount: this.#retryCount + 1,

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1172why, one step back
1172 }));

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 1173why, one step back
1173 } catch (hookError) {

Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8

lines 1174–1177why, one step back
1174 // A cancellation is part of the request lifecycle, so it reaches `beforeError` like every other abort rather than being hidden as a hook error below.
1175 this.#throwIfAbortedByUser();11761177 // Preserve the original request error path (`throw error`) so beforeError hooks can still run. `isError` rather than `instanceof`, so a cross-realm error is recognised the same way `#throwProcessedError` does.

TweaksSindre Sorhusbefore adoption3ded2aa

line 1178why, one step back
1178 if (isError(hookError) && hookError !== error) {

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 1179why, one step back
1179 this.#beforeRetryHookErrors.add(hookError);

Allow `beforeRetry` hooks to return a `Request` or `Response` (#774)Sindre Sorhusbefore adoptiona51bb1e

lines 1180–1181why, one step back
1180 }
1181

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1182–1183why, one step back
1182 throw hookError;
1183 }

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1184why, one step back
1184

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1185why, one step back
1185 if (hookResult === timedOut) {

TweaksSindre Sorhusbefore adoption3ded2aa

line 1186why, one step back
1186 throw new TimeoutError(this.#sentRequest);

Harden retrySindre Sorhusbefore adoptionc426f19

lines 1187–1188why, one step back
1187 }
1188

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1189why, one step back
1189 if (isRequest(hookResult)) {

TweaksSindre Sorhusbefore adoption8f28eac

lines 1190–1191why, one step back
1190 // Same contract as `ky.retry({request})`: a Request returned from `beforeRetry`
1191 // is used as-is rather than being sanitized or otherwise rewritten by Ky.

Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooksSindre Sorhusbefore adoptione1b088e

line 1192why, one step back
1192 this.#assignRequest(this.#withManagedSignal(hookResult));

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 1193why, one step back
1193 break;

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1194–1195why, one step back
1194 }
1195

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 1196–1197why, one step back
1196 if (isResponse(hookResult)) {
1197 this.#hookResponses.add(hookResult);

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1198–1199why, one step back
1198 this.#retryCount++;
1199 return hookResult;

Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa

lines 1200–1201why, one step back
1200 }
1201

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1202–1205why, one step back
1202 // If `stop` is returned from the hook, the retry process is stopped
1203 if (hookResult === stop) {1204 return;1205 }

Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327

lines 1206–1209why, one step back
1206
1207 if (isNonArrayObject(hookResult)) {1208 this.#applyBeforeRetryOptions(hookResult.options);1209 }

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1210why, one step back
1210 }

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 1211why, one step back
1211

Various tweaksSindre Sorhusbefore adoption0dd9522

line 1212why, one step back
1212 this.#throwIfTotalTimeoutExhausted();

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 1213–1214why, one step back
1213
1214 this.#retryCount++;

Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90

line 1215why, one step back
1215 return this.#retry();

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1216–1217why, one step back
1216 }
1217

Code styleSindre Sorhusbefore adoption333afbe

line 1218why, one step back
1218 async #fetch(): Promise<Response> {

Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f

line 1219why, one step back
1219 // A previous attempt can return without consuming its upload. Release that unused branch before replacing the request reference.

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1220why, one step back
1220 cancelBody(this.#originalRequest, this.request);

Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f

line 1221why, one step back
1221

Fix hook state leaks and fetch option forwardingSindre Sorhusbefore adoption2df9b7e

line 1222why, one step back
1222 const nonRequestOptions = findUnknownOptions(this.#options);

Harden retrySindre Sorhusbefore adoptionc426f19

line 1223why, one step back
1223 this.#retryLimit = normalizeRetryOptions(this.#options.retry).limit;

Fix retry abort propagation and uploads without request stream supportSindre Sorhusbefore adoption6520f64

lines 1224–1225why, one step back
1224 // Reattach the managed signal because Node.js can garbage-collect the abort controller used by Request.clone().
1225 const retryRequest = this.#retryLimit > 0 ? this.#withManagedSignal(this.request.clone()) : undefined;

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1226why, one step back
1226 const request = this.#wrapRequestWithUploadProgress(this.request);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1227why, one step back
1227

Skip request cloning when retries are disabled to prevent buffering large streaming bodiesSindre Sorhusbefore adoption6f3d1bd

line 1228why, one step back
1228 // Cloning is done here to prepare in advance for retries.

Fix typosSindre Sorhusbefore adoptionbbc98fc

line 1229why, one step back
1229 // Skip cloning when retries are disabled - cloning a streaming body calls ReadableStream#tee()

Skip request cloning when retries are disabled to prevent buffering large streaming bodiesSindre Sorhusbefore adoption6f3d1bd

line 1230why, one step back
1230 // which buffers the entire stream in memory, causing excessive memory usage for large uploads.

Fix `beforeRequest` hooks being skipped when a `Request` is returned (#832)Sindre Sorhusbefore adoptionaec65db

lines 1231–1233why, one step back
1231 this.#originalRequest = request;
1232 if (retryRequest) {1233 this.request = retryRequest;

Improve docsSindre Sorhusbefore adoption8778439

line 1234why, one step back
1234 this.#requestBodyCanBeCancelled = true;

Skip request cloning when retries are disabled to prevent buffering large streaming bodiesSindre Sorhusbefore adoption6f3d1bd

line 1235why, one step back
1235 }

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1236why, one step back
1236

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

line 1237why, one step back
1237 try {

Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90

line 1238why, one step back
1238 const effectiveTimeout = this.#getEffectiveTimeout();

Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7

line 1239why, one step back
1239

Fix `fetch: window.fetch` throwing "Illegal invocation" in browsersSindre Sorhusbefore adoption92ef60e

lines 1240–1241why, one step back
1240 // Called unbound so a native `window.fetch` is not invoked with the options object as `this`, which throws "Illegal invocation" in browsers.
1241 const {fetch} = this.#options;

Various tweaksSindre Sorhusbefore adoption0dd9522

line 1242why, one step back
1242 const response = effectiveTimeout === undefined

Fix `fetch: window.fetch` throwing "Illegal invocation" in browsersSindre Sorhusbefore adoption92ef60e

line 1243why, one step back
1243 ? await fetch(request, nonRequestOptions)

Various tweaksSindre Sorhusbefore adoption0dd9522

lines 1244–1245why, one step back
1244 : await timeout(request, nonRequestOptions, this.#abortController, {
1245 timeout: effectiveTimeout,

Fix `fetch: window.fetch` throwing "Illegal invocation" in browsersSindre Sorhusbefore adoption92ef60e

line 1246why, one step back
1246 fetch,

Various tweaksSindre Sorhusbefore adoption0dd9522

line 1247why, one step back
1247 });

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1248why, one step back
1248

TweaksSindre Sorhusbefore adoption3ded2aa

line 1249why, one step back
1249 // `undefined` would otherwise look like `ky.stop`, and any other value fails later with an error that does not name the cause.

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1250why, one step back
1250 if (!isResponse(response)) {

TweaksSindre Sorhusbefore adoption3ded2aa

lines 1251–1253why, one step back
1251 throw new TypeError('The `fetch` option must resolve with a `Response`');
1252 }1253

Enforce total timeout after fetch and body processingSindre Sorhusbefore adoption82fa84c

lines 1254–1255why, one step back
1254 if (this.#getRemainingTotalTimeout() === 0) {
1255 this.#abortController?.abort();

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1256why, one step back
1256 cancelBody(response);

Enforce total timeout after fetch and body processingSindre Sorhusbefore adoption82fa84c

lines 1257–1259why, one step back
1257 throw new TimeoutError(request);
1258 }1259

Various tweaksSindre Sorhusbefore adoption0dd9522

line 1260why, one step back
1260 return this.#setResponseRequest(response, request);

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

line 1261why, one step back
1261 } catch (error) {

Enforce total timeout after fetch and body processingSindre Sorhusbefore adoption82fa84c

lines 1262–1267why, one step back
1262 this.#throwIfAbortedByUser();
1263 if (this.#getRemainingTotalTimeout() === 0) {1264 this.#abortController?.abort();1265 throw new TimeoutError(request);1266 }1267

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

line 1268why, one step back
1268 if (isRawNetworkError(error)) {

Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f

line 1269why, one step back
1269 throw new NetworkError(request, {cause: error as Error});

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

lines 1270–1273why, one step back
1270 }
12711272 throw error;1273 }

Fix a user abort in Chromium being reported as `NetworkError` and retriedSindre Sorhusbefore adoption7c1272b

lines 1274–1278why, one step back
1274 }
12751276 // Chromium reports a user abort during a fetch or body read as `TypeError: Failed to fetch`, which would otherwise be mistaken for a dropped connection. Surface the abort reason instead, like other runtimes do.1277 #throwIfAbortedByUser(): void {1278 this.#userProvidedAbortSignal?.throwIfAborted();

Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa

lines 1279–1280why, one step back
1279 }
1280

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 1281–1283why, one step back
1281 // `0` once the `totalTimeout` budget is spent, and `Infinity` without a `totalTimeout`.
1282 #getRemainingTotalTimeout(): number {1283 return Math.max(0, this.#deadline - getCurrentTime());

Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327

lines 1284–1304why, one step back
1284 }
12851286 // Omitted options keep their value, and `undefined` restores Ky's default. The changes apply to the next attempt and every later one.1287 #applyBeforeRetryOptions(options: unknown): void {1288 if (!isNonArrayObject(options)) {1289 throw new TypeError('The `options` returned from a `beforeRetry` hook must be an object');1290 }12911292 for (const key of Object.keys(options)) {1293 if (!(beforeRetryOptionKeys as readonly string[]).includes(key)) {1294 throw new TypeError(`The \`${key}\` option cannot be changed from a \`beforeRetry\` hook`);1295 }1296 }12971298 const mergedOptions = {...this.#options, ...options};1299 const updatedOptions = {...mergedOptions, ...withAttemptDefaults(mergedOptions)};1300 validateCallbackOptions(updatedOptions);1301 validateTimeoutOption(updatedOptions.timeout, 'timeout');13021303 Object.assign(this.#options, updatedOptions);1304 this.#cachedNormalizedOptions = undefined;

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

lines 1305–1306why, one step back
1305 }
1306

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1307–1308why, one step back
1307 #getNormalizedOptions(): NormalizedOptions {
1308 if (!this.#cachedNormalizedOptions) {

Strip Ky-specific properties from normalized options passed to hooks (#826)Sindre Sorhusbefore adoption433febd

lines 1309–1316why, one step back
1309 // Exclude Ky-specific options that are not part of `RequestInit`.
1310 const {1311 hooks,1312 json,1313 parseJson,1314 stringifyJson,1315 searchParams,1316 timeout,

Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7

line 1317why, one step back
1317 totalTimeout,

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

line 1318why, one step back
1318 maxResponseSize,

Strip Ky-specific properties from normalized options passed to hooks (#826)Sindre Sorhusbefore adoption433febd

lines 1319–1323why, one step back
1319 throwHttpErrors,
1320 fetch,1321 ...normalizedOptions1322 } = this.#options;1323

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1324–1327why, one step back
1324 this.#cachedNormalizedOptions = Object.freeze(normalizedOptions) as NormalizedOptions;
1325 }13261327 return this.#cachedNormalizedOptions;

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

lines 1328–1329why, one step back
1328 }
1329

Improve docsSindre Sorhusbefore adoption8778439

lines 1330–1331why, one step back
1330 #assignRequest(request: Request, requestBodyCanBeCancelled = false): void {
1331 // Runtime-derived bodies such as `FormData` may still be serialized after a hook constructs a replacement Request, so only caller-provided streams and Ky's own prepared retry clones are safe to cancel here.

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 1332–1333why, one step back
1332 if (this.#requestBodyCanBeCancelled) {
1333 cancelBody(this.request, request);

Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f

lines 1334–1335why, one step back
1334 }
1335

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

line 1336why, one step back
1336 this.#cachedNormalizedOptions = undefined;

Fix `beforeRequest` hooks being skipped when a `Request` is returned (#832)Sindre Sorhusbefore adoptionaec65db

line 1337why, one step back
1337 this.request = request;

Improve docsSindre Sorhusbefore adoption8778439

line 1338why, one step back
1338 this.#requestBodyCanBeCancelled = requestBodyCanBeCancelled;

Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooksSindre Sorhusbefore adoptione1b088e

lines 1339–1340why, one step back
1339 }
1340

Fix headers set to `undefined` not removing the header from a `Request` inputSindre Sorhusbefore adoptiond5bacef

line 1341why, one step back
1341 // A replacement `Request` from a hook or `ky.retry({request})` carries its own signal, so re-attach Ky's managed signal to keep timeouts and user aborts working. Request-like objects are used as-is since the `Request` constructor cannot copy them, so they keep whatever signal they carry, even on a retry after a timeout.

Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooksSindre Sorhusbefore adoptione1b088e

lines 1342–1346why, one step back
1342 #withManagedSignal(request: Request): Request {
1343 if (!this.#options.signal || !(request instanceof globalThis.Request)) {1344 return request;1345 }1346

Fix retry abort propagation and uploads without request stream supportSindre Sorhusbefore adoption6520f64

lines 1347–1351why, one step back
1347 return new globalThis.Request(request, {
1348 signal: this.#options.signal,1349 referrer: request.referrer,1350 referrerPolicy: request.referrerPolicy,1351 });

Various tweaksSindre Sorhusbefore adoption0dd9522

lines 1352–1353why, one step back
1352 }
1353

Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d

line 1354why, one step back
1354 // A response Ky did not fetch, such as one returned from a `beforeRetry` hook, is reported with the last request that was sent, like every error is.

Various tweaksSindre Sorhusbefore adoption0dd9522

line 1355why, one step back
1355 #getResponseRequest(response: Response): Request {

Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d

line 1356why, one step back
1356 return this.#responseRequests.get(response) ?? this.#sentRequest;

Various tweaksSindre Sorhusbefore adoption0dd9522

lines 1357–1359why, one step back
1357 }
13581359 #setResponseRequest(response: Response, request: Request): Response {

Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435

line 1360why, one step back
1360 this.#responseRequests.set(response, request);

Various tweaksSindre Sorhusbefore adoption0dd9522

line 1361why, one step back
1361 return response;

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

lines 1362–1366why, one step back
1362 }
13631364 #limitResponseSize(response: Response): Response {1365 const request = this.#getResponseRequest(response);1366 return this.#setResponseRequest(limitResponseSize(response, request, this.#options.maxResponseSize), request);

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

lines 1367–1368why, one step back
1367 }
1368

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1369why, one step back
1369 #wrapRequestWithUploadProgress(request: Request): Request {

Fix retry abort propagation and uploads without request stream supportSindre Sorhusbefore adoption6520f64

line 1370why, one step back
1370 if (!this.#options.onUploadProgress || !supportsRequestStreams || !request.body) {

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

lines 1371–1373why, one step back
1371 return request;
1372 }1373

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1374why, one step back
1374 return streamRequest(request, this.#options.onUploadProgress, this.#options.body);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1375–1376why, one step back
1375 }
1376}