Skip to content
Myr

Let a `beforeRetry` hook change per-attempt options

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Fixes #885

authored by Sindre Sorhus · committed by Sindre Sorhus · parent d9ddb03 · Browse files · 9 files+543 added−13 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+543 added−13 removed

  • tests:+391 added−0 removed
  • other:+152 added−13 removed

9 files+543 added−13 removed

modified:source/core/constants.ts+3 added
260 unmodified lines
261```262*/263export const retry = (options?: ForceRetryOptions) => new RetryMarker(options);264265// Ky reads these again for every attempt, so a `beforeRetry` hook can change them without rebuilding the request.266export const beforeRetryOptionKeys = ['onUploadProgress', 'onDownloadProgress', 'timeout', 'fetch', 'throwHttpErrors'] as const;267268export const kyOptionKeys: KyOptionsRegistry = {269 json: true,270 parseJson: true,271 stringifyJson: true,
36 unmodified lines
modified:source/core/Ky.ts+31 added-7 removed
48 unmodified lines
49 maxSafeTimeout,50 responseTypes,51 getSupportedResponseTypes,52 stop,53 beforeRetryOptionKeys,54 isRetryMarker,55 supportsAbortController,56 supportsAbortSignal,57 supportsFormData,
155 unmodified lines
213 throw new RangeError(`The \`${name}\` option cannot be greater than ${maxSafeTimeout}`);214 }215};216217// Defaults only replace `undefined`, so a `null` reaches the validation and is reported instead of silently becoming the default.218const withAttemptDefaults = ({throwHttpErrors = true, timeout = 10_000, fetch = globalThis.fetch.bind(globalThis)}: Options) => ({throwHttpErrors, timeout, fetch});219220// These callbacks are called directly, so a non-function value otherwise surfaces as a runtime error naming Ky's own internals rather than the option the caller set.221const validateCallbackOptions = (options: Record<string, unknown>): void => {222 for (const key of ['parseJson', 'stringifyJson', 'fetch', 'onDownloadProgress', 'onUploadProgress'] as const) {223 if (options[key] !== undefined && typeof options[key] !== 'function') {
239 unmodified lines
463464 // Defaults only replace `undefined`, so a `null` reaches the validation below and is reported instead of silently becoming the default.465 const {466 maxResponseSize = Number.POSITIVE_INFINITY,463 throwHttpErrors = true,464 timeout = 10_000,467 totalTimeout = false,466 fetch = globalThis.fetch.bind(globalThis),468 } = options;469 if (Object.hasOwn(options, 'prefixUrl')) {470 throw new Error(prefixUrlRenamedErrorMessage);471 }
18 unmodified lines
490 referrerPolicy: options.referrerPolicy ?? (input as Request).referrerPolicy,491 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing492 prefix: String(options.prefix || ''),493 retry: normalizeRetryOptions(options.retry),493 throwHttpErrors,494 timeout,494 ...withAttemptDefaults(options),495 totalTimeout,496 maxResponseSize,497 fetch,497 context: options.context ?? {},498 };499 // Checked here rather than on the way out, because the constructor already calls `stringifyJson`.500 validateCallbackOptions(this.#options);502 validateTimeoutOption(timeout, 'timeout');501 validateTimeoutOption(this.#options.timeout, 'timeout');502 validateTimeoutOption(totalTimeout, 'totalTimeout');503 this.#retryLimit = this.#options.retry.limit;504505 if (maxResponseSize !== Number.POSITIVE_INFINITY && (!Number.isSafeInteger(maxResponseSize) || maxResponseSize < 0)) {
696 unmodified lines
1202 // If `stop` is returned from the hook, the retry process is stopped1203 if (hookResult === stop) {1204 return;1205 }12061207 if (isNonArrayObject(hookResult)) {1208 this.#applyBeforeRetryOptions(hookResult.options);1209 }1210 }12111212 this.#throwIfTotalTimeoutExhausted();1213
68 unmodified lines
1282 #getRemainingTotalTimeout(): number {1283 return Math.max(0, this.#deadline - getCurrentTime());1284 }12851286 // Omitted options keep their value, and `undefined` restores Ky's default. The changes apply to the next attempt and every later one.1287 #applyBeforeRetryOptions(options: unknown): void {1288 if (!isNonArrayObject(options)) {1289 throw new TypeError('The `options` returned from a `beforeRetry` hook must be an object');1290 }12911292 for (const key of Object.keys(options)) {1293 if (!(beforeRetryOptionKeys as readonly string[]).includes(key)) {1294 throw new TypeError(`The \`${key}\` option cannot be changed from a \`beforeRetry\` hook`);1295 }1296 }12971298 const mergedOptions = {...this.#options, ...options};1299 const updatedOptions = {...mergedOptions, ...withAttemptDefaults(mergedOptions)};1300 validateCallbackOptions(updatedOptions);1301 validateTimeoutOption(updatedOptions.timeout, 'timeout');13021303 Object.assign(this.#options, updatedOptions);1304 this.#cachedNormalizedOptions = undefined;1305 }13061307 #getNormalizedOptions(): NormalizedOptions {1308 if (!this.#cachedNormalizedOptions) {1309 // Exclude Ky-specific options that are not part of `RequestInit`.1310 const {
66 unmodified lines
modified:source/types/hooks.ts+51 added-3 removed
1import {type stop, type RetryMarker} from '../core/constants.js';1import {type stop, type RetryMarker, type beforeRetryOptionKeys} from '../core/constants.js';2import type {KyRequest, KyResponse} from '../index.js';3import type {InitOptions, NormalizedOptions} from './options.js';3import type {InitOptions, NormalizedOptions, Options} from './options.js';45/**6This 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
43 unmodified lines
51 */52 retryCount: number;53};5455export type BeforeRetryHook = (state: BeforeRetryState) => Request | Response | typeof stop | void | Promise<Request | Response | typeof stop | void>;55/**56The value a `beforeRetry` hook can return to change options for this retry and the ones after it.5758@example59```60import ky, {type BeforeRetryUpdate} from 'ky';6162const withoutUploadProgress = (): BeforeRetryUpdate => ({options: {onUploadProgress: undefined}});6364await ky.put(uploadUrl, {65 body: file,66 onUploadProgress: updateProgress,67 hooks: {68 beforeRetry: [withoutUploadProgress],69 },70});71```72*/73export type BeforeRetryUpdate = {74 options: Pick<Options, typeof beforeRetryOptionKeys[number]>;75};7677export type BeforeRetryHook = (state: BeforeRetryState) => Request | Response | BeforeRetryUpdate | typeof stop | void | Promise<Request | Response | BeforeRetryUpdate | typeof stop | void>;7879export type BeforeErrorState = {80 request: KyRequest;81 options: Readonly<NormalizedOptions>;82
121 unmodified lines
204 If the request received a response, the error will be of type `HTTPError`. The `Response` object will be available at `error.response`, and the pre-parsed response body may be available at `error.data`. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will be an instance of `NetworkError` instead of `HTTPError`.205206 You can prevent Ky from retrying the request by throwing an error. Ky will not handle it in any way and the error will be propagated to the request initiator. The rest of the `beforeRetry` hooks will not be called in this case. Alternatively, you can return the [`ky.stop`](#kystop) symbol to do the same thing but without propagating an error (this has some limitations, see `ky.stop` docs for details).207208 **Changing options:**209210 Return `{options: {...}}` to change `onUploadProgress`, `onDownloadProgress`, `timeout`, `fetch`, or `throwHttpErrors` for this retry and the ones after it. Omitted options keep their value, and `undefined` restores Ky's default, not the value from `ky.create()` or `ky.extend()`. Any other option, or an invalid value, throws an error. The remaining `beforeRetry` hooks still run and see the new progress callbacks in `options`. The `options` a hook receives never include `timeout`, `fetch`, or `throwHttpErrors`.211212 For example, turn off upload progress after a network error. Upload progress needs a streamed request body, which Chromium only sends over HTTP/2 or HTTP/3, so the upload fails on an HTTP/1.1 connection. Only retry an upload when it is safe to send it again, since a network error does not tell whether the server got the request.213214 @example215 ```216 import ky, {isNetworkError} from 'ky';217218 await ky.put(uploadUrl, {219 body: file,220 onUploadProgress: updateProgress,221 retry: {limit: 1},222 hooks: {223 beforeRetry: [224 ({error}) => {225 if (isNetworkError(error)) {226 return {options: {onUploadProgress: undefined}};227 }228 }229 ]230 }231 });232 ```233234 **Modifying headers:**235236 @example237 ```
187 unmodified lines
modified:source/types/options.ts+1 added-1 removed
317 unmodified lines
318319 /**320 Upload progress event handler.321322 Note: Requires [request stream support](https://caniuse.com/wf-fetch-request-streams) and, in Chromium-based browsers, an HTTP/2 or HTTP/3 connection (streaming uploads over HTTP/1.1 fail with a network error, even over plain HTTP). This handler is silently ignored in unsupported environments and for requests with `keepalive: true` or `mode: 'no-cors'`, since they cannot use streaming request bodies.322 Note: Requires [request stream support](https://caniuse.com/wf-fetch-request-streams) and, in Chromium-based browsers, an HTTP/2 or HTTP/3 connection (streaming uploads over HTTP/1.1 fail with a network error, even over plain HTTP). This handler is silently ignored in unsupported environments and for requests with `keepalive: true` or `mode: 'no-cors'`, since they cannot use streaming request bodies. If an upload fails over HTTP/1.1 in Chromium, you can retry it without upload progress by returning `{options: {onUploadProgress: undefined}}` from a [`beforeRetry`](#hooksbeforeretry) hook.323324 @param progress - Object containing upload progress information.325 @param chunk - Data that was sent. When an empty request body stream completes, the callback receives an empty chunk.326
229 unmodified lines
modified:source/index.ts+1 added
modified:test/browser.ts+73 added
828 unmodified lines
829830 t.deepEqual(results, ['rainbow', 'rainbow', 'rainbow', 'rainbow', 'recovered']);831 t.is(requestCount, 2);832});833834browserTest('beforeRetry upload progress override allows HTTP/1.1 fallback', [chromium], async (t, page) => {835 const uploadServer = await createEsmTestServer({bodyParser: false});836 t.teardown(uploadServer.close);837 uploadServer.get('/', (_request, response) => {838 response.end();839 });840 let receivedRequests = 0;841 uploadServer.put('/upload', async (request, response) => {842 receivedRequests++;843 const body = await parseRawBody(request);844 response.json({body, contentType: request.headers['content-type']});845 });846 await page.goto(uploadServer.url);847 await addKyScriptToPage(page);848849 const results = await page.evaluate(async (url: string) => {850 const formData = new FormData();851 formData.append('field', 'payload');852 const bodies = ['payload', new Blob(['payload']), formData, new URLSearchParams({field: 'payload'})];853 const results = [];854 for (const body of bodies) {855 let retryCount = 0;856 let errorName = '';857 let retryContentType: string | undefined;858 // eslint-disable-next-line no-await-in-loop859 const response = await globalThis.ky.put(`${url}/upload`, {860 body,861 onUploadProgress() {862 // Only enables the streamed upload, which fails over HTTP/1.1 in Chromium.863 },864 retry: {865 limit: 1,866 // A method, because tsx wraps an arrow function assigned to a property with a `__name` helper that does not exist in the page.867 delay() {868 return 0;869 },870 },871 hooks: {872 beforeRetry: [state => {873 retryCount = state.retryCount;874 errorName = state.error.name;875 retryContentType = state.request.headers.get('content-type') ?? undefined;876 return {options: {onUploadProgress: undefined}};877 }],878 },879 }).json<{body: string; contentType?: string}>();880 results.push({881 ...response,882 retryCount,883 errorName,884 retryContentType,885 });886 }887888 return results;889 }, uploadServer.url);890891 t.is(receivedRequests, 4);892 for (const result of results) {893 t.is(result.retryCount, 1);894 t.is(result.errorName, 'NetworkError');895 t.is(result.contentType, result.retryContentType);896 }897898 t.is(results[0]!.body, 'payload');899 t.is(results[1]!.body, 'payload');900 // The multipart boundary in the retried body must match its content type.901 const boundary = results[2]!.contentType!.split('boundary=')[1]!;902 t.true(results[2]!.body.startsWith(`--${boundary}\r\n`));903 t.true(results[2]!.body.includes('name="field"\r\n\r\npayload\r\n'));904 t.is(results[3]!.body, 'field=payload');905});
added:test/retry-options.ts+318 added
1import test from 'ava';2import ky from '../source/index.js';3import {createHttpTestServer} from './helpers/create-http-test-server.js';45// Retries right away, so the tests do not wait for a backoff.6const retryOnce = {limit: 1, delay: () => 0};78// A `fetch` that always answers `503` and counts its calls.9const createUnavailableFetch = () => {10 const state = {11 calls: 0,12 async fetch() {13 state.calls++;14 return new Response('retry', {status: 503});15 },16 };1718 return state;19};2021test('beforeRetry can turn off upload progress without losing the body', async t => {22 let attempts = 0;23 const progressAttempts: number[] = [];24 const response = await ky.put('https://example.com', {25 body: 'payload',26 retry: retryOnce,27 onUploadProgress() {28 progressAttempts.push(attempts);29 },30 async fetch(request) {31 attempts++;32 t.is(await request.text(), 'payload');33 if (attempts === 1) {34 throw new TypeError('Failed to fetch');35 }3637 return new Response('ok');38 },39 hooks: {40 beforeRetry: [() => ({options: {onUploadProgress: undefined}})],41 },42 });4344 t.is(await response.text(), 'ok');45 t.is(attempts, 2);46 t.deepEqual(progressAttempts, [1]);47});4849test('beforeRetry can turn on upload progress without losing the body', async t => {50 let attempts = 0;51 const progressAttempts: number[] = [];52 const response = await ky.put('https://example.com', {53 body: 'payload',54 retry: retryOnce,55 async fetch(request) {56 attempts++;57 t.is(await request.text(), 'payload');58 if (attempts === 1) {59 throw new TypeError('Failed to fetch');60 }6162 return new Response('ok');63 },64 hooks: {65 beforeRetry: [() => ({66 options: {67 onUploadProgress() {68 progressAttempts.push(attempts);69 },70 },71 })],72 },73 });7475 t.is(await response.text(), 'ok');76 t.deepEqual(progressAttempts, [2]);77});7879test('beforeRetry options apply to later retries and later hooks', async t => {80 let attempts = 0;81 let originalProgressCalls = 0;82 let replacementProgressCalls = 0;83 const originalProgress = () => {84 originalProgressCalls++;85 };8687 const replacementProgress = () => {88 replacementProgressCalls++;89 };9091 const seenProgress: unknown[] = [];92 const text = await ky('https://example.com', {93 onDownloadProgress: originalProgress,94 retry: {...retryOnce, limit: 2},95 async fetch() {96 attempts++;97 return new Response('ok', {status: attempts < 3 ? 503 : 200});98 },99 hooks: {100 beforeRetry: [101 ({options, retryCount}) => {102 seenProgress.push(options.onDownloadProgress);103 if (retryCount === 1) {104 return {options: {onDownloadProgress: replacementProgress}};105 }106 },107 ({options}) => {108 t.is(options.onDownloadProgress, replacementProgress);109 },110 ],111 },112 }).text();113114 t.is(text, 'ok');115 t.is(attempts, 3);116 t.deepEqual(seenProgress, [originalProgress, replacementProgress]);117 t.is(originalProgressCalls, 0);118 t.true(replacementProgressCalls > 0);119});120121test('beforeRetry can change fetch and throwHttpErrors', async t => {122 const unavailable = createUnavailableFetch();123 let replacementFetchCalls = 0;124 const response = await ky('https://example.com', {125 retry: retryOnce,126 fetch: unavailable.fetch,127 hooks: {128 beforeRetry: [() => ({129 options: {130 async fetch() {131 replacementFetchCalls++;132 return new Response('still failing', {status: 500});133 },134 throwHttpErrors: false,135 },136 })],137 },138 });139140 t.is(response.status, 500);141 t.is(unavailable.calls, 1);142 t.is(replacementFetchCalls, 1);143});144145test('beforeRetry can change throwHttpErrors to a function', async t => {146 const unavailable = createUnavailableFetch();147 const statuses: number[] = [];148 const response = await ky('https://example.com', {149 retry: retryOnce,150 fetch: unavailable.fetch,151 hooks: {152 beforeRetry: [() => ({153 options: {154 throwHttpErrors(status) {155 statuses.push(status);156 return false;157 },158 },159 })],160 },161 });162163 t.is(response.status, 503);164 t.deepEqual(statuses, [503]);165});166167test('beforeRetry can change the timeout', async t => {168 let attempts = 0;169 const response = await ky('https://example.com', {170 timeout: 10,171 retry: {...retryOnce, retryOnTimeout: true},172 async fetch(request) {173 attempts++;174 await new Promise(resolve => {175 setTimeout(resolve, 50);176 });177 request.signal.throwIfAborted();178 return new Response('ok');179 },180 hooks: {181 beforeRetry: [() => ({options: {timeout: 1000}})],182 },183 });184185 t.is(await response.text(), 'ok');186 t.is(attempts, 2);187});188189test('beforeRetry options apply to a response returned by a later hook', async t => {190 const unavailable = createUnavailableFetch();191 const response = await ky('https://example.com', {192 retry: retryOnce,193 fetch: unavailable.fetch,194 hooks: {195 beforeRetry: [196 () => ({options: {throwHttpErrors: false}}),197 () => new Response('from hook', {status: 500}),198 ],199 },200 });201202 t.is(response.status, 500);203 t.is(await response.text(), 'from hook');204 t.is(unavailable.calls, 1);205});206207test('beforeRetry `undefined` restores the global fetch', async t => {208 const server = await createHttpTestServer(t);209 server.get('/', (_request, response) => {210 response.end('native');211 });212213 const unavailable = createUnavailableFetch();214 const result = await ky(server.url, {215 retry: retryOnce,216 fetch: unavailable.fetch,217 hooks: {beforeRetry: [() => ({options: {fetch: undefined}})]},218 }).text();219220 t.is(result, 'native');221 t.is(unavailable.calls, 1);222});223224test('beforeRetry `undefined` restores Ky\'s default rather than the instance value', async t => {225 let attempts = 0;226 const api = ky.create({227 throwHttpErrors: false,228 retry: retryOnce,229 async fetch() {230 attempts++;231 if (attempts === 1) {232 throw new TypeError('Failed to fetch');233 }234235 return new Response('failed', {status: 500});236 },237 });238239 await t.throwsAsync(api('https://example.com', {240 hooks: {beforeRetry: [() => ({options: {throwHttpErrors: undefined}})]},241 }), {name: 'HTTPError'});242 t.is(attempts, 2);243});244245test('beforeRetry options do not leak into other requests from the same instance', async t => {246 let progressCalls = 0;247 const attempts = new Map<string, number>();248 const api = ky.create({249 retry: retryOnce,250 onUploadProgress() {251 progressCalls++;252 },253 async fetch(request) {254 const count = (attempts.get(request.url) ?? 0) + 1;255 attempts.set(request.url, count);256 await request.text();257 return new Response('ok', {status: count === 1 ? 503 : 200});258 },259 });260261 await api.put('https://example.com/changed', {262 body: 'payload',263 hooks: {beforeRetry: [() => ({options: {onUploadProgress: undefined}})]},264 });265 // A small body reports progress once per streamed attempt.266 t.is(progressCalls, 1);267268 await api.put('https://example.com/unchanged', {body: 'payload'});269 t.is(progressCalls, 3);270});271272test('beforeRetry options do not reset the retry limit', async t => {273 const unavailable = createUnavailableFetch();274 await t.throwsAsync(ky('https://example.com', {275 retry: {...retryOnce, limit: 2},276 fetch: unavailable.fetch,277 hooks: {beforeRetry: [() => ({options: {timeout: false}})]},278 }), {name: 'HTTPError'});279280 t.is(unavailable.calls, 3);281});282283const notAnOptionsObject = 'The `options` returned from a `beforeRetry` hook must be an object';284285for (const {name, update, message, errorClass = TypeError} of [286 {name: 'a missing `options`', update: {}, message: notAnOptionsObject},287 {name: 'array options', update: {options: []}, message: notAnOptionsObject},288 {name: '`null` options', update: {options: null}, message: notAnOptionsObject},289 {name: 'the `body` option', update: {options: {body: 'payload'}}, message: 'The `body` option cannot be changed from a `beforeRetry` hook'},290 {name: 'the `retry` option', update: {options: {retry: 10}}, message: 'The `retry` option cannot be changed from a `beforeRetry` hook'},291 {292 name: 'a `__proto__` key',293 update: {options: JSON.parse('{"__proto__": {"timeout": 1}}') as unknown},294 message: 'The `__proto__` option cannot be changed from a `beforeRetry` hook',295 },296 {name: 'an invalid callback', update: {options: {onUploadProgress: 'invalid'}}, message: 'The `onUploadProgress` option must be a function'},297 {name: 'a `null` fetch', update: {options: {fetch: null}}, message: 'The `fetch` option must be a function'},298 {name: 'an invalid throwHttpErrors', update: {options: {throwHttpErrors: 'yes'}}, message: 'The `throwHttpErrors` option must be a boolean or a function'},299 {name: 'a `null` throwHttpErrors', update: {options: {throwHttpErrors: null}}, message: 'The `throwHttpErrors` option must be a boolean or a function'},300 {name: 'a `null` timeout', update: {options: {timeout: null}}, message: 'The `timeout` option must be a non-negative number or `false`'},301 {302 name: 'an invalid timeout',303 update: {options: {timeout: 2 ** 31}},304 message: 'The `timeout` option cannot be greater than 2147483647',305 errorClass: RangeError,306 },307]) {308 test(`beforeRetry rejects ${name} before retrying`, async t => {309 const unavailable = createUnavailableFetch();310 await t.throwsAsync(ky('https://example.com', {311 retry: retryOnce,312 fetch: unavailable.fetch,313 hooks: {beforeRetry: [() => update as never]},314 }), {instanceOf: errorClass, message});315316 t.is(unavailable.calls, 1);317 });318}
modified:test-d/hooks.ts+39 added-1 removed
modified:readme.md+26 added-1 removed
572 unmodified lines
573If the request received a response, the error will be of type `HTTPError`. The `Response` object will be available at `error.response`, and the pre-parsed response body may be available at `error.data`. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will be an instance of `NetworkError` instead of `HTTPError`.574575You can prevent Ky from retrying the request by throwing an error. Ky will not handle it in any way and the error will be propagated to the request initiator. The rest of the `beforeRetry` hooks will not be called in this case. Alternatively, you can return the [`ky.stop`](#kystop) symbol to do the same thing but without propagating an error (this has some limitations, see `ky.stop` docs for details).576577**Changing options:**578579Return `{options: {...}}` to change `onUploadProgress`, `onDownloadProgress`, `timeout`, `fetch`, or `throwHttpErrors` for this retry and the ones after it. Omitted options keep their value, and `undefined` restores Ky's default, not the value from `ky.create()` or `ky.extend()`. Any other option, or an invalid value, throws an error. The remaining `beforeRetry` hooks still run and see the new progress callbacks in `options`. The `options` a hook receives never include `timeout`, `fetch`, or `throwHttpErrors`.580581For example, turn off upload progress after a network error. Upload progress needs a streamed request body, which Chromium only sends over HTTP/2 or HTTP/3, so the upload fails on an HTTP/1.1 connection. Only retry an upload when it is safe to send it again, since a network error does not tell whether the server got the request.582583```js584import ky, {isNetworkError} from 'ky';585586await ky.put(uploadUrl, {587 body: file,588 onUploadProgress: updateProgress,589 retry: {limit: 1},590 hooks: {591 beforeRetry: [592 ({error}) => {593 if (isNetworkError(error)) {594 return {options: {onUploadProgress: undefined}};595 }596 }597 ]598 }599});600```601602**Modifying headers:**603604```js605import ky from 'ky';
223 unmodified lines
829830Upload progress event handler.831832> [!NOTE]808> Requires [request stream support](https://caniuse.com/wf-fetch-request-streams) and, in Chromium-based browsers, an HTTP/2 or HTTP/3 connection (streaming uploads over HTTP/1.1 fail with a network error, even over plain HTTP). This handler is silently ignored in unsupported environments and for requests with `keepalive: true` or `mode: 'no-cors'`, since they cannot use streaming request bodies.833> Requires [request stream support](https://caniuse.com/wf-fetch-request-streams) and, in Chromium-based browsers, an HTTP/2 or HTTP/3 connection (streaming uploads over HTTP/1.1 fail with a network error, even over plain HTTP). This handler is silently ignored in unsupported environments and for requests with `keepalive: true` or `mode: 'no-cors'`, since they cannot use streaming request bodies. If an upload fails over HTTP/1.1 in Chromium, you can retry it without upload progress by returning `{options: {onUploadProgress: undefined}}` from a [`beforeRetry`](#hooksbeforeretry) hook.834835The function receives these arguments:836- `progress` is an object with these properties:837 - `percent` is a number between 0 and 1 representing the progress percentage.
1121 unmodified lines