@xharness/util-values 0.0.0-stage → 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,309 @@
1
+ /** Duplicate-install-safe JSON and immutable-value helpers. @module @xharness/util-values */
2
+
3
+ /** A value that round-trips through JSON without loss. */
4
+ export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
5
+
6
+ /**
7
+ * Mark an unreachable closed-union branch.
8
+ * @param value - impossible value; an unhandled typed variant fails at the call site.
9
+ * @param context - optional switch-site label included in the failure message.
10
+ * @returns never; a runtime value that escaped its type always throws.
11
+ */
12
+ export function assertNever(value: never, context?: string): never {
13
+ const rendered = (JSON.stringify(value) as string | undefined) ?? String(value)
14
+ throw new Error(`unreachable variant${context ? ` in ${context}` : ''}: ${rendered}`)
15
+ }
16
+
17
+ /** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */
18
+ function hasIntrinsicConstructor(prototype: object, name: 'Array' | 'Object'): boolean {
19
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, 'constructor')
20
+ const constructor: unknown = descriptor?.value
21
+ if (typeof constructor !== 'function') return false
22
+ try {
23
+ return constructor.name === name
24
+ && constructor.prototype === prototype
25
+ && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === 'Array' ? Array : Object)
26
+ } catch {
27
+ return false
28
+ }
29
+ }
30
+
31
+ /** Whether a candidate is this or another realm's intrinsic `Object.prototype`. */
32
+ function isIntrinsicObjectPrototype(value: object): boolean {
33
+ return value === Object.prototype
34
+ || Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, 'Object')
35
+ }
36
+
37
+ /** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */
38
+ function hasPlainArrayPrototype(value: unknown[]): boolean {
39
+ const prototype: unknown = Object.getPrototypeOf(value)
40
+ if (prototype === Array.prototype) return true
41
+ if (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, 'Array')) return false
42
+ const objectPrototype: unknown = Object.getPrototypeOf(prototype)
43
+ return typeof objectPrototype === 'object'
44
+ && objectPrototype !== null
45
+ && isIntrinsicObjectPrototype(objectPrototype)
46
+ }
47
+
48
+ /** Whether an object is a plain or null-prototype record from any JavaScript realm. */
49
+ function hasPlainObjectPrototype(value: object): boolean {
50
+ const prototype: unknown = Object.getPrototypeOf(value)
51
+ return prototype === null
52
+ || typeof prototype === 'object' && isIntrinsicObjectPrototype(prototype)
53
+ }
54
+
55
+ /**
56
+ * Test whether a value is a plain array or record from any JavaScript realm, such as an iframe:
57
+ * an array whose prototype is a realm's intrinsic `Array.prototype`, which inherits that realm's
58
+ * `Object.prototype`, or a non-array object whose prototype is `null` or a realm's intrinsic
59
+ * `Object.prototype`. Class instances, built-in objects, and objects that inherit any other
60
+ * prototype, which could supply `toJSON`, fail. Elements and property values are not inspected.
61
+ * @param value - candidate value from any realm.
62
+ * @returns whether the value is a plain array or a plain or null-prototype record.
63
+ */
64
+ export function hasPlainPrototype(value: unknown): value is unknown[] | Record<string, unknown> {
65
+ if (typeof value !== 'object' || value === null) return false
66
+ return Array.isArray(value) ? hasPlainArrayPrototype(value) : hasPlainObjectPrototype(value)
67
+ }
68
+
69
+ /** Return every JSON-visible object key, or reject own data JSON would discard. */
70
+ function enumerableStringKeys(value: object): string[] | undefined {
71
+ const keys = Reflect.ownKeys(value)
72
+ if (keys.some(key => typeof key !== 'string' || !Object.prototype.propertyIsEnumerable.call(value, key))) return undefined
73
+ return keys as string[]
74
+ }
75
+
76
+ /** One active container, with child reads in its captured key or index order. */
77
+ type JsonWalkFrame =
78
+ | { kind: 'array'; source: unknown[]; length: number; index: number; key: number; indices: number[] | undefined; target: JsonValue[] | undefined }
79
+ | { kind: 'object'; source: Record<string, unknown>; keys: string[]; index: number; key: string; target: { [key: string]: JsonValue } | undefined }
80
+
81
+ /** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */
82
+ function walkJsonValue(value: unknown, detach: boolean): JsonValue | true | undefined {
83
+ const ancestors = new Set<object>()
84
+ let root: JsonValue | undefined
85
+ let parent: JsonWalkFrame | undefined
86
+ const assign = (item: JsonValue): void => {
87
+ if (parent === undefined) {
88
+ if (detach) root = item
89
+ } else if (parent.kind === 'array') {
90
+ if (parent.target !== undefined) parent.target[parent.key] = item
91
+ } else if (parent.target !== undefined) {
92
+ Object.defineProperty(parent.target, parent.key, {
93
+ value: item,
94
+ enumerable: true,
95
+ configurable: true,
96
+ writable: true,
97
+ })
98
+ }
99
+ }
100
+
101
+ const frames: JsonWalkFrame[] = []
102
+ let current: unknown = value
103
+ for (;;) {
104
+ if (current === null) {
105
+ assign(null)
106
+ } else if (typeof current === 'boolean' || typeof current === 'string') {
107
+ assign(current)
108
+ } else if (typeof current === 'number') {
109
+ if (!Number.isFinite(current) || Object.is(current, -0)) return undefined
110
+ assign(current)
111
+ } else {
112
+ if (typeof current !== 'object') return undefined
113
+ if (ancestors.has(current)) return undefined
114
+ if (Array.isArray(current)) {
115
+ if (!hasPlainArrayPrototype(current)) return undefined
116
+ const length = current.length
117
+ if (Reflect.ownKeys(current).length !== length + 1) return undefined
118
+ const target = detach ? [] as JsonValue[] : undefined
119
+ if (target !== undefined) assign(target)
120
+ let indices: number[] | undefined
121
+ if (!Number.isInteger(length)) {
122
+ // Capture indices with one subtraction for fractional or coercible Proxy lengths.
123
+ indices = []
124
+ for (let index = length - 1; index >= 0; index--) indices.push(index)
125
+ }
126
+ frames.push({ kind: 'array', source: current, length: indices?.length ?? length, index: 0, key: 0, indices, target })
127
+ } else {
128
+ if (!hasPlainObjectPrototype(current)) return undefined
129
+ const keys = enumerableStringKeys(current)
130
+ if (keys === undefined) return undefined
131
+ const target = detach ? {} as { [key: string]: JsonValue } : undefined
132
+ if (target !== undefined) assign(target)
133
+ frames.push({ kind: 'object', source: current as Record<string, unknown>, keys, index: 0, key: '', target })
134
+ }
135
+ ancestors.add(current)
136
+ }
137
+
138
+ for (;;) {
139
+ const frame = frames.at(-1)
140
+ if (frame === undefined) return detach ? root : true
141
+ const length = frame.kind === 'array' ? frame.length : frame.keys.length
142
+ if (frame.index >= length) {
143
+ ancestors.delete(frame.source)
144
+ frames.pop()
145
+ continue
146
+ }
147
+ const index = frame.index++
148
+ parent = frame
149
+ if (frame.kind === 'array') {
150
+ const key = frame.indices === undefined ? index : frame.indices[frame.indices.length - index - 1]
151
+ /* v8 ignore next -- the loop is bounded by the captured index count. */
152
+ if (key === undefined) return undefined
153
+ if (!Object.prototype.hasOwnProperty.call(frame.source, key)) return undefined
154
+ frame.key = key
155
+ current = frame.source[key]
156
+ } else {
157
+ const key = frame.keys[index]
158
+ /* v8 ignore next -- the loop is bounded by the captured key count. */
159
+ if (key === undefined) return undefined
160
+ frame.key = key
161
+ current = frame.source[key]
162
+ }
163
+ break
164
+ }
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Validate and detach lossless JSON in one read per property.
170
+ * @param value - candidate value to validate and detach.
171
+ * @returns the detached snapshot, or `undefined` when the value is not losslessly JSON-serializable.
172
+ */
173
+ export function snapshotJsonValue<T>(value: T): T | undefined {
174
+ return walkJsonValue(value, true) as T | undefined
175
+ }
176
+
177
+ /**
178
+ * Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.
179
+ * @param value - candidate value to test.
180
+ * @returns whether the value survives a JSON round trip without loss.
181
+ */
182
+ export function isJsonValue(value: unknown): boolean {
183
+ return walkJsonValue(value, false) === true
184
+ }
185
+
186
+ /**
187
+ * Compare JSON-compatible values structurally.
188
+ * @param a - one JSON-compatible value.
189
+ * @param b - the other JSON-compatible value.
190
+ * @returns whether both values contain the same JSON data.
191
+ */
192
+ export function deepEqualJson(a: unknown, b: unknown): boolean {
193
+ if (a === b) return true
194
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false
195
+ if (Array.isArray(a) || Array.isArray(b)) {
196
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false
197
+ return a.every((entry, index) => deepEqualJson(entry, b[index]))
198
+ }
199
+ const left = a as Record<string, unknown>
200
+ const right = b as Record<string, unknown>
201
+ const keys = Object.keys(left)
202
+ if (keys.length !== Object.keys(right).length) return false
203
+ return keys.every(key => key in right && deepEqualJson(left[key], right[key]))
204
+ }
205
+
206
+ /**
207
+ * Deep-freeze an object graph in place while leaving live AbortSignal objects mutable.
208
+ * @param value - value to freeze.
209
+ * @returns the same value after every reachable enumerable child is frozen.
210
+ */
211
+ export function deepFreeze<T>(value: T): T {
212
+ const seen = new WeakSet<object>()
213
+ const pending: (
214
+ | { kind: 'visit'; node: unknown }
215
+ | { kind: 'property'; source: Record<string, unknown>; key: string }
216
+ )[] = [{ kind: 'visit', node: value }]
217
+ while (pending.length > 0) {
218
+ const task = pending.pop()
219
+ /* v8 ignore next -- the loop condition guarantees one pending task. */
220
+ if (task === undefined) continue
221
+ if (task.kind === 'property') {
222
+ pending.push({ kind: 'visit', node: task.source[task.key] })
223
+ continue
224
+ }
225
+ const node = task.node
226
+ if (node === null || typeof node !== 'object') continue
227
+ if (node instanceof AbortSignal) continue
228
+ if (seen.has(node)) continue
229
+ seen.add(node)
230
+ Object.freeze(node)
231
+ const keys = Object.keys(node)
232
+ for (let index = keys.length - 1; index >= 0; index--) {
233
+ const key = keys[index]
234
+ /* v8 ignore next -- the loop is bounded by the captured key count. */
235
+ if (key === undefined) continue
236
+ pending.push({ kind: 'property', source: node as Record<string, unknown>, key })
237
+ }
238
+ }
239
+ return value
240
+ }
241
+
242
+ /**
243
+ * Weak-key lookup with a strongly retained iterable set of associated values.
244
+ *
245
+ * Each value must belong to only one key. The container performs no automatic
246
+ * cleanup; owners delete associations or clear the container at lifecycle end.
247
+ */
248
+ export class WeakMapWithValues<Key extends object, Value> {
249
+ private keys = new WeakMap<Key, Value>()
250
+ private readonly valueSet = new Set<Value>()
251
+ /** Live strongly retained values in insertion order. */
252
+ readonly values: ReadonlySet<Value> = this.valueSet
253
+
254
+ /**
255
+ * Read the value associated with a key.
256
+ * @param key - weakly held lookup key.
257
+ * @returns the associated value, or absence.
258
+ */
259
+ get(key: Key): Value | undefined {
260
+ return this.keys.get(key)
261
+ }
262
+
263
+ /**
264
+ * Test whether a key has an association.
265
+ * @param key - weakly held lookup key.
266
+ * @returns whether the key is present.
267
+ */
268
+ has(key: Key): boolean {
269
+ return this.keys.has(key)
270
+ }
271
+
272
+ /**
273
+ * Associate one key with one caller-unique value.
274
+ * @param key - weakly held lookup key.
275
+ * @param value - strongly retained value that belongs to no other key.
276
+ * @returns this container.
277
+ */
278
+ set(key: Key, value: Value): this {
279
+ if (this.keys.has(key)) {
280
+ const previous = this.keys.get(key) as Value
281
+ if (previous === value) return this
282
+ this.valueSet.delete(previous)
283
+ }
284
+ this.keys.set(key, value)
285
+ this.valueSet.add(value)
286
+ return this
287
+ }
288
+
289
+ /**
290
+ * Remove one association and its strongly retained value.
291
+ * @param key - weakly held lookup key.
292
+ * @returns whether an association was removed.
293
+ */
294
+ delete(key: Key): boolean {
295
+ if (!this.keys.has(key)) return false
296
+ const value = this.keys.get(key) as Value
297
+ const deleted = this.keys.delete(key)
298
+ this.valueSet.delete(value)
299
+ return deleted
300
+ }
301
+
302
+ /** Remove every association and strongly retained value. */
303
+ clear(): void {
304
+ this.keys = new WeakMap()
305
+ this.valueSet.clear()
306
+ }
307
+ }
308
+
309
+ export { PartialArguments, type LengthReadOptions } from './partial-json.ts'