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 fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308import type {Expect, Equal} from '@type-challenges/utils';import {type KyOptionsRegistry, type RequestHttpMethod} from '../types/options.js';
export const supportsRequestStreams = (() => { let duplexAccessed = false; let hasContentType = false; const supportsReadableStream = typeof globalThis.ReadableStream === 'function'; const supportsRequest = typeof globalThis.Request === 'function';
if (supportsReadableStream && supportsRequest) { try { hasContentType = new globalThis.Request('https://empty.invalid', { body: new globalThis.ReadableStream(), method: 'POST', // @ts-expect-error - Types are outdated. get duplex() { duplexAccessed = true; return 'half'; }, }).headers.has('Content-Type'); } catch { // Unsupported implementations throw different errors, such as QQBrowser on iOS throwing "unsupported BodyInit type" (see issue #581). return false; } }
// 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. const isBunOrDeno = 'Bun' in globalThis || 'Deno' in globalThis;
return (duplexAccessed || isBunOrDeno) && !hasContentType;})();
export const supportsAbortController = typeof globalThis.AbortController === 'function';export const supportsAbortSignal = typeof globalThis.AbortSignal === 'function' && typeof globalThis.AbortSignal.any === 'function';export const supportsResponseStreams = typeof globalThis.ReadableStream === 'function';export const supportsFormData = typeof globalThis.FormData === 'function';
export const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete', 'query'] as const;
const validate = <T extends Array<true>>() => undefined as unknown as T;validate<[ Expect<Equal<typeof requestMethods[number], RequestHttpMethod>>,]>();
// 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.export const responseTypes = { json: 'application/json', text: 'text/*', formData: 'multipart/form-data', arrayBuffer: '*/*', blob: '*/*', // Supported in modern Fetch implementations (for example, browsers and recent Node.js/undici). // We still feature-check at runtime before exposing the shortcut. bytes: '*/*',} as const;
// Only expose `.bytes()` when the environment implements it. Checked on each call, so a polyfill added after Ky is imported still counts.export const getSupportedResponseTypes = (): Array<keyof typeof responseTypes> => (Object.keys(responseTypes) as Array<keyof typeof responseTypes>).filter(type => type !== 'bytes' || typeof (globalThis.Response?.prototype as unknown as {bytes?: unknown})?.bytes === 'function');
// The maximum value of a 32bit int (see issue #117)export const maxSafeTimeout = 2_147_483_647;
// 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.export const usualFormBoundarySize = 40;
/**Symbol that can be returned by a `beforeRetry` hook to stop retrying without throwing an error.
Registered 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.*/export const stop = Symbol.for('ky.stop');
/**Options for forcing a retry via `ky.retry()`.*/export type ForceRetryOptions = { /** Custom delay in milliseconds before retrying.
If not provided, uses the default retry delay calculation based on `retry.delay` configuration.
**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.
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. */ delay?: number | undefined;
/** Error code for the retry.
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`.
@example ``` return ky.retry({code: 'RATE_LIMIT'}); // Resulting error message: 'Forced retry: RATE_LIMIT' ``` */ code?: string | undefined;
/** Original error that caused the retry.
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.
@example ``` try { const data = await response.json(); validateBusinessLogic(data); } catch (error) { return ky.retry({ code: 'VALIDATION_FAILED', cause: error // Preserves original error in chain }); } ``` */ cause?: Error | undefined;
/** Custom request to use for the retry.
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`.
**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.
**Warning:** Custom retry requests are not sanitized. If you reuse headers across origins, remove any credentials you do not want forwarded.
@example ``` // Fallback to a different endpoint return ky.retry({ request: new Request('https://backup-api.com/endpoint', { method: request.method, headers: request.headers, }), code: 'BACKUP_ENDPOINT' });
// Retry with refreshed authentication token const data = await response.json(); return ky.retry({ request: new Request(request, { headers: { ...Object.fromEntries(request.headers), 'Authorization': `Bearer ${data.newToken}` } }), code: 'TOKEN_REFRESHED' }); ``` */ request?: Request | undefined;};
/**Marker returned by `ky.retry()` to signal a forced retry from `afterResponse` hooks.*/export class RetryMarker { // 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. get isRetryMarker(): true { return true; }
options: ForceRetryOptions | undefined;
constructor(options?: ForceRetryOptions) { this.options = options; }}
export const isRetryMarker = (value: unknown): value is RetryMarker => value instanceof RetryMarker || (value as {isRetryMarker?: unknown} | undefined)?.isRetryMarker === true;
/**Force a retry from an `afterResponse` hook.
This 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`.
A 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.
@param options - Optional configuration for the retry.
@example```import ky, {isForceRetryError} from 'ky';
const api = ky.extend({ hooks: { afterResponse: [ async ({request, response}) => { // Retry based on response body content if (response.status === 200) { const data = await response.json();
// Simple retry with default delay if (data.error?.code === 'TEMPORARY_ERROR') { return ky.retry(); }
// Retry with custom delay from API response if (data.error?.code === 'RATE_LIMIT') { return ky.retry({ delay: data.error.retryAfter * 1000, code: 'RATE_LIMIT' }); }
// Retry with a modified request (e.g., fallback endpoint) if (data.error?.code === 'FALLBACK_TO_BACKUP') { return ky.retry({ request: new Request('https://backup-api.com/endpoint', { method: request.method, headers: request.headers, }), code: 'BACKUP_ENDPOINT' }); }
// Retry with refreshed authentication if (data.error?.code === 'TOKEN_REFRESH' && data.newToken) { return ky.retry({ request: new Request(request, { headers: { ...Object.fromEntries(request.headers), 'Authorization': `Bearer ${data.newToken}` } }), code: 'TOKEN_REFRESHED' }); }
// Retry with cause to preserve error chain try { validateResponse(data); } catch (error) { return ky.retry({ code: 'VALIDATION_FAILED', cause: error }); } } } ], beforeRetry: [ ({error, retryCount}) => { // Observable in beforeRetry hooks if (isForceRetryError(error)) { console.log(`Forced retry #${retryCount}: ${error.message}`); // Example output: "Forced retry #1: Forced retry: RATE_LIMIT" } } ] }});
const response = await api.get('https://example.com/api');```*/export const retry = (options?: ForceRetryOptions) => new RetryMarker(options);
// Ky reads these again for every attempt, so a `beforeRetry` hook can change them without rebuilding the request.export const beforeRetryOptionKeys = ['onUploadProgress', 'onDownloadProgress', 'timeout', 'fetch', 'throwHttpErrors'] as const;
export const kyOptionKeys: KyOptionsRegistry = { json: true, parseJson: true, stringifyJson: true, searchParams: true, baseUrl: true, prefix: true, retry: true, timeout: true, totalTimeout: true, maxResponseSize: true, hooks: true, throwHttpErrors: true, onDownloadProgress: true, onUploadProgress: true, fetch: true, context: true,};
// Standard RequestInit options that should NOT be passed separately to fetch()// because they're already applied to the Request object.// Note: `dispatcher` and `priority` are NOT included here - they're fetch-only// options that the Request constructor doesn't accept, so they need to be passed// separately to fetch().export const requestOptionsRegistry = { method: true, headers: true, body: true, mode: true, credentials: true, cache: true, redirect: true, referrer: true, referrerPolicy: true, integrity: true, keepalive: true, signal: true, window: true, duplex: true,} as const;