( value: unknown, seen?: Set<unknown> | undefined )
| 2174 | * @since 4.2.0 |
| 2175 | */ |
| 2176 | export const structural = ( |
| 2177 | value: unknown, |
| 2178 | seen?: Set<unknown> | undefined |
| 2179 | ): Schema.Json => { |
| 2180 | switch (typeof value) { |
| 2181 | case "string": |
| 2182 | case "boolean": |
| 2183 | return value |
| 2184 | case "number": |
| 2185 | return Number.isFinite(value) ? value : { "~unserialisable": "number" } |
| 2186 | case "undefined": |
| 2187 | return null |
| 2188 | case "bigint": |
| 2189 | case "symbol": |
| 2190 | case "function": |
| 2191 | return { "~unserialisable": typeof value } |
| 2192 | } |
| 2193 | if (value === null) return null |
| 2194 | if (Redacted.isRedacted(value)) return { "~redacted": true } |
| 2195 | if (seen?.has(value)) return { "~unserialisable": "cycle" } |
| 2196 | if (value instanceof Date) { |
| 2197 | return Number.isNaN(value.getTime()) |
| 2198 | ? { "~unserialisable": "Date" } |
| 2199 | : value.toISOString() |
| 2200 | } |
| 2201 | const visited = seen ?? new Set() |
| 2202 | visited.add(value) |
| 2203 | try { |
| 2204 | if (value instanceof Error) { |
| 2205 | return { |
| 2206 | name: guarded(() => structural(value.name, visited)), |
| 2207 | message: guarded(() => structural(value.message, visited)) |
| 2208 | } |
| 2209 | } |
| 2210 | if (Array.isArray(value)) return value.map((item) => structural(item, visited)) |
| 2211 | const proto = Object.getPrototypeOf(value as object) |
| 2212 | if (proto !== Object.prototype && proto !== null) { |
| 2213 | if (typeof (value as any).toJSON === "function") { |
| 2214 | return structural((value as any).toJSON(), visited) |
| 2215 | } |
| 2216 | if ( |
| 2217 | value instanceof Map || value instanceof Set || |
| 2218 | ArrayBuffer.isView(value) |
| 2219 | ) { |
| 2220 | return { "~unserialisable": value.constructor.name } |
| 2221 | } |
| 2222 | } |
| 2223 | // Preserve `__proto__` as an own property. |
| 2224 | return Object.fromEntries( |
| 2225 | Object.keys(value as object).map((key) => [key, guarded(() => structural((value as any)[key], visited))]) |
| 2226 | ) |
| 2227 | } catch { |
| 2228 | return failed |
| 2229 | } finally { |
| 2230 | visited.delete(value) |
| 2231 | } |
| 2232 | } |
| 2233 |
no test coverage detected