|
1
|
import { isDefined } from "./is-defined" |
|
2
|
|
|
3
|
/** |
|
4
|
* Creates a deep copy of the input, ensuring it's JSON-serializable. |
|
5
|
* - Breaks all reference sharing (creates new objects/arrays) |
|
6
|
* - Removes non-serializable values (functions, symbols, undefined properties) |
|
7
|
* - Normalizes special types (Date -> string) |
|
8
|
* - Only stringifies special objects, not entire tree (optimization) |
|
9
|
* @param result |
|
10
|
* @returns A deep copy with no shared references, guaranteed to be JSON-serializable |
|
11
|
*/ |
|
12
|
export function parseStringifyIfNecessary(result: unknown): any { |
|
13
|
if (result == null || typeof result !== "object") { |
|
14
|
return result |
|
15
|
} |
|
16
|
|
|
17
|
if (Array.isArray(result)) { |
|
18
|
return result.map((item) => parseStringifyIfNecessary(item)) |
|
19
|
} |
|
20
|
|
|
21
|
const isPlainObject = |
|
22
|
result.constructor === Object || result.constructor === undefined |
|
23
|
|
|
24
|
if (!isPlainObject) { |
|
25
|
const strResult = JSON.stringify(result) |
|
26
|
if (isDefined(strResult)) { |
|
27
|
return JSON.parse(strResult) |
|
28
|
} |
|
29
|
return undefined |
|
30
|
} |
|
31
|
|
|
32
|
const copy: any = {} |
|
33
|
for (const key in result) { |
|
34
|
if (result.hasOwnProperty(key)) { |
|
35
|
const value = (result as any)[key] |
|
36
|
|
|
37
|
if (typeof value === "function" || typeof value === "symbol") { |
|
38
|
continue |
|
39
|
} |
|
40
|
|
|
41
|
const copiedValue = parseStringifyIfNecessary(value) |
|
42
|
|
|
43
|
if (copiedValue !== undefined) { |
|
44
|
copy[key] = copiedValue |
|
45
|
} |
|
46
|
} |
|
47
|
} |
|
48
|
return copy |
|
49
|
} |