Restore the retry-only marker condition and cover the remaining cases
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 58233f1 · Browse files · 9 files·+329 added−277 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+329 added−277 removed
- tests:+242 added−49 removed
- other:+87 added−228 removed
Provenance
- Commit
692c435- Tree
362825f- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
58233f1
9 files changed+329 added−277 removed
modified:source/core/Ky.ts+85 added-226 removed
35 unmodified lines36 import delay from '../utils/delay.js';37 import {type ObjectEntries} from '../utils/types.js';38 import {findUnknownOptions, hasSearchParameters} from '../utils/options.js';39 import isRawNetworkError from '../utils/is-network-error.js';40-import {isError} from '../utils/is.js';40 import {42- isHTTPError, isNetworkError, isTimeoutError, isResponseSizeError, isForceRetryError,41+ isHTTPError, isNetworkError, isTimeoutError, isResponseSizeError,42 } from '../utils/type-guards.js';43 import {44 calculateRetryTimingDelay,45 getRetryTimingHeader,1 unmodified line47 import {48 maxSafeTimeout,49 responseTypes,50 stop,52- isRetryMarker,51+ RetryMarker,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';83-const missingResponseMessage = 'The request resolved without a response, so there is no body to read.'84- + ' Returning `ky.stop` from a `beforeRetry` hook, or a custom `fetch` that resolves with nothing, both do that.'85- + ' Throw from the hook instead of returning `ky.stop`.';82 87-// Both timeout options are milliseconds or `false`. A non-finite or negative value used to reach `setTimeout()`,88-// which silently clamps it to ~1ms, or to be ignored entirely when `totalTimeout` was not a number.89-const validateTimeoutOption = (value: unknown, name: 'timeout' | 'totalTimeout'): void => {90- if (value === false) {91- return;92- }93-94- if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {95- throw new TypeError(`The \`${name}\` option must be a non-negative number or \`false\``);96- }97-98- if (value > maxSafeTimeout) {99- throw new RangeError(`The \`${name}\` option cannot be greater than ${maxSafeTimeout}`);100- }101-};102-103-// These callbacks are called directly, so a non-function value otherwise surfaces as a runtime error naming Ky's104-// own internals rather than the option the caller set.105-const validateCallbackOptions = (options: Record<string, unknown>): void => {106- for (const key of ['parseJson', 'stringifyJson', 'fetch', 'onDownloadProgress'] as const) {107- if (options[key] !== undefined && typeof options[key] !== 'function') {108- throw new TypeError(`The \`${key}\` option must be a function`);109- }110- }111-112- const {throwHttpErrors} = options;113- if (typeof throwHttpErrors !== 'boolean' && typeof throwHttpErrors !== 'function') {114- throw new TypeError('The `throwHttpErrors` option must be a boolean or a function');115- }116-};117-83 const cloneRetryOptions = (retry: RetryOptions | number): RetryOptions | number => {84 if (retry === null || typeof retry !== 'object' || Array.isArray(retry)) {85 return retry as RetryOptions | number;86 }45 unmodified lines132 return cloneShallow(searchParameters) as SearchParamsOption | undefined;133 };134 135 // Shallow-clone mutable option properties so init hook mutations don't leak across requests.171-// Every one of them also copies on assignment, so a hook that replaces the value with an object of its own cannot172-// accumulate mutations on that object across requests. Non-plain values (functions, class instances) are kept by173-// reference, matching how option merging treats them as whole values.136 function cloneInitHookOptions(options: Options): InitOptions {137 let headers = mergeHeaderContainers({}, options.headers ?? {});138 let context = cloneDeep(options.context) ?? {};177- let json = cloneDeep(options.json);178- let searchParameters = cloneSearchParametersForInitHook(options.searchParams);179- let retry = options.retry === undefined ? undefined : cloneRetryOptions(options.retry);139+ const clonedOptions: Options = {140+ ...options,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.142+ json: cloneDeep(options.json),143+ searchParams: cloneSearchParametersForInitHook(options.searchParams),144+ };145 181- const clonedOptions: Options = {...options};182-146 Object.defineProperties(clonedOptions, {147 headers: {148 enumerable: true,149 configurable: true,10 unmodified lines160 get() {161 return context;162 },163 set(value: Record<string, unknown> | undefined) {201- context = cloneDeep(value) ?? {};164+ context = value ?? {};165 },166 },204- json: {205- enumerable: true,206- configurable: true,207- get() {208- return json;209- },210- set(value: unknown) {211- json = cloneDeep(value);212- },213- },214- searchParams: {215- enumerable: true,216- configurable: true,217- get() {218- return searchParameters;219- },220- set(value: SearchParamsOption | undefined) {221- searchParameters = cloneSearchParametersForInitHook(value);222- },223- },224- retry: {225- enumerable: true,226- configurable: true,227- get() {228- return retry;229- },230- set(value: Options['retry']) {231- retry = value === undefined ? undefined : cloneRetryOptions(value);232- },233- },167 });168 169+ if (options.retry !== undefined) {170+ clonedOptions.retry = cloneRetryOptions(options.retry);171+ }172+173 return clonedOptions as InitOptions;174 }175 176 const validateJsonWithSchema = async (jsonValue: unknown, schema: StandardSchemaV1): Promise<unknown> => {37 unmodified lines214 215 const ky = new Ky(input, initHookOptions);216 217 const function_ = async (): Promise<Response | void> => {281- validateTimeoutOption(ky.#options.totalTimeout, 'totalTimeout');282- validateTimeoutOption(ky.#options.timeout, 'timeout');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+226 // Delay the fetch so that body method shortcuts can set the Accept header227 await Promise.resolve();228 const beforeRequestResponse = await ky.#runBeforeRequestHooks();229 if (beforeRequestResponse !== undefined) {4 unmodified lines234 let responseFromHook = beforeRequestResponse !== undefined235 || ky.#consumeReturnedResponseFromBeforeRetryHook();236 237 for (;;) {296- // A nullish value means a hook stopped the flow, or a custom `fetch` resolved with nothing. The caller297- // sees it normalized to `undefined` either way.238+ // `undefined` means a hook stopped the flow without providing a response.239 // Non-native Responses still continue through Ky if they pass `isResponseInstance()`.299- if (response === undefined || response === null) {240+ if (response === undefined) {241 return response;242 }243 244 if (isResponseInstance(response)) {245 try {246 // eslint-disable-next-line no-await-in-loop247 response = await ky.#runAfterResponseHooks(response);248 } catch (error) {308- if (!isForceRetryError(error)) {249+ if (!(error instanceof ForceRetryError)) {250 throw error;251 }252 253 // eslint-disable-next-line no-await-in-loop10 unmodified lines264 265 const currentResponse: Response = response;266 267 // 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.327- if (!currentResponse.ok && currentResponse.type !== 'opaque' && ky.#shouldThrowHttpErrors(currentResponse)) {268+ if (!currentResponse.ok && currentResponse.type !== 'opaque' && (269+ typeof ky.#options.throwHttpErrors === 'function'270+ ? ky.#options.throwHttpErrors(currentResponse.status)271+ : ky.#options.throwHttpErrors272+ )) {273 // `request` must reflect the request that actually failed, but `options` stays as Ky's274 // normalized options snapshot. Replacement `Request` instances do not preserve the275 // original `BodyInit`, so trying to make `options` mirror arbitrary requests would be lossy.276 const httpError: HTTPError = new HTTPError(currentResponse, ky.#getResponseRequest(currentResponse), ky.#getNormalizedOptions());27 unmodified lines304 ky.#decorateResponse(response);305 306 // If `onDownloadProgress` is passed, it uses the stream API internally307 if (ky.#options.onDownloadProgress) {308+ if (typeof ky.#options.onDownloadProgress !== 'function') {309+ throw new TypeError('The `onDownloadProgress` option must be a function');310+ }311+312 if (!supportsResponseStreams) {313 throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');314 }315 20 unmodified lines336 if (originalRequest?.body !== response?.body) {337 ky.#cancelBody(originalRequest?.body ?? undefined);338 }339 391- // Only cancel the current request body if it's distinct from the original (i.e. it was cloned for392- // retries). `#originalRequest` is only set once a request is handed to fetch, so a pipeline that393- // never started, for example one that failed validation, leaves the caller's own body alone.394- if (originalRequest && ky.request !== originalRequest && ky.request.body !== response?.body) {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) {342 ky.#cancelBody(ky.request.body ?? undefined);343 }344 }345 })() as ResponsePromise;7 unmodified lines353 continue;354 }355 356 result[type] = async (schema?: StandardSchemaV1) => {410- // `#fetch()` replaces `ky.request` with the clone it prepares for a possible retry, so a shortcut called411- // after the request was dispatched would otherwise advertise its media type on that clone, which is only412- // sent if a retry happens, instead of on the attempt that produced the response.413- const acceptRequest = ky.#sentRequest;357 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing415- acceptRequest.headers.set('accept', acceptRequest.headers.get('accept') || mimeType);358+ ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);359 360 const response = await result;361 419- // `ky.stop` from a `beforeRetry` hook resolves the request with no response at all. Reading a body420- // method would otherwise crash deep inside Ky with a TypeError that names Ky internals.421- if (response === undefined) {422- throw new TypeError(missingResponseMessage);423- }424-362 if (type !== 'json') {363 return ky.#raceBodyRead(async () => response[type](), response);364 }365 18 unmodified lines384 }, ky.#userProvidedAbortSignal);385 } catch (error: unknown) {386 // 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.387 if (ky.#userProvidedAbortSignal?.aborted) {451- await ky.#throwProcessedError(ky.#userProvidedAbortSignal.reason, request);388+ await ky.#throwProcessedError(ky.#userProvidedAbortSignal.reason);389 }390 391 throw error;392 }393 394 if (parsedResult === timedOutOperation) {458- await ky.#throwProcessedError(new TimeoutError(request), request);395+ await ky.#throwProcessedError(new TimeoutError(request));396 }397 398 return parsedResult;399 };22 unmodified lines422 #originalRequest?: Request;423 #requestBodyCanBeCancelled = false;424 readonly #userProvidedAbortSignal: AbortSignal | undefined;425 readonly #beforeRetryHookErrors = new WeakSet<Error>();489- // Values thrown by a user callback that runs while the request is in flight. Retrying would re-send the body and490- // run the callback again, so they are never retriable, whatever `shouldRetry` says. A strong `Set` is safe because491- // a `Ky` instance lives for exactly one request, and the callback can throw a non-`Error` value.492- readonly #inFlightCallbackErrors = new Set<unknown>();426 #cachedNormalizedOptions: NormalizedOptions | undefined;427 readonly #startTime: number | undefined;428 #returnedResponseFromBeforeRetryHook = false;429 readonly #responseRequests = new WeakMap<Response, Request>();430 readonly #decoratedResponses = new WeakSet<Response>();431 432 // eslint-disable-next-line complexity433 constructor(input: Input, options: Options = {}) {501- // Checked before the options are built, since building them reads `input.headers`.502- if (typeof input !== 'string' && !(input instanceof URL || input instanceof globalThis.Request)) {503- throw new TypeError('`input` must be a string, URL, or Request');504- }505-434 const {maxResponseSize = Number.POSITIVE_INFINITY} = options;435 if (Object.hasOwn(options, 'prefixUrl')) {436 throw new Error(prefixUrlRenamedErrorMessage);437 }15 unmodified lines453 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) ?? {},456 };529- // Checked here rather than on the way out, because the constructor already calls `stringifyJson`.530- validateCallbackOptions(this.#options);457 this.#retryLimit = this.#options.retry.limit;458 459 if (maxResponseSize !== Number.POSITIVE_INFINITY && (!Number.isSafeInteger(maxResponseSize) || maxResponseSize < 0)) {460 throw new TypeError('The `maxResponseSize` option must be a non-negative safe integer or Infinity');461 }462 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+467 this.#requestInput = input instanceof globalThis.Request ? input : undefined;468 469 if (typeof input === 'string') {470 if (this.#options.prefix) {127 unmodified lines598 // Ky's internal scheduling and user hook time before the first fetch attempt.599 this.#startTime = typeof this.#options.totalTimeout === 'number' ? this.#getCurrentTime() : undefined;600 }601 672- #calculateDelay(retry: InternalOptions['retry'], error: unknown): number {602+ #calculateDelay(retry: InternalOptions['retry']): number {603 const retryDelay = retry.delay(this.#retryCount + 1);604 675- // A `retry.delay` that does not return a usable number would turn every delay into `NaN`, which676- // `setTimeout()` clamps to 1ms, silently disabling the configured backoff. The `jitter` function form677- // already guards its own result, so the input is checked here for every jitter form.678- if (typeof retryDelay !== 'number' || Number.isNaN(retryDelay) || retryDelay < 0) {679- // The failure that was being retried is chained as the cause, so `beforeError` can still inspect it680- // instead of losing the response and data to this configuration mistake.681- throw new TypeError('`retry.delay` must return a non-negative number or `Infinity`', {cause: error});682- }683-605 let jitteredDelay = retryDelay;606 if (retry.jitter === true) {607 jitteredDelay = Math.random() * retryDelay;608 } else if (typeof retry.jitter === 'function') {7 unmodified lines616 return Math.min(retry.backoffLimit, jitteredDelay);617 }618 619 async #calculateRetryDelay(error: unknown) {699- if (this.#inFlightCallbackErrors.has(error)) {700- throw error;701- }702-620 const retry = normalizeRetryOptions(this.#options.retry);621 if (this.#retryCount >= Math.min(retry.limit, this.#retryLimit)) {622 throw error;623 }1 unmodified line625 // Wrap non-Error throws to ensure consistent error handling626 const errorObject = error instanceof Error ? error : new NonError(error);627 628 // Handle forced retry from afterResponse hook - skip method check and shouldRetry712- if (isForceRetryError(errorObject)) {713- return errorObject.customDelay ?? this.#calculateDelay(retry, error);629+ if (errorObject instanceof ForceRetryError) {630+ return errorObject.customDelay ?? this.#calculateDelay(retry);631 }632 633 // Check if method is retriable for non-forced retries634 if (!retry.methods.includes(normalizeRetryMethod(this.request.method))) {5 unmodified lines640 if (shouldRetry !== undefined) {641 const result = await this.#raceWithTotalTimeout(async () => shouldRetry({error: errorObject, retryCount: this.#retryCount + 1}), this.#userProvidedAbortSignal);642 this.#throwIfAbortedByUser();643 if (result === timedOutOperation) {727- throw new TimeoutError(this.#sentRequest);644+ throw new TimeoutError(this.request);645 }646 647 // Only exact booleans override the default retry checks.648 if (result === false) {8 unmodified lines657 if (!shouldRetryOverride && !retry.retryOnTimeout) {658 throw error;659 }660 744- return this.#calculateDelay(retry, error);661+ return this.#calculateDelay(retry);662 }663 747- // The `isHTTPError()` brand only checks `name`, so a cross-realm error may not carry a `response`.748- if (isHTTPError(error) && error.response) {664+ if (isHTTPError(error)) {665 if (!shouldRetryOverride && !retry.statusCodes.includes(error.response.status)) {666 throw error;667 }668 1 unmodified line670 if (retryTimingHeader && retry.afterStatusCodes.includes(error.response.status)) {671 const after = calculateRetryTimingDelay(retryTimingHeader);672 if (after === undefined) {673 // Malformed retry timing headers should not disable retries; they only lose their server-provided timing.758- return this.#calculateDelay(retry, error);674+ return this.#calculateDelay(retry);675 }676 677 // Don't apply jitter when server provides explicit retry timing678 return Math.min(retry.maxRetryAfter, after);2 unmodified lines681 if (!shouldRetryOverride && error.response.status === 413) {682 throw error;683 }684 769- return this.#calculateDelay(retry, error);685+ return this.#calculateDelay(retry);686 }687 688 // Only retry known retriable error types. Unknown errors (e.g., programming bugs) are not retried.689 if (!shouldRetryOverride && !isNetworkError(error)) {690 throw error;691 }692 777- return this.#calculateDelay(retry, error);693+ return this.#calculateDelay(retry);694 }695 696 #decorateResponse(response: Response): Response {697 if (!this.#options.parseJson || this.#decoratedResponses.has(response)) {2 unmodified lines700 701 this.#decoratedResponses.add(response);702 const request = this.#getResponseRequest(response);703 788- try {789- response.json = async () => {790- const text = await response.text();791- return this.#options.parseJson!(text, {request, response});792- };704+ response.json = async () => {705+ const text = await response.text();706+ return this.#options.parseJson!(text, {request, response});707+ };708 794- // `clone()` returns a fresh `Response` that would otherwise fall back to the native `json()`.795- const nativeClone = response.clone.bind(response);796- response.clone = () => this.#decorateResponse(this.#setResponseRequest(nativeClone(), request));797- } catch (error: unknown) {798- // A frozen response cannot be decorated, so the caller never receives it and nothing else can release its799- // body. Report the real problem and let go of the connection.800- this.#cancelResponseBody(response);801- throw error;802- }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));712 713 return response;714 }715 807- // Defaults to the last request that was actually sent, because `this.request` is the clone `#fetch()` prepares808- // for a possible retry and may never be sent at all.809- async #throwProcessedError(error: unknown, request: Request = this.#sentRequest): Promise<never> {810- // Non-Error throws (e.g., thrown strings) pass through unchanged. `isError` reads the internal brand, so an811- // error from another realm still runs the hooks, the same way the Ky type guards accept branded errors.812- if (!isError(error)) {716+ async #throwProcessedError(error: unknown): Promise<never> {717+ // Non-Error throws (e.g., thrown strings) pass through unchanged718+ if (!(error instanceof Error)) {719 throw error;720 }721 722 // Errors thrown by beforeRetry hooks must propagate unchanged.2 unmodified lines725 }726 727 let processedError: Error = error;728 for (const hook of this.#options.hooks.beforeError) {729+ // `request` is the current failing request. `options` intentionally remains the823- // `options` intentionally remains the stable normalized Ky options snapshot for the same reason as `HTTPError` above.730+ // stable normalized Ky options snapshot for the same reason as `HTTPError` above.731 // eslint-disable-next-line no-await-in-loop732 const hookResult: unknown = await hook({826- request,733+ request: this.request,734 options: this.#getNormalizedOptions(),735 error: processedError,736 retryCount: this.#retryCount,737 });738 832- // Only overwrite if the hook returns a valid Error, including one from another realm.833- if (isError(hookResult)) {739+ // Only overwrite if the hook returns a valid Error instance.740+ if (hookResult instanceof Error) {741 processedError = hookResult;742 }743 }744 62 unmodified lines807 #getEffectiveTimeout(): number | undefined {808 const remainingTotal = this.#getRemainingTotalTimeout();809 if (remainingTotal !== undefined) {810 if (remainingTotal <= 0) {904- throw new TimeoutError(this.#sentRequest);811+ throw new TimeoutError(this.request);812 }813 814 return this.#options.timeout === false815 ? remainingTotal5 unmodified lines821 822 // Unlike error bodies (`#getResponseData`), a successful body read has no fallback value to return -823 // the caller's `.json()`/`.text()`/etc. promise must settle, so a timeout here always rejects.824 async #raceBodyRead(createBodyPromise: () => Promise<unknown>, response: Response): Promise<unknown> {918- const failedRequest = this.#getResponseRequest(response);825 let timeoutMs: number | undefined;826 try {827 timeoutMs = this.#getEffectiveTimeout();828 } catch (error: unknown) {923- await this.#throwProcessedError(error, failedRequest);829+ await this.#throwProcessedError(error);830 }831 832 const bodyPromise = createBodyPromise();833 const timeoutPromise = timeoutMs === undefined13 unmodified lines847 ? await bodyPromise848 : await Promise.race([bodyPromise, timeoutPromise]);849 } catch (error: unknown) {850 if (this.#userProvidedAbortSignal?.aborted) {945- await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);851+ await this.#throwProcessedError(this.#userProvidedAbortSignal.reason);852 }853 854 if (this.#getRemainingTotalTimeout() !== 0) {855 // 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.856 const progressCallbackError = getProgressCallbackError(response.body ?? undefined);857 if (progressCallbackError !== undefined) {952- await this.#throwProcessedError(progressCallbackError, failedRequest);858+ await this.#throwProcessedError(progressCallbackError);859 }860 861 // 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.862 // This only happens on the awaited path, so a body that fails after the timeout already won does not run the hooks again.863 if (isRawNetworkError(error)) {958- await this.#throwProcessedError(new NetworkError(failedRequest, {cause: error as Error}), failedRequest);864+ await this.#throwProcessedError(new NetworkError(this.#getResponseRequest(response), {cause: error as Error}));865 }866 961- await this.#throwProcessedError(error, failedRequest);867+ await this.#throwProcessedError(error);868 }869 870 result = timedOutResponseData;871 }872 967- // A cancellation is part of the request lifecycle, so it must not resolve as a successful body read just968- // because the bytes happened to arrive first. `.json()` already gets this check for free through969- // `#raceWithTotalTimeout()`, which is why the shortcuts used to disagree here.970- if (this.#userProvidedAbortSignal?.aborted) {971- await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);972- }973-873 if (result === timedOutResponseData || this.#getRemainingTotalTimeout() === 0) {874 // The stream is locked by the native body method's own reader by this point, so875 // `response.body.cancel()` would reject as "already locked". Aborting the request's876 // signal is what actually interrupts the underlying network read.877 this.#abortController?.abort();979- await this.#throwProcessedError(new TimeoutError(failedRequest), failedRequest);878+ await this.#throwProcessedError(new TimeoutError(this.#getResponseRequest(response)));879 }880 881 return result;882 }8 unmodified lines891 }892 893 let timeoutId: ReturnType<typeof setTimeout> | undefined;894 let abortListener: (() => void) | undefined;996- let operationPromise: Promise<T> | undefined;895 try {896 const abortPromise = new Promise<never>((_resolve, reject) => {897 if (!abortSignal) {898 return;9 unmodified lines908 if (abortSignal.aborted) {909 abortListener();910 }911 });1014- operationPromise = operation();912+ const operationPromise = operation();913 914 if (remainingTotal === undefined) {915 return await Promise.race([operationPromise, abortPromise]);916 }21 unmodified lines938 }939 940 return result;941 } catch (error: unknown) {1044- if (abortSignal?.aborted) {1045- // The abort won the race, so whatever the operation eventually returns is discarded. Release its body, the1046- // same way the timeout path below does for a value it never consumed.1047- if (operationPromise) {1048- void operationPromise.then(value => {1049- this.#cancelReturnedBody(value);1050- }).catch(() => undefined);1051- }942+ abortSignal?.throwIfAborted();943 1053- abortSignal.throwIfAborted();1054- }1055-944 const remainingAfterOperation = this.#getRemainingTotalTimeout();945 if (remainingAfterOperation !== undefined && remainingAfterOperation <= 0) {946 this.#abortController?.abort();947 return timedOutOperation;148 unmodified lines1096 ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController!.signal])1097 : this.#abortController!.signal;1098 }1099 1212- // A `throwHttpErrors` predicate that throws used to escape from the `if` condition, before the body was read or1213- // released, leaving the caller with an error and no handle on the response to release it with.1214- #shouldThrowHttpErrors(response: Response): boolean {1215- const {throwHttpErrors} = this.#options;1216- try {1217- return typeof throwHttpErrors === 'function' ? throwHttpErrors(response.status) : throwHttpErrors;1218- } catch (error: unknown) {1219- this.#cancelResponseBody(response);1220- throw error;1221- }1222- }1223-1224- // `#fetch()` replaces `this.request` with the clone it prepares for a possible retry, so anything reporting the1225- // request that produced a response or failed has to use the one that was actually sent.1226- get #sentRequest(): Request {1227- return this.#originalRequest ?? this.request;1228- }1229-1230- #throwIfTotalTimeoutExhausted(request: Request = this.#sentRequest): void {1100+ #throwIfTotalTimeoutExhausted(request: Request = this.request): void {1101 const remaining = this.#getRemainingTotalTimeout();1102 if (remaining !== undefined && remaining <= 0) {1103 throw new TimeoutError(request);1104 }8 unmodified lines1113 retryCount: 0,1114 }), this.#userProvidedAbortSignal);1115 1116 if (result === timedOutOperation) {1247- throw new TimeoutError(this.#sentRequest);1117+ throw new TimeoutError(this.request);1118 }1119 1120 if (isRequestInstance(result)) {1121 this.#assignRequest(this.#withManagedSignal(result));16 unmodified lines1138 let modifiedResponse;1139 try {1140 // eslint-disable-next-line no-await-in-loop1141 modifiedResponse = await this.#raceWithTotalTimeout(async () => hook({1272- // Deliberately `this.request`, which `#fetch()` has already replaced with the clone prepared for a1273- // retry, so its body is still unread. A hook that forces a retry with `ky.retry({request: new1274- // Request(request)})` depends on being able to copy an unconsumed request from here.1142 request: this.request,1143 options: this.#getNormalizedOptions(),1144 response: hookResponse,1145 retryCount: this.#retryCount,1146 }), this.#userProvidedAbortSignal);1147 1148 if (modifiedResponse === timedOutOperation) {1282- throw new TimeoutError(this.#sentRequest);1149+ throw new TimeoutError(this.request);1150 }1151 } catch (error) {1152 // Cancel both responses to prevent memory leaks when hook throws1153 if (hookResponse !== response) {3 unmodified lines1157 this.#cancelResponseBody(response);1158 throw error;1159 }1160 1294- if (isRetryMarker(modifiedResponse)) {1161+ if (modifiedResponse instanceof RetryMarker) {1162 // Cancel both the cloned response passed to the hook and the current response to prevent resource leaks (especially important in Deno/Bun).1163 // Do not await cancellation since hooks can clone the response, leaving extra tee branches that keep cancel promises pending per the Streams spec.1164 if (hookResponse !== response) {1165 this.#cancelResponseBody(hookResponse);43 unmodified lines1209 1210 const remainingTimeout = this.#getRemainingTotalTimeout();1211 if (remainingTimeout !== undefined) {1212 if (remainingTimeout <= 0) {1346- throw new TimeoutError(this.#sentRequest);1213+ throw new TimeoutError(this.request);1214 }1215 1216 // If waiting would consume all remaining budget, time out without starting another request.1217 if (retryDelay >= remainingTimeout) {1218 await delay(remainingTimeout, delayOptions);1352- throw new TimeoutError(this.#sentRequest);1219+ throw new TimeoutError(this.request);1220 }1221 }1222 1223 // Only use user-provided signal for delay, not our internal abortController9 unmodified lines1233 }1234 1235 // Apply custom request from forced retry before beforeRetry hooks1236 // Ensure the custom request has the correct managed signal for timeouts and user aborts1370- if (isForceRetryError(error) && error.customRequest) {1237+ if (error instanceof ForceRetryError && error.customRequest) {1238 // Replacement Requests are authoritative by design. Do not rewrite headers here,1239 // even for cross-origin retries. Callers using `ky.retry({request})` explicitly1240 // opted into the exact Request they constructed.1241 this.#assignRequest(this.#withManagedSignal(error.customRequest));9 unmodified lines1251 error: error instanceof Error ? error : new NonError(error),1252 retryCount: this.#retryCount + 1,1253 }), this.#userProvidedAbortSignal);1254 } catch (hookError) {1388- // Preserve the original request error path (`throw error`) so beforeError hooks can still run. `isError`1389- // rather than `instanceof`, so a cross-realm error is recognised the same way `#throwProcessedError` does.1390- if (isError(hookError) && hookError !== error) {1255+ // Preserve the original request error path (`throw error`) so beforeError hooks can still run.1256+ if (hookError instanceof Error && hookError !== error) {1257 this.#beforeRetryHookErrors.add(hookError);1258 }1259 1260 throw hookError;1261 }1262 1263 if (hookResult === timedOutOperation) {1398- throw new TimeoutError(this.#sentRequest);1264+ throw new TimeoutError(this.request);1265 }1266 1267 if (isRequestInstance(hookResult)) {1268 // Same contract as `ky.retry({request})`: a Request returned from `beforeRetry`75 unmodified lines1344 1345 // 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.1346 const progressCallbackError = getProgressCallbackError(this.#originalRequest?.body ?? undefined);1347 if (progressCallbackError !== undefined) {1482- this.#inFlightCallbackErrors.add(progressCallbackError);1483-1348 // eslint-disable-next-line @typescript-eslint/only-throw-error -- The callback can throw any value, and non-Error throws are propagated as-is elsewhere.1349 throw progressCallbackError;1350 }1351 74 unmodified lines1426 return this.#responseRequests.get(response) ?? this.request;1427 }1428 1429 #setResponseRequest(response: Response, request: Request): Response {1566- // A custom `fetch` is allowed to resolve with anything, and the main loop decides what to do with a value that1567- // is not a Response. A primitive cannot key a `WeakMap`, so only a real object is recorded.1568- if (isResponseInstance(response)) {1569- this.#responseRequests.set(response, request);1430+ this.#responseRequests.set(response, request);1570- }1571-1431 return response;1432 }1433 1434 #limitResponseSize(response: Response): Response {12 unmodified linesmodified:source/utils/merge.ts+2 added-2 removed
414 unmodified lines415 value = {limit: value};416 }417 }418 419- if (isRoot && isPlainObject(value) && (isReplace || !isMergeable(returnValue[key]))) {420- // Resolve nested replacement markers even when there is no parent configuration to merge.419+ if (isRoot && key === 'retry' && isPlainObject(value) && (isReplace || !isMergeable(returnValue[key]))) {420+ // Resolve nested replacement markers even when there is no parent retry configuration to merge.421 value = deepMergeInternal<unknown>(false, {}, value);422 } else if (!isReplace && isMergeable(returnValue[key]) && isMergeable(value) && Array.isArray(returnValue[key]) === Array.isArray(value)) {423 value = deepMergeInternal<unknown>(false, returnValue[key], value);424 }56 unmodified linesmodified:test/body-size.ts+106 added
121 unmodified linesExpand all122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231121 unmodified linesExpand all const size = getBodySize(formData); // Size should be at least the blob content size (11 bytes) t.true(size >= 11, `Expected size >= 11, got ${size}`);});
// Pinned exactly, because the per-part byte counts are the whole point of the estimate erring high and a one-byte change to any of them is invisible to a range assertion.test('the FormData estimate counts the framing, the filename and the content type', t => { const one = new FormData(); one.append('a', 'one'); // Closing boundary 46, plus one part of 44 + 40 + 4 + 3 + 2. t.is(getBodySize(one), 139);
const two = new FormData(); two.append('a', 'one'); two.append('b', 'two'); // 139, plus one more part of 44 + 40 + 4 + 3 + 2 for the value `two`. t.is(getBodySize(two), 232);
const withFile = new FormData(); withFile.append('f', new File(['abc'], 'n.txt', {type: 'text/plain'})); // A `File` adds `; filename="n.txt"` (18) and a `\r\nContent-Type: text/plain` (26). t.is(getBodySize(withFile), 46 + 44 + 40 + 18 + 26 + 4 + 3 + 2);
const withBlob = new Blob(['abc']); const withUnnamedBlob = new FormData(); withUnnamedBlob.append('f', withBlob); // The runtime names the blob `blob`, so `; filename="blob"` (17), and the default `\r\nContent-Type: application/octet-stream` (40). t.is(getBodySize(withUnnamedBlob), 46 + 44 + 40 + 17 + 40 + 4 + 3 + 2);
// Bun keeps an appended `Blob` as a `Blob` with an `undefined` name and sends `; filename=""` (13) for it. const bunLikeFormData = new FormData(); bunLikeFormData.append('f', 'placeholder'); bunLikeFormData[Symbol.iterator] = function * () { yield ['f', Object.defineProperty(new Blob(['abc']), 'name', {value: undefined})]; } as FormData[typeof Symbol.iterator]; t.is(getBodySize(bunLikeFormData), 46 + 44 + 40 + 13 + 40 + 4 + 3 + 2);
t.is(getBodySize(new FormData()), 0);});
// The FormData estimate omitted the per-part framing, the `filename` parameter, the `Content-Type` line and the closing boundary, so it was always below the real size. An estimate below the real size makes the reported upload percentage reach its ceiling part way through, so the estimate now errs high instead.test('the FormData estimate is never below the serialized size', async t => { const server = await createHttpTestServer(t, {bodyParser: false}); server.post('/', async (request, response) => { response.end(String(request.headers['content-length'])); });
const cases: Array<[string, () => FormData]> = [ ['a few short fields', () => { const form = new FormData(); form.append('a', 'one'); form.append('b', 'two'); form.append('c', 'three'); return form; }], ['many short fields', () => { const form = new FormData(); for (let index = 0; index < 100; index++) { form.append('field', 'value'); }
return form; }], ['a file with a name and a type', () => { const form = new FormData(); form.append('file', new File(['x'.repeat(1024)], 'a.txt', {type: 'text/plain'})); return form; }], ['a blob with no name', () => { const form = new FormData(); form.append('file', new Blob(['x'.repeat(1024)])); return form; }], ['a large file', () => { const form = new FormData(); form.append('file', new File(['x'.repeat(1024 * 1024)], 'big.bin')); return form; }], ['a field with a long name', () => { const form = new FormData(); form.append('a'.repeat(60), 'value'); return form; }], // Line breaks in a value are sent as CRLF, so a bare `\n` or `\r` takes two bytes. ['bare line breaks in a value', () => { const form = new FormData(); form.append('text', 'line\n'.repeat(1000)); form.append('other', 'a\rb'.repeat(500)); return form; }], // Quotes and line breaks in a name or filename are escaped to three bytes each. ['quotes and line breaks in names', () => { const form = new FormData(); form.append('a"b\nc'.repeat(50), 'value'); form.append('file', new File(['x'], 'q"u\no"te'.repeat(50))); return form; }], ];
for (const [label, build] of cases) { const form = build(); // eslint-disable-next-line no-await-in-loop const serialized = Number(await ky.post(server.url, {body: form, retry: 0}).text()); const estimate = getBodySize(form);
t.true(estimate >= serialized, `${label}: estimate ${estimate} must not be below the real ${serialized}`); // A wildly high estimate would be just as wrong, so keep it in the same ballpark. t.true(estimate < serialized * 1.2, `${label}: estimate ${estimate} is too far above the real ${serialized}`); }});modified:test/hooks.ts+43 added-26 removed
6900 unmodified lines6901 },6902 }).text();6903 6904 t.is(responseText, 'ok');6905- // Progress is best effort: the body is read by the runtime, not wrapped by Ky.6906- t.deepEqual(events, []);6905+ // Progress is best effort: the body is read by the runtime, so it is not wrapped and no event is reported.6906+ t.deepEqual(events, [], 'a Request-like result is sent as-is, so it reports no upload progress');6907 });6908 6909-// `ky.stop` resolves the request with `undefined`, which is documented as incompatible with body method6910-// shortcuts. The shortcut used to crash while masking the real reason with an internal TypeError that named6911-// Ky's own internals instead of the returned symbol.6909+// `ky.stop` resolves the request with `undefined`, which is documented as incompatible with body method shortcuts. The shortcut used to crash while masking the real reason with an internal TypeError that named Ky's own internals instead of the returned symbol.6910 for (const type of ['json', 'text', 'arrayBuffer', 'blob', 'formData', 'bytes'] as const) {6911 test(`the \`${type}\` shortcut reports that \`ky.stop\` left no response`, async t => {6912 await t.throwsAsync(ky(requestFixtureUrl, {6913 fetch: async () => new Response('server error', {status: 500}),173 unmodified lines7087 let errorRequest: unknown;7088 7089 // eslint-disable-next-line no-await-in-loop7090 const error = await t.throwsAsync(ky('https://example.com', {7093- retry,7091+ retry: {limit: retry, delay: () => 0},7092 async fetch(request) {7093 sent = request;7094 return new Response('server error', {status: 500});7095 },106 unmodified lines7202 options.timeout = 3_000_000_000;7203 }],7204 },7205 },7206+ // A hook that answers the request itself never reaches fetch either.7207+ {7208+ hooks: {7209+ beforeRequest: [() => new Response('from the hook')],7210+ },7211+ },7212+ // Neither does a `totalTimeout` that runs out inside a hook.7213+ {7214+ totalTimeout: 20,7215+ hooks: {7216+ beforeRequest: [async () => {7217+ await delay(200);7218+ }],7219+ },7220+ },7221 ]) {7222 let cancelled = false;7223 let fetchCalled = false;7224 const body = new ReadableStream<Uint8Array>({4 unmodified lines7229 cancelled = true;7230 },7231 });7232 7233+ // Some of these throw and some resolve, for example a hook that answers the request itself, so the outcome is not asserted here. What matters is that fetch never ran and the caller's body survived.7234+ try {7220- // eslint-disable-next-line no-await-in-loop7221- await t.throwsAsync(ky('https://example.com', {7222- method: 'POST',7223- body,7224- retry: 0,7225- ...options,7226- async fetch() {7227- fetchCalled = true;7228- return new Response('ok');7229- },7230- }).text());7235+ // eslint-disable-next-line no-await-in-loop7236+ await ky('https://example.com', {7237+ method: 'POST',7238+ body,7239+ retry: 0,7240+ ...options,7241+ async fetch() {7242+ fetchCalled = true;7243+ return new Response('ok');7244+ },7245+ }).text();7246+ } catch {}7247 7248 failedFetches.push(fetchCalled);7249 cancelledBodies.push(cancelled);7250 }7251 7236- t.deepEqual(failedFetches, [false, false, false]);7237- t.deepEqual(cancelledBodies, [false, false, false]);7252+ t.deepEqual(failedFetches, [false, false, false, false, false]);7253+ t.deepEqual(cancelledBodies, [false, false, false, false, false]);7254 });7255 7256 test('a request that did start still releases its upload body', async t => {7241- let cancelled = false;7257+ let release: () => void;7258+ // Awaiting the cancel itself, rather than a sleep, keeps this reliable on a loaded machine.7259+ const cancelled = new Promise<void>(resolve => {7260+ release = resolve;7261+ });7262 const body = new ReadableStream<Uint8Array>({7263 start(controller) {7264 controller.enqueue(new TextEncoder().encode('hi'));7265 },7266 cancel() {7247- cancelled = true;7267+ release!();7268 },7269 });7270 7271 await ky('https://example.com', {2 unmodified lines7274 retry: 0,7275 fetch: async () => new Response('ok'),7276 }).text();7277 7258- await new Promise(resolve => {7259- setTimeout(resolve, 10);7260- });7261-7262- t.true(cancelled);7278+ await cancelled;7279+ t.pass();7280 });7281 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 any245 unmodified linesmodified:test/http-error.ts+14 added-12 removed
756 unmodified lines757 758 t.is(error.request, sentRequest);759 });760 761-// A `throwHttpErrors` predicate ran inside the `if` condition, so a throw from it escaped before the body was read762-// or released, leaving the caller with an error and no handle on the response to release it with.761+// A `throwHttpErrors` predicate ran inside the `if` condition, so a throw from it escaped before the body was read or released, leaving the caller with an error and no handle on the response to release it with.762 test('a `throwHttpErrors` predicate that throws releases the response body', async t => {764- let cancelled = false;763+ let release: () => void;764+ // Awaiting the cancel itself, rather than a sleep, keeps this reliable on a loaded machine.765+ const cancelled = new Promise<void>(resolve => {766+ release = resolve;767+ });768 const body = new ReadableStream<Uint8Array>({769 start(controller) {770 controller.enqueue(new TextEncoder().encode('server error'));771 },772 cancel() {770- cancelled = true;773+ release!();774 },775 });776 777 const error = await t.throwsAsync(ky('https://example.com', {4 unmodified lines782 fetch: async () => new Response(body, {status: 500}),783 }).text(), {message: 'policy engine exploded'});784 785 t.is(error?.message, 'policy engine exploded');783- await new Promise(resolve => {784- setTimeout(resolve, 10);785- });786- t.true(cancelled, 'the response body must be released');786+ await cancelled;787 });788 789 test('a `throwHttpErrors` predicate that throws is still seen by `beforeError`', async t => {790- const seen: string[] = [];790+ const seen: unknown[] = [];791+ const thrown = new Error('policy engine exploded');792 793 await t.throwsAsync(ky('https://example.com', {794 retry: 0,795 throwHttpErrors() {795- throw new Error('policy engine exploded');796+ throw thrown;797 },798 fetch: async () => new Response('server error', {status: 500}),799 hooks: {800 beforeError: [({error}) => {800- seen.push(error.message);801+ seen.push(error);802 }],803 },804 }).text(), {message: 'policy engine exploded'});805 805- t.deepEqual(seen, ['policy engine exploded']);806+ // The predicate's own error is what the hook sees, unchanged.807+ t.deepEqual(seen, [thrown]);808 });modified:test/response-consumption.ts+3 added-1 removed
237 unmodified lines238 // The media type each shortcut advertises is deliberately narrow, so a caller that wants another representation asks for it through `headers` instead.239 test('each body shortcut advertises exactly one media type', async t => {240 const accepts: Record<string, string | undefined> = {};241 242- for (const type of ['json', 'text', 'formData', 'arrayBuffer', 'blob'] as const) {242+ for (const type of ['json', 'text', 'formData', 'arrayBuffer', 'blob', 'bytes'] as const) {243 // eslint-disable-next-line no-await-in-loop244 await ky('https://example.com', {245 retry: 0,246 async fetch(request) {8 unmodified lines255 text: 'text/*',256 formData: 'multipart/form-data',257 arrayBuffer: '*/*',258 blob: '*/*',259+ // Only exposed when the runtime implements `Response.prototype.bytes()`.260+ bytes: typeof Response.prototype.bytes === 'function' ? '*/*' : undefined,261 });262 });modified:test/response-size.ts+8 added-8 removed
567 unmodified lines568 response.headers.set('x-injected', '1');569 }, {instanceOf: TypeError});570 });571 572-// Decoration assigns to the response, so a frozen one throws. The caller then gets the error and never receives573-// the response, which left its body with nobody able to release it.572+// Decoration assigns to the response, so a frozen one throws. The caller then gets the error and never receives the response, which left its body with nobody able to release it.573 test('a response that cannot be decorated releases its body', async t => {575- let cancelled = false;574+ let release: () => void;575+ // Awaiting the cancel itself, rather than a sleep, keeps this reliable on a loaded machine.576+ const cancelled = new Promise<void>(resolve => {577+ release = resolve;578+ });579 const body = new ReadableStream<Uint8Array>({580 start(controller) {581 controller.enqueue(new TextEncoder().encode('{"a":1}'));582 },583 cancel() {581- cancelled = true;584+ release!();585 },586 });587 588 const error = await t.throwsAsync(ky(url, {5 unmodified lines594 message: /not extensible/,595 });596 597 t.is(error?.name, 'TypeError');595- await new Promise(resolve => {596- setTimeout(resolve, 10);597- });598- t.true(cancelled, 'the response body must be released');598+ await cancelled;599 });modified:test/stream.ts+66 added-2 removed
1370 unmodified lines1371 t.is(text.length, 64);1372 t.is(progressEvents.at(-1)?.totalBytes, 64);1373 });1374 1375-// `content-encoding: identity` is a registered no-op coding (RFC 9110 §8.4.2), so `content-length` is the decoded1376-// length and remains a valid total, as it is for a response with no `content-encoding` at all.1375+// A coding list that mentions `identity` alongside a real coding is still content-coded, so the encoded length cannot be used.1376+test('download progress reports an unknown total for a multi-coding content-encoding', async t => {1377+ const progressEvents: Progress[] = [];1378+ const text = await ky('https://example.com', {1379+ async fetch() {1380+ const body = new ReadableStream<Uint8Array>({1381+ start(controller) {1382+ for (let index = 0; index < 8; index++) {1383+ controller.enqueue(new Uint8Array(1024));1384+ }1385+1386+ controller.close();1387+ },1388+ });1389+ return new Response(body, {headers: {'content-length': '64', 'content-encoding': 'identity, gzip'}});1390+ },1391+ onDownloadProgress(progress) {1392+ progressEvents.push(progress);1393+ },1394+ }).text();1395+1396+ t.is(text.length, 8192);1397+ for (const event of progressEvents.slice(0, -1)) {1398+ t.is(event.totalBytes, 0);1399+ }1400+1401+ t.deepEqual(progressEvents.at(-1), {percent: 1, totalBytes: 8192, transferredBytes: 8192});1402+});1403+1404+// `content-encoding: identity` is a registered no-op coding (RFC 9110 §8.4.2), so `content-length` is the decoded length and remains a valid total, as it is for a response with no `content-encoding` at all.1405 for (const [label, headers] of [1406 ['no content-encoding', {}],1407 ['content-encoding: identity', {'content-encoding': 'identity'}],1408 ['content-encoding: Identity', {'content-encoding': 'Identity'}],75 unmodified lines1484 1485 t.is(progressEvents.at(-1)?.totalBytes, 10);1486 });1487 1488+// The byte accounting holds the last chunk back so the final event can report the real total, which means an intermediate event is attributed to the previous chunk. Chunks of differing sizes are what pins that down, and an estimate below the delivered size is what makes the reported total grow.1489+test('progress attributes bytes to the chunk before the one arriving', async t => {1490+ const chunkSizes = [10, 30, 20, 40];1491+ const chunks: number[] = [];1492+ const transferred: number[] = [];1493+ const totals: number[] = [];1494+1495+ const text = await ky('https://example.com', {1496+ async fetch() {1497+ const body = new ReadableStream<Uint8Array>({1498+ start(controller) {1499+ for (const size of chunkSizes) {1500+ controller.enqueue(new Uint8Array(size));1501+ }1502+1503+ controller.close();1504+ },1505+ });1506+ // A total below the delivered size, so the reported total has to grow.1507+ return new Response(body, {headers: {'content-length': '1'}});1508+ },1509+ onDownloadProgress({totalBytes, transferredBytes}, chunk) {1510+ chunks.push(chunk.byteLength);1511+ transferred.push(transferredBytes);1512+ totals.push(totalBytes);1513+ },1514+ }).text();1515+1516+ t.is(text.length, 100);1517+ // Each event carries the chunk it was counted for, so the sizes run one behind the arrival order.1518+ t.deepEqual(chunks, chunkSizes);1519+ t.deepEqual(transferred, [10, 40, 60, 100]);1520+ // Each intermediate event reports the running total, which starts below the estimate and grows past it.1521+ t.deepEqual(totals, [10, 40, 60, 100]);1522+});1523+1524 // A response with no body at all is not streamed. That covers a null body status, and a `HEAD` response in runtimes that give it no body, such as Node.js.1525 test('download progress stays silent for a null body status', async t => {1526 let calls = 0;1527 const result = await ky('https://example.com', {87 unmodified linesmodified:test/validation.ts+2 added
81 unmodified lines82 for (const [key, value] of [83 ['parseJson', 'x'],84 ['stringifyJson', 5],85 ['fetch', 'x'],86+ ['onDownloadProgress', 'x'],87+ ['onUploadProgress', 'x'],88 ] as Array<[string, unknown]>) {89 const options: Record<string, unknown> = {[key]: value};90 91 t.throws(() => {87 unmodified lines