Skip to content
Myr

Skip a needless request rebuild, report an unknown total as zero, and fix two stale tests

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 a2dfbd7 · Browse files · 6 files+117 added−52 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+117 added−52 removed

  • tests:+84 added−25 removed
  • other:+33 added−27 removed

6 files+117 added−52 removed

modified:source/core/Ky.ts+30 added-26 removed
519 unmodified lines
520 }521 }522523 // Recreate request with the updated URL. We already have all options in this.#options, including duplex.524 // Rebuilding is also what drops an inherited `Request` body, so it is skipped when the search parameters leave the URL unchanged.525 if (url.href !== this.request.url) {524 // Request options are read back from the current request so values inherited from a `Request` input (like `credentials`) survive, while explicit options already won when that request was built.525 // A `Request` input's body is only available as a stream, so keeping it requires request stream support.526 const {527 body: inheritedBody,528 cache,529 credentials,530 integrity,531 keepalive,532 mode,533 redirect,534 referrer,535 referrerPolicy,536 } = this.request;537 const canUseInheritedBody = supportsRequestStreams && !keepalive && mode !== 'no-cors';538 this.request = new globalThis.Request(url, {539 ...this.#options,540 cache,541 credentials,542 integrity,543 keepalive,544 mode,545 redirect,546 referrer,547 referrerPolicy,548 body: this.#options.body ?? (canUseInheritedBody ? inheritedBody : undefined),549 } as RequestInit);526 // Request options are read back from the current request so values inherited from a `Request` input (like `credentials`) survive, while explicit options already won when that request was built.527 // A `Request` input's body is only available as a stream, so keeping it requires request stream support.528 const {529 body: inheritedBody,530 cache,531 credentials,532 integrity,533 keepalive,534 mode,535 redirect,536 referrer,537 referrerPolicy,538 } = this.request;539 const canUseInheritedBody = supportsRequestStreams && !keepalive && mode !== 'no-cors';540541 this.request = new globalThis.Request(url, {542 ...this.#options,543 cache,544 credentials,545 integrity,546 keepalive,547 mode,548 redirect,549 referrer,550 referrerPolicy,551 body: this.#options.body ?? (canUseInheritedBody ? inheritedBody : undefined),552 } as RequestInit);553 }554 }555556 if (this.#options.onUploadProgress && typeof this.#options.onUploadProgress !== 'function') {557 throw new TypeError('The `onUploadProgress` option must be a function');
830 unmodified lines
modified:source/utils/body.ts+3 added-1 removed
78 unmodified lines
79 // If we were to use 0.99 here, percent could potentially go backwards.80 percent = 1 - Number.EPSILON;81 }8283 // An unknown total stays `0`, matching the `percent` computed from the same estimate and the documented progress shape.84 const reportedTotalBytes = totalBytes === 0 ? 0 : Math.max(totalBytes, transferredBytes);83 report({percent, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes}, previousChunk);85 report({percent, totalBytes: reportedTotalBytes, transferredBytes}, previousChunk);86 }8788 previousChunk = currentChunk;89 },
133 unmodified lines
modified:test/headers.ts+13 added-15 removed
302 unmodified lines
303304 t.is(Number(headers['content-length']), buffer.length);305});306307test.failing('removes undefined value headers', async t => {308 const server = await createHttpTestServer(t);309 server.get('/', echoHeaders);310311 const headers = await ky312 .get(server.url, {313 headers: {314 'user-agent': undefined,315 unicorn: 'unicorn',316 },317 })318 .json<IncomingHttpHeaders>();319320 t.is(headers['user-agent'], 'undefined');321 t.is(headers['unicorn'], 'unicorn');307// A header set to `undefined` is removed from the request Ky sends. It is asserted on the outgoing request, because a runtime default header, such as Undici's `user-agent`, is added again by `fetch` and so cannot be removed.308test('removes undefined value headers', async t => {309 await ky.get('https://example.com', {310 headers: {311 'user-agent': undefined,312 unicorn: 'unicorn',313 },314 async fetch(request) {315 t.false(request.headers.has('user-agent'));316 t.is(request.headers.get('unicorn'), 'unicorn');317 return new Response();318 },319 });320});321322test('non-existent headers set to undefined are omitted', async t => {323 const server = await createHttpTestServer(t);
782 unmodified lines
modified:test/main.ts+18 added
1954 unmodified lines
1955 },1956 });1957});19581959// An inherited `Request` body is only dropped because the request is rebuilt with the updated URL, so a `searchParams` value that leaves the URL unchanged must not rebuild the request.1960for (const searchParameters of ['?', {missing: undefined}] as const) {1961 test(`searchParams ${JSON.stringify(searchParameters)} that leaves the URL unchanged preserves an inherited Request input body`, async t => {1962 const request = new Request('https://example.com/?foo=1', {method: 'POST', body: fixture});19631964 await ky(request, {1965 searchParams: searchParameters,1966 keepalive: true,1967 async fetch(request) {1968 t.is(request.url, 'https://example.com/?foo=1');1969 t.true(request.keepalive);1970 t.is(await request.text(), fixture);1971 return new Response();1972 },1973 });1974 });1975}19761977test('searchParams preserves keepalive inherited from a Request input', async t => {1978 const request = new Request('https://example.com', {method: 'POST', body: fixture, keepalive: true});19791980 await ky(request, {
2057 unmodified lines
modified:test/methods.ts+7 added-10 removed
modified:test/stream.ts+46 added
1276 unmodified lines
12771278 t.is(error, callbackError);1279 t.false(isNetworkError(error));1280});12811282// `Progress.totalBytes` is documented to be `0` when the total size cannot be determined, and it must agree with the `percent` it is reported with, which is computed from the same estimate.1283test('download progress reports an unknown total as 0', async t => {1284 const progressEvents: Progress[] = [];1285 const text = await ky('https://example.com', {1286 retry: 0,1287 fetch: async () => new Response(new ReadableStream<Uint8Array>({1288 start(controller) {1289 controller.enqueue(new TextEncoder().encode('ab'));1290 controller.enqueue(new TextEncoder().encode('cd'));1291 controller.close();1292 },1293 }), {headers: {'content-type': 'text/plain'}}),1294 onDownloadProgress(progress) {1295 progressEvents.push(progress);1296 },1297 }).text();12981299 t.is(text, 'abcd');1300 t.deepEqual(progressEvents.at(0), {percent: 0, transferredBytes: 2, totalBytes: 0});1301 t.deepEqual(progressEvents.at(-1), {percent: 1, transferredBytes: 4, totalBytes: 4});1302});13031304test('download progress keeps reporting the estimate when it is smaller than the bytes transferred', async t => {1305 const progressEvents: Progress[] = [];1306 await ky('https://example.com', {1307 retry: 0,1308 fetch: async () => new Response(new ReadableStream<Uint8Array>({1309 start(controller) {1310 controller.enqueue(new TextEncoder().encode('ab'));1311 controller.enqueue(new TextEncoder().encode('cd'));1312 controller.close();1313 },1314 }), {headers: {'content-type': 'text/plain', 'content-length': '2'}}),1315 onDownloadProgress(progress) {1316 progressEvents.push(progress);1317 },1318 }).text();13191320 t.deepEqual(progressEvents.at(0), {1321 // The size estimate is exceeded, so `percent` is capped just below 1 instead of reporting completion.1322 percent: 1 - Number.EPSILON,1323 transferredBytes: 2,1324 totalBytes: 2,1325 });1326});