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
The walk stopped after 200 commits: lines older than 37fc250 point at it.
Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 1why, one step back1import type {KyHeadersInit, Options} from '../types/options.js';Fix `hooks: {x: undefined}` and `signal: undefined` failing to type-check with `exactOptionalPropertyTypes`Sindre Sorhusbefore adoptionee806e0
line 2why, one step back2import type {Hooks, NormalizedHooks} from '../types/hooks.js';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 3why, one step back3import {supportsAbortSignal} from '../core/constants.js';RefactorSindre Sorhusbefore adoptiona5ed57b
line 4why, one step back4import {isNonArrayObject, isObject} from './is.js';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 5why, one step back5Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
lines 6–7why, one step back6// 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');Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e
line 8why, one step back8Various tweaksSindre Sorhusbefore adoption0dd9522
lines 9–11why, one step back9type ReplaceMarked<T> = {10 [replaceSymbol]: true;11 value: T;Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
line 12why, one step back12 toJSON: () => T;Various tweaksSindre Sorhusbefore adoption0dd9522
line 13why, one step back13};Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e
line 14why, one step back14Various tweaksSindre Sorhusbefore adoption0dd9522
lines 15–30why, one step back15type 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 };30Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e
line 31why, one step back31/**Readme tweaksSindre Sorhusbefore adoption7f2eade
line 32why, one step back32Wraps 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.Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e
line 33why, one step back33Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
lines 34–35why, one step back34Inside 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.35Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e
lines 36–52why, one step back36By 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*/Various tweaksSindre Sorhusbefore adoption0dd9522
line 53why, one step back53export const replaceOption = <T>(value: T): T => {Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
lines 54–59why, one step back54 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 };Various tweaksSindre Sorhusbefore adoption0dd9522
line 60why, one step back60 return markedValue as unknown as T;Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e
lines 61–62why, one step back61};62Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 63–64why, one step back63export const validateAndMerge = (...sources: Array<Partial<Options> | undefined>): Partial<Options> => {64 for (const source of sources) {RefactorSindre Sorhusbefore adoptiona5ed57b
line 65why, one step back65 if (source !== undefined && !isNonArrayObject(source)) {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 66–73why, one step back66 throw new TypeError('The `options` argument must be an object');67 }68 }6970 return deepMerge({}, ...sources);71};7273export const mergeHeaders = (source1: KyHeadersInit = {}, source2: KyHeadersInit = {}) => {Fix headers set to `undefined` not removing the header from a `Request` inputSindre Sorhusbefore adoptiond5bacef
line 74why, one step back74 // 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.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 75why, one step back75 const result = new globalThis.Headers(source1 as RequestInit['headers']);Fix headers set to `undefined` in `init` hooks being sent as the string `"undefined"`Sindre Sorhusbefore adoption224034d
line 76why, one step back76Fix headers set to `undefined` not removing the header from a `Request` inputSindre Sorhusbefore adoptiond5bacef
lines 77–78why, one step back77 for (const [key, value] of Object.entries(toHeaderObject(source2))) {78 if (value === undefined) {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 79–87why, one step back79 result.delete(key);80 } else {81 result.set(key, value);82 }83 }8485 return result;86};87Various tweaksSindre Sorhusbefore adoption0dd9522
line 88why, one step back88const isPlainObject = (value: unknown): value is Record<string, unknown> => {RefactorSindre Sorhusbefore adoptiona5ed57b
line 89why, one step back89 if (!isNonArrayObject(value)) {Various tweaksSindre Sorhusbefore adoption0dd9522
lines 90–96why, one step back90 return false;91 }9293 const prototype = Object.getPrototypeOf(value);94 return prototype === Object.prototype || prototype === null;95};96Fix option merging rewriting nested user data and flattening class instancesSindre Sorhusbefore adoptione06d351
lines 97–99why, one step back97// 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);99Various tweaksSindre Sorhusbefore adoption0dd9522
lines 100–101why, one step back100export const cloneShallow = <T>(value: T): T => {101 if (value instanceof URLSearchParams) {RefactorSindre Sorhusbefore adoptiona5ed57b
lines 102–103why, one step back102 const copy: MarkedSearchParameters = new URLSearchParams(value);103 const deleted = (value as MarkedSearchParameters)[deletedParametersSymbol];Fix init hook URLSearchParams deletionsSindre Sorhusbefore adoptionadd0703
lines 104–109why, one step back104 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;Various tweaksSindre Sorhusbefore adoption0dd9522
lines 110–123why, one step back110 }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};123RefactorSindre Sorhusbefore adoptiona5ed57b
lines 124–127why, one step back124// 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);127Fix `init` hook mutations to nested `json` and `context` values leaking across requestsSindre Sorhusbefore adoption88e2432
lines 128–148why, one step back128// 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 }148HardenSindre Sorhusbefore adoption8d8e7a4
lines 149–150why, one step back149 // 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) : {};Fix `init` hook mutations to nested `json` and `context` values leaking across requestsSindre Sorhusbefore adoption88e2432
line 151why, one step back151 seen.set(value, copy);Preserve symbol-keyed context in init hooksSindre Sorhusbefore adoptiona8753dc
lines 152–156why, one step back152 for (const key of Reflect.ownKeys(value)) {153 if (!Object.prototype.propertyIsEnumerable.call(value, key)) {154 continue;155 }156Fix `init` hook mutations to nested `json` and `context` values leaking across requestsSindre Sorhusbefore adoption88e2432
lines 157–158why, one step back157 // Define instead of assign so a `__proto__` key becomes an own property rather than changing the prototype.158 Object.defineProperty(copy, key, {Preserve symbol-keyed context in init hooksSindre Sorhusbefore adoptiona8753dc
line 159why, one step back159 value: cloneDeep((value as Record<PropertyKey, unknown>)[key], seen),Fix `init` hook mutations to nested `json` and `context` values leaking across requestsSindre Sorhusbefore adoption88e2432
lines 160–168why, one step back160 writable: true,161 enumerable: true,162 configurable: true,163 });164 }165166 return copy as T;167};168Fix headers set to `undefined` not removing the header from a `Request` inputSindre Sorhusbefore adoptiond5bacef
lines 169–172why, one step back169// 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>;Various tweaksSindre Sorhusbefore adoption0dd9522
lines 173–174why, one step back173 }174Fix headers set to `undefined` not removing the header from a `Request` inputSindre Sorhusbefore adoptiond5bacef
lines 175–183why, one step back175 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;Various tweaksSindre Sorhusbefore adoption0dd9522
lines 184–185why, one step back184};185RefactorSindre Sorhusbefore adoptiona5ed57b
lines 186–189why, one step back186// 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>();Fix headers set to `undefined` not removing the header from a `Request` inputSindre Sorhusbefore adoptiond5bacef
line 190why, one step back190RefactorSindre Sorhusbefore adoptiona5ed57b
lines 191–197why, one step back191 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};197Fix `hooks: {x: undefined}` and `signal: undefined` failing to type-check with `exactOptionalPropertyTypes`Sindre Sorhusbefore adoptionee806e0
line 198why, one step back198function newHookValue<K extends keyof Hooks>(original: Hooks, incoming: Hooks, property: K): NormalizedHooks[K] {Reject a nullish hook list instead of treating it as absentSindre Sorhusbefore adoption33462fc
line 199why, one step back199 // An absent key must keep the parent's hooks, which is why this check needs `Object.hasOwn`.Fix `replaceOption()` crashing when wrapping a single hook typeSindre Sorhusbefore adoptioncc9b5a3
lines 200–205why, one step back200 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]);Reject a nullish hook list instead of treating it as absentSindre Sorhusbefore adoption33462fc
lines 206–208why, one step back206 // 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`);Report a `hooks` option that is not an objectSindre Sorhusbefore adoption0a9cbb1
lines 209–210why, one step back209 }210Fix `replaceOption()` crashing when wrapping a single hook typeSindre Sorhusbefore adoptioncc9b5a3
line 211why, one step back211 if (isReplace) {Fix `hooks: {x: undefined}` and `signal: undefined` failing to type-check with `exactOptionalPropertyTypes`Sindre Sorhusbefore adoptionee806e0
line 212why, one step back212 return [...(value ?? [])] as NormalizedHooks[K];Fix `replaceOption()` crashing when wrapping a single hook typeSindre Sorhusbefore adoptioncc9b5a3
lines 213–214why, one step back213 }214Fix `hooks: {x: undefined}` and `signal: undefined` failing to type-check with `exactOptionalPropertyTypes`Sindre Sorhusbefore adoptionee806e0
line 215why, one step back215 return deepMerge<NormalizedHooks[K]>(original[property] ?? [], value ?? []);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 216–217why, one step back216}217Report a `hooks` option that is not an objectSindre Sorhusbefore adoption0a9cbb1
line 218why, one step back218export const mergeHooks = (original: Hooks = {}, incoming: Hooks = {}): NormalizedHooks => {Reject a nullish hook list instead of treating it as absentSindre Sorhusbefore adoption33462fc
line 219why, one step back219 // `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.RefactorSindre Sorhusbefore adoptiona5ed57b
line 220why, one step back220 if (!isNonArrayObject(incoming)) {Report a `hooks` option that is not an objectSindre Sorhusbefore adoption0a9cbb1
line 221why, one step back221 throw new TypeError('The `hooks` option must be an object');Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 222why, one step back222 }Report a `hooks` option that is not an objectSindre Sorhusbefore adoption0a9cbb1
lines 223–224why, one step back223224 return {Reject a nullish hook list instead of treating it as absentSindre Sorhusbefore adoption33462fc
lines 225–229why, one step back225 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'),Report a `hooks` option that is not an objectSindre Sorhusbefore adoption0a9cbb1
lines 230–231why, one step back230 };231};Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 232why, one step back232Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe
lines 233–234why, one step back233export const deletedParametersSymbol = Symbol('deletedParameters');234RefactorSindre Sorhusbefore adoptiona5ed57b
line 235why, one step back235export type MarkedSearchParameters = URLSearchParams & {[deletedParametersSymbol]?: Set<string>};Resolve leftover `replaceOption()` wrappers, name the request behind a response, and advertise the media typesSindre Sorhusbefore adoptiona0eeae2
line 236why, one step back236RefactorSindre Sorhusbefore adoptiona5ed57b
lines 237–239why, one step back237// 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;Resolve leftover `replaceOption()` wrappers, name the request behind a response, and advertise the media typesSindre Sorhusbefore adoptiona0eeae2
lines 240–242why, one step back240 for (const [key, item] of Object.entries(value)) {241 const replacement = resolveItem(item);242 if (replacement !== item) {RefactorSindre Sorhusbefore adoptiona5ed57b
lines 243–245why, one step back243 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;Resolve leftover `replaceOption()` wrappers, name the request behind a response, and advertise the media typesSindre Sorhusbefore adoptiona0eeae2
lines 246–248why, one step back246 }247 }248RefactorSindre Sorhusbefore adoptiona5ed57b
line 249why, one step back249 return resolved ?? value;Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569
lines 250–251why, one step back250};251Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
lines 252–254why, one step back252// `json` and `context` are user data, which can be large, so they are not walked on every request.253const userDataOptions = new Set(['json', 'context']);254Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
lines 255–257why, one step back255// `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)) {Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569
lines 258–260why, one step back258 return value;259 }260Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
lines 261–263why, one step back261 if (resolved.has(value)) {262 return resolved.get(value);263 }Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569
line 264why, one step back264Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
lines 265–266why, one step back265 resolved.set(value, value);266 const resolveItem = (item: unknown) => resolveReplaceMarkers(getReplaceState(item).value, resolved);RefactorSindre Sorhusbefore adoptiona5ed57b
line 267why, one step back267 const result = resolveItemMarkers(value, resolveItem);Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
lines 268–270why, one step back268 resolved.set(value, result);269270 return result;Resolve leftover `replaceOption()` wrappers, name the request behind a response, and advertise the media typesSindre Sorhusbefore adoptiona0eeae2
lines 271–272why, one step back271};272Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 273why, one step back273const appendSearchParameters = (target: any, source: any): URLSearchParams => {RefactorSindre Sorhusbefore adoptiona5ed57b
line 274why, one step back274 const result: MarkedSearchParameters = new URLSearchParams();Fix a search parameter removed with `undefined` staying in the input URL when a later layer re-adds itSindre Sorhusbefore adoption91ea8a9
line 275why, one step back275 // 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.Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe
line 276why, one step back276 const deleted = new Set<string>();Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 277why, one step back277RefactorSindre Sorhusbefore adoptiona5ed57b
line 278why, one step back278 // Both are defined, since an `undefined` layer clears the search parameters instead of being merged.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 279–280why, one step back279 for (const input of [target, source]) {280 if (input instanceof URLSearchParams) {Fix a search parameter removed with `undefined` staying in the input URL when a later layer re-adds itSindre Sorhusbefore adoption91ea8a9
line 281why, one step back281 // A merged `URLSearchParams` already applied its own deletions before any re-added entries, so its deletions only apply to what was merged before it.RefactorSindre Sorhusbefore adoptiona5ed57b
line 282why, one step back282 const inputDeleted = (input as MarkedSearchParameters)[deletedParametersSymbol];Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe
lines 283–288why, one step back283 if (inputDeleted) {284 for (const key of inputDeleted) {285 result.delete(key);286 deleted.add(key);287 }288 }Fix a search parameter removed with `undefined` staying in the input URL when a later layer re-adds itSindre Sorhusbefore adoption91ea8a9
lines 289–292why, one step back289290 for (const [key, value] of input.entries()) {291 result.append(key, value);292 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 293–298why, one step back293 } 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 }298Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
lines 299–306why, one step back299 // 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));Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 307–309why, one step back307 }308 } else if (isObject(input)) {309 for (const [key, value] of Object.entries(input)) {TweaksSindre Sorhusbefore adoption3ded2aa
lines 310–312why, one step back310 // 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) {Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe
lines 313–315why, one step back313 result.delete(key);314 deleted.add(key);315 } else {TweaksSindre Sorhusbefore adoption3ded2aa
lines 316–320why, one step back316 if (isReplace) {317 result.delete(key);318 }319320 result.append(key, String(entry));Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 321–329why, one step back321 }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 }Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe
lines 330–333why, one step back330 }331332 if (deleted.size > 0) {333 result[deletedParametersSymbol] = deleted;Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 334–339why, one step back334 }335336 return result;337};338339// TODO: Make this strongly-typed (no `any`).Fix `extend()` dropping numeric `retry` limit when merging with an object (#867)Alexander Kireyevbefore adoption06375ef
line 340why, one step back340const deepMergeInternal = <T>(isRoot: boolean, ...sources: Array<Partial<T> | undefined>): T => {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 341why, one step back341 let returnValue: any = {};Various tweaksSindre Sorhusbefore adoption0dd9522
line 342why, one step back342 let headers: KyHeadersInit = {};Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 343–355why, one step back343 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)) {Various tweaksSindre Sorhusbefore adoption0dd9522
lines 356–359why, one step back356 const replaceState = getReplaceState(value);357 const {isReplace} = replaceState;358 value = replaceState.value;359Fix `signal` replacement when extending instances (#880)Sindre Sorhusbefore adoption0bda554
lines 360–370why, one step back360 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 }370TweaksSindre Sorhusbefore adoption3ded2aa
lines 371–375why, one step back371 // 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 }375Fix option merging rewriting nested user data and flattening class instancesSindre Sorhusbefore adoptione06d351
lines 376–379why, one step back376 // 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') {TweaksSindre Sorhusbefore adoption3ded2aa
line 380why, one step back380 // `null` is not accepted, so it is reported here rather than treated as absent.RefactorSindre Sorhusbefore adoptiona5ed57b
line 381why, one step back381 if (value !== undefined && !isNonArrayObject(value)) {Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba
lines 382–384why, one step back382 throw new TypeError('The `context` option must be an object');383 }384TweaksSindre Sorhusbefore adoption3ded2aa
line 385why, one step back385 // Shallow merge: always create a new object to prevent mutation bugsAdd `context` option (#772)Sindre Sorhusbefore adoption1e749ba
lines 386–387why, one step back386 returnValue = {387 ...returnValue,TweaksSindre Sorhusbefore adoption3ded2aa
line 388why, one step back388 context: value === undefinedAdd `context` option (#772)Sindre Sorhusbefore adoption1e749ba
line 389why, one step back389 ? {}Various tweaksSindre Sorhusbefore adoption0dd9522
line 390why, one step back390 : (isReplaceTweaksSindre Sorhusbefore adoption3ded2aa
lines 391–392why, one step back391 ? {...value}392 : {...returnValue.context, ...value}),Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba
lines 393–396why, one step back393 };394 continue;395 }396Fix option merging rewriting nested user data and flattening class instancesSindre Sorhusbefore adoptione06d351
lines 397–400why, one step back397 // 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') {TweaksSindre Sorhusbefore adoption3ded2aa
lines 401–406why, one step back401 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 searchParamsAdd retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 407why, one step back407 searchParameters = undefined;Detect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c
lines 408–409why, one step back408 } else if (isReplace || searchParameters === undefined) {409 // First or replacement source: shallow-clone to preserve type (string/object/URLSearchParams/tuples) without sharing the caller's objectRefactorSindre Sorhusbefore adoptiona5ed57b
line 410why, one step back410 searchParameters = cloneSearchParameters(value);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 411–412why, one step back411 } else {412 // Subsequent sources: merge and convert to URLSearchParamsDetect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c
line 413why, one step back413 searchParameters = appendSearchParameters(searchParameters, value);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 414–418why, one step back414 }415416 continue;417 }418RefactorSindre Sorhusbefore adoptiona5ed57b
lines 419–423why, one step back419 // 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 }423Fix `extend()` dropping numeric `retry` limit when merging with an object (#867)Alexander Kireyevbefore adoption06375ef
lines 424–425why, one step back424 // `retry` accepts a number as shorthand for `{limit: number}`. Expand it before425 // merging so extending a numeric `retry` with an object keeps the limit insteadFix extending an object `retry` with a number dropping the other retry optionsSindre Sorhusbefore adoptionee3dec1
lines 426–428why, one step back426 // 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})`).Fix `extend()` dropping numeric `retry` limit when merging with an object (#867)Alexander Kireyevbefore adoption06375ef
lines 429–430why, one step back429 // 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).Fix extending an object `retry` with a number dropping the other retry optionsSindre Sorhusbefore adoptionee3dec1
lines 431–436why, one step back431 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 }Fix `extend()` dropping numeric `retry` limit when merging with an object (#867)Alexander Kireyevbefore adoption06375ef
lines 437–438why, one step back437 }438Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435
lines 439–440why, one step back439 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.Resolve retry replacements without parent retry optionsSindre Sorhusbefore adoptiond6e049a
lines 441–442why, one step back441 value = deepMergeInternal<unknown>(false, {}, value);442 } else if (!isReplace && isMergeable(returnValue[key]) && isMergeable(value) && Array.isArray(returnValue[key]) === Array.isArray(value)) {Fix option merging rewriting nested user data and flattening class instancesSindre Sorhusbefore adoptione06d351
line 443why, one step back443 value = deepMergeInternal<unknown>(false, returnValue[key], value);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 444–448why, one step back444 }445446 returnValue = {...returnValue, [key]: value};447 }448Fix option merging rewriting nested user data and flattening class instancesSindre Sorhusbefore adoptione06d351
lines 449–450why, one step back449 // 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).TweaksSindre Sorhusbefore adoption3ded2aa
lines 451–452why, one step back451 // 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) {Various tweaksSindre Sorhusbefore adoption0dd9522
lines 453–456why, one step back453 const {value: hookValue, isReplace} = getReplaceState((source as any).hooks);454 hooks = isReplace455 ? mergeHooks({}, hookValue)456 : mergeHooks(hooks, hookValue);Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e
line 457why, one step back457Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 458–460why, one step back458 returnValue.hooks = hooks;459 }460Fix option merging rewriting nested user data and flattening class instancesSindre Sorhusbefore adoptione06d351
lines 461–463why, one step back461 // 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)) {Various tweaksSindre Sorhusbefore adoption0dd9522
line 464why, one step back464 const {value: headerValue, isReplace} = getReplaceState((source as any).headers);Fix headers set to `undefined` not removing the header from a `Request` inputSindre Sorhusbefore adoptiond5bacef
line 465why, one step back465 headers = mergeHeaderContainers(isReplace ? {} : headers, headerValue as KyHeadersInit);Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e
line 466why, one step back466Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 467–483why, one step back467 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 addedFix `signal` replacement when extending instances (#880)Sindre Sorhusbefore adoption0bda554
line 484why, one step back484 // This can be removed when the `supportsAbortSignal` check is removed.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 485–486why, one step back485 returnValue.signal = signals.at(-1);486 }Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba
lines 487–488why, one step back487 }488Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
lines 489–491why, one step back489 if (isRoot) {490 for (const [key, value] of Object.entries(returnValue)) {491 if (!userDataOptions.has(key)) {Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
line 492why, one step back492 returnValue[key] = resolveReplaceMarkers(value, new Map());Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
lines 493–497why, one step back493 }494 }495 }496497 return returnValue;Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 498why, one step back498};Fix `extend()` dropping numeric `retry` limit when merging with an object (#867)Alexander Kireyevbefore adoption06375ef
lines 499–501why, one step back499500export const deepMerge = <T>(...sources: Array<Partial<T> | undefined>): T =>501 deepMergeInternal<T>(true, ...sources);