(val: any, seen: WeakMap<WeakKey, any> = new WeakMap())
| 29 | |
| 30 | // https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm |
| 31 | export function serializeValue(val: any, seen: WeakMap<WeakKey, any> = new WeakMap()): any { |
| 32 | if (!val || typeof val === 'string') { |
| 33 | return val |
| 34 | } |
| 35 | if (val instanceof Error && 'toJSON' in val && typeof val.toJSON === 'function') { |
| 36 | const jsonValue = val.toJSON() |
| 37 | |
| 38 | if (jsonValue && jsonValue !== val && typeof jsonValue === 'object') { |
| 39 | if (typeof val.message === 'string') { |
| 40 | safe(() => jsonValue.message ??= normalizeErrorMessage(val.message)) |
| 41 | } |
| 42 | if (typeof val.stack === 'string') { |
| 43 | safe(() => jsonValue.stack ??= val.stack) |
| 44 | } |
| 45 | if (typeof val.name === 'string') { |
| 46 | safe(() => jsonValue.name ??= val.name) |
| 47 | } |
| 48 | if (val.cause != null) { |
| 49 | safe(() => jsonValue.cause ??= serializeValue(val.cause, seen)) |
| 50 | } |
| 51 | } |
| 52 | return serializeValue(jsonValue, seen) |
| 53 | } |
| 54 | if (typeof val === 'function') { |
| 55 | return `Function<${val.name || 'anonymous'}>` |
| 56 | } |
| 57 | if (typeof val === 'symbol') { |
| 58 | return val.toString() |
| 59 | } |
| 60 | if (typeof val !== 'object') { |
| 61 | return val |
| 62 | } |
| 63 | if (typeof Buffer !== 'undefined' && val instanceof Buffer) { |
| 64 | return `<Buffer(${val.length}) ...>` |
| 65 | } |
| 66 | if (typeof Uint8Array !== 'undefined' && val instanceof Uint8Array) { |
| 67 | return `<Uint8Array(${val.length}) ...>` |
| 68 | } |
| 69 | // cannot serialize immutables as immutables |
| 70 | if (isImmutable(val)) { |
| 71 | return serializeValue(val.toJSON(), seen) |
| 72 | } |
| 73 | if ( |
| 74 | val instanceof Promise |
| 75 | || (val.constructor && val.constructor.prototype === 'AsyncFunction') |
| 76 | ) { |
| 77 | return 'Promise' |
| 78 | } |
| 79 | if (typeof Element !== 'undefined' && val instanceof Element) { |
| 80 | return val.tagName |
| 81 | } |
| 82 | if (typeof val.toJSON === 'function') { |
| 83 | return serializeValue(val.toJSON(), seen) |
| 84 | } |
| 85 | |
| 86 | if (seen.has(val)) { |
| 87 | return seen.get(val) |
| 88 | } |
no test coverage detected