Count a compressed response as unknown, deep-copy context, and isolate `init` hook assignments
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 5b7080a · Browse files · 11 files·+307 added−26 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+307 added−26 removed
- tests:+237 added−7 removed
- other:+70 added−19 removed
Provenance
- Commit
d89c8c8- Tree
e1e494d- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
5b7080a
11 files changed+307 added−26 removed
modified:source/core/Ky.ts+39 added-11 removed
147 unmodified lines148 return cloneShallow(searchParameters) as SearchParamsOption | undefined;149 };150 151 // Shallow-clone mutable option properties so init hook mutations don't leak across requests.152+// Every one of them also copies on assignment, so a hook that replaces the value with an object of its own cannot153+// accumulate mutations on that object across requests. Non-plain values (functions, class instances) are kept by154+// reference, matching how option merging treats them as whole values.155 function cloneInitHookOptions(options: Options): InitOptions {156 let headers = mergeHeaderContainers({}, options.headers ?? {});157 let context = cloneDeep(options.context) ?? {};155- const clonedOptions: Options = {156- ...options,157- // Deep-clone so init-hook mutations to nested values do not leak across requests, matching the nested `retry` cloning below. Non-plain values (functions, class instances) are kept by reference.158- json: cloneDeep(options.json),159- searchParams: cloneSearchParametersForInitHook(options.searchParams),160- };158+ let json = cloneDeep(options.json);159+ let searchParameters = cloneSearchParametersForInitHook(options.searchParams);160+ let retry = options.retry === undefined ? undefined : cloneRetryOptions(options.retry);161 162+ const clonedOptions: Options = {...options};163+164 Object.defineProperties(clonedOptions, {165 headers: {166 enumerable: true,167 configurable: true,10 unmodified lines178 get() {179 return context;180 },181 set(value: Record<string, unknown> | undefined) {180- context = value ?? {};182+ context = cloneDeep(value) ?? {};183 },184 },185+ json: {186+ enumerable: true,187+ configurable: true,188+ get() {189+ return json;190+ },191+ set(value: unknown) {192+ json = cloneDeep(value);193+ },194+ },195+ searchParams: {196+ enumerable: true,197+ configurable: true,198+ get() {199+ return searchParameters;200+ },201+ set(value: SearchParamsOption | undefined) {202+ searchParameters = cloneSearchParametersForInitHook(value);203+ },204+ },205+ retry: {206+ enumerable: true,207+ configurable: true,208+ get() {209+ return retry;210+ },211+ set(value: Options['retry']) {212+ retry = value === undefined ? undefined : cloneRetryOptions(value);213+ },214+ },215 });216 185- if (options.retry !== undefined) {186- clonedOptions.retry = cloneRetryOptions(options.retry);187- }188-217 return clonedOptions as InitOptions;218 }219 220 const validateJsonWithSchema = async (jsonValue: unknown, schema: StandardSchemaV1): Promise<unknown> => {1279 unmodified linesmodified:source/types/options.ts+2 added
287 unmodified lines288 289 @param progress - Object containing download progress information.290 @param chunk - Data that was received. When an empty response body stream completes, the callback receives an empty chunk.291 292+ `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.293+294 Responses with a [null body status](https://fetch.spec.whatwg.org/#null-body-status) are not streamed, so no progress events are emitted for them.295 296 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`.297 249 unmodified linesmodified:source/utils/body.ts+5 added-1 removed
193 unmodified lines194 if (!response.body || nullBodyStatuses.has(response.status)) {195 return response;196 }197 198+ // `content-length` counts encoded bytes on the wire, while the progress stream counts the bytes after199+ // decompression. Using it for a content-coded response would report a total below what actually arrives, so200+ // every event would sit at ~100%. The total is then unknown, which `Progress` already models with `0`.201+ const isContentCoded = response.headers.get('content-encoding') !== null;198- const totalBytes = Math.max(0, Number(response.headers.get('content-length')) || 0);202+ const totalBytes = isContentCoded ? 0 : Math.max(0, Number(response.headers.get('content-length')) || 0);203 const body = withProgress(response.body, totalBytes, onDownloadProgress);204 205 return copyResponseMetadata(new Response(body, response), response);206 };21 unmodified linesmodified:source/utils/merge.ts+4 added-3 removed
305 unmodified lines306 if (value !== undefined && value !== null && (!isObject(value) || Array.isArray(value))) {307 throw new TypeError('The `context` option must be an object');308 }309 310- // Shallow merge: always create a new object to prevent mutation bugs310+ // Shallow merge: top-level keys are replaced, but each layer is deep-copied so nested values are311+ // never shared with the caller's object.312 returnValue = {313 ...returnValue,314 context: (value === undefined || value === null)315 ? {}316 : (isReplace316- ? {...value}317- : {...returnValue.context, ...value}),317+ ? cloneDeep(value)318+ : {...returnValue.context, ...cloneDeep(value as Record<string, unknown>)}),319 };320 continue;321 }322 87 unmodified linesmodified:source/utils/normalize.ts+12 added-2 removed
69 unmodified lines7071727374757475767778798081828384858687888920 unmodified lines69 unmodified lines throw new Error(`retry.${key} must be an array`); } }
// Both limits are passed to `Math.min()`, so a non-number silently turns every delay into `NaN`, which // `setTimeout()` clamps to 1ms. That defeats the whole point of the limits. // A mistyped entry only ever fails to match, so `statusCodes: ['429']` quietly disabled retrying instead of reporting the typo. for (const [key, isValid] of [ ['methods', (value: unknown) => typeof value === 'string'], ['statusCodes', (value: unknown) => Number.isInteger(value)], ['afterStatusCodes', (value: unknown) => Number.isInteger(value)], ] as const) { if (normalizedRetry[key].some(value => !isValid(value))) { throw new TypeError(`\`retry.${key}\` must only contain ${key === 'methods' ? 'strings' : 'numbers'}`); } }
// Both limits are passed to `Math.min()`, so a non-number silently turns every delay into `NaN`, which `setTimeout()` clamps to 1ms. That defeats the whole point of the limits. for (const key of ['maxRetryAfter', 'backoffLimit'] as const) { const value = normalizedRetry[key]; if (typeof value !== 'number' || Number.isNaN(value) || value < 0) { throw new TypeError(`\`retry.${key}\` must be a non-negative number or \`Infinity\``);20 unmodified linesmodified:source/utils/options.ts+6 added-2 removed
27 unmodified lines2829303132333233343536373839404142434416 unmodified lines27 unmodified lines return unknownOptions;};
export const hasSearchParameters = (search: SearchParamsOption): boolean => { // `null` is handled like an absent value by option merging, but an `init` hook can still assign it directly. if (search === undefined || search === null) { if (search === undefined) { return false; }
// Option merging turns `null` into an absent value, but an `init` hook assigns straight onto the options object. `null` is not accepted, so report it instead of treating it as absent. if (search === null) { throw new TypeError('The `searchParams` option must not be `null`. Use `undefined` to clear it.'); }
// The `typeof array` still gives "object", so we need different checking for array. if (Array.isArray(search)) { return search.length > 0; }16 unmodified linesmodified:test/hooks.ts+99 added
6922 unmodified lines6923 beforeRetry: [() => ky.stop],6924 },6925 }), undefined);6926 });6927+6928+// The defensive copy only ran on the values the options object started with. A hook that assigned one of its own6929+// objects got that same object back for every later hook and every later request, so a mutation in a second hook6930+// wrote straight through to the object the first hook owned.6931+test('an `init` hook that assigns `json` hands later hooks a copy', async t => {6932+ const bodies: string[] = [];6933+ const ownBody = {list: [1, 2]};6934+ const instance = ky.create({6935+ method: 'POST',6936+ json: {list: [1, 2]},6937+ retry: 0,6938+ hooks: {6939+ init: [6940+ options => {6941+ options.json = ownBody;6942+ },6943+ options => {6944+ (options.json as typeof ownBody).list.push(99);6945+ },6946+ ],6947+ },6948+ async fetch(request) {6949+ bodies.push(await request.clone().text());6950+ return new Response('ok');6951+ },6952+ });6953+6954+ await instance('https://example.com').text();6955+ await instance('https://example.com').text();6956+6957+ t.deepEqual(bodies, ['{"list":[1,2,99]}', '{"list":[1,2,99]}']);6958+ t.deepEqual(ownBody, {list: [1, 2]});6959+});6960+6961+test('an `init` hook that assigns `searchParams` or `context` hands later hooks a copy', async t => {6962+ const urls: string[] = [];6963+ const contexts: string[] = [];6964+ const ownSearchParameters = {page: 1};6965+ const ownContext = {token: 'first'};6966+6967+ const instance = ky.create({6968+ retry: 0,6969+ hooks: {6970+ init: [6971+ options => {6972+ options.searchParams = ownSearchParameters;6973+ options.context = ownContext;6974+ },6975+ options => {6976+ (options.searchParams as typeof ownSearchParameters).page = 2;6977+ (options.context as typeof ownContext).token = 'second';6978+ },6979+ ],6980+ beforeRequest: [({options}) => {6981+ contexts.push(JSON.stringify(options.context));6982+ }],6983+ },6984+ async fetch(request) {6985+ urls.push(request.url);6986+ return new Response('ok');6987+ },6988+ });6989+6990+ await instance('https://example.com').text();6991+ await instance('https://example.com').text();6992+6993+ t.deepEqual(urls, ['https://example.com/?page=2', 'https://example.com/?page=2']);6994+ t.deepEqual(contexts, ['{"token":"second"}', '{"token":"second"}']);6995+ t.deepEqual(ownSearchParameters, {page: 1});6996+ t.deepEqual(ownContext, {token: 'first'});6997+});6998+6999+test('an `init` hook that assigns `retry` hands later hooks a copy', async t => {7000+ const attemptCounts: number[] = [];7001+ const ownRetry = {limit: 0, delay: () => 0};7002+7003+ const instance = ky.create({7004+ hooks: {7005+ init: [7006+ options => {7007+ options.retry = ownRetry;7008+ },7009+ options => {7010+ (options.retry as typeof ownRetry).limit = 1;7011+ },7012+ ],7013+ },7014+ async fetch() {7015+ attemptCounts.push(1);7016+ return new Response('server error', {status: 500});7017+ },7018+ });7019+7020+ await t.throwsAsync(instance('https://example.com').text());7021+ await t.throwsAsync(instance('https://example.com').text());7022+7023+ t.deepEqual(attemptCounts, [1, 1, 1, 1]);7024+ t.deepEqual(ownRetry, {limit: 0, delay: ownRetry.delay});7025+});modified:test/main.ts+47 added-7 removed
4197 unmodified lines4198 },4199 }).json());4200 });4201 4202-// `hasSearchParameters()` reached `Object.keys()` on `null`, so clearing the option from an `init` hook crashed4203-// with an internal error instead of simply leaving the URL alone.4202 test('an `init` hook can clear `searchParams`', async t => {4203 const server = await createHttpTestServer(t);4204 server.get('/', (request, response) => {4205 response.end(request.url);1 unmodified line4207 4208 t.is(await ky(server.url, {4209 searchParams: {a: '1'}, hooks: {4210 init: [options => {4213- options.searchParams = null as never;4211+ options.searchParams = undefined;4212 }],4213 },4214 }).text(), '/');4217- t.is(await ky(server.url, {4215+});4216+4217+// `hasSearchParameters()` reached `Object.keys()` on `null`, so an `init` hook that assigned `null` crashed with an internal error. `null` is not accepted anywhere in Ky, so the error names the option instead.4218+test('an `init` hook that sets `searchParams` to `null` gets an error naming the option', t => {4219+ t.throws(() => {4220+ void ky('https://example.com', {4221+ searchParams: {a: '1'},4222+ hooks: {4223+ init: [options => {4224+ options.searchParams = null as never;4225+ }],4226+ },4227+ });4228+ }, {4229+ instanceOf: TypeError,4230+ message: 'The `searchParams` option must not be `null`. Use `undefined` to clear it.',4231+ });4232+});4233+4234+// The top-level context is merged shallowly, so a nested value arrived from the caller by reference and mutating4235+// it after `ky.create()` silently changed what every later request carried. The per-request deep copy happens too4236+// late to help. `searchParams` is already copied at this point.4237+test('mutating a caller-owned `context` object after creating an instance does not change it', async t => {4238+ const bodies: string[] = [];4239+ const contexts: string[] = [];4240+ const json = {nested: {value: 1}};4241+ const context = {nested: {value: 1}};4242+4243+ const instance = ky.create({4244+ method: 'POST',4245+ json,4246+ context,4247+ async fetch(request) {4248+ bodies.push(await request.clone().text());4249+ return new Response('ok');4250+ },4251 hooks: {4219- init: [options => {4220- options.searchParams = null as never;4252+ beforeRequest: [({options}) => {4253+ contexts.push(JSON.stringify(options.context));4254 }],4255 },4223- }).text(), '/');4256+ });4257+4258+ context.nested.value = 2;4259+4260+ await instance('https://example.com').text();4261+4262+ t.is(contexts[0], '{"nested":{"value":1}}');4263+ t.deepEqual(context, {nested: {value: 2}});4264 });modified:test/retry.ts+41 added
4883 unmodified lines4884 instanceOf: TypeError,4885 message: '`retry.delay` must return a non-negative number or `Infinity`',4886 });4887 });4888+4889+// Array-shaped retry options were only checked for being arrays, so a mistyped entry silently disabled retrying4890+// with no indication of why.4891+test('rejects non-string `retry.methods` entries and non-number status code entries', t => {4892+ for (const [key, value] of [4893+ ['methods', ['GET', 5]],4894+ ['statusCodes', ['429']],4895+ ['statusCodes', [429.5]],4896+ ['statusCodes', [null]],4897+ ['afterStatusCodes', ['503']],4898+ ['afterStatusCodes', [Number.NaN]],4899+ ] as Array<[string, unknown]>) {4900+ const retry: Record<string, unknown> = {[key]: value};4901+4902+ t.throws(() => {4903+ void ky('https://example.com', {retry: retry as never});4904+ }, {4905+ instanceOf: TypeError,4906+ message: `\`retry.${key}\` must only contain ${key === 'methods' ? 'strings' : 'numbers'}`,4907+ }, `${key}: ${JSON.stringify(value)}`);4908+ }4909+});4910+4911+test('a rejected retry list entry is reported before the request is sent', t => {4912+ let requestCount = 0;4913+ const retry: Record<string, unknown> = {statusCodes: ['500']};4914+4915+ t.throws(() => {4916+ void ky('https://example.com', {4917+ async fetch() {4918+ requestCount++;4919+ return new Response(null, {status: 500});4920+ },4921+ retry: retry as never,4922+ });4923+ }, {4924+ instanceOf: TypeError,4925+ message: '`retry.statusCodes` must only contain numbers',4926+ });4927+ t.is(requestCount, 0);4928+});modified:test/stream.ts+50 added
1319 unmodified lines1320 transferredBytes: 2,1321 totalBytes: 2,1322 });1323 });1324+1325+// `content-length` is the size of the encoded body on the wire, while the progress stream counts the bytes after decompression. Trusting it made every event report 100% for a compressed response, so a progress bar was useless for exactly the responses that are large enough to need one.1326+test('download progress does not trust content-length for a compressed response', async t => {1327+ const progressEvents: Progress[] = [];1328+ const text = await ky('https://example.com', {1329+ async fetch() {1330+ const body = new ReadableStream<Uint8Array>({1331+ start(controller) {1332+ for (let index = 0; index < 8; index++) {1333+ controller.enqueue(new Uint8Array(1024));1334+ }1335+1336+ controller.close();1337+ },1338+ });1339+1340+ return new Response(body, {headers: {'content-length': '64', 'content-encoding': 'gzip'}});1341+ },1342+ onDownloadProgress(progress) {1343+ progressEvents.push(progress);1344+ },1345+ }).text();1346+1347+ t.is(text.length, 8192);1348+ t.true(progressEvents.length > 1);1349+ // The encoded size is not a usable total, so it is reported as unknown instead of pinning every event to ~100%.1350+ for (const event of progressEvents.slice(0, -1)) {1351+ t.is(event.percent, 0);1352+ t.is(event.totalBytes, 0);1353+ }1354+1355+ t.deepEqual(progressEvents.at(-1), {1356+ percent: 1,1357+ transferredBytes: 8192,1358+ totalBytes: 8192,1359+ });1360+});1361+1362+test('download progress still uses content-length for an uncompressed response', async t => {1363+ const progressEvents: Progress[] = [];1364+ const text = await ky('https://example.com', {1365+ fetch: async () => new Response('x'.repeat(64), {headers: {'content-length': '64'}}),1366+ onDownloadProgress(progress) {1367+ progressEvents.push(progress);1368+ },1369+ }).text();1370+1371+ t.is(text.length, 64);1372+ t.is(progressEvents.at(-1)?.totalBytes, 64);1373+});modified:readme.md+2 added
760 unmodified lines761 - `transferredBytes` is the number of bytes transferred so far.762 - `totalBytes` is the total number of bytes to be transferred. This is an estimate and may be 0 for an empty transfer or when the total size cannot be determined.763 - `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.764 765+`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.766+767 Responses with a [null body status](https://fetch.spec.whatwg.org/#null-body-status) are not streamed, so no progress events are emitted for them.768 769 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`.770 1137 unmodified lines