Skip to content
Myr

headers.ts

This file

Path

test/headers.ts

1,105 lines · 33.4 KiB · TypeScript

Last changed by

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

History of this file

Take it

1import {Buffer} from 'node:buffer';2import process from 'node:process';3import type {IncomingHttpHeaders} from 'node:http';4import test from 'ava';5import type {RequestHandler} from 'express';6import ky, {replaceOption} from '../source/index.js';7import {createHttpTestServer} from './helpers/create-http-test-server.js';89const timeout = 60_000;1011const echoHeaders: RequestHandler = (request, response) => {12	request.resume();13	response.end(JSON.stringify(request.headers));14};1516test('frozen header pairs work directly and with inherited defaults', async t => {17	const server = await createHttpTestServer(t);18	server.get('/', echoHeaders);19	const headers = Object.freeze([20		Object.freeze(['X-Tag', 'one'] as const),21		Object.freeze(['x-tag', 'two'] as const),22		Object.freeze(['X-Value', 'updated'] as const),23	]);24	const expectedHeaders = {'x-tag': 'one, two', 'x-value': 'updated'};2526	t.like(await ky(server.url, {headers}).json(), expectedHeaders);27	const parent = ky.create({headers: {'x-default': 'parent', 'x-value': 'original'}});28	t.like(await parent.extend({headers})(server.url).json(), {...expectedHeaders, 'x-default': 'parent'});29	t.like(await parent(server.url).json(), {'x-default': 'parent', 'x-value': 'original'});30});3132test.serial('works with nullish headers even in old browsers', async t => {33	// One `Headers` construction while merging headers, plus the two response assertions.34	t.plan(3);3536	const server = await createHttpTestServer(t);37	server.get('/', echoHeaders);3839	const OriginalHeaders = Headers;40	// Some old browsers throw for new Headers(undefined) or new Headers(null)41	// so we check that Ky never does that and passes an empty object instead.42	// See: https://github.com/sindresorhus/ky/issues/26043	globalThis.Headers = class Headers extends OriginalHeaders {44		constructor(headersInit?: RequestInit['headers']) {45			t.deepEqual(headersInit, {});46			super(headersInit);47		}48	};49	const response = await ky.get(server.url).json<IncomingHttpHeaders>();5051	t.is(typeof response, 'object');52	t.truthy(response);5354	globalThis.Headers = OriginalHeaders;55});5657test('`user-agent`', async t => {58	const server = await createHttpTestServer(t);59	server.get('/', echoHeaders);6061	const headers = await ky.get(server.url).json<IncomingHttpHeaders>();62	t.is(headers['user-agent'], 'node');63});6465test('`accept-encoding`', async t => {66	const server = await createHttpTestServer(t);67	server.get('/', echoHeaders);6869	const headers = await ky.get(server.url).json<IncomingHttpHeaders>();7071	t.is(headers['accept-encoding'], 'gzip, deflate');72});7374test('does not override provided `accept-encoding`', async t => {75	const server = await createHttpTestServer(t);76	server.get('/', echoHeaders);7778	const headers = await ky79		.get(server.url, {80			headers: {81				'accept-encoding': 'gzip',82			},83		})84		.json<IncomingHttpHeaders>();85	t.is(headers['accept-encoding'], 'gzip');86});8788test('does not remove user headers from `url` object argument', async t => {89	const server = await createHttpTestServer(t);90	server.get('/', echoHeaders);9192	const headers = await ky93		.get(server.url, {94			headers: {95				'X-Request-Id': 'value',96			},97		})98		.json<IncomingHttpHeaders>();99100	t.is(headers.accept, 'application/json');101	t.is(headers['user-agent'], 'node');102	t.is(headers['accept-encoding'], 'gzip, deflate');103	t.is(headers['x-request-id'], 'value');104});105106test('`accept` header with `json` option', async t => {107	const server = await createHttpTestServer(t);108	server.get('/', echoHeaders);109110	let headers = await ky.get(server.url).json<IncomingHttpHeaders>();111	t.is(headers.accept, 'application/json');112113	headers = await ky114		.get(server.url, {115			headers: {116				accept: '',117			},118		})119		.json<IncomingHttpHeaders>();120121	t.is(headers.accept, 'application/json');122});123124test('`host` header', async t => {125	const server = await createHttpTestServer(t);126	server.get('/', echoHeaders);127128	const headers = await ky.get(server.url).json<IncomingHttpHeaders>();129	t.is(headers.host, `localhost:${server.port}`);130});131132test('transforms names to lowercase', async t => {133	const server = await createHttpTestServer(t);134	server.get('/', echoHeaders);135136	const headers = await ky(server.url, {137		headers: {138			'ACCEPT-ENCODING': 'identity',139		},140	}).json<IncomingHttpHeaders>();141	t.is(headers['accept-encoding'], 'identity');142});143144test('setting `content-length` to 0', async t => {145	const server = await createHttpTestServer(t);146	server.post('/', echoHeaders);147148	const request = ky149		.post(server.url, {150			headers: {151				'content-length': '0',152			},153			body: 'sup',154		})155		.json<IncomingHttpHeaders>();156157	const error = await t.throwsAsync(request);158159	// The undici TypeError ("fetch failed") is wrapped in NetworkError, so the undici cause is one level deeper160	t.is(error.cause?.cause?.code, 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH');161});162163test('sets `content-length` to `0` when requesting PUT with empty body', async t => {164	const server = await createHttpTestServer(t);165	server.put('/', echoHeaders);166167	const headers = await ky.put(server.url).json<IncomingHttpHeaders>();168169	t.is(headers['content-length'], '0');170});171172test('json manual `content-type` header', async t => {173	const server = await createHttpTestServer(t);174	server.post('/', echoHeaders);175176	const headers = await ky177		.post(server.url, {178			headers: {179				'content-type': 'custom',180			},181			json: {182				foo: true,183			},184		})185		.json<IncomingHttpHeaders>();186187	t.is(headers['content-type'], 'custom');188});189190test('json option overrides `content-type` inherited from a Request input body', async t => {191	const server = await createHttpTestServer(t);192	server.post('/', echoHeaders);193194	const headers = await ky(new Request(server.url, {method: 'POST', body: 'plain'}), {195		json: {196			foo: true,197		},198	}).json<IncomingHttpHeaders>();199200	t.is(headers['content-type'], 'application/json');201});202203test('form-data manual `content-type` header', async t => {204	const server = await createHttpTestServer(t);205	server.post('/', echoHeaders);206207	const form = new FormData();208	form.append('a', 'b');209	const headers = await ky210		.post(server.url, {211			headers: {212				'content-type': 'custom',213			},214			// @ts-expect-error FormData type mismatch215			body: form,216		})217		.json<IncomingHttpHeaders>();218219	t.is(headers['content-type'], 'custom');220});221222test('form-data automatic `content-type` header', async t => {223	const server = await createHttpTestServer(t);224	server.post('/', echoHeaders);225226	const form = new FormData();227	form.append('a', 'b');228	const headers = await ky229		.post(server.url, {230			// @ts-expect-error FormData type mismatch231			body: form,232		})233		.json<IncomingHttpHeaders>();234235	// eslint-disable-next-line ava/assertion-arguments236	t.true(headers['content-type'].startsWith('multipart/form-data; boundary='), headers['content-type']);237});238239test('form-data manual `content-type` header with search params', async t => {240	const server = await createHttpTestServer(t);241	server.post('/', echoHeaders);242243	const form = new FormData();244	form.append('a', 'b');245	const headers = await ky246		.post(server.url, {247			searchParams: 'foo=1',248			headers: {249				'content-type': 'custom',250			},251			// @ts-expect-error FormData type mismatch252			body: form,253		})254		.json<IncomingHttpHeaders>();255256	t.is(headers['content-type'], 'custom');257});258259test('form-data automatic `content-type` header with search params', async t => {260	const server = await createHttpTestServer(t);261	server.post('/', echoHeaders);262263	const form = new FormData();264	form.append('a', 'b');265	const headers = await ky266		.post(server.url, {267			searchParams: 'foo=1',268			// @ts-expect-error FormData type mismatch269			body: form,270		})271		.json<IncomingHttpHeaders>();272273	// eslint-disable-next-line ava/assertion-arguments274	t.true(headers['content-type'].startsWith('multipart/form-data; boundary='), headers['content-type']);275});276277test('form-data sets `content-length` header', async t => {278	const server = await createHttpTestServer(t);279	server.post('/', echoHeaders);280281	const form = new FormData();282	form.append('a', 'b');283284	const headers = await ky.post(server.url, {body: form}).json<IncomingHttpHeaders>();285286	// Undici 6.21.3+ added trailing CRLF to FormData (backported from 7.1.0)287	// Older versions: 119 bytes (without CRLF)288	// Newer versions: 121 bytes (with CRLF)289	// Eventually this should only check for '121' when older Node.js versions are dropped290	t.true(headers['content-length'] === '119' || headers['content-length'] === '121');291});292293test('buffer as `options.body` sets `content-length` header', async t => {294	const server = await createHttpTestServer(t);295	server.post('/', echoHeaders);296297	const buffer = Buffer.from('unicorn');298	const headers = await ky299		.post(server.url, {300			body: buffer,301		})302		.json<IncomingHttpHeaders>();303304	t.is(Number(headers['content-length']), buffer.length);305});306307// 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);324	server.get('/', echoHeaders);325326	const headers = await ky327		.get(server.url, {328			headers: {329				blah: undefined,330				rainbow: 'unicorn',331			},332		})333		.json<IncomingHttpHeaders>();334335	t.false('blah' in headers);336	t.true('rainbow' in headers);337});338339test('preserve port in host header if non-standard port', async t => {340	const server = await createHttpTestServer(t);341	server.get('/', echoHeaders);342343	const body = await ky.get(server.url).json<IncomingHttpHeaders>();344	t.is(body.host, `localhost:${server.port}`);345});346347test('strip port in host header if explicit standard port (:80) & protocol (HTTP)', async t => {348	const customFetch: typeof fetch = async () => new Response(349		JSON.stringify({headers: {Host: 'httpbin.org'}}),350		{status: 200, headers: {'content-type': 'application/json'}},351	);352353	const body = await ky.get('http://httpbin.org:80/headers', {fetch: customFetch}).json<{headers: IncomingHttpHeaders}>();354	t.is(body.headers['Host'], 'httpbin.org');355});356357test('strip port in host header if explicit standard port (:443) & protocol (HTTPS)', async t => {358	const customFetch: typeof fetch = async () => new Response(359		JSON.stringify({headers: {Host: 'httpbin.org'}}),360		{status: 200, headers: {'content-type': 'application/json'}},361	);362363	const body = await ky.get('https://httpbin.org:443/headers', {fetch: customFetch}).json<{headers: IncomingHttpHeaders}>();364	t.is(body.headers['Host'], 'httpbin.org');365});366367test('strip port in host header if implicit standard port & protocol (HTTP)', async t => {368	const customFetch: typeof fetch = async () => new Response(369		JSON.stringify({headers: {Host: 'httpbin.org'}}),370		{status: 200, headers: {'content-type': 'application/json'}},371	);372373	const body = await ky.get('http://httpbin.org/headers', {fetch: customFetch}).json<{headers: IncomingHttpHeaders}>();374	t.is(body.headers['Host'], 'httpbin.org');375});376377test('strip port in host header if implicit standard port & protocol (HTTPS)', async t => {378	const customFetch: typeof fetch = async () => new Response(379		JSON.stringify({headers: {Host: 'httpbin.org'}}),380		{status: 200, headers: {'content-type': 'application/json'}},381	);382383	const body = await ky.get('https://httpbin.org/headers', {fetch: customFetch}).json<{headers: IncomingHttpHeaders}>();384	t.is(body.headers['Host'], 'httpbin.org');385});386387test('remove custom header by extending instance (plain objects)', async t => {388	const server = await createHttpTestServer(t);389	server.get('/', echoHeaders);390391	const original = ky.create({392		headers: {393			rainbow: 'rainbow',394			unicorn: 'unicorn',395		},396	});397398	const extended = original.extend({399		headers: {400			rainbow: undefined,401		},402	});403404	const response = await extended(server.url).json<IncomingHttpHeaders>();405406	t.true('unicorn' in response);407	t.false('rainbow' in response);408});409410test('remove header by extending instance (Headers instance)', async t => {411	const server = await createHttpTestServer(t);412	server.get('/', echoHeaders);413414	const original = ky.create({415		headers: new Headers({416			rainbow: 'rainbow',417			unicorn: 'unicorn',418		}),419	});420421	const extended = original.extend({422		// @ts-expect-error Headers does not support undefined values423		headers: new Headers({424			rainbow: undefined,425		}),426	});427428	const response = await extended(server.url).json<IncomingHttpHeaders>();429430	t.false('rainbow' in response);431	t.true('unicorn' in response);432});433434test('remove header by extending instance (Headers instance and plain object)', async t => {435	const server = await createHttpTestServer(t);436	server.get('/', echoHeaders);437438	const original = ky.create({439		headers: new Headers({440			rainbow: 'rainbow',441			unicorn: 'unicorn',442		}),443	});444445	const extended = original.extend({446		headers: {447			rainbow: undefined,448		},449	});450451	const response = await extended(server.url).json<IncomingHttpHeaders>();452453	t.false('rainbow' in response);454	t.true('unicorn' in response);455});456457test('remove header by extending instance (plain object and Headers instance)', async t => {458	const server = await createHttpTestServer(t);459	server.get('/', echoHeaders);460461	const original = ky.create({462		headers: {463			rainbow: 'rainbow',464			unicorn: 'unicorn',465		},466	});467468	const extended = original.extend({469		// @ts-expect-error Headers does not support undefined values470		headers: new Headers({471			rainbow: undefined,472		}),473	});474475	const response = await extended(server.url).json<IncomingHttpHeaders>();476477	t.false('rainbow' in response);478	t.true('unicorn' in response);479});480481test('remove header by extending instance with a differently cased name (plain objects)', async t => {482	const server = await createHttpTestServer(t);483	server.get('/', echoHeaders);484485	const original = ky.create({486		headers: {487			'X-Rainbow': 'rainbow',488			'X-Unicorn': 'unicorn',489		},490	});491492	const extended = original.extend({493		headers: {494			'x-rainbow': undefined,495		},496	});497498	const response = await extended(server.url).json<IncomingHttpHeaders>();499500	t.false('x-rainbow' in response);501	t.is(response['x-unicorn'], 'unicorn');502});503504test('override header by extending instance with a differently cased name (plain objects)', async t => {505	const server = await createHttpTestServer(t);506	server.get('/', echoHeaders);507508	const original = ky.create({509		headers: {510			'X-Rainbow': 'rainbow',511		},512	});513514	const extended = original.extend({515		headers: {516			'x-rainbow': 'double-rainbow',517		},518	});519520	const response = await extended(server.url).json<IncomingHttpHeaders>();521522	t.is(response['x-rainbow'], 'double-rainbow');523});524525test('last extend wins when the same header is set with mixed cases across multiple extends', async t => {526	const server = await createHttpTestServer(t);527	server.get('/', echoHeaders);528529	const extended = ky530		.create({headers: {'X-Rainbow': 'first'}})531		.extend({headers: {'x-rainbow': 'second'}})532		.extend({headers: {'X-RAINBOW': 'third'}});533534	const response = await extended(server.url).json<IncomingHttpHeaders>();535536	t.is(response['x-rainbow'], 'third');537});538539test('header removed with a differently cased name can be re-added by a later extend', async t => {540	const server = await createHttpTestServer(t);541	server.get('/', echoHeaders);542543	const extended = ky544		.create({headers: {'X-Rainbow': 'rainbow'}})545		.extend({headers: {'x-rainbow': undefined}})546		.extend({headers: {'X-RAINBOW': 'again'}});547548	const response = await extended(server.url).json<IncomingHttpHeaders>();549550	t.is(response['x-rainbow'], 'again');551});552553test('remove header with a differently cased name in per-request options (plain objects)', async t => {554	const server = await createHttpTestServer(t);555	server.get('/', echoHeaders);556557	const instance = ky.create({558		headers: {559			'X-Rainbow': 'rainbow',560			'X-Unicorn': 'unicorn',561		},562	});563564	const response = await instance(server.url, {565		headers: {566			'x-rainbow': undefined,567		},568	}).json<IncomingHttpHeaders>();569570	t.false('x-rainbow' in response);571	t.is(response['x-unicorn'], 'unicorn');572});573574test('override header with a differently cased name in per-request options (plain objects)', async t => {575	const server = await createHttpTestServer(t);576	server.get('/', echoHeaders);577578	const instance = ky.create({579		headers: {580			'X-Rainbow': 'rainbow',581		},582	});583584	const response = await instance(server.url, {585		headers: {586			'x-rainbow': 'double-rainbow',587		},588	}).json<IncomingHttpHeaders>();589590	t.is(response['x-rainbow'], 'double-rainbow');591});592593test('remove and override differently cased headers in the same extend (plain objects)', async t => {594	const server = await createHttpTestServer(t);595	server.get('/', echoHeaders);596597	const extended = ky598		.create({599			headers: {600				'X-Rainbow': 'rainbow',601				'X-Unicorn': 'unicorn',602				'X-Cat': 'cat',603			},604		})605		.extend({606			headers: {607				'x-rainbow': undefined,608				'x-unicorn': 'double-unicorn',609			},610		});611612	const response = await extended(server.url).json<IncomingHttpHeaders>();613614	t.false('x-rainbow' in response);615	t.is(response['x-unicorn'], 'double-unicorn');616	t.is(response['x-cat'], 'cat');617});618619test('remove header with a differently cased name when extending with a function', async t => {620	const server = await createHttpTestServer(t);621	server.get('/', echoHeaders);622623	const extended = ky624		.create({headers: {'X-Rainbow': 'rainbow', 'X-Unicorn': 'unicorn'}})625		.extend(() => ({headers: {'x-rainbow': undefined}}));626627	const response = await extended(server.url).json<IncomingHttpHeaders>();628629	t.false('x-rainbow' in response);630	t.is(response['x-unicorn'], 'unicorn');631});632633test('remove header with a differently cased name using a Headers instance over plain object defaults', async t => {634	const server = await createHttpTestServer(t);635	server.get('/', echoHeaders);636637	const extended = ky638		.create({headers: {'X-Rainbow': 'rainbow', 'X-Unicorn': 'unicorn'}})639		.extend({640			// @ts-expect-error Headers does not support undefined values641			headers: new Headers({'x-rainbow': undefined}),642		});643644	const response = await extended(server.url).json<IncomingHttpHeaders>();645646	t.false('x-rainbow' in response);647	t.is(response['x-unicorn'], 'unicorn');648});649650test('init hook receives a single value for a header set with different cases across extends', async t => {651	const server = await createHttpTestServer(t);652	server.get('/', echoHeaders);653654	let headerValue: string | undefined;655656	const extended = ky657		.create({headers: {'X-Rainbow': 'rainbow'}})658		.extend({headers: {'x-rainbow': 'double-rainbow'}})659		.extend({660			hooks: {661				init: [662					options => {663						headerValue = new Headers(options.headers as RequestInit['headers']).get('x-rainbow') ?? undefined;664					},665				],666			},667		});668669	const response = await extended(server.url).json<IncomingHttpHeaders>();670671	t.is(headerValue, 'double-rainbow');672	t.is(response['x-rainbow'], 'double-rainbow');673});674675test('init hook sees plain object header names normalized to lowercase', async t => {676	const server = await createHttpTestServer(t);677	server.get('/', echoHeaders);678679	let initHeaders: Record<string, string | undefined> | undefined;680681	const extended = ky682		.create({headers: {Authorization: 'token', 'X-Rainbow': 'rainbow'}})683		.extend({headers: {'x-rainbow': 'double-rainbow'}})684		.extend({685			hooks: {686				init: [687					options => {688						initHeaders = {...(options.headers as Record<string, string | undefined>)};689					},690				],691			},692		});693694	const response = await extended(server.url).json<IncomingHttpHeaders>();695696	t.deepEqual(initHeaders, {authorization: 'token', 'x-rainbow': 'double-rainbow'});697	t.is(response.authorization, 'token');698	t.is(response['x-rainbow'], 'double-rainbow');699});700701test('`replaceOption` headers ignore differently cased defaults', async t => {702	const server = await createHttpTestServer(t);703	server.get('/', echoHeaders);704705	const extended = ky706		.create({headers: {'X-Rainbow': 'rainbow', 'X-Unicorn': 'unicorn'}})707		.extend({headers: replaceOption({'x-unicorn': 'double-unicorn'})});708709	const response = await extended(server.url).json<IncomingHttpHeaders>();710711	t.false('x-rainbow' in response);712	t.is(response['x-unicorn'], 'double-unicorn');713});714715test('remove header by setting it to undefined in an init hook (inherited from defaults)', async t => {716	const server = await createHttpTestServer(t);717	server.get('/', echoHeaders);718719	const api = ky.create({720		headers: {721			rainbow: 'rainbow',722			unicorn: 'unicorn',723		},724		hooks: {725			init: [726				options => {727					(options.headers as Record<string, string | undefined>)['rainbow'] = undefined;728				},729			],730		},731	});732733	const response = await api(server.url).json<IncomingHttpHeaders>();734735	t.is(response['unicorn'], 'unicorn');736	t.false('rainbow' in response);737});738739test('remove header by setting it to undefined in an init hook (inherited from a Request input)', async t => {740	const server = await createHttpTestServer(t);741	server.get('/', echoHeaders);742743	const response = await ky(new Request(server.url, {headers: {rainbow: 'rainbow', unicorn: 'unicorn'}}), {744		hooks: {745			init: [746				options => {747					options.headers = {rainbow: undefined};748				},749			],750		},751	}).json<IncomingHttpHeaders>();752753	t.is(response['unicorn'], 'unicorn');754	t.false('rainbow' in response);755});756757test('init hook headers object with undefined values only sends defined headers', async t => {758	const server = await createHttpTestServer(t);759	server.get('/', echoHeaders);760761	const response = await ky(server.url, {762		hooks: {763			init: [764				options => {765					options.headers = {766						rainbow: undefined,767						unicorn: 'unicorn',768					};769				},770			],771		},772	}).json<IncomingHttpHeaders>();773774	t.is(response['unicorn'], 'unicorn');775	t.false('rainbow' in response);776});777778test('json option sets `content-type` when an init hook removes the header with undefined', async t => {779	const server = await createHttpTestServer(t);780	server.post('/', echoHeaders);781782	const headers = await ky.post(server.url, {783		json: {foo: true},784		hooks: {785			init: [786				options => {787					options.headers = {'content-type': undefined};788				},789			],790		},791	}).json<IncomingHttpHeaders>();792793	t.is(headers['content-type'], 'application/json');794});795796test('remove a `Request` input header by setting it to undefined in the request options', async t => {797	const server = await createHttpTestServer(t);798	server.get('/', echoHeaders);799800	const response = await ky(new Request(server.url, {headers: {rainbow: 'rainbow', unicorn: 'unicorn'}}), {801		headers: {rainbow: undefined},802	}).json<IncomingHttpHeaders>();803804	t.is(response['unicorn'], 'unicorn');805	t.false('rainbow' in response);806});807808test('remove a `Request` input header with a differently cased name in the request options', async t => {809	const server = await createHttpTestServer(t);810	server.get('/', echoHeaders);811812	const response = await ky(new Request(server.url, {headers: {'X-Rainbow': 'rainbow', unicorn: 'unicorn'}}), {813		headers: {'x-rainbow': undefined},814	}).json<IncomingHttpHeaders>();815816	t.is(response['unicorn'], 'unicorn');817	t.false('x-rainbow' in response);818});819820test('remove a `Request` input header by setting it to undefined in instance defaults', async t => {821	const server = await createHttpTestServer(t);822	server.get('/', echoHeaders);823824	const instance = ky.create({headers: {rainbow: undefined}});825	const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow', unicorn: 'unicorn'}})).json<IncomingHttpHeaders>();826827	t.is(response['unicorn'], 'unicorn');828	t.false('rainbow' in response);829});830831test('header removal set to undefined survives extending the instance', async t => {832	const server = await createHttpTestServer(t);833	server.get('/', echoHeaders);834835	const instance = ky.create({headers: {rainbow: undefined}}).extend({headers: {'x-extended': 'yes'}});836	const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow'}})).json<IncomingHttpHeaders>();837838	t.is(response['x-extended'], 'yes');839	t.false('rainbow' in response);840});841842test('a header set to undefined in instance defaults can be set again in the request options', async t => {843	const server = await createHttpTestServer(t);844	server.get('/', echoHeaders);845846	const instance = ky.create({headers: {rainbow: undefined}});847	const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow'}}), {848		headers: {rainbow: 'request'},849	}).json<IncomingHttpHeaders>();850851	t.is(response['rainbow'], 'request');852});853854test('a header set to undefined in the request options removes the value from instance defaults and a `Request` input', async t => {855	const server = await createHttpTestServer(t);856	server.get('/', echoHeaders);857858	const instance = ky.create({headers: {rainbow: 'instance', unicorn: 'unicorn'}});859	const response = await instance(new Request(server.url, {headers: {rainbow: 'request'}}), {860		headers: {rainbow: undefined},861	}).json<IncomingHttpHeaders>();862863	t.is(response['unicorn'], 'unicorn');864	t.false('rainbow' in response);865});866867test('headers set to undefined in the request options are not visible to `beforeRequest` hooks', async t => {868	const server = await createHttpTestServer(t);869	server.get('/', echoHeaders);870871	let hookHeaders: string[] | undefined;872	await ky(server.url, {873		headers: {rainbow: undefined, unicorn: 'unicorn'},874		hooks: {875			beforeRequest: [876				({request, options}) => {877					hookHeaders = [...options.headers.keys(), ...request.headers.keys()];878				},879			],880		},881	});882883	t.false(hookHeaders!.includes('rainbow'));884	t.true(hookHeaders!.includes('unicorn'));885});886887test('`json` option removes a `content-type` header set to undefined from a `Request` input', async t => {888	const server = await createHttpTestServer(t);889	server.post('/', echoHeaders);890891	const headers = await ky.post(new Request(server.url, {method: 'POST', body: 'text', headers: {'content-type': 'text/custom'}}), {892		json: {foo: true},893		headers: {'content-type': undefined},894	}).json<IncomingHttpHeaders>();895896	t.is(headers['content-type'], 'application/json');897});898899test('remove a `Request` input header with a shortcut method and a plain object', async t => {900	const server = await createHttpTestServer(t);901	server.post('/', echoHeaders);902903	const response = await ky.post(new Request(server.url, {method: 'POST', body: 'text', headers: {'x-token': 'secret'}}), {904		headers: {'x-token': undefined},905	}).json<IncomingHttpHeaders>();906907	t.false('x-token' in response);908	t.is(response['content-type'], 'text/plain;charset=UTF-8');909});910911test('remove the automatic `content-type` of a `Request` input body with undefined', async t => {912	const server = await createHttpTestServer(t);913	server.post('/', echoHeaders);914915	const response = await ky.post(new Request(server.url, {method: 'POST', body: 'text'}), {916		headers: {'content-type': undefined},917	}).json<IncomingHttpHeaders>();918919	t.false('content-type' in response);920});921922test('remove a `Request` input header with the function form of `.extend()`', async t => {923	const server = await createHttpTestServer(t);924	server.get('/', echoHeaders);925926	const instance = ky.create({headers: {'x-parent': 'parent'}}).extend(parentDefaults => ({927		headers: {...parentDefaults.headers as Record<string, string>, rainbow: undefined},928	}));929	const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow'}})).json<IncomingHttpHeaders>();930931	t.is(response['x-parent'], 'parent');932	t.false('rainbow' in response);933});934935test('remove a `Request` input header with `replaceOption()` headers containing undefined', async t => {936	const server = await createHttpTestServer(t);937	server.get('/', echoHeaders);938939	const instance = ky.create({headers: {'x-parent': 'parent'}}).extend({940		headers: replaceOption({rainbow: undefined, unicorn: 'unicorn'}),941	});942	const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow'}})).json<IncomingHttpHeaders>();943944	t.false('x-parent' in response);945	t.false('rainbow' in response);946	t.is(response['unicorn'], 'unicorn');947});948949test('an init hook can set a header that was removed with undefined in the request options', async t => {950	const server = await createHttpTestServer(t);951	server.get('/', echoHeaders);952953	const response = await ky(new Request(server.url, {headers: {rainbow: 'rainbow'}}), {954		headers: {rainbow: undefined},955		hooks: {956			init: [957				options => {958					t.is((options.headers as Record<string, string | undefined>)['rainbow'], undefined);959					t.true('rainbow' in (options.headers as Record<string, string | undefined>));960					(options.headers as Record<string, string | undefined>)['rainbow'] = 'from-init';961				},962			],963		},964	}).json<IncomingHttpHeaders>();965966	t.is(response['rainbow'], 'from-init');967});968969test('headers set to undefined in the request options do not affect other requests of the instance', async t => {970	const server = await createHttpTestServer(t);971	server.get('/', echoHeaders);972973	const instance = ky.create({headers: {rainbow: 'instance'}});974	const first = await instance(server.url, {headers: {rainbow: undefined}}).json<IncomingHttpHeaders>();975	const second = await instance(server.url).json<IncomingHttpHeaders>();976977	t.false('rainbow' in first);978	t.is(second['rainbow'], 'instance');979});980981test('remove a `Request` input header with undefined when instance defaults are a `Headers` instance', async t => {982	const server = await createHttpTestServer(t);983	server.get('/', echoHeaders);984985	const instance = ky.create({headers: new Headers({'x-instance': '1'})});986	const response = await instance(new Request(server.url, {headers: {'x-token': 'secret'}}), {987		headers: {'x-token': undefined},988	}).json<IncomingHttpHeaders>();989990	t.is(response['x-instance'], '1');991	t.false('x-token' in response);992});993994test('remove a `Request` input header with undefined when instance defaults are an array of pairs', async t => {995	const server = await createHttpTestServer(t);996	server.get('/', echoHeaders);997998	const instance = ky.create({headers: [['x-instance', '1']]});999	const response = await instance(new Request(server.url, {headers: {'x-token': 'secret'}}), {1000		headers: {'x-token': undefined},1001	}).json<IncomingHttpHeaders>();10021003	t.is(response['x-instance'], '1');1004	t.false('x-token' in response);1005});10061007test('remove a `Request` input header with a `Headers` instance holding the string "undefined"', async t => {1008	const server = await createHttpTestServer(t);1009	server.get('/', echoHeaders);10101011	const response = await ky(new Request(server.url, {headers: {'x-token': 'secret', unicorn: 'unicorn'}}), {1012		// @ts-expect-error Headers does not support undefined values1013		headers: new Headers({'x-token': undefined}),1014	}).json<IncomingHttpHeaders>();10151016	t.is(response['unicorn'], 'unicorn');1017	t.false('x-token' in response);1018});10191020test('remove a `Request` input header with undefined when the request headers are a `Headers` instance', async t => {1021	const server = await createHttpTestServer(t);1022	server.get('/', echoHeaders);10231024	const instance = ky.create({headers: {'x-token': undefined}});1025	const response = await instance(new Request(server.url, {headers: {'x-token': 'secret'}}), {1026		headers: new Headers({'x-request': '1'}),1027	}).json<IncomingHttpHeaders>();10281029	t.is(response['x-request'], '1');1030	t.false('x-token' in response);1031});10321033test('`init` hooks receive plain object headers even when a `Headers` instance was passed', async t => {1034	const server = await createHttpTestServer(t);1035	server.get('/', echoHeaders);10361037	let initHeaders: unknown;1038	const response = await ky(server.url, {1039		headers: new Headers({'X-Rainbow': 'rainbow'}),1040		hooks: {1041			init: [1042				options => {1043					initHeaders = options.headers;1044				},1045			],1046		},1047	}).json<IncomingHttpHeaders>();10481049	t.deepEqual(initHeaders, {'x-rainbow': 'rainbow'});1050	t.is(response['x-rainbow'], 'rainbow');1051});10521053test('a `Request` input header with the literal string "undefined" is sent as-is', async t => {1054	let sentHeaders: string[][] | undefined;10551056	await ky(new Request('https://example.com', {headers: {'x-a': 'undefined', 'x-b': '1'}}), {1057		async fetch(request) {1058			sentHeaders = [...(request as Request).headers];1059			return new Response('ok');1060		},1061	});10621063	t.deepEqual(sentHeaders, [['x-a', 'undefined'], ['x-b', '1']]);1064});10651066test('duplicate `set-cookie` headers on a `Request` input are all sent', async t => {1067	let sentHeaders: string[][] | undefined;1068	const request = new Request('https://example.com');1069	request.headers.append('set-cookie', 'a=1');1070	request.headers.append('set-cookie', 'b=2');10711072	await ky(request, {1073		async fetch(request) {1074			sentHeaders = [...(request as Request).headers];1075			return new Response('ok');1076		},1077	});10781079	t.deepEqual(sentHeaders, [['set-cookie', 'a=1'], ['set-cookie', 'b=2']]);1080});10811082test('`.extend()` callbacks receive plain object headers even when a `Headers` instance was passed', t => {1083	let parentHeaders: unknown;1084	ky.create({headers: new Headers({'X-Rainbow': 'rainbow'})}).extend(parentDefaults => {1085		parentHeaders = parentDefaults.headers;1086		return {};1087	});10881089	t.deepEqual(parentHeaders, {'x-rainbow': 'rainbow'});1090});10911092for (const replaceHeaders of [false, true]) {1093	test(`clearing inherited headers with ${replaceHeaders ? 'replaceOption(undefined)' : 'undefined'} preserves Request input headers`, async t => {1094		const api = ky.create({1095			headers: {'x-default': 'parent'},1096			fetch: async request => new Response(JSON.stringify(Object.fromEntries(request.headers))),1097		});1098		// eslint-disable-next-line @typescript-eslint/no-confusing-void-expression -- replaceOption(undefined) returns a replacement marker at runtime.1099		const cleared = api.extend({headers: replaceHeaders ? replaceOption(undefined) : undefined});1100		const request = new Request('https://example.com', {headers: {'x-input': 'kept'}});11011102		t.deepEqual(await cleared(request).json(), {'x-input': 'kept', accept: 'application/json'});1103		t.deepEqual(await api(request).json(), {'x-default': 'parent', 'x-input': 'kept', accept: 'application/json'});1104	});1105}