Open History to see the last commit
1// ESM shim for extend package (CJS/ESM interop issues)
2// Implements deep object extend/merge functionality
3
4type ExtendTarget = Record<string, unknown> | ((...args: unknown[]) => unknown)
5
6function isPlainObject(obj: unknown): obj is Record<string, unknown> {
7 if (!obj || Object.prototype.toString.call(obj) !== '[object Object]') {
8 return false
9 }
10 const proto = Object.getPrototypeOf(obj)
11 return proto === null || proto === Object.prototype
12}
13
14function extend(
15 deep: boolean,
16 target: ExtendTarget,
17 ...sources: unknown[]
18): ExtendTarget
19function extend(target: ExtendTarget, ...sources: unknown[]): ExtendTarget
20function extend(...args: unknown[]): ExtendTarget {
21 let deep = false
22 let i = 0
23
24 // Check if first argument is a boolean (deep flag)
25 if (typeof args[0] === 'boolean') {
26 deep = args[0]
27 i = 1
28 }
29
30 let target = args[i] as ExtendTarget
31 i++
32
33 // Handle case where target is null or not an object
34 if (
35 target == null ||
36 (typeof target !== 'object' && typeof target !== 'function')
37 ) {
38 target = {}
39 }
40
41 for (; i < args.length; i++) {
42 const source = args[i]
43 if (source == null) continue
44
45 for (const key in source as Record<string, unknown>) {
46 if (!Object.prototype.hasOwnProperty.call(source, key)) continue
47
48 const srcVal = (target as Record<string, unknown>)[key]
49 const copyVal = (source as Record<string, unknown>)[key]
50
51 // Prevent infinite loop
52 if (target === copyVal) continue
53
54 // Recurse if deep and merging objects/arrays
55 if (
56 deep &&
57 copyVal &&
58 (isPlainObject(copyVal) || Array.isArray(copyVal))
59 ) {
60 let clone: Record<string, unknown> | unknown[]
61 if (Array.isArray(copyVal)) {
62 clone = Array.isArray(srcVal) ? srcVal : []
63 } else {
64 clone = isPlainObject(srcVal) ? srcVal : {}
65 }
66 ;(target as Record<string, unknown>)[key] = extend(
67 deep,
68 clone as ExtendTarget,
69 copyVal,
70 )
71 } else if (copyVal !== undefined) {
72 ;(target as Record<string, unknown>)[key] = copyVal
73 }
74 }
75 }
76
77 return target
78}
79
80export default extend
81export { extend }