merge.ts
This file
Path
source/utils/merge.ts
501 lines · 20.1 KiB · TypeScript
Last changed by
RefactorSindre Sorhusbefore adoptiona5ed57b
History of this fileTake it
1import type {KyHeadersInit, Options} from '../types/options.js';2import type {Hooks, NormalizedHooks} from '../types/hooks.js';3import {supportsAbortSignal} from '../core/constants.js';4import {isNonArrayObject, isObject} from './is.js';56// Registered globally so that a wrapper created by a second copy of Ky, which happens with a duplicated dependency, is still recognised.7const replaceSymbol: unique symbol = Symbol.for('ky.replaceOption');89type ReplaceMarked<T> = {10 [replaceSymbol]: true;11 value: T;12 toJSON: () => T;13};1415type ReplaceState<T> = {16 isReplace: boolean;17 value: T;18};1920const getReplaceState = <T>(value: T): ReplaceState<T> =>21 isObject(value) && (value as any)[replaceSymbol] === true22 ? {23 isReplace: true,24 value: (value as unknown as ReplaceMarked<T>).value,25 }26 : {27 isReplace: false,28 value,29 };3031/**32Wraps a value so that `ky.extend()` will replace the parent value instead of merging with it. Works with hooks, headers, search parameters, context, and any other deep-merged option.3334Inside the `json` option, which holds your own data, use it only where it replaces an inherited value. Ky does not look for it anywhere else there. The `context` option is merged shallowly, so only a wrapper around the whole `context` is supported.3536By default, `.extend()` deep-merges options with the parent instance: hooks get appended, headers get merged, and search parameters get accumulated. Use `replaceOption` when you want to fully replace a merged property instead.3738@example39```40import ky, {replaceOption} from 'ky';4142const base = ky.create({43 hooks: {beforeRequest: [addAuth, addTracking]},44});4546// Replaces instead of appending47const extended = base.extend({48 hooks: replaceOption({beforeRequest: [onlyThis]}),49});50// hooks.beforeRequest is now [onlyThis], not [addAuth, addTracking, onlyThis]51```52*/53export const replaceOption = <T>(value: T): T => {54 const markedValue: ReplaceMarked<T> = {55 [replaceSymbol]: true,56 value,57 // The leftover pass below skips `json`, so a wrapper there with nothing to replace is unwrapped when the body is serialized.58 toJSON: () => value,59 };60 return markedValue as unknown as T;61};6263export const validateAndMerge = (...sources: Array<Partial<Options> | undefined>): Partial<Options> => {64 for (const source of sources) {65 if (source !== undefined && !isNonArrayObject(source)) {66 throw new TypeError('The `options` argument must be an object');67 }68 }6970 return deepMerge({}, ...sources);71};7273export const mergeHeaders = (source1: KyHeadersInit = {}, source2: KyHeadersInit = {}) => {74 // 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.75 const result = new globalThis.Headers(source1 as RequestInit['headers']);7677 for (const [key, value] of Object.entries(toHeaderObject(source2))) {78 if (value === undefined) {79 result.delete(key);80 } else {81 result.set(key, value);82 }83 }8485 return result;86};8788const isPlainObject = (value: unknown): value is Record<string, unknown> => {89 if (!isNonArrayObject(value)) {90 return false;91 }9293 const prototype = Object.getPrototypeOf(value);94 return prototype === Object.prototype || prototype === null;95};9697// Only plain objects and arrays are merged. Class instances (for example, a `Date` in `json` or an undici `Agent` in `dispatcher`) are replaced as a whole, since merging their own properties into a plain object would strip their prototype.98const isMergeable = (value: unknown): value is Record<string, unknown> | unknown[] => isPlainObject(value) || Array.isArray(value);99100export const cloneShallow = <T>(value: T): T => {101 if (value instanceof URLSearchParams) {102 const copy: MarkedSearchParameters = new URLSearchParams(value);103 const deleted = (value as MarkedSearchParameters)[deletedParametersSymbol];104 if (deleted) {105 // Preserve internal deletion markers so init-hook cloning does not resurrect params removed during option merging.106 copy[deletedParametersSymbol] = new Set(deleted);107 }108109 return copy as T;110 }111112 if (Array.isArray(value)) {113 return [...value] as T;114 }115116 if (isPlainObject(value)) {117 const copy = {...value};118 return copy as T;119 }120121 return value;122};123124// A tuple array is copied pair by pair, so changing a pair of the copy does not change the caller's `searchParams`.125export const cloneSearchParameters = <T>(value: T): T =>126 Array.isArray(value) ? value.map(parameter => cloneShallow(parameter)) as T : cloneShallow(value);127128// Recursively clone plain objects and arrays so that `init`-hook mutations to nested `json` or `context` values do not leak into the next request. Non-plain values (functions, class instances, `Date`, `URLSearchParams`, …) are kept by reference, matching how option merging treats them as whole values. The `seen` map keeps shared and cyclic references intact.129export const cloneDeep = <T>(value: T, seen: WeakMap<Record<string, unknown> | unknown[], unknown> = new WeakMap()): T => {130 if (!isMergeable(value)) {131 return value;132 }133134 const existingCopy = seen.get(value);135 if (existingCopy) {136 return existingCopy as T;137 }138139 if (Array.isArray(value)) {140 const copy: unknown[] = [];141 seen.set(value, copy);142 for (const item of value) {143 copy.push(cloneDeep(item, seen));144 }145146 return copy as T;147 }148149 // Preserve a null prototype, which callers use to avoid inheriting from `Object.prototype`.150 const copy: Record<string, unknown> = Object.getPrototypeOf(value) === null ? Object.create(null) : {};151 seen.set(value, copy);152 for (const key of Reflect.ownKeys(value)) {153 if (!Object.prototype.propertyIsEnumerable.call(value, key)) {154 continue;155 }156157 // Define instead of assign so a `__proto__` key becomes an own property rather than changing the prototype.158 Object.defineProperty(copy, key, {159 value: cloneDeep((value as Record<PropertyKey, unknown>)[key], seen),160 writable: true,161 enumerable: true,162 configurable: true,163 });164 }165166 return copy as T;167};168169// 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.170const toHeaderObject = (source: KyHeadersInit): Record<string, string | undefined> => {171 if (isPlainObject(source)) {172 return source as Record<string, string | undefined>;173 }174175 const isHeadersInstance = source instanceof globalThis.Headers;176 const result: Record<string, string | undefined> = {};177178 // 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.179 for (const [key, value] of new globalThis.Headers(source as RequestInit['headers']).entries()) {180 result[key] = isHeadersInstance && value === 'undefined' ? undefined : value;181 }182183 return result;184};185186// 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.187// 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.188export const mergeHeaderContainers = (source1: KyHeadersInit, source2: KyHeadersInit): Record<string, string | undefined> => {189 const result = new Map<string, string | undefined>();190191 for (const [key, value] of [...Object.entries(toHeaderObject(source1)), ...Object.entries(toHeaderObject(source2))]) {192 result.set(key.toLowerCase(), value);193 }194195 return Object.fromEntries(result);196};197198function newHookValue<K extends keyof Hooks>(original: Hooks, incoming: Hooks, property: K): NormalizedHooks[K] {199 // An absent key must keep the parent's hooks, which is why this check needs `Object.hasOwn`.200 if (Object.hasOwn(incoming, property) && incoming[property] === undefined) {201 return [];202 }203204 // A single hook type can be wrapped in `replaceOption()` to replace only that array instead of the whole `hooks` object.205 const {isReplace, value} = getReplaceState(incoming[property]);206 // Merging ignores anything that is neither an array nor an object, so a single function or a string used to be dropped without a word and the hook simply never ran. `null` is rejected here too, rather than treated as absent: use `undefined` to clear a hook list.207 if (value !== undefined && (!Array.isArray(value) || !value.every(hook => typeof hook === 'function'))) {208 throw new TypeError(`\`hooks.${property}\` must be an array of functions`);209 }210211 if (isReplace) {212 return [...(value ?? [])] as NormalizedHooks[K];213 }214215 return deepMerge<NormalizedHooks[K]>(original[property] ?? [], value ?? []);216}217218export const mergeHooks = (original: Hooks = {}, incoming: Hooks = {}): NormalizedHooks => {219 // `undefined` selects the default through the parameter default. `null` is not accepted, so it reaches this check and is reported like any other bad shape.220 if (!isNonArrayObject(incoming)) {221 throw new TypeError('The `hooks` option must be an object');222 }223224 return {225 init: newHookValue(original, incoming, 'init'),226 beforeRequest: newHookValue(original, incoming, 'beforeRequest'),227 beforeRetry: newHookValue(original, incoming, 'beforeRetry'),228 beforeError: newHookValue(original, incoming, 'beforeError'),229 afterResponse: newHookValue(original, incoming, 'afterResponse'),230 };231};232233export const deletedParametersSymbol = Symbol('deletedParameters');234235export type MarkedSearchParameters = URLSearchParams & {[deletedParametersSymbol]?: Set<string>};236237// Copies the array or object only when an item actually changes, so an untouched value keeps its identity. A hole in a sparse array is skipped, which is fine since it holds no wrapper.238const resolveItemMarkers = (value: Record<string, unknown> | unknown[], resolveItem: (item: unknown) => unknown): Record<string, unknown> | unknown[] => {239 let resolved: Record<string, unknown> | unknown[] | undefined;240 for (const [key, item] of Object.entries(value)) {241 const replacement = resolveItem(item);242 if (replacement !== item) {243 resolved ??= Array.isArray(value) ? [...value] : {...value};244 // An array index is written through its string key, the same way `Object.entries()` gave it.245 (resolved as Record<string, unknown>)[key] = replacement;246 }247 }248249 return resolved ?? value;250};251252// `json` and `context` are user data, which can be large, so they are not walked on every request.253const userDataOptions = new Set(['json', 'context']);254255// `replaceOption()` can wrap a value at any depth of a deep-merged option, but a wrapper is only unwrapped where a merge actually runs, so a wrapper on a key with no parent value kept its `{value}` envelope. This resolves the leftovers in one pass, copying only the branches that actually contained a wrapper so every other value keeps its identity. `resolved` maps each visited value to its result, so a value shared by two branches is walked once and stays shared, and a cyclic option cannot recurse forever: a value still being resolved maps to itself.256const resolveReplaceMarkers = (value: unknown, resolved: Map<unknown, unknown>): unknown => {257 if (!isMergeable(value)) {258 return value;259 }260261 if (resolved.has(value)) {262 return resolved.get(value);263 }264265 resolved.set(value, value);266 const resolveItem = (item: unknown) => resolveReplaceMarkers(getReplaceState(item).value, resolved);267 const result = resolveItemMarkers(value, resolveItem);268 resolved.set(value, result);269270 return result;271};272273const appendSearchParameters = (target: any, source: any): URLSearchParams => {274 const result: MarkedSearchParameters = new URLSearchParams();275 // Deleted keys stay marked even when a later layer re-adds the key, so the key is still removed from the input URL before the re-added value is appended.276 const deleted = new Set<string>();277278 // Both are defined, since an `undefined` layer clears the search parameters instead of being merged.279 for (const input of [target, source]) {280 if (input instanceof URLSearchParams) {281 // A merged `URLSearchParams` already applied its own deletions before any re-added entries, so its deletions only apply to what was merged before it.282 const inputDeleted = (input as MarkedSearchParameters)[deletedParametersSymbol];283 if (inputDeleted) {284 for (const key of inputDeleted) {285 result.delete(key);286 deleted.add(key);287 }288 }289290 for (const [key, value] of input.entries()) {291 result.append(key, value);292 }293 } else if (Array.isArray(input)) {294 for (const pair of input) {295 if (!Array.isArray(pair) || pair.length !== 2) {296 throw new TypeError('Array search parameters must be provided in [[key, value], ...] format');297 }298299 // Unwrapped for the same reason as in the object branch below.300 const key = String(pair[0]);301 const {isReplace, value} = getReplaceState(pair[1]);302 if (isReplace) {303 result.delete(key);304 }305306 result.append(key, String(value));307 }308 } else if (isObject(input)) {309 for (const [key, value] of Object.entries(input)) {310 // A `replaceOption()` wrapper is unwrapped here, because this branch stringifies every value, so a wrapper that reached it would land in the URL as `[object Object]`. A wrapped value replaces the inherited values of its key instead of being added to them.311 const {isReplace, value: entry} = getReplaceState(value);312 if (entry === undefined) {313 result.delete(key);314 deleted.add(key);315 } else {316 if (isReplace) {317 result.delete(key);318 }319320 result.append(key, String(entry));321 }322 }323 } else {324 // String325 const parameters = new URLSearchParams(input);326 for (const [key, value] of parameters.entries()) {327 result.append(key, value);328 }329 }330 }331332 if (deleted.size > 0) {333 result[deletedParametersSymbol] = deleted;334 }335336 return result;337};338339// TODO: Make this strongly-typed (no `any`).340const deepMergeInternal = <T>(isRoot: boolean, ...sources: Array<Partial<T> | undefined>): T => {341 let returnValue: any = {};342 let headers: KyHeadersInit = {};343 let hooks = {};344 let searchParameters: any;345 const signals: AbortSignal[] = [];346347 for (const source of sources) {348 if (Array.isArray(source)) {349 if (!Array.isArray(returnValue)) {350 returnValue = [];351 }352353 returnValue = [...returnValue, ...source];354 } else if (isObject(source)) {355 for (let [key, value] of Object.entries(source)) {356 const replaceState = getReplaceState(value);357 const {isReplace} = replaceState;358 value = replaceState.value;359360 const isRootSignal = isRoot && key === 'signal';361 if (isRootSignal && (isReplace || value === undefined)) {362 signals.length = 0;363 }364365 // Special handling for AbortSignal instances at the root options level366 if (isRootSignal && value instanceof globalThis.AbortSignal) {367 signals.push(value);368 continue;369 }370371 // Option merging would otherwise let a `null` silently replace the inherited headers.372 if (isRoot && key === 'headers' && value === null) {373 throw new TypeError('The `headers` option must not be `null`. Use `undefined` to clear it.');374 }375376 // Special handling for context - shallow merge only.377 // Scoped to the root options level so it never rewrites nested user data that378 // happens to contain a `context` key (e.g. a `json` request body).379 if (isRoot && key === 'context') {380 // `null` is not accepted, so it is reported here rather than treated as absent.381 if (value !== undefined && !isNonArrayObject(value)) {382 throw new TypeError('The `context` option must be an object');383 }384385 // Shallow merge: always create a new object to prevent mutation bugs386 returnValue = {387 ...returnValue,388 context: value === undefined389 ? {}390 : (isReplace391 ? {...value}392 : {...returnValue.context, ...value}),393 };394 continue;395 }396397 // Special handling for searchParams.398 // Scoped to the root options level so it never rewrites nested user data that399 // happens to contain a `searchParams` key (e.g. a `json` request body).400 if (isRoot && key === 'searchParams') {401 if (value === null) {402 throw new TypeError('The `searchParams` option must not be `null`. Use `undefined` to clear it.');403 }404405 if (value === undefined) {406 // Explicit undefined removes searchParams407 searchParameters = undefined;408 } else if (isReplace || searchParameters === undefined) {409 // First or replacement source: shallow-clone to preserve type (string/object/URLSearchParams/tuples) without sharing the caller's object410 searchParameters = cloneSearchParameters(value);411 } else {412 // Subsequent sources: merge and convert to URLSearchParams413 searchParameters = appendSearchParameters(searchParameters, value);414 }415416 continue;417 }418419 // Checked here as well as when the request is built, because a later layer would otherwise replace an invalid value, `null` included, before anything reports it.420 if (isRoot && key === 'retry' && value !== undefined && typeof value !== 'number' && !isNonArrayObject(value)) {421 throw new TypeError('`retry` must be a number or an object');422 }423424 // `retry` accepts a number as shorthand for `{limit: number}`. Expand it before425 // merging so extending a numeric `retry` with an object keeps the limit instead426 // of dropping it (e.g. `ky.create({retry: 3}).extend({retry: {methods: ['get']}})`),427 // and extending an object `retry` with a number keeps the other options428 // (e.g. `ky.create({retry: {methods: ['post']}}).extend({retry: 3})`).429 // Scoped to the root options level so it never rewrites nested user data that430 // happens to contain a `retry` key (e.g. a `json` request body).431 if (isRoot && key === 'retry' && !isReplace) {432 if (isObject(value) && typeof returnValue[key] === 'number') {433 returnValue = {...returnValue, [key]: {limit: returnValue[key]}};434 } else if (typeof value === 'number' && isObject(returnValue[key])) {435 value = {limit: value};436 }437 }438439 if (isRoot && key === 'retry' && isPlainObject(value) && (isReplace || !isMergeable(returnValue[key]))) {440 // Resolve nested replacement markers even when there is no parent retry configuration to merge.441 value = deepMergeInternal<unknown>(false, {}, value);442 } else if (!isReplace && isMergeable(returnValue[key]) && isMergeable(value) && Array.isArray(returnValue[key]) === Array.isArray(value)) {443 value = deepMergeInternal<unknown>(false, returnValue[key], value);444 }445446 returnValue = {...returnValue, [key]: value};447 }448449 // Scoped to the root options level so it never rewrites nested user data that450 // happens to contain a `hooks` key (e.g. a `json` request body).451 // Every value but `undefined` goes through `mergeHooks`, which rejects a bad shape, `null` included, so a later layer cannot hide it.452 if (isRoot && (source as any).hooks !== undefined) {453 const {value: hookValue, isReplace} = getReplaceState((source as any).hooks);454 hooks = isReplace455 ? mergeHooks({}, hookValue)456 : mergeHooks(hooks, hookValue);457458 returnValue.hooks = hooks;459 }460461 // Scoped to the root options level so it never rewrites nested user data that462 // happens to contain a `headers` key (e.g. a `json` request body).463 if (isRoot && isObject((source as any).headers)) {464 const {value: headerValue, isReplace} = getReplaceState((source as any).headers);465 headers = mergeHeaderContainers(isReplace ? {} : headers, headerValue as KyHeadersInit);466467 returnValue.headers = headers;468 }469 }470 }471472 if (searchParameters !== undefined) {473 returnValue.searchParams = searchParameters;474 }475476 if (signals.length > 0) {477 if (signals.length === 1) {478 returnValue.signal = signals[0];479 } else if (supportsAbortSignal) {480 returnValue.signal = AbortSignal.any(signals);481 } else {482 // When AbortSignal.any is not available, use the last signal483 // This maintains the previous behavior before signal merging was added484 // This can be removed when the `supportsAbortSignal` check is removed.485 returnValue.signal = signals.at(-1);486 }487 }488489 if (isRoot) {490 for (const [key, value] of Object.entries(returnValue)) {491 if (!userDataOptions.has(key)) {492 returnValue[key] = resolveReplaceMarkers(value, new Map());493 }494 }495 }496497 return returnValue;498};499500export const deepMerge = <T>(...sources: Array<Partial<T> | undefined>): T =>501 deepMergeInternal<T>(true, ...sources);