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 fileTake it
1import {HTTPError} from '../errors/HTTPError.js';2import {NetworkError} from '../errors/NetworkError.js';3import {NonError} from '../errors/NonError.js';4import {ForceRetryError} from '../errors/ForceRetryError.js';5import {SchemaValidationError} from '../errors/SchemaValidationError.js';6import {TimeoutError} from '../errors/TimeoutError.js';7import type {8 Input,9 InitOptions,10 InternalOptions,11 NormalizedOptions,12 Options,13 SearchParamsInit,14 SearchParamsOption,15} from '../types/options.js';16import {type ResponsePromise} from '../types/ResponsePromise.js';17import type {StandardSchemaV1} from '../types/standard-schema.js';18import {19 cancelBody,20 limitResponseSize,21 streamRequest,22 streamResponse,23} from '../utils/body.js';24import {25 cloneDeep,26 cloneSearchParameters,27 mergeHeaders,28 mergeHeaderContainers,29 mergeHooks,30 deletedParametersSymbol,31 type MarkedSearchParameters,32} from '../utils/merge.js';33import {normalizeRequestMethod, normalizeRetryMethod, normalizeRetryOptions} from '../utils/normalize.js';34import timeout from '../utils/timeout.js';35import delay from '../utils/delay.js';36import {findUnknownOptions, hasSearchParameters} from '../utils/options.js';37import isRawNetworkError from '../utils/is-network-error.js';38import {39 isError, isNonArrayObject, isNonNegativeNumber, isObject, isRequest, isResponse,40} from '../utils/is.js';41import {42 isHTTPError, isNetworkError, isTimeoutError, isResponseSizeError, isForceRetryError,43} from '../utils/type-guards.js';44import {45 calculateRetryTimingDelay,46 getRetryTimingHeader,47} from './retry-timing.js';48import {49 maxSafeTimeout,50 responseTypes,51 getSupportedResponseTypes,52 stop,53 beforeRetryOptionKeys,54 isRetryMarker,55 supportsAbortController,56 supportsAbortSignal,57 supportsFormData,58 supportsResponseStreams,59 supportsRequestStreams,60} from './constants.js';6162const maxErrorResponseBodySize = 10 * 1024 * 1024;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';64const timedOut = Symbol('timedOut');6566const 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};9596type ErrorDataTimeout = {97 milliseconds: number;98 fromTotalTimeout: boolean;99};100101const 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};112113const 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};196197const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';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`.';200201// 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 }206207 if (!isNonNegativeNumber(value)) {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};216217// 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});219220// 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.221const validateCallbackOptions = (options: Record<string, unknown>): void => {222 for (const key of ['parseJson', 'stringifyJson', 'fetch', 'onDownloadProgress', 'onUploadProgress'] as const) {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};233234const leadingC0ControlOrSpacePattern = /^[\0-\u0020]+/g;235const asciiTabOrNewLinePattern = /[\t\n\r]/g;236const schemePattern = /^[a-z][\d+.a-z-]*:/i;237const malformedHttpProtocolPattern = /^https?:(?!\/\/)/i;238239const isAbsoluteInput = (input: string): boolean =>240 schemePattern.test(input);241242const normalizeInputForProtocolCheck = (input: string): string =>243 input.replaceAll(leadingC0ControlOrSpacePattern, '').replaceAll(asciiTabOrNewLinePattern, '');244245// 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;249 }250251 if (prefix) {252 const normalizedPrefix = prefix.replace(/\/+$/, '');253 const normalizedInput = input.replace(/^\/+/, '');254 input = `${normalizedPrefix}/${normalizedInput}`;255 }256257 if (baseUrl) {258 const normalizedInput = normalizeInputForProtocolCheck(input);259260 if (malformedHttpProtocolPattern.test(normalizedInput)) {261 throw new TypeError('`input` url protocol must be followed by `//` when using `baseUrl`');262 }263264 if (!isAbsoluteInput(normalizedInput)) {265 return new URL(input, (new Request(baseUrl)).url);266 }267 }268269 return input;270};271272// `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};278279// 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];282283 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 }288 }289290 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 }309};310311// 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.312function cloneInitHookOptions(options: Options): InitOptions {313 const clonedOptions: Options = {314 ...options,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 ?? {}),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},319 // Deep-clone so init-hook mutations to nested values do not leak across requests, matching the nested `retry` cloning below.320 json: cloneDeep(options.json),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),324 };325326 return clonedOptions as InitOptions;327}328329const validateJsonWithSchema = async (jsonValue: unknown, schema: StandardSchemaV1): Promise<unknown> => {330 const standardSchema = isObject(schema) || typeof schema === 'function' ? schema['~standard'] : undefined;331332 if (333 !isObject(standardSchema)334 || typeof standardSchema.validate !== 'function'335 ) {336 throw new TypeError(invalidSchemaMessage);337 }338339 const validationResult = await standardSchema.validate(jsonValue);340341 if (validationResult.issues) {342 throw new SchemaValidationError(validationResult.issues);343 }344345 return validationResult.value;346};347348export class Ky {349 static create(input: Input, options: Options): ResponsePromise {350 const initHooks = options.hooks?.init ?? [];351 const initHookOptions = initHooks.length > 0 ? cloneInitHookOptions(options) : options;352353 for (const hook of initHooks) {354 hook(initHookOptions as InitOptions);355 }356357 const ky = new Ky(input, initHookOptions);358359 const result = (async () => {360 let response: Response | undefined;361 try {362 response = await ky.#run();363 return response;364 } catch (error: unknown) {365 return await ky.#throwProcessedError(error);366 } finally {367 const originalRequest = ky.#originalRequest;368369 // Ignore cancellation errors from already-locked or already-consumed streams.370 // A custom fetch or hook can return the request body as its response body; ownership then belongs to the caller.371 cancelBody(originalRequest, response);372373 // 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.374 if (originalRequest && ky.request !== originalRequest) {375 cancelBody(ky.request, response);376 }377 }378 })() as ResponsePromise;379380 // Only expose `.bytes()` when the environment implements it.381 for (const type of getSupportedResponseTypes()) {382 const mimeType = responseTypes[type];383 result[type] = async (schema?: StandardSchemaV1) => {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 }389390 const response = await result;391392 // `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 }396397 if (type !== 'json') {398 return ky.#raceBodyRead(async () => response[type](), response);399 }400401 const text = await ky.#raceBodyRead(async () => response.text(), response) as string;402 const request = ky.#getResponseRequest(response);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 () => {407 const jsonValue = text === '' && schema !== undefined && !ky.#options.parseJson408 ? undefined409 : await ky.#parseJson(text, request, response);410411 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);417 });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) {421 await ky.#throwProcessedError(ky.#userProvidedAbortSignal.reason, request);422 }423424 throw error;425 }426427 if (parsedResult === timedOut) {428 await ky.#throwProcessedError(new TimeoutError(request), request);429 }430431 return parsedResult;432 };433 }434435 return result;436 }437438 public request: Request;439 #abortController?: AbortController;440 #retryCount = 0;441 #retryLimit: number;442 readonly #options: InternalOptions;443 // Keep the input Request alive because Node.js stops forwarding its signal when the Request is garbage-collected.444 readonly #requestInput: Request | undefined;445 #originalRequest?: Request;446 #requestBodyCanBeCancelled = false;447 readonly #userProvidedAbortSignal: AbortSignal | undefined;448 readonly #beforeRetryHookErrors = new WeakSet<Error>();449 #cachedNormalizedOptions: NormalizedOptions | undefined;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>();454 readonly #responseRequests = new WeakMap<Response, Request>();455 readonly #decoratedResponses = new WeakSet<Response>();456457 // eslint-disable-next-line complexity458 constructor(input: Input, options: Options = {}) {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;469 if (Object.hasOwn(options, 'prefixUrl')) {470 throw new Error(prefixUrlRenamedErrorMessage);471 }472473 // 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) {475 if (options[key] === null) {476 throw new TypeError(`The \`${key}\` option must not be \`null\`. Use \`undefined\` to clear it.`);477 }478 }479480 if (options.context !== undefined && !isNonArrayObject(options.context)) {481 throw new TypeError('The `context` option must be an object');482 }483484 this.#options = {485 ...options,486 headers: mergeHeaders((input as Request).headers, options.headers),487 hooks: mergeHooks({}, options.hooks),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,491 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing492 prefix: String(options.prefix || ''),493 retry: normalizeRetryOptions(options.retry),494 ...withAttemptDefaults(options),495 totalTimeout,496 maxResponseSize,497 context: options.context ?? {},498 };499 // Checked here rather than on the way out, because the constructor already calls `stringifyJson`.500 validateCallbackOptions(this.#options);501 validateTimeoutOption(this.#options.timeout, 'timeout');502 validateTimeoutOption(totalTimeout, 'totalTimeout');503 this.#retryLimit = this.#options.retry.limit;504505 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 }508509 this.#requestInput = input instanceof globalThis.Request ? input : undefined;510511 input = resolveInput(input, this.#options.prefix, this.#options.baseUrl);512513 if (supportsAbortController && supportsAbortSignal) {514 this.#userProvidedAbortSignal = this.#options.signal ?? this.#requestInput?.signal;515 this.#abortController = new globalThis.AbortController();516 this.#options.signal = this.#createManagedSignal();517 }518519 if (supportsRequestStreams) {520 // @ts-expect-error - Types are outdated.521 this.#options.duplex = 'half';522 }523524 // A `Request` input's headers are already merged in, so only a content-type from `options.headers` counts as user-provided.525 const userProvidedContentType = options.headers !== undefined && mergeHeaders({}, options.headers).has('content-type');526527 if (this.#options.json !== undefined) {528 this.#options.body = this.#options.stringifyJson?.(this.#options.json) ?? JSON.stringify(this.#options.json);529 if (!userProvidedContentType) {530 this.#options.headers.set('content-type', 'application/json');531 }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 (537 input instanceof globalThis.Request538 && ((supportsFormData && this.#options.body instanceof globalThis.FormData) || this.#options.body instanceof URLSearchParams)539 && !userProvidedContentType540 ) {541 this.#options.headers.delete('content-type');542 }543544 this.request = new globalThis.Request(input, this.#options as RequestInit);545 this.#requestBodyCanBeCancelled = typeof globalThis.ReadableStream === 'function' && this.#options.body instanceof globalThis.ReadableStream;546547 const {searchParams} = this.#options;548 if (hasSearchParameters(searchParams)) {549 const url = new URL(this.request.url);550 applySearchParameters(url, searchParams);551552 // Recreate request with the updated URL. We already have all options in this.#options, including duplex.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 }583 }584585 // `totalTimeout` starts when the request pipeline is created, so it also includes586 // Ky's internal scheduling and user hook time before the first fetch attempt.587 this.#deadline = typeof totalTimeout === 'number' ? getCurrentTime() + totalTimeout : Number.POSITIVE_INFINITY;588 }589590 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 }664665 #calculateDelay(retry: InternalOptions['retry'], error: unknown): number {666 const retryDelay = retry.delay(this.#retryCount + 1);667668 // 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.669 if (!isNonNegativeNumber(retryDelay)) {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 }673674 let jitteredDelay = retryDelay;675 if (retry.jitter === true) {676 jitteredDelay = Math.random() * retryDelay;677 } else if (typeof retry.jitter === 'function') {678 jitteredDelay = retry.jitter(retryDelay);679680 if (!Number.isFinite(jitteredDelay) || jitteredDelay < 0) {681 jitteredDelay = retryDelay;682 }683 }684685 return Math.min(retry.backoffLimit, jitteredDelay);686 }687688 async #calculateRetryDelay(error: unknown) {689 const retry = normalizeRetryOptions(this.#options.retry);690 if (this.#retryCount >= Math.min(retry.limit, this.#retryLimit)) {691 throw error;692 }693694 // 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);696697 // Handle forced retry from afterResponse hook - skip method check and shouldRetry698 if (isForceRetryError(errorObject)) {699 return errorObject.customDelay ?? this.#calculateDelay(retry, error);700 }701702 // Check if method is retriable for non-forced retries703 if (!retry.methods.includes(normalizeRetryMethod(this.request.method))) {704 throw error;705 }706707 let shouldRetryOverride = false;708 const {shouldRetry} = retry;709 if (shouldRetry !== undefined) {710 const result = await this.#raceWithTotalTimeout(async () => shouldRetry({error: errorObject, retryCount: this.#retryCount + 1}));711 this.#throwIfAbortedByUser();712 if (result === timedOut) {713 throw new TimeoutError(this.#sentRequest);714 }715716 // Only exact booleans override the default retry checks.717 if (result === false) {718 throw error;719 }720721 shouldRetryOverride = result === true;722 }723724 // Default timeout behavior725 if (isTimeoutError(error)) {726 if (!shouldRetryOverride && !retry.retryOnTimeout) {727 throw error;728 }729730 return this.#calculateDelay(retry, error);731 }732733 if (isHTTPError(error)) {734 if (!shouldRetryOverride && !retry.statusCodes.includes(error.response.status)) {735 throw error;736 }737738 const retryTimingHeader = getRetryTimingHeader(error.response.headers);739 if (retryTimingHeader && retry.afterStatusCodes.includes(error.response.status)) {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.743 return this.#calculateDelay(retry, error);744 }745746 // Don't apply jitter when server provides explicit retry timing747 return Math.min(retry.maxRetryAfter, after);748 }749750 if (!shouldRetryOverride && error.response.status === 413) {751 throw error;752 }753754 return this.#calculateDelay(retry, error);755 }756757 // Only retry known retriable error types. Unknown errors (e.g., programming bugs) are not retried.758 if (!shouldRetryOverride && !isNetworkError(error)) {759 throw error;760 }761762 return this.#calculateDelay(retry, error);763 }764765 #decorateResponse(response: Response): Response {766 if (!this.#options.parseJson || this.#decoratedResponses.has(response)) {767 return response;768 }769770 this.#decoratedResponses.add(response);771 const request = this.#getResponseRequest(response);772773 response.json = async () => this.#parseJson(await response.text(), request, response);774775 // `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));778779 return response;780 }781782 // 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)) {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) {796 // `options` intentionally remains the stable normalized Ky options snapshot for the same reason as `HTTPError` above.797 // eslint-disable-next-line no-await-in-loop798 const hookResult: unknown = await hook({799 request,800 options: this.#getNormalizedOptions(),801 error: processedError,802 retryCount: this.#retryCount,803 });804805 // Only overwrite if the hook returns a valid Error, including one from another realm.806 if (isError(hookResult)) {807 processedError = hookResult;808 }809 }810811 throw processedError;812 }813814 async #getResponseData(response: Response): Promise<unknown> {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);817818 // 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) {821 throw new TimeoutError(request);822 }823824 this.#throwIfTotalTimeoutExhausted(request);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);833 return undefined;834 }835836 if (!text) {837 return undefined;838 }839840 if (!isJsonContentType(response.headers.get('content-type') ?? '')) {841 return text;842 }843844 const parseTimeout = this.#getErrorDataTimeout(request);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);849 return undefined;850 }851852 return data;853 }854855 #getErrorDataTimeout(request: Request): ErrorDataTimeout {856 const errorDataTimeout = this.#options.timeout === false ? 10_000 : this.#options.timeout;857 const remainingTotal = this.#getRemainingTotalTimeout();858 if (remainingTotal === 0) {859 throw new TimeoutError(request);860 }861862 return {863 milliseconds: Math.min(errorDataTimeout, remainingTotal),864 fromTotalTimeout: remainingTotal <= errorDataTimeout,865 };866 }867868 // The smaller of `timeout` and the `totalTimeout` budget left, or `undefined` when neither applies, since `setTimeout()` cannot wait forever.869 #getEffectiveTimeout(): number | undefined {870 const remainingTotal = this.#getRemainingTotalTimeout();871 if (remainingTotal === 0) {872 throw new TimeoutError(this.#sentRequest);873 }874875 const effectiveTimeout = Math.min(this.#options.timeout === false ? Number.POSITIVE_INFINITY : this.#options.timeout, remainingTotal);876 return effectiveTimeout === Number.POSITIVE_INFINITY ? undefined : effectiveTimeout;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> {882 const failedRequest = this.#getResponseRequest(response);883 let timeoutMilliseconds: number | undefined;884 try {885 timeoutMilliseconds = this.#getEffectiveTimeout();886 } catch (error: unknown) {887 await this.#throwProcessedError(error, failedRequest);888 }889890 const bodyPromise = createBodyPromise();891892 let result: unknown;893 try {894 result = timeoutMilliseconds === undefined895 ? await bodyPromise896 : await raceWithTimeout(bodyPromise, timeoutMilliseconds);897 } catch (error: unknown) {898 if (this.#userProvidedAbortSignal?.aborted) {899 await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);900 }901902 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)) {906 await this.#throwProcessedError(new NetworkError(failedRequest, {cause: error as Error}), failedRequest);907 }908909 await this.#throwProcessedError(error, failedRequest);910 }911912 result = timedOut;913 }914915 // 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 }919920 if (result === timedOut || this.#getRemainingTotalTimeout() === 0) {921 // The stream is locked by the native body method's own reader by this point, so922 // `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();925 await this.#throwProcessedError(new TimeoutError(failedRequest), failedRequest);926 }927928 return result;929 }930931 async #raceWithTotalTimeout<T>(operation: () => Promise<T>): Promise<T | typeof timedOut> {932 const abortSignal = this.#userProvidedAbortSignal;933 abortSignal?.throwIfAborted();934935 const remainingTotal = this.#getRemainingTotalTimeout();936 if (remainingTotal === 0) {937 this.#abortController?.abort();938 return timedOut;939 }940941 let timeoutId: ReturnType<typeof setTimeout> | undefined;942 let abortListener: (() => void) | undefined;943 let operationPromise: Promise<T> | undefined;944 try {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 };954955 // The signal was checked above, and nothing ran since, so it cannot have aborted before the listener is added.956 abortSignal.addEventListener('abort', abortListener, {once: true});957 });958 operationPromise = operation();959960 if (remainingTotal === Number.POSITIVE_INFINITY) {961 return await Promise.race([operationPromise, abortPromise]);962 }963964 const timeoutPromise = new Promise<typeof timedOut>(resolve => {965 timeoutId = setTimeout(() => {966 resolve(timedOut);967 }, remainingTotal);968 });969 const result = await Promise.race([operationPromise, timeoutPromise, abortPromise]);970 if (result === timedOut || this.#getRemainingTotalTimeout() === 0) {971 this.#abortController?.abort();972973 if (result === timedOut) {974 releaseWhenSettled(operationPromise);975 } else {976 cancelReturnedBody(result);977 }978979 return timedOut;980 }981982 return result;983 } catch (error: unknown) {984 if (abortSignal?.aborted) {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.986 if (operationPromise) {987 releaseWhenSettled(operationPromise);988 }989990 abortSignal.throwIfAborted();991 }992993 if (this.#getRemainingTotalTimeout() === 0) {994 this.#abortController?.abort();995 return timedOut;996 }997998 throw error;999 } finally {1000 clearTimeout(timeoutId);1001 if (abortListener) {1002 abortSignal?.removeEventListener('abort', abortListener);1003 }1004 }1005 }10061007 // 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);1011 }10121013 #createManagedSignal(): AbortSignal {1014 return this.#userProvidedAbortSignal1015 ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController!.signal])1016 : this.#abortController!.signal;1017 }10181019 // 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) {1025 cancelBody(response);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 {1036 if (this.#getRemainingTotalTimeout() === 0) {1037 throw new TimeoutError(request);1038 }1039 }10401041 async #runBeforeRequestHooks(): Promise<Response | undefined> {1042 for (const hook of this.#options.hooks.beforeRequest) {1043 // eslint-disable-next-line no-await-in-loop1044 const result = await this.#raceWithTotalTimeout(async () => hook({1045 request: this.request,1046 options: this.#getNormalizedOptions(),1047 retryCount: 0,1048 }));10491050 if (result === timedOut) {1051 throw new TimeoutError(this.#sentRequest);1052 }10531054 if (isRequest(result)) {1055 this.#assignRequest(this.#withManagedSignal(result));1056 } else if (isResponse(result)) {1057 this.#hookResponses.add(result);1058 return result;1059 }1060 }10611062 return undefined;1063 }10641065 async #runAfterResponseHooks(response: Response): Promise<Response> {1066 const responseRequest = this.#getResponseRequest(response);1067 response = this.#limitResponseSize(response);10681069 for (const hook of this.#options.hooks.afterResponse) {1070 const hookResponse = this.#setResponseRequest(response.clone(), responseRequest);1071 this.#decorateResponse(hookResponse);10721073 let modifiedResponse;1074 try {1075 // eslint-disable-next-line no-await-in-loop1076 modifiedResponse = await this.#raceWithTotalTimeout(async () => hook({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.1078 request: this.request,1079 options: this.#getNormalizedOptions(),1080 response: hookResponse,1081 retryCount: this.#retryCount,1082 }));10831084 if (modifiedResponse === timedOut) {1085 throw new TimeoutError(this.#sentRequest);1086 }10871088 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);1096 throw error;1097 }10981099 const nextResponse = isResponse(modifiedResponse)1100 ? this.#setResponseRequest(modifiedResponse, responseRequest)1101 : response;11021103 // 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.1105 // If the hook wrapped an existing body into a new Response, both Response objects can still point at the same stream.1106 cancelBody(hookResponse, nextResponse);1107 cancelBody(response, nextResponse);11081109 if (nextResponse !== response) {1110 response = this.#limitResponseSize(nextResponse);1111 }1112 }11131114 return response;1115 }11161117 async #retry(): Promise<Response | void> {1118 try {1119 return await this.#fetch();1120 } catch (error) {1121 return this.#retryFromError(error);1122 }1123 }11241125 async #retryFromError(error: unknown): Promise<Response | void> {1126 this.#throwIfAbortedByUser();11271128 const retryDelay = Math.min(await this.#calculateRetryDelay(error), maxSafeTimeout);1129 const delayOptions = {signal: this.#userProvidedAbortSignal};11301131 const remainingTimeout = this.#getRemainingTotalTimeout();1132 if (remainingTimeout === 0) {1133 throw new TimeoutError(this.#sentRequest);1134 }11351136 // 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);1140 }11411142 // Only use user-provided signal for delay, not our internal abortController1143 await delay(retryDelay, delayOptions);11441145 this.#throwIfTotalTimeoutExhausted();11461147 // Reset abortController if it was aborted (happens on timeout retry) so hooks and the retried request get a fresh signal1148 if (this.#abortController?.signal.aborted) {1149 this.#abortController = new globalThis.AbortController();1150 this.#options.signal = this.#createManagedSignal();1151 this.#assignRequest(this.#withManagedSignal(this.request), this.#requestBodyCanBeCancelled);1152 }11531154 // Apply custom request from forced retry before beforeRetry hooks1155 // Ensure the custom request has the correct managed signal for timeouts and user aborts1156 if (isForceRetryError(error) && error.customRequest) {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.1160 this.#assignRequest(this.#withManagedSignal(error.customRequest));1161 }11621163 for (const hook of this.#options.hooks.beforeRetry) {1164 let hookResult: Awaited<ReturnType<typeof hook>> | typeof timedOut;1165 try {1166 // eslint-disable-next-line no-await-in-loop1167 hookResult = await this.#raceWithTotalTimeout(async () => hook({1168 request: this.request,1169 options: this.#getNormalizedOptions(),1170 error: NonError.wrap(error),1171 retryCount: this.#retryCount + 1,1172 }));1173 } catch (hookError) {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.1178 if (isError(hookError) && hookError !== error) {1179 this.#beforeRetryHookErrors.add(hookError);1180 }11811182 throw hookError;1183 }11841185 if (hookResult === timedOut) {1186 throw new TimeoutError(this.#sentRequest);1187 }11881189 if (isRequest(hookResult)) {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.1192 this.#assignRequest(this.#withManagedSignal(hookResult));1193 break;1194 }11951196 if (isResponse(hookResult)) {1197 this.#hookResponses.add(hookResult);1198 this.#retryCount++;1199 return hookResult;1200 }12011202 // If `stop` is returned from the hook, the retry process is stopped1203 if (hookResult === stop) {1204 return;1205 }12061207 if (isNonArrayObject(hookResult)) {1208 this.#applyBeforeRetryOptions(hookResult.options);1209 }1210 }12111212 this.#throwIfTotalTimeoutExhausted();12131214 this.#retryCount++;1215 return this.#retry();1216 }12171218 async #fetch(): Promise<Response> {1219 // A previous attempt can return without consuming its upload. Release that unused branch before replacing the request reference.1220 cancelBody(this.#originalRequest, this.request);12211222 const nonRequestOptions = findUnknownOptions(this.#options);1223 this.#retryLimit = normalizeRetryOptions(this.#options.retry).limit;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;1226 const request = this.#wrapRequestWithUploadProgress(this.request);12271228 // Cloning is done here to prepare in advance for retries.1229 // Skip cloning when retries are disabled - cloning a streaming body calls ReadableStream#tee()1230 // which buffers the entire stream in memory, causing excessive memory usage for large uploads.1231 this.#originalRequest = request;1232 if (retryRequest) {1233 this.request = retryRequest;1234 this.#requestBodyCanBeCancelled = true;1235 }12361237 try {1238 const effectiveTimeout = this.#getEffectiveTimeout();12391240 // 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;1242 const response = effectiveTimeout === undefined1243 ? await fetch(request, nonRequestOptions)1244 : await timeout(request, nonRequestOptions, this.#abortController, {1245 timeout: effectiveTimeout,1246 fetch,1247 });12481249 // `undefined` would otherwise look like `ky.stop`, and any other value fails later with an error that does not name the cause.1250 if (!isResponse(response)) {1251 throw new TypeError('The `fetch` option must resolve with a `Response`');1252 }12531254 if (this.#getRemainingTotalTimeout() === 0) {1255 this.#abortController?.abort();1256 cancelBody(response);1257 throw new TimeoutError(request);1258 }12591260 return this.#setResponseRequest(response, request);1261 } catch (error) {1262 this.#throwIfAbortedByUser();1263 if (this.#getRemainingTotalTimeout() === 0) {1264 this.#abortController?.abort();1265 throw new TimeoutError(request);1266 }12671268 if (isRawNetworkError(error)) {1269 throw new NetworkError(request, {cause: error as Error});1270 }12711272 throw error;1273 }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();1279 }12801281 // `0` once the `totalTimeout` budget is spent, and `Infinity` without a `totalTimeout`.1282 #getRemainingTotalTimeout(): number {1283 return Math.max(0, this.#deadline - getCurrentTime());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;1305 }13061307 #getNormalizedOptions(): NormalizedOptions {1308 if (!this.#cachedNormalizedOptions) {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,1317 totalTimeout,1318 maxResponseSize,1319 throwHttpErrors,1320 fetch,1321 ...normalizedOptions1322 } = this.#options;13231324 this.#cachedNormalizedOptions = Object.freeze(normalizedOptions) as NormalizedOptions;1325 }13261327 return this.#cachedNormalizedOptions;1328 }13291330 #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.1332 if (this.#requestBodyCanBeCancelled) {1333 cancelBody(this.request, request);1334 }13351336 this.#cachedNormalizedOptions = undefined;1337 this.request = request;1338 this.#requestBodyCanBeCancelled = requestBodyCanBeCancelled;1339 }13401341 // 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.1342 #withManagedSignal(request: Request): Request {1343 if (!this.#options.signal || !(request instanceof globalThis.Request)) {1344 return request;1345 }13461347 return new globalThis.Request(request, {1348 signal: this.#options.signal,1349 referrer: request.referrer,1350 referrerPolicy: request.referrerPolicy,1351 });1352 }13531354 // 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.1355 #getResponseRequest(response: Response): Request {1356 return this.#responseRequests.get(response) ?? this.#sentRequest;1357 }13581359 #setResponseRequest(response: Response, request: Request): Response {1360 this.#responseRequests.set(response, request);1361 return response;1362 }13631364 #limitResponseSize(response: Response): Response {1365 const request = this.#getResponseRequest(response);1366 return this.#setResponseRequest(limitResponseSize(response, request, this.#options.maxResponseSize), request);1367 }13681369 #wrapRequestWithUploadProgress(request: Request): Request {1370 if (!this.#options.onUploadProgress || !supportsRequestStreams || !request.body) {1371 return request;1372 }13731374 return streamRequest(request, this.#options.onUploadProgress, this.#options.body);1375 }1376}