@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.
@@ -0,0 +1,666 @@
1
+ /**
2
+ * Lazily scanned view of one JSON object's top-level fields, built from text
3
+ * that may still be streaming or from an already parsed object. Nothing is
4
+ * scanned until a reader asks; the view remembers every question it answered
5
+ * and reports changed answers when the owner refreshes for publication.
6
+ * Used for model tool-call arguments: a row reads the fields it
7
+ * cares about at whatever granularity it displays, at every stage of the call.
8
+ * @module @xharness/util-values/src/partial-json
9
+ */
10
+ import { assertNever, type JsonValue } from './index.ts'
11
+
12
+ /** Granularity of a length read; a change is reported only when the rounded-up step moves. */
13
+ export interface LengthReadOptions {
14
+ /** Characters per step; defaults to 1 (every character counts). */
15
+ readonly step?: number
16
+ /** Completed characters included in the displayed total; affects change detection only. */
17
+ readonly offset?: number
18
+ }
19
+
20
+ /** Scanner position inside the object text. */
21
+ type Mode =
22
+ | 'root' | 'key-or-end' | 'key-only' | 'key' | 'colon' | 'value'
23
+ | 'string' | 'scalar' | 'nested' | 'comma-or-end' | 'closed' | 'invalid'
24
+
25
+ /** A content reader advances independently of the boundary scanner. */
26
+ interface StringRead {
27
+ at: number
28
+ length: number
29
+ text: string
30
+ }
31
+
32
+ /** Raw ranges exclude string quotes and include a non-string value's own brackets. */
33
+ type Entry =
34
+ | {
35
+ readonly kind: 'string'
36
+ readonly start: number
37
+ end: number
38
+ needsDecoding: boolean
39
+ invalidAt: number | undefined
40
+ length: StringRead | undefined
41
+ text: StringRead | undefined
42
+ prefixes: Map<number, StringRead> | undefined
43
+ }
44
+ | { readonly kind: 'value'; readonly start: number; end: number; parsed: JsonValue | undefined; invalid: boolean }
45
+
46
+ type ReadKind = 'closed' | 'keys' | 'has' | 'complete' | 'text' | 'value'
47
+ | `length:${number}:${number}` | `prefix:${number}` | `exceeds:${number}`
48
+
49
+ /** One answered question, kept to detect whether later text changes the answer. */
50
+ interface Read {
51
+ readonly completion: boolean
52
+ readonly answer: () => unknown
53
+ last: unknown
54
+ }
55
+
56
+ const SIMPLE_ESCAPES: Readonly<Record<string, string>> = {
57
+ '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t',
58
+ }
59
+
60
+ const CONTENT_ESCAPE = /[\\\u0000-\u001f]/u
61
+
62
+ function isWhitespace(c: string): boolean {
63
+ return c === ' ' || c === '\n' || c === '\r' || c === '\t'
64
+ }
65
+
66
+ function isHex(c: string): boolean {
67
+ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
68
+ }
69
+
70
+ /**
71
+ * The view. A streaming instance grows through {@link PartialArguments.append};
72
+ * {@link PartialArguments.fromText} and {@link PartialArguments.fromObject} build
73
+ * sealed instances over a finished call. Every reader is total: an absent or
74
+ * differently typed field answers `undefined` (or `false`), never throws.
75
+ */
76
+ export class PartialArguments {
77
+ /** The view of a call with no arguments available. */
78
+ static readonly EMPTY: PartialArguments = PartialArguments.fromObject({})
79
+
80
+ /**
81
+ * View finished argument text without scanning it until a reader asks.
82
+ * @param text - the complete argument JSON text.
83
+ * @returns a sealed view.
84
+ */
85
+ static fromText(text: string): PartialArguments {
86
+ const view = new PartialArguments()
87
+ view.append(text)
88
+ view.sealed = true
89
+ return view
90
+ }
91
+
92
+ /**
93
+ * View an already parsed argument payload, such as a PTC dispatch object.
94
+ * @param value - the parsed argument value.
95
+ * @returns a sealed view; a non-object payload has no fields.
96
+ */
97
+ static fromObject(value: unknown): PartialArguments {
98
+ const view = new PartialArguments()
99
+ view.object = typeof value === 'object' && value !== null && !Array.isArray(value)
100
+ ? value as Readonly<Record<string, JsonValue>>
101
+ : {}
102
+ view.sealed = true
103
+ return view
104
+ }
105
+
106
+ /**
107
+ * The source: text so far or a parsed object, plus whether it can still grow.
108
+ * These are the only enumerable fields, so two views over the same source
109
+ * compare equal structurally however far each has been read.
110
+ */
111
+ private chunks: string[] = []
112
+ private object: Readonly<Record<string, JsonValue>> | undefined
113
+ private sealed = false
114
+ // Scan progress, located fields, and remembered reads are caches over the source.
115
+ #ends: number[] = []
116
+ #size = 0
117
+ #consumed = 0
118
+ #mode: Mode = 'root'
119
+ #escape = false
120
+ #keyStart = 0
121
+ #keyEscaped = false
122
+ #key = ''
123
+ #current: Entry | null = null
124
+ #nestedEnds: string[] = []
125
+ #nestedInString = false
126
+ #invalidAt: number | undefined
127
+ #invalidValue = false
128
+ readonly #entries = new Map<string, Entry>()
129
+ readonly #order: string[] = []
130
+ readonly #reads = new Map<string, Read>()
131
+
132
+ /** Whether this view rejects further appends; does not scan text or register reads. */
133
+ get isSealed(): boolean {
134
+ return this.sealed
135
+ }
136
+
137
+ /** Whether indexing or a content read found invalid JSON; unread value contents are not validated. */
138
+ get invalid(): boolean {
139
+ this.scan()
140
+ return this.#mode === 'invalid' || this.#invalidValue
141
+ }
142
+
143
+ /**
144
+ * Retain streamed argument text without scanning or comparing observed answers.
145
+ * @param fragment - the text following every fragment appended before.
146
+ */
147
+ append(fragment: string): void {
148
+ if (this.sealed) throw new Error('PartialArguments: cannot append to a sealed view')
149
+ if (fragment.length === 0) return
150
+ this.chunks.push(fragment)
151
+ this.#size += fragment.length
152
+ this.#ends.push(this.#size)
153
+ }
154
+
155
+ /**
156
+ * Reconcile a streamed prefix with authoritative complete text without joining the fragments.
157
+ * @param text - the final argument text, which replaces missing or conflicting deltas.
158
+ * @returns this view sealed with its caches retained when every character matches; otherwise a new sealed view.
159
+ */
160
+ settle(text: string): PartialArguments {
161
+ if (this.object !== undefined || text.length !== this.#size) return PartialArguments.fromText(text)
162
+ let offset = 0
163
+ for (const chunk of this.chunks) {
164
+ if (!text.startsWith(chunk, offset)) return PartialArguments.fromText(text)
165
+ offset += chunk.length
166
+ }
167
+ this.chunks = text.length === 0 ? [] : [text]
168
+ this.#ends = text.length === 0 ? [] : [text.length]
169
+ this.sealed = true
170
+ return this
171
+ }
172
+
173
+ /**
174
+ * Compare observed answers and advance their publication baseline. Unread views remain unscanned.
175
+ * @returns whether any observed answer changed since its first read or the preceding refresh.
176
+ */
177
+ refresh(): boolean {
178
+ if (this.#reads.size === 0) return false
179
+ this.scan()
180
+ let changed = false
181
+ let completions = false
182
+ for (const read of this.#reads.values()) {
183
+ if (read.completion) {
184
+ completions = true
185
+ continue
186
+ }
187
+ changed = this.refreshRead(read) || changed
188
+ }
189
+ // Content reads can discover errors that change a field's completion answer.
190
+ if (completions) {
191
+ for (const read of this.#reads.values()) if (read.completion) changed = this.refreshRead(read) || changed
192
+ }
193
+ if (this.sealed) this.#reads.clear()
194
+ return changed
195
+ }
196
+
197
+ private refreshRead(read: Read): boolean {
198
+ const now = read.answer()
199
+ if (Object.is(now, read.last)) return false
200
+ read.last = now
201
+ return true
202
+ }
203
+
204
+ /**
205
+ * Check whether no further fields can arrive.
206
+ * @returns whether the outer object closed, indexing failed, or the view is sealed; unread values are not validated.
207
+ */
208
+ closed(): boolean {
209
+ return this.remember('closed', '', () => this.closedNow())
210
+ }
211
+
212
+ /**
213
+ * List discovered fields in first-appearance order.
214
+ * @returns top-level keys seen so far, in first-appearance order.
215
+ */
216
+ keys(): readonly string[] {
217
+ return this.remember('keys', '', () => this.keysNow(), keys => keys.length)
218
+ }
219
+
220
+ /**
221
+ * Check whether a top-level field has appeared.
222
+ * @param key - argument name.
223
+ * @returns whether the field has appeared (a string opened or another value began).
224
+ */
225
+ has(key: string): boolean {
226
+ return this.remember('has', key, () => this.hasNow(key))
227
+ }
228
+
229
+ /**
230
+ * Check whether a field's closing delimiter has arrived, without validating its contents.
231
+ * @param key - argument name.
232
+ * @returns whether its delimiter arrived and no content reader has reported an error for this value.
233
+ */
234
+ complete(key: string): boolean {
235
+ return this.remember('complete', key, () => this.completeNow(key))
236
+ }
237
+
238
+ /**
239
+ * Read string length without materializing its text.
240
+ * @param key - argument name.
241
+ * @param options - change granularity for a streaming string.
242
+ * @returns decoded UTF-16 length of the string field so far; undefined when absent or not a string.
243
+ */
244
+ stringLength(key: string, options?: LengthReadOptions): number | undefined {
245
+ const step = Math.max(1, Math.floor(options?.step ?? 1))
246
+ const offset = options?.offset ?? 0
247
+ return this.remember(`length:${step}:${offset}`, key, () => this.lengthNow(key),
248
+ length => length === undefined ? undefined : Math.ceil((length + offset) / step))
249
+ }
250
+
251
+ /**
252
+ * Check a string against a decoded UTF-16 length limit without materializing it.
253
+ * @param key - argument name.
254
+ * @param maxLength - decoded UTF-16 limit, floored to at least zero.
255
+ * @returns whether the string is longer than the limit; false when absent or not a string.
256
+ */
257
+ stringExceeds(key: string, maxLength: number): boolean {
258
+ const limit = Math.max(0, Math.floor(maxLength))
259
+ return this.remember(`exceeds:${limit}`, key,
260
+ () => (this.lengthNow(key, limit + 1) ?? 0) > limit)
261
+ }
262
+
263
+ /**
264
+ * Read a decoded string, including a streaming prefix.
265
+ * @param key - argument name.
266
+ * @returns the string field's decoded text so far; undefined when absent or not a string.
267
+ */
268
+ text(key: string): string | undefined {
269
+ return this.remember('text', key, () => this.textNow(key))
270
+ }
271
+
272
+ /**
273
+ * Read at most the first decoded UTF-16 units of a string.
274
+ * @param key - argument name.
275
+ * @param maxLength - maximum decoded UTF-16 length, floored to at least one.
276
+ * @returns the bounded string prefix; undefined when absent or not a string.
277
+ */
278
+ textPrefix(key: string, maxLength: number): string | undefined {
279
+ const limit = Math.max(1, Math.floor(maxLength))
280
+ return this.remember(`prefix:${limit}`, key,
281
+ () => this.textPrefixNow(key, limit))
282
+ }
283
+
284
+ /**
285
+ * Read a completed non-string argument.
286
+ * @param key - argument name.
287
+ * @returns the parsed non-string value once it closed; undefined while open, absent, or a string.
288
+ */
289
+ value(key: string): JsonValue | undefined {
290
+ return this.remember('value', key, () => this.valueNow(key))
291
+ }
292
+
293
+ /** Answer a question and, on a streaming view, remember it for change detection. */
294
+ private remember<T>(
295
+ kind: ReadKind,
296
+ key: string,
297
+ read: () => T,
298
+ comparison?: (value: T) => unknown,
299
+ ): T {
300
+ this.scan()
301
+ const result = read()
302
+ if (!this.sealed) {
303
+ const id = `${kind}/${key}`
304
+ if (!this.#reads.has(id)) {
305
+ this.#reads.set(id, {
306
+ completion: kind === 'complete',
307
+ answer: comparison === undefined ? read : () => comparison(read()),
308
+ last: comparison === undefined ? result : comparison(result),
309
+ })
310
+ }
311
+ }
312
+ return result
313
+ }
314
+
315
+ private closedNow(): boolean {
316
+ return this.sealed || this.#mode === 'closed' || this.#mode === 'invalid'
317
+ }
318
+
319
+ private keysNow(): readonly string[] {
320
+ return this.object === undefined ? this.#order : Object.keys(this.object)
321
+ }
322
+
323
+ private hasNow(key: string): boolean {
324
+ return this.object === undefined ? this.#entries.has(key) : Object.hasOwn(this.object, key)
325
+ }
326
+
327
+ private completeNow(key: string): boolean {
328
+ if (this.object !== undefined) return Object.hasOwn(this.object, key)
329
+ const entry = this.#entries.get(key)
330
+ return entry !== undefined && entry.end >= 0
331
+ && (entry.kind === 'string' ? entry.invalidAt === undefined : !entry.invalid)
332
+ }
333
+
334
+ private lengthNow(key: string, limit = Number.POSITIVE_INFINITY): number | undefined {
335
+ if (this.object !== undefined) {
336
+ const field = Object.hasOwn(this.object, key) ? this.object[key] : undefined
337
+ return typeof field === 'string' ? field.length : undefined
338
+ }
339
+ const entry = this.#entries.get(key)
340
+ if (entry?.kind !== 'string') return undefined
341
+ if (entry.text !== undefined && entry.text.at === entry.end) return entry.text.length
342
+ const read = entry.length ??= { at: entry.start, length: 0, text: '' }
343
+ this.readString(entry, read, limit, false)
344
+ return read.length
345
+ }
346
+
347
+ private textNow(key: string): string | undefined {
348
+ if (this.object !== undefined) {
349
+ const field = Object.hasOwn(this.object, key) ? this.object[key] : undefined
350
+ return typeof field === 'string' ? field : undefined
351
+ }
352
+ const entry = this.#entries.get(key)
353
+ if (entry?.kind !== 'string') return undefined
354
+ if (entry.text === undefined && entry.end >= 0 && entry.needsDecoding && entry.invalidAt === undefined) {
355
+ let text: string | undefined
356
+ try {
357
+ text = JSON.parse(`"${this.slice(entry.start, entry.end)}"`) as string
358
+ } catch (_error) {
359
+ // The incremental reader retains the valid prefix when complete text contains an invalid escape.
360
+ }
361
+ if (text !== undefined) entry.text = { at: entry.end, length: text.length, text }
362
+ }
363
+ const read = entry.text ??= { at: entry.start, length: 0, text: '' }
364
+ this.readString(entry, read, Number.POSITIVE_INFINITY, true)
365
+ return read.text
366
+ }
367
+
368
+ private textPrefixNow(key: string, maxLength: number): string | undefined {
369
+ if (this.object !== undefined) {
370
+ const field = Object.hasOwn(this.object, key) ? this.object[key] : undefined
371
+ return typeof field === 'string' ? field.slice(0, maxLength) : undefined
372
+ }
373
+ const entry = this.#entries.get(key)
374
+ if (entry?.kind !== 'string') return undefined
375
+ const prefixes = entry.prefixes ??= new Map<number, StringRead>()
376
+ let read = prefixes.get(maxLength)
377
+ if (read === undefined) {
378
+ read = { at: entry.start, length: 0, text: '' }
379
+ prefixes.set(maxLength, read)
380
+ }
381
+ this.readString(entry, read, maxLength, true)
382
+ return read.text
383
+ }
384
+
385
+ private valueNow(key: string): JsonValue | undefined {
386
+ if (this.object !== undefined) {
387
+ if (!Object.hasOwn(this.object, key)) return undefined
388
+ const field = this.object[key]
389
+ return typeof field === 'string' ? undefined : field
390
+ }
391
+ const entry = this.#entries.get(key)
392
+ if (entry?.kind !== 'value' || entry.end < 0 || entry.invalid) return undefined
393
+ if (entry.parsed === undefined) {
394
+ try {
395
+ entry.parsed = JSON.parse(this.slice(entry.start, entry.end)) as JsonValue
396
+ } catch (_error) {
397
+ // Unread values retain only their ranges; a requested malformed value has no parsed result.
398
+ entry.invalid = true
399
+ this.#invalidValue = true
400
+ }
401
+ }
402
+ return entry.parsed
403
+ }
404
+
405
+ private chunkAt(at: number): number {
406
+ let low = 0
407
+ let high = this.#ends.length
408
+ while (low < high) {
409
+ const mid = (low + high) >>> 1
410
+ if ((this.#ends[mid] as number) <= at) low = mid + 1
411
+ else high = mid
412
+ }
413
+ return low
414
+ }
415
+
416
+ /** Materialize only a requested range, never the cumulative source. */
417
+ private slice(start: number, end: number): string {
418
+ if (start >= end) return ''
419
+ const first = this.chunkAt(start)
420
+ const last = this.chunkAt(end - 1)
421
+ const base = first === 0 ? 0 : this.#ends[first - 1] as number
422
+ if (first === last) return (this.chunks[first] as string).slice(start - base, end - base)
423
+ const parts = [(this.chunks[first] as string).slice(start - base)]
424
+ for (let i = first + 1; i < last; i++) parts.push(this.chunks[i] as string)
425
+ parts.push((this.chunks[last] as string).slice(0, end - (this.#ends[last - 1] as number)))
426
+ return parts.join('')
427
+ }
428
+
429
+ private readString(
430
+ entry: Extract<Entry, { kind: 'string' }>,
431
+ read: StringRead,
432
+ limit: number,
433
+ materialize: boolean,
434
+ ): void {
435
+ const end = Math.min(entry.end < 0 ? this.#consumed : entry.end,
436
+ entry.invalidAt ?? Number.POSITIVE_INFINITY, this.#invalidAt ?? Number.POSITIVE_INFINITY)
437
+ if (!entry.needsDecoding) {
438
+ const length = Math.min(end - read.at, limit - read.length)
439
+ if (length <= 0) return
440
+ if (materialize) read.text += this.slice(read.at, read.at + length)
441
+ read.at += length
442
+ read.length += length
443
+ return
444
+ }
445
+ let chunkIndex = this.chunkAt(read.at)
446
+ while (read.at < end && read.length < limit) {
447
+ const base = chunkIndex === 0 ? 0 : this.#ends[chunkIndex - 1] as number
448
+ const chunk = this.chunks[chunkIndex] as string
449
+ const remaining = chunk.slice(read.at - base, Math.min(chunk.length, end - base))
450
+ const boundary = remaining.search(CONTENT_ESCAPE)
451
+ const length = Math.min(boundary < 0 ? remaining.length : boundary, limit - read.length)
452
+ if (length > 0) {
453
+ if (materialize) read.text += remaining.slice(0, length)
454
+ read.at += length
455
+ read.length += length
456
+ if (read.at === base + chunk.length) chunkIndex++
457
+ continue
458
+ }
459
+ const type = remaining.length > 1 ? remaining[1]
460
+ : read.at + 1 < end ? (this.chunks[chunkIndex + 1] as string)[0] : undefined
461
+ let decoded: string | undefined
462
+ let width = 2
463
+ if (remaining[0] === '\\' && type === undefined && entry.end < 0) return
464
+ if (remaining[0] === '\\' && type === 'u') {
465
+ const hex = this.slice(read.at + 2, Math.min(end, read.at + 6))
466
+ let valid = true
467
+ for (let i = 0; i < hex.length; i++) if (!isHex(hex[i] as string)) valid = false
468
+ if (valid) {
469
+ if (hex.length < 4 && entry.end < 0) return
470
+ if (hex.length === 4) decoded = String.fromCharCode(Number.parseInt(hex, 16))
471
+ }
472
+ width = 6
473
+ } else if (remaining[0] === '\\' && type !== undefined) {
474
+ decoded = SIMPLE_ESCAPES[type]
475
+ }
476
+ if (decoded === undefined) {
477
+ entry.invalidAt = read.at
478
+ this.#invalidValue = true
479
+ return
480
+ }
481
+ if (materialize) read.text += decoded
482
+ read.length++
483
+ read.at += width
484
+ while (chunkIndex < this.chunks.length && read.at >= (this.#ends[chunkIndex] as number)) chunkIndex++
485
+ }
486
+ }
487
+
488
+ /** Locate new field ranges without decoding or parsing their contents. */
489
+ private scan(): void {
490
+ if (this.object !== undefined || this.#consumed === this.#size) return
491
+ for (let i = this.chunkAt(this.#consumed); i < this.chunks.length && this.#invalidAt === undefined; i++) {
492
+ const pending = this.chunks[i] as string
493
+ const base = i === 0 ? 0 : this.#ends[i - 1] as number
494
+ for (let index = this.#consumed - base; index < pending.length && this.#mode !== 'invalid'; index++) {
495
+ if (this.#mode === 'string' || (this.#mode === 'nested' && this.#nestedInString)) {
496
+ const end = this.stringBoundary(pending, index)
497
+ this.#consumed += end - index
498
+ index = end
499
+ if (index === pending.length) break
500
+ }
501
+ this.step(pending[index] as string, this.#consumed)
502
+ this.#consumed++
503
+ }
504
+ }
505
+ }
506
+
507
+ /** Only raw quotes and their preceding backslash runs can terminate a string. */
508
+ private stringBoundary(fragment: string, start: number): number {
509
+ let at = start
510
+ while (true) {
511
+ const quote = fragment.indexOf('"', at)
512
+ const end = quote < 0 ? fragment.length : quote
513
+ if (this.#mode === 'string') {
514
+ const entry = this.#current as Extract<Entry, { kind: 'string' }>
515
+ if (!entry.needsDecoding && CONTENT_ESCAPE.test(fragment.slice(at, end))) entry.needsDecoding = true
516
+ }
517
+ let slashStart = end
518
+ while (slashStart > at && fragment[slashStart - 1] === '\\') slashStart--
519
+ const escaped = ((end - slashStart) % 2 === 1) !== (slashStart === at && this.#escape)
520
+ this.#escape = quote < 0 && escaped
521
+ if (quote < 0 || !escaped) return end
522
+ at = quote + 1
523
+ }
524
+ }
525
+
526
+ private step(c: string, at: number): void {
527
+ switch (this.#mode) {
528
+ case 'root':
529
+ if (isWhitespace(c)) return
530
+ if (c === '{') { this.#mode = 'key-or-end'; return }
531
+ this.fail(); return
532
+ case 'key-or-end':
533
+ if (isWhitespace(c)) return
534
+ if (c === '}') { this.#mode = 'closed'; return }
535
+ if (c === '"') { this.beginKey(at); return }
536
+ this.fail(); return
537
+ case 'key-only':
538
+ if (isWhitespace(c)) return
539
+ if (c === '"') { this.beginKey(at); return }
540
+ this.fail(); return
541
+ case 'key':
542
+ this.stepKey(c, at); return
543
+ case 'colon':
544
+ if (isWhitespace(c)) return
545
+ if (c === ':') { this.#mode = 'value'; return }
546
+ this.fail(); return
547
+ case 'value':
548
+ this.beginValue(c, at); return
549
+ case 'string': {
550
+ const entry = this.#current as Extract<Entry, { kind: 'string' }>
551
+ entry.end = at
552
+ this.#current = null
553
+ this.#mode = 'comma-or-end'
554
+ return
555
+ }
556
+ case 'scalar':
557
+ this.stepScalar(c, at); return
558
+ case 'nested':
559
+ this.stepNested(c, at); return
560
+ case 'comma-or-end':
561
+ if (isWhitespace(c)) return
562
+ if (c === ',') { this.#mode = 'key-only'; return }
563
+ if (c === '}') { this.#mode = 'closed'; return }
564
+ this.fail(); return
565
+ case 'closed':
566
+ if (isWhitespace(c)) return
567
+ this.fail(); return
568
+ /* v8 ignore next 2 -- scan() stops stepping once the view is invalid. */
569
+ case 'invalid':
570
+ return
571
+ /* v8 ignore next 2 -- Every scanner mode has a handler above. */
572
+ default:
573
+ assertNever(this.#mode)
574
+ }
575
+ }
576
+
577
+ private fail(): void {
578
+ this.#invalidAt = this.#consumed
579
+ this.#mode = 'invalid'
580
+ this.#current = null
581
+ }
582
+
583
+ private beginKey(at: number): void {
584
+ this.#mode = 'key'
585
+ this.#keyStart = at + 1
586
+ this.#keyEscaped = false
587
+ this.#escape = false
588
+ }
589
+
590
+ private stepKey(c: string, at: number): void {
591
+ if (c < ' ') { this.fail(); return }
592
+ if (this.#escape) { this.#escape = false; return }
593
+ if (c === '\\') { this.#escape = true; this.#keyEscaped = true; return }
594
+ if (c !== '"') return
595
+ const raw = this.slice(this.#keyStart, at)
596
+ if (this.#keyEscaped) {
597
+ try {
598
+ this.#key = JSON.parse(`"${raw}"`) as string
599
+ } catch (_error) {
600
+ // Invalid key escapes prevent identifying subsequent fields.
601
+ this.fail()
602
+ return
603
+ }
604
+ } else {
605
+ this.#key = raw
606
+ }
607
+ this.#mode = 'colon'
608
+ }
609
+
610
+ private open(entry: Entry): void {
611
+ if (!this.#entries.has(this.#key)) this.#order.push(this.#key)
612
+ this.#entries.set(this.#key, entry)
613
+ this.#current = entry
614
+ }
615
+
616
+ private beginValue(c: string, at: number): void {
617
+ if (isWhitespace(c)) return
618
+ if (c === '"') {
619
+ this.open({
620
+ kind: 'string', start: at + 1, end: -1, needsDecoding: false, invalidAt: undefined,
621
+ length: undefined, text: undefined, prefixes: undefined,
622
+ })
623
+ this.#escape = false
624
+ this.#mode = 'string'
625
+ return
626
+ }
627
+ if (c === '}' || c === ',' || c === ':' || c === ']') { this.fail(); return }
628
+ this.open({ kind: 'value', start: at, end: -1, parsed: undefined, invalid: false })
629
+ if (c === '{' || c === '[') {
630
+ this.#mode = 'nested'
631
+ this.#nestedEnds = [c === '{' ? '}' : ']']
632
+ this.#nestedInString = false
633
+ this.#escape = false
634
+ return
635
+ }
636
+ this.#mode = 'scalar'
637
+ }
638
+
639
+ private stepScalar(c: string, at: number): void {
640
+ if (c !== ',' && c !== '}' && !isWhitespace(c)) return
641
+ this.closeValue(at)
642
+ this.#mode = c === ',' ? 'key-only' : c === '}' ? 'closed' : 'comma-or-end'
643
+ }
644
+
645
+ private stepNested(c: string, at: number): void {
646
+ if (this.#nestedInString) {
647
+ this.#nestedInString = false
648
+ return
649
+ }
650
+ if (c === '"') { this.#nestedInString = true; return }
651
+ if (c === '{' || c === '[') { this.#nestedEnds.push(c === '{' ? '}' : ']'); return }
652
+ if (c === '}' || c === ']') {
653
+ if (this.#nestedEnds.pop() !== c) { this.fail(); return }
654
+ if (this.#nestedEnds.length === 0) {
655
+ this.closeValue(at + 1)
656
+ this.#mode = 'comma-or-end'
657
+ }
658
+ }
659
+ }
660
+
661
+ private closeValue(end: number): void {
662
+ const entry = this.#current as Extract<Entry, { kind: 'value' }>
663
+ entry.end = end
664
+ this.#current = null
665
+ }
666
+ }