Skip to content
Myr

Resolve leftover `replaceOption()` wrappers, name the request behind a response, and advertise the media types

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 23ca564 · Browse files · 6 files+326 added−18 removed
This commit

State

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

Diff stats

6 files+326 added−18 removed

  • tests:+260 added−0 removed
  • other:+66 added−18 removed

6 files+326 added−18 removed

modified:source/core/constants.ts+5 added-2 removed
40 unmodified lines
41validate<[42 Expect<Equal<typeof requestMethods[number], RequestHttpMethod>>,43]>();4445// Each media type is one Ky can actually parse, so a server that only serves one of them does not answer 406 to a46// request the matching shortcut would have handled.47export const responseTypes = {48 json: 'application/json',47 text: 'text/*',48 formData: 'multipart/form-data',49 // `.text()` returns JSON as-is, and `.formData()` parses URL-encoded bodies as well as multipart ones.50 text: 'text/*, application/json',51 formData: 'multipart/form-data, application/x-www-form-urlencoded',52 arrayBuffer: '*/*',53 blob: '*/*',54 // Supported in modern Fetch implementations (for example, browsers and recent Node.js/undici).55 // We still feature-check at runtime before exposing the shortcut.
232 unmodified lines
modified:source/core/Ky.ts+23 added-15 removed
77 unmodified lines
78 return new TextDecoder();79};8081const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';82const 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.';8384// Both timeout options are milliseconds or `false`. A non-finite or negative value used to reach `setTimeout()`,85// which silently clamps it to ~1ms, or to be ignored entirely when `totalTimeout` was not a number.86const validateTimeoutOption = (value: unknown, name: 'timeout' | 'totalTimeout'): void => {
289 unmodified lines
376 if (originalRequest?.body !== response?.body) {377 ky.#cancelBody(originalRequest?.body ?? undefined);378 }379379 // Only cancel the current request body if it's distinct from the original (i.e. it was cloned for retries).380 if (ky.request !== originalRequest && ky.request.body !== response?.body) {380 // Only cancel the current request body if it's distinct from the original (i.e. it was cloned for381 // retries). `#originalRequest` is only set once a request is handed to fetch, so a pipeline that382 // never started, for example one that failed validation, leaves the caller's own body alone.383 if (originalRequest && ky.request !== originalRequest && ky.request.body !== response?.body) {384 ky.#cancelBody(ky.request.body ?? undefined);385 }386 }387 })() as ResponsePromise;
15 unmodified lines
403404 // `ky.stop` from a `beforeRetry` hook resolves the request with no response at all. Reading a body405 // method would otherwise crash deep inside Ky with a TypeError that names Ky internals.406 if (response === undefined) {404 throw new TypeError('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.');407 throw new TypeError(missingResponseMessage);408 }409410 if (type !== 'json') {411 return ky.#raceBodyRead(async () => response[type](), response);
20 unmodified lines
432 }, ky.#userProvidedAbortSignal);433 } catch (error: unknown) {434 // 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.435 if (ky.#userProvidedAbortSignal?.aborted) {433 await ky.#throwProcessedError(ky.#userProvidedAbortSignal.reason);436 await ky.#throwProcessedError(ky.#userProvidedAbortSignal.reason, request);437 }438439 throw error;440 }441442 if (parsedResult === timedOutOperation) {440 await ky.#throwProcessedError(new TimeoutError(request));443 await ky.#throwProcessedError(new TimeoutError(request), request);444 }445446 return parsedResult;447 };
320 unmodified lines
768769 return response;770 }771772 // Defaults to the last request that was actually sent, because `this.request` is the clone `#fetch()` prepares773 // for a possible retry and may never be sent at all.769 async #throwProcessedError(error: unknown): Promise<never> {774 async #throwProcessedError(error: unknown, request: Request = this.#originalRequest ?? this.request): Promise<never> {775 // Non-Error throws (e.g., thrown strings) pass through unchanged776 if (!(error instanceof Error)) {777 throw error;778 }
4 unmodified lines
783 }784785 let processedError: Error = error;786 for (const hook of this.#options.hooks.beforeError) {782 // `request` is the current failing request. `options` intentionally remains the783 // stable normalized Ky options snapshot for the same reason as `HTTPError` above.787 // `options` intentionally remains the stable normalized Ky options snapshot for the same reason as `HTTPError` above.788 // eslint-disable-next-line no-await-in-loop789 const hookResult: unknown = await hook({786 request: this.request,790 request,791 options: this.#getNormalizedOptions(),792 error: processedError,793 retryCount: this.#retryCount,794 });
83 unmodified lines
878879 // Unlike error bodies (`#getResponseData`), a successful body read has no fallback value to return -880 // the caller's `.json()`/`.text()`/etc. promise must settle, so a timeout here always rejects.881 async #raceBodyRead(createBodyPromise: () => Promise<unknown>, response: Response): Promise<unknown> {882 const failedRequest = this.#getResponseRequest(response);883 let timeoutMs: number | undefined;884 try {885 timeoutMs = this.#getEffectiveTimeout();886 } catch (error: unknown) {882 await this.#throwProcessedError(error);887 await this.#throwProcessedError(error, failedRequest);888 }889890 const bodyPromise = createBodyPromise();891 const timeoutPromise = timeoutMs === undefined
13 unmodified lines
905 ? await bodyPromise906 : await Promise.race([bodyPromise, timeoutPromise]);907 } catch (error: unknown) {908 if (this.#userProvidedAbortSignal?.aborted) {904 await this.#throwProcessedError(this.#userProvidedAbortSignal.reason);909 await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);910 }911912 if (this.#getRemainingTotalTimeout() !== 0) {913 // 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.914 const progressCallbackError = getProgressCallbackError(response.body ?? undefined);915 if (progressCallbackError !== undefined) {911 await this.#throwProcessedError(progressCallbackError);916 await this.#throwProcessedError(progressCallbackError, failedRequest);917 }918919 // 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.920 // This only happens on the awaited path, so a body that fails after the timeout already won does not run the hooks again.921 if (isRawNetworkError(error)) {917 await this.#throwProcessedError(new NetworkError(this.#getResponseRequest(response), {cause: error as Error}));922 await this.#throwProcessedError(new NetworkError(failedRequest, {cause: error as Error}), failedRequest);923 }924920 await this.#throwProcessedError(error);925 await this.#throwProcessedError(error, failedRequest);926 }927928 result = timedOutResponseData;929 }
2 unmodified lines
932 // The stream is locked by the native body method's own reader by this point, so933 // `response.body.cancel()` would reject as "already locked". Aborting the request's934 // signal is what actually interrupts the underlying network read.935 this.#abortController?.abort();931 await this.#throwProcessedError(new TimeoutError(this.#getResponseRequest(response)));936 await this.#throwProcessedError(new TimeoutError(failedRequest), failedRequest);937 }938939 return result;940 }
255 unmodified lines
1196 let modifiedResponse;1197 try {1198 // eslint-disable-next-line no-await-in-loop1199 modifiedResponse = await this.#raceWithTotalTimeout(async () => hook({1200 // Deliberately `this.request`, which `#fetch()` has already replaced with the clone prepared for a1201 // retry, so its body is still unread. A hook that forces a retry with `ky.retry({request: new1202 // Request(request)})` depends on being able to copy an unconsumed request from here.1203 request: this.request,1204 options: this.#getNormalizedOptions(),1205 response: hookResponse,1206 retryCount: this.#retryCount,
301 unmodified lines
modified:source/utils/merge.ts+38 added-1 removed
209 unmodified lines
210);211212export const deletedParametersSymbol = Symbol('deletedParameters');213214// `replaceOption()` can wrap a value at any depth of a deep-merged option, but a wrapper is only unwrapped where a215// merge actually runs, so a wrapper on a key with no parent value kept its `{value}` envelope. This resolves the216// leftovers in one pass, copying only the branches that actually contained a wrapper so every other value keeps its217// identity. `seen` keeps a cyclic option from recursing forever; a cyclic branch is left as-is.218const resolveReplaceMarkers = (value: unknown, seen: Set<Record<string, unknown> | unknown[]>): unknown => {219 if (!isMergeable(value) || seen.has(value)) {220 return value;221 }222223 seen.add(value);224 const resolveItem = (item: unknown) => resolveReplaceMarkers(getReplaceState(item).value, seen);225226 if (Array.isArray(value)) {227 let resolved: unknown[] | undefined;228 for (const [index, item] of value.entries()) {229 const replacement = resolveItem(item);230 if (replacement !== item) {231 resolved ??= [...value];232 resolved[index] = replacement;233 }234 }235236 return resolved ?? value;237 }238239 let resolved: Record<string, unknown> | undefined;240 for (const [key, item] of Object.entries(value)) {241 const replacement = resolveItem(item);242 if (replacement !== item) {243 resolved ??= {...value};244 resolved[key] = replacement;245 }246 }247248 return resolved ?? value;249};250251const appendSearchParameters = (target: any, source: any): URLSearchParams => {252 const result = new URLSearchParams() as URLSearchParams & {[deletedParametersSymbol]?: Set<string>};253 // Deleted keys stay marked even when a later layer re-adds the key, so the key is still removed from the input URL before the re-added value is appended.254 const deleted = new Set<string>();
183 unmodified lines
438 returnValue.signal = signals.at(-1);439 }440 }441405 return returnValue;442 return isRoot ? resolveReplaceMarkers(returnValue, new Set()) : returnValue;443};444445export const deepMerge = <T>(...sources: Array<Partial<T> | undefined>): T =>446 deepMergeInternal<T>(true, ...sources);
modified:test/hooks.ts+183 added
7021 unmodified lines
70227023 t.deepEqual(attemptCounts, [1, 1, 1, 1]);7024 t.deepEqual(ownRetry, {limit: 0, delay: ownRetry.delay});7025});70267027// `afterResponse` hooks deliberately receive the clone `#fetch()` prepared for a possible retry, whose body is7028// still unread, so a hook that forces a retry can copy an unconsumed request from it.7029test('an `afterResponse` hook can copy the unconsumed request it is given', async t => {7030 const bodies: string[] = [];7031 let attempts = 0;70327033 const text = await ky.post('https://example.com', {7034 body: 'payload',7035 retry: {limit: 1, methods: ['post'], delay: () => 0},7036 async fetch(request) {7037 attempts++;7038 bodies.push(await request.text());7039 return attempts === 1 ? new Response('server error', {status: 500}) : new Response('ok');7040 },7041 hooks: {7042 afterResponse: [({request, response}) => {7043 if (response.status === 500) {7044 return ky.retry({request: new Request(request)});7045 }7046 }],7047 },7048 }).text();70497050 t.is(text, 'ok');7051 t.deepEqual(bodies, ['payload', 'payload']);7052});70537054test('an `afterResponse` hook receives the replacement request from `beforeRequest`', async t => {7055 let sent: Request | undefined;7056 const hookUrls: string[] = [];7057 const replacement = new Request('https://example.com/replacement');70587059 await ky('https://example.com', {7060 retry: 1,7061 async fetch(request) {7062 sent = request;7063 return new Response('ok');7064 },7065 hooks: {7066 beforeRequest: [() => replacement],7067 afterResponse: [({request}) => {7068 hookUrls.push(request.url);7069 }],7070 },7071 }).text();70727073 t.is(sent?.url, 'https://example.com/replacement');7074 t.deepEqual(hookUrls, ['https://example.com/replacement']);7075});70767077// `beforeError` hooks received `this.request`, which `#fetch()` replaces with a clone prepared for a possible retry, so the hook got a request object that was never sent and did not match the request on the error.7078test('a `beforeError` hook receives the request that failed', async t => {7079 for (const retry of [0, 2]) {7080 let sent: Request | undefined;7081 let hookRequest: Request | undefined;7082 let errorRequest: unknown;70837084 // eslint-disable-next-line no-await-in-loop7085 const error = await t.throwsAsync(ky('https://example.com', {7086 retry,7087 async fetch(request) {7088 sent = request;7089 return new Response('server error', {status: 500});7090 },7091 hooks: {7092 beforeError: [({request, error: hookError}) => {7093 hookRequest = request;7094 errorRequest = (hookError as {request?: unknown}).request;7095 }],7096 },7097 }).text());70987099 t.is(hookRequest, sent, `retry: ${retry}`);7100 t.is(errorRequest, sent, `retry: ${retry}`);7101 t.is((error as {request?: unknown}).request, sent, `retry: ${retry}`);7102 }7103});71047105test('a `beforeError` hook receives the request that failed during a body read', async t => {7106 let sent: Request | undefined;7107 const hookRequests: Array<Request | undefined> = [];71087109 await t.throwsAsync(ky('https://example.com', {7110 retry: 1,7111 async fetch(request) {7112 sent = request;7113 return new Response(new ReadableStream({7114 start(controller) {7115 controller.error(new TypeError('terminated'));7116 },7117 }));7118 },7119 hooks: {7120 beforeError: [({request}) => {7121 hookRequests.push(request);7122 }],7123 },7124 }).text());71257126 t.is(hookRequests.length, 1);7127 t.is(hookRequests[0], sent);7128});71297130// The cleanup in the request pipeline cancelled the current request body even when fetch was never called, so a7131// caller-owned upload stream was destroyed by a configuration error or a hook that threw before the request started.7132test('a request that never started leaves the caller-owned body alone', async t => {7133 const failedFetches: boolean[] = [];7134 const cancelledBodies: boolean[] = [];71357136 for (const options of [7137 {7138 hooks: {7139 beforeRequest: [() => {7140 throw new Error('boom');7141 }],7142 },7143 },7144 // Invalid options are rejected by the constructor, before the pipeline and its cleanup exist, so these two guard against validation moving back into the pipeline.7145 {timeout: 3_000_000_000},7146 {7147 hooks: {7148 init: [options => {7149 options.timeout = 3_000_000_000;7150 }],7151 },7152 },7153 ]) {7154 let cancelled = false;7155 let fetchCalled = false;7156 const body = new ReadableStream<Uint8Array>({7157 start(controller) {7158 controller.enqueue(new TextEncoder().encode('hi'));7159 },7160 cancel() {7161 cancelled = true;7162 },7163 });71647165 // eslint-disable-next-line no-await-in-loop7166 await t.throwsAsync(ky('https://example.com', {7167 method: 'POST',7168 body,7169 retry: 0,7170 ...options,7171 async fetch() {7172 fetchCalled = true;7173 return new Response('ok');7174 },7175 }).text());71767177 failedFetches.push(fetchCalled);7178 cancelledBodies.push(cancelled);7179 }71807181 t.deepEqual(failedFetches, [false, false, false]);7182 t.deepEqual(cancelledBodies, [false, false, false]);7183});71847185test('a request that did start still releases its upload body', async t => {7186 let cancelled = false;7187 const body = new ReadableStream<Uint8Array>({7188 start(controller) {7189 controller.enqueue(new TextEncoder().encode('hi'));7190 },7191 cancel() {7192 cancelled = true;7193 },7194 });71957196 await ky('https://example.com', {7197 method: 'POST',7198 body,7199 retry: 0,7200 fetch: async () => new Response('ok'),7201 }).text();72027203 await new Promise(resolve => {7204 setTimeout(resolve, 10);7205 });72067207 t.true(cancelled);7208});
modified:test/response-consumption.ts+47 added
232 unmodified lines
233234 t.is(fetchCalls, 1);235 t.is(hookCalls, 1);236});237238// Each body shortcut advertises exactly what it can parse, so a server that only serves one of those media types239// must not answer 406 to a request Ky could have parsed.240test('the `accept` header of each body shortcut covers what Ky can parse', async t => {241 const accepts: Record<string, string | undefined> = {};242243 for (const type of ['json', 'text', 'formData', 'arrayBuffer', 'blob'] as const) {244 // eslint-disable-next-line no-await-in-loop245 await ky('https://example.com', {246 retry: 0,247 async fetch(request) {248 accepts[type] = request.headers.get('accept') ?? undefined;249 return new Response('x', {headers: {'content-type': 'application/json'}});250 },251 })[type]().catch(() => undefined);252 }253254 t.is(accepts.json, 'application/json');255 t.true(accepts.text!.includes('text/*'));256 t.true(accepts.text!.includes('application/json'));257 t.true(accepts.formData!.includes('multipart/form-data'));258 t.true(accepts.formData!.includes('application/x-www-form-urlencoded'));259 t.is(accepts.arrayBuffer, '*/*');260 t.is(accepts.blob, '*/*');261});262263test('a server that only serves a parseable media type does not reject the shortcut', async t => {264 for (const [contentType, body, read] of [265 ['application/json', '{"a":1}', 'text'],266 ['application/x-www-form-urlencoded', 'a=1&b=2', 'formData'],267 ] as Array<[string, string, 'text' | 'formData']>) {268 // eslint-disable-next-line no-await-in-loop269 const server = await createHttpTestServer(t);270 server.get('/', (request, response) => {271 const accept = (request.headers.accept ?? '').split(',').map(mediaType => mediaType.trim());272 if (!accept.includes(contentType)) {273 response.sendStatus(406);274 return;275 }276277 response.set('content-type', contentType).end(body);278 });279280 // eslint-disable-next-line no-await-in-loop281 t.truthy(await ky(server.url, {retry: 0})[read]());282 }283});
modified:test/retry.ts+30 added
9 unmodified lines
10 isNetworkError,11 type RetryOptions,12} from '../source/index.js';13import {NonError} from '../source/errors/NonError.js';14import {validateAndMerge} from '../source/utils/merge.js';15import {createHttpTestServer} from './helpers/create-http-test-server.js';16import {parseRawBody} from './helpers/parse-body.js';17import {withPerformance} from './helpers/with-performance.js';18
4938 unmodified lines
4957 }49584959 t.is(requestCount, 3);4960});49614962// `replaceOption()` is documented to work with any deep-merged option, but a wrapper was only unwrapped where a4963// merge actually ran, so a nested wrapper with no parent value leaked its `{value}` envelope into the result.4964test('`replaceOption` resolves nested wrappers with and without a parent value', t => {4965 t.deepEqual(validateAndMerge({json: {filters: replaceOption({tags: ['a']})}}).json, {filters: {tags: ['a']}});4966 t.deepEqual(validateAndMerge({json: {filters: {tags: ['old']}}}, {json: {filters: replaceOption({tags: ['a']})}}).json, {filters: {tags: ['a']}});4967 t.deepEqual(validateAndMerge({json: {a: {b: 1}}}, {json: {a: {c: replaceOption({d: 1})}}}).json, {a: {b: 1, c: {d: 1}}});4968 t.deepEqual(validateAndMerge({list: [replaceOption({a: 1})]}).list, [{a: 1}]);4969 t.deepEqual(validateAndMerge({list: [1, replaceOption(2), 3]}).list, [1, 2, 3]);4970 t.deepEqual(validateAndMerge({custom: {inner: replaceOption({a: 1})}}).custom, {inner: {a: 1}});4971});49724973test('`replaceOption` leaves untouched values identical', t => {4974 const json = {nested: {list: [1, 2]}};4975 const fetchFunction = () => new Response('ok');4976 const merged = validateAndMerge({json, fetch: fetchFunction}) as {json: unknown; fetch: unknown};49774978 t.is(merged.json, json);4979 t.is(merged.fetch, fetchFunction);4980});49814982test('`replaceOption` resolution handles a cyclic option', t => {4983 const custom: {self?: unknown} = {};4984 custom.self = custom;49854986 const merged = validateAndMerge({custom, json: {filters: replaceOption({tags: ['a']})}});4987 t.is(merged.custom, custom);4988 t.deepEqual(merged.json, {filters: {tags: ['a']}});4989});