Skip to content
Myr

constants.ts

This file

Path

source/core/constants.ts

307 lines · 10.9 KiB · TypeScript

Last changed by

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

History of this file

Take it

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

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

line 1why, one step back
1import type {Expect, Equal} from '@type-challenges/utils';

Fix handling of uppercase `retry.methods` and improve typing (#789)Martin Vokrinekbefore adoptioncec10a9

line 2why, one step back
2import {type KyOptionsRegistry, type RequestHttpMethod} from '../types/options.js';

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

lines 3–20why, one step back
3
4export const supportsRequestStreams = (() => {5 let duplexAccessed = false;6 let hasContentType = false;7 const supportsReadableStream = typeof globalThis.ReadableStream === 'function';8 const supportsRequest = typeof globalThis.Request === 'function';910 if (supportsReadableStream && supportsRequest) {11 try {12 hasContentType = new globalThis.Request('https://empty.invalid', {13 body: new globalThis.ReadableStream(),14 method: 'POST',15 // @ts-expect-error - Types are outdated.16 get duplex() {17 duplexAccessed = true;18 return 'half';19 },20 }).headers.has('Content-Type');

Handle unsupported streaming uploads gracefullySindre Sorhusbefore adoption06ebf18

lines 21–23why, one step back
21 } catch {
22 // Unsupported implementations throw different errors, such as QQBrowser on iOS throwing "unsupported BodyInit type" (see issue #581).23 return false;

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

lines 24–26why, one step back
24 }
25 }26

Detect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c

lines 27–30why, one step back
27 // Bun and Deno support streaming request bodies but never read the `duplex` option, which the check relies on to tell streaming support apart from WebKit, where the `Request` constructor accepts a stream body that `fetch()` then rejects.
28 const isBunOrDeno = 'Bun' in globalThis || 'Deno' in globalThis;2930 return (duplexAccessed || isBunOrDeno) && !hasContentType;

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

lines 31–37why, one step back
31})();
3233export const supportsAbortController = typeof globalThis.AbortController === 'function';34export const supportsAbortSignal = typeof globalThis.AbortSignal === 'function' && typeof globalThis.AbortSignal.any === 'function';35export const supportsResponseStreams = typeof globalThis.ReadableStream === 'function';36export const supportsFormData = typeof globalThis.FormData === 'function';37

Add QUERY method support (#873)Sindre Sorhusbefore adoption6edddd9

line 38why, one step back
38export const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete', 'query'] as const;

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

lines 39–41why, one step back
39
40const validate = <T extends Array<true>>() => undefined as unknown as T;41validate<[

Fix handling of uppercase `retry.methods` and improve typing (#789)Martin Vokrinekbefore adoptioncec10a9

line 42why, one step back
42 Expect<Equal<typeof requestMethods[number], RequestHttpMethod>>,

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

lines 43–44why, one step back
43]>();
44

Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569

line 45why, one step back
45// The media type each shortcut advertises. Deliberately narrow: `.text()` asks for text and `.formData()` for multipart, so a server can serve a different representation of the same resource when the caller wants one.

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

lines 46–47why, one step back
46export const responseTypes = {
47 json: 'application/json',

Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569

lines 48–49why, one step back
48 text: 'text/*',
49 formData: 'multipart/form-data',

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

lines 50–56why, one step back
50 arrayBuffer: '*/*',
51 blob: '*/*',52 // Supported in modern Fetch implementations (for example, browsers and recent Node.js/undici).53 // We still feature-check at runtime before exposing the shortcut.54 bytes: '*/*',55} as const;56

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 57–61why, one step back
57// Only expose `.bytes()` when the environment implements it. Checked on each call, so a polyfill added after Ky is imported still counts.
58export const getSupportedResponseTypes = (): Array<keyof typeof responseTypes> =>59 (Object.keys(responseTypes) as Array<keyof typeof responseTypes>).filter(type =>60 type !== 'bytes' || typeof (globalThis.Response?.prototype as unknown as {bytes?: unknown})?.bytes === 'function');61

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

lines 62–64why, one step back
62// The maximum value of a 32bit int (see issue #117)
63export const maxSafeTimeout = 2_147_483_647;64

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

line 65why, one step back
65// Size in bytes of a typical form boundary (e.g., '------WebKitFormBoundaryaxpyiPgbbPti10Rw'), used to help estimate upload size. Bun's boundary is 54 bytes, so there the estimate runs 14 bytes low for each part and once more for the closing boundary. That is negligible next to a file, but for a body of many small fields `percent` can reach its ceiling before the upload ends. The final event always reports the real total.

Improve body size estimationSindre Sorhusbefore adoption7565d94

line 66why, one step back
66export const usualFormBoundarySize = 40;

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

line 67why, one step back
67

TweaksSindre Sorhusbefore adoption191057d

lines 68–69why, one step back
68/**
69Symbol that can be returned by a `beforeRetry` hook to stop retrying without throwing an error.

Recognise another copy of Ky: the stop symbol and the retry markerSindre Sorhusbefore adoption01b0839

lines 70–71why, one step back
70
71Registered globally so that a hook written against a second copy of Ky, which happens with a duplicated dependency, still stops the retries. A plain `Symbol` is per module, so the copies would not recognise each other's symbol.

TweaksSindre Sorhusbefore adoption191057d

line 72why, one step back
72*/

Recognise another copy of Ky: the stop symbol and the retry markerSindre Sorhusbefore adoption01b0839

line 73why, one step back
73export const stop = Symbol.for('ky.stop');

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

line 74why, one step back
74

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

lines 75–84why, one step back
75/**
76Options for forcing a retry via `ky.retry()`.77*/78export type ForceRetryOptions = {79 /**80 Custom delay in milliseconds before retrying.8182 If not provided, uses the default retry delay calculation based on `retry.delay` configuration.8384 **Note:** Custom delays bypass jitter and `backoffLimit`. This is intentional, as custom delays often come from server responses (e.g., `Retry-After` headers) and should be respected exactly as specified.

Accept a cross-realm `beforeError` error and validate a `ky.retry({delay})`Sindre Sorhusbefore adoptionbd0e26f

line 85why, one step back
85

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

line 86why, one step back
86 Must be a non-negative number, `Infinity` included, or `undefined`; anything else makes the request throw a `TypeError` rather than collapsing to a 1ms retry.

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

line 87why, one step back
87 */

Support readonly inputs and explicit undefined in TypeScript optionsSindre Sorhusbefore adoption51b3177

line 88why, one step back
88 delay?: number | undefined;

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

lines 89–92why, one step back
89
90 /**91 Error code for the retry.92

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

line 93why, one step back
93 This machine-readable identifier will be included in the error message passed to `beforeRetry` hooks, allowing you to distinguish between different types of forced retries. Anything other than a string makes the request throw a `TypeError`.

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

lines 94–100why, one step back
94
95 @example96 ```97 return ky.retry({code: 'RATE_LIMIT'});98 // Resulting error message: 'Forced retry: RATE_LIMIT'99 ```100 */

Support readonly inputs and explicit undefined in TypeScript optionsSindre Sorhusbefore adoption51b3177

line 101why, one step back
101 code?: string | undefined;

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

lines 102–110why, one step back
102
103 /**104 Original error that caused the retry.105106 This allows you to preserve the error chain when forcing a retry based on caught exceptions. The error will be set as the `cause` of the `ForceRetryError`, enabling proper error chain traversal.107108 @example109 ```110 try {

Readme tweaksSindre Sorhusbefore adoption7f2eade

line 111why, one step back
111 const data = await response.json();

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

lines 112–115why, one step back
112 validateBusinessLogic(data);
113 } catch (error) {114 return ky.retry({115 code: 'VALIDATION_FAILED',

Fix typosSindre Sorhusbefore adoptionbbc98fc

line 116why, one step back
116 cause: error // Preserves original error in chain

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

lines 117–120why, one step back
117 });
118 }119 ```120 */

Support readonly inputs and explicit undefined in TypeScript optionsSindre Sorhusbefore adoption51b3177

line 121why, one step back
121 cause?: Error | undefined;

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

lines 122–125why, one step back
122
123 /**124 Custom request to use for the retry.125

RefactorSindre Sorhusbefore adoptiona5ed57b

line 126why, one step back
126 This allows you to modify or completely replace the request during a forced retry. The custom request becomes the starting point for the retry - `beforeRetry` hooks can still further modify it if needed. Anything other than a `Request` or `undefined` makes the request throw a `TypeError`.

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

lines 127–129why, one step back
127
128 **Note:** The custom request's `signal` will be replaced with Ky's managed signal to handle timeouts and user-provided abort signals correctly. If the original request body has been consumed, you must provide a new body or clone the request before consuming.129

TweaksSindre Sorhusbefore adoption8f28eac

lines 130–131why, one step back
130 **Warning:** Custom retry requests are not sanitized. If you reuse headers across origins, remove any credentials you do not want forwarded.
131

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

lines 132–143why, one step back
132 @example
133 ```134 // Fallback to a different endpoint135 return ky.retry({136 request: new Request('https://backup-api.com/endpoint', {137 method: request.method,138 headers: request.headers,139 }),140 code: 'BACKUP_ENDPOINT'141 });142143 // Retry with refreshed authentication token

Readme tweaksSindre Sorhusbefore adoption7f2eade

line 144why, one step back
144 const data = await response.json();

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

lines 145–155why, one step back
145 return ky.retry({
146 request: new Request(request, {147 headers: {148 ...Object.fromEntries(request.headers),149 'Authorization': `Bearer ${data.newToken}`150 }151 }),152 code: 'TOKEN_REFRESHED'153 });154 ```155 */

Support readonly inputs and explicit undefined in TypeScript optionsSindre Sorhusbefore adoption51b3177

line 156why, one step back
156 request?: Request | undefined;

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

lines 157–159why, one step back
157};
158159/**

Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc

line 160why, one step back
160Marker returned by `ky.retry()` to signal a forced retry from `afterResponse` hooks.

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

lines 161–162why, one step back
161*/
162export class RetryMarker {

Recognise another copy of Ky: the stop symbol and the retry markerSindre Sorhusbefore adoption01b0839

lines 163–167why, one step back
163 // Branded so a marker created by a second copy of Ky, which happens with a duplicated dependency, is still recognised. A plain `instanceof` check fails across module instances, and the hook's intent would then vanish silently: no retry and no error.
164 get isRetryMarker(): true {165 return true;166 }167

Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc

lines 168–172why, one step back
168 options: ForceRetryOptions | undefined;
169170 constructor(options?: ForceRetryOptions) {171 this.options = options;172 }

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

line 173why, one step back
173}

Recognise another copy of Ky: the stop symbol and the retry markerSindre Sorhusbefore adoption01b0839

lines 174–176why, one step back
174
175export const isRetryMarker = (value: unknown): value is RetryMarker =>176 value instanceof RetryMarker || (value as {isRetryMarker?: unknown} | undefined)?.isRetryMarker === true;

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

lines 177–181why, one step back
177
178/**179Force a retry from an `afterResponse` hook.180181This allows you to retry a request based on the response content, even if the response has a successful status code. The retry will respect the `retry.limit` option and skip the `shouldRetry` check. The forced retry is observable in `beforeRetry` hooks, where the error will be a `ForceRetryError`.

Explain both causes of a missing response and document the new validationSindre Sorhusbefore adoption58233f1

lines 182–183why, one step back
182
183A marker returned by a second copy of Ky, which happens with a duplicated dependency, is still recognised, the same way the Ky error guards accept branded errors.

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

lines 184–193why, one step back
184
185@param options - Optional configuration for the retry.186187@example188```189import ky, {isForceRetryError} from 'ky';190191const api = ky.extend({192 hooks: {193 afterResponse: [

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 194why, one step back
194 async ({request, response}) => {

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

lines 195–196why, one step back
195 // Retry based on response body content
196 if (response.status === 200) {

Readme tweaksSindre Sorhusbefore adoption7f2eade

line 197why, one step back
197 const data = await response.json();

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

lines 198–264why, one step back
198
199 // Simple retry with default delay200 if (data.error?.code === 'TEMPORARY_ERROR') {201 return ky.retry();202 }203204 // Retry with custom delay from API response205 if (data.error?.code === 'RATE_LIMIT') {206 return ky.retry({207 delay: data.error.retryAfter * 1000,208 code: 'RATE_LIMIT'209 });210 }211212 // Retry with a modified request (e.g., fallback endpoint)213 if (data.error?.code === 'FALLBACK_TO_BACKUP') {214 return ky.retry({215 request: new Request('https://backup-api.com/endpoint', {216 method: request.method,217 headers: request.headers,218 }),219 code: 'BACKUP_ENDPOINT'220 });221 }222223 // Retry with refreshed authentication224 if (data.error?.code === 'TOKEN_REFRESH' && data.newToken) {225 return ky.retry({226 request: new Request(request, {227 headers: {228 ...Object.fromEntries(request.headers),229 'Authorization': `Bearer ${data.newToken}`230 }231 }),232 code: 'TOKEN_REFRESHED'233 });234 }235236 // Retry with cause to preserve error chain237 try {238 validateResponse(data);239 } catch (error) {240 return ky.retry({241 code: 'VALIDATION_FAILED',242 cause: error243 });244 }245 }246 }247 ],248 beforeRetry: [249 ({error, retryCount}) => {250 // Observable in beforeRetry hooks251 if (isForceRetryError(error)) {252 console.log(`Forced retry #${retryCount}: ${error.message}`);253 // Example output: "Forced retry #1: Forced retry: RATE_LIMIT"254 }255 }256 ]257 }258});259260const response = await api.get('https://example.com/api');261```262*/263export const retry = (options?: ForceRetryOptions) => new RetryMarker(options);264

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

lines 265–267why, one step back
265// 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;267

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

lines 268–272why, one step back
268export const kyOptionKeys: KyOptionsRegistry = {
269 json: true,270 parseJson: true,271 stringifyJson: true,272 searchParams: true,

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

lines 273–274why, one step back
273 baseUrl: true,
274 prefix: true,

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

lines 275–276why, one step back
275 retry: true,
276 timeout: true,

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

line 277why, one step back
277 totalTimeout: true,

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

line 278why, one step back
278 maxResponseSize: true,

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

lines 279–283why, one step back
279 hooks: true,
280 throwHttpErrors: true,281 onDownloadProgress: true,282 onUploadProgress: true,283 fetch: true,

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

line 284why, one step back
284 context: true,

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

lines 285–307why, one step back
285};
286287// Standard RequestInit options that should NOT be passed separately to fetch()288// because they're already applied to the Request object.289// Note: `dispatcher` and `priority` are NOT included here - they're fetch-only290// options that the Request constructor doesn't accept, so they need to be passed291// separately to fetch().292export const requestOptionsRegistry = {293 method: true,294 headers: true,295 body: true,296 mode: true,297 credentials: true,298 cache: true,299 redirect: true,300 referrer: true,301 referrerPolicy: true,302 integrity: true,303 keepalive: true,304 signal: true,305 window: true,306 duplex: true,307} as const;