Explain both causes of a missing response and document the new validation
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 33462fc · Browse files · 10 files·+69 added−39 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+69 added−39 removed
- tests:+15 added−1 removed
- other:+54 added−38 removed
Provenance
- Commit
58233f1- Tree
b07a8f3- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
33462fc
10 files changed+69 added−39 removed
modified:source/core/constants.ts+3 added-1 removed
55 unmodified lines56 57 // The maximum value of a 32bit int (see issue #117)58 export const maxSafeTimeout = 2_147_483_647;59 60-// Size in bytes of a typical form boundary (e.g., '------WebKitFormBoundaryaxpyiPgbbPti10Rw'), used to help estimate upload size60+// 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 per part low, which is negligible next to any real upload, and the final event always reports the real total.61 export const usualFormBoundarySize = 40;62 63 /**64 Symbol that can be returned by a `beforeRetry` hook to stop retrying without throwing an error.109 unmodified lines174 Force a retry from an `afterResponse` hook.175 176 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`.177 178+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.179+180 @param options - Optional configuration for the retry.181 182 @example183 ```116 unmodified linesmodified:source/core/Ky.ts+3 added-1 removed
78 unmodified lines79 return new TextDecoder();80 };81 82 const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';83-const missingResponseMessage = 'The request resolved without a response. Returning `ky.stop` from a `beforeRetry` hook is not compatible with body method shortcuts. Throw from the hook instead.';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`.';86 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 => {1498 unmodified linesmodified:source/types/ky.ts+6 added-5 removed
121 unmodified lines122 123 /**124 A `Symbol` that can be returned by a `beforeRetry` hook to stop the retry. This will also short circuit the remaining `beforeRetry` hooks.125 126- Note: Returning this symbol makes Ky abort and return with an `undefined` response. Be sure to check for a response before accessing any properties on it or use [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). It is also incompatible with body methods, such as `.json()` or `.text()`, because there is no response to parse. In general, we recommend throwing an error instead of returning this symbol, as that will cause Ky to abort and then throw, which avoids these limitations.126+ Note: Returning this symbol makes Ky abort and return with an `undefined` response. Be sure to check for a response before accessing any properties on it or use [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). It is also incompatible with body methods, such as `.json()` or `.text()`, because there is no response to parse. Calling one throws a `TypeError` explaining this. In general, we recommend throwing an error instead of returning this symbol, as that will cause Ky to abort and then throw, which avoids these limitations.127 128 A valid use-case for `ky.stop` is to prevent retries when making requests for side effects, where the returned data is not important. For example, logging client activity to the server.129 130 @example131 ```132 import ky from 'ky';133 134- // Note that response will be `undefined` in case `ky.stop` is returned.134+ // Note that `response` will be `undefined` in case `ky.stop` is returned.135 const response = await ky.post('https://example.com', {136 hooks: {137 beforeRetry: [138- async ({error}) => {138+ async ({request, options, error, retryCount}) => {139 const shouldStopRetry = await ky('https://example.com/api');140 if (shouldStopRetry) {141 return ky.stop;142 }1 unmodified line144 ]145 }146 });147 148- // Using `.text()` or other body methods is not supported.149- // const text = await ky('https://example.com', options).text();148+ // Using `.text()` or other body methods is not supported, because there is no response to parse.149 ```150 */151 readonly stop: typeof stop;152 1 unmodified line154 Force a retry from an `afterResponse` hook.155 156 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`.157 158+ 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.159+160 @example161 ```162 import ky, {isForceRetryError} from 'ky';163 40 unmodified linesmodified:source/types/options.ts+1 added-19 removed
291 unmodified lines292 @param chunk - Data that was received. When an empty response body stream completes, the callback receives an empty chunk.293 294 `content-length` is only used as the total for a response that is not content-coded, since it counts encoded bytes while the progress stream counts the bytes after decompression. A compressed response therefore reports `totalBytes: 0` until it completes, which means the percentage cannot be calculated while downloading.295 296- Responses with no body at all are not streamed, so no progress events are emitted for them. That covers a [null body status](https://fetch.spec.whatwg.org/#null-body-status) such as `204`, and a `HEAD` request, which has no body even on an ordinary status. A response whose body an `afterResponse` hook already read, or locked with a reader, is passed through unchanged, so it reports no progress either.296+ Responses with no body at all are not streamed, so no progress events are emitted for them. That covers a [null body status](https://fetch.spec.whatwg.org/#null-body-status) such as `204`, and a `HEAD` response in runtimes that give it no body, such as browsers, Node.js and Deno. Bun gives a `HEAD` response an empty body, so it reports one final event with `transferredBytes: 0`. A response whose body an `afterResponse` hook already read, or locked with a reader, is passed through unchanged, so it reports no progress either.297 298 When the callback throws, the error is reported by Ky's body method shortcuts. A response read directly with `response.text()` or `response.json()` may instead report the runtime's own stream error, such as Chromium's generic `TypeError`.299 300 @example149 unmodified lines450 export interface Options extends KyOptions, RequestOptions { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- This must stay an interface so that it can be extended outside of Ky for use in `ky.create`.451 /**452 HTTP method used to make the request.453 454- Ky forwards every option it does not recognize straight to `fetch()`, so fetch-only extensions are supported even455- when the ambient `RequestInit` type does not declare them. The two documented below are declared here for that456- reason; any other extension is accepted at runtime and needs a type assertion.457- */458-459- /**460- An undici `Agent` or `Dispatcher`, forwarded to `fetch()` as-is.461- */462- dispatcher?: unknown;463-464- /**465- A framework-specific fetch extension, such as Next.js's `next`, forwarded to `fetch()` as-is.466- */467- next?: unknown;468-469- /**470- HTTP method used to make the request.471-454 Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD`, `DELETE`, and `QUERY`) are uppercased in order to avoid server errors due to case sensitivity.455 */456 method?: LiteralUnion<HttpMethod, string> | undefined;457 93 unmodified linesmodified:source/types/ResponsePromise.ts+1 added-1 removed
122345663 unmodified lines/**Returns a `Response` object with `Body` methods added for convenience. So you can, for example, call `ky.get(input).json()` directly without having to await the `Response` first. When called like that, an appropriate `Accept` header will be set depending on the body method used. Unlike the `Body` methods of `window.fetch`, these will throw an `HTTPError` if the response status is not in the range of `200...299`. Note that `.json()` will throw if the body is empty, as it cannot be parsed. However, you can use the `parseJson` option to add custom handling for empty bodies.Returns a `Response` object with `Body` methods added for convenience. So you can, for example, call `ky.get(input).json()` directly without having to await the `Response` first. When called like that, an appropriate `Accept` header will be set depending on the body method used. Unlike the `Body` methods of `window.fetch`, these will throw an `HTTPError` if the response status is not in the range of `200...299`. Note that `.json()` will throw if the body is empty, as it cannot be parsed. However, you can use the `parseJson` option to add custom handling for empty bodies. If the signal passed in the `signal` option is aborted while the body is being read, or just after it finished, the shortcut rejects with the abort reason, the same as `.json()` always has.*/import {type KyResponse} from './response.js';import type {StandardSchemaV1, StandardSchemaV1InferOutput} from './standard-schema.js';
63 unmodified linesmodified:source/utils/merge.ts+2 added-2 removed
414 unmodified lines415 value = {limit: value};416 }417 }418 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.419+ if (isRoot && isPlainObject(value) && (isReplace || !isMergeable(returnValue[key]))) {420+ // Resolve nested replacement markers even when there is no parent 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/hooks.ts+6 added-1 removed
12 unmodified lines13 } from '../source/index.js';14 import {type Options, type NormalizedOptions} from '../source/types/options.js';15 import {createHttpTestServer} from './helpers/create-http-test-server.js';16 17+// Kept in sync with `missingResponseMessage` in source/core/Ky.ts.18+const noResponseMessage = 'The request resolved without a response, so there is no body to read.'19+ + ' Returning `ky.stop` from a `beforeRetry` hook, or a custom `fetch` that resolves with nothing, both do that.'20+ + ' Throw from the hook instead of returning `ky.stop`.';21+22 const withHeader = (request: Request, name: string, value: string) => {23 const headers = new Headers(request.headers);24 headers.set(name, value);25 return new Request(request, {headers});6891 unmodified lines6917 beforeRetry: [() => ky.stop],6918 },6919 })[type](), {6920 name: 'TypeError',6916- message: 'The request resolved without a response. Returning `ky.stop` from a `beforeRetry` hook is not compatible with body method shortcuts. Throw from the hook instead.',6921+ message: noResponseMessage,6922 });6923 });6924 }6925 586 unmodified linesmodified:test/main.ts+9 added
2580 unmodified lines2581 t.deepEqual(result, {foo: 'bar', baz: 'baz'});2582 t.false('context' in result);2583 });2584 2585+test('json merging resolves nested replacement markers without a parent property', async t => {2586+ const api = ky.create({2587+ fetch: async request => new Response(await request.text()),2588+ });2589+ const extended = api.extend({json: {items: replaceOption(['new'])}});2590+2591+ t.deepEqual(await extended.post('https://example.com').json(), {items: ['new']});2592+});2593+2594 for (const [original, replacement] of [2595 [['old'], {value: 'new'}],2596 [{value: 'old'}, ['new']],2597 ] as const) {1718 unmodified linesmodified:test-d/fetch-extensions.ts+16 added-4 removed
1+import {expectTypeOf} from 'expect-type';2 import type {Options} from 'ky';3 3-// Ky forwards options it does not recognize to `fetch()`, so a fetch-only extension must be accepted even though4-// the ambient `RequestInit` type does not declare it.5-const withDispatcher: Options = {dispatcher: {fake: true}};4+type NextFetchRequestConfig = {5+ revalidate?: number | false;6+ tags?: string[];7+};8+9+// Frameworks and runtimes declare their fetch-only extensions on the global `RequestInit`, the way Next.js declares `next` and `@types/node` declares `dispatcher`. Ky must pick up that type rather than redeclare the option, which conflicts with the ambient declaration.10+declare global {11+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- Global augmentation requires an interface.12+ interface RequestInit {13+ next?: NextFetchRequestConfig;14+ }15+}16+17 const withNext: Options = {next: {revalidate: 0}};18 8-void withDispatcher;19+expectTypeOf<Options['next']>().toEqualTypeOf<NextFetchRequestConfig | undefined>();20+21 void withNext;modified:readme.md+22 added-5 removed
400 unmodified lines401 402 Type: `number | false`\403 Default: `10000`404 405-Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Ky shortcut methods also use this value as a separate timeout for reading the response body. Cannot be greater than 2147483647. See also [`totalTimeout`](#totaltimeout).405+Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Ky shortcut methods also use this value as a separate timeout for reading the response body. Must be a non-negative number no greater than 2147483647, or `false`; anything else throws a `TypeError`. See also [`totalTimeout`](#totaltimeout).406 407 If set to `false`, there will be no per-attempt timeout.408 409+If the signal you passed in is aborted while a body method is reading, or just after the read finished, the body method rejects with the abort reason rather than resolving with the bytes that already arrived.410+411 ##### totalTimeout412 413 Type: `number | false`\414 Default: `false`415 414-Overall timeout in milliseconds for the entire operation, including retries and delays. Throws a `TimeoutError` if exceeded. Cannot be greater than 2147483647.416+Overall timeout in milliseconds for the entire operation, including retries and delays. Throws a `TimeoutError` if exceeded. Must be a non-negative number no greater than 2147483647, or `false`; anything else throws a `TypeError`.417 418 `beforeError` hooks run after an error is produced and are not bounded by `totalTimeout`.419 420 If set to `false` or not specified, there is no overall timeout.32 unmodified lines453 maxResponseSize: 20 * 1024 * 1024,454 }).json();455 ```456 457+##### dispatcher458+459+An [undici](https://github.com/nodejs/undici) `Agent` or `Dispatcher`, forwarded to `fetch()` as-is. Ky does not use it, it just passes it through.460+461+##### next462+463+A framework-specific fetch extension, such as [Next.js's `next`](https://nextjs.org/docs/app/api-reference/functions/next#options), forwarded to `fetch()` as-is.464+465+Ky forwards every option it does not recognize to `fetch()`. The type of such an option comes from the global `RequestInit` type, which `@types/node` extends with `dispatcher` and Next.js extends with `next`. An extension that your environment does not declare needs a type assertion.466+467 ##### hooks468 469 Type: `object<string, Function[]>`\470 Default: `{init: [], beforeRequest: [], beforeRetry: [], beforeError: [], afterResponse: []}`471 472 Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially, unless otherwise noted.473 474+Each hook must be an array of functions. A single function, a string, or any other value throws a `TypeError` rather than being silently dropped, and a nullish value means absent, so it clears the hooks it would have replaced.475+476 ###### hooks.init477 478 Type: `Function[]`\479 Default: `[]`297 unmodified lines777 - `chunk` is an instance of `Uint8Array` containing the data that was received. When an empty response body stream completes, the callback receives an empty chunk.778 779 `content-length` is only used as the total for a response that is not content-coded, since it counts encoded bytes while the progress stream counts the bytes after decompression. A compressed response therefore reports `totalBytes: 0` until it completes, so the percentage cannot be calculated while downloading.780 767-Responses with no body at all are not streamed, so no progress events are emitted for them. That covers a [null body status](https://fetch.spec.whatwg.org/#null-body-status) such as `204`, and a `HEAD` request, which has no body even on an ordinary status. A response whose body an `afterResponse` hook already read, or locked with a reader, is passed through unchanged, so it reports no progress either.781+Responses with no body at all are not streamed, so no progress events are emitted for them. That covers a [null body status](https://fetch.spec.whatwg.org/#null-body-status) such as `204`, and a `HEAD` response in runtimes that give it no body, such as browsers, Node.js and Deno. Bun gives a `HEAD` response an empty body, so it reports one final event with `transferredBytes: 0`. A response whose body an `afterResponse` hook already read, or locked with a reader, is passed through unchanged, so it reports no progress either.782 783 When the callback throws, the error is reported by Ky's body method shortcuts. A response read directly with `response.text()` or `response.json()` may instead report the runtime's own stream error, such as Chromium's generic `TypeError`.784 785 ```js324 unmodified lines1110 ]1111 }1112 });1113 1100-// Using `.text()` or other body methods is not supported.1101-const text = await ky('https://example.com', options).text();1114+// Using `.text()` or other body methods is not supported, because there is no response to parse.1115 ```1116 1117 ### ky.retry(options?)1118 1119 Force a retry from an `afterResponse` hook.1120 1121 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`.1122 1123+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.1124+1125 #### options1126 1127 Type: `object`1128 4 unmodified lines1133 Custom delay in milliseconds before retrying. If not provided, uses the default retry delay calculation based on `retry.delay` configuration.1134 1135 **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.1136 1137+Must be a non-negative number, or `undefined`; anything else throws a `TypeError` rather than collapsing to a 1ms retry.1138+1139 ##### code1140 1141 Type: `string`1142 785 unmodified lines