main.ts
This file
Path
test/main.ts
4,366 lines · 117.9 KiB · TypeScript
Last changed by
RefactorSindre Sorhusbefore adoptiona5ed57b
History of this fileTake it
1import {Buffer} from 'node:buffer';2import {setTimeout as delay} from 'node:timers/promises';3import test from 'ava';4import {expectTypeOf} from 'expect-type';5import ky, {6 HTTPError,7 KyError,8 SchemaValidationError,9 TimeoutError,10 isKyError,11 replaceOption,12 type StandardSchemaV1,13} from '../source/index.js';14import {createHttpTestServer} from './helpers/create-http-test-server.js';15import {parseRawBody} from './helpers/parse-body.js';1617const fixture = 'fixture';1819test('.json(undefined) parses JSON without schema validation', async t => {20 const request = ky.create({fetch: async () => Response.json({name: 'Ada'})});21 t.deepEqual(await request('https://example.com').json(undefined), {name: 'Ada'});22 t.deepEqual(await request('https://example.com', {23 parseJson: text => ({...JSON.parse(text), parsed: true}),24 }).json(undefined), {name: 'Ada', parsed: true});2526 await t.throwsAsync(ky('https://example.com', {27 fetch: async () => new Response(''),28 }).json(undefined), {instanceOf: SyntaxError});29});3031test('typed response clones can independently parse the same JSON body', async t => {32 const response = await ky<{name: string}>('https://example.com', {33 fetch: async () => Response.json({name: 'Ada'}),34 });35 const clone = response.clone();36 const nestedClone = clone.clone();3738 t.false(response.bodyUsed);39 t.deepEqual(await clone.json(), {name: 'Ada'});40 t.false(response.bodyUsed);41 t.deepEqual(await nestedClone.json(), {name: 'Ada'});42 t.deepEqual(await response.json(), {name: 'Ada'});43});4445type TestSchemaResult<Output> = {value: Output} | {issues: Array<{message: string}>};4647const createSchema = <Output>(48 validate: (value: unknown) => TestSchemaResult<Output> | Promise<TestSchemaResult<Output>>,49): StandardSchemaV1<unknown, Output> => ({50 '~standard': {51 version: 1,52 vendor: 'test',53 validate,54 },55});5657const isObjectWithValue = (value: unknown): value is {value: unknown} => (58 typeof value === 'object'59 && value !== null60 && 'value' in value61);6263const createSchemaCallTracker = () => {64 let isSchemaCalled = false;6566 return {67 schema: createSchema(() => {68 isSchemaCalled = true;69 return {value: {value: 1}};70 }),71 isSchemaCalled: () => isSchemaCalled,72 };73};7475test('extending with undefined containers clears inherited headers, hooks, and context', async t => {76 let inheritedHookCalls = 0;77 const instance = ky.create({78 headers: {'x-default': 'parent'},79 context: {label: 'parent'},80 hooks: {81 beforeRequest: [({options}) => {82 inheritedHookCalls++;83 t.deepEqual(options.context, {label: 'parent'});84 }],85 },86 fetch: async request => new Response(request.headers.get('x-default') ?? 'none'),87 });88 const extended = instance.extend({headers: undefined, hooks: undefined, context: undefined});8990 t.is(await instance('https://example.com').text(), 'parent');91 t.is(await extended('https://example.com', {92 hooks: {93 beforeRequest: [({options}) => {94 t.deepEqual(options.context, {});95 }],96 },97 }).text(), 'none');98 t.is(inheritedHookCalls, 1);99});100101test('ky()', async t => {102 const server = await createHttpTestServer(t);103 server.get('/', (_request, response) => {104 response.end();105 });106107 const {ok} = await ky(server.url);108 t.true(ok);109});110111test('GET request', async t => {112 const server = await createHttpTestServer(t);113 server.get('/', (request, response) => {114 response.end(request.method);115 });116117 t.is(await ky(server.url).text(), 'GET');118});119120test('POST request', async t => {121 const server = await createHttpTestServer(t);122 server.post('/', (request, response) => {123 response.end(request.method);124 });125126 t.is(await ky.post(server.url).text(), 'POST');127});128129test('PUT request', async t => {130 const server = await createHttpTestServer(t);131 server.put('/', (request, response) => {132 response.end(request.method);133 });134135 t.is(await ky.put(server.url).text(), 'PUT');136});137138test('PATCH request', async t => {139 const server = await createHttpTestServer(t);140 server.patch('/', (request, response) => {141 response.end(request.method);142 });143144 t.is(await ky.patch(server.url).text(), 'PATCH');145});146147test('HEAD request', async t => {148 t.plan(2);149150 const server = await createHttpTestServer(t);151 server.head('/', (request, response) => {152 response.end(request.method);153 t.pass();154 });155156 t.is(await ky.head(server.url).text(), '');157});158159test('DELETE request', async t => {160 const server = await createHttpTestServer(t);161 server.delete('/', (request, response) => {162 response.end(request.method);163 });164165 t.is(await ky.delete(server.url).text(), 'DELETE');166});167168test('QUERY request', async t => {169 t.plan(3);170171 const server = await createHttpTestServer(t);172 server.all('/', (request, response) => {173 t.is(request.method, 'QUERY');174 t.is(request.headers['content-type'], 'application/json');175 response.json(request.body);176 });177178 const json = {179 foo: true,180 };181182 const responseJson = await ky.query<typeof json>(server.url, {json}).json();183184 expectTypeOf(responseJson).toEqualTypeOf<typeof json>();185 t.deepEqual(responseJson, json);186});187188test('POST JSON', async t => {189 t.plan(2);190191 const server = await createHttpTestServer(t);192 server.post('/', async (request, response) => {193 t.is(request.headers['content-type'], 'application/json');194 response.json(request.body);195 });196197 const json = {198 foo: true,199 };200201 const responseJson = await ky.post(server.url, {json}).json();202203 t.deepEqual(responseJson, json);204});205206test('cannot use `body` option with GET or HEAD method', async t => {207 await t.throwsAsync(ky.get('https://example.com', {body: 'foobar'}),208 {209 message: 'Request with GET/HEAD method cannot have body.',210 },211 );212213 await t.throwsAsync(ky.head('https://example.com', {body: 'foobar'}),214 {215 message: 'Request with GET/HEAD method cannot have body.',216 },217 );218});219220test('cannot use `json` option with GET or HEAD method', async t => {221 await t.throwsAsync(ky.get('https://example.com', {json: {}}),222 {223 message: 'Request with GET/HEAD method cannot have body.',224 },225 );226227 await t.throwsAsync(ky.head('https://example.com', {json: {}}),228 {229 message: 'Request with GET/HEAD method cannot have body.',230 },231 );232});233234test('`json` option overrides the `body` option', async t => {235 t.plan(2);236237 const server = await createHttpTestServer(t);238 server.post('/', async (request, response) => {239 t.is(request.headers['content-type'], 'application/json');240 response.json(request.body);241 });242243 const json = {244 foo: 'bar',245 };246247 const responseJson = await ky248 .post(server.url, {249 body: 'hello',250 json,251 })252 .json();253254 t.deepEqual(responseJson, json);255});256257test('a streaming request body is sent without passing the `duplex` option', async t => {258 const server = await createHttpTestServer(t, {bodyParser: false});259 server.post('/', async (request, response) => {260 response.send(await parseRawBody(request));261 });262263 const body = 'hello stream';264 const stream = new ReadableStream({265 start(controller) {266 controller.enqueue(new TextEncoder().encode(body));267 controller.close();268 },269 });270271 t.is(await ky.post(server.url, {body: stream}).text(), body);272});273274test('a streaming request body is replayed on a retry without passing the `duplex` option', async t => {275 const server = await createHttpTestServer(t, {bodyParser: false});276 let attempts = 0;277 server.post('/', async (request, response) => {278 attempts++;279 const body = await parseRawBody(request);280 if (attempts === 1) {281 response.sendStatus(500);282 return;283 }284285 response.send(body);286 });287288 const stream = new ReadableStream({289 start(controller) {290 controller.enqueue(new TextEncoder().encode('replay me'));291 controller.close();292 },293 });294295 const result = await ky.post(server.url, {296 body: stream,297 retry: {methods: ['post'], limit: 1, delay: () => 0},298 }).text();299300 t.is(result, 'replay me');301 t.is(attempts, 2);302});303304test('a streaming request body survives the `searchParams` request rebuild without passing the `duplex` option', async t => {305 const server = await createHttpTestServer(t, {bodyParser: false});306 server.post('/', async (request, response) => {307 response.send(`${request.originalUrl}|${await parseRawBody(request)}`);308 });309310 const stream = new ReadableStream({311 start(controller) {312 controller.enqueue(new TextEncoder().encode('with params'));313 controller.close();314 },315 });316317 const result = await ky.post(server.url, {body: stream, searchParams: {foo: 'bar'}}).text();318319 t.is(result, '/?foo=bar|with params');320});321322test('a streaming request body reports upload progress without passing the `duplex` option', async t => {323 const server = await createHttpTestServer(t, {bodyParser: false});324 server.post('/', async (request, response) => {325 response.send(await parseRawBody(request));326 });327328 const stream = new ReadableStream({329 start(controller) {330 controller.enqueue(new TextEncoder().encode('progress body'));331 controller.close();332 },333 });334335 const percentages: number[] = [];336 const result = await ky.post(server.url, {337 body: stream,338 onUploadProgress(progress) {339 percentages.push(progress.percent);340 },341 }).text();342343 t.is(result, 'progress body');344 t.is(percentages.at(-1), 1);345});346347test('a streaming request body keeps a custom `content-type` without passing the `duplex` option', async t => {348 const server = await createHttpTestServer(t, {bodyParser: false});349 server.post('/', async (request, response) => {350 response.send(`${request.headers['content-type']}|${await parseRawBody(request)}`);351 });352353 const stream = new ReadableStream({354 start(controller) {355 controller.enqueue(new TextEncoder().encode('typed body'));356 controller.close();357 },358 });359360 const result = await ky.post(server.url, {361 body: stream,362 headers: {'content-type': 'text/x-custom'},363 }).text();364365 t.is(result, 'text/x-custom|typed body');366});367368test('custom headers', async t => {369 const server = await createHttpTestServer(t);370 server.get('/', (request, response) => {371 response.end(request.headers.unicorn);372 });373374 t.is(375 await ky(server.url, {376 headers: {377 unicorn: fixture,378 },379 }).text(),380 fixture,381 );382});383384test('JSON with custom Headers instance', async t => {385 t.plan(3);386387 const server = await createHttpTestServer(t);388 server.post('/', async (request, response) => {389 t.is(request.headers.unicorn, 'rainbow');390 t.is(request.headers['content-type'], 'application/json');391 response.json(request.body);392 });393394 const json = {395 foo: true,396 };397398 const responseJson = await ky399 .post(server.url, {400 headers: new Headers({unicorn: 'rainbow'}),401 json,402 })403 .json();404405 t.deepEqual(responseJson, json);406});407408test('.json() with custom accept header', async t => {409 t.plan(2);410411 const server = await createHttpTestServer(t);412 server.get('/', async (request, response) => {413 t.is(request.headers.accept, 'foo/bar');414 response.json({});415 });416417 const responseJson = await ky(server.url, {418 headers: {accept: 'foo/bar'},419 }).json();420421 t.deepEqual(responseJson, {});422});423424test('.json() when response is chunked', async t => {425 const server = await createHttpTestServer(t);426 server.get('/', async (request, response) => {427 response.write('[');428 response.write('"one",');429 response.write('"two"');430 response.end(']');431 });432433 const responseJson = await ky.get<['one', 'two']>(server.url).json();434435 expectTypeOf(responseJson).toEqualTypeOf<['one', 'two']>();436437 t.deepEqual(responseJson, ['one', 'two']);438});439440test('.json() with invalid JSON body', async t => {441 const server = await createHttpTestServer(t);442 server.get('/', async (request, response) => {443 t.is(request.headers.accept, 'application/json');444 response.end('not json');445 });446447 await t.throwsAsync(ky.get(server.url).json(), {448 message: /Unexpected token/,449 });450});451452test('.json() with empty body', async t => {453 t.plan(2);454455 const server = await createHttpTestServer(t);456 server.get('/', async (request, response) => {457 t.is(request.headers.accept, 'application/json');458 response.end();459 });460461 const promise = ky.get<{foo: string}>(server.url).json();462 expectTypeOf(promise).toEqualTypeOf<Promise<{foo: string}>>();463464 await t.throwsAsync(promise, {465 message: /Unexpected end of JSON input/,466 });467});468469test('.json() with 204 response and empty body', async t => {470 t.plan(2);471472 const server = await createHttpTestServer(t);473 server.get('/', async (request, response) => {474 t.is(request.headers.accept, 'application/json');475 response.status(204).end();476 });477478 await t.throwsAsync(ky(server.url).json(), {479 message: /Unexpected end of JSON input/,480 });481});482483test('extending with undefined JSON callbacks restores native JSON handling', async t => {484 const server = await createHttpTestServer(t);485 server.post('/', (request, response) => {486 response.json(request.body);487 });488489 const instance = ky.create({490 parseJson() {491 throw new Error('Inherited parseJson must not run');492 },493 stringifyJson() {494 throw new Error('Inherited stringifyJson must not run');495 },496 }).extend({parseJson: undefined, stringifyJson: undefined});497 const json = {message: 'hello', count: 2};498499 t.deepEqual(await instance.post(server.url, {json}).json(), json);500});501502test('.json() with 204 response is overridden by parseJson', async t => {503 const server = await createHttpTestServer(t);504 server.get('/', async (_request, response) => {505 response.status(204).end();506 });507508 const responseJson = await ky.get(server.url, {509 parseJson(text) {510 t.is(text, '');511 return {parsed: true};512 },513 }).json();514515 t.deepEqual(responseJson, {parsed: true});516});517518test('.json() with empty body is overridden by parseJson', async t => {519 const server = await createHttpTestServer(t);520 server.get('/', async (_request, response) => {521 response.end();522 });523524 const responseJson = await ky.get(server.url, {525 parseJson(text) {526 t.is(text, '');527 return {parsed: true};528 },529 }).json();530531 t.deepEqual(responseJson, {parsed: true});532});533534test('.json(schema) returns validated output and infers type', async t => {535 const server = await createHttpTestServer(t);536 server.get('/', (_request, response) => {537 response.json({value: 1});538 });539540 const schema = createSchema<{value: number}>(value => {541 if (542 isObjectWithValue(value)543 && typeof value.value === 'number'544 ) {545 return {value: {value: value.value}};546 }547548 return {issues: [{message: 'Expected {value:number}'}]};549 });550551 const responseJson = await ky.get(server.url).json(schema);552553 expectTypeOf(responseJson).toEqualTypeOf<{value: number}>();554 t.deepEqual(responseJson, {value: 1});555});556557test('.json(schema) accepts schema with typed input generic', async t => {558 const server = await createHttpTestServer(t);559 server.get('/', (_request, response) => {560 response.json('1');561 });562563 const schema: StandardSchemaV1<string, number> = {564 '~standard': {565 version: 1,566 vendor: 'test',567 validate(value) {568 if (typeof value === 'string') {569 return {value: Number(value)};570 }571572 return {issues: [{message: 'Expected string'}]};573 },574 },575 };576577 const responseJson = await ky.get(server.url).json(schema);578579 expectTypeOf(responseJson).toEqualTypeOf<number>();580 t.is(responseJson, 1);581});582583test('.json(schema) accepts callable schema objects', async t => {584 const server = await createHttpTestServer(t);585 server.get('/', (_request, response) => {586 response.json({value: 1});587 });588589 const schema: StandardSchemaV1<unknown, {value: number}> = Object.assign(590 () => undefined,591 {592 '~standard': {593 version: 1 as const,594 vendor: 'test',595 validate(value: unknown) {596 if (597 isObjectWithValue(value)598 && typeof value.value === 'number'599 ) {600 return {value: {value: value.value}};601 }602603 return {issues: [{message: 'Expected {value:number}'}]};604 },605 },606 },607 );608609 const responseJson = await ky.get(server.url).json(schema);610611 t.deepEqual(responseJson, {value: 1});612});613614test('.json(schema) throws SchemaValidationError when validation fails', async t => {615 const server = await createHttpTestServer(t);616 server.get('/', (_request, response) => {617 response.json({value: 'invalid'});618 });619620 const issues = [{message: 'Expected {value:number}'}];621 const schema = createSchema<{value: number}>(() => ({issues}));622623 const error = await t.throwsAsync(ky.get(server.url).json(schema), {624 instanceOf: SchemaValidationError,625 message: 'Response schema validation failed',626 });627628 t.false(isKyError(error));629 t.deepEqual(error?.issues, issues);630});631632test('.json(schema) keeps the caller in the error stack with and without totalTimeout', async t => {633 const server = await createHttpTestServer(t);634 server.get('/', (_request, response) => {635 response.json({value: 'invalid'});636 });637638 const schema = createSchema<{value: number}>(() => ({issues: [{message: 'Expected {value:number}'}]}));639640 async function schemaValidationCaller(totalTimeout: number | false) {641 const {value} = await ky.get(server.url, {totalTimeout}).json(schema);642 return value;643 }644645 async function schemaValidationEntryPoint(totalTimeout: number | false) {646 await schemaValidationCaller(totalTimeout);647 }648649 for (const totalTimeout of [false, 10_000] as const) {650 // eslint-disable-next-line no-await-in-loop651 const error = await t.throwsAsync(schemaValidationEntryPoint(totalTimeout), {instanceOf: SchemaValidationError});652653 t.regex(error?.stack ?? '', /schemaValidationCaller/);654 t.regex(error?.stack ?? '', /schemaValidationEntryPoint/);655 }656});657658test('.json(schema) preserves async validator errors without aborting the request', async t => {659 let requestSignal: AbortSignal | undefined;660 let validationError: Error | undefined;661 const schema = createSchema(async () => {662 await delay(0);663 validationError = new Error('validate exploded');664 throw validationError;665 });666667 async function asyncValidationCaller() {668 await ky('https://example.com', {669 async fetch(request) {670 requestSignal = request.signal;671 return new Response('{"value":1}');672 },673 totalTimeout: 10_000,674 }).json(schema);675 }676677 const error = await t.throwsAsync(asyncValidationCaller(), {message: 'validate exploded'});678679 t.is(error, validationError);680 t.regex(error?.stack ?? '', /asyncValidationCaller/);681 t.false(requestSignal?.aborted);682});683684test('.json(schema) throws TypeError for invalid schema objects', async t => {685 const server = await createHttpTestServer(t);686 server.get('/', (_request, response) => {687 response.json({value: 1});688 });689690 const invalidSchema = {'~standard': {}} as unknown as StandardSchemaV1;691692 await t.throwsAsync(ky.get(server.url).json(invalidSchema), {693 instanceOf: TypeError,694 message: 'The `schema` argument must follow the Standard Schema specification',695 });696});697698test('.json(schema) throws TypeError for null schema values', async t => {699 const server = await createHttpTestServer(t);700 server.get('/', (_request, response) => {701 response.json({value: 1});702 });703704 const invalidSchema = null as unknown as StandardSchemaV1;705706 await t.throwsAsync(ky.get(server.url).json(invalidSchema), {707 instanceOf: TypeError,708 message: 'The `schema` argument must follow the Standard Schema specification',709 });710});711712test('isKyError works for branded cross-realm KyError subclasses', t => {713 class CustomKyError extends KyError {714 override name = 'CustomKyError';715 }716717 const error = Object.assign(new Error('cross-realm error'), {718 name: 'CustomKyError',719 isKyError: new CustomKyError().isKyError,720 });721722 t.true(isKyError(error));723});724725test('isKyError does not match unrelated errors named KyError', t => {726 const error = new Error('not from ky');727 error.name = 'KyError';728729 t.false(isKyError(error));730});731732test('.json(schema) allows schema output transformations', async t => {733 const server = await createHttpTestServer(t);734 server.get('/', (_request, response) => {735 response.json({value: '1'});736 });737738 const schema = createSchema<{value: number}>(value => {739 if (740 isObjectWithValue(value)741 && typeof value.value === 'string'742 ) {743 return {value: {value: Number(value.value)}};744 }745746 return {issues: [{message: 'Expected {value:string}'}]};747 });748749 const responseJson = await ky.get(server.url).json(schema);750751 t.deepEqual(responseJson, {value: 1});752});753754test('.json(schema) supports async validation', async t => {755 const server = await createHttpTestServer(t);756 server.get('/', (_request, response) => {757 response.json({value: 1});758 });759760 const schema = createSchema<{value: number}>(async value => {761 await delay(1);762763 if (764 isObjectWithValue(value)765 && typeof value.value === 'number'766 ) {767 return {value: {value: value.value}};768 }769770 return {issues: [{message: 'Expected {value:number}'}]};771 });772773 const responseJson = await ky.get(server.url).json(schema);774775 t.deepEqual(responseJson, {value: 1});776});777778test('.json(schema) validates empty body values as undefined', async t => {779 const server = await createHttpTestServer(t);780 server.get('/', (_request, response) => {781 response.end();782 });783784 const issues = [{message: 'Expected non-empty JSON'}];785 let validatedValue: unknown = Symbol('unset');786 const schema = createSchema<unknown>(value => {787 validatedValue = value;788 return {issues};789 });790791 const error = await t.throwsAsync(ky.get(server.url).json(schema), {792 instanceOf: SchemaValidationError,793 message: 'Response schema validation failed',794 });795796 t.is(validatedValue, undefined);797 t.deepEqual(error?.issues, issues);798});799800test('.json(schema) validates 204 responses as undefined', async t => {801 const server = await createHttpTestServer(t);802 server.get('/', (_request, response) => {803 response.status(204).end();804 });805806 const issues = [{message: 'Expected non-empty JSON'}];807 let validatedValue: unknown = Symbol('unset');808 const schema = createSchema<unknown>(value => {809 validatedValue = value;810 return {issues};811 });812813 const error = await t.throwsAsync(ky.get(server.url).json(schema), {814 instanceOf: SchemaValidationError,815 message: 'Response schema validation failed',816 });817818 t.is(validatedValue, undefined);819 t.deepEqual(error?.issues, issues);820});821822test('.json(schema) with empty body calls parseJson before validation', async t => {823 const server = await createHttpTestServer(t);824 server.get('/', (_request, response) => {825 response.end();826 });827828 let parseJsonCalled = false;829 const schema = createSchema<string>(value => ({830 value: value === undefined ? 'empty:undefined' : 'non-empty',831 }));832833 const responseJson = await ky.get(server.url, {834 parseJson(text) {835 parseJsonCalled = true;836 return {parsed: true};837 },838 }).json(schema);839840 t.true(parseJsonCalled);841 t.is(responseJson, 'non-empty');842});843844test('.json(schema) with 204 response calls parseJson before validation', async t => {845 const server = await createHttpTestServer(t);846 server.get('/', (_request, response) => {847 response.status(204).end();848 });849850 let parseJsonCalled = false;851 const schema = createSchema<string>(value => ({852 value: value === undefined ? 'empty:undefined' : 'non-empty',853 }));854855 const responseJson = await ky.get(server.url, {856 parseJson(text) {857 parseJsonCalled = true;858 return {parsed: true};859 },860 }).json(schema);861862 t.true(parseJsonCalled);863 t.is(responseJson, 'non-empty');864});865866test('.json(schema) with invalid JSON body throws parse error before validation', async t => {867 const server = await createHttpTestServer(t);868 server.get('/', (_request, response) => {869 response.end('not json');870 });871872 const {schema, isSchemaCalled} = createSchemaCallTracker();873874 await t.throwsAsync(ky.get(server.url).json(schema), {875 message: /Unexpected token/,876 });877878 t.false(isSchemaCalled());879});880881test('.json(schema) does not run validation for HTTP errors', async t => {882 const server = await createHttpTestServer(t);883 server.get('/', (_request, response) => {884 response.status(500).json({value: 1});885 });886887 const {schema, isSchemaCalled} = createSchemaCallTracker();888889 await t.throwsAsync(ky.get(server.url).json(schema), {890 instanceOf: HTTPError,891 });892893 t.false(isSchemaCalled());894});895896test('.json(schema) accepts empty body when schema validates it', async t => {897 const server = await createHttpTestServer(t);898 server.get('/', (_request, response) => {899 response.end();900 });901902 const schema = createSchema<string>(value => ({903 value: value === undefined ? 'empty:undefined' : 'non-empty',904 }));905906 const responseJson = await ky.get(server.url).json(schema);907908 t.is(responseJson, 'empty:undefined');909});910911test('.json(schema) runs validation when throwHttpErrors is false', async t => {912 const server = await createHttpTestServer(t);913 server.get('/', (_request, response) => {914 response.status(500).json({error: 'server error'});915 });916917 const schema = createSchema<{error: string}>(value => {918 if (919 typeof value === 'object'920 && value !== null921 && 'error' in value922 ) {923 return {value: value as {error: string}};924 }925926 return {issues: [{message: 'Expected {error:string}'}]};927 });928929 const responseJson = await ky.get(server.url, {throwHttpErrors: false}).json(schema);930931 t.deepEqual(responseJson, {error: 'server error'});932});933934test('.json(schema) propagates errors thrown by validate()', async t => {935 const server = await createHttpTestServer(t);936 server.get('/', (_request, response) => {937 response.json({value: 1});938 });939940 const schema = createSchema<unknown>(() => {941 throw new Error('validate exploded');942 });943944 await t.throwsAsync(ky.get(server.url).json(schema), {945 message: 'validate exploded',946 });947});948949for (const timeoutOption of ['timeout', 'totalTimeout'] as const) {950 test(`undefined resets inherited ${timeoutOption} without changing the parent`, async t => {951 const server = await createHttpTestServer(t);952 server.get('/', async (_request, response) => {953 await delay(20);954 response.end(fixture);955 });956 const parent = ky.create({[timeoutOption]: 0, retry: 0});957 const child = parent.extend({[timeoutOption]: undefined});958959 await t.throwsAsync(parent(server.url), {instanceOf: TimeoutError});960 t.is(await child(server.url).text(), fixture);961 await t.throwsAsync(parent(server.url), {instanceOf: TimeoutError});962 });963}964965test('timeout option', async t => {966 t.plan(2);967 let requestCount = 0;968969 const server = await createHttpTestServer(t);970 server.get('/', async (_request, response) => {971 requestCount++;972 await delay(2000);973 response.end(fixture);974 });975976 await t.throwsAsync(ky(server.url, {timeout: 1000}).text(), {977 instanceOf: TimeoutError,978 });979980 t.is(requestCount, 1);981});982983test('timeout:false option', async t => {984 let requestCount = 0;985986 const server = await createHttpTestServer(t);987 server.get('/', async (_request, response) => {988 requestCount++;989 await delay(1000);990 response.end(fixture);991 });992993 await t.notThrowsAsync(ky(server.url, {timeout: false}).text());994995 t.is(requestCount, 1);996});997998// A timer created with an infinite delay fires after 1ms, so without any timeout Ky must not create one for the fetch or the body read.999test('`timeout: false` without totalTimeout does not time out a slow fetch or a slow body read', async t => {1000 const text = await ky('https://example.com', {1001 timeout: false,1002 async fetch() {1003 await delay(50);1004 return new Response(new ReadableStream({1005 async pull(controller) {1006 await delay(50);1007 controller.enqueue(new TextEncoder().encode('slow'));1008 controller.close();1009 },1010 }, {highWaterMark: 0}));1011 },1012 }).text();10131014 t.is(text, 'slow');1015});10161017test('invalid timeout option', async t => {1018 // #1171019 let requestCount = 0;10201021 const server = await createHttpTestServer(t);1022 server.get('/', async (_request, response) => {1023 requestCount++;1024 await delay(1000);1025 response.end(fixture);1026 });10271028 await t.throwsAsync(ky(server.url, {timeout: 21_474_836_470}), {1029 instanceOf: RangeError,1030 message: 'The `timeout` option cannot be greater than 2147483647',1031 });10321033 t.is(requestCount, 0);1034});10351036test.serial('timeout option is cancelled when the promise is resolved', async t => {1037 const server = await createHttpTestServer(t);10381039 server.get('/', (request, response) => {1040 response.end(request.method);1041 });10421043 const originalSetTimeout = globalThis.setTimeout;1044 const originalClearTimeout = globalThis.clearTimeout;1045 let requestTimeoutId: ReturnType<typeof globalThis.setTimeout> | undefined;1046 let didClearRequestTimeout = false;10471048 globalThis.setTimeout = ((handler, delayMs, ...arguments_) => {1049 const timeoutId = originalSetTimeout(handler, delayMs, ...arguments_);1050 if (delayMs === 2000) {1051 requestTimeoutId = timeoutId;1052 }10531054 return timeoutId;1055 }) as typeof globalThis.setTimeout;10561057 globalThis.clearTimeout = (timeoutId => {1058 if (timeoutId === requestTimeoutId) {1059 didClearRequestTimeout = true;1060 }10611062 originalClearTimeout(timeoutId);1063 }) as typeof globalThis.clearTimeout;10641065 try {1066 await ky(server.url, {timeout: 2000});1067 } finally {1068 globalThis.setTimeout = originalSetTimeout;1069 globalThis.clearTimeout = originalClearTimeout;1070 }10711072 t.truthy(requestTimeoutId);1073 t.true(didClearRequestTimeout);1074});10751076test.serial('timeout option is cancelled when a shortcut body read is resolved', async t => {1077 const request = ky('https://example.com', {1078 fetch: async () => new Response('ok'),1079 timeout: 2000,1080 });10811082 await request;10831084 const originalSetTimeout = globalThis.setTimeout;1085 const originalClearTimeout = globalThis.clearTimeout;1086 let bodyTimeoutId: ReturnType<typeof globalThis.setTimeout> | undefined;1087 let didClearBodyTimeout = false;10881089 globalThis.setTimeout = ((handler, delayMs, ...arguments_) => {1090 const timeoutId = originalSetTimeout(handler, delayMs, ...arguments_);1091 if (delayMs === 2000) {1092 bodyTimeoutId = timeoutId;1093 }10941095 return timeoutId;1096 }) as typeof globalThis.setTimeout;10971098 globalThis.clearTimeout = (timeoutId => {1099 if (timeoutId === bodyTimeoutId) {1100 didClearBodyTimeout = true;1101 }11021103 originalClearTimeout(timeoutId);1104 }) as typeof globalThis.clearTimeout;11051106 try {1107 t.is(await request.text(), 'ok');1108 } finally {1109 globalThis.setTimeout = originalSetTimeout;1110 globalThis.clearTimeout = originalClearTimeout;1111 }11121113 t.truthy(bodyTimeoutId);1114 t.true(didClearBodyTimeout);1115});11161117test('timeout bounds a never-ending successful response body', async t => {1118 let didStartBodyRead = false;11191120 const customFetch: typeof fetch = async () => {1121 const response = new Response(undefined, {1122 status: 200,1123 headers: {'content-type': 'application/json'},1124 });11251126 response.text = async () => {1127 didStartBodyRead = true;1128 return new Promise<string>(resolve => {1129 t.teardown(() => {1130 resolve('');1131 });1132 });1133 };11341135 return response;1136 };11371138 const start = Date.now();1139 await t.throwsAsync(ky('https://example.com', {1140 fetch: customFetch,1141 timeout: 50,1142 }).json(), {1143 instanceOf: TimeoutError,1144 });1145 t.true(didStartBodyRead);1146 t.true(Date.now() - start < 2000);1147});11481149test('totalTimeout bounds a never-ending successful response body', async t => {1150 let didStartBodyRead = false;11511152 const customFetch: typeof fetch = async () => {1153 const response = new Response(undefined, {status: 200});1154 response.text = async () => {1155 didStartBodyRead = true;1156 return new Promise<string>(resolve => {1157 t.teardown(() => {1158 resolve('');1159 });1160 });1161 };11621163 return response;1164 };11651166 const start = Date.now();1167 await t.throwsAsync(ky('https://example.com', {1168 fetch: customFetch,1169 timeout: false,1170 totalTimeout: 500,1171 }).text(), {1172 instanceOf: TimeoutError,1173 });1174 t.true(didStartBodyRead);1175 t.true(Date.now() - start < 2000);1176});11771178for (const timeout of [false, 10_000] as const) {1179 test.serial(`totalTimeout rejects a completed fetch past the deadline with timeout ${timeout}`, async t => {1180 const originalPerformanceNow = globalThis.performance.now;1181 let currentTime = 0;1182 let fetchCount = 0;1183 let hookCallCount = 0;1184 let requestSignal: AbortSignal | undefined;1185 let canceledBody = false;1186 globalThis.performance.now = () => currentTime;1187 t.teardown(() => {1188 globalThis.performance.now = originalPerformanceNow;1189 });11901191 await t.throwsAsync(ky('https://example.com', {1192 timeout,1193 totalTimeout: 500,1194 async fetch(request) {1195 fetchCount++;1196 requestSignal = request.signal;1197 currentTime = 501;1198 return new Response(new ReadableStream({1199 cancel() {1200 canceledBody = true;1201 },1202 }));1203 },1204 hooks: {1205 beforeError: [({error}) => {1206 hookCallCount++;1207 t.true(error instanceof TimeoutError);1208 return error;1209 }],1210 },1211 }), {instanceOf: TimeoutError});1212 t.is(fetchCount, 1);1213 t.is(hookCallCount, 1);1214 t.true(requestSignal?.aborted);1215 t.true(canceledBody);1216 });1217}12181219for (const method of ['text', 'arrayBuffer', 'json'] as const) {1220 test.serial(`totalTimeout rejects a completed ${method} body read past the deadline`, async t => {1221 const originalPerformanceNow = globalThis.performance.now;1222 let currentTime = 0;1223 let didRead = false;1224 let requestSignal: AbortSignal | undefined;1225 let hookCallCount = 0;1226 globalThis.performance.now = () => currentTime;1227 t.teardown(() => {1228 globalThis.performance.now = originalPerformanceNow;1229 });12301231 const response = ky('https://example.com', {1232 totalTimeout: 500,1233 async fetch(request) {1234 requestSignal = request.signal;1235 return new Response(new ReadableStream({1236 pull(controller) {1237 didRead = true;1238 currentTime = 501;1239 controller.enqueue(new TextEncoder().encode('{"ok":true}'));1240 controller.close();1241 },1242 }, {highWaterMark: 0}));1243 },1244 hooks: {1245 beforeError: [({error}) => {1246 hookCallCount++;1247 t.true(error instanceof TimeoutError);1248 return error;1249 }],1250 },1251 });12521253 await t.throwsAsync(response[method](), {instanceOf: TimeoutError});1254 t.true(didRead);1255 t.true(requestSignal?.aborted);1256 t.is(hookCallCount, 1);1257 });1258}12591260test.serial('beforeError hook receives totalTimeout exhausted before a shortcut body read starts', async t => {1261 const originalPerformanceNow = globalThis.performance.now;1262 let currentTime = 0;1263 globalThis.performance.now = () => currentTime;1264 t.teardown(() => {1265 globalThis.performance.now = originalPerformanceNow;1266 });12671268 let didReadBody = false;1269 let hookError: Error | undefined;12701271 const customFetch: typeof fetch = async () => {1272 const response = new Response('ok');1273 response.text = async () => {1274 didReadBody = true;1275 return 'ok';1276 };12771278 return response;1279 };12801281 const response = ky('https://example.com', {1282 fetch: customFetch,1283 timeout: false,1284 totalTimeout: 250,1285 hooks: {1286 beforeError: [1287 ({error}) => {1288 hookError = error;1289 error.message = 'pre-read-timeout-beforeError';1290 return error;1291 },1292 ],1293 },1294 });12951296 await response;1297 currentTime = 300;12981299 await t.throwsAsync(response.text(), {1300 instanceOf: TimeoutError,1301 message: 'pre-read-timeout-beforeError',1302 });13031304 t.false(didReadBody);1305 t.true(hookError instanceof TimeoutError);1306});13071308test('timeout aborts a never-ending successful response body read', async t => {1309 let didAbort = false;1310 const customFetch: typeof fetch = async request => {1311 request.signal.addEventListener('abort', () => {1312 didAbort = true;1313 }, {once: true});13141315 const body = new ReadableStream<Uint8Array>({1316 start(controller) {1317 controller.enqueue(new TextEncoder().encode('partial'));1318 },1319 });13201321 return new Response(body, {status: 200});1322 };13231324 await t.throwsAsync(ky('https://example.com', {1325 fetch: customFetch,1326 timeout: 50,1327 }).text(), {1328 instanceOf: TimeoutError,1329 });13301331 t.true(didAbort);1332});13331334test('timeout does not retry a never-ending successful response body read', async t => {1335 let requestCount = 0;1336 const customFetch: typeof fetch = async () => {1337 requestCount++;13381339 const body = new ReadableStream<Uint8Array>({1340 start(controller) {1341 controller.enqueue(new TextEncoder().encode('partial'));1342 },1343 });13441345 return new Response(body, {status: 200});1346 };13471348 await t.throwsAsync(ky('https://example.com', {1349 fetch: customFetch,1350 timeout: 50,1351 retry: {1352 limit: 2,1353 delay: () => 0,1354 retryOnTimeout: true,1355 },1356 }).text(), {1357 instanceOf: TimeoutError,1358 });13591360 t.is(requestCount, 1);1361});13621363test('beforeError hook receives successful response body TimeoutError', async t => {1364 let hookError: Error | undefined;1365 const customFetch: typeof fetch = async () => {1366 const body = new ReadableStream<Uint8Array>({1367 start(controller) {1368 controller.enqueue(new TextEncoder().encode('partial'));1369 },1370 });13711372 return new Response(body, {status: 200});1373 };13741375 await t.throwsAsync(ky('https://example.com', {1376 fetch: customFetch,1377 timeout: 50,1378 hooks: {1379 beforeError: [1380 ({error}) => {1381 hookError = error;1382 error.message = 'body-timeout-beforeError';1383 return error;1384 },1385 ],1386 },1387 }).text(), {1388 instanceOf: TimeoutError,1389 message: 'body-timeout-beforeError',1390 });13911392 t.true(hookError instanceof TimeoutError);1393});13941395test.serial('totalTimeout bounds hanging parseJson on successful response shortcut', async t => {1396 t.timeout(5000);1397 const originalPerformanceNow = globalThis.performance.now;1398 // Keep the budget available until parsing starts; the timeout timer still runs normally.1399 globalThis.performance.now = () => 0;1400 t.teardown(() => {1401 globalThis.performance.now = originalPerformanceNow;1402 });14031404 let parseJsonCalled = false;1405 let hookError: Error | undefined;1406 await t.throwsAsync(ky('https://example.com', {1407 fetch: async () => new Response('{"value":1}', {1408 headers: {'content-type': 'application/json'},1409 }),1410 timeout: false,1411 totalTimeout: 250,1412 parseJson: async () => new Promise<never>(() => {1413 parseJsonCalled = true;1414 // Intentionally never settles1415 }),1416 hooks: {1417 beforeError: [1418 ({error}) => {1419 hookError = error;1420 error.message = 'parse-timeout-beforeError';1421 return error;1422 },1423 ],1424 },1425 }).json(), {1426 instanceOf: TimeoutError,1427 message: 'parse-timeout-beforeError',1428 });14291430 t.true(parseJsonCalled);1431 t.true(hookError instanceof TimeoutError);1432});14331434test.serial('totalTimeout bounds hanging schema validation on successful response shortcut', async t => {1435 t.timeout(5000);1436 const originalPerformanceNow = globalThis.performance.now;1437 // Keep the budget available until validation starts; the timeout timer still runs normally.1438 globalThis.performance.now = () => 0;1439 t.teardown(() => {1440 globalThis.performance.now = originalPerformanceNow;1441 });14421443 let schemaValidationCalled = false;1444 const schema = createSchema(async () => new Promise<never>(() => {1445 schemaValidationCalled = true;1446 // Intentionally never settles1447 }));14481449 await t.throwsAsync(ky('https://example.com', {1450 fetch: async () => new Response('{"value":1}', {1451 headers: {'content-type': 'application/json'},1452 }),1453 timeout: false,1454 totalTimeout: 250,1455 }).json(schema), {1456 instanceOf: TimeoutError,1457 });14581459 t.true(schemaValidationCalled);1460});14611462test.serial('timeout false does not apply a successful response body timeout', async t => {1463 const originalSetTimeout = globalThis.setTimeout;1464 const scheduledDelays: number[] = [];1465 globalThis.setTimeout = ((handler, delayMs, ...arguments_) => {1466 if (delayMs === 10_000) {1467 scheduledDelays.push(delayMs);1468 }14691470 const testDelay = delayMs === 10_000 ? 0 : delayMs;1471 return originalSetTimeout(handler, testDelay, ...arguments_);1472 }) as typeof globalThis.setTimeout;14731474 const abortController = new AbortController();1475 const request = ky('https://example.com', {1476 async fetch(request) {1477 const body = new ReadableStream<Uint8Array>({1478 start(controller) {1479 controller.enqueue(new TextEncoder().encode('partial'));1480 request.signal.addEventListener('abort', () => {1481 controller.error(new DOMException('Aborted', 'AbortError'));1482 }, {once: true});1483 },1484 });14851486 return new Response(body);1487 },1488 signal: abortController.signal,1489 timeout: false,1490 }).text();14911492 try {1493 t.is(await Promise.race([1494 request.then(() => 'settled').catch(() => 'settled'),1495 delay(50).then(() => 'pending'),1496 ]), 'pending');1497 } finally {1498 abortController.abort();1499 await request.catch(() => undefined);1500 globalThis.setTimeout = originalSetTimeout;1501 }15021503 t.deepEqual(scheduledDelays, []);1504});15051506test('normalizing retry options does not mutate the caller retry object', async t => {1507 const retry = {1508 methods: ['GET'],1509 };15101511 await ky('https://example.com', {1512 fetch: async () => new Response('ok'),1513 retry,1514 }).text();15151516 t.deepEqual(retry, {1517 methods: ['GET'],1518 });1519});15201521test('frozen retry lists support retries without being mutated', async t => {1522 const methods = Object.freeze(['get'] as const);1523 const statusCodes = Object.freeze([503] as const);1524 const afterStatusCodes = Object.freeze([503] as const);1525 let attempts = 0;1526 const result = await ky('https://example.com', {1527 retry: {1528 methods,1529 statusCodes,1530 afterStatusCodes,1531 delay() {1532 throw new Error('The Retry-After header should determine the delay');1533 },1534 },1535 async fetch() {1536 attempts++;1537 return attempts === 11538 ? new Response('Unavailable', {status: 503, headers: {'Retry-After': '0'}})1539 : new Response('Success');1540 },1541 }).text();15421543 t.is(result, 'Success');1544 t.is(attempts, 2);1545 t.deepEqual(methods, ['get']);1546 t.deepEqual(statusCodes, [503]);1547 t.deepEqual(afterStatusCodes, [503]);1548});15491550test('readonly search parameter pairs work directly and with defaults', async t => {1551 const searchParameters = Object.freeze([['tag', 'one'], ['tag', 'two'], ['page', 2], ['active', true]] as const);1552 const instance = ky.create({1553 fetch: async request => new Response(new URL(request.url).search),1554 });15551556 t.is(await instance('https://example.com', {searchParams: searchParameters}).text(), '?tag=one&tag=two&page=2&active=true');1557 t.is(await instance.extend({searchParams: {source: 'default'}})('https://example.com', {searchParams: searchParameters}).text(), '?source=default&tag=one&tag=two&page=2&active=true');1558 t.deepEqual(searchParameters, [['tag', 'one'], ['tag', 'two'], ['page', 2], ['active', true]]);1559});15601561test('searchParams option', async t => {1562 const server = await createHttpTestServer(t);15631564 server.get('/', (request, response) => {1565 response.end(request.url.slice(1));1566 });15671568 const arrayParameters = [1569 ['cats', 'meow'],1570 ['dogs', 'true'],1571 ['opossums', 'false'],1572 ];1573 const objectParameters = {1574 cats: 'meow',1575 dogs: 'true',1576 opossums: 'false',1577 };1578 const searchParameters = new URLSearchParams(arrayParameters);1579 const stringParameters = '?cats=meow&dogs=true&opossums=false';1580 const customStringParameters = '?cats&dogs[0]=true&dogs[1]=false';15811582 t.is(await ky(server.url, {searchParams: arrayParameters}).text(), stringParameters);1583 t.is(await ky(server.url, {searchParams: objectParameters}).text(), stringParameters);1584 t.is(await ky(server.url, {searchParams: searchParameters}).text(), stringParameters);1585 t.is(await ky(server.url, {searchParams: stringParameters}).text(), stringParameters);1586 t.is(await ky(server.url, {searchParams: customStringParameters}).text(), customStringParameters);1587});15881589test('searchParams option with undefined values', async t => {1590 const server = await createHttpTestServer(t);15911592 server.get('/', (request, response) => {1593 response.end(request.url.slice(1));1594 });15951596 const objectWithUndefined = {1597 cats: 'meow',1598 dogs: undefined,1599 opossums: 'false',1600 birds: undefined,1601 };16021603 // `null` is rejected by the type on purpose, but the runtime still sends it as the string `'null'`.1604 const objectWithNull = {1605 cats: 'meow',1606 dogs: null as any,1607 opossums: 'false',1608 };16091610 // Undefined values should be filtered out1611 t.is(await ky(server.url, {searchParams: objectWithUndefined}).text(), '?cats=meow&opossums=false');16121613 // Null values should be preserved as string "null"1614 t.is(await ky(server.url, {searchParams: objectWithNull}).text(), '?cats=meow&dogs=null&opossums=false');16151616 // The same applies through `.extend()` merging and to the tuple form1617 t.is(await ky.extend({searchParams: {a: null as any}})(server.url, {searchParams: {b: null as any}}).text(), '?a=null&b=null');1618 t.is(await ky(server.url, {searchParams: [['a', null as any]]}).text(), '?a=null');1619});16201621test('merges searchParams with input URL', async t => {1622 const server = await createHttpTestServer(t);1623 server.get('/', (request, response) => {1624 response.end(request.url);1625 });16261627 const response = await ky(`${server.url}?foo=1`, {1628 searchParams: {bar: '2'},1629 });16301631 const url = await response.text();1632 t.true(url.includes('foo=1'), `URL should contain foo=1, got: ${url}`);1633 t.true(url.includes('bar=2'), `URL should contain bar=2, got: ${url}`);1634});16351636test('searchParams with undefined deletes input URL searchParams', async t => {1637 const server = await createHttpTestServer(t);1638 server.get('/', (request, response) => {1639 response.end(request.url);1640 });16411642 const response = await ky(`${server.url}?foo=1&bar=2&qux=3`, {1643 // @ts-expect-error - we test that explicitly undefined value is handled1644 searchParams: {foo: undefined, baz: '3', qux: 'undefined'},1645 });16461647 const url = await response.text();1648 t.false(url.includes('foo=1'), `URL should not contain foo=1, got: ${url}`);1649 t.true(url.includes('bar=2'), `URL should contain bar=2, got: ${url}`);1650 t.true(url.includes('baz=3'), `URL should contain baz=3, got: ${url}`);1651 t.true(url.includes('qux=undefined'), `URL should contain qux=undefined, got: ${url}`);1652});16531654test('merges searchParams with explicitly undefined deep options', async t => {1655 const server = await createHttpTestServer(t);1656 server.get('/', (request, response) => {1657 response.end(request.url);1658 });16591660 const api = ky.create({searchParams: new URLSearchParams({a: '1', b: '2'})});1661 const response = await api.get(`${server.url}?z=0`, {1662 // @ts-expect-error - testing undefined value1663 searchParams: {b: undefined, c: '3'},1664 });16651666 const url = await response.text();1667 t.true(url.includes('z=0'), `URL should contain z=0, got: ${url}`);1668 t.true(url.includes('a=1'), `URL should contain a=1, got: ${url}`);1669 t.false(url.includes('b=2'), `URL should not contain b=2, got: ${url}`);1670 t.true(url.includes('c=3'), `URL should contain c=3, got: ${url}`);1671});16721673test('merges plain object searchParams with URLSearchParams', async t => {1674 const server = await createHttpTestServer(t);1675 server.get('/', (request, response) => {1676 response.end(request.url);1677 });16781679 const client = ky.create({searchParams: {api: '123'}});1680 const response = await client.get(server.url, {1681 searchParams: new URLSearchParams({_limit_: '1'}),1682 });16831684 const url = await response.text();1685 t.true(url.includes('api=123'), `URL should contain api=123, got: ${url}`);1686 t.true(url.includes('_limit_=1'), `URL should contain _limit_=1, got: ${url}`);1687 t.false(url.includes('[object Object]'), `URL should not contain [object Object], got: ${url}`);1688 t.false(url.includes('headers'), `URL should not contain 'headers', got: ${url}`);1689});16901691test('merges URLSearchParams with plain object searchParams', async t => {1692 const server = await createHttpTestServer(t);1693 server.get('/', (request, response) => {1694 response.end(request.url);1695 });16961697 const client = ky.create({searchParams: new URLSearchParams({api: '123'})});1698 const response = await client.get(server.url, {1699 searchParams: {_limit_: '1'},1700 });17011702 const url = await response.text();1703 t.true(url.includes('api=123'), `URL should contain api=123, got: ${url}`);1704 t.true(url.includes('_limit_=1'), `URL should contain _limit_=1, got: ${url}`);1705 t.false(url.includes('[object Object]'), `URL should not contain [object Object], got: ${url}`);1706});17071708test('merges URLSearchParams with URLSearchParams', async t => {1709 const server = await createHttpTestServer(t);1710 server.get('/', (request, response) => {1711 response.end(request.url);1712 });17131714 const client = ky.create({searchParams: new URLSearchParams({api: '123'})});1715 const response = await client.get(server.url, {1716 searchParams: new URLSearchParams({_limit_: '1'}),1717 });17181719 const url = await response.text();1720 t.true(url.includes('api=123'), `URL should contain api=123, got: ${url}`);1721 t.true(url.includes('_limit_=1'), `URL should contain _limit_=1, got: ${url}`);1722 t.false(url.includes('[object Object]'), `URL should not contain [object Object], got: ${url}`);1723});17241725test('merges searchParams with duplicate keys', async t => {1726 const server = await createHttpTestServer(t);1727 server.get('/', (request, response) => {1728 response.end(request.url);1729 });17301731 const client = ky.create({searchParams: new URLSearchParams({filter: 'active'})});1732 const response = await client.get(server.url, {1733 searchParams: new URLSearchParams({filter: 'recent', _limit_: '10'}),1734 });17351736 const urlString = await response.text();1737 const url = new URL(urlString, server.url);1738 const filterValues = url.searchParams.getAll('filter');17391740 t.deepEqual(filterValues.sort(), ['active', 'recent'], `Both filter values should be present, got: ${JSON.stringify(filterValues)}`);1741 t.is(url.searchParams.get('_limit_'), '10', `URL should contain _limit_=10, got: ${urlString}`);1742 t.false(urlString.includes('[object Object]'), `URL should not contain [object Object], got: ${urlString}`);1743});17441745test('deletes merged search params even when all additions are removed by undefined', async t => {1746 const server = await createHttpTestServer(t);17471748 server.get('/', (request, response) => {1749 response.end(request.url);1750 });17511752 const api = ky.create({searchParams: {foo: '1', bar: '2'}});1753 const response = await api.get(`${server.url}?foo=from-url&bar=from-url&keep=1`, {1754 // @ts-expect-error - testing undefined value1755 searchParams: {foo: undefined, bar: undefined},1756 });17571758 const url = new URL(await response.text(), server.url);1759 t.false(url.searchParams.has('foo'));1760 t.false(url.searchParams.has('bar'));1761 t.is(url.searchParams.get('keep'), '1');1762});17631764test('request searchParams undefined removes merged keys but keeps unrelated values', async t => {1765 const server = await createHttpTestServer(t);17661767 server.get('/', (request, response) => {1768 response.end(request.url);1769 });17701771 const api = ky.extend({searchParams: {foo: '1', bar: '2'}}).extend({searchParams: {baz: '3'}});17721773 const response = await api.get(`${server.url}?bar=from-url&keep=1`, {1774 // @ts-expect-error - testing undefined value1775 searchParams: {foo: undefined, extra: '4'},1776 });17771778 const url = new URL(await response.text(), server.url);1779 t.false(url.searchParams.has('foo'));1780 t.is(url.searchParams.get('baz'), '3');1781 t.is(url.searchParams.get('bar'), 'from-url');1782 t.is(url.searchParams.get('extra'), '4');1783 t.is(url.searchParams.get('keep'), '1');1784});17851786test('string searchParams merge keeps duplicates across input URL and defaults', async t => {1787 const server = await createHttpTestServer(t);17881789 server.get('/', (request, response) => {1790 response.end(request.url);1791 });17921793 const api = ky.create({searchParams: new URLSearchParams({filter: 'active'})});1794 const response = await api.get(`${server.url}?filter=old&sort=old`, {1795 searchParams: 'filter=recent&sort=new',1796 });17971798 const url = new URL(await response.text(), server.url);1799 t.deepEqual(url.searchParams.getAll('filter').sort(), ['active', 'old', 'recent']);1800 t.deepEqual(url.searchParams.getAll('sort').sort(), ['new', 'old']);1801});18021803test('init hook can delete merged search params via undefined', async t => {1804 const server = await createHttpTestServer(t);18051806 server.get('/', (request, response) => {1807 response.end(request.url);1808 });18091810 const api = ky.create({1811 searchParams: {foo: '1', bar: '2'},1812 hooks: {1813 init: [1814 options => {1815 // @ts-expect-error - testing undefined value1816 options.searchParams = {foo: undefined, baz: '3'};1817 },1818 ],1819 },1820 });18211822 const response = await api.get(`${server.url}?bar=from-url`);1823 const url = new URL(await response.text(), server.url);18241825 t.false(url.searchParams.has('foo'));1826 t.is(url.searchParams.get('bar'), 'from-url'); // Input URL overrides instance default1827 t.is(url.searchParams.get('baz'), '3'); // Added by init hook1828});18291830test('ky.extend() searchParams layer deletion propagates through merged instances', async t => {1831 const server = await createHttpTestServer(t);18321833 server.get('/', (request, response) => {1834 response.end(request.url);1835 });18361837 const api = ky.extend({searchParams: {foo: '1'}})1838 .extend({searchParams: {bar: '2'}});1839 const response = await api.get(`${server.url}?bar=from-url`, {1840 // @ts-expect-error - testing undefined value1841 searchParams: {foo: undefined},1842 });18431844 const url = new URL(await response.text(), server.url);1845 t.false(url.searchParams.has('foo'));1846 t.is(url.searchParams.get('bar'), 'from-url');1847});18481849test('searchParams option merges with existing query when hash is present', async t => {1850 const customFetch: typeof fetch = async input => {1851 if (!(input instanceof Request)) {1852 throw new TypeError('Expected to have input as request');1853 }18541855 return new Response(input.url);1856 };18571858 const url = 'https://example.com/unicorn';18591860 t.is(1861 await ky(url + '?old#hash', {1862 fetch: customFetch,1863 searchParams: {foo: '1'},1864 }).text(),1865 url + '?old=&foo=1#hash',1866 );1867});18681869test('searchParams preserves the body of a Request input', async t => {1870 const server = await createHttpTestServer(t);1871 server.post('/', (request, response) => {1872 response.json({url: request.url, body: request.body});1873 });18741875 const request = new Request(server.url, {method: 'POST', body: fixture});1876 const result = await ky(request, {searchParams: {foo: '1'}}).json<{url: string; body: string}>();18771878 t.is(result.url, '/?foo=1');1879 t.is(result.body, fixture);1880});18811882test('searchParams preserves the JSON body and headers of a Request input', async t => {1883 const server = await createHttpTestServer(t);1884 server.post('/', (request, response) => {1885 response.json({url: request.url, body: request.body, custom: request.headers['x-custom']});1886 });18871888 const request = new Request(server.url, {1889 method: 'POST',1890 body: JSON.stringify({hello: 'world'}),1891 headers: {'content-type': 'application/json', 'x-custom': 'unicorn'},1892 });1893 const result = await ky(request, {searchParams: {foo: '1'}}).json<{url: string; body: unknown; custom: string}>();18941895 t.is(result.url, '/?foo=1');1896 t.deepEqual(result.body, {hello: 'world'});1897 t.is(result.custom, 'unicorn');1898});18991900test('searchParams with a Request input still prefers the body option', async t => {1901 const server = await createHttpTestServer(t);1902 server.post('/', (request, response) => {1903 response.json({body: request.body, contentLength: request.headers['content-length']});1904 });19051906 const request = new Request(server.url, {method: 'POST', body: 'ignored'});1907 const result = await ky(request, {body: fixture, searchParams: {foo: '1'}, keepalive: true}).json<{body: string; contentLength: string}>();19081909 t.is(result.body, fixture);1910 t.is(result.contentLength, String(fixture.length));1911});19121913test('searchParams preserves a Request input body across retries', async t => {1914 let requestCount = 0;1915 const server = await createHttpTestServer(t);1916 server.post('/', (request, response) => {1917 requestCount++;1918 if (requestCount === 1) {1919 response.sendStatus(500);1920 return;1921 }19221923 response.json({body: request.body});1924 });19251926 const request = new Request(server.url, {method: 'POST', body: fixture});1927 const result = await ky(request, {1928 searchParams: {foo: '1'},1929 retry: {limit: 1, methods: ['post'], delay: () => 0},1930 }).json<{body: string}>();19311932 t.is(requestCount, 2);1933 t.is(result.body, fixture);1934});19351936test('searchParams drops an inherited Request input body with keepalive', async t => {1937 const request = new Request('https://example.com', {method: 'POST', body: fixture});19381939 await ky(request, {1940 searchParams: {foo: '1'},1941 keepalive: true,1942 async fetch(request) {1943 t.is(request.url, 'https://example.com/?foo=1');1944 t.true(request.keepalive);1945 t.is(request.body, null);1946 return new Response();1947 },1948 });1949});19501951test('searchParams drops an inherited Request input body in no-cors mode', async t => {1952 const request = new Request('https://example.com', {method: 'POST', body: fixture});19531954 await ky(request, {1955 searchParams: {foo: '1'},1956 mode: 'no-cors',1957 async fetch(request) {1958 t.is(request.url, 'https://example.com/?foo=1');1959 t.is(request.mode, 'no-cors');1960 t.is(request.body, null);1961 return new Response();1962 },1963 });1964});19651966// 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.1967for (const searchParameters of ['?', {missing: undefined}] as const) {1968 test(`searchParams ${JSON.stringify(searchParameters)} that leaves the URL unchanged preserves an inherited Request input body`, async t => {1969 const request = new Request('https://example.com/?foo=1', {method: 'POST', body: fixture});19701971 await ky(request, {1972 searchParams: searchParameters,1973 keepalive: true,1974 async fetch(request) {1975 t.is(request.url, 'https://example.com/?foo=1');1976 t.true(request.keepalive);1977 t.is(await request.text(), fixture);1978 return new Response();1979 },1980 });1981 });1982}19831984test('searchParams preserves keepalive inherited from a Request input', async t => {1985 const request = new Request('https://example.com', {method: 'POST', body: fixture, keepalive: true});19861987 await ky(request, {1988 searchParams: {foo: '1'},1989 async fetch(request) {1990 t.true(request.keepalive);1991 t.is(request.body, null);1992 return new Response();1993 },1994 });1995});19961997test('searchParams preserves no-cors mode inherited from a Request input', async t => {1998 const request = new Request('https://example.com', {method: 'POST', body: fixture, mode: 'no-cors'});19992000 await ky(request, {The first 2,000 of 4,366 lines.