| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239 |
- /** Duplicate-install-safe JSON and immutable-value helpers. @module @deepseek-ai/dsh-util-values */
- /** A value that round-trips through JSON without loss. */
- export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
- /**
- * Mark an unreachable closed-union branch.
- * @param value - impossible value; an unhandled typed variant fails at the call site.
- * @param context - optional switch-site label included in the failure message.
- * @returns never; a runtime value that escaped its type always throws.
- */
- export function assertNever(value: never, context?: string): never {
- const rendered = (JSON.stringify(value) as string | undefined) ?? String(value)
- throw new Error(`unreachable variant${context ? ` in ${context}` : ''}: ${rendered}`)
- }
- /** Whether a realm-owned intrinsic prototype is backed by its native constructor. */
- function hasIntrinsicConstructor(prototype: object, name: 'Array' | 'Object'): boolean {
- const descriptor = Object.getOwnPropertyDescriptor(prototype, 'constructor')
- const constructor: unknown = descriptor?.value
- if (typeof constructor !== 'function') return false
- try {
- return constructor.name === name
- && constructor.prototype === prototype
- && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`
- } catch {
- return false
- }
- }
- /** Whether a candidate is one realm's intrinsic `Object.prototype`. */
- function isIntrinsicObjectPrototype(value: object): boolean {
- return Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, 'Object')
- }
- /** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */
- function hasPlainArrayPrototype(value: unknown[]): boolean {
- const prototype: unknown = Object.getPrototypeOf(value)
- if (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, 'Array')) return false
- const objectPrototype: unknown = Object.getPrototypeOf(prototype)
- return typeof objectPrototype === 'object'
- && objectPrototype !== null
- && isIntrinsicObjectPrototype(objectPrototype)
- }
- /** Whether an object is a plain or null-prototype record from any JavaScript realm. */
- function hasPlainObjectPrototype(value: object): boolean {
- const prototype: unknown = Object.getPrototypeOf(value)
- return prototype === null
- || typeof prototype === 'object' && isIntrinsicObjectPrototype(prototype)
- }
- /** Return every JSON-visible object key, or reject own data JSON would discard. */
- function enumerableStringKeys(value: object): string[] | undefined {
- const keys = Reflect.ownKeys(value)
- if (keys.some(key => typeof key !== 'string' || !Object.prototype.propertyIsEnumerable.call(value, key))) return undefined
- return keys as string[]
- }
- type SnapshotDestination =
- | { kind: 'root' }
- | { kind: 'array'; target: JsonValue[]; index: number }
- | { kind: 'object'; target: { [key: string]: JsonValue }; key: string }
- type JsonWalkTask =
- | { kind: 'visit'; value: unknown; destination?: SnapshotDestination }
- | { kind: 'array-item'; source: unknown[]; index: number; target?: JsonValue[] }
- | { kind: 'object-property'; source: Record<string, unknown>; key: string; target?: { [key: string]: JsonValue } }
- | { kind: 'leave'; source: object }
- /** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */
- function walkJsonValue(value: unknown, detach: boolean): JsonValue | true | undefined {
- const ancestors = new Set<object>()
- let root: JsonValue | undefined
- const assign = (destination: SnapshotDestination | undefined, item: JsonValue): void => {
- if (destination === undefined) return
- if (destination.kind === 'root') {
- root = item
- } else if (destination.kind === 'array') {
- destination.target[destination.index] = item
- } else {
- Object.defineProperty(destination.target, destination.key, {
- value: item,
- enumerable: true,
- configurable: true,
- writable: true,
- })
- }
- }
- const tasks: JsonWalkTask[] = [{
- kind: 'visit',
- value,
- ...(detach ? { destination: { kind: 'root' } as const } : {}),
- }]
- for (let task = tasks.pop(); task !== undefined; task = tasks.pop()) {
- if (task.kind === 'leave') {
- ancestors.delete(task.source)
- continue
- }
- if (task.kind === 'array-item') {
- if (!Object.prototype.hasOwnProperty.call(task.source, task.index)) return undefined
- tasks.push({
- kind: 'visit',
- value: task.source[task.index],
- ...(task.target === undefined ? {} : { destination: { kind: 'array', target: task.target, index: task.index } as const }),
- })
- continue
- }
- if (task.kind === 'object-property') {
- tasks.push({
- kind: 'visit',
- value: task.source[task.key],
- ...(task.target === undefined ? {} : { destination: { kind: 'object', target: task.target, key: task.key } as const }),
- })
- continue
- }
- const current = task.value
- if (current === null) {
- assign(task.destination, null)
- continue
- }
- if (typeof current === 'boolean' || typeof current === 'string') {
- assign(task.destination, current)
- continue
- }
- if (typeof current === 'number') {
- if (!Number.isFinite(current) || Object.is(current, -0)) return undefined
- assign(task.destination, current)
- continue
- }
- if (typeof current !== 'object') return undefined
- if (ancestors.has(current)) return undefined
- if (Array.isArray(current)) {
- if (!hasPlainArrayPrototype(current)) return undefined
- const length = current.length
- if (Reflect.ownKeys(current).length !== length + 1) return undefined
- const target = detach ? [] as JsonValue[] : undefined
- if (target !== undefined) assign(task.destination, target)
- ancestors.add(current)
- tasks.push({ kind: 'leave', source: current })
- for (let index = length - 1; index >= 0; index--) {
- tasks.push({ kind: 'array-item', source: current, index, ...(target === undefined ? {} : { target }) })
- }
- continue
- }
- if (!hasPlainObjectPrototype(current)) return undefined
- const keys = enumerableStringKeys(current)
- if (keys === undefined) return undefined
- const target = detach ? {} as { [key: string]: JsonValue } : undefined
- if (target !== undefined) assign(task.destination, target)
- ancestors.add(current)
- tasks.push({ kind: 'leave', source: current })
- for (let index = keys.length - 1; index >= 0; index--) {
- const key = keys[index]
- /* v8 ignore next -- the loop is bounded by the captured key count. */
- if (key === undefined) return undefined
- tasks.push({ kind: 'object-property', source: current as Record<string, unknown>, key, ...(target === undefined ? {} : { target }) })
- }
- }
- return detach ? root : true
- }
- /**
- * Validate and detach lossless JSON in one read per property.
- * @param value - candidate value to validate and detach.
- * @returns the detached snapshot, or `undefined` when the value is not losslessly JSON-serializable.
- */
- export function snapshotJsonValue<T>(value: T): T | undefined {
- return walkJsonValue(value, true) as T | undefined
- }
- /**
- * Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.
- * @param value - candidate value to test.
- * @returns whether the value survives a JSON round trip without loss.
- */
- export function isJsonValue(value: unknown): boolean {
- return walkJsonValue(value, false) === true
- }
- /**
- * Compare JSON-compatible values structurally.
- * @param a - one JSON-compatible value.
- * @param b - the other JSON-compatible value.
- * @returns whether both values contain the same JSON data.
- */
- export function deepEqualJson(a: unknown, b: unknown): boolean {
- if (a === b) return true
- if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false
- if (Array.isArray(a) || Array.isArray(b)) {
- if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false
- return a.every((entry, index) => deepEqualJson(entry, b[index]))
- }
- const left = a as Record<string, unknown>
- const right = b as Record<string, unknown>
- const keys = Object.keys(left)
- if (keys.length !== Object.keys(right).length) return false
- return keys.every(key => key in right && deepEqualJson(left[key], right[key]))
- }
- /**
- * Deep-freeze an object graph in place while leaving live AbortSignal objects mutable.
- * @param value - value to freeze.
- * @returns the same value after every reachable enumerable child is frozen.
- */
- export function deepFreeze<T>(value: T): T {
- const seen = new WeakSet<object>()
- const pending: (
- | { kind: 'visit'; node: unknown }
- | { kind: 'property'; source: Record<string, unknown>; key: string }
- )[] = [{ kind: 'visit', node: value }]
- while (pending.length > 0) {
- const task = pending.pop()
- /* v8 ignore next -- the loop condition guarantees one pending task. */
- if (task === undefined) continue
- if (task.kind === 'property') {
- pending.push({ kind: 'visit', node: task.source[task.key] })
- continue
- }
- const node = task.node
- if (node === null || typeof node !== 'object') continue
- if (node instanceof AbortSignal) continue
- if (seen.has(node)) continue
- seen.add(node)
- Object.freeze(node)
- const keys = Object.keys(node)
- for (let index = keys.length - 1; index >= 0; index--) {
- const key = keys[index]
- /* v8 ignore next -- the loop is bounded by the captured key count. */
- if (key === undefined) continue
- pending.push({ kind: 'property', source: node as Record<string, unknown>, key })
- }
- }
- return value
- }
|