Fix headers set to `undefined` not removing the header from a `Request` input
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 91ea8a9 · Browse files · 8 files·+329 added−44 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+329 added−44 removed
- tests:+298 added−1 removed
- other:+31 added−43 removed
Provenance
- Commit
d5bacef- Tree
a72c138- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
91ea8a9
8 files changed+329 added−44 removed
modified:source/core/Ky.ts+1 added-1 removed
1250 unmodified lines1251 this.#cachedNormalizedOptions = undefined;1252 this.request = request;1253 }1254 1255- // A replacement `Request` from a hook or `ky.retry({request})` carries its own signal, so re-attach Ky's managed signal to keep timeouts and user aborts working. Request-like objects are used as-is since the `Request` constructor cannot copy them.1255+ // A replacement `Request` from a hook or `ky.retry({request})` carries its own signal, so re-attach Ky's managed signal to keep timeouts and user aborts working. Request-like objects are used as-is since the `Request` constructor cannot copy them, so they keep whatever signal they carry, even on a retry after a timeout.1256 #withManagedSignal(request: Request): Request {1257 if (!this.#options.signal || !(request instanceof globalThis.Request)) {1258 return request;1259 }21 unmodified linesmodified:source/types/hooks.ts+2 added-2 removed
1 unmodified line2 import type {KyRequest, KyResponse} from '../index.js';3 import type {NormalizedOptions, Options} from './options.js';4 5 /**6-This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here.6+This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option is always a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.7 8 Unlike other hooks, `init` hooks are synchronous. Any error thrown will propagate synchronously and will not be caught by `beforeError` hooks.9 10 @example75 unmodified lines86 export type AfterResponseHook = (state: AfterResponseState) => Response | RetryMarker | void | Promise<Response | RetryMarker | void>;87 88 export type Hooks = {89 /**90- This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here.90+ This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option is always a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.91 92 Unlike other hooks, `init` hooks are synchronous. Any error thrown will propagate synchronously and will not be caught by `beforeError` hooks.93 94 A common use case is to add a search parameter to every request:276 unmodified linesmodified:source/types/ky.ts+1 added-1 removed
87 unmodified lines88 Create a new Ky instance with some defaults overridden with your own.89 90 In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.91 92- You can pass headers as a `Headers` instance or a plain object. Plain object header names are normalized to lowercase when options are merged, so `init` hooks always see lowercase keys.92+ You can pass headers as a `Headers` instance or a plain object. Headers are normalized to a plain object with lowercase names when options are merged, so `init` hooks always see a plain object with lowercase keys. A header removed with `undefined` stays in that object with an `undefined` value.93 94 You can remove a header with `.extend()` by passing the header with an `undefined` value. Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.95 96 Similarly, you can remove existing `hooks` entries by extending the hook with an explicit `undefined`.108 unmodified linesmodified:source/types/options.ts+1 added-1 removed
414 unmodified lines415 416 /**417 HTTP headers used to make the request.418 419- You can pass a `Headers` instance or a plain object. Plain object header names are normalized to lowercase when options are merged, so `init` hooks always see lowercase keys.419+ You can pass a `Headers` instance or a plain object. Headers are normalized to a plain object with lowercase names when options are merged, so `init` hooks always see a plain object with lowercase keys. A header removed with `undefined` stays in that object with an `undefined` value.420 421 You can remove a header with `.extend()` by passing the header with an `undefined` value. Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.422 423 @example71 unmodified linesmodified:source/utils/merge.ts+24 added-36 removed
60 unmodified lines61 return deepMerge({}, ...sources);62 };63 64 export const mergeHeaders = (source1: KyHeadersInit = {}, source2: KyHeadersInit = {}) => {65+ // The base source is copied as-is. Only the second source carries deletion markers: `undefined` in a plain object (for example, from `init` hooks or merged options), or the string `'undefined'` in a `Headers` instance.66 const result = new globalThis.Headers(source1 as RequestInit['headers']);67 67- // The `Headers` constructor would turn an `undefined` value into the string `'undefined'`, so plain objects are applied directly to keep the documented deletion behavior (for example, from `init` hooks).68- if (isPlainObject(source2)) {69- for (const [key, value] of Object.entries(source2)) {70- if (value === undefined) {68+ for (const [key, value] of Object.entries(toHeaderObject(source2))) {69+ if (value === undefined) {71- result.delete(key);72- } else {73- result.set(key, value as string);74- }75- }76-77- return result;78- }79-80- const isHeadersInstance = source2 instanceof globalThis.Headers;81- const source = new globalThis.Headers(source2 as RequestInit['headers']);82-83- for (const [key, value] of source.entries()) {84- if ((isHeadersInstance && value === 'undefined') || value === undefined) {70 result.delete(key);71 } else {72 result.set(key, value);73 }25 unmodified lines99 100 return copy as T;101 }102 118- if (value instanceof globalThis.Headers) {119- return new globalThis.Headers(value) as T;120- }121-103 if (Array.isArray(value)) {104 return [...value] as T;105 }106 5 unmodified lines112 return value;113 };114 115 // Header names are case-insensitive, so they are normalized to lowercase (like `Headers` does) so that overrides and `undefined` deletions match regardless of how the name was spelled and `init` hooks can rely on lowercase keys.116+// An `undefined` value is kept as a deletion marker so it can still remove a header inherited from a `Request` input when the request is created.135-const mergeHeaderObjects = (source1: Record<string, unknown>, source2: Record<string, unknown>): Record<string, string> => {136- const result = new Map<string, string>();117+const mergeHeaderObjects = (source1: Record<string, unknown>, source2: Record<string, unknown>): Record<string, string | undefined> => {118+ const result = new Map<string, string | undefined>();119 120 for (const [key, value] of [...Object.entries(source1), ...Object.entries(source2)]) {139- if (value === undefined) {140- result.delete(key.toLowerCase());141- } else {142- result.set(key.toLowerCase(), value as string);121+ result.set(key.toLowerCase(), value as string | undefined);143- }122 }123 124 return Object.fromEntries(result);125 };126 149-const mergeHeaderContainers = (source1: KyHeadersInit, source2: KyHeadersInit): KyHeadersInit => {150- if (isPlainObject(source1) && isPlainObject(source2)) {151- return mergeHeaderObjects(source1, source2);127+// Every header source is merged as a plain object so deletion markers survive no matter how the headers were provided. A `Headers` instance cannot hold `undefined`, so its string `'undefined'` counts as a deletion. A plain object is returned as-is, so callers must not mutate the result.128+const toHeaderObject = (source: KyHeadersInit): Record<string, string | undefined> => {129+ if (isPlainObject(source)) {130+ return source as Record<string, string | undefined>;131 }132 154- return mergeHeaders(source1, source2);133+ const isHeadersInstance = source instanceof globalThis.Headers;134+ const result: Record<string, string | undefined> = {};135+136+ // A header named `__proto__` is dropped here, because assigning it sets the prototype instead of an own property. This is too much of an edge case to be worth supporting.137+ for (const [key, value] of new globalThis.Headers(source as RequestInit['headers']).entries()) {138+ result[key] = isHeadersInstance && value === 'undefined' ? undefined : value;139+ }140+141+ return result;142 };143 144+const mergeHeaderContainers = (source1: KyHeadersInit, source2: KyHeadersInit): Record<string, string | undefined> =>145+ mergeHeaderObjects(toHeaderObject(source1), toHeaderObject(source2));146+147 function newHookValue<K extends keyof Hooks>(original: Hooks, incoming: Hooks, property: K): NormalizedHooks[K] {148 if (Object.hasOwn(incoming, property) && incoming[property] === undefined) {149 return [];150 }181 unmodified lines332 // Scoped to the root options level so it never rewrites nested user data that333 // happens to contain a `headers` key (e.g. a `json` request body).334 if (isRoot && isObject((source as any).headers)) {335 const {value: headerValue, isReplace} = getReplaceState((source as any).headers);346- headers = isReplace347- ? cloneShallow(headerValue as KyHeadersInit)348- : mergeHeaderContainers(headers, headerValue as KyHeadersInit);336+ headers = mergeHeaderContainers(isReplace ? {} : headers, headerValue as KyHeadersInit);337 338 returnValue.headers = headers;339 }340 }24 unmodified linesmodified:test/headers.ts+296 added
776 unmodified lines777 }).json<IncomingHttpHeaders>();778 779 t.is(headers['content-type'], 'application/json');780 });781+782+test('remove a `Request` input header by setting it to undefined in the request options', async t => {783+ const server = await createHttpTestServer(t);784+ server.get('/', echoHeaders);785+786+ const response = await ky(new Request(server.url, {headers: {rainbow: 'rainbow', unicorn: 'unicorn'}}), {787+ headers: {rainbow: undefined},788+ }).json<IncomingHttpHeaders>();789+790+ t.is(response['unicorn'], 'unicorn');791+ t.false('rainbow' in response);792+});793+794+test('remove a `Request` input header with a differently cased name in the request options', async t => {795+ const server = await createHttpTestServer(t);796+ server.get('/', echoHeaders);797+798+ const response = await ky(new Request(server.url, {headers: {'X-Rainbow': 'rainbow', unicorn: 'unicorn'}}), {799+ headers: {'x-rainbow': undefined},800+ }).json<IncomingHttpHeaders>();801+802+ t.is(response['unicorn'], 'unicorn');803+ t.false('x-rainbow' in response);804+});805+806+test('remove a `Request` input header by setting it to undefined in instance defaults', async t => {807+ const server = await createHttpTestServer(t);808+ server.get('/', echoHeaders);809+810+ const instance = ky.create({headers: {rainbow: undefined}});811+ const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow', unicorn: 'unicorn'}})).json<IncomingHttpHeaders>();812+813+ t.is(response['unicorn'], 'unicorn');814+ t.false('rainbow' in response);815+});816+817+test('header removal set to undefined survives extending the instance', async t => {818+ const server = await createHttpTestServer(t);819+ server.get('/', echoHeaders);820+821+ const instance = ky.create({headers: {rainbow: undefined}}).extend({headers: {'x-extended': 'yes'}});822+ const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow'}})).json<IncomingHttpHeaders>();823+824+ t.is(response['x-extended'], 'yes');825+ t.false('rainbow' in response);826+});827+828+test('a header set to undefined in instance defaults can be set again in the request options', async t => {829+ const server = await createHttpTestServer(t);830+ server.get('/', echoHeaders);831+832+ const instance = ky.create({headers: {rainbow: undefined}});833+ const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow'}}), {834+ headers: {rainbow: 'request'},835+ }).json<IncomingHttpHeaders>();836+837+ t.is(response['rainbow'], 'request');838+});839+840+test('a header set to undefined in the request options removes the value from instance defaults and a `Request` input', async t => {841+ const server = await createHttpTestServer(t);842+ server.get('/', echoHeaders);843+844+ const instance = ky.create({headers: {rainbow: 'instance', unicorn: 'unicorn'}});845+ const response = await instance(new Request(server.url, {headers: {rainbow: 'request'}}), {846+ headers: {rainbow: undefined},847+ }).json<IncomingHttpHeaders>();848+849+ t.is(response['unicorn'], 'unicorn');850+ t.false('rainbow' in response);851+});852+853+test('headers set to undefined in the request options are not visible to `beforeRequest` hooks', async t => {854+ const server = await createHttpTestServer(t);855+ server.get('/', echoHeaders);856+857+ let hookHeaders: string[] | undefined;858+ await ky(server.url, {859+ headers: {rainbow: undefined, unicorn: 'unicorn'},860+ hooks: {861+ beforeRequest: [862+ ({request, options}) => {863+ hookHeaders = [...options.headers.keys(), ...request.headers.keys()];864+ },865+ ],866+ },867+ });868+869+ t.false(hookHeaders!.includes('rainbow'));870+ t.true(hookHeaders!.includes('unicorn'));871+});872+873+test('`json` option removes a `content-type` header set to undefined from a `Request` input', async t => {874+ const server = await createHttpTestServer(t);875+ server.post('/', echoHeaders);876+877+ const headers = await ky.post(new Request(server.url, {method: 'POST', body: 'text', headers: {'content-type': 'text/custom'}}), {878+ json: {foo: true},879+ headers: {'content-type': undefined},880+ }).json<IncomingHttpHeaders>();881+882+ t.is(headers['content-type'], 'application/json');883+});884+885+test('remove a `Request` input header with a shortcut method and a plain object', async t => {886+ const server = await createHttpTestServer(t);887+ server.post('/', echoHeaders);888+889+ const response = await ky.post(new Request(server.url, {method: 'POST', body: 'text', headers: {'x-token': 'secret'}}), {890+ headers: {'x-token': undefined},891+ }).json<IncomingHttpHeaders>();892+893+ t.false('x-token' in response);894+ t.is(response['content-type'], 'text/plain;charset=UTF-8');895+});896+897+test('remove the automatic `content-type` of a `Request` input body with undefined', async t => {898+ const server = await createHttpTestServer(t);899+ server.post('/', echoHeaders);900+901+ const response = await ky.post(new Request(server.url, {method: 'POST', body: 'text'}), {902+ headers: {'content-type': undefined},903+ }).json<IncomingHttpHeaders>();904+905+ t.false('content-type' in response);906+});907+908+test('remove a `Request` input header with the function form of `.extend()`', async t => {909+ const server = await createHttpTestServer(t);910+ server.get('/', echoHeaders);911+912+ const instance = ky.create({headers: {'x-parent': 'parent'}}).extend(parentDefaults => ({913+ headers: {...parentDefaults.headers as Record<string, string>, rainbow: undefined},914+ }));915+ const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow'}})).json<IncomingHttpHeaders>();916+917+ t.is(response['x-parent'], 'parent');918+ t.false('rainbow' in response);919+});920+921+test('remove a `Request` input header with `replaceOption()` headers containing undefined', async t => {922+ const server = await createHttpTestServer(t);923+ server.get('/', echoHeaders);924+925+ const instance = ky.create({headers: {'x-parent': 'parent'}}).extend({926+ headers: replaceOption({rainbow: undefined, unicorn: 'unicorn'}),927+ });928+ const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow'}})).json<IncomingHttpHeaders>();929+930+ t.false('x-parent' in response);931+ t.false('rainbow' in response);932+ t.is(response['unicorn'], 'unicorn');933+});934+935+test('an init hook can set a header that was removed with undefined in the request options', async t => {936+ const server = await createHttpTestServer(t);937+ server.get('/', echoHeaders);938+939+ const response = await ky(new Request(server.url, {headers: {rainbow: 'rainbow'}}), {940+ headers: {rainbow: undefined},941+ hooks: {942+ init: [943+ options => {944+ t.is((options.headers as Record<string, string | undefined>)['rainbow'], undefined);945+ t.true('rainbow' in (options.headers as Record<string, string | undefined>));946+ (options.headers as Record<string, string | undefined>)['rainbow'] = 'from-init';947+ },948+ ],949+ },950+ }).json<IncomingHttpHeaders>();951+952+ t.is(response['rainbow'], 'from-init');953+});954+955+test('headers set to undefined in the request options do not affect other requests of the instance', async t => {956+ const server = await createHttpTestServer(t);957+ server.get('/', echoHeaders);958+959+ const instance = ky.create({headers: {rainbow: 'instance'}});960+ const first = await instance(server.url, {headers: {rainbow: undefined}}).json<IncomingHttpHeaders>();961+ const second = await instance(server.url).json<IncomingHttpHeaders>();962+963+ t.false('rainbow' in first);964+ t.is(second['rainbow'], 'instance');965+});966+967+test('remove a `Request` input header with undefined when instance defaults are a `Headers` instance', async t => {968+ const server = await createHttpTestServer(t);969+ server.get('/', echoHeaders);970+971+ const instance = ky.create({headers: new Headers({'x-instance': '1'})});972+ const response = await instance(new Request(server.url, {headers: {'x-token': 'secret'}}), {973+ headers: {'x-token': undefined},974+ }).json<IncomingHttpHeaders>();975+976+ t.is(response['x-instance'], '1');977+ t.false('x-token' in response);978+});979+980+test('remove a `Request` input header with undefined when instance defaults are an array of pairs', async t => {981+ const server = await createHttpTestServer(t);982+ server.get('/', echoHeaders);983+984+ const instance = ky.create({headers: [['x-instance', '1']]});985+ const response = await instance(new Request(server.url, {headers: {'x-token': 'secret'}}), {986+ headers: {'x-token': undefined},987+ }).json<IncomingHttpHeaders>();988+989+ t.is(response['x-instance'], '1');990+ t.false('x-token' in response);991+});992+993+test('remove a `Request` input header with a `Headers` instance holding the string "undefined"', async t => {994+ const server = await createHttpTestServer(t);995+ server.get('/', echoHeaders);996+997+ const response = await ky(new Request(server.url, {headers: {'x-token': 'secret', unicorn: 'unicorn'}}), {998+ // @ts-expect-error Headers does not support undefined values999+ headers: new Headers({'x-token': undefined}),1000+ }).json<IncomingHttpHeaders>();1001+1002+ t.is(response['unicorn'], 'unicorn');1003+ t.false('x-token' in response);1004+});1005+1006+test('remove a `Request` input header with undefined when the request headers are a `Headers` instance', async t => {1007+ const server = await createHttpTestServer(t);1008+ server.get('/', echoHeaders);1009+1010+ const instance = ky.create({headers: {'x-token': undefined}});1011+ const response = await instance(new Request(server.url, {headers: {'x-token': 'secret'}}), {1012+ headers: new Headers({'x-request': '1'}),1013+ }).json<IncomingHttpHeaders>();1014+1015+ t.is(response['x-request'], '1');1016+ t.false('x-token' in response);1017+});1018+1019+test('`init` hooks receive plain object headers even when a `Headers` instance was passed', async t => {1020+ const server = await createHttpTestServer(t);1021+ server.get('/', echoHeaders);1022+1023+ let initHeaders: unknown;1024+ const response = await ky(server.url, {1025+ headers: new Headers({'X-Rainbow': 'rainbow'}),1026+ hooks: {1027+ init: [1028+ options => {1029+ initHeaders = options.headers;1030+ },1031+ ],1032+ },1033+ }).json<IncomingHttpHeaders>();1034+1035+ t.deepEqual(initHeaders, {'x-rainbow': 'rainbow'});1036+ t.is(response['x-rainbow'], 'rainbow');1037+});1038+1039+test('a `Request` input header with the literal string "undefined" is sent as-is', async t => {1040+ let sentHeaders: string[][] | undefined;1041+1042+ await ky(new Request('https://example.com', {headers: {'x-a': 'undefined', 'x-b': '1'}}), {1043+ async fetch(request) {1044+ sentHeaders = [...(request as Request).headers];1045+ return new Response('ok');1046+ },1047+ });1048+1049+ t.deepEqual(sentHeaders, [['x-a', 'undefined'], ['x-b', '1']]);1050+});1051+1052+test('duplicate `set-cookie` headers on a `Request` input are all sent', async t => {1053+ let sentHeaders: string[][] | undefined;1054+ const request = new Request('https://example.com');1055+ request.headers.append('set-cookie', 'a=1');1056+ request.headers.append('set-cookie', 'b=2');1057+1058+ await ky(request, {1059+ async fetch(request) {1060+ sentHeaders = [...(request as Request).headers];1061+ return new Response('ok');1062+ },1063+ });1064+1065+ t.deepEqual(sentHeaders, [['set-cookie', 'a=1'], ['set-cookie', 'b=2']]);1066+});1067+1068+test('`.extend()` callbacks receive plain object headers even when a `Headers` instance was passed', t => {1069+ let parentHeaders: unknown;1070+ ky.create({headers: new Headers({'X-Rainbow': 'rainbow'})}).extend(parentDefaults => {1071+ parentHeaders = parentDefaults.headers;1072+ return {};1073+ });1074+1075+ t.deepEqual(parentHeaders, {'x-rainbow': 'rainbow'});1076+});modified:test/hooks.ts+2 added-1 removed
5831 unmodified lines5832 headers: new Headers(),5833 hooks: {5834 init: [5835 options => {5836- (options.headers as Headers).set('x-request-id', String(++requestIdentifier));5836+ // Merged headers are always a plain object with lowercase names, even when a `Headers` instance was passed.5837+ (options.headers as Record<string, string>)['x-request-id'] = String(++requestIdentifier);5838 },5839 ],5840 },5841 });129 unmodified linesmodified:readme.md+2 added-2 removed
438 unmodified lines439 440 Type: `Function[]`\441 Default: `[]`442 443-This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here.443+This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option is always a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.444 445 Unlike other hooks, `init` hooks are synchronous. Any error thrown will propagate synchronously and will not be caught by `beforeError` hooks.446 447 A common use case is to add a search parameter to every request:481 unmodified lines929 Create a new `ky` instance with some defaults overridden with your own.930 931 In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.932 933-You can pass headers as a `Headers` instance or a plain object. Plain object header names are normalized to lowercase when options are merged, so `init` hooks always see lowercase keys.933+You can pass headers as a `Headers` instance or a plain object. Headers are normalized to a plain object with lowercase names when options are merged, so `init` hooks always see a plain object with lowercase keys. A header removed with `undefined` stays in that object with an `undefined` value.934 935 You can remove a header with `.extend()` by passing the header with an `undefined` value.936 Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.937 919 unmodified lines