-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathdeepMerge.ts
More file actions
175 lines (156 loc) · 4.63 KB
/
deepMerge.ts
File metadata and controls
175 lines (156 loc) · 4.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
const UNSAFE_KEYS = new Set(['__proto__', 'constructor']);
/**
* Check if a value is a plain object (not a class instance, array, null, etc.)
*
* @internal
*/
const isPlainObject = (value: unknown): value is Record<string, unknown> => {
if (typeof value !== 'object' || value === null) {
return false;
}
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
};
/**
* Merge source array items into target array by index.
*
* When both source and target items at the same index are plain objects,
* they are merged recursively. Otherwise, the source item replaces the target.
*
* @internal
*/
const mergeArrayItemsByIndex = (
targetArray: unknown[],
sourceArray: unknown[],
ancestors: object[]
): void => {
for (let i = 0; i < sourceArray.length; i++) {
const srcItem = sourceArray[i];
const tgtItem = targetArray[i];
const isSrcPlainObject = isPlainObject(srcItem);
// Skip objects in the current ancestor chain to prevent circular references
if (isSrcPlainObject && ancestors.includes(srcItem)) {
continue;
}
// Merge nested plain objects recursively
if (isSrcPlainObject && isPlainObject(tgtItem)) {
ancestors.push(srcItem);
mergeRecursive(tgtItem, srcItem, ancestors);
ancestors.pop();
continue;
}
// Otherwise, replace the target item with source item
if (srcItem !== undefined || tgtItem === undefined) {
targetArray[i] = srcItem;
}
}
};
/**
* Handle merging when source value is an array.
*
* @internal
*/
const handleArrayMerge = (
target: Record<string, unknown>,
key: string,
sourceArray: unknown[],
targetValue: unknown,
ancestors: object[]
): void => {
if (!Array.isArray(targetValue)) {
target[key] = [...sourceArray];
return;
}
mergeArrayItemsByIndex(targetValue, sourceArray, ancestors);
};
/**
* Handle merging when source value is a plain object.
*
* @internal
*/
const handleObjectMerge = (
target: Record<string, unknown>,
key: string,
sourceObject: Record<string, unknown>,
targetValue: unknown,
ancestors: object[]
): void => {
if (isPlainObject(targetValue)) {
mergeRecursive(targetValue, sourceObject, ancestors);
return;
}
const newTarget: Record<string, unknown> = {};
mergeRecursive(newTarget, sourceObject, ancestors);
target[key] = newTarget;
};
/**
* Recursively merge source into target.
*
* @internal
*/
const mergeRecursive = (
target: Record<string, unknown>,
source: Record<string, unknown>,
ancestors: object[]
): void => {
for (const key of Object.keys(source)) {
if (UNSAFE_KEYS.has(key)) {
continue;
}
const sourceValue = source[key];
const targetValue = target[key];
if (Array.isArray(sourceValue)) {
if (ancestors.includes(sourceValue)) continue;
ancestors.push(sourceValue);
handleArrayMerge(target, key, sourceValue, targetValue, ancestors);
ancestors.pop();
continue;
}
if (isPlainObject(sourceValue)) {
if (ancestors.includes(sourceValue)) continue;
ancestors.push(sourceValue);
handleObjectMerge(target, key, sourceValue, targetValue, ancestors);
ancestors.pop();
continue;
}
if (sourceValue !== undefined || targetValue === undefined) {
target[key] = sourceValue;
}
}
};
/**
* Recursively merge properties from source objects into the target object, mutating it.
*
* Nested plain objects are merged recursively, arrays are merged by index (e.g., `[1, 2]` + `[3]` → `[3, 2]`),
* and class instances (Date, RegExp, custom classes) are assigned by reference. Circular references are
* detected via ancestor-chain tracking and safely skipped, while shared (non-circular) object references
* are merged correctly. Prototype pollution attempts (`__proto__`, `constructor`) are also skipped.
*
* @example
* ```typescript
* import { deepMerge } from '@aws-lambda-powertools/commons';
*
* const target = { a: 1, nested: { x: 1 } };
* const source = { b: 2, nested: { y: 2 } };
* const result = deepMerge(target, source);
* // result === target === { a: 1, b: 2, nested: { x: 1, y: 2 } }
* ```
*
* @param target - The target object to merge into (mutated)
* @param sources - One or more source objects to merge from
*/
const deepMerge = <T extends Record<string, unknown>>(
target: T,
...sources: Array<Record<string, unknown> | undefined | null>
): T => {
const ancestors: object[] = [target];
for (const source of sources) {
if (source != null) {
ancestors.push(source);
mergeRecursive(target, source, ancestors);
ancestors.pop();
}
}
return target;
};
export { deepMerge };