| 106 | // put, or undefined where arktype reads one other than to write a union, as |
| 107 | // what it writes would then depend on what a call's fallback returns |
| 108 | export const traceFallbacks = ( |
| 109 | root: BaseRoot, |
| 110 | write: ( |
| 111 | fallback: ToJsonSchema.UniversalFallback, |
| 112 | writers: UnionJsonSchemaWriters |
| 113 | ) => unknown, |
| 114 | // as arktype's error does, whose message is all that's kept |
| 115 | printsResults?: true |
| 116 | ): FallbackTrace | undefined => { |
| 117 | if (tooDeep.has(root) || root.references.some(isUnreplayable)) return |
| 118 | const objects: object[] = [] |
| 119 | const ids = new Map<object, number>() |
| 120 | const holes = new Map<object, number>() |
| 121 | const markers = new Map<string, number>() |
| 122 | const copies: number[] = [] |
| 123 | const steps: Step[] = [] |
| 124 | // writing a union, where any read of a result is one it replays |
| 125 | let isWritingUnion = false |
| 126 | |
| 127 | const refOf = (value: unknown): Ref => { |
| 128 | if (typeof value !== "object" || value === null) return { value } |
| 129 | const hole = holes.get(value) |
| 130 | if (hole !== undefined) return { hole } |
| 131 | let id = ids.get(value) |
| 132 | if (id === undefined) { |
| 133 | const prototype = prototypeOf(value) |
| 134 | if (prototype !== Object.prototype && prototype !== Array.prototype) |
| 135 | return { value } |
| 136 | if (Object.getOwnPropertySymbols(value).length) refuseReplay() |
| 137 | ids.set(value, (id = objects.length)) |
| 138 | objects.push(value) |
| 139 | } |
| 140 | return { object: id } |
| 141 | } |
| 142 | |
| 143 | const states: States = [] |
| 144 | const keysRead: string[][] = [] |
| 145 | const valuesRead: unknown[][] = [] |
| 146 | let reads = 0 |
| 147 | |
| 148 | // discovering objects as it reads them, so changes hold each reachable one |
| 149 | const changesSinceLastStep = (): Changes => { |
| 150 | const changes: Changes = [] |
| 151 | // its result is only printed where it stops arktype's write |
| 152 | if (printsResults) return changes |
| 153 | for (let id = 0; id < objects.length; id++) { |
| 154 | if (++reads > maxTracedReads) { |
| 155 | tooDeep.add(root) |
| 156 | refuseReplay() |
| 157 | } |
| 158 | const o = objects[id] as Record<string, unknown> |
| 159 | const keys = Object.keys(o) |
| 160 | if (isUnchanged(keys, o, keysRead[id], valuesRead[id])) continue |
| 161 | const values = keys.map(key => o[key]) |
| 162 | keysRead[id] = keys |
| 163 | valuesRead[id] = values |
| 164 | states[id] = keys.map((key, i) => { |
| 165 | const spread = markers.get(key) |