Tweaks
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 692c435 · Browse files · 24 files·+799 added−777 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
24 files+799 added−777 removed
- tests:+470 added−592 removed
- other:+329 added−185 removed
Provenance
- Commit
3ded2aa- Tree
403e57c- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
692c435
24 files changed+799 added−777 removed
modified:source/core/Ky.ts+210 added-130 removed
6 unmodified lines7 import type {8 Input,9 InitOptions,10 InternalOptions,11- KyHeadersInit,11 NormalizedOptions,12 Options,13 SearchParamsInit,14 SearchParamsOption,20 unmodified lines35 import delay from '../utils/delay.js';36 import {type ObjectEntries} from '../utils/types.js';37 import {findUnknownOptions, hasSearchParameters} from '../utils/options.js';38 import isRawNetworkError from '../utils/is-network-error.js';39+import {isError, isObject} from '../utils/is.js';40 import {41- isHTTPError, isNetworkError, isTimeoutError, isResponseSizeError,41+ isHTTPError, isNetworkError, isTimeoutError, isResponseSizeError, isForceRetryError,42 } from '../utils/type-guards.js';43 import {44 calculateRetryTimingDelay,45 getRetryTimingHeader,1 unmodified line47 import {48 maxSafeTimeout,49 responseTypes,50 stop,51- RetryMarker,51+ isRetryMarker,52 supportsAbortController,53 supportsAbortSignal,54 supportsFormData,55 supportsResponseStreams,22 unmodified lines78 return new TextDecoder();79 };80 81 const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';82+const missingResponseMessage = 'The request resolved without a response, so there is no body to read.'83+ + ' This happens when a `beforeRetry` hook returns `ky.stop`. Throw from the hook instead of returning `ky.stop`.';84 85+// 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.86+const validateTimeoutOption = (value: unknown, name: 'timeout' | 'totalTimeout'): void => {87+ if (value === false) {88+ return;89+ }90+91+ if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {92+ throw new TypeError(`The \`${name}\` option must be a non-negative number or \`false\``);93+ }94+95+ // `Infinity` lands here too, since it is not a usable delay either.96+ if (value > maxSafeTimeout) {97+ throw new RangeError(`The \`${name}\` option cannot be greater than ${maxSafeTimeout}`);98+ }99+};100+101+// These callbacks are called directly, so a non-function value otherwise surfaces as a runtime error naming Ky's102+// own internals rather than the option the caller set.103+const validateCallbackOptions = (options: Record<string, unknown>): void => {104+ for (const key of ['parseJson', 'stringifyJson', 'fetch', 'onDownloadProgress'] as const) {105+ if (options[key] !== undefined && typeof options[key] !== 'function') {106+ throw new TypeError(`The \`${key}\` option must be a function`);107+ }108+ }109+110+ const {throwHttpErrors} = options;111+ if (typeof throwHttpErrors !== 'boolean' && typeof throwHttpErrors !== 'function') {112+ throw new TypeError('The `throwHttpErrors` option must be a boolean or a function');113+ }114+};115+116 const cloneRetryOptions = (retry: RetryOptions | number): RetryOptions | number => {117 if (retry === null || typeof retry !== 'object' || Array.isArray(retry)) {118 return retry as RetryOptions | number;119 }44 unmodified lines164 165 return cloneShallow(searchParameters) as SearchParamsOption | undefined;166 };167 135-// Shallow-clone mutable option properties so init hook mutations don't leak across requests.168+// 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.169 function cloneInitHookOptions(options: Options): InitOptions {137- let headers = mergeHeaderContainers({}, options.headers ?? {});138- let context = cloneDeep(options.context) ?? {};170 const clonedOptions: Options = {171 ...options,172+ // `headers` starts as a plain object with lowercase names in `init` hooks, so hooks can add headers in place even when none were provided.173+ headers: mergeHeaderContainers({}, options.headers ?? {}),174+ // `context` starts as an object in `init` hooks, the same as in every other hook.175+ context: cloneDeep(options.context) ?? {},141- // Deep-clone so init-hook mutations to nested values do not leak across requests, matching the nested `retry` cloning below. Non-plain values (functions, class instances) are kept by reference.176+ // Deep-clone so init-hook mutations to nested values do not leak across requests, matching the nested `retry` cloning below.177 json: cloneDeep(options.json),178 searchParams: cloneSearchParametersForInitHook(options.searchParams),179 };180 146- Object.defineProperties(clonedOptions, {147- headers: {148- enumerable: true,149- configurable: true,150- get() {151- return headers;152- },153- set(value: KyHeadersInit | undefined) {154- headers = mergeHeaderContainers({}, value ?? {});155- },156- },157- context: {158- enumerable: true,159- configurable: true,160- get() {161- return context;162- },163- set(value: Record<string, unknown> | undefined) {164- context = value ?? {};165- },166- },167- });168-181 if (options.retry !== undefined) {182 clonedOptions.retry = cloneRetryOptions(options.retry);183 }184 41 unmodified lines226 227 const ky = new Ky(input, initHookOptions);228 229 const function_ = async (): Promise<Response | void> => {218- if (typeof ky.#options.timeout === 'number' && ky.#options.timeout > maxSafeTimeout) {219- throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);220- }221-222- if (typeof ky.#options.totalTimeout === 'number' && ky.#options.totalTimeout > maxSafeTimeout) {223- throw new RangeError(`The \`totalTimeout\` option cannot be greater than ${maxSafeTimeout}`);224- }225-230 // Delay the fetch so that body method shortcuts can set the Accept header231 await Promise.resolve();232 const beforeRequestResponse = await ky.#runBeforeRequestHooks();233 if (beforeRequestResponse !== undefined) {4 unmodified lines238 let responseFromHook = beforeRequestResponse !== undefined239 || ky.#consumeReturnedResponseFromBeforeRetryHook();240 241 for (;;) {238- // `undefined` means a hook stopped the flow without providing a response.239- // Non-native Responses still continue through Ky if they pass `isResponseInstance()`.242+ // `undefined` means a hook stopped the flow.243 if (response === undefined) {244 return response;245 }246 244- if (isResponseInstance(response)) {245- try {246- // eslint-disable-next-line no-await-in-loop247- response = await ky.#runAfterResponseHooks(response);248- } catch (error) {249- if (!(error instanceof ForceRetryError)) {250- throw error;251- }247+ try {248+ // eslint-disable-next-line no-await-in-loop249+ response = await ky.#runAfterResponseHooks(response);250+ } catch (error) {251+ if (!isForceRetryError(error)) {252+ throw error;253+ }254 253- // eslint-disable-next-line no-await-in-loop254- const retriedResponse: Response | void = await ky.#retryFromError(error);255- if (retriedResponse === undefined) {256- return retriedResponse;257- }258-259- response = retriedResponse;260- responseFromHook = ky.#consumeReturnedResponseFromBeforeRetryHook();261- continue;255+ // eslint-disable-next-line no-await-in-loop256+ const retriedResponse: Response | void = await ky.#retryFromError(error);257+ if (retriedResponse === undefined) {258+ return retriedResponse;259 }260+261+ response = retriedResponse;262+ responseFromHook = ky.#consumeReturnedResponseFromBeforeRetryHook();263+ continue;264 }265 266 const currentResponse: Response = response;267 268 // 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.268- if (!currentResponse.ok && currentResponse.type !== 'opaque' && (269- typeof ky.#options.throwHttpErrors === 'function'270- ? ky.#options.throwHttpErrors(currentResponse.status)271- : ky.#options.throwHttpErrors272- )) {269+ if (!currentResponse.ok && currentResponse.type !== 'opaque' && ky.#shouldThrowHttpErrors(currentResponse)) {270 // `request` must reflect the request that actually failed, but `options` stays as Ky's271 // normalized options snapshot. Replacement `Request` instances do not preserve the272 // original `BodyInit`, so trying to make `options` mirror arbitrary requests would be lossy.273 const httpError: HTTPError = new HTTPError(currentResponse, ky.#getResponseRequest(currentResponse), ky.#getNormalizedOptions());19 unmodified lines293 294 break;295 }296 300- if (!isResponseInstance(response)) {301- return response;302- }303-297 ky.#decorateResponse(response);298 299 // If `onDownloadProgress` is passed, it uses the stream API internally300 if (ky.#options.onDownloadProgress) {308- if (typeof ky.#options.onDownloadProgress !== 'function') {309- throw new TypeError('The `onDownloadProgress` option must be a function');310- }311-301 if (!supportsResponseStreams) {302 throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');303 }304 20 unmodified lines325 if (originalRequest?.body !== response?.body) {326 ky.#cancelBody(originalRequest?.body ?? undefined);327 }328 340- // Only cancel the current request body if it's distinct from the original (i.e. it was cloned for retries).341- if (ky.request !== originalRequest && ky.request.body !== response?.body) {329+ // 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.330+ if (originalRequest && ky.request !== originalRequest && ky.request.body !== response?.body) {331 ky.#cancelBody(ky.request.body ?? undefined);332 }333 }334 })() as ResponsePromise;7 unmodified lines342 continue;343 }344 345 result[type] = async (schema?: StandardSchemaV1) => {346+ // 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.347+ if (ky.request !== ky.#originalRequest) {357- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing358- ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);348+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing349+ ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);350+ }351 352 const response = await result;353 354+ // `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.355+ if (response === undefined) {356+ throw new TypeError(missingResponseMessage);357+ }358+359 if (type !== 'json') {360 return ky.#raceBodyRead(async () => response[type](), response);361 }362 18 unmodified lines381 }, ky.#userProvidedAbortSignal);382 } catch (error: unknown) {383 // 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.384 if (ky.#userProvidedAbortSignal?.aborted) {388- await ky.#throwProcessedError(ky.#userProvidedAbortSignal.reason);385+ await ky.#throwProcessedError(ky.#userProvidedAbortSignal.reason, request);386 }387 388 throw error;389 }390 391 if (parsedResult === timedOutOperation) {395- await ky.#throwProcessedError(new TimeoutError(request));392+ await ky.#throwProcessedError(new TimeoutError(request), request);393 }394 395 return parsedResult;396 };22 unmodified lines419 #originalRequest?: Request;420 #requestBodyCanBeCancelled = false;421 readonly #userProvidedAbortSignal: AbortSignal | undefined;422 readonly #beforeRetryHookErrors = new WeakSet<Error>();423+ // Values thrown by a user callback that runs while the request is in flight. Retrying would re-send the body and run the callback again, so they are never retriable, whatever `shouldRetry` says. A strong `Set` is safe because a `Ky` instance lives for exactly one request, and the callback can throw a non-`Error` value.424+ readonly #inFlightCallbackErrors = new Set<unknown>();425 #cachedNormalizedOptions: NormalizedOptions | undefined;426 readonly #startTime: number | undefined;427 #returnedResponseFromBeforeRetryHook = false;428 readonly #responseRequests = new WeakMap<Response, Request>();429 readonly #decoratedResponses = new WeakSet<Response>();430 431 // eslint-disable-next-line complexity432 constructor(input: Input, options: Options = {}) {434- const {maxResponseSize = Number.POSITIVE_INFINITY} = options;433+ // Checked before the options are built, since building them reads `input.headers`.434+ if (typeof input !== 'string' && !(input instanceof URL || input instanceof globalThis.Request)) {435+ throw new TypeError('`input` must be a string, URL, or Request');436+ }437+438+ // Defaults only replace `undefined`, so a `null` reaches the validation below and is reported instead of silently becoming the default.439+ const {440+ maxResponseSize = Number.POSITIVE_INFINITY,441+ throwHttpErrors = true,442+ timeout = 10_000,443+ totalTimeout = false,444+ fetch = globalThis.fetch.bind(globalThis),445+ } = options;446 if (Object.hasOwn(options, 'prefixUrl')) {447 throw new Error(prefixUrlRenamedErrorMessage);448 }449 450+ // 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` or no prefix.451+ for (const key of ['headers', 'method', 'prefix', 'baseUrl'] as const) {452+ if (options[key] === null) {453+ throw new TypeError(`The \`${key}\` option must not be \`null\`. Use \`undefined\` to clear it.`);454+ }455+ }456+457+ if (options.context !== undefined && (!isObject(options.context) || Array.isArray(options.context))) {458+ throw new TypeError('The `context` option must be an object');459+ }460+461 this.#options = {462 ...options,463 headers: mergeHeaders((input as Request).headers, options.headers),464 hooks: mergeHooks({}, options.hooks),2 unmodified lines467 referrerPolicy: options.referrerPolicy ?? (input as Request).referrerPolicy,468 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing469 prefix: String(options.prefix || ''),470 retry: normalizeRetryOptions(options.retry),449- throwHttpErrors: options.throwHttpErrors ?? true,450- timeout: options.timeout ?? 10_000,451- totalTimeout: options.totalTimeout ?? false,471+ throwHttpErrors,472+ timeout,473+ totalTimeout,474 maxResponseSize,453- fetch: options.fetch ?? globalThis.fetch.bind(globalThis),454- // Deep-cloned so a hook mutating a nested plain object or array cannot write back to the instance defaults or the caller's object. Non-plain values such as class instances are kept by reference, matching how `json` and the shallow `context` merge treat them.455- context: cloneDeep(options.context) ?? {},475+ fetch,476+ context: options.context ?? {},477 };478+ // Checked here rather than on the way out, because the constructor already calls `stringifyJson`.479+ validateCallbackOptions(this.#options);480+ validateTimeoutOption(timeout, 'timeout');481+ validateTimeoutOption(totalTimeout, 'totalTimeout');482 this.#retryLimit = this.#options.retry.limit;483 484 if (maxResponseSize !== Number.POSITIVE_INFINITY && (!Number.isSafeInteger(maxResponseSize) || maxResponseSize < 0)) {485 throw new TypeError('The `maxResponseSize` option must be a non-negative safe integer or Infinity');486 }487 463- if (typeof input !== 'string' && !(input instanceof URL || input instanceof globalThis.Request)) {464- throw new TypeError('`input` must be a string, URL, or Request');465- }466-488 this.#requestInput = input instanceof globalThis.Request ? input : undefined;489 490 if (typeof input === 'string') {491 if (this.#options.prefix) {127 unmodified lines619 // Ky's internal scheduling and user hook time before the first fetch attempt.620 this.#startTime = typeof this.#options.totalTimeout === 'number' ? this.#getCurrentTime() : undefined;621 }622 602- #calculateDelay(retry: InternalOptions['retry']): number {623+ #calculateDelay(retry: InternalOptions['retry'], error: unknown): number {624 const retryDelay = retry.delay(this.#retryCount + 1);625 626+ // 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.627+ if (typeof retryDelay !== 'number' || Number.isNaN(retryDelay) || retryDelay < 0) {628+ // 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.629+ throw new TypeError('`retry.delay` must return a non-negative number or `Infinity`', {cause: error});630+ }631+632 let jitteredDelay = retryDelay;633 if (retry.jitter === true) {634 jitteredDelay = Math.random() * retryDelay;635 } else if (typeof retry.jitter === 'function') {7 unmodified lines643 return Math.min(retry.backoffLimit, jitteredDelay);644 }645 646 async #calculateRetryDelay(error: unknown) {647+ if (this.#inFlightCallbackErrors.has(error)) {648+ throw error;649+ }650+651 const retry = normalizeRetryOptions(this.#options.retry);652 if (this.#retryCount >= Math.min(retry.limit, this.#retryLimit)) {653 throw error;654 }1 unmodified line656 // Wrap non-Error throws to ensure consistent error handling657 const errorObject = error instanceof Error ? error : new NonError(error);658 659 // Handle forced retry from afterResponse hook - skip method check and shouldRetry629- if (errorObject instanceof ForceRetryError) {630- return errorObject.customDelay ?? this.#calculateDelay(retry);660+ if (isForceRetryError(errorObject)) {661+ return errorObject.customDelay ?? this.#calculateDelay(retry, error);662 }663 664 // Check if method is retriable for non-forced retries665 if (!retry.methods.includes(normalizeRetryMethod(this.request.method))) {5 unmodified lines671 if (shouldRetry !== undefined) {672 const result = await this.#raceWithTotalTimeout(async () => shouldRetry({error: errorObject, retryCount: this.#retryCount + 1}), this.#userProvidedAbortSignal);673 this.#throwIfAbortedByUser();674 if (result === timedOutOperation) {644- throw new TimeoutError(this.request);675+ throw new TimeoutError(this.#sentRequest);676 }677 678 // Only exact booleans override the default retry checks.679 if (result === false) {8 unmodified lines688 if (!shouldRetryOverride && !retry.retryOnTimeout) {689 throw error;690 }691 661- return this.#calculateDelay(retry);692+ return this.#calculateDelay(retry, error);693 }694 695+ // The `isHTTPError()` brand only checks `name`, so a cross-realm error may not carry a `response`.664- if (isHTTPError(error)) {696+ if (isHTTPError(error) && error.response) {697 if (!shouldRetryOverride && !retry.statusCodes.includes(error.response.status)) {698 throw error;699 }700 1 unmodified line702 if (retryTimingHeader && retry.afterStatusCodes.includes(error.response.status)) {703 const after = calculateRetryTimingDelay(retryTimingHeader);704 if (after === undefined) {705 // Malformed retry timing headers should not disable retries; they only lose their server-provided timing.674- return this.#calculateDelay(retry);706+ return this.#calculateDelay(retry, error);707 }708 709 // Don't apply jitter when server provides explicit retry timing710 return Math.min(retry.maxRetryAfter, after);2 unmodified lines713 if (!shouldRetryOverride && error.response.status === 413) {714 throw error;715 }716 685- return this.#calculateDelay(retry);717+ return this.#calculateDelay(retry, error);718 }719 720 // Only retry known retriable error types. Unknown errors (e.g., programming bugs) are not retried.721 if (!shouldRetryOverride && !isNetworkError(error)) {722 throw error;723 }724 693- return this.#calculateDelay(retry);725+ return this.#calculateDelay(retry, error);726 }727 728 #decorateResponse(response: Response): Response {729 if (!this.#options.parseJson || this.#decoratedResponses.has(response)) {2 unmodified lines732 733 this.#decoratedResponses.add(response);734 const request = this.#getResponseRequest(response);735 736+ try {704- response.json = async () => {705- const text = await response.text();706- return this.#options.parseJson!(text, {request, response});707- };737+ response.json = async () => {738+ const text = await response.text();739+ return this.#options.parseJson!(text, {request, response});740+ };741 709- // `clone()` returns a fresh `Response` that would otherwise fall back to the native `json()`.710- const nativeClone = response.clone.bind(response);711- response.clone = () => this.#decorateResponse(this.#setResponseRequest(nativeClone(), request));742+ // `clone()` returns a fresh `Response` that would otherwise fall back to the native `json()`.743+ const nativeClone = response.clone.bind(response);744+ response.clone = () => this.#decorateResponse(this.#setResponseRequest(nativeClone(), request));745+ } catch (error: unknown) {746+ // A frozen response cannot be decorated, so the caller never receives it and nothing else can release its body. Report the real problem and let go of the connection.747+ this.#cancelResponseBody(response);748+ throw error;749+ }750 751 return response;752 }753 716- async #throwProcessedError(error: unknown): Promise<never> {717- // Non-Error throws (e.g., thrown strings) pass through unchanged718- if (!(error instanceof Error)) {754+ // 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.755+ async #throwProcessedError(error: unknown, request: Request = this.#sentRequest): Promise<never> {756+ // 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.757+ if (!isError(error)) {758 throw error;759 }760 761 // Errors thrown by beforeRetry hooks must propagate unchanged.2 unmodified lines764 }765 766 let processedError: Error = error;767 for (const hook of this.#options.hooks.beforeError) {729- // `request` is the current failing request. `options` intentionally remains the730- // stable normalized Ky options snapshot for the same reason as `HTTPError` above.768+ // `options` intentionally remains the stable normalized Ky options snapshot for the same reason as `HTTPError` above.769 // eslint-disable-next-line no-await-in-loop770 const hookResult: unknown = await hook({733- request: this.request,771+ request,772 options: this.#getNormalizedOptions(),773 error: processedError,774 retryCount: this.#retryCount,775 });776 739- // Only overwrite if the hook returns a valid Error instance.740- if (hookResult instanceof Error) {777+ // Only overwrite if the hook returns a valid Error, including one from another realm.778+ if (isError(hookResult)) {779 processedError = hookResult;780 }781 }782 62 unmodified lines845 #getEffectiveTimeout(): number | undefined {846 const remainingTotal = this.#getRemainingTotalTimeout();847 if (remainingTotal !== undefined) {848 if (remainingTotal <= 0) {811- throw new TimeoutError(this.request);849+ throw new TimeoutError(this.#sentRequest);850 }851 852 return this.#options.timeout === false853 ? remainingTotal5 unmodified lines859 860 // Unlike error bodies (`#getResponseData`), a successful body read has no fallback value to return -861 // the caller's `.json()`/`.text()`/etc. promise must settle, so a timeout here always rejects.862 async #raceBodyRead(createBodyPromise: () => Promise<unknown>, response: Response): Promise<unknown> {863+ const failedRequest = this.#getResponseRequest(response);864 let timeoutMs: number | undefined;865 try {866 timeoutMs = this.#getEffectiveTimeout();867 } catch (error: unknown) {829- await this.#throwProcessedError(error);868+ await this.#throwProcessedError(error, failedRequest);869 }870 871 const bodyPromise = createBodyPromise();872 const timeoutPromise = timeoutMs === undefined13 unmodified lines886 ? await bodyPromise887 : await Promise.race([bodyPromise, timeoutPromise]);888 } catch (error: unknown) {889 if (this.#userProvidedAbortSignal?.aborted) {851- await this.#throwProcessedError(this.#userProvidedAbortSignal.reason);890+ await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);891 }892 893 if (this.#getRemainingTotalTimeout() !== 0) {894 // A throwing progress callback errors the response stream, which a browser may report as a raw `TypeError` that would otherwise be mistaken for a dropped connection. Surface the callback error instead.895 const progressCallbackError = getProgressCallbackError(response.body ?? undefined);896 if (progressCallbackError !== undefined) {858- await this.#throwProcessedError(progressCallbackError);897+ await this.#throwProcessedError(progressCallbackError, failedRequest);898 }899 900 // 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.901 // This only happens on the awaited path, so a body that fails after the timeout already won does not run the hooks again.902 if (isRawNetworkError(error)) {864- await this.#throwProcessedError(new NetworkError(this.#getResponseRequest(response), {cause: error as Error}));903+ await this.#throwProcessedError(new NetworkError(failedRequest, {cause: error as Error}), failedRequest);904 }905 867- await this.#throwProcessedError(error);906+ await this.#throwProcessedError(error, failedRequest);907 }908 909 result = timedOutResponseData;910 }911 912+ // 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.913+ if (this.#userProvidedAbortSignal?.aborted) {914+ await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);915+ }916+917 if (result === timedOutResponseData || this.#getRemainingTotalTimeout() === 0) {918 // The stream is locked by the native body method's own reader by this point, so919 // `response.body.cancel()` would reject as "already locked". Aborting the request's920 // signal is what actually interrupts the underlying network read.921 this.#abortController?.abort();878- await this.#throwProcessedError(new TimeoutError(this.#getResponseRequest(response)));922+ await this.#throwProcessedError(new TimeoutError(failedRequest), failedRequest);923 }924 925 return result;926 }8 unmodified lines935 }936 937 let timeoutId: ReturnType<typeof setTimeout> | undefined;938 let abortListener: (() => void) | undefined;939+ let operationPromise: Promise<T> | undefined;940 try {941 const abortPromise = new Promise<never>((_resolve, reject) => {942 if (!abortSignal) {943 return;9 unmodified lines953 if (abortSignal.aborted) {954 abortListener();955 }956 });912- const operationPromise = operation();957+ operationPromise = operation();958 959 if (remainingTotal === undefined) {960 return await Promise.race([operationPromise, abortPromise]);961 }21 unmodified lines983 }984 985 return result;986 } catch (error: unknown) {942- abortSignal?.throwIfAborted();987+ if (abortSignal?.aborted) {988+ // The abort won the race, so whatever the operation eventually returns is discarded. Release its body, the989+ // same way the timeout path below does for a value it never consumed.990+ if (operationPromise) {991+ void operationPromise.then(value => {992+ this.#cancelReturnedBody(value);993+ }).catch(() => undefined);994+ }995 996+ abortSignal.throwIfAborted();997+ }998+999 const remainingAfterOperation = this.#getRemainingTotalTimeout();1000 if (remainingAfterOperation !== undefined && remainingAfterOperation <= 0) {1001 this.#abortController?.abort();1002 return timedOutOperation;148 unmodified lines1151 ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController!.signal])1152 : this.#abortController!.signal;1153 }1154 1155+ // 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.1156+ #shouldThrowHttpErrors(response: Response): boolean {1157+ const {throwHttpErrors} = this.#options;1158+ try {1159+ return typeof throwHttpErrors === 'function' ? throwHttpErrors(response.status) : throwHttpErrors;1160+ } catch (error: unknown) {1161+ this.#cancelResponseBody(response);1162+ throw error;1163+ }1164+ }1165+1166+ // `#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.1167+ get #sentRequest(): Request {1168+ return this.#originalRequest ?? this.request;1169+ }1170+1100- #throwIfTotalTimeoutExhausted(request: Request = this.request): void {1171+ #throwIfTotalTimeoutExhausted(request: Request = this.#sentRequest): void {1172 const remaining = this.#getRemainingTotalTimeout();1173 if (remaining !== undefined && remaining <= 0) {1174 throw new TimeoutError(request);1175 }8 unmodified lines1184 retryCount: 0,1185 }), this.#userProvidedAbortSignal);1186 1187 if (result === timedOutOperation) {1117- throw new TimeoutError(this.request);1188+ throw new TimeoutError(this.#sentRequest);1189 }1190 1191 if (isRequestInstance(result)) {1192 this.#assignRequest(this.#withManagedSignal(result));16 unmodified lines1209 let modifiedResponse;1210 try {1211 // eslint-disable-next-line no-await-in-loop1212 modifiedResponse = await this.#raceWithTotalTimeout(async () => hook({1213+ // 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.1214 request: this.request,1215 options: this.#getNormalizedOptions(),1216 response: hookResponse,1217 retryCount: this.#retryCount,1218 }), this.#userProvidedAbortSignal);1219 1220 if (modifiedResponse === timedOutOperation) {1149- throw new TimeoutError(this.request);1221+ throw new TimeoutError(this.#sentRequest);1222 }1223 } catch (error) {1224 // Cancel both responses to prevent memory leaks when hook throws1225 if (hookResponse !== response) {3 unmodified lines1229 this.#cancelResponseBody(response);1230 throw error;1231 }1232 1161- if (modifiedResponse instanceof RetryMarker) {1233+ if (isRetryMarker(modifiedResponse)) {1234 // Cancel both the cloned response passed to the hook and the current response to prevent resource leaks (especially important in Deno/Bun).1235 // Do not await cancellation since hooks can clone the response, leaving extra tee branches that keep cancel promises pending per the Streams spec.1236 if (hookResponse !== response) {1237 this.#cancelResponseBody(hookResponse);43 unmodified lines1281 1282 const remainingTimeout = this.#getRemainingTotalTimeout();1283 if (remainingTimeout !== undefined) {1284 if (remainingTimeout <= 0) {1213- throw new TimeoutError(this.request);1285+ throw new TimeoutError(this.#sentRequest);1286 }1287 1288 // If waiting would consume all remaining budget, time out without starting another request.1289 if (retryDelay >= remainingTimeout) {1290 await delay(remainingTimeout, delayOptions);1219- throw new TimeoutError(this.request);1291+ throw new TimeoutError(this.#sentRequest);1292 }1293 }1294 1295 // Only use user-provided signal for delay, not our internal abortController9 unmodified lines1305 }1306 1307 // Apply custom request from forced retry before beforeRetry hooks1308 // Ensure the custom request has the correct managed signal for timeouts and user aborts1237- if (error instanceof ForceRetryError && error.customRequest) {1309+ if (isForceRetryError(error) && error.customRequest) {1310 // Replacement Requests are authoritative by design. Do not rewrite headers here,1311 // even for cross-origin retries. Callers using `ky.retry({request})` explicitly1312 // opted into the exact Request they constructed.1313 this.#assignRequest(this.#withManagedSignal(error.customRequest));9 unmodified lines1323 error: error instanceof Error ? error : new NonError(error),1324 retryCount: this.#retryCount + 1,1325 }), this.#userProvidedAbortSignal);1326 } catch (hookError) {1255- // Preserve the original request error path (`throw error`) so beforeError hooks can still run.1256- if (hookError instanceof Error && hookError !== error) {1327+ // Preserve the original request error path (`throw error`) so beforeError hooks can still run. `isError`1328+ // rather than `instanceof`, so a cross-realm error is recognised the same way `#throwProcessedError` does.1329+ if (isError(hookError) && hookError !== error) {1330 this.#beforeRetryHookErrors.add(hookError);1331 }1332 1333 throw hookError;1334 }1335 1336 if (hookResult === timedOutOperation) {1264- throw new TimeoutError(this.request);1337+ throw new TimeoutError(this.#sentRequest);1338 }1339 1340 if (isRequestInstance(hookResult)) {1341 // Same contract as `ky.retry({request})`: a Request returned from `beforeRetry`58 unmodified lines1400 timeout: effectiveTimeout,1401 fetch,1402 });1403 1404+ // `undefined` would otherwise look like `ky.stop`, and any other value fails later with an error that does not name the cause.1405+ if (!isResponseInstance(response)) {1406+ throw new TypeError('The `fetch` option must resolve with a `Response`');1407+ }1408+1409 if (this.#getRemainingTotalTimeout() === 0) {1410 this.#abortController?.abort();1411 this.#cancelResponseBody(response);1412 throw new TimeoutError(request);9 unmodified lines1422 1423 // The upload progress wrapper errors the request body stream when its callback throws, which the runtime reports as a network failure. Surface the callback error instead.1424 const progressCallbackError = getProgressCallbackError(this.#originalRequest?.body ?? undefined);1425 if (progressCallbackError !== undefined) {1426+ this.#inFlightCallbackErrors.add(progressCallbackError);1427+1428 // eslint-disable-next-line @typescript-eslint/only-throw-error -- The callback can throw any value, and non-Error throws are propagated as-is elsewhere.1429 throw progressCallbackError;1430 }1431 95 unmodified linesmodified:source/types/hooks.ts+6 added-6 removed
1 unmodified line2 import type {KyRequest, KyResponse} from '../index.js';3 import type {InitOptions, NormalizedOptions} from './options.js';4 5 /**6-This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option is always a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.6+This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option starts as a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.7 8-The `body` option is the exception: it is passed through by reference, so mutating a `FormData` or `URLSearchParams` body in place changes your own object and repeats on every request from the same instance. Replace `options.body` with a new instance instead, the way the `beforeRequest` workflow does.8+Ky gives the hook its own copies of `headers`, `context`, `json`, `searchParams` and `retry`, so changing them in place only affects the current request. The `context` copy is deep, so when an instance has an `init` hook, nested `context` values are not shared across requests. The `body` option is not copied, so mutating a `FormData` or `URLSearchParams` body in place changes your own object and repeats on every request from the same instance. Assign a new instance instead, as shown in [Modifying FormData in hooks](https://github.com/sindresorhus/ky#modifying-formdata-in-hooks). A value that a hook assigns is used as is, so assign a new object rather than one that you change later.9 10-Unlike other hooks, `init` hooks are synchronous. Any error thrown will propagate synchronously and will not be caught by `beforeError` hooks.10+Unlike other hooks, `init` hooks are synchronous. An error thrown by one rejects the returned promise and is not passed to `beforeError` hooks.11 12 @example13 ```14 import ky from 'ky';73 unmodified lines88 export type AfterResponseHook = (state: AfterResponseState) => Response | RetryMarker | void | Promise<Response | RetryMarker | void>;89 90 export type Hooks = {91 /**92- This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option is always a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.92+ This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option starts as a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.93 94- Unlike other hooks, `init` hooks are synchronous. Any error thrown will propagate synchronously and will not be caught by `beforeError` hooks.94+ Ky gives the hook its own copies of `headers`, `context`, `json`, `searchParams` and `retry`, so changing them in place only affects the current request. The `context` copy is deep, so when an instance has an `init` hook, nested `context` values are not shared across requests. The `body` option is not copied, so mutating a `FormData` or `URLSearchParams` body in place changes your own object and repeats on every request from the same instance. Assign a new instance instead, as shown in [Modifying FormData in hooks](https://github.com/sindresorhus/ky#modifying-formdata-in-hooks). A value that a hook assigns is used as is, so assign a new object rather than one that you change later.95 96- The `body` option is passed through by reference, so mutating a `FormData` or `URLSearchParams` body in place changes your own object and repeats on every request from the same instance. Replace `options.body` with a new instance instead, the way the `beforeRequest` workflow does.96+ Unlike other hooks, `init` hooks are synchronous. An error thrown by one rejects the returned promise and is not passed to `beforeError` hooks.97 98 A common use case is to add a search parameter to every request:99 100 @example276 unmodified linesmodified:source/types/ky.ts+2 added
4 unmodified lines5 export type KyInstance = {6 /**7 Fetch the given `url`.8 9+ Invalid options, an invalid `input`, and an error thrown by an `init` hook reject the returned promise instead of throwing, the same way `fetch()` reports them. They are not passed to `beforeError` hooks, because no request was made.10+11 @param url - `Request` object, `URL` object, or URL string.12 @returns A promise with `Body` method added.13 14 @example191 unmodified linesmodified:source/types/options.ts+6 added-10 removed
205 unmodified lines206 */207 retry?: RetryOptions | number | undefined;208 209 /**210- Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Ky shortcut methods also use this value as a separate timeout for reading the response body. Cannot be greater than 2147483647. See also `totalTimeout`.210+ Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Ky shortcut methods also use this value as a separate timeout for reading the response body. Must be a non-negative number or `false`, or a `TypeError` is thrown. A value greater than 2147483647, `Infinity` included, throws a `RangeError`. See also `totalTimeout`.211 212 If set to `false`, there will be no per-attempt timeout.213 214+ If the signal you passed in is aborted while a body method is reading, or just after the read finished, the body method rejects with the abort reason rather than resolving with the bytes that already arrived.215+216 @default 10000217 */218 timeout?: number | false | undefined;219 220 /**219- Overall timeout in milliseconds for the entire operation, including retries and delays. Throws a `TimeoutError` if exceeded. Cannot be greater than 2147483647.221+ Overall timeout in milliseconds for the entire operation, including retries and delays. Throws a `TimeoutError` if exceeded. Must be a non-negative number or `false`, or a `TypeError` is thrown. A value greater than 2147483647, `Infinity` included, throws a `RangeError`.222 223 `beforeError` hooks run after an error is produced and are not bounded by `totalTimeout`.224 225 If set to `false` or not specified, there is no overall timeout.115 unmodified lines341 onUploadProgress?: ((progress: Progress, chunk: Uint8Array) => void) | undefined;342 343 /**344 User-defined `fetch` function.343- Has to be fully compatible with the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) standard.345+ Has to be fully compatible with the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) standard. It must resolve with a `Response`, or a `TypeError` is thrown.346 347 Use-cases:348 1. Use the `fetch` wrapper function provided by some frameworks that use server-side rendering (SSR).349 2. Add custom instrumentation or logging to all requests.31 unmodified lines381 - Pass serverless environment bindings (e.g., Cloudflare Workers)382 383 **Note:** Context is shallow merged. Top-level properties are merged, but nested objects are replaced. Only enumerable properties are copied.384 383- **Note:** Each request gets its own deep copy of the context, so a hook that mutates a nested plain object or array cannot write back to the instance defaults or to the object you passed in. Non-plain values such as class instances are shared by reference. A hook that caches data in the context, for example with `options.context.token ??= await getToken()`, therefore recomputes it once per request rather than once per instance.384-385 @example386 ```387 import ky from 'ky';388 113 unmodified lines502 // eslint-disable-next-line @typescript-eslint/no-restricted-types503 signal?: AbortSignal | null | undefined;504 }505 506-export type InitOptions = Omit<Options, 'retry' | 'hooks' | 'headers' | 'context'> & {507- get headers(): Record<string, string | undefined>;508- set headers(value: KyHeadersInit | undefined);509- get context(): Record<string, unknown>;510- set context(value: Record<string, unknown> | undefined);506+export type InitOptions = Omit<Options, 'retry' | 'hooks'> & {507 retry?: MutableRetryOptions | number | undefined;508 hooks?: {[Key in keyof Hooks]?: NormalizedHooks[Key] | undefined} | undefined;509 };510 36 unmodified linesmodified:source/types/ResponsePromise.ts+2 added
1234567863 unmodified lines/**Returns a `Response` object with `Body` methods added for convenience. So you can, for example, call `ky.get(input).json()` directly without having to await the `Response` first. When called like that, an appropriate `Accept` header will be set depending on the body method used. Unlike the `Body` methods of `window.fetch`, these will throw an `HTTPError` if the response status is not in the range of `200...299`. Note that `.json()` will throw if the body is empty, as it cannot be parsed. However, you can use the `parseJson` option to add custom handling for empty bodies. If the signal passed in the `signal` option is aborted while the body is being read, or just after it finished, the shortcut rejects with the abort reason, the same as `.json()` always has.
Invalid options, an invalid `input`, and an error thrown by an `init` hook reject the returned promise instead of throwing, the same way `fetch()` reports them. They are not passed to `beforeError` hooks, because no request was made.*/import {type KyResponse} from './response.js';import type {StandardSchemaV1, StandardSchemaV1InferOutput} from './standard-schema.js';
63 unmodified linesmodified:source/utils/body.ts+19 added-5 removed
8 unmodified lines9 const progressCallbackErrors = new WeakMap<ReadableStream, () => unknown>();10 // The `Response` constructor rejects a body for these statuses, but some browsers (for example, Chromium and WebKit) still expose a body stream on such responses, so they must not be wrapped. A runtime that exposes a non-empty body for one of them, such as WebKit for 205, is therefore left unlimited and without progress events.11 const nullBodyStatuses = new Set([101, 103, 204, 205, 304]);12 13+// A multipart body sends every line break in a field name or string value as CRLF, and escapes line breaks and quotes in a field name or filename.14+const normalizeLineBreaks = (value: string): string => value.replaceAll(/\r\n|\r|\n/g, '\r\n');15+const escapeFormDataName = (name: string): string => name.replaceAll('\n', '%0A').replaceAll('\r', '%0D').replaceAll('"', '%22');16+17 // eslint-disable-next-line @typescript-eslint/no-restricted-types18 export const getBodySize = (body?: BodyInit | null): number => {19 if (!body) {20 return 0;21 }22 23 if (body instanceof FormData) {20- // This is an approximation, as FormData size calculation is not straightforward24+ // This is an approximation, as FormData size calculation is not straightforward. The boundary length is a stand-in for the runtime's own, and every other byte is counted so the estimate errs high (except slightly in Bun, see `usualFormBoundarySize`): an estimate below the real size makes `percent` reach its ceiling part way through the upload.25 let size = 0;26 27 for (const [key, value] of body) {24- size += usualFormBoundarySize;25- size += encoder.encode(`Content-Disposition: form-data; name="${key}"`).byteLength;28+ size += usualFormBoundarySize + 4; // `--<boundary>\r\n`29+ size += encoder.encode(`Content-Disposition: form-data; name="${escapeFormDataName(normalizeLineBreaks(key))}"`).byteLength;30+31+ if (value instanceof Blob) {32+ // Most runtimes turn an appended `Blob` into a `File` named `blob`, but Bun keeps a `Blob` with an `undefined` name and sends an empty filename.33+ size += encoder.encode(`; filename="${escapeFormDataName((value as Partial<File>).name ?? '')}"`).byteLength;34+ size += encoder.encode(`\r\nContent-Type: ${value.type || 'application/octet-stream'}`).byteLength;35+ }36+37+ size += 4; // The CRLF that ends the headers, plus the blank line.38 size += typeof value === 'string'27- ? encoder.encode(value).byteLength39+ ? encoder.encode(normalizeLineBreaks(value)).byteLength40 : value.size;41+ size += 2; // The CRLF that ends the part.42 }43 31- return size;44+ // The closing `--<boundary>--\r\n`. An empty `FormData` still sends it, but reports `0`, the documented total for an empty transfer.45+ return size === 0 ? 0 : size + usualFormBoundarySize + 6;46 }47 48 if (body instanceof Blob) {49 return body.size;199 unmodified linesmodified:source/utils/merge.ts+32 added-11 removed
305 unmodified lines306 result.append(String(pair[0]), String(pair[1]));307 }308 } else if (isObject(input)) {309 for (const [key, value] of Object.entries(input)) {310+ // A `replaceOption()` wrapper is unwrapped here, because this branch stringifies every value, so a wrapper that reached it would land in the URL as `[object Object]`. A wrapped value replaces the inherited values of its key instead of being added to them.311+ const {isReplace, value: entry} = getReplaceState(value);310- if (value === undefined) {312+ if (entry === undefined) {313 result.delete(key);314 deleted.add(key);315 } else {316+ if (isReplace) {317+ result.delete(key);318+ }319+314- result.append(key, String(value));320+ result.append(key, String(entry));321 }322 }323 } else {324 // String42 unmodified lines367 signals.push(value);368 continue;369 }370 371+ // Option merging would otherwise let a `null` silently replace the inherited headers.372+ if (isRoot && key === 'headers' && value === null) {373+ throw new TypeError('The `headers` option must not be `null`. Use `undefined` to clear it.');374+ }375+376 // Special handling for context - shallow merge only.377 // Scoped to the root options level so it never rewrites nested user data that378 // happens to contain a `context` key (e.g. a `json` request body).379 if (isRoot && key === 'context') {380+ // `null` is not accepted, so it is reported here rather than treated as absent.369- if (value !== undefined && value !== null && (!isObject(value) || Array.isArray(value))) {381+ if (value !== undefined && (!isObject(value) || Array.isArray(value))) {382 throw new TypeError('The `context` option must be an object');383 }384 373- // Shallow merge: top-level keys are replaced, but each layer is deep-copied so nested values are374- // never shared with the caller's object.385+ // Shallow merge: always create a new object to prevent mutation bugs386 returnValue = {387 ...returnValue,377- context: (value === undefined || value === null)388+ context: value === undefined389 ? {}390 : (isReplace380- ? {...cloneDeep(value as Record<string, unknown>)}381- : {...returnValue.context, ...cloneDeep(value as Record<string, unknown>)}),391+ ? {...value}392+ : {...returnValue.context, ...value}),393 };394 continue;395 }396 397 // Special handling for searchParams.398 // Scoped to the root options level so it never rewrites nested user data that399 // happens to contain a `searchParams` key (e.g. a `json` request body).400 if (isRoot && key === 'searchParams') {401+ if (value === null) {402+ throw new TypeError('The `searchParams` option must not be `null`. Use `undefined` to clear it.');403+ }404+390- if (value === undefined || value === null) {391- // Explicit undefined or null removes searchParams405+ if (value === undefined) {406+ // Explicit undefined removes searchParams407 searchParameters = undefined;408 } else if (isReplace || searchParameters === undefined) {409 // First or replacement source: shallow-clone to preserve type (string/object/URLSearchParams/tuples) without sharing the caller's object410 searchParameters = Array.isArray(value) ? value.map(parameter => cloneShallow(parameter)) : cloneShallow(value);11 unmodified lines422 // and extending an object `retry` with a number keeps the other options423 // (e.g. `ky.create({retry: {methods: ['post']}}).extend({retry: 3})`).424 // Scoped to the root options level so it never rewrites nested user data that425 // happens to contain a `retry` key (e.g. a `json` request body).426+ // Checked here as well as when the request is built, because a later layer would otherwise replace an invalid value, `null` included, before anything reports it.427+ if (isRoot && key === 'retry' && value !== undefined && typeof value !== 'number' && (!isObject(value) || Array.isArray(value))) {428+ throw new TypeError('`retry` must be a number or an object');429+ }430+431 if (isRoot && key === 'retry' && !isReplace) {432 if (isObject(value) && typeof returnValue[key] === 'number') {433 returnValue = {...returnValue, [key]: {limit: returnValue[key]}};434 } else if (typeof value === 'number' && isObject(returnValue[key])) {12 unmodified lines447 }448 449 // Scoped to the root options level so it never rewrites nested user data that450 // happens to contain a `hooks` key (e.g. a `json` request body).431- if (isRoot && isObject((source as any).hooks)) {451+ // Every value but `undefined` goes through `mergeHooks`, which rejects a bad shape, `null` included, so a later layer cannot hide it.452+ if (isRoot && (source as any).hooks !== undefined) {453 const {value: hookValue, isReplace} = getReplaceState((source as any).hooks);454 hooks = isReplace455 ? mergeHooks({}, hookValue)456 : mergeHooks(hooks, hookValue);45 unmodified linesmodified:source/utils/normalize.ts+4 added
99 unmodified lines1001011021031041051061071081091101112 unmodified lines99 unmodified lines if (normalizedRetry.jitter !== undefined && typeof normalizedRetry.jitter !== 'boolean' && typeof normalizedRetry.jitter !== 'function') { throw new TypeError('`retry.jitter` must be a boolean or a function'); }
if (typeof normalizedRetry.retryOnTimeout !== 'boolean') { throw new TypeError('`retry.retryOnTimeout` must be a boolean'); }
normalizedRetry.methods = normalizedRetry.methods.map(method => normalizeRetryMethod(method)); normalizedRetry.statusCodes = [...normalizedRetry.statusCodes]; normalizedRetry.afterStatusCodes = [...normalizedRetry.afterStatusCodes];
2 unmodified linesmodified:source/utils/options.ts+9 added-4 removed
16 unmodified lines17 // We intentionally do not check whether the key also exists on `Request`, because some runtimes18 // patch `Request.prototype` with fetch-only extensions. For example, Next.js adds `next`, and the19 // old `key in request` heuristic dropped it unless Ky kept a special-case allowlist.20 // Passing all non-standard keys makes that allowlist unnecessary and preserves future fetch extensions too.21- // The registries are plain objects, so `Object.hasOwn()` is required: `in` would also match22- // `Object.prototype` members such as `constructor` and `toString`, silently dropping those options.21+ // The registries are plain objects, so `Object.hasOwn()` is required: `in` would also match `Object.prototype` members such as `constructor` and `toString`, silently dropping those options.22 if (!Object.hasOwn(requestOptionsRegistry, key) && !Object.hasOwn(kyOptionKeys, key)) {24- unknownOptions[key] = options[key];23+ // Defined instead of assigned, so a `__proto__` key becomes an own property of the init object rather than replacing its prototype, which would both drop the option and give `fetch()` an object that inherits from caller data.24+ Object.defineProperty(unknownOptions, key, {25+ value: options[key],26+ writable: true,27+ enumerable: true,28+ configurable: true,29+ });30 }31 }32 33 return unknownOptions;3 unmodified lines37 if (search === undefined) {38 return false;39 }40 36- // Option merging turns `null` into an absent value, but an `init` hook assigns straight onto the options object. `null` is not accepted, so report it instead of treating it as absent.41+ // Option merging already rejects `null`, but an `init` hook assigns straight onto the options object.42 if (search === null) {43 throw new TypeError('The `searchParams` option must not be `null`. Use `undefined` to clear it.');44 }45 20 unmodified linesmodified:source/index.ts+30 added-3 removed
1 /*! MIT License © Sindre Sorhus */2 3 import {Ky} from './core/Ky.js';4-import {requestMethods, stop, retry} from './core/constants.js';4+import {5+ requestMethods,6+ responseTypes,7+ stop,8+ retry,9+} from './core/constants.js';10 import type {KyInstance} from './types/ky.js';11 import type {Input, Options} from './types/options.js';12+import type {ResponsePromise} from './types/ResponsePromise.js';13 import {cloneDeep, validateAndMerge} from './utils/merge.js';14 import {type Mutable} from './utils/types.js';15 16+// Errors while setting up the request, such as invalid options or a throwing `init` hook, reject the returned promise instead of throwing, the same way `fetch()` reports them, so callers only have one error channel to handle.17+const createRequest = (input: Input, getOptions: () => Options): ResponsePromise => {18+ try {19+ return Ky.create(input, getOptions());20+ } catch (error: unknown) {21+ // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- A hook can throw any value, and it must be preserved exactly.22+ const result = Promise.reject(error) as ResponsePromise;23+ for (const type of Object.keys(responseTypes) as Array<keyof typeof responseTypes>) {24+ // Matches `Ky.create()`, which only exposes `.bytes()` when the environment implements it.25+ if (type === 'bytes' && typeof (globalThis.Response?.prototype as unknown as {bytes?: unknown})?.bytes !== 'function') {26+ continue;27+ }28+29+ // Returning the same promise marks it as handled, so a body method call does not also report an unhandled rejection.30+ result[type] = async () => result as never;31+ }32+33+ return result;34+ }35+};36+37 const createInstance = (defaults?: Partial<Options>): KyInstance => {38 // eslint-disable-next-line @typescript-eslint/promise-function-async12- const ky: Partial<Mutable<KyInstance>> = (input: Input, options?: Options) => Ky.create(input, validateAndMerge(defaults, options));39+ const ky: Partial<Mutable<KyInstance>> = (input: Input, options?: Options) => createRequest(input, () => validateAndMerge(defaults, options));40 41 for (const method of requestMethods) {42 // eslint-disable-next-line @typescript-eslint/promise-function-async16- ky[method] = (input: Input, options?: Options) => Ky.create(input, validateAndMerge(defaults, options, {method}));43+ ky[method] = (input: Input, options?: Options) => createRequest(input, () => validateAndMerge(defaults, options, {method}));44 }45 46 ky.create = (newDefaults?: Partial<Options>) => createInstance(validateAndMerge(newDefaults));47 ky.extend = (newDefaults?: Partial<Options> | ((parentDefaults: Partial<Options>) => Partial<Options>)) => {70 unmodified linesmodified:test/base-url.ts+11 added-17 removed
8 unmodified lines9 });10 const child = parent.extend({baseUrl: undefined});11 12 t.is(await parent('users').text(), 'https://example.com/api/users');13- t.throws(() => {14- void child('users');15- }, {instanceOf: TypeError});13+ await t.throwsAsync(child('users'), {instanceOf: TypeError});14 t.is(await child('https://example.org/users').text(), 'https://example.org/users');15 t.is(await parent('users').text(), 'https://example.com/api/users');16 });17 80 unmodified lines98 String.raw`https:\/example.com/collect`,99 ];100 101 for (const input of inputs) {104- t.throws(105- () => {106- void ky(input, {107- baseUrl: 'https://trusted.test/api/',108- fetch,109- headers: {110- authorization: 'Bearer secret',102+ // eslint-disable-next-line no-await-in-loop103+ await t.throwsAsync(ky(input, {104+ baseUrl: 'https://trusted.test/api/',105+ fetch,106+ headers: {107+ authorization: 'Bearer secret',111- },112- });108 },114- {115- instanceOf: TypeError,116- message: '`input` url protocol must be followed by `//` when using `baseUrl`',117- },118- );109+ }), {110+ instanceOf: TypeError,111+ message: '`input` url protocol must be followed by `//` when using `baseUrl`',112+ });113 }114 115 let absoluteUrl: string | undefined;116 const absoluteFetch: typeof globalThis.fetch = async input => {44 unmodified linesmodified:test/body-size.ts+2 added
1 import test from 'ava';2+import ky from '../source/index.js';3 import {getBodySize} from '../source/utils/body.js';4+import {createHttpTestServer} from './helpers/create-http-test-server.js';5 6 test('returns 0 for undefined', t => {7 t.is(getBodySize(undefined), 0);8 });225 unmodified linesmodified:test/browser.ts+2 added-4 removed
271 unmodified lines272 await addKyScriptToPage(page);273 274 const results = await page.evaluate(async (url: string) => Promise.all([275 globalThis.ky(`${url}/api/unicorn`).text(),276- // @ts-expect-error unsupported {baseUrl: null} type277- globalThis.ky(`${url}/api/unicorn`, {baseUrl: null}).text(),276+ globalThis.ky(`${url}/api/unicorn`, {baseUrl: undefined}).text(),277 globalThis.ky('api/unicorn', {baseUrl: url}).text(),278 globalThis.ky('unicorn', {baseUrl: `${url}/api`}).text(),279 globalThis.ky('/unicorn', {baseUrl: `${url}/api`}).text(),280 globalThis.ky('unicorn', {baseUrl: `${url}/api/`}).text(),16 unmodified lines297 await addKyScriptToPage(page);298 299 const results = await page.evaluate(async (url: string) => Promise.all([300 globalThis.ky(`${url}/api/unicorn`).text(),302- // @ts-expect-error unsupported {prefix: null} type303- globalThis.ky(`${url}/api/unicorn`, {prefix: null}).text(),301+ globalThis.ky(`${url}/api/unicorn`, {prefix: undefined}).text(),302 globalThis.ky('api/unicorn', {prefix: url}).text(),303 globalThis.ky('unicorn', {prefix: `${url}/api`}).text(),304 globalThis.ky('/unicorn', {prefix: `${url}/api`}).text(),305 globalThis.ky('unicorn', {prefix: `${url}/api/`}).text(),588 unmodified linesmodified:test/context.ts+9 added-13 removed
297 unmodified lines298 t.is(initCalls, 2);299 t.is(beforeRequestCalls, 2);300 });301 302-test('hook mutation of a nested context value does not leak into the instance defaults', async t => {303- const context = {nested: {count: 0}};304- const observed: number[] = [];305-302+// Context is merged shallowly, so a nested object is shared by every request from the instance, which lets hooks keep state such as a cache in it. An `init` hook gets a deep copy, so this does not hold for an instance with one.303+test('a nested context object is shared across requests', async t => {304+ const context = {cache: {count: 0}};305 const api = ky.create({306 context,308- retry: {limit: 0},307 hooks: {308 beforeRequest: [({options}) => {311- observed.push(options.context.nested.count);312- options.context.nested.count++;309+ (options.context.cache as typeof context.cache).count++;310 }],311 },312 fetch: async () => new Response('ok'),313 });314 315 await api('https://example.com/1').text();316 await api('https://example.com/2').text();320- await api('https://example.com/3').text();317 322- t.deepEqual(observed, [0, 0, 0]);323- t.deepEqual(context, {nested: {count: 0}});318+ t.is(context.cache.count, 2);319 });320 321 test('hooks in one request still share a single context object', async t => {322 const seen: unknown[] = [];21 unmodified lines344 t.is(seen[0], seen[1]);345 t.deepEqual(seen[1], {shared: 'set-in-beforeRequest'});346 });347 348+// `init` hooks get a deep copy of the context, which must keep a null prototype.353-test('a nested null-prototype context value keeps its prototype', async t => {349+test('a nested null-prototype context value keeps its prototype in an `init` hook', async t => {350 const bag = Object.create(null) as Record<string, unknown>;351 bag.count = 1;352 353 let seen: Record<string, unknown> | undefined;354 const api = ky.create({355 context: {bag},356 hooks: {361- beforeRequest: [({options}) => {362- seen = options.context.bag as Record<string, unknown>;357+ init: [options => {358+ seen = options.context!.bag as Record<string, unknown>;359 }],360 },361 fetch: async () => new Response('ok'),362 });41 unmodified linesmodified:test/fetch.ts+31 added-21 removed
1 import {setTimeout as delay} from 'node:timers/promises';2 import test from 'ava';3-import ky, {HTTPError, NetworkError} from '../source/index.js';3+import ky, {NetworkError} from '../source/index.js';4 import {createHttpTestServer} from './helpers/create-http-test-server.js';5 6 const fixture = 'https://example.com/unicorn';7 903 unmodified lines911 fetch: customFetch,912 } as never).text();913 });914 915-// A custom `fetch` is allowed to resolve with anything, and Ky's own comments say a non-native Response only916-// continues if it passes `isResponseInstance()`. Recording the value in a `WeakMap` first made that unreachable for917-// a primitive, and reported a message that named a `WeakMap` instead of the option that was wrong.918-test('a custom fetch that resolves with a non-Response does not crash on a WeakMap key', async t => {915+// The init object was built with a plain assignment, so a `__proto__` key hit the inherited setter instead of becoming an own property. The extension was dropped and `fetch()` received an object whose prototype was caller data.916+test('a `__proto__` fetch extension is forwarded as an own property', async t => {917+ let init: unknown;918+919+ await ky(fixture, {920+ ...JSON.parse('{"__proto__": {"marker": 1}, "priority": "low"}'),921+ async fetch(request, options) {922+ init = options;923+ return new Response(request.url);924+ },925+ } as never).text();926+927+ t.is(Object.getPrototypeOf(init), Object.prototype);928+ t.deepEqual(Object.getOwnPropertyDescriptor(init, '__proto__')?.value, {marker: 1});929+ t.is((init as {priority: unknown}).priority, 'low');930+});931+932+// `undefined` would otherwise look like `ky.stop`, and any other value failed later with an error that did not name the cause.933+test('a custom fetch that resolves with a value that is not a Response is reported', async t => {934+ for (const value of [undefined, null, 'ok', 42, {}] as unknown[]) {935+ // eslint-disable-next-line no-await-in-loop936+ await t.throwsAsync(ky(fixture, {retry: 0, fetch: async () => value as Response}), {937+ instanceOf: TypeError,938+ message: 'The `fetch` option must resolve with a `Response`',939+ }, `value: ${String(value)}`);940+ }941+});942+943+// A Response from another realm or a Response-like object with the `Response` brand is accepted as-is.944+test('a custom fetch can resolve with a branded Response-like object', async t => {945 const responseLike = {946 status: 200,947 ok: true,948 type: 'default',6 unmodified lines955 },956 [Symbol.toStringTag]: 'Response',957 };958 933- // A nullish result is normalized to `undefined`, the same as a hook that stopped the flow.934- for (const value of [undefined, null]) {935- // eslint-disable-next-line no-await-in-loop936- t.is(await ky(fixture, {retry: 0, fetch: async () => value as Response}), undefined);937- }938-959 t.is(await ky(fixture, {retry: 0, fetch: async () => responseLike as unknown as Response}), responseLike);960 });941-942-test('a custom fetch that resolves with a value that is not a response produces an HTTPError', async t => {943- for (const value of ['ok', 42, {}] as unknown[]) {944- // eslint-disable-next-line no-await-in-loop945- await t.throwsAsync(ky(fixture, {retry: 0, fetch: async () => value as Response}).text(), {946- instanceOf: HTTPError,947- message: /an unknown error/,948- }, `value: ${String(value)}`);949- }950-});modified:test/hooks.ts+49 added-195 removed
14 unmodified lines15 import {createHttpTestServer} from './helpers/create-http-test-server.js';16 17 // Kept in sync with `missingResponseMessage` in source/core/Ky.ts.18 const noResponseMessage = 'The request resolved without a response, so there is no body to read.'19- + ' Returning `ky.stop` from a `beforeRetry` hook, or a custom `fetch` that resolves with nothing, both do that.'20- + ' Throw from the hook instead of returning `ky.stop`.';19+ + ' This happens when a `beforeRetry` hook returns `ky.stop`. Throw from the hook instead of returning `ky.stop`.';20 21 const withHeader = (request: Request, name: string, value: string) => {22 const headers = new Headers(request.headers);23 headers.set(name, value);5514 unmodified lines5538 5539 t.is(fetchCount, 1);5540 });5541 5543-test('init hook that throws propagates synchronously', t => {5544- t.throws(5545- () => {5546- void ky.get('https://example.com', {5547- hooks: {5548- init: [5549- () => {5550- throw new Error('init failed');5542+test('init hook that throws rejects the returned promise', async t => {5543+ await t.throwsAsync(ky.get('https://example.com', {5544+ hooks: {5545+ init: [5546+ () => {5547+ throw new Error('init failed');5551- },5552- ],5548 },5554- });5549+ ],5550 },5556- {message: 'init failed'},5557- );5551+ }), {message: 'init failed'});5552 });5553 5554 test('init hook works with ky.create()', async t => {5555 const called: string[] = [];59 unmodified lines5615 },5616 });5617 });5618 5625-test('init hook replacements stay normalized for later init hooks', async t => {5626- await ky.get('https://example.com', {5627- fetch: async () => new Response('ok'),5628- hooks: {5629- init: [5630- options => {5631- options.headers = new Headers({'X-Test': 'value'});5632- options.context = undefined;5633- },5634- options => {5635- t.deepEqual(options.headers, {'x-test': 'value'});5636- t.deepEqual(options.context, {});5637- options.headers['x-added'] = 'added';5638- options.context.added = true;5639- },5640- ],5641- },5642- });5643-});5644-5619 test('init hook sees per-request options merged with defaults', async t => {5620 t.plan(2);5621 5622 const api = ky.extend({14 unmodified lines5637 },5638 });5639 });5640 5667-test('init hook error is not caught by beforeError hooks', t => {5641+test('init hook error is not caught by beforeError hooks', async t => {5642 let beforeErrorCalled = false;5643 5670- t.throws(5671- () => {5672- void ky.get('https://example.com', {5673- hooks: {5674- init: [5675- () => {5676- throw new Error('init boom');5644+ await t.throwsAsync(ky.get('https://example.com', {5645+ hooks: {5646+ init: [5647+ () => {5648+ throw new Error('init boom');5677- },5678- ],5679- beforeError: [5680- ({error}) => {5681- beforeErrorCalled = true;5682- return error;5683- },5684- ],5649 },5686- });5650+ ],5651+ beforeError: [5652+ ({error}) => {5653+ beforeErrorCalled = true;5654+ return error;5655+ },5656+ ],5657 },5688- {message: 'init boom'},5689- );5658+ }), {message: 'init boom'});5659 5660 t.false(beforeErrorCalled);5661 });5662 1235 unmodified lines6898 },6899 }), undefined);6900 });6901 6933-// The defensive copy only ran on the values the options object started with. A hook that assigned one of its own6934-// objects got that same object back for every later hook and every later request, so a mutation in a second hook6935-// wrote straight through to the object the first hook owned.6936-test('an `init` hook that assigns `json` hands later hooks a copy', async t => {6937- const bodies: string[] = [];6938- const ownBody = {list: [1, 2]};6939- const instance = ky.create({6940- method: 'POST',6941- json: {list: [1, 2]},6942- retry: 0,6943- hooks: {6944- init: [6945- options => {6946- options.json = ownBody;6947- },6948- options => {6949- (options.json as typeof ownBody).list.push(99);6950- },6951- ],6952- },6953- async fetch(request) {6954- bodies.push(await request.clone().text());6955- return new Response('ok');6956- },6957- });6958-6959- await instance('https://example.com').text();6960- await instance('https://example.com').text();6961-6962- t.deepEqual(bodies, ['{"list":[1,2,99]}', '{"list":[1,2,99]}']);6963- t.deepEqual(ownBody, {list: [1, 2]});6964-});6965-6966-test('an `init` hook that assigns `searchParams` or `context` hands later hooks a copy', async t => {6967- const urls: string[] = [];6968- const contexts: string[] = [];6969- const ownSearchParameters = {page: 1};6970- const ownContext = {token: 'first'};6971-6972- const instance = ky.create({6973- retry: 0,6974- hooks: {6975- init: [6976- options => {6977- options.searchParams = ownSearchParameters;6978- options.context = ownContext;6979- },6980- options => {6981- (options.searchParams as typeof ownSearchParameters).page = 2;6982- (options.context as typeof ownContext).token = 'second';6983- },6984- ],6985- beforeRequest: [({options}) => {6986- contexts.push(JSON.stringify(options.context));6987- }],6988- },6989- async fetch(request) {6990- urls.push(request.url);6991- return new Response('ok');6992- },6993- });6994-6995- await instance('https://example.com').text();6996- await instance('https://example.com').text();6997-6998- t.deepEqual(urls, ['https://example.com/?page=2', 'https://example.com/?page=2']);6999- t.deepEqual(contexts, ['{"token":"second"}', '{"token":"second"}']);7000- t.deepEqual(ownSearchParameters, {page: 1});7001- t.deepEqual(ownContext, {token: 'first'});7002-});7003-7004-test('an `init` hook that assigns `retry` hands later hooks a copy', async t => {7005- const attemptCounts: number[] = [];7006- const ownRetry = {limit: 0, delay: () => 0};7007-7008- const instance = ky.create({7009- hooks: {7010- init: [7011- options => {7012- options.retry = ownRetry;7013- },7014- options => {7015- (options.retry as typeof ownRetry).limit = 1;7016- },7017- ],7018- },7019- async fetch() {7020- attemptCounts.push(1);7021- return new Response('server error', {status: 500});7022- },7023- });7024-7025- await t.throwsAsync(instance('https://example.com').text());7026- await t.throwsAsync(instance('https://example.com').text());7027-7028- t.deepEqual(attemptCounts, [1, 1, 1, 1]);7029- t.deepEqual(ownRetry, {limit: 0, delay: ownRetry.delay});7030-});7031-7032-// `afterResponse` hooks deliberately receive the clone `#fetch()` prepared for a possible retry, whose body is6902+// `afterResponse` hooks deliberately receive the clone `#fetch()` prepared for a possible retry, whose body is still unread, so a hook that forces a retry can copy an unconsumed request from it.7033-// still unread, so a hook that forces a retry can copy an unconsumed request from it.6903 test('an `afterResponse` hook can copy the unconsumed request it is given', async t => {6904 const bodies: string[] = [];6905 let attempts = 0;6906 240 unmodified lines7147 await cancelled;7148 t.pass();7149 });7150 7282-// `newHookValue` merged with `deepMerge`, which ignores sources that are neither arrays nor objects, so a single7283-// function, a string or a `null` was dropped without a word and the hook simply never ran. `null` is reported like any7284-// other bad shape, since `undefined` is how a hook list is cleared.7285-test('rejects a hook list that is not an array', t => {7151+// `newHookValue` merged with `deepMerge`, which ignores sources that are neither arrays nor objects, so a single function, a string or a `null` was dropped without a word and the hook simply never ran. `null` is reported like any other bad shape, since `undefined` is how a hook list is cleared.7152+test('rejects a hook list that is not an array', async t => {7153 for (const [key, value] of [7154 ['init', () => undefined],7155 ['beforeRequest', 'not a function'],7156 ['beforeRetry', {}],5 unmodified lines7162 ['afterResponse', [() => undefined, 'not a function']],7163 ] as Array<[string, unknown]>) {7164 const hooks: Record<string, unknown> = {[key]: value};7165 7299- t.throws(() => {7300- void ky('https://example.com', {hooks: hooks as never});7301- }, {7166+ // eslint-disable-next-line no-await-in-loop7167+ await t.throwsAsync(ky('https://example.com', {hooks: hooks as never}), {7168 instanceOf: TypeError,7303- message: `\`hooks.${key}\` must be an array`,7169+ message: `\`hooks.${key}\` must be an array of functions`,7170 }, `${key}: ${JSON.stringify(value)}`);7171 }7172 });7173 7308-test('rejects `replaceOption()` around a non-array hook list', t => {7174+test('rejects `replaceOption()` around a non-array hook list', async t => {7175 for (const value of [() => undefined, 42, {}] as unknown[]) {7310- t.throws(() => {7311- void ky('https://example.com', {hooks: {beforeRetry: replaceOption(value as never)}});7312- }, {7176+ // eslint-disable-next-line no-await-in-loop7177+ await t.throwsAsync(ky('https://example.com', {hooks: {beforeRetry: replaceOption(value as never)}}), {7178 instanceOf: TypeError,7314- message: '`hooks.beforeRetry` must be an array',7179+ message: '`hooks.beforeRetry` must be an array of functions',7180 });7181 }7182 });7183 7319-test('a single-function hook is reported instead of silently dropped', t => {7184+test('a single-function hook is reported instead of silently dropped', async t => {7185 let ran = 0;7186 const hooks = {7187 beforeRequest: (() => {7188 ran++;7189 }) as never,7190 };7191 7327- const error = t.throws(() => {7328- void ky('https://example.com', {7329- retry: 0,7330- hooks,7331- fetch: async () => new Response('ok'),7332- });7192+ const error = await t.throwsAsync(ky('https://example.com', {7193+ retry: 0,7194+ hooks,7195+ fetch: async () => new Response('ok'),7196+ }));7333- });7197 7335- t.is(error?.message, '`hooks.beforeRequest` must be an array');7198+ t.is(error?.message, '`hooks.beforeRequest` must be an array of functions');7199 t.is(ran, 0);7200 });7201 7339-test('`hooks` that is not an object reports a clear error', t => {7202+test('`hooks` that is not an object reports a clear error', async t => {7203 for (const hooks of ['none', 42, true, []] as unknown[]) {7341- t.throws(() => {7342- void ky('https://example.com', {hooks: hooks as never});7343- }, {7204+ // eslint-disable-next-line no-await-in-loop7205+ await t.throwsAsync(ky('https://example.com', {hooks: hooks as never}), {7206 instanceOf: TypeError,7207 message: 'The `hooks` option must be an object',7208 }, `hooks: ${JSON.stringify(hooks)}`);7209 }7210 });7211 7350-// `hooks: null` used to reach `Object.hasOwn(null, ...)` and report an internal error. It is reported like any other7351-// bad shape instead, since `undefined` is how the option is omitted.7352-test('`hooks: null` reports a clear error', t => {7353- for (const hooks of [null, undefined, 'none', 42, true, []] as unknown[]) {7354- if (hooks === undefined) {7355- // The one shape that selects the default, through the parameter default.7356- t.pass();7357- continue;7358- }7359-7360- t.throws(() => {7361- void ky('https://example.com', {hooks: hooks as never});7362- }, {7212+// `hooks: null` used to reach `Object.hasOwn(null, ...)` and report an internal error. It is reported like any other bad shape instead, since `undefined` is how the option is omitted.7213+test('`hooks: null` reports a clear error', async t => {7214+ for (const hooks of [null, 'none', 42, true, []] as unknown[]) {7215+ // eslint-disable-next-line no-await-in-loop7216+ await t.throwsAsync(ky('https://example.com', {hooks: hooks as never}), {7217 instanceOf: TypeError,7218 message: 'The `hooks` option must be an object',7219 }, `hooks: ${JSON.stringify(hooks)}`);7220 }7221 });7222 7223 test('an explicit `undefined` hook list clears the parent hooks', async t => {7224 const cleared: string[] = [];7371- const undefinedHookList = {hooks: {beforeRequest: undefined}} as Options;7225+ const undefinedHookList: Options = {hooks: {beforeRequest: undefined}};7226 const instance = ky.create({7227 hooks: {7228 beforeRequest: [() => {7229 cleared.push('parent');153 unmodified linesmodified:test/main.ts+106 added-74 removed
201 unmodified lines202 203 t.deepEqual(responseJson, json);204 });205 206-test('cannot use `body` option with GET or HEAD method', t => {207- t.throws(208- () => {209- void ky.get('https://example.com', {body: 'foobar'});210- },206+test('cannot use `body` option with GET or HEAD method', async t => {207+ await t.throwsAsync(ky.get('https://example.com', {body: 'foobar'}),208 {209 message: 'Request with GET/HEAD method cannot have body.',210 },211 );212 216- t.throws(217- () => {218- void ky.head('https://example.com', {body: 'foobar'});219- },213+ await t.throwsAsync(ky.head('https://example.com', {body: 'foobar'}),214 {215 message: 'Request with GET/HEAD method cannot have body.',216 },217 );218 });219 226-test('cannot use `json` option with GET or HEAD method', t => {227- t.throws(228- () => {229- void ky.get('https://example.com', {json: {}});230- },220+test('cannot use `json` option with GET or HEAD method', async t => {221+ await t.throwsAsync(ky.get('https://example.com', {json: {}}),222 {223 message: 'Request with GET/HEAD method cannot have body.',224 },225 );226 236- t.throws(237- () => {238- void ky.head('https://example.com', {json: {}});239- },227+ await t.throwsAsync(ky.head('https://example.com', {json: {}}),228 {229 message: 'Request with GET/HEAD method cannot have body.',230 },231 );773 unmodified lines1005 await delay(1000);1006 response.end(fixture);1007 });1008 1021- await t.throwsAsync(ky(server.url, {timeout: 21_474_836_470}).text(), {1009+ await t.throwsAsync(ky(server.url, {timeout: 21_474_836_470}), {1010 instanceOf: RangeError,1011 message: 'The `timeout` option cannot be greater than 2147483647',1012 });1013 2533 unmodified lines3547 3548 t.is(await ky(inputRequest).text(), inputRequest.method);3549 });3550 3563-test('throws when input is not a string, URL, or Request', t => {3564- t.throws(3565- () => {3566- // @ts-expect-error3567- void ky.get(0);3568- },3569- {3570- message: '`input` must be a string, URL, or Request',3571- },3572- );3551+test('throws when input is not a string, URL, or Request', async t => {3552+ // @ts-expect-error3553+ await t.throwsAsync(ky.get(0), {3554+ message: '`input` must be a string, URL, or Request',3555+ });3556 });3557 3558 test('options override Request instance method', async t => {3559 const server = await createHttpTestServer(t);645 unmodified lines4205 },4206 }).text(), '/');4207 });4208 4226-// `hasSearchParameters()` reached `Object.keys()` on `null`, so an `init` hook that assigned `null` crashed with an internal error. `null` is not accepted anywhere in Ky, so the error names the option instead.4227-test('an `init` hook that sets `searchParams` to `null` gets an error naming the option', t => {4228- t.throws(() => {4229- void ky('https://example.com', {4230- searchParams: {a: '1'},4209+// Merging let a `null` silently replace the inherited headers.4210+test('`headers: null` gets an error naming the option', async t => {4211+ const api = ky.create({headers: {a: '1'}});4212+4213+ t.throws(() => api.extend({headers: null as never}), {4214+ instanceOf: TypeError,4215+ message: 'The `headers` option must not be `null`. Use `undefined` to clear it.',4216+ });4217+ await t.throwsAsync(ky('https://example.com', {headers: null as never}), {4218+ instanceOf: TypeError,4219+ message: 'The `headers` option must not be `null`. Use `undefined` to clear it.',4220+ });4221+});4222+4223+// Merging treated a `null` `context` or `searchParams` as absent, and an `init` hook could assign `null` to `headers` or `context`.4224+test('`null` for `context`, `searchParams` or `headers` gets an error naming the option', async t => {4225+ const contextError = {instanceOf: TypeError, message: 'The `context` option must be an object'};4226+ const searchParametersError = {instanceOf: TypeError, message: 'The `searchParams` option must not be `null`. Use `undefined` to clear it.'};4227+ const headersError = {instanceOf: TypeError, message: 'The `headers` option must not be `null`. Use `undefined` to clear it.'};4228+4229+ await t.throwsAsync(ky('https://example.com', {context: null as never}), contextError);4230+ await t.throwsAsync(ky('https://example.com', {searchParams: null as never}), searchParametersError);4231+4232+ for (const [key, expectation] of [['context', contextError], ['headers', headersError]] as const) {4233+ // eslint-disable-next-line no-await-in-loop4234+ await t.throwsAsync(ky('https://example.com', {4235 hooks: {4236 init: [options => {4233- options.searchParams = null as never;4237+ (options as Record<string, unknown>)[key] = null;4238 }],4239 },4236- });4237- }, {4238- instanceOf: TypeError,4239- message: 'The `searchParams` option must not be `null`. Use `undefined` to clear it.',4240- });4240+ }), expectation, `init hook: ${key}`);4241+ }4242 });4243 4243-// The top-level context is merged shallowly, so a nested value arrived from the caller by reference and mutating4244-// it after `ky.create()` silently changed what every later request carried. The per-request deep copy happens too4245-// late to help. `searchParams` is already copied at this point.4246-test('mutating a caller-owned `context` object after creating an instance does not change it', async t => {4247- const bodies: string[] = [];4248- const contexts: string[] = [];4249- const json = {nested: {value: 1}};4250- const context = {nested: {value: 1}};4244+// A `null` `method`, `prefix` or `baseUrl` fell through to the default, so the request went out as a `GET` or without the prefix.4245+test('`null` for `method`, `prefix` or `baseUrl` gets an error naming the option', async t => {4246+ for (const key of ['method', 'prefix', 'baseUrl'] as const) {4247+ const expectation = {instanceOf: TypeError, message: `The \`${key}\` option must not be \`null\`. Use \`undefined\` to clear it.`};4248 4252- const instance = ky.create({4253- method: 'POST',4254- json,4255- context,4256- async fetch(request) {4257- bodies.push(await request.clone().text());4258- return new Response('ok');4259- },4249+ // eslint-disable-next-line no-await-in-loop4250+ await t.throwsAsync(ky('https://example.com', {[key]: null as never}), expectation, `option: ${key}`);4251+4252+ // eslint-disable-next-line no-await-in-loop4253+ await t.throwsAsync(ky('https://example.com', {4254+ hooks: {4255+ init: [options => {4256+ (options as Record<string, unknown>)[key] = null;4257+ }],4258+ },4259+ }), expectation, `init hook: ${key}`);4260+ }4261+});4262+4263+// `hasSearchParameters()` reached `Object.keys()` on `null`, so an `init` hook that assigned `null` crashed with an internal error. `null` is not accepted anywhere in Ky, so the error names the option instead.4264+test('an `init` hook that sets `searchParams` to `null` gets an error naming the option', async t => {4265+ await t.throwsAsync(ky('https://example.com', {4266+ searchParams: {a: '1'},4267 hooks: {4261- beforeRequest: [({options}) => {4262- contexts.push(JSON.stringify(options.context));4268+ init: [options => {4269+ options.searchParams = null as never;4270 }],4271 },4272+ }), {4273+ instanceOf: TypeError,4274+ message: 'The `searchParams` option must not be `null`. Use `undefined` to clear it.',4275 });4266-4267- context.nested.value = 2;4268-4269- await instance('https://example.com').text();4270-4271- t.is(contexts[0], '{"nested":{"value":1}}');4272- t.deepEqual(context, {nested: {value: 2}});4276 });4277 4275-// `#fetch()` replaces `ky.request` with the clone prepared for a possible retry, so a shortcut called after the4276-// request was dispatched advertised its media type on that clone, which is only sent if a retry happens, instead of4277-// on the attempt that produced the response the caller reads.4278-test('a body shortcut called after dispatch does not advertise its media type on the retry', async t => {4278+// A shortcut called after dispatch cannot change the attempt that is already in flight, so it advertises its media type on the retry. The request that was already sent must stay as it was, or `error.request` would report a header that never went over the wire.4279+test('a body shortcut called after dispatch advertises its media type only on later attempts', async t => {4280+ const requests: Request[] = [];4281 const accepts: string[] = [];4280- let attempts = 0;4282 let markBeforeRetry: () => void;4283 let releaseBeforeRetry: () => void;4284 4285 // The `beforeRetry` hook gates the retry, so the shortcut is guaranteed to be called while `ky.request` is the clone prepared for that retry rather than racing a timer against it.6 unmodified lines4292 4293 const promise = ky('https://example.com', {4294 retry: {limit: 1, delay: () => 0},4295 async fetch(request) {4295- attempts++;4296+ requests.push(request as Request);4297 accepts.push(request.headers.get('accept') ?? 'none');4297- return attempts === 1 ? new Response('{"ok":true}', {status: 500}) : new Response('{"ok":true}');4298+ return requests.length === 1 ? new Response('{"ok":true}', {status: 500}) : new Response('{"ok":true}');4299 },4300 hooks: {4301 beforeRetry: [async () => {4302 markBeforeRetry!();7 unmodified lines4310 const jsonPromise = promise.json();4311 releaseBeforeRetry!();4312 t.is(JSON.stringify(await jsonPromise), '{"ok":true}');4313 4313- t.is(attempts, 2);4314- t.deepEqual(accepts, ['none', 'none']);4314+ t.deepEqual(accepts, ['none', 'application/json']);4315+ t.is(requests[0]!.headers.get('accept'), null);4316 });4317+4318+test('a body shortcut called after dispatch does not change the sent request when retries are disabled', async t => {4319+ const requests: Request[] = [];4320+ let markFetchStarted: () => void;4321+ let releaseFetch: () => void;4322+4323+ const fetchStarted = new Promise<void>(resolve => {4324+ markFetchStarted = resolve;4325+ });4326+ const fetchGate = new Promise<void>(resolve => {4327+ releaseFetch = resolve;4328+ });4329+4330+ const promise = ky('https://example.com', {4331+ retry: 0,4332+ async fetch(request) {4333+ requests.push(request as Request);4334+ markFetchStarted!();4335+ await fetchGate;4336+ return new Response('{"ok":true}');4337+ },4338+ });4339+4340+ await fetchStarted;4341+ const jsonPromise = promise.json();4342+ releaseFetch!();4343+ t.is(JSON.stringify(await jsonPromise), '{"ok":true}');4344+4345+ t.is(requests.length, 1);4346+ t.is(requests[0]!.headers.get('accept'), null);4347+});modified:test/prefix.ts+6 added-23 removed
8 unmodified lines9 });10 const child = parent.extend({prefix: undefined});11 12 t.is(await parent('users').text(), 'https://example.com/api/users');13- t.throws(() => {14- void child('users');15- }, {instanceOf: TypeError});13+ await t.throwsAsync(child('users'), {instanceOf: TypeError});14 t.is(await child('https://example.org/users').text(), 'https://example.org/users');15 t.is(await parent('users').text(), 'https://example.com/api/users');16 });17 40 unmodified lines58 ),59 ).text(),60 '/foo/bar',61 );64- t.throws(65- () => {66- void ky(`${server.url}/unicorn`, {prefixUrl: ''});67- },62+ await t.throwsAsync(ky(`${server.url}/unicorn`, {prefixUrl: ''}),63 {64 message: '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',65 },66 );72- t.throws(73- () => {74- void ky(`${server.url}/unicorn`, {prefixUrl: undefined});75- },67+ await t.throwsAsync(ky(`${server.url}/unicorn`, {prefixUrl: undefined}),68 {69 message: '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',70 },71 );72 81- t.throws(82- () => {83- void ky('/unicorn', {prefixUrl: `${server.url}/api`});84- },73+ await t.throwsAsync(ky('/unicorn', {prefixUrl: `${server.url}/api`}),74 {75 message: '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',76 },77 );89- t.throws(90- () => {91- void ky(new Request(`${server.url}/unicorn`), {prefixUrl: `${server.url}/api`});92- },78+ await t.throwsAsync(ky(new Request(`${server.url}/unicorn`), {prefixUrl: `${server.url}/api`}),79 {80 message: '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',81 },82 );97- t.throws(98- () => {99- void ky(new URL(`${server.url}/unicorn`), {prefixUrl: `${server.url}/api`});100- },83+ await t.throwsAsync(ky(new URL(`${server.url}/unicorn`), {prefixUrl: `${server.url}/api`}),84 {85 message: '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',86 },87 );1 unmodified linemodified:test/response-size.ts+8 added-10 removed
17 unmodified lines18 });19 }20 21 for (const maxResponseSize of [-1, 1.5, Number.NaN, Number.NEGATIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1, '4', null]) {22- test(`rejects invalid maxResponseSize: ${String(maxResponseSize)}`, t => {23- t.throws(() => {24- void ky(url, {25- maxResponseSize: maxResponseSize as number,26- async fetch() {27- t.fail('Should validate before fetching');28- return new Response();29- },30- });22+ test(`rejects invalid maxResponseSize: ${String(maxResponseSize)}`, async t => {23+ await t.throwsAsync(ky(url, {24+ maxResponseSize: maxResponseSize as number,25+ async fetch() {26+ t.fail('Should validate before fetching');27+ return new Response();28+ },29+ }), {instanceOf: TypeError});31- }, {instanceOf: TypeError});30 });31 }32 33 test('counts bytes rather than characters and ignores Content-Length', async t => {564 unmodified linesmodified:test/retry.ts+121 added-156 removed
1024 unmodified lines1025 );1026 t.is(requestCount, 4);1027 });1028 1029-test('rejects invalid retry limits', t => {1029+test('rejects invalid retry limits', async t => {1030 for (const limit of [Number.NaN, Number.POSITIVE_INFINITY, -1, 1.5]) {1031- t.throws(() => {1032- void ky('https://example.com', {1033- retry: {1034- limit,1035- },1036- });1037- }, {1031+ // eslint-disable-next-line no-await-in-loop1032+ await t.throwsAsync(ky('https://example.com', {1033+ retry: {1034+ limit,1035+ },1036+ }), {1037 instanceOf: TypeError,1038 message: '`retry.limit` must be a finite, non-negative integer',1039 });1040 1042- t.throws(() => {1043- void ky('https://example.com', {retry: limit});1044- }, {1041+ // eslint-disable-next-line no-await-in-loop1042+ await t.throwsAsync(ky('https://example.com', {retry: limit}), {1043 instanceOf: TypeError,1044 message: '`retry.limit` must be a finite, non-negative integer',1045 });1046 }1047 });1048 1051-test('rejects non-number retry limits', t => {1049+test('rejects non-number retry limits', async t => {1050 for (const limit of ['NaN', true, null]) {1053- t.throws(() => {1054- void ky('https://example.com', {1055- retry: {1056- limit: limit as never,1057- },1058- });1059- }, {1051+ // eslint-disable-next-line no-await-in-loop1052+ await t.throwsAsync(ky('https://example.com', {1053+ retry: {1054+ limit: limit as never,1055+ },1056+ }), {1057 instanceOf: TypeError,1058 message: '`retry.limit` must be a finite, non-negative integer',1059 });1060 }119 unmodified lines1180 1181 t.is(requestCount, 3);1182 });1183 1187-test('rejects invalid retry option values', t => {1184+test('rejects invalid retry option values', async t => {1185 for (const retry of [true, 'NaN', []]) {1189- t.throws(() => {1190- void ky('https://example.com', {retry: retry as never});1191- }, {1186+ // eslint-disable-next-line no-await-in-loop1187+ await t.throwsAsync(ky('https://example.com', {retry: retry as never}), {1188 instanceOf: TypeError,1189 message: '`retry` must be a number or an object',1190 });1191 1196- t.throws(() => {1197- void ky('https://example.com', {1198- retry: retry as never,1199- hooks: {1200- init: [() => undefined],1201- },1202- });1203- }, {1192+ // eslint-disable-next-line no-await-in-loop1193+ await t.throwsAsync(ky('https://example.com', {1194+ retry: retry as never,1195+ hooks: {1196+ init: [() => undefined],1197+ },1198+ }), {1199 instanceOf: TypeError,1200 message: '`retry` must be a number or an object',1201 });1202 }364 unmodified lines1567 1568 t.deepEqual(initRetry, {methods: ['post'], limit: 3});1569 });1570 1576-test('retry - invalid numeric `retry` extending an object still throws', t => {1571+test('retry - invalid numeric `retry` extending an object still throws', async t => {1572 const client = ky.create({retry: {methods: ['post']}}).extend({retry: -1});1573 1579- t.throws(() => {1580- void client.post('https://example.com');1581- }, {1574+ await t.throwsAsync(client.post('https://example.com'), {1575 instanceOf: TypeError,1576 message: '`retry.limit` must be a finite, non-negative integer',1577 });1578 });407 unmodified lines1986 1987 test('throws when retry.methods is not an array', async t => {1988 const server = await createHttpTestServer(t);1989 1997- t.throws(() => {1998- void ky(server.url, {1999- retry: {2000- // @ts-expect-error2001- methods: 'get',2002- },2003- });1990+ await t.throwsAsync(ky(server.url, {1991+ retry: {1992+ // @ts-expect-error1993+ methods: 'get',1994+ },1995+ }), {message: 'retry.methods must be an array'});2004- });1996 2006- t.throws(() => {2007- void ky(server.url, {2008- retry: {2009- // @ts-expect-error2010- methods: 'get',2011- },2012- hooks: {2013- init: [() => undefined],2014- },2015- });1997+ await t.throwsAsync(ky(server.url, {1998+ retry: {1999+ // @ts-expect-error2000+ methods: 'get',2001+ },2002+ hooks: {2003+ init: [() => undefined],2004+ },2005+ }), {message: 'retry.methods must be an array'});2016- });2006 });2007 2008 test('throws when retry.statusCodes is not an array', async t => {2009 const server = await createHttpTestServer(t);2010 2022- t.throws(() => {2023- void ky(server.url, {2024- retry: {2025- // @ts-expect-error2026- statusCodes: 403,2027- },2028- });2011+ await t.throwsAsync(ky(server.url, {2012+ retry: {2013+ // @ts-expect-error2014+ statusCodes: 403,2015+ },2016+ }), {message: 'retry.statusCodes must be an array'});2029- });2017 2031- t.throws(() => {2032- void ky(server.url, {2033- retry: {2034- // @ts-expect-error2035- statusCodes: 403,2036- },2037- hooks: {2038- init: [() => undefined],2039- },2040- });2018+ await t.throwsAsync(ky(server.url, {2019+ retry: {2020+ // @ts-expect-error2021+ statusCodes: 403,2022+ },2023+ hooks: {2024+ init: [() => undefined],2025+ },2026+ }), {message: 'retry.statusCodes must be an array'});2041- });2027 });2028 2029 test('throws when retry.afterStatusCodes is not an array', async t => {2030 const server = await createHttpTestServer(t);2031 2047- t.throws(() => {2048- void ky(server.url, {2049- retry: {2050- // @ts-expect-error2051- afterStatusCodes: 503,2052- },2053- });2032+ await t.throwsAsync(ky(server.url, {2033+ retry: {2034+ // @ts-expect-error2035+ afterStatusCodes: 503,2036+ },2037+ }), {message: 'retry.afterStatusCodes must be an array'});2054- });2038 2056- t.throws(() => {2057- void ky(server.url, {2058- retry: {2059- // @ts-expect-error2060- afterStatusCodes: 503,2061- },2062- hooks: {2063- init: [() => undefined],2064- },2065- });2039+ await t.throwsAsync(ky(server.url, {2040+ retry: {2041+ // @ts-expect-error2042+ afterStatusCodes: 503,2043+ },2044+ hooks: {2045+ init: [() => undefined],2046+ },2047+ }), {message: 'retry.afterStatusCodes must be an array'});2066- });2048 });2049 2069-test('throws when retry array options are falsy non-arrays', t => {2050+test('throws when retry array options are falsy non-arrays', async t => {2051 for (const [key, value] of [2052 ['methods', 0],2053 ['statusCodes', false],2054 ['afterStatusCodes', null],2055 ] as const) {2056 const retry = {[key]: value};2057 2077- t.throws(() => {2078- void ky('https://example.com', {2079- retry: retry as never,2080- });2081- });2058+ // eslint-disable-next-line no-await-in-loop2059+ await t.throwsAsync(ky('https://example.com', {2060+ retry: retry as never,2061+ }), {message: `retry.${key} must be an array`});2062 2083- t.throws(() => {2084- void ky('https://example.com', {2085- retry: retry as never,2086- hooks: {2087- init: [() => undefined],2088- },2089- });2090- });2063+ // eslint-disable-next-line no-await-in-loop2064+ await t.throwsAsync(ky('https://example.com', {2065+ retry: retry as never,2066+ hooks: {2067+ init: [() => undefined],2068+ },2069+ }), {message: `retry.${key} must be an array`});2070 }2071 });2072 2073 test('request hooks cannot mutate default retry status codes', async t => {1329 unmodified lines3403 t.false(fetchCalled);3404 });3405 3406 test('totalTimeout exceeding maxSafeTimeout throws RangeError', async t => {3428- await t.throwsAsync(3429- ky('https://example.com', {3430- fetch: async () => new Response('ok'),3431- totalTimeout: 2_147_483_648,3432- }).text(),3433- {3434- instanceOf: RangeError,3435- },3436- );3407+ await t.throwsAsync(ky('https://example.com', {3408+ fetch: async () => new Response('ok'),3409+ totalTimeout: 2_147_483_648,3410+ }), {3411+ instanceOf: RangeError,3412+ });3413 });3414 3415 test('totalTimeout expires mid-delay between retries', async t => {3416 let requestCount = 0;1352 unmodified lines4769 4770 t.is(error.message, 'rewritten: NetworkError');4771 });4772 4797-// Both limits feed `Math.min()`, so a non-number turns the retry delay into `NaN`, which `setTimeout()` clamps to4798-// 1ms. A `Retry-After: 1` header would then be retried almost immediately, which is the thundering herd those4799-// options exist to prevent.4800-test('rejects non-numeric or negative `maxRetryAfter` and `backoffLimit`', t => {4773+// Both limits feed `Math.min()`, so a non-number turns the retry delay into `NaN`, which `setTimeout()` clamps to 1ms. A `Retry-After: 1` header would then be retried almost immediately, which is the thundering herd those options exist to prevent.4774+test('rejects non-numeric or negative `maxRetryAfter` and `backoffLimit`', async t => {4775 for (const key of ['maxRetryAfter', 'backoffLimit'] as const) {4776 for (const value of ['1000', Number.NaN, -1, {}, null] as unknown[]) {4777 // `null` is nullish, so it selects the default instead of being rejected.4778 if (value === null) {1 unmodified line4780 }4781 4782 const retry: Record<string, unknown> = {[key]: value};4783 4810- t.throws(() => {4811- void ky('https://example.com', {retry: retry as never});4812- }, {4784+ // eslint-disable-next-line no-await-in-loop4785+ await t.throwsAsync(ky('https://example.com', {retry: retry as never}), {4786 instanceOf: TypeError,4787 message: `\`retry.${key}\` must be a non-negative number or \`Infinity\``,4788 }, `${key}: ${JSON.stringify(value)}`);4789 }4790 }4791 });4792 4820-// Validating up front means the misconfiguration is reported before the request is sent, instead of replacing the4821-// `HTTPError` with a `TypeError` from deep inside the retry delay calculation.4822-test('a rejected retry limit is reported before the request is sent', t => {4793+// Validating up front means the misconfiguration is reported before the request is sent, instead of replacing the `HTTPError` with a `TypeError` from deep inside the retry delay calculation.4794+test('a rejected retry limit is reported before the request is sent', async t => {4795 for (const key of ['maxRetryAfter', 'backoffLimit'] as const) {4796 let requestCount = 0;4797 const retry: Record<string, unknown> = {[key]: 'soon'};4798 4827- t.throws(() => {4828- void ky('https://example.com', {4829- async fetch() {4830- requestCount++;4831- return new Response(null, {status: 500});4832- },4833- retry: retry as never,4834- });4835- }, {4799+ // eslint-disable-next-line no-await-in-loop4800+ await t.throwsAsync(ky('https://example.com', {4801+ async fetch() {4802+ requestCount++;4803+ return new Response(null, {status: 500});4804+ },4805+ retry: retry as never,4806+ }), {4807 instanceOf: TypeError,4808 message: `\`retry.${key}\` must be a non-negative number or \`Infinity\``,4809 }, key);4810 4811 t.is(requestCount, 0, key);4812 }4813 });4814 4844-// A non-function `delay`/`shouldRetry` used to be called blindly, so the resulting `TypeError` replaced the4845-// `HTTPError` that actually caused the retry. Validate the shapes up front instead.4846-test('rejects non-function `retry.delay`, `retry.shouldRetry` and `retry.jitter`', t => {4815+// A non-function `delay`/`shouldRetry` used to be called blindly, so the resulting `TypeError` replaced the `HTTPError` that actually caused the retry. Validate the shapes up front instead.4816+test('rejects non-function `retry.delay`, `retry.shouldRetry` and `retry.jitter`', async t => {4817 for (const [key, value] of [4818 ['delay', 1000],4819 ['shouldRetry', true],4820 ['jitter', 'yes'],4821 ['jitter', 1],4822 ] as Array<[string, unknown]>) {4823 const retry: Record<string, unknown> = {[key]: value};4824 4855- t.throws(() => {4856- void ky('https://example.com', {retry: retry as never});4857- }, {4825+ // eslint-disable-next-line no-await-in-loop4826+ await t.throwsAsync(ky('https://example.com', {retry: retry as never}), {4827 instanceOf: TypeError,4828 message: `\`retry.${key}\` must be ${key === 'jitter' ? 'a boolean or a function' : 'a function'}`,4829 }, `${key}: ${JSON.stringify(value)}`);4830 }25 unmodified lines4856 message: '`retry.delay` must return a non-negative number or `Infinity`',4857 });4858 });4859 4891-// Array-shaped retry options were only checked for being arrays, so a mistyped entry silently disabled retrying4892-// with no indication of why.4893-test('rejects non-string `retry.methods` entries and non-number status code entries', t => {4860+// Array-shaped retry options were only checked for being arrays, so a mistyped entry silently disabled retrying with no indication of why.4861+test('rejects non-string `retry.methods` entries and non-number status code entries', async t => {4862 for (const [key, value] of [4863 ['methods', ['GET', 5]],4864 ['statusCodes', ['429']],4865 ['statusCodes', [429.5]],2 unmodified lines4868 ['afterStatusCodes', [Number.NaN]],4869 ] as Array<[string, unknown]>) {4870 const retry: Record<string, unknown> = {[key]: value};4871 4904- t.throws(() => {4905- void ky('https://example.com', {retry: retry as never});4906- }, {4872+ // eslint-disable-next-line no-await-in-loop4873+ await t.throwsAsync(ky('https://example.com', {retry: retry as never}), {4874 instanceOf: TypeError,4875 message: `\`retry.${key}\` must only contain ${key === 'methods' ? 'strings' : 'numbers'}`,4876 }, `${key}: ${JSON.stringify(value)}`);4877 }4878 });4879 4913-test('a rejected retry list entry is reported before the request is sent', t => {4880+test('a rejected retry list entry is reported before the request is sent', async t => {4881 let requestCount = 0;4882 const retry: Record<string, unknown> = {statusCodes: ['500']};4883 4917- t.throws(() => {4918- void ky('https://example.com', {4919- async fetch() {4920- requestCount++;4921- return new Response(null, {status: 500});4922- },4923- retry: retry as never,4924- });4884+ await t.throwsAsync(ky('https://example.com', {4885+ async fetch() {4886+ requestCount++;4887+ return new Response(null, {status: 500});4888+ },4889+ retry: retry as never,4890+ }), {4925- }, {4891 instanceOf: TypeError,4892 message: '`retry.statusCodes` must only contain numbers',4893 });4894 t.is(requestCount, 0);297 unmodified linesmodified:test/validation.ts+125 added-79 removed
1 import test from 'ava';2-import ky from '../source/index.js';2+import ky, {type ResponsePromise} from '../source/index.js';3 4 const okFetch = async () => new Response('ok');5 6-// `timeout` and `totalTimeout` are documented as milliseconds or `false`. Anything else used to be passed7-// straight to `setTimeout()`, which clamps it to ~1ms, or was silently ignored, so the request never got the8-// timeout the caller asked for. `null` is left out: it is nullish, so it selects the default.6+// `timeout` and `totalTimeout` are documented as milliseconds or `false`. Anything else used to be passed straight to `setTimeout()`, which clamps it to ~1ms, or was silently ignored, so the request never got the timeout the caller asked for. `null` is not accepted either, so it is reported rather than selecting the default.7 test('rejects non-numeric and negative `timeout` values', async t => {10- for (const timeout of ['1000', Number.NaN, -1, -0.5, {}] as unknown[]) {8+ for (const timeout of ['1000', Number.NaN, -1, -0.5, {}, null] as unknown[]) {9 // eslint-disable-next-line no-await-in-loop12- await t.throwsAsync(13- ky('https://example.com', {timeout: timeout as never, fetch: okFetch}).text(),10+ await t.throwsAsync(ky('https://example.com', {timeout: timeout as never, fetch: okFetch}),11 {12 name: 'TypeError',13 message: 'The `timeout` option must be a non-negative number or `false`',14 },2 unmodified lines17 }18 });19 20 test('rejects non-numeric and negative `totalTimeout` values', async t => {24- for (const totalTimeout of ['1000', Number.NaN, -1, -0.5, {}] as unknown[]) {21+ for (const totalTimeout of ['1000', Number.NaN, -1, -0.5, {}, null] as unknown[]) {22 // eslint-disable-next-line no-await-in-loop26- await t.throwsAsync(27- ky('https://example.com', {totalTimeout: totalTimeout as never, fetch: okFetch}).text(),23+ await t.throwsAsync(ky('https://example.com', {totalTimeout: totalTimeout as never, fetch: okFetch}),24 {25 name: 'TypeError',26 message: 'The `totalTimeout` option must be a non-negative number or `false`',27 },1 unmodified line29 );30 }31 });32 37-test('treats a nullish timeout as absent', async t => {38- t.is(await ky('https://example.com', {timeout: null as never, totalTimeout: null as never, fetch: okFetch}).text(), 'ok');33+test('treats an `undefined` timeout as absent', async t => {34+ t.is(await ky('https://example.com', {timeout: undefined, totalTimeout: undefined, fetch: okFetch}).text(), 'ok');35 });36 37 test('rejects `timeout` and `totalTimeout` above the maximum safe value', async t => {38 for (const option of ['timeout', 'totalTimeout'] as const) {43- // eslint-disable-next-line no-await-in-loop44- await t.throwsAsync(45- ky('https://example.com', {[option]: 2_147_483_648, fetch: okFetch}).text(),46- {47- instanceOf: RangeError,48- message: `The \`${option}\` option cannot be greater than 2147483647`,49- },50- `option: ${option}`,51- );39+ for (const value of [2_147_483_648, Number.POSITIVE_INFINITY]) {40+ // eslint-disable-next-line no-await-in-loop41+ await t.throwsAsync(ky('https://example.com', {[option]: value, fetch: okFetch}),42+ {43+ instanceOf: RangeError,44+ message: `The \`${option}\` option cannot be greater than 2147483647`,45+ },46+ `${option}: ${value}`,47+ );48+ }49 }50 });51 52 test('accepts `false`, `0` and non-negative numbers for the timeout options', async t => {1 unmodified line54 t.is(await ky('https://example.com', {timeout: 0, totalTimeout: 5000, fetch: async () => new Response('a')}).text(), 'a');55 });56 57 test('rejects invalid timeout values set from an `init` hook', async t => {61- await t.throwsAsync(62- ky('https://example.com', {63- fetch: okFetch,64- hooks: {65- init: [options => {66- options.timeout = 'soon' as never;67- }],58+ await t.throwsAsync(ky('https://example.com', {59+ fetch: okFetch,60+ hooks: {61+ init: [options => {62+ options.timeout = 'soon' as never;63+ }],68- },69- }).text(),70- {71- name: 'TypeError',72- message: 'The `timeout` option must be a non-negative number or `false`',64 },65+ }), {66+ name: 'TypeError',67+ message: 'The `timeout` option must be a non-negative number or `false`',74- );68+ });69 });70 77-// These callbacks are called directly, so a non-function value surfaced as a runtime error naming Ky's own78-// internals (`this[#options].stringifyJson`, `initHookOptions.parseJson`) instead of the option the user set, and79-// only once the request had already been built. The constructor calls `stringifyJson` itself, so that one has to be80-// checked before anything else happens.81-test('rejects non-function callback options', t => {71+// These callbacks are called directly, so a non-function value surfaced as a runtime error naming Ky's own internals (`this[#options].stringifyJson`, `initHookOptions.parseJson`) instead of the option the user set, and only once the request had already been built. The constructor calls `stringifyJson` itself, so that one has to be checked before anything else happens.72+test('rejects non-function callback options', async t => {73 for (const [key, value] of [74 ['parseJson', 'x'],75 ['stringifyJson', 5],76 ['fetch', 'x'],77+ ['fetch', null],78 ['onDownloadProgress', 'x'],79 ['onUploadProgress', 'x'],80 ] as Array<[string, unknown]>) {81 const options: Record<string, unknown> = {[key]: value};82 91- t.throws(() => {92- void ky('https://example.com', options as never);93- }, {83+ // eslint-disable-next-line no-await-in-loop84+ await t.throwsAsync(ky('https://example.com', options as never), {85 name: 'TypeError',86 message: `The \`${key}\` option must be a function`,87 }, `${key}: ${JSON.stringify(value)}`);88 }89 });90 100-test('rejects a non-function `stringifyJson` before it is called', t => {101- t.throws(() => {102- void ky.post('https://example.com', {103- json: {a: 1},104- stringifyJson: 'nope' as never,105- fetch: okFetch,106- });91+test('rejects a non-function `stringifyJson` before it is called', async t => {92+ await t.throwsAsync(ky.post('https://example.com', {93+ json: {a: 1},94+ stringifyJson: 'nope' as never,95+ fetch: okFetch,96+ }), {107- }, {97 name: 'TypeError',98 message: 'The `stringifyJson` option must be a function',99 });100 });101 113-test('rejects a `throwHttpErrors` value that is neither a boolean nor a function', t => {114- for (const value of ['yes', 1, {}] as unknown[]) {102+test('rejects a `throwHttpErrors` value that is neither a boolean nor a function', async t => {103+ for (const value of ['yes', 1, {}, null] as unknown[]) {104 const options: Record<string, unknown> = {105 throwHttpErrors: value,106 fetch: async () => new Response('server error', {status: 500}),107 };108 120- t.throws(() => {121- void ky('https://example.com', options as never);122- }, {109+ // eslint-disable-next-line no-await-in-loop110+ await t.throwsAsync(ky('https://example.com', options as never), {111 name: 'TypeError',112 message: 'The `throwHttpErrors` option must be a boolean or a function',113 }, `throwHttpErrors: ${JSON.stringify(value)}`);114 }7 unmodified lines122 123 t.is(await ky('https://example.com', options as never).text(), 'server error');124 });125 138-// The `input` type check ran after the options were built, so a nullish input dereferenced `.headers` first and139-// reported an internal TypeError instead of the option the caller got wrong.140-test('a nullish or non-string `input` reports the input error', t => {126+// The `input` type check ran after the options were built, so a nullish input dereferenced `.headers` first and reported an internal TypeError instead of the option the caller got wrong.127+test('a nullish or non-string `input` reports the input error', async t => {128 for (const input of [null, undefined, 5, {}, true] as unknown[]) {142- t.throws(() => {143- void ky(input as never, {fetch: okFetch});144- }, {129+ // eslint-disable-next-line no-await-in-loop130+ await t.throwsAsync(ky(input as never, {fetch: okFetch}), {131 name: 'TypeError',132 message: '`input` must be a string, URL, or Request',133 }, `input: ${String(input)}`);134 }135 });136 151-// `onDownloadProgress` was type-checked at the very end of the pipeline, so an invalid value ran the whole request152-// and only then reported the typo, leaving the response body with nobody able to release it.153-test('rejects a non-function `onDownloadProgress` before the request is sent', t => {137+// `onDownloadProgress` was type-checked at the very end of the pipeline, so an invalid value ran the whole request and only then reported the typo, leaving the response body with nobody able to release it.138+test('rejects a non-function `onDownloadProgress` before the request is sent', async t => {139 let fetchCalled = false;140 let beforeRequestCalls = 0;141 157- t.throws(() => {158- void ky('https://example.com', {159- onDownloadProgress: 'x' as never,160- retry: 0,161- hooks: {162- beforeRequest: [() => {163- beforeRequestCalls++;164- }],165- },166- async fetch() {167- fetchCalled = true;168- return new Response('ok');169- },170- });142+ await t.throwsAsync(ky('https://example.com', {143+ onDownloadProgress: 'x' as never,144+ retry: 0,145+ hooks: {146+ beforeRequest: [() => {147+ beforeRequestCalls++;148+ }],149+ },150+ async fetch() {151+ fetchCalled = true;152+ return new Response('ok');153+ },154+ }), {171- }, {155 name: 'TypeError',156 message: 'The `onDownloadProgress` option must be a function',157 });158 159 t.false(fetchCalled);160 t.is(beforeRequestCalls, 0);161 });162+163+// `ky()` returns a promise, so errors while setting up the request reject it, the same way `fetch()` reports them, instead of also throwing synchronously.164+test('setup errors reject the returned promise and every body method', async t => {165+ const setups: Array<[string, unknown, Record<string, unknown>]> = [166+ ['invalid option', 'https://example.com', {timeout: -1}],167+ ['invalid input', 42, {}],168+ ['invalid merged option', 'https://example.com', {hooks: 'none'}],169+ ['throwing `init` hook', 'https://example.com', {170+ hooks: {171+ init: [() => {172+ throw new Error('init failed');173+ }],174+ },175+ }],176+ ];177+178+ for (const [label, input, options] of setups) {179+ let responsePromise: ResponsePromise | undefined;180+ t.notThrows(() => {181+ responsePromise = ky(input as never, {...options, fetch: okFetch});182+ }, `${label}`);183+184+ // eslint-disable-next-line no-await-in-loop185+ const error = await t.throwsAsync(responsePromise!, undefined, `${label}`);186+187+ for (const method of ['json', 'text', 'arrayBuffer', 'blob', 'formData'] as const) {188+ // eslint-disable-next-line no-await-in-loop189+ t.is(await t.throwsAsync(responsePromise![method]()), error, `${label}: ${method}`);190+ }191+ }192+});193+194+// Option merging only checked `hooks` when it was an object, and replaced an invalid `retry`, so a later layer hid a `null` or another bad shape instead of reporting it.195+test('rejects a bad `hooks` or `retry` while merging, before a later layer can hide it', async t => {196+ for (const hooks of [null, 'nope', []] as unknown[]) {197+ t.throws(() => ky.create({hooks: hooks as never}), {198+ instanceOf: TypeError,199+ message: 'The `hooks` option must be an object',200+ }, `hooks: ${JSON.stringify(hooks)}`);201+ }202+203+ for (const retry of [null, 'nope', []] as unknown[]) {204+ t.throws(() => ky.create({retry: retry as never}), {205+ instanceOf: TypeError,206+ message: '`retry` must be a number or an object',207+ }, `retry: ${JSON.stringify(retry)}`);208+ }209+210+ await t.throwsAsync(ky.extend({fetch: okFetch})('https://example.com', {hooks: null as never}), {211+ name: 'TypeError',212+ message: 'The `hooks` option must be an object',213+ });214+});215+216+test('rejects a `retry.retryOnTimeout` that is not a boolean', async t => {217+ for (const retryOnTimeout of [null, 'false', 0] as unknown[]) {218+ // eslint-disable-next-line no-await-in-loop219+ await t.throwsAsync(ky('https://example.com', {retry: {retryOnTimeout: retryOnTimeout as never}, fetch: okFetch}), {220+ name: 'TypeError',221+ message: '`retry.retryOnTimeout` must be a boolean',222+ }, `retryOnTimeout: ${JSON.stringify(retryOnTimeout)}`);223+ }224+});modified:test-d/hooks.ts-7 removed
2 unmodified lines3 4 const hookList = [() => undefined] as const;5 const beforeErrorHook: BeforeErrorHook = ({error}) => error;6 const beforeErrorHooks = [beforeErrorHook] as const;7-const exampleKey = String('example');7 const hooks: Hooks = {8 init: hookList,9 beforeRequest: hookList,10 beforeRetry: hookList,4 unmodified lines15 expectTypeOf(hooks).toEqualTypeOf<Hooks>();16 17 const initHook: InitHook = options => {18 options.hooks?.beforeRequest?.push(() => undefined);20- expectTypeOf(options.headers).toEqualTypeOf<Record<string, string | undefined>>();21- expectTypeOf(options.context).toEqualTypeOf<Record<string, unknown>>();22- options.headers = new Headers();23- options.headers[exampleKey] = 'value';24- options.context = undefined;25- options.context[exampleKey] = 'value';19 if (options.hooks) {20 options.hooks.beforeRequest = undefined;21 }22 };2 unmodified linesmodified:AGENTS.md+1 added-1 removed
1 # Conventions2 3-- Prefer `undefined` for absent values. Do not add special handling for `null`.3+- `null` is not an accepted value anywhere in this project. Options, hook lists, arguments and hook state all use `undefined` to mean absent, and passing `null` is a mistake that should be reported as one rather than quietly treated as `undefined`. Do not add `null`-tolerant branches, do not widen a type to include `null`, and do not default a `null` parameter to another value. When a caller can plausibly write `null`, the fix is a clear error that names the option, not a fallback. The one exception is the `signal` option, which accepts `null` for `RequestInit` compatibility and treats it as absent.modified:readme.md+8 added-8 removed
96 unmodified lines97 Returns a [`Response` object](https://developer.mozilla.org/en-US/docs/Web/API/Response) with [`Body` methods](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#body) added for convenience. So you can, for example, call `ky.get(input).json()` directly without having to await the `Response` first. When called like that, an appropriate `Accept` header will be set depending on the body method used. Unlike the `Body` methods of `window.fetch`, these will throw an `HTTPError` if the response status is not in the range of `200...299`. Note that `.json()` will throw if the body is empty, as it cannot be parsed. However, you can use the `parseJson` option to add custom handling for empty bodies.98 99 Available body shortcuts: `.json()`, `.text()`, `.formData()`, `.arrayBuffer()`, `.blob()`, and `.bytes()`. The `.bytes()` shortcut is only present when the runtime supports `Response.prototype.bytes()`.100 101+Invalid options, an invalid `input`, and an error thrown by an `init` hook reject the returned promise instead of throwing, the same way `fetch()` reports them. They are not passed to `beforeError` hooks, because no request was made.102+103 ```js104 import ky from 'ky';105 106 const user = await ky('/api/user').json();296 unmodified lines403 404 Type: `number | false`\405 Default: `10000`406 405-Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Ky shortcut methods also use this value as a separate timeout for reading the response body. Must be a non-negative number no greater than 2147483647, or `false`; anything else throws a `TypeError`. See also [`totalTimeout`](#totaltimeout).407+Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Ky shortcut methods also use this value as a separate timeout for reading the response body. Must be a non-negative number or `false`, or a `TypeError` is thrown. A value greater than 2147483647, `Infinity` included, throws a `RangeError`. See also [`totalTimeout`](#totaltimeout).408 409 If set to `false`, there will be no per-attempt timeout.410 411 If the signal you passed in is aborted while a body method is reading, or just after the read finished, the body method rejects with the abort reason rather than resolving with the bytes that already arrived.2 unmodified lines414 415 Type: `number | false`\416 Default: `false`417 416-Overall timeout in milliseconds for the entire operation, including retries and delays. Throws a `TimeoutError` if exceeded. Must be a non-negative number no greater than 2147483647, or `false`; anything else throws a `TypeError`.418+Overall timeout in milliseconds for the entire operation, including retries and delays. Throws a `TimeoutError` if exceeded. Must be a non-negative number or `false`, or a `TypeError` is thrown. A value greater than 2147483647, `Infinity` included, throws a `RangeError`.419 420 `beforeError` hooks run after an error is produced and are not bounded by `totalTimeout`.421 422 If set to `false` or not specified, there is no overall timeout.56 unmodified lines479 480 Type: `Function[]`\481 Default: `[]`482 481-This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option is always a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.483+This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option starts as a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.484 483-Unlike other hooks, `init` hooks are synchronous. Any error thrown will propagate synchronously and will not be caught by `beforeError` hooks.485+Ky gives the hook its own copies of `headers`, `context`, `json`, `searchParams` and `retry`, so changing them in place only affects the current request. The `context` copy is deep, so when an instance has an `init` hook, nested `context` values are not shared across requests. The `body` option is not copied, so mutating a `FormData` or `URLSearchParams` body in place changes your own object and repeats on every request from the same instance. Assign a new instance instead, as shown in [Modifying FormData in hooks](#modifying-formdata-in-hooks). A value that a hook assigns is used as is, so assign a new object rather than one that you change later.486 485-The `body` option is the exception: it is passed through by reference, so mutating a `FormData` or `URLSearchParams` body in place changes your own object and repeats on every request from the same instance. Replace `options.body` with a new instance instead, the way the [`beforeRequest`](#hooksbeforerequest) workflow does.487+Unlike other hooks, `init` hooks are synchronous. An error thrown by one rejects the returned promise and is not passed to `beforeError` hooks.488 489 A common use case is to add a search parameter to every request:490 491 ```js399 unmodified lines891 Type: `Function`\892 Default: `fetch`893 894 User-defined `fetch` function.893-Has to be fully compatible with the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) standard.895+Has to be fully compatible with the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) standard. It must resolve with a `Response`, or a `TypeError` is thrown.896 897 Use-cases:898 1. Use the `fetch` wrapper function provided by some frameworks that use server-side rendering (SSR).899 2. Add custom instrumentation or logging to all requests.30 unmodified lines930 - Pass serverless environment bindings (e.g., Cloudflare Workers)931 932 **Note:** Context is shallow merged. Top-level properties are merged, but nested objects are replaced. Only enumerable properties are copied.933 932-**Note:** Each request gets its own deep copy of the context, so a hook that mutates a nested plain object or array cannot write back to the instance defaults or to the object you passed in. Non-plain values such as class instances are shared by reference. A hook that caches data in the context, for example with `options.context.token ??= await getToken()`, therefore recomputes it once per request rather than once per instance.933-934 ```js935 import ky from 'ky';936 937 // Pass data to hooks990 unmodified lines