@ai-matrx/content-ir 0.8.0 → 0.10.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.
Files changed (45) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +24 -5
  3. package/dist/convert.cjs +1680 -0
  4. package/dist/convert.cjs.map +1 -0
  5. package/dist/convert.d.cts +230 -0
  6. package/dist/convert.d.ts +230 -0
  7. package/dist/convert.js +1666 -0
  8. package/dist/convert.js.map +1 -0
  9. package/dist/core.cjs +2493 -0
  10. package/dist/core.cjs.map +1 -0
  11. package/dist/core.d.cts +370 -0
  12. package/dist/core.d.ts +370 -0
  13. package/dist/core.js +2452 -0
  14. package/dist/core.js.map +1 -0
  15. package/dist/index.cjs +11 -1
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +9 -2030
  18. package/dist/index.d.ts +9 -2030
  19. package/dist/index.js +11 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/ir-tree-DbLVxbf1.d.cts +441 -0
  22. package/dist/ir-tree-Dsc_66ek.d.ts +441 -0
  23. package/dist/ir-types-95bA2cXH.d.cts +119 -0
  24. package/dist/ir-types-95bA2cXH.d.ts +119 -0
  25. package/dist/kind-schema.types-CwncWj9U.d.cts +139 -0
  26. package/dist/kind-schema.types-CwncWj9U.d.ts +139 -0
  27. package/dist/registry.cjs +468 -0
  28. package/dist/registry.cjs.map +1 -0
  29. package/dist/registry.d.cts +357 -0
  30. package/dist/registry.d.ts +357 -0
  31. package/dist/registry.js +456 -0
  32. package/dist/registry.js.map +1 -0
  33. package/dist/session.cjs +2052 -0
  34. package/dist/session.cjs.map +1 -0
  35. package/dist/session.d.cts +75 -0
  36. package/dist/session.d.ts +75 -0
  37. package/dist/session.js +2047 -0
  38. package/dist/session.js.map +1 -0
  39. package/dist/wire.cjs +310 -0
  40. package/dist/wire.cjs.map +1 -0
  41. package/dist/wire.d.cts +326 -0
  42. package/dist/wire.d.ts +326 -0
  43. package/dist/wire.js +291 -0
  44. package/dist/wire.js.map +1 -0
  45. package/package.json +73 -1
package/dist/core.cjs ADDED
@@ -0,0 +1,2493 @@
1
+ 'use strict';
2
+
3
+ // core/ir-types.ts
4
+ var IR_VERSION = 1;
5
+ var IR_ENVELOPE_KEY = "__ir";
6
+ function irPathKey(path) {
7
+ return path.map((segment) => String(segment)).join(".");
8
+ }
9
+ function irPathsEqual(left, right) {
10
+ if (left.length !== right.length) return false;
11
+ for (let i = 0; i < left.length; i++) {
12
+ if (left[i] !== right[i]) return false;
13
+ }
14
+ return true;
15
+ }
16
+ function irPathIsUnderOrEqual(path, prefix) {
17
+ if (path.length < prefix.length) return false;
18
+ for (let i = 0; i < prefix.length; i++) {
19
+ if (path[i] !== prefix[i]) return false;
20
+ }
21
+ return true;
22
+ }
23
+ function irPathLabel(path) {
24
+ if (path.length === 0) return "root";
25
+ const parts = [];
26
+ for (const segment of path) {
27
+ if (typeof segment === "number") {
28
+ parts[parts.length - 1] += `[${segment}]`;
29
+ } else {
30
+ parts.push(String(segment));
31
+ }
32
+ }
33
+ return parts.join(".");
34
+ }
35
+ function isEmptyResidue(residue) {
36
+ return (residue.extra === null || Object.keys(residue.extra).length === 0) && (residue.optionalMissing === null || residue.optionalMissing.length === 0) && (residue.notices === null || residue.notices.length === 0);
37
+ }
38
+
39
+ // core/kind-schema.types.ts
40
+ var KIND_KEY = "__kind";
41
+ function readObjectKind(value) {
42
+ const kind = value[KIND_KEY];
43
+ return typeof kind === "string" ? kind : null;
44
+ }
45
+ function isScalarArrayType(type) {
46
+ return type === "string[]" || type === "number[]" || type === "boolean[]";
47
+ }
48
+ function scalarArrayItemType(type) {
49
+ if (type === "number[]") return "number";
50
+ if (type === "boolean[]") return "boolean";
51
+ return "string";
52
+ }
53
+ function isJsonAnyField(field) {
54
+ return field.type === "json" || field.type === "json[]";
55
+ }
56
+
57
+ // core/discriminator.ts
58
+ var JSON_DISCRIMINATOR = {
59
+ format: "json",
60
+ key: KIND_KEY
61
+ };
62
+ function xmlDiscriminator(tag) {
63
+ return { format: "xml", tag };
64
+ }
65
+ function fenceDiscriminator(language) {
66
+ return { format: "fence", language };
67
+ }
68
+
69
+ // core/ir-tree.ts
70
+ function isRecord(value) {
71
+ return typeof value === "object" && value !== null && !Array.isArray(value);
72
+ }
73
+ function mergeWithoutLoss(prior, incoming) {
74
+ if (!isRecord(prior)) return { value: incoming, rescued: [] };
75
+ if (!isRecord(incoming)) {
76
+ if (incoming !== null && incoming !== void 0) {
77
+ return { value: incoming, rescued: [] };
78
+ }
79
+ return { value: prior, rescued: Object.keys(prior) };
80
+ }
81
+ const rescued = Object.keys(prior).filter((key) => !(key in incoming));
82
+ if (rescued.length === 0) return { value: incoming, rescued };
83
+ return { value: { ...prior, ...incoming }, rescued };
84
+ }
85
+ var IrTree = class {
86
+ nodes = /* @__PURE__ */ new Map();
87
+ rawPaths = /* @__PURE__ */ new Map();
88
+ // pathKey → reason
89
+ dirty = /* @__PURE__ */ new Set();
90
+ /**
91
+ * KIND PRESERVATION (streaming db/cloud kinds): pathKey → identified kind
92
+ * for nodes whose kind is KNOWN (kind_identified / pending_schema) but that
93
+ * have no snapshot node yet because the schema is still cold-fetching.
94
+ * Without this, the envelope reports `kind: ""` for the whole pending
95
+ * window and the render seam can only show raw JSON.
96
+ */
97
+ identifiedKinds = /* @__PURE__ */ new Map();
98
+ /** pathKeys currently waiting on a schema cold fetch. */
99
+ pendingSchemaPaths = /* @__PURE__ */ new Set();
100
+ /**
101
+ * Early top-level scalar fields (title, loading_message, …) captured for
102
+ * identified-but-schema-pending nodes — the loading-component fuel. Scalars
103
+ * only (no live parser references can escape through here). Superseded the
104
+ * moment a real snapshot node exists.
105
+ */
106
+ earlyFields = /* @__PURE__ */ new Map();
107
+ /**
108
+ * pathKey → identified kind preserved through a raw fallback (parser stamped
109
+ * `kind` on the raw_object event) — schema-availability degrades and, since
110
+ * 2026-08-29, structural ones too. Only a node nothing ever identified (no
111
+ * `__kind` at all) is absent here.
112
+ */
113
+ rawKinds = /* @__PURE__ */ new Map();
114
+ /**
115
+ * pathKey → WHY the node degraded. `"unverified"` means no schema was
116
+ * available and nothing was ever checked; `"invalid"` means a check ran and
117
+ * failed. THE RENDER ROUTE BRANCHES ON THIS — see `IrKindState`. Absent =
118
+ * `"invalid"`, so a parser that predates the `cause` field (or any consumer
119
+ * hand-building events) keeps the strict, safe reading.
120
+ */
121
+ rawCauses = /* @__PURE__ */ new Map();
122
+ regionStatus = "streaming";
123
+ errorReason = null;
124
+ rootRawValue = null;
125
+ /** Notices for degrades that tried to erase already-published data. */
126
+ rescueNotices = [];
127
+ completedKind = "";
128
+ get status() {
129
+ return this.regionStatus;
130
+ }
131
+ applyEvent(event) {
132
+ switch (event.type) {
133
+ case "kind_identified": {
134
+ this.identifiedKinds.set(irPathKey(event.path), event.kind);
135
+ this.dirty.add(irPathKey(event.path));
136
+ return;
137
+ }
138
+ case "pending_schema": {
139
+ const pathKey = irPathKey(event.path);
140
+ this.identifiedKinds.set(pathKey, event.kind);
141
+ this.pendingSchemaPaths.add(pathKey);
142
+ this.dirty.add(pathKey);
143
+ return;
144
+ }
145
+ case "field": {
146
+ const parentKey = irPathKey(event.path.slice(0, -1));
147
+ if (this.nodes.has(parentKey)) return;
148
+ if (!this.identifiedKinds.has(parentKey)) return;
149
+ const v = event.value;
150
+ if (v !== null && typeof v === "object") return;
151
+ const bucket = this.earlyFields.get(parentKey) ?? {};
152
+ bucket[event.key] = v;
153
+ this.earlyFields.set(parentKey, bucket);
154
+ this.dirty.add(parentKey);
155
+ return;
156
+ }
157
+ case "block_snapshot": {
158
+ const pathKey = irPathKey(event.path);
159
+ this.pendingSchemaPaths.delete(pathKey);
160
+ this.earlyFields.delete(pathKey);
161
+ this.upsertNode(event.path, {
162
+ kind: event.kind,
163
+ value: event.value,
164
+ residue: event.residue,
165
+ complete: event.complete
166
+ });
167
+ return;
168
+ }
169
+ case "raw_object": {
170
+ const pathKey = irPathKey(event.path);
171
+ this.pendingSchemaPaths.delete(pathKey);
172
+ this.earlyFields.delete(pathKey);
173
+ if (event.kind) this.rawKinds.set(pathKey, event.kind);
174
+ this.rawCauses.set(pathKey, event.cause ?? "invalid");
175
+ this.markRaw(event.path, event.reason, event.value);
176
+ return;
177
+ }
178
+ case "complete": {
179
+ this.regionStatus = this.errorReason ? "error" : "complete";
180
+ this.completedKind = event.kind;
181
+ if (this.rawPaths.has("") && isRecord(event.value)) {
182
+ const merged = mergeWithoutLoss(this.rootRawValue, event.value);
183
+ this.recordRescue("", "complete", merged.rescued);
184
+ if (isRecord(merged.value)) this.rootRawValue = merged.value;
185
+ }
186
+ this.dirty.add("");
187
+ return;
188
+ }
189
+ case "error": {
190
+ this.errorReason = event.reason;
191
+ this.regionStatus = "error";
192
+ this.dirty.add("");
193
+ return;
194
+ }
195
+ default:
196
+ return;
197
+ }
198
+ }
199
+ getNode(pathKey) {
200
+ return this.nodes.get(pathKey) ?? null;
201
+ }
202
+ listNodes() {
203
+ return [...this.nodes.values()];
204
+ }
205
+ isRawPath(pathKey) {
206
+ return this.rawPaths.has(pathKey);
207
+ }
208
+ /** Dirty pathKeys since the last drain — the flush/notify unit. */
209
+ drainDirty() {
210
+ const drained = [...this.dirty];
211
+ this.dirty.clear();
212
+ return drained;
213
+ }
214
+ hasDirty() {
215
+ return this.dirty.size > 0;
216
+ }
217
+ // -------------------------------------------------------------------------
218
+ upsertNode(path, payload) {
219
+ const pathKey = irPathKey(path);
220
+ if (this.rawPaths.has(pathKey)) return;
221
+ const stabilized = this.stabilizeValue(
222
+ payload.value,
223
+ path,
224
+ pathKey
225
+ );
226
+ const prior = this.nodes.get(pathKey);
227
+ const node = {
228
+ kind: payload.kind,
229
+ kindState: payload.complete ? "resolved" : prior?.kindState ?? "resolved",
230
+ path,
231
+ pathKey,
232
+ value: stabilized,
233
+ residue: payload.residue,
234
+ complete: payload.complete,
235
+ version: (prior?.version ?? 0) + 1
236
+ };
237
+ this.nodes.set(pathKey, node);
238
+ this.dirty.add(pathKey);
239
+ this.propagateToAncestors(path, node.value);
240
+ }
241
+ /**
242
+ * Substitute kind-node children with their current tree values so sibling
243
+ * identities are stable; deep-copy everything else so no live parser
244
+ * reference ever escapes.
245
+ */
246
+ stabilizeValue(value, path, applyingPathKey) {
247
+ if (Array.isArray(value)) {
248
+ return value.map(
249
+ (item, index) => this.stabilizeValue(item, [...path, index], applyingPathKey)
250
+ );
251
+ }
252
+ if (isRecord(value)) {
253
+ const pathKey = irPathKey(path);
254
+ if (pathKey !== applyingPathKey) {
255
+ const childNode = this.nodes.get(pathKey);
256
+ if (childNode) return childNode.value;
257
+ }
258
+ const out = {};
259
+ for (const [key, child] of Object.entries(value)) {
260
+ out[key] = this.stabilizeValue(child, [...path, key], applyingPathKey);
261
+ }
262
+ return out;
263
+ }
264
+ return value;
265
+ }
266
+ /**
267
+ * COW spine rebuild: replace the child's slot in each ancestor kind-node's
268
+ * value, shallow-copying only the containers along the way. Siblings keep
269
+ * identity; every ancestor gets a new value identity + version bump.
270
+ */
271
+ propagateToAncestors(childPath, childValue) {
272
+ let currentPath = childPath;
273
+ let currentValue = childValue;
274
+ while (currentPath.length > 0) {
275
+ const ancestor = this.findNearestAncestorNode(currentPath);
276
+ if (!ancestor) return;
277
+ const relative = currentPath.slice(ancestor.path.length);
278
+ const rebuilt = this.cloneAlong(ancestor.value, relative, currentValue);
279
+ if (rebuilt === ancestor.value) return;
280
+ const updated = {
281
+ ...ancestor,
282
+ value: rebuilt,
283
+ version: ancestor.version + 1
284
+ };
285
+ this.nodes.set(ancestor.pathKey, updated);
286
+ this.dirty.add(ancestor.pathKey);
287
+ currentPath = ancestor.path;
288
+ currentValue = updated.value;
289
+ }
290
+ }
291
+ findNearestAncestorNode(path) {
292
+ for (let len = path.length - 1; len >= 0; len--) {
293
+ const node = this.nodes.get(irPathKey(path.slice(0, len)));
294
+ if (node) return node;
295
+ }
296
+ return null;
297
+ }
298
+ cloneAlong(container, relative, leaf) {
299
+ if (relative.length === 0) return leaf;
300
+ const [head, ...rest] = relative;
301
+ if (Array.isArray(container)) {
302
+ const index = typeof head === "number" ? head : Number(head);
303
+ const copy = container.slice();
304
+ while (copy.length <= index) copy.push(void 0);
305
+ copy[index] = this.cloneAlong(container[index], rest, leaf);
306
+ return copy;
307
+ }
308
+ if (isRecord(container)) {
309
+ const key = String(head);
310
+ return {
311
+ ...container,
312
+ [key]: this.cloneAlong(container[key], rest, leaf)
313
+ };
314
+ }
315
+ const built = typeof head === "number" ? this.cloneAlong([], relative, leaf) : this.cloneAlong({}, relative, leaf);
316
+ return built;
317
+ }
318
+ markRaw(path, reason, value) {
319
+ const pathKey = irPathKey(path);
320
+ const prior = path.length === 0 ? this.nodes.get("")?.value ?? this.rootRawValue : this.nodes.get(pathKey)?.value;
321
+ const merged = mergeWithoutLoss(prior, value);
322
+ this.recordRescue(pathKey, reason, merged.rescued);
323
+ this.rawPaths.set(pathKey, reason);
324
+ this.nodes.delete(pathKey);
325
+ this.dirty.add(pathKey);
326
+ if (path.length === 0) {
327
+ if (isRecord(merged.value)) this.rootRawValue = merged.value;
328
+ return;
329
+ }
330
+ this.propagateToAncestors(path, merged.value);
331
+ }
332
+ /**
333
+ * A rescue means a degrade tried to erase data a user could already see —
334
+ * an upstream defect. It rides the envelope as a notice so it surfaces in the
335
+ * Error Inspector instead of being silently absorbed (`core/` is a pure
336
+ * kernel: no console, no capture — the notice IS the alarm).
337
+ */
338
+ recordRescue(pathKey, reason, rescued) {
339
+ if (rescued.length === 0) return;
340
+ this.rescueNotices.push({
341
+ code: "degrade_data_rescued",
342
+ message: `degrade (${reason}) at path "${pathKey || "<root>"}" would have dropped: ${rescued.join(", ")}`
343
+ });
344
+ }
345
+ /**
346
+ * Assemble the canonical envelope. ONE code path for stream + one-shot.
347
+ * Callers supply the fingerprint (one-shot hashes the source; live sessions
348
+ * keep an incremental hasher so no per-flush re-hash happens).
349
+ */
350
+ buildEnvelope(fingerprint) {
351
+ const rootNode = this.nodes.get("");
352
+ const rootRawReason = this.rawPaths.get("") ?? null;
353
+ const notices = [];
354
+ if (this.errorReason) {
355
+ notices.push({ code: "parse_error", message: this.errorReason });
356
+ }
357
+ if (rootRawReason) {
358
+ notices.push({ code: "raw_fallback", message: rootRawReason });
359
+ }
360
+ notices.push(...this.rescueNotices);
361
+ const baseResidue = rootNode?.residue ?? null;
362
+ let residue = baseResidue;
363
+ if (notices.length > 0) {
364
+ residue = {
365
+ extra: baseResidue?.extra ?? null,
366
+ optionalMissing: baseResidue?.optionalMissing ?? null,
367
+ notices: [...baseResidue?.notices ?? [], ...notices]
368
+ };
369
+ }
370
+ const isRaw = rootRawReason !== null;
371
+ const identifiedKind = this.identifiedKinds.get("") ?? "";
372
+ const rootKind = isRaw ? this.rawKinds.get("") ?? "" : rootNode?.kind ?? (this.completedKind || identifiedKind);
373
+ const rootRawState = this.rawCauses.get("") === "unverified" ? "unverified" : "raw";
374
+ const root = {
375
+ role: "structured",
376
+ kind: rootKind,
377
+ kindState: isRaw ? rootRawState : rootNode ? rootNode.kindState : this.pendingSchemaPaths.has("") ? "pending_schema" : this.regionStatus === "streaming" ? identifiedKind ? "pending_schema" : "pending_kind" : "raw",
378
+ discriminator: JSON_DISCRIMINATOR,
379
+ path: [],
380
+ status: this.regionStatus,
381
+ value: rootNode?.value ?? this.rootRawValue ?? // Copy: the early-fields bucket keeps mutating as fields arrive; the
382
+ // envelope must be freezable (Redux dev-mode immutability).
383
+ (this.earlyFields.has("") ? { ...this.earlyFields.get("") } : {}),
384
+ residue
385
+ };
386
+ const nodeIndex = {};
387
+ for (const node of this.nodes.values()) {
388
+ if (node.pathKey === "") continue;
389
+ nodeIndex[node.pathKey] = {
390
+ kind: node.kind,
391
+ kindState: node.kindState,
392
+ status: node.complete ? "complete" : "streaming",
393
+ ...node.residue ? { residue: node.residue } : {}
394
+ };
395
+ }
396
+ for (const [pathKey] of this.rawPaths) {
397
+ if (pathKey === "") continue;
398
+ nodeIndex[pathKey] = {
399
+ kind: this.rawKinds.get(pathKey) ?? "",
400
+ kindState: this.rawCauses.get(pathKey) === "unverified" ? "unverified" : "raw",
401
+ status: "complete"
402
+ };
403
+ }
404
+ return {
405
+ v: IR_VERSION,
406
+ engine: "fe-kind-parser",
407
+ fingerprint,
408
+ root,
409
+ ...Object.keys(nodeIndex).length > 0 ? { nodeIndex } : {}
410
+ };
411
+ }
412
+ };
413
+
414
+ // core/json-tokenizer.ts
415
+ var JsonStreamTokenizer = class {
416
+ mode = "normal";
417
+ pos = 0;
418
+ stringBuffer = "";
419
+ primitiveBuffer = "";
420
+ unicodeBuffer = "";
421
+ tokenStart = 0;
422
+ onToken;
423
+ // Explicit field rather than a parameter property: consumers compile this
424
+ // source directly, and a strict host (the dashboard) sets
425
+ // `erasableSyntaxOnly`, under which parameter properties are a hard error.
426
+ constructor(onToken) {
427
+ this.onToken = onToken;
428
+ }
429
+ get position() {
430
+ return this.pos;
431
+ }
432
+ push(chunk) {
433
+ for (let i = 0; i < chunk.length; i++) {
434
+ const ch = chunk[i];
435
+ const at = this.pos;
436
+ this.pos += 1;
437
+ if (ch === void 0) continue;
438
+ if (this.mode === "primitive") {
439
+ if (this.isDelimiter(ch)) {
440
+ this.emitPrimitive();
441
+ this.handleNormalChar(ch, at);
442
+ } else {
443
+ this.primitiveBuffer += ch;
444
+ }
445
+ continue;
446
+ }
447
+ if (this.mode === "string") {
448
+ if (ch === '"') {
449
+ this.onToken({
450
+ type: "string",
451
+ value: this.stringBuffer,
452
+ at: this.tokenStart
453
+ });
454
+ this.stringBuffer = "";
455
+ this.mode = "normal";
456
+ continue;
457
+ }
458
+ if (ch === "\\") {
459
+ this.mode = "escape";
460
+ continue;
461
+ }
462
+ if (ch === "\n" || ch === "\r") {
463
+ throw new Error(`Invalid unescaped newline in JSON string at ${at}`);
464
+ }
465
+ this.stringBuffer += ch;
466
+ continue;
467
+ }
468
+ if (this.mode === "escape") {
469
+ if (ch === "u") {
470
+ this.unicodeBuffer = "";
471
+ this.mode = "unicode";
472
+ continue;
473
+ }
474
+ const escaped = {
475
+ '"': '"',
476
+ "\\": "\\",
477
+ "/": "/",
478
+ b: "\b",
479
+ f: "\f",
480
+ n: "\n",
481
+ r: "\r",
482
+ t: " "
483
+ };
484
+ if (!(ch in escaped)) {
485
+ throw new Error(`Invalid JSON escape sequence at ${at}`);
486
+ }
487
+ this.stringBuffer += escaped[ch];
488
+ this.mode = "string";
489
+ continue;
490
+ }
491
+ if (this.mode === "unicode") {
492
+ if (!/[0-9a-fA-F]/.test(ch)) {
493
+ throw new Error(`Invalid unicode escape at ${at}`);
494
+ }
495
+ this.unicodeBuffer += ch;
496
+ if (this.unicodeBuffer.length === 4) {
497
+ this.stringBuffer += String.fromCharCode(
498
+ parseInt(this.unicodeBuffer, 16)
499
+ );
500
+ this.unicodeBuffer = "";
501
+ this.mode = "string";
502
+ }
503
+ continue;
504
+ }
505
+ this.handleNormalChar(ch, at);
506
+ }
507
+ }
508
+ end() {
509
+ if (this.mode === "primitive") {
510
+ this.emitPrimitive();
511
+ return;
512
+ }
513
+ if (this.mode !== "normal") {
514
+ throw new Error(
515
+ `Stream ended while parsing JSON ${this.mode} at ${this.pos}`
516
+ );
517
+ }
518
+ }
519
+ handleNormalChar(ch, at) {
520
+ if (/\s/.test(ch)) return;
521
+ if (ch === "{" || ch === "}" || ch === "[" || ch === "]" || ch === ":" || ch === ",") {
522
+ this.onToken({ type: "punct", value: ch, at });
523
+ return;
524
+ }
525
+ if (ch === '"') {
526
+ this.mode = "string";
527
+ this.stringBuffer = "";
528
+ this.tokenStart = at;
529
+ return;
530
+ }
531
+ if (/[-0-9tfn]/.test(ch)) {
532
+ this.mode = "primitive";
533
+ this.primitiveBuffer = ch;
534
+ this.tokenStart = at;
535
+ return;
536
+ }
537
+ throw new Error(`Unexpected character "${ch}" at ${at}`);
538
+ }
539
+ emitPrimitive() {
540
+ const raw = this.primitiveBuffer;
541
+ const at = this.tokenStart;
542
+ this.primitiveBuffer = "";
543
+ this.mode = "normal";
544
+ let value;
545
+ try {
546
+ value = JSON.parse(raw);
547
+ } catch {
548
+ throw new Error(`Invalid JSON primitive "${raw}" at ${at}`);
549
+ }
550
+ if (typeof value === "number") {
551
+ this.onToken({ type: "number", value, at });
552
+ return;
553
+ }
554
+ if (typeof value === "boolean") {
555
+ this.onToken({ type: "boolean", value, at });
556
+ return;
557
+ }
558
+ if (value === null) {
559
+ this.onToken({ type: "null", value, at });
560
+ return;
561
+ }
562
+ throw new Error(`Unsupported JSON primitive "${raw}" at ${at}`);
563
+ }
564
+ isDelimiter(ch) {
565
+ return /\s/.test(ch) || ch === "{" || ch === "}" || ch === "[" || ch === "]" || ch === ":" || ch === ",";
566
+ }
567
+ };
568
+
569
+ // core/kind-snapshot.ts
570
+ function emptyValueForFieldSchema(field) {
571
+ if (field.nullable) return null;
572
+ switch (field.type) {
573
+ case "string":
574
+ return "";
575
+ case "number":
576
+ return 0;
577
+ case "boolean":
578
+ return false;
579
+ case "json":
580
+ return null;
581
+ case "string[]":
582
+ case "number[]":
583
+ case "boolean[]":
584
+ case "json[]":
585
+ case "array":
586
+ return [];
587
+ case "object":
588
+ case "inline_object":
589
+ case "record":
590
+ return {};
591
+ case "enum":
592
+ return "";
593
+ case "union":
594
+ if (field.scalars.includes("string")) return "";
595
+ if (field.scalars.includes("number")) return 0;
596
+ if (field.scalars.includes("boolean")) return false;
597
+ return {};
598
+ default:
599
+ return null;
600
+ }
601
+ }
602
+ function buildCompliantKindSnapshot(schema, partial) {
603
+ const value = {
604
+ [KIND_KEY]: schema.kind
605
+ };
606
+ const optionalMissing = [];
607
+ for (const [fieldName, fieldSchema] of Object.entries(schema.fields)) {
608
+ if (fieldName in partial && partial[fieldName] !== void 0) {
609
+ value[fieldName] = partial[fieldName];
610
+ } else if (fieldSchema.required) {
611
+ value[fieldName] = emptyValueForFieldSchema(fieldSchema);
612
+ } else {
613
+ optionalMissing.push(fieldName);
614
+ }
615
+ }
616
+ let extra = null;
617
+ for (const [fieldName, fieldValue] of Object.entries(partial)) {
618
+ if (fieldName === KIND_KEY) continue;
619
+ if (fieldName in schema.fields) continue;
620
+ if (extra === null) extra = {};
621
+ extra[fieldName] = fieldValue;
622
+ }
623
+ const residue = {
624
+ extra,
625
+ optionalMissing: optionalMissing.length > 0 ? optionalMissing : null,
626
+ notices: null
627
+ };
628
+ return { value, residue: isEmptyResidue(residue) ? null : residue };
629
+ }
630
+ function mergeResidueIntoValue(value, residue) {
631
+ if (!residue?.extra) return value;
632
+ return { ...value, ...residue.extra };
633
+ }
634
+
635
+ // core/kind-parser.ts
636
+ var jsonRootKeyLookup = null;
637
+ function setJsonRootKeyLookup(lookup) {
638
+ jsonRootKeyLookup = lookup;
639
+ }
640
+ function isSchemaResolver(source) {
641
+ return typeof source.get === "function";
642
+ }
643
+ function safeCopy(value) {
644
+ try {
645
+ return structuredClone(value);
646
+ } catch {
647
+ return value;
648
+ }
649
+ }
650
+ var KindStreamParser = class {
651
+ resolver;
652
+ stack = [];
653
+ objectKinds = /* @__PURE__ */ new Map();
654
+ inlineSchemas = /* @__PURE__ */ new Map();
655
+ recordSchemas = /* @__PURE__ */ new Map();
656
+ rawObjectPaths = /* @__PURE__ */ new Set();
657
+ /**
658
+ * Subtrees whose value domain is "any JSON" by schema (`json` / `json[]`
659
+ * fields, `record` with `values:"json"` members). OPAQUE by contract: no
660
+ * kind identification, no pending_kind, no raw_object degradation — unknown
661
+ * structure here is the declared shape, not a failure. Propagates to every
662
+ * descendant compound.
663
+ */
664
+ opaquePaths = /* @__PURE__ */ new Set();
665
+ deferredFields = /* @__PURE__ */ new Map();
666
+ awaitingKindPaths = /* @__PURE__ */ new Set();
667
+ /** Paths whose kind came from parent-schema prediction, unconfirmed so far. */
668
+ speculativeKinds = /* @__PURE__ */ new Set();
669
+ /**
670
+ * Kind named by the root object's FIRST key through the `json_root_key`
671
+ * surface registry — a candidate, adopted only at root finalize.
672
+ */
673
+ rootSurfaceKind = null;
674
+ /** kind → paths (by key) waiting for the resolver's cold fetch. */
675
+ pendingSchemaPaths = /* @__PURE__ */ new Map();
676
+ /** Pending-schema paths whose object already closed. */
677
+ closedPendingPaths = /* @__PURE__ */ new Set();
678
+ /** Schemas delivered via notifySchemaArrived (overlay over the resolver). */
679
+ arrivedSchemas = /* @__PURE__ */ new Map();
680
+ tokenizer;
681
+ root;
682
+ rootKind = "";
683
+ rootDone = false;
684
+ failed = false;
685
+ options;
686
+ // Explicit field, not a parameter property — see the note in
687
+ // `json-tokenizer.ts`: `erasableSyntaxOnly` hosts compile this source.
688
+ constructor(options) {
689
+ this.options = options;
690
+ this.resolver = isSchemaResolver(options.schemas) ? options.schemas : {
691
+ get: (kind) => options.schemas[kind]
692
+ };
693
+ this.tokenizer = new JsonStreamTokenizer(
694
+ (token) => this.handleToken(token)
695
+ );
696
+ }
697
+ push(chunk) {
698
+ if (this.failed || this.rootDone) return;
699
+ try {
700
+ this.tokenizer.push(chunk);
701
+ } catch (error) {
702
+ this.fail(
703
+ error instanceof Error ? error.message : String(error),
704
+ this.tokenizer.position
705
+ );
706
+ }
707
+ }
708
+ end() {
709
+ if (this.failed) return;
710
+ try {
711
+ this.tokenizer.end();
712
+ } catch (error) {
713
+ this.fail(
714
+ error instanceof Error ? error.message : String(error),
715
+ this.tokenizer.position
716
+ );
717
+ return;
718
+ }
719
+ this.resolvePendingSchemasAsRaw();
720
+ if (!this.rootDone) {
721
+ this.fail(
722
+ "Stream ended before the root JSON object was complete.",
723
+ this.tokenizer.position
724
+ );
725
+ }
726
+ }
727
+ resolvePendingSchemasAsRaw() {
728
+ const at = this.tokenizer.position;
729
+ for (const [kind, paths] of [...this.pendingSchemaPaths]) {
730
+ this.pendingSchemaPaths.delete(kind);
731
+ for (const [pathKey, path] of paths) {
732
+ this.closedPendingPaths.delete(pathKey);
733
+ if (this.rawObjectPaths.has(pathKey)) continue;
734
+ const value = this.getLiveObjectValue(path) ?? this.getFinalizedObjectValue(path) ?? {};
735
+ this.emitRawObject(
736
+ path,
737
+ safeCopy(value),
738
+ `No block schema registered for "${kind}".`,
739
+ at,
740
+ kind,
741
+ "unverified"
742
+ );
743
+ }
744
+ }
745
+ }
746
+ /** True once the root value has closed — the region is fully consumed. */
747
+ get isComplete() {
748
+ return this.rootDone;
749
+ }
750
+ get hasFailed() {
751
+ return this.failed;
752
+ }
753
+ /**
754
+ * Upgrade-in-place: the registry's cold fetch answered. Pending nodes for
755
+ * this kind validate and complete (closed nodes retroactively); a null
756
+ * schema (fetch miss) drops them to raw. Safe to call after end().
757
+ */
758
+ notifySchemaArrived(kind, schema) {
759
+ const waiting = this.pendingSchemaPaths.get(kind);
760
+ if (!waiting) return;
761
+ this.pendingSchemaPaths.delete(kind);
762
+ if (schema) {
763
+ this.arrivedSchemas.set(kind, schema);
764
+ }
765
+ const at = this.tokenizer.position;
766
+ for (const [pathKey, path] of waiting) {
767
+ if (this.rawObjectPaths.has(pathKey)) continue;
768
+ const value = this.getLiveObjectValue(path) ?? this.getFinalizedObjectValue(path);
769
+ if (!schema) {
770
+ this.emitRawObject(
771
+ path,
772
+ safeCopy(value ?? {}),
773
+ `No block schema registered for "${kind}".`,
774
+ at,
775
+ kind,
776
+ "unverified"
777
+ );
778
+ this.closedPendingPaths.delete(pathKey);
779
+ continue;
780
+ }
781
+ if (this.closedPendingPaths.has(pathKey)) {
782
+ this.closedPendingPaths.delete(pathKey);
783
+ if (value) {
784
+ this.finalizeTypedObject(path, value, at);
785
+ }
786
+ } else {
787
+ this.emitBlockSnapshotForObject(path, at);
788
+ }
789
+ }
790
+ }
791
+ handleToken(token) {
792
+ if (this.failed) return;
793
+ if (this.rootDone) {
794
+ this.fail("Unexpected token after complete JSON object.", token.at);
795
+ return;
796
+ }
797
+ if (token.type === "punct") {
798
+ this.handlePunctuation(token);
799
+ return;
800
+ }
801
+ if (token.type === "string") {
802
+ this.handleString(token);
803
+ return;
804
+ }
805
+ this.beginScalar(token.value, token.at);
806
+ }
807
+ handleString(token) {
808
+ const frame = this.currentFrame();
809
+ if (frame?.kind === "object" && (frame.expecting === "keyOrEnd" || frame.expecting === "key")) {
810
+ this.acceptObjectKey(frame, token.value, token.at);
811
+ return;
812
+ }
813
+ this.beginScalar(token.value, token.at);
814
+ }
815
+ handlePunctuation(token) {
816
+ switch (token.value) {
817
+ case "{":
818
+ this.beginCompound("object", token.at);
819
+ return;
820
+ case "[":
821
+ this.beginCompound("array", token.at);
822
+ return;
823
+ case "}":
824
+ this.closeCompound("object", token.at);
825
+ return;
826
+ case "]":
827
+ this.closeCompound("array", token.at);
828
+ return;
829
+ case ":":
830
+ this.acceptColon(token.at);
831
+ return;
832
+ case ",":
833
+ this.acceptComma(token.at);
834
+ return;
835
+ }
836
+ }
837
+ beginCompound(kind, at) {
838
+ const value = kind === "object" ? {} : [];
839
+ const container = this.currentFrame();
840
+ const path = this.placeValue(value, kind, at, false);
841
+ if (!path || this.failed) return;
842
+ const opaque = container !== void 0 && this.opaquePaths.has(this.pathKey(container.path)) || this.isJsonAnyPlacement(path);
843
+ if (opaque) this.opaquePaths.add(this.pathKey(path));
844
+ if (kind === "object") {
845
+ this.emit({ type: "object_start", path, at });
846
+ if (opaque) {
847
+ this.stack.push({
848
+ kind: "object",
849
+ path,
850
+ value,
851
+ expecting: "keyOrEnd",
852
+ keyCount: 0
853
+ });
854
+ return;
855
+ }
856
+ this.registerObjectContext(path);
857
+ const pathKey = this.pathKey(path);
858
+ this.stack.push({
859
+ kind: "object",
860
+ path,
861
+ value,
862
+ expecting: "keyOrEnd",
863
+ keyCount: 0
864
+ });
865
+ if (this.inlineSchemas.has(pathKey) || this.recordSchemas.has(pathKey)) {
866
+ return;
867
+ }
868
+ const speculated = this.resolveSpeculativeKind(path);
869
+ if (speculated) {
870
+ this.objectKinds.set(pathKey, speculated);
871
+ this.speculativeKinds.add(pathKey);
872
+ if (path.length === 0) {
873
+ this.rootKind = speculated;
874
+ }
875
+ this.emit({
876
+ type: "kind_identified",
877
+ kind: speculated,
878
+ path,
879
+ speculative: true,
880
+ at
881
+ });
882
+ this.emitBlockSnapshotForObject(path, at);
883
+ return;
884
+ }
885
+ this.awaitingKindPaths.add(pathKey);
886
+ this.emit({ type: "pending_kind", path, at });
887
+ return;
888
+ }
889
+ const parentField = this.parentFieldName(path);
890
+ if (parentField) {
891
+ this.emit({ type: "array_start", path, field: parentField, at });
892
+ }
893
+ this.stack.push({
894
+ kind: "array",
895
+ path,
896
+ value,
897
+ expecting: "valueOrEnd",
898
+ nextIndex: 0
899
+ });
900
+ }
901
+ /**
902
+ * THE JSON-ROOT-KEY SURFACE — `content_ir.kind_surface` rows of type
903
+ * `json_root_key`, live at last (they were inert phantom rows until
904
+ * 2026-08-20).
905
+ *
906
+ * A legacy payload such as `{"quiz_title": ...}` carries no `__kind`, but
907
+ * the ONE surface registry knows exactly which kind that root key names —
908
+ * the same lookup the SERVER performs before adapting the payload
909
+ * (`aidream .../processing/blocks/envelope.py`). Consulting it HERE, in the
910
+ * shared parser core, is what makes one place decide it: both hosts — the
911
+ * one-shot `normalizeJsonRegion` (DB reload / reconcile) and the live
912
+ * `openParseSession` (streaming) — build their parser through
913
+ * `createKindStreamParser`, so neither passes an option and neither can
914
+ * drift from the other.
915
+ *
916
+ * Recorded at the first root key; ADOPTED only when the root object closes
917
+ * (`completeTypedObject`). That is the surface registry's complete-only
918
+ * convergence law, and every json_root_key row is `streaming:false` — these
919
+ * legacy shapes are recognized by their whole payload, so speculating
920
+ * mid-stream would flash a kind component over an object that may never
921
+ * satisfy the schema. An explicit `expectedRootKind` (an agent's declared
922
+ * output schema) is stronger context and always wins; an actual `__kind`
923
+ * still wins over both.
924
+ */
925
+ noteRootSurfaceKind(key) {
926
+ if (key === KIND_KEY) return;
927
+ if (this.options.expectedRootKind) return;
928
+ if (this.rootKind || this.objectKinds.has(this.pathKey([]))) return;
929
+ const kind = this.resolver.kindForJsonRootKey?.(key) ?? jsonRootKeyLookup?.(key);
930
+ if (!kind) return;
931
+ this.rootSurfaceKind = kind;
932
+ if (!this.lookupSchema(kind)) {
933
+ this.resolver.request?.(kind);
934
+ }
935
+ }
936
+ /**
937
+ * Prediction from the parent schema: object field → declared kind; array
938
+ * item → sole itemKind; root → expectedRootKind. Only when the schema is
939
+ * actually resolvable (a prediction we can't validate against is not a
940
+ * commitment worth making).
941
+ */
942
+ resolveSpeculativeKind(path) {
943
+ if (path.length === 0) {
944
+ const expected = this.options.expectedRootKind;
945
+ return expected && this.lookupObjectSchema(expected) ? expected : null;
946
+ }
947
+ const last = path[path.length - 1];
948
+ if (typeof last === "string") {
949
+ const fieldSchema2 = this.resolveParentFieldSchema(path);
950
+ if (fieldSchema2?.type === "object" && this.lookupObjectSchema(fieldSchema2.kind)) {
951
+ return fieldSchema2.kind;
952
+ }
953
+ return null;
954
+ }
955
+ const fieldName = this.parentFieldName(path);
956
+ if (!fieldName) return null;
957
+ const ownerPath = path.slice(0, -2);
958
+ const ownerKind = this.getObjectKindForPath(ownerPath);
959
+ if (!ownerKind) return null;
960
+ const fieldSchema = this.lookupSchema(ownerKind)?.fields[fieldName];
961
+ const soleItemKind = fieldSchema?.type === "array" && fieldSchema.itemKinds.length === 1 ? fieldSchema.itemKinds[0] : void 0;
962
+ if (soleItemKind !== void 0 && this.lookupObjectSchema(soleItemKind)) {
963
+ return soleItemKind;
964
+ }
965
+ return null;
966
+ }
967
+ /**
968
+ * A schema usable for OBJECT speculation/snapshots — root-form kinds
969
+ * (non-object data-only shapes) are never a valid object commitment.
970
+ */
971
+ lookupObjectSchema(kind) {
972
+ const schema = this.lookupSchema(kind);
973
+ return schema && !schema.root ? schema : void 0;
974
+ }
975
+ beginScalar(value, at) {
976
+ this.placeValue(value, "scalar", at, true);
977
+ }
978
+ placeValue(value, valueKind, at, finalizedImmediately) {
979
+ if (this.root === void 0) {
980
+ if (valueKind !== "object") {
981
+ this.fail("Root value must be a JSON object.", at);
982
+ return null;
983
+ }
984
+ this.root = value;
985
+ return [];
986
+ }
987
+ const parent = this.currentFrame();
988
+ if (!parent) {
989
+ this.fail("Unexpected value after root object.", at);
990
+ return null;
991
+ }
992
+ let path;
993
+ let fieldKey;
994
+ if (parent.kind === "object") {
995
+ if (parent.expecting !== "value") {
996
+ this.fail(
997
+ `Unexpected value inside object. Expected ${parent.expecting}.`,
998
+ at
999
+ );
1000
+ return null;
1001
+ }
1002
+ if (parent.currentKey === void 0) {
1003
+ this.fail("Internal parser error: missing object key.", at);
1004
+ return null;
1005
+ }
1006
+ fieldKey = parent.currentKey;
1007
+ path = [...parent.path, fieldKey];
1008
+ const placementError = this.validateFieldPlacement(
1009
+ parent,
1010
+ fieldKey,
1011
+ valueKind,
1012
+ value
1013
+ );
1014
+ if (placementError) {
1015
+ this.markNodeRaw(parent.path, parent.value, placementError, at);
1016
+ }
1017
+ parent.value[fieldKey] = value;
1018
+ parent.currentKey = void 0;
1019
+ parent.expecting = "commaOrEnd";
1020
+ } else {
1021
+ if (parent.expecting !== "valueOrEnd" && parent.expecting !== "value") {
1022
+ this.fail(
1023
+ `Unexpected value inside array. Expected ${parent.expecting}.`,
1024
+ at
1025
+ );
1026
+ return null;
1027
+ }
1028
+ const index = parent.nextIndex;
1029
+ path = [...parent.path, index];
1030
+ fieldKey = this.parentFieldName(path);
1031
+ parent.value.push(value);
1032
+ parent.nextIndex += 1;
1033
+ parent.expecting = "commaOrEnd";
1034
+ }
1035
+ if (finalizedImmediately) {
1036
+ this.onValueFinalized(path, value, at);
1037
+ }
1038
+ return path;
1039
+ }
1040
+ acceptObjectKey(frame, key, at) {
1041
+ if (frame.expecting !== "keyOrEnd" && frame.expecting !== "key") {
1042
+ this.fail(`Unexpected object key "${key}".`, at);
1043
+ return;
1044
+ }
1045
+ if (Object.prototype.hasOwnProperty.call(frame.value, key)) {
1046
+ this.markNodeRaw(
1047
+ frame.path,
1048
+ frame.value,
1049
+ `Duplicate key "${key}".`,
1050
+ at
1051
+ );
1052
+ }
1053
+ if (frame.path.length === 0 && frame.keyCount === 0) {
1054
+ this.noteRootSurfaceKind(key);
1055
+ }
1056
+ frame.currentKey = key;
1057
+ frame.keyCount += 1;
1058
+ frame.expecting = "colon";
1059
+ }
1060
+ acceptColon(at) {
1061
+ const frame = this.currentFrame();
1062
+ if (!frame || frame.kind !== "object" || frame.expecting !== "colon") {
1063
+ this.fail("Unexpected colon.", at);
1064
+ return;
1065
+ }
1066
+ frame.expecting = "value";
1067
+ }
1068
+ acceptComma(at) {
1069
+ const frame = this.currentFrame();
1070
+ if (!frame || frame.expecting !== "commaOrEnd") {
1071
+ this.fail("Unexpected comma.", at);
1072
+ return;
1073
+ }
1074
+ if (frame.kind === "object") {
1075
+ frame.expecting = "key";
1076
+ } else {
1077
+ frame.expecting = "value";
1078
+ }
1079
+ }
1080
+ closeCompound(kind, at) {
1081
+ const frame = this.currentFrame();
1082
+ if (!frame || frame.kind !== kind) {
1083
+ this.fail(
1084
+ `Unexpected closing ${kind === "object" ? "brace" : "bracket"}.`,
1085
+ at
1086
+ );
1087
+ return;
1088
+ }
1089
+ if (frame.kind === "object") {
1090
+ if (frame.expecting !== "keyOrEnd" && frame.expecting !== "commaOrEnd") {
1091
+ this.fail(`Object closed too early. Expected ${frame.expecting}.`, at);
1092
+ return;
1093
+ }
1094
+ } else if (frame.expecting !== "valueOrEnd" && frame.expecting !== "commaOrEnd") {
1095
+ this.fail(`Array closed too early. Expected ${frame.expecting}.`, at);
1096
+ return;
1097
+ }
1098
+ this.stack.pop();
1099
+ if (this.stack.length === 0) {
1100
+ this.rootDone = true;
1101
+ }
1102
+ this.onValueFinalized(frame.path, frame.value, at);
1103
+ }
1104
+ /**
1105
+ * True when a value placed at `path` sits directly under a json-any
1106
+ * placement: a `json`/`json[]` FIELD, or a member of a `record` whose
1107
+ * values are `"json"`. (Deeper descendants inherit via `opaquePaths`.)
1108
+ */
1109
+ isJsonAnyPlacement(path) {
1110
+ const fieldSchema = this.resolveParentFieldSchema(path);
1111
+ if (fieldSchema && isJsonAnyField(fieldSchema)) return true;
1112
+ const last = path[path.length - 1];
1113
+ if (typeof last === "string") {
1114
+ const parentKey = this.pathKey(path.slice(0, -1));
1115
+ if (this.recordSchemas.get(parentKey) === "json") return true;
1116
+ }
1117
+ return false;
1118
+ }
1119
+ onValueFinalized(path, value, at) {
1120
+ if (this.failed) return;
1121
+ const pathKey = this.pathKey(path);
1122
+ const parentIsOpaque = path.length > 0 && this.opaquePaths.has(this.pathKey(path.slice(0, -1)));
1123
+ if (this.opaquePaths.has(pathKey)) {
1124
+ if (!parentIsOpaque) this.emitFieldIfReady(path, value, at);
1125
+ return;
1126
+ }
1127
+ if (parentIsOpaque) return;
1128
+ if (this.isKindFieldPath(path)) {
1129
+ if (typeof value !== "string") {
1130
+ return;
1131
+ }
1132
+ this.onKindDiscriminatorArrived(path.slice(0, -1), value, at);
1133
+ return;
1134
+ }
1135
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
1136
+ const objectValue = value;
1137
+ const inlineFields = this.inlineSchemas.get(pathKey);
1138
+ if (inlineFields) {
1139
+ const inlineError = this.validateObjectAgainstFields(
1140
+ objectValue,
1141
+ inlineFields
1142
+ );
1143
+ if (inlineError.error) {
1144
+ this.emitRawObject(path, objectValue, inlineError.error, at);
1145
+ return;
1146
+ }
1147
+ this.inlineSchemas.delete(pathKey);
1148
+ this.emitSchemaNotices(path, "inline_object", inlineError, at);
1149
+ this.emit({
1150
+ type: "object_complete",
1151
+ kind: "inline_object",
1152
+ path,
1153
+ value: objectValue,
1154
+ at
1155
+ });
1156
+ } else {
1157
+ const recordValueType = this.recordSchemas.get(pathKey);
1158
+ if (recordValueType) {
1159
+ const recordError = this.validateRecordObject(
1160
+ objectValue,
1161
+ recordValueType
1162
+ );
1163
+ if (recordError) {
1164
+ this.emitRawObject(path, objectValue, recordError, at);
1165
+ return;
1166
+ }
1167
+ this.recordSchemas.delete(pathKey);
1168
+ this.emit({
1169
+ type: "object_complete",
1170
+ kind: "record",
1171
+ path,
1172
+ value: objectValue,
1173
+ at
1174
+ });
1175
+ } else {
1176
+ this.completeTypedObject(path, objectValue, at);
1177
+ }
1178
+ }
1179
+ }
1180
+ this.emitFieldIfReady(path, value, at);
1181
+ if (path.length === 0) {
1182
+ this.completeRoot(value, at);
1183
+ }
1184
+ }
1185
+ /** __kind arrived for an object — confirm speculation, identify, or backtrack. */
1186
+ onKindDiscriminatorArrived(objectPath, kind, at) {
1187
+ const objectPathKey = this.pathKey(objectPath);
1188
+ if (this.rawObjectPaths.has(objectPathKey)) return;
1189
+ const prior = this.objectKinds.get(objectPathKey);
1190
+ const wasSpeculative = this.speculativeKinds.has(objectPathKey);
1191
+ if (prior !== void 0 && wasSpeculative) {
1192
+ this.speculativeKinds.delete(objectPathKey);
1193
+ if (prior === kind) {
1194
+ this.emitBlockSnapshotForObject(objectPath, at);
1195
+ return;
1196
+ }
1197
+ if (this.lookupSchema(kind) && this.validateArrayItemKind(objectPath, kind) === null && this.speculativeRetagAllowed(objectPath, kind)) {
1198
+ this.objectKinds.set(objectPathKey, kind);
1199
+ if (objectPath.length === 0) {
1200
+ this.rootKind = kind;
1201
+ }
1202
+ this.emit({ type: "kind_identified", kind, path: objectPath, at });
1203
+ this.emitBlockSnapshotForObject(objectPath, at);
1204
+ return;
1205
+ }
1206
+ const live = this.getLiveObjectValue(objectPath);
1207
+ this.objectKinds.delete(objectPathKey);
1208
+ if (objectPath.length === 0) {
1209
+ this.rootKind = "";
1210
+ }
1211
+ this.emitRawObject(
1212
+ objectPath,
1213
+ safeCopy(live ?? {}),
1214
+ `Speculated kind "${prior}" contradicted by ${KIND_KEY} "${kind}".`,
1215
+ at
1216
+ );
1217
+ return;
1218
+ }
1219
+ this.objectKinds.set(objectPathKey, kind);
1220
+ this.emit({
1221
+ type: "kind_identified",
1222
+ kind,
1223
+ path: objectPath,
1224
+ at
1225
+ });
1226
+ this.clearKindWait(objectPath, "identified", at, kind);
1227
+ if (objectPath.length === 0) {
1228
+ this.rootKind = kind;
1229
+ }
1230
+ if (!this.lookupSchema(kind) && this.resolver.request) {
1231
+ this.addPendingSchemaPath(kind, objectPath);
1232
+ this.emit({ type: "pending_schema", kind, path: objectPath, at });
1233
+ this.resolver.request(kind);
1234
+ return;
1235
+ }
1236
+ this.flushDeferredFields(objectPath, kind, at);
1237
+ this.emitBlockSnapshotForObject(objectPath, at);
1238
+ }
1239
+ /** A contradicted speculation may re-tag only where the new kind is legal. */
1240
+ speculativeRetagAllowed(path, kind) {
1241
+ if (path.length === 0) {
1242
+ return true;
1243
+ }
1244
+ const last = path[path.length - 1];
1245
+ if (typeof last === "number") {
1246
+ const fieldName = this.parentFieldName(path);
1247
+ const ownerKind = this.getObjectKindForPath(path.slice(0, -2));
1248
+ if (!fieldName || !ownerKind) return false;
1249
+ const fieldSchema = this.lookupSchema(ownerKind)?.fields[fieldName];
1250
+ return fieldSchema?.type === "array" && fieldSchema.itemKinds.includes(kind);
1251
+ }
1252
+ return false;
1253
+ }
1254
+ addPendingSchemaPath(kind, path) {
1255
+ const pathKey = this.pathKey(path);
1256
+ const existing = this.pendingSchemaPaths.get(kind) ?? /* @__PURE__ */ new Map();
1257
+ existing.set(pathKey, path);
1258
+ this.pendingSchemaPaths.set(kind, existing);
1259
+ }
1260
+ completeTypedObject(path, objectValue, at) {
1261
+ const pathKey = this.pathKey(path);
1262
+ if (this.rawObjectPaths.has(pathKey)) return;
1263
+ const declaredKind = readObjectKind(objectValue);
1264
+ const committedKind = this.objectKinds.get(pathKey);
1265
+ if (committedKind && this.pendingSchemaPaths.get(committedKind)?.has(pathKey)) {
1266
+ this.closedPendingPaths.add(pathKey);
1267
+ return;
1268
+ }
1269
+ if (!declaredKind && committedKind && this.speculativeKinds.has(pathKey)) {
1270
+ this.speculativeKinds.delete(pathKey);
1271
+ this.finalizeSpeculatedObject(path, objectValue, committedKind, at);
1272
+ return;
1273
+ }
1274
+ if (path.length === 0 && !declaredKind && !committedKind && this.rootSurfaceKind) {
1275
+ const surfaceKind = this.rootSurfaceKind;
1276
+ this.rootSurfaceKind = null;
1277
+ this.objectKinds.set(pathKey, surfaceKind);
1278
+ this.rootKind = surfaceKind;
1279
+ this.emit({
1280
+ type: "kind_identified",
1281
+ kind: surfaceKind,
1282
+ path,
1283
+ speculative: true,
1284
+ at
1285
+ });
1286
+ this.clearKindWait(path, "identified", at, surfaceKind);
1287
+ this.finalizeSpeculatedObject(path, objectValue, surfaceKind, at);
1288
+ return;
1289
+ }
1290
+ if (!declaredKind) {
1291
+ this.emitRawObject(
1292
+ path,
1293
+ objectValue,
1294
+ `Object is missing "${KIND_KEY}".`,
1295
+ at
1296
+ );
1297
+ return;
1298
+ }
1299
+ this.speculativeKinds.delete(pathKey);
1300
+ this.finalizeTypedObject(path, objectValue, at);
1301
+ }
1302
+ /** Validate + complete an object whose value carries __kind. */
1303
+ finalizeTypedObject(path, objectValue, at) {
1304
+ const pathKey = this.pathKey(path);
1305
+ const kind = readObjectKind(objectValue);
1306
+ if (!kind) {
1307
+ this.emitRawObject(
1308
+ path,
1309
+ objectValue,
1310
+ `Object is missing "${KIND_KEY}".`,
1311
+ at
1312
+ );
1313
+ return;
1314
+ }
1315
+ const schema = this.lookupSchema(kind);
1316
+ if (!schema) {
1317
+ this.emitRawObject(
1318
+ path,
1319
+ objectValue,
1320
+ `No block schema registered for "${kind}".`,
1321
+ at,
1322
+ kind,
1323
+ "unverified"
1324
+ );
1325
+ return;
1326
+ }
1327
+ const arrayItemError = this.validateArrayItemKind(path, kind);
1328
+ if (arrayItemError) {
1329
+ this.emitRawObject(path, objectValue, arrayItemError, at, kind);
1330
+ return;
1331
+ }
1332
+ const outcome = this.validateObjectAgainstSchema(objectValue, schema);
1333
+ if (outcome.error) {
1334
+ this.emitRawObject(path, objectValue, outcome.error, at, kind);
1335
+ return;
1336
+ }
1337
+ this.objectKinds.set(pathKey, kind);
1338
+ this.emitSchemaNotices(path, kind, outcome, at);
1339
+ this.emitBlockSnapshotForObject(path, at, true);
1340
+ this.emit({
1341
+ type: "object_complete",
1342
+ kind,
1343
+ path,
1344
+ value: objectValue,
1345
+ at
1346
+ });
1347
+ }
1348
+ /** Validate + complete an object typed purely by parent prediction. */
1349
+ finalizeSpeculatedObject(path, objectValue, kind, at) {
1350
+ const schema = this.lookupSchema(kind);
1351
+ if (!schema) {
1352
+ this.emitRawObject(
1353
+ path,
1354
+ objectValue,
1355
+ `No block schema registered for "${kind}".`,
1356
+ at,
1357
+ kind,
1358
+ "unverified"
1359
+ );
1360
+ return;
1361
+ }
1362
+ const outcome = this.validateObjectAgainstSchema(
1363
+ { ...objectValue, [KIND_KEY]: kind },
1364
+ schema
1365
+ );
1366
+ if (outcome.error) {
1367
+ this.emitRawObject(path, objectValue, outcome.error, at, kind);
1368
+ return;
1369
+ }
1370
+ this.emitSchemaNotices(path, kind, outcome, at);
1371
+ this.emitBlockSnapshotForObject(path, at, true);
1372
+ this.emit({
1373
+ type: "object_complete",
1374
+ kind,
1375
+ path,
1376
+ value: objectValue,
1377
+ at
1378
+ });
1379
+ }
1380
+ validateArrayItemKind(path, kind) {
1381
+ const last = path[path.length - 1];
1382
+ if (typeof last !== "number") return null;
1383
+ const fieldName = this.parentFieldName(path);
1384
+ if (!fieldName) return null;
1385
+ const ownerObjectPath = path.slice(0, -2);
1386
+ const parentKind = this.getObjectKindForPath(ownerObjectPath);
1387
+ if (!parentKind) return null;
1388
+ const fieldSchema = this.lookupSchema(parentKind)?.fields[fieldName];
1389
+ if (!fieldSchema || fieldSchema.type !== "array") return null;
1390
+ if (!fieldSchema.itemKinds.includes(kind)) {
1391
+ return `Kind "${kind}" is not allowed in "${fieldName}" on "${parentKind}" (expected one of: ${fieldSchema.itemKinds.join(", ")}).`;
1392
+ }
1393
+ return null;
1394
+ }
1395
+ completeRoot(rootObject, at) {
1396
+ const pathKey = this.pathKey([]);
1397
+ if (this.rawObjectPaths.has(pathKey)) {
1398
+ this.emit({
1399
+ type: "complete",
1400
+ kind: readObjectKind(rootObject) ?? "",
1401
+ value: rootObject,
1402
+ at
1403
+ });
1404
+ return;
1405
+ }
1406
+ const committedKind = this.objectKinds.get(pathKey);
1407
+ if (committedKind && this.pendingSchemaPaths.get(committedKind)?.has(pathKey)) {
1408
+ this.emit({
1409
+ type: "complete",
1410
+ kind: committedKind,
1411
+ value: rootObject,
1412
+ at
1413
+ });
1414
+ return;
1415
+ }
1416
+ this.emit({
1417
+ type: "complete",
1418
+ kind: this.objectKinds.get(pathKey) ?? readObjectKind(rootObject) ?? "",
1419
+ value: rootObject,
1420
+ at
1421
+ });
1422
+ }
1423
+ /** Mark a node raw (node-scoped failure) without killing the stream. */
1424
+ markNodeRaw(path, liveValue, reason, at) {
1425
+ const pathKey = this.pathKey(path);
1426
+ if (this.rawObjectPaths.has(pathKey)) return;
1427
+ const identifiedKind = this.objectKinds.get(pathKey) ?? (typeof liveValue === "object" && liveValue !== null && !Array.isArray(liveValue) ? readObjectKind(liveValue) ?? void 0 : void 0);
1428
+ this.speculativeKinds.delete(pathKey);
1429
+ this.emitRawObject(path, safeCopy(liveValue), reason, at, identifiedKind);
1430
+ }
1431
+ /**
1432
+ * Degrade ONE node off the resolved path.
1433
+ *
1434
+ * `cause` defaults to `"invalid"` deliberately: every call site that omits
1435
+ * it is a real failure (validation, duplicate key, placement, contradicted
1436
+ * speculation). ONLY the "no schema registered" sites pass `"unverified"`,
1437
+ * and they are the reason the parameter exists — see `IrKindState`.
1438
+ */
1439
+ emitRawObject(path, value, reason, at, identifiedKind, cause = "invalid") {
1440
+ const pathKey = this.pathKey(path);
1441
+ if (this.rawObjectPaths.has(pathKey)) return;
1442
+ this.rawObjectPaths.add(pathKey);
1443
+ this.clearKindWait(path, "raw_fallback", at, void 0, reason);
1444
+ this.emit({
1445
+ type: "raw_object",
1446
+ path,
1447
+ value,
1448
+ reason,
1449
+ ...identifiedKind !== void 0 && { kind: identifiedKind },
1450
+ cause,
1451
+ at
1452
+ });
1453
+ }
1454
+ clearKindWait(path, outcome, at, kind, reason) {
1455
+ const pathKey = this.pathKey(path);
1456
+ if (!this.awaitingKindPaths.has(pathKey)) return;
1457
+ this.awaitingKindPaths.delete(pathKey);
1458
+ this.emit({
1459
+ type: "kind_wait_end",
1460
+ path,
1461
+ outcome,
1462
+ ...kind !== void 0 && { kind },
1463
+ ...reason !== void 0 && { reason },
1464
+ at
1465
+ });
1466
+ }
1467
+ emitFieldIfReady(path, value, at) {
1468
+ const fieldKey = this.fieldKeyFromPath(path);
1469
+ if (!fieldKey || fieldKey === KIND_KEY) return;
1470
+ const parentPath = path.slice(0, -1);
1471
+ const objectKind = this.getDirectObjectKind(parentPath);
1472
+ if (!objectKind) {
1473
+ const parentPathKey = this.pathKey(parentPath);
1474
+ const deferred = this.deferredFields.get(parentPathKey) ?? [];
1475
+ deferred.push({ key: fieldKey, value, at });
1476
+ this.deferredFields.set(parentPathKey, deferred);
1477
+ return;
1478
+ }
1479
+ const schemaResolved = this.lookupSchema(objectKind) !== void 0;
1480
+ if (schemaResolved && !this.isAllowedSchemaField(parentPath, fieldKey, objectKind)) {
1481
+ return;
1482
+ }
1483
+ this.emit({
1484
+ type: "field",
1485
+ kind: objectKind,
1486
+ path,
1487
+ key: fieldKey,
1488
+ value,
1489
+ at
1490
+ });
1491
+ this.emitBlockSnapshotForObject(parentPath, at);
1492
+ }
1493
+ flushDeferredFields(objectPath, kind, at) {
1494
+ const pathKey = this.pathKey(objectPath);
1495
+ const deferred = this.deferredFields.get(pathKey);
1496
+ if (!deferred) return;
1497
+ for (const entry of deferred) {
1498
+ if (entry.key === KIND_KEY) continue;
1499
+ if (!this.isAllowedSchemaField(objectPath, entry.key, kind)) continue;
1500
+ this.emit({
1501
+ type: "field",
1502
+ kind,
1503
+ path: [...objectPath, entry.key],
1504
+ key: entry.key,
1505
+ value: entry.value,
1506
+ at: entry.at
1507
+ });
1508
+ }
1509
+ this.deferredFields.delete(pathKey);
1510
+ this.emitBlockSnapshotForObject(objectPath, at);
1511
+ }
1512
+ getLiveObjectValue(path) {
1513
+ const pathKey = this.pathKey(path);
1514
+ for (let i = this.stack.length - 1; i >= 0; i--) {
1515
+ const frame = this.stack[i];
1516
+ if (!frame) continue;
1517
+ if (frame.kind === "object" && this.pathKey(frame.path) === pathKey) {
1518
+ return frame.value;
1519
+ }
1520
+ }
1521
+ return null;
1522
+ }
1523
+ emitBlockSnapshotForObject(objectPath, at, complete = false) {
1524
+ const pathKey = this.pathKey(objectPath);
1525
+ if (this.rawObjectPaths.has(pathKey)) return;
1526
+ const kind = this.getDirectObjectKind(objectPath);
1527
+ if (!kind) return;
1528
+ const schema = this.lookupObjectSchema(kind);
1529
+ if (!schema) return;
1530
+ const partial = complete ? this.getFinalizedObjectValue(objectPath) : this.getLiveObjectValue(objectPath);
1531
+ if (!partial) return;
1532
+ const { value, residue } = buildCompliantKindSnapshot(schema, partial);
1533
+ this.emit({
1534
+ type: "block_snapshot",
1535
+ kind,
1536
+ path: objectPath,
1537
+ value,
1538
+ residue,
1539
+ complete,
1540
+ at
1541
+ });
1542
+ }
1543
+ /**
1544
+ * On `complete` snapshots (and post-close schema upgrades) the frame has
1545
+ * already been popped — the finalized value lives in the root tree.
1546
+ */
1547
+ getFinalizedObjectValue(path) {
1548
+ const live = this.getLiveObjectValue(path);
1549
+ if (live) return live;
1550
+ if (path.length === 0) {
1551
+ return typeof this.root === "object" && this.root !== null && !Array.isArray(this.root) ? this.root : null;
1552
+ }
1553
+ let cursor = this.root;
1554
+ for (const segment of path) {
1555
+ if (cursor === null || typeof cursor !== "object") return null;
1556
+ cursor = cursor[segment];
1557
+ }
1558
+ return typeof cursor === "object" && cursor !== null && !Array.isArray(cursor) ? cursor : null;
1559
+ }
1560
+ validateFieldPlacement(parent, fieldKey, valueKind, value) {
1561
+ const parentPathKey = this.pathKey(parent.path);
1562
+ const inlineFields = this.inlineSchemas.get(parentPathKey);
1563
+ if (inlineFields) {
1564
+ const fieldSchema = inlineFields[fieldKey];
1565
+ if (!fieldSchema) {
1566
+ return null;
1567
+ }
1568
+ return this.validateValueAgainstField(
1569
+ fieldSchema,
1570
+ valueKind,
1571
+ value,
1572
+ fieldKey
1573
+ );
1574
+ }
1575
+ const recordValueType = this.recordSchemas.get(parentPathKey);
1576
+ if (recordValueType) {
1577
+ if (recordValueType === "json") return null;
1578
+ if (valueKind !== "scalar") {
1579
+ return `Record field "${fieldKey}" must be a scalar.`;
1580
+ }
1581
+ return this.validateRecordScalar(recordValueType, value, fieldKey);
1582
+ }
1583
+ return null;
1584
+ }
1585
+ emitSchemaNotices(path, kind, outcome, at) {
1586
+ for (const field of outcome.optionalMissing) {
1587
+ this.emit({
1588
+ type: "optional_field_missing",
1589
+ kind,
1590
+ path,
1591
+ field,
1592
+ at
1593
+ });
1594
+ }
1595
+ for (const field of outcome.extraFields) {
1596
+ this.emit({
1597
+ type: "extra_field",
1598
+ kind,
1599
+ path,
1600
+ field,
1601
+ at
1602
+ });
1603
+ }
1604
+ }
1605
+ validateObjectAgainstSchema(objectValue, schema) {
1606
+ const optionalMissing = [];
1607
+ const extraFields = [];
1608
+ const emptyOutcome = { optionalMissing, extraFields };
1609
+ if (schema.root) {
1610
+ return {
1611
+ error: `Kind "${schema.kind}" has a non-object root form and cannot be a "${KIND_KEY}" object.`,
1612
+ ...emptyOutcome
1613
+ };
1614
+ }
1615
+ const kind = readObjectKind(objectValue);
1616
+ if (kind !== schema.kind) {
1617
+ return {
1618
+ error: `Object "${KIND_KEY}" is "${kind ?? "missing"}", expected "${schema.kind}".`,
1619
+ ...emptyOutcome
1620
+ };
1621
+ }
1622
+ for (const [fieldName, fieldSchema] of Object.entries(schema.fields)) {
1623
+ if (fieldSchema.required) {
1624
+ if (!(fieldName in objectValue)) {
1625
+ return {
1626
+ error: `Kind "${schema.kind}" is missing required field "${fieldName}".`,
1627
+ ...emptyOutcome
1628
+ };
1629
+ }
1630
+ continue;
1631
+ }
1632
+ if (!(fieldName in objectValue)) {
1633
+ optionalMissing.push(fieldName);
1634
+ }
1635
+ }
1636
+ for (const [fieldName, fieldValue] of Object.entries(objectValue)) {
1637
+ if (fieldName === KIND_KEY) continue;
1638
+ const fieldSchema = schema.fields[fieldName];
1639
+ if (!fieldSchema) {
1640
+ extraFields.push(fieldName);
1641
+ continue;
1642
+ }
1643
+ const error = this.validateFinalFieldValue(
1644
+ fieldSchema,
1645
+ fieldValue,
1646
+ fieldName,
1647
+ schema.kind
1648
+ );
1649
+ if (error) {
1650
+ return { error, optionalMissing, extraFields };
1651
+ }
1652
+ }
1653
+ return { error: null, optionalMissing, extraFields };
1654
+ }
1655
+ validateFinalFieldValue(fieldSchema, value, fieldName, objectKind) {
1656
+ if (fieldSchema.type === "json") return null;
1657
+ if (fieldSchema.type === "json[]") {
1658
+ if (value === null) {
1659
+ return fieldSchema.nullable ? null : `Field "${fieldName}" on kind "${objectKind}" cannot be null.`;
1660
+ }
1661
+ if (!Array.isArray(value)) {
1662
+ return `Field "${fieldName}" on kind "${objectKind}" must be an array.`;
1663
+ }
1664
+ return null;
1665
+ }
1666
+ if (isScalarArrayType(fieldSchema.type)) {
1667
+ if (!Array.isArray(value)) {
1668
+ return `Field "${fieldName}" on kind "${objectKind}" must be an array.`;
1669
+ }
1670
+ const itemType = scalarArrayItemType(fieldSchema.type);
1671
+ if (!value.every((item) => typeof item === itemType)) {
1672
+ return `Field "${fieldName}" on kind "${objectKind}" must be an array of ${itemType}s.`;
1673
+ }
1674
+ if (fieldSchema.type === "string[]" && fieldSchema.values !== void 0 && !fieldSchema.open) {
1675
+ const allowed = fieldSchema.values;
1676
+ const bad = value.find(
1677
+ (item) => typeof item === "string" && !allowed.includes(item)
1678
+ );
1679
+ if (bad !== void 0) {
1680
+ return `Field "${fieldName}" on kind "${objectKind}" items must be one of: ${allowed.join(", ")}.`;
1681
+ }
1682
+ }
1683
+ return null;
1684
+ }
1685
+ if (fieldSchema.type === "array") {
1686
+ if (!Array.isArray(value)) {
1687
+ return `Field "${fieldName}" on kind "${objectKind}" must be an array.`;
1688
+ }
1689
+ return null;
1690
+ }
1691
+ if (fieldSchema.type === "object") {
1692
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1693
+ return `Field "${fieldName}" on kind "${objectKind}" must be an object.`;
1694
+ }
1695
+ const nestedKind = readObjectKind(value);
1696
+ if (nestedKind !== fieldSchema.kind) {
1697
+ return `Field "${fieldName}" on kind "${objectKind}" must be kind "${fieldSchema.kind}".`;
1698
+ }
1699
+ const nestedSchema = this.lookupSchema(fieldSchema.kind);
1700
+ if (!nestedSchema) {
1701
+ return `Unknown nested kind "${fieldSchema.kind}" on field "${fieldName}".`;
1702
+ }
1703
+ return this.validateObjectAgainstSchema(
1704
+ value,
1705
+ nestedSchema
1706
+ ).error;
1707
+ }
1708
+ if (fieldSchema.type === "inline_object") {
1709
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1710
+ return `Field "${fieldName}" on kind "${objectKind}" must be an inline object.`;
1711
+ }
1712
+ return this.validateObjectAgainstFields(
1713
+ value,
1714
+ fieldSchema.fields
1715
+ ).error;
1716
+ }
1717
+ if (fieldSchema.type === "record") {
1718
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1719
+ return `Field "${fieldName}" on kind "${objectKind}" must be a record object.`;
1720
+ }
1721
+ return this.validateRecordObject(
1722
+ value,
1723
+ fieldSchema.values
1724
+ );
1725
+ }
1726
+ if (fieldSchema.type === "union") {
1727
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
1728
+ const kinds = fieldSchema.kinds ?? [];
1729
+ if (kinds.length === 0) {
1730
+ return `Field "${fieldName}" on kind "${objectKind}" must be ${fieldSchema.scalars.join(" | ")}.`;
1731
+ }
1732
+ const memberKind = readObjectKind(value);
1733
+ if (!memberKind || !kinds.includes(memberKind)) {
1734
+ return `Field "${fieldName}" on kind "${objectKind}" must be one of kinds: ${kinds.join(", ")}.`;
1735
+ }
1736
+ const memberSchema = this.lookupSchema(memberKind);
1737
+ if (!memberSchema) {
1738
+ return `Unknown union member kind "${memberKind}" on field "${fieldName}".`;
1739
+ }
1740
+ return this.validateObjectAgainstSchema(
1741
+ value,
1742
+ memberSchema
1743
+ ).error;
1744
+ }
1745
+ return this.validateScalarField(fieldSchema, value, fieldName);
1746
+ }
1747
+ if (fieldSchema.type === "string" || fieldSchema.type === "number" || fieldSchema.type === "boolean" || fieldSchema.type === "enum") {
1748
+ return this.validateScalarField(fieldSchema, value, fieldName);
1749
+ }
1750
+ return `Unsupported field schema for "${fieldName}".`;
1751
+ }
1752
+ validateValueAgainstField(fieldSchema, valueKind, value, fieldName) {
1753
+ if (fieldSchema.type === "json") {
1754
+ return null;
1755
+ }
1756
+ if (fieldSchema.type === "array" || fieldSchema.type === "json[]") {
1757
+ return valueKind === "array" ? null : `Field "${fieldName}" must be an array.`;
1758
+ }
1759
+ if (fieldSchema.type === "object" || fieldSchema.type === "inline_object") {
1760
+ return valueKind === "object" ? null : `Field "${fieldName}" must be an object.`;
1761
+ }
1762
+ if (fieldSchema.type === "record") {
1763
+ return valueKind === "object" ? null : `Field "${fieldName}" must be a record object.`;
1764
+ }
1765
+ if (isScalarArrayType(fieldSchema.type)) {
1766
+ return valueKind === "array" ? null : `Field "${fieldName}" must be an array.`;
1767
+ }
1768
+ if (fieldSchema.type === "union" && (fieldSchema.kinds?.length ?? 0) > 0) {
1769
+ if (valueKind === "object") return null;
1770
+ }
1771
+ if (valueKind !== "scalar") {
1772
+ return `Field "${fieldName}" must be a scalar.`;
1773
+ }
1774
+ return this.validateScalarField(fieldSchema, value, fieldName);
1775
+ }
1776
+ validateScalarField(fieldSchema, value, fieldName) {
1777
+ if (value === null) {
1778
+ return fieldSchema.nullable ? null : `Field "${fieldName}" cannot be null.`;
1779
+ }
1780
+ if (fieldSchema.type === "enum") {
1781
+ if (typeof value !== "string") {
1782
+ return `Field "${fieldName}" must be a string.`;
1783
+ }
1784
+ if (!fieldSchema.open && !fieldSchema.values.includes(value)) {
1785
+ return `Field "${fieldName}" must be one of: ${fieldSchema.values.join(", ")}.`;
1786
+ }
1787
+ return null;
1788
+ }
1789
+ if (fieldSchema.type === "union") {
1790
+ const valueType = typeof value;
1791
+ if (valueType !== "string" && valueType !== "number" && valueType !== "boolean") {
1792
+ return `Field "${fieldName}" must be ${fieldSchema.scalars.join(" | ")}.`;
1793
+ }
1794
+ if (!fieldSchema.scalars.includes(
1795
+ valueType
1796
+ )) {
1797
+ return `Field "${fieldName}" must be ${fieldSchema.scalars.join(" | ")}.`;
1798
+ }
1799
+ return null;
1800
+ }
1801
+ if (fieldSchema.type === "string" || fieldSchema.type === "number" || fieldSchema.type === "boolean") {
1802
+ if (typeof value !== fieldSchema.type) {
1803
+ return `Field "${fieldName}" must be ${fieldSchema.type}.`;
1804
+ }
1805
+ if (fieldSchema.type === "number" && typeof value === "number") {
1806
+ if (fieldSchema.min !== void 0 && value < fieldSchema.min) {
1807
+ return `Field "${fieldName}" must be >= ${fieldSchema.min}.`;
1808
+ }
1809
+ if (fieldSchema.max !== void 0 && value > fieldSchema.max) {
1810
+ return `Field "${fieldName}" must be <= ${fieldSchema.max}.`;
1811
+ }
1812
+ }
1813
+ return null;
1814
+ }
1815
+ return `Field "${fieldName}" is not a scalar.`;
1816
+ }
1817
+ validateRecordScalar(valueType, value, fieldName) {
1818
+ if (valueType === "json") return null;
1819
+ if (typeof value !== valueType) {
1820
+ return `Record field "${fieldName}" must be ${valueType}.`;
1821
+ }
1822
+ return null;
1823
+ }
1824
+ validateRecordObject(objectValue, valueType) {
1825
+ if (valueType === "json") return null;
1826
+ for (const [key, entry] of Object.entries(objectValue)) {
1827
+ if (typeof entry !== valueType) {
1828
+ return `Record key "${key}" must be ${valueType}.`;
1829
+ }
1830
+ }
1831
+ return null;
1832
+ }
1833
+ validateObjectAgainstFields(objectValue, fields) {
1834
+ const optionalMissing = [];
1835
+ const extraFields = [];
1836
+ const emptyOutcome = { optionalMissing, extraFields };
1837
+ for (const [fieldName, fieldSchema] of Object.entries(fields)) {
1838
+ if (fieldSchema.required) {
1839
+ if (!(fieldName in objectValue)) {
1840
+ return {
1841
+ error: `Inline object is missing required field "${fieldName}".`,
1842
+ ...emptyOutcome
1843
+ };
1844
+ }
1845
+ continue;
1846
+ }
1847
+ if (!(fieldName in objectValue)) {
1848
+ optionalMissing.push(fieldName);
1849
+ }
1850
+ }
1851
+ for (const [fieldName, fieldValue] of Object.entries(objectValue)) {
1852
+ const fieldSchema = fields[fieldName];
1853
+ if (!fieldSchema) {
1854
+ extraFields.push(fieldName);
1855
+ continue;
1856
+ }
1857
+ const error = this.validateFinalFieldValue(
1858
+ fieldSchema,
1859
+ fieldValue,
1860
+ fieldName,
1861
+ "inline_object"
1862
+ );
1863
+ if (error) {
1864
+ return { error, optionalMissing, extraFields };
1865
+ }
1866
+ }
1867
+ return { error: null, optionalMissing, extraFields };
1868
+ }
1869
+ registerObjectContext(path) {
1870
+ const fieldSchema = this.resolveParentFieldSchema(path);
1871
+ if (!fieldSchema) return;
1872
+ const pathKey = this.pathKey(path);
1873
+ if (fieldSchema.type === "inline_object") {
1874
+ this.inlineSchemas.set(pathKey, fieldSchema.fields);
1875
+ }
1876
+ if (fieldSchema.type === "record") {
1877
+ this.recordSchemas.set(pathKey, fieldSchema.values);
1878
+ }
1879
+ }
1880
+ resolveParentFieldSchema(path) {
1881
+ const fieldKey = this.fieldKeyFromPath(path);
1882
+ if (!fieldKey) return void 0;
1883
+ const parentPath = path.slice(0, -1);
1884
+ const parentKind = this.getObjectKindForPath(parentPath);
1885
+ if (!parentKind) return void 0;
1886
+ return this.lookupSchema(parentKind)?.fields[fieldKey];
1887
+ }
1888
+ getObjectKindForPath(path) {
1889
+ return this.objectKinds.get(this.pathKey(path)) ?? (path.length === 0 ? this.rootKind || null : null);
1890
+ }
1891
+ getDirectObjectKind(objectPath) {
1892
+ if (objectPath.length === 0) {
1893
+ return this.rootKind || null;
1894
+ }
1895
+ return this.objectKinds.get(this.pathKey(objectPath)) ?? null;
1896
+ }
1897
+ isAllowedSchemaField(objectPath, fieldKey, objectKind) {
1898
+ const pathKey = this.pathKey(objectPath);
1899
+ const inlineFields = this.inlineSchemas.get(pathKey);
1900
+ if (inlineFields) {
1901
+ return fieldKey in inlineFields;
1902
+ }
1903
+ if (this.recordSchemas.has(pathKey)) {
1904
+ return true;
1905
+ }
1906
+ const schema = this.lookupSchema(objectKind);
1907
+ return !!schema?.fields[fieldKey];
1908
+ }
1909
+ parentFieldName(path) {
1910
+ if (path.length === 0) return void 0;
1911
+ const parent = path[path.length - 2];
1912
+ return typeof parent === "string" ? parent : void 0;
1913
+ }
1914
+ fieldKeyFromPath(path) {
1915
+ const last = path[path.length - 1];
1916
+ return typeof last === "string" ? last : null;
1917
+ }
1918
+ isKindFieldPath(path) {
1919
+ return path[path.length - 1] === KIND_KEY;
1920
+ }
1921
+ pathKey(path) {
1922
+ return path.map((segment) => String(segment)).join(".");
1923
+ }
1924
+ lookupSchema(kind) {
1925
+ return this.resolver.get(kind) ?? this.arrivedSchemas.get(kind);
1926
+ }
1927
+ fail(reason, at) {
1928
+ if (this.failed) return;
1929
+ this.failed = true;
1930
+ this.emit({ type: "error", reason, at });
1931
+ }
1932
+ emit(event) {
1933
+ this.options.onEvent(event);
1934
+ }
1935
+ currentFrame() {
1936
+ return this.stack[this.stack.length - 1];
1937
+ }
1938
+ };
1939
+ function createKindStreamParser(options) {
1940
+ return new KindStreamParser(options);
1941
+ }
1942
+
1943
+ // core/fingerprint.ts
1944
+ var SEED_A = 2166136261;
1945
+ var SEED_B = 16777619;
1946
+ function fnv1aStep(hash, input) {
1947
+ let h = hash >>> 0;
1948
+ for (let i = 0; i < input.length; i++) {
1949
+ h ^= input.charCodeAt(i);
1950
+ h = h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24)) >>> 0;
1951
+ }
1952
+ return h >>> 0;
1953
+ }
1954
+ function createFingerprinter() {
1955
+ let a = SEED_A;
1956
+ let b = SEED_B;
1957
+ let length = 0;
1958
+ return {
1959
+ push(chunk) {
1960
+ a = fnv1aStep(a, chunk);
1961
+ b = fnv1aStep(b, chunk);
1962
+ length += chunk.length;
1963
+ },
1964
+ current() {
1965
+ return `${length.toString(36)}-${a.toString(36)}${b.toString(36)}`;
1966
+ }
1967
+ };
1968
+ }
1969
+ function fingerprintText(source) {
1970
+ const hasher = createFingerprinter();
1971
+ hasher.push(source);
1972
+ return hasher.current();
1973
+ }
1974
+
1975
+ // core/normalize.ts
1976
+ function isCanonicalBlockIR(value) {
1977
+ if (typeof value !== "object" || value === null) return false;
1978
+ const candidate = value;
1979
+ return candidate.v === IR_VERSION && typeof candidate.fingerprint === "string" && typeof candidate.engine === "string" && typeof candidate.root === "object" && candidate.root !== null && candidate.root.role === "structured";
1980
+ }
1981
+ function reuseEnvelopeIfCurrent(source, candidate) {
1982
+ if (!isCanonicalBlockIR(candidate)) return null;
1983
+ return candidate.fingerprint === fingerprintText(source) ? candidate : null;
1984
+ }
1985
+ function envelopeFromCompleteValue(value, kind, options) {
1986
+ return {
1987
+ v: IR_VERSION,
1988
+ engine: "fe-kind-parser",
1989
+ fingerprint: fingerprintText(JSON.stringify(value)),
1990
+ root: {
1991
+ role: "structured",
1992
+ kind,
1993
+ kindState: "resolved",
1994
+ discriminator: options?.discriminator ?? { format: "json", key: KIND_KEY },
1995
+ path: [],
1996
+ status: "complete",
1997
+ value,
1998
+ residue: null
1999
+ }
2000
+ };
2001
+ }
2002
+ function normalizeJsonRegion(source, options) {
2003
+ const reused = reuseEnvelopeIfCurrent(source, options.existing);
2004
+ if (reused) return reused;
2005
+ const tree = new IrTree();
2006
+ const parser = createKindStreamParser({
2007
+ schemas: options.schemas,
2008
+ ...options.expectedRootKind !== void 0 && {
2009
+ expectedRootKind: options.expectedRootKind
2010
+ },
2011
+ onEvent(event) {
2012
+ tree.applyEvent(event);
2013
+ }
2014
+ });
2015
+ parser.push(source);
2016
+ parser.end();
2017
+ return tree.buildEnvelope(fingerprintText(source));
2018
+ }
2019
+
2020
+ // core/envelope-cache.ts
2021
+ var IR_ENVELOPE_CACHE_VERSION = 1;
2022
+ function isRecord2(value) {
2023
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2024
+ }
2025
+ function isIrEnvelopeCache(value) {
2026
+ if (!isRecord2(value)) return false;
2027
+ if (value.v !== IR_ENVELOPE_CACHE_VERSION) return false;
2028
+ if (!isRecord2(value.blocks)) return false;
2029
+ const entries = Object.entries(value.blocks);
2030
+ if (entries.length === 0) return false;
2031
+ for (const [fingerprint, envelope] of entries) {
2032
+ if (!isCanonicalBlockIR(envelope)) return false;
2033
+ if (envelope.fingerprint !== fingerprint) return false;
2034
+ if (envelope.root.status !== "complete") return false;
2035
+ }
2036
+ return true;
2037
+ }
2038
+ function envelopeCacheFromEnvelopes(envelopes) {
2039
+ let blocks = null;
2040
+ for (const envelope of envelopes) {
2041
+ if (!isCanonicalBlockIR(envelope)) continue;
2042
+ if (envelope.root.status !== "complete") continue;
2043
+ (blocks ??= {})[envelope.fingerprint] = envelope;
2044
+ }
2045
+ return blocks ? { v: IR_ENVELOPE_CACHE_VERSION, blocks } : null;
2046
+ }
2047
+
2048
+ // core/envelope-read.ts
2049
+ function readEnvelope(metadata) {
2050
+ const candidate = metadata?.[IR_ENVELOPE_KEY];
2051
+ return isCanonicalBlockIR(candidate) ? candidate : null;
2052
+ }
2053
+ function classifyInboundEnvelopeMetadata(metadata) {
2054
+ if (!metadata || !(IR_ENVELOPE_KEY in metadata)) {
2055
+ return { outcome: "absent", metadata: metadata ?? void 0 };
2056
+ }
2057
+ const candidate = metadata[IR_ENVELOPE_KEY];
2058
+ if (isCanonicalBlockIR(candidate)) {
2059
+ return { outcome: "valid", metadata, envelope: candidate };
2060
+ }
2061
+ const engine = typeof candidate === "object" && candidate !== null && typeof candidate.engine === "string" ? candidate.engine : "unknown";
2062
+ const { [IR_ENVELOPE_KEY]: _dropped, ...rest } = metadata;
2063
+ return { outcome: "malformed", metadata: rest, engine, raw: candidate };
2064
+ }
2065
+ function sanitizeInboundEnvelopeMetadata(metadata, context, hooks = {}) {
2066
+ const verdict = classifyInboundEnvelopeMetadata(metadata);
2067
+ if (verdict.outcome === "valid") {
2068
+ hooks.seedEnvelope?.(verdict.envelope);
2069
+ return verdict.metadata;
2070
+ }
2071
+ if (verdict.outcome === "malformed") {
2072
+ hooks.reportMalformed?.({
2073
+ blockId: context.blockId,
2074
+ engine: verdict.engine,
2075
+ raw: verdict.raw
2076
+ });
2077
+ return verdict.metadata;
2078
+ }
2079
+ return verdict.metadata;
2080
+ }
2081
+
2082
+ // core/envelope-value.ts
2083
+ function isRecord3(value) {
2084
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2085
+ }
2086
+ function reconstructRegionValue(envelope) {
2087
+ const cloned = structuredClone(envelope.root.value);
2088
+ const applyExtras = (target, extras) => {
2089
+ if (!extras) return;
2090
+ for (const [key, value] of Object.entries(extras)) {
2091
+ target[key] = structuredClone(value);
2092
+ }
2093
+ };
2094
+ applyExtras(cloned, envelope.root.residue?.extra);
2095
+ for (const [pathKey, meta] of Object.entries(envelope.nodeIndex ?? {})) {
2096
+ const residue = meta.residue;
2097
+ if (!residue || isEmptyResidue(residue) || !residue.extra) continue;
2098
+ const segments = pathKey.split(".");
2099
+ let cursor = cloned;
2100
+ for (const segment of segments) {
2101
+ if (Array.isArray(cursor)) {
2102
+ cursor = cursor[Number(segment)];
2103
+ } else if (isRecord3(cursor)) {
2104
+ cursor = cursor[segment];
2105
+ } else {
2106
+ cursor = void 0;
2107
+ break;
2108
+ }
2109
+ }
2110
+ if (isRecord3(cursor)) {
2111
+ applyExtras(cursor, residue.extra);
2112
+ }
2113
+ }
2114
+ return cloned;
2115
+ }
2116
+ function stripKindDeep(value) {
2117
+ if (Array.isArray(value)) {
2118
+ return value.map(stripKindDeep);
2119
+ }
2120
+ if (isRecord3(value)) {
2121
+ const out = {};
2122
+ for (const [key, child] of Object.entries(value)) {
2123
+ if (key === KIND_KEY) continue;
2124
+ out[key] = stripKindDeep(child);
2125
+ }
2126
+ return out;
2127
+ }
2128
+ return value;
2129
+ }
2130
+
2131
+ // utils/text-case-converter.ts
2132
+ var DEFAULT_WORD_REPLACEMENTS = {
2133
+ // Acronyms & initialisms
2134
+ "api": "API",
2135
+ "apis": "APIs",
2136
+ "ui": "UI",
2137
+ "ux": "UX",
2138
+ "id": "ID",
2139
+ "ids": "IDs",
2140
+ "qr": "QR",
2141
+ "ssr": "SSR",
2142
+ "csr": "CSR",
2143
+ "ssg": "SSG",
2144
+ "isr": "ISR",
2145
+ "spa": "SPA",
2146
+ "pwa": "PWA",
2147
+ "sdk": "SDK",
2148
+ "sdks": "SDKs",
2149
+ "cli": "CLI",
2150
+ "tty": "TTY",
2151
+ "repl": "REPL",
2152
+ "ci": "CI",
2153
+ "cd": "CD",
2154
+ "cpu": "CPU",
2155
+ "cpus": "CPUs",
2156
+ "gpu": "GPU",
2157
+ "gpus": "GPUs",
2158
+ "ram": "RAM",
2159
+ "rom": "ROM",
2160
+ "ssd": "SSD",
2161
+ "ssds": "SSDs",
2162
+ "hdd": "HDD",
2163
+ "hdds": "HDDs",
2164
+ "kpi": "KPI",
2165
+ "kpis": "KPIs",
2166
+ "sla": "SLA",
2167
+ "slas": "SLAs",
2168
+ "slo": "SLO",
2169
+ "slos": "SLOs",
2170
+ "sli": "SLI",
2171
+ "slis": "SLIs",
2172
+ "dom": "DOM",
2173
+ // Web, formats, protocols
2174
+ "url": "URL",
2175
+ "urls": "URLs",
2176
+ "uri": "URI",
2177
+ "uris": "URIs",
2178
+ "http": "HTTP",
2179
+ "https": "HTTPS",
2180
+ "html": "HTML",
2181
+ "css": "CSS",
2182
+ "json": "JSON",
2183
+ "yaml": "YAML",
2184
+ "yml": "YML",
2185
+ "toml": "TOML",
2186
+ "csv": "CSV",
2187
+ "pdf": "PDF",
2188
+ "tsv": "TSV",
2189
+ "jpg": "JPG",
2190
+ "jpeg": "JPEG",
2191
+ "png": "PNG",
2192
+ "gif": "GIF",
2193
+ "webp": "WebP",
2194
+ "heic": "HEIC",
2195
+ "heif": "HEIF",
2196
+ "bmp": "BMP",
2197
+ "tiff": "TIFF",
2198
+ "ico": "ICO",
2199
+ "xml": "XML",
2200
+ "sql": "SQL",
2201
+ "db": "DB",
2202
+ "dbs": "DBs",
2203
+ "nosql": "NoSQL",
2204
+ "graphql": "GraphQL",
2205
+ "grpc": "gRPC",
2206
+ "rest": "REST",
2207
+ "restful": "RESTful",
2208
+ "websocket": "WebSocket",
2209
+ "websockets": "WebSockets",
2210
+ "webrtc": "WebRTC",
2211
+ // Networking
2212
+ "ip": "IP",
2213
+ "ipv4": "IPv4",
2214
+ "ipv6": "IPv6",
2215
+ "dns": "DNS",
2216
+ "dhcp": "DHCP",
2217
+ "nat": "NAT",
2218
+ "tcp": "TCP",
2219
+ "udp": "UDP",
2220
+ "icmp": "ICMP",
2221
+ "ttl": "TTL",
2222
+ "lan": "LAN",
2223
+ "wan": "WAN",
2224
+ "vlan": "VLAN",
2225
+ "cdn": "CDN",
2226
+ "ftp": "FTP",
2227
+ "ssh": "SSH",
2228
+ "tls": "TLS",
2229
+ "ssl": "SSL",
2230
+ // Security & crypto
2231
+ "jwt": "JWT",
2232
+ "jws": "JWS",
2233
+ "jwe": "JWE",
2234
+ "hmac": "HMAC",
2235
+ "rsa": "RSA",
2236
+ "ecdsa": "ECDSA",
2237
+ "aes": "AES",
2238
+ "pbkdf2": "PBKDF2",
2239
+ "argon2": "Argon2",
2240
+ "scrypt": "scrypt",
2241
+ "totp": "TOTP",
2242
+ "hotp": "HOTP",
2243
+ "mfa": "MFA",
2244
+ "2fa": "2FA",
2245
+ "csrf": "CSRF",
2246
+ "xss": "XSS",
2247
+ "ssrf": "SSRF",
2248
+ "rce": "RCE",
2249
+ "dos": "DoS",
2250
+ "ddos": "DDoS",
2251
+ "mitm": "MITM",
2252
+ "csp": "CSP",
2253
+ "cors": "CORS",
2254
+ "pii": "PII",
2255
+ "phi": "PHI",
2256
+ "gdpr": "GDPR",
2257
+ "ccpa": "CCPA",
2258
+ "hipaa": "HIPAA",
2259
+ "rfc": "RFC",
2260
+ // Platforms, langs, tools (single-token)
2261
+ "javascript": "JavaScript",
2262
+ "typescript": "TypeScript",
2263
+ "jsx": "JSX",
2264
+ "tsx": "TSX",
2265
+ "node": "Node",
2266
+ // (used when tokenized alone)
2267
+ "deno": "Deno",
2268
+ "bun": "Bun",
2269
+ "react": "React",
2270
+ "nextjs": "Next.js",
2271
+ // if your tokenizer drops dots, keep this
2272
+ "nodejs": "Node.js",
2273
+ "postgresql": "PostgreSQL",
2274
+ "postgres": "Postgres",
2275
+ "mysql": "MySQL",
2276
+ "sqlite": "SQLite",
2277
+ "redis": "Redis",
2278
+ "supabase": "Supabase",
2279
+ "docker": "Docker",
2280
+ "kubernetes": "Kubernetes",
2281
+ "k8s": "Kubernetes",
2282
+ "helm": "Helm",
2283
+ "npm": "npm",
2284
+ "pnpm": "pnpm",
2285
+ "yarn": "Yarn",
2286
+ "eslint": "ESLint",
2287
+ "prettier": "Prettier",
2288
+ "vite": "Vite",
2289
+ "webpack": "Webpack",
2290
+ "babel": "Babel",
2291
+ // OS & vendors
2292
+ "macos": "macOS",
2293
+ "ios": "iOS",
2294
+ "ipados": "iPadOS",
2295
+ "watchos": "watchOS",
2296
+ "tvos": "tvOS",
2297
+ "windows": "Windows",
2298
+ "linux": "Linux",
2299
+ "ubuntu": "Ubuntu",
2300
+ "github": "GitHub",
2301
+ "gitlab": "GitLab",
2302
+ "bitbucket": "Bitbucket",
2303
+ // Data & analytics
2304
+ "etl": "ETL",
2305
+ "elt": "ELT",
2306
+ "olap": "OLAP",
2307
+ "oltp": "OLTP",
2308
+ "bi": "BI",
2309
+ // Time & locales
2310
+ "utc": "UTC",
2311
+ "gmt": "GMT",
2312
+ "pst": "PST",
2313
+ "pdt": "PDT",
2314
+ "pt": "PT",
2315
+ // Common “small words” to keep lowercase (unless first/last word)
2316
+ "or": "or",
2317
+ "and": "and",
2318
+ "the": "the",
2319
+ "of": "of",
2320
+ "in": "in",
2321
+ "to": "to",
2322
+ "with": "with",
2323
+ "as": "as",
2324
+ "by": "by",
2325
+ "for": "for",
2326
+ "on": "on",
2327
+ "at": "at",
2328
+ "up": "up",
2329
+ "a": "a",
2330
+ "an": "an",
2331
+ "is": "is",
2332
+ "are": "are",
2333
+ "was": "was",
2334
+ "were": "were",
2335
+ "be": "be",
2336
+ "but": "but",
2337
+ "nor": "nor",
2338
+ "so": "so",
2339
+ "yet": "yet",
2340
+ "per": "per",
2341
+ "via": "via",
2342
+ // Latin abbreviations (tokenized as words in some pipelines)
2343
+ "eg": "e.g.",
2344
+ "ie": "i.e.",
2345
+ "etc": "etc.",
2346
+ "aka": "aka",
2347
+ "vs": "vs.",
2348
+ "v": "v.",
2349
+ // Client abbreviations
2350
+ "CIC": "CIC",
2351
+ "AGR": "AGR",
2352
+ "AGER": "AGER",
2353
+ "DD": "DD",
2354
+ "TS": "TS",
2355
+ "TM": "TM",
2356
+ "arman": "Arman"
2357
+ };
2358
+ var DEFAULT_OPTIONS = {
2359
+ textCase: "title",
2360
+ wordReplacements: DEFAULT_WORD_REPLACEMENTS,
2361
+ trim: true
2362
+ };
2363
+ function formatText(text, options = {}) {
2364
+ const opts = { ...DEFAULT_OPTIONS, ...options };
2365
+ if (!text) return "";
2366
+ let normalized = text.replace(/_/g, " ").replace(/-/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").replace(/\s+/g, " ");
2367
+ if (opts.trim) {
2368
+ normalized = normalized.trim();
2369
+ }
2370
+ let caseTransformed = normalized;
2371
+ switch (opts.textCase) {
2372
+ case "title":
2373
+ caseTransformed = normalized.replace(
2374
+ /\w\S*/g,
2375
+ (word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
2376
+ );
2377
+ break;
2378
+ case "sentence":
2379
+ if (normalized.length > 0) {
2380
+ caseTransformed = normalized.charAt(0).toUpperCase() + normalized.slice(1).toLowerCase();
2381
+ }
2382
+ break;
2383
+ case "lower":
2384
+ caseTransformed = normalized.toLowerCase();
2385
+ break;
2386
+ case "upper":
2387
+ caseTransformed = normalized.toUpperCase();
2388
+ break;
2389
+ }
2390
+ let result = caseTransformed;
2391
+ if (opts.wordReplacements) {
2392
+ Object.entries(opts.wordReplacements).forEach(([key, value]) => {
2393
+ const regex = new RegExp(`\\b${key}\\b`, "gi");
2394
+ result = result.replace(regex, value);
2395
+ });
2396
+ }
2397
+ return result;
2398
+ }
2399
+
2400
+ // core/schema-structure.ts
2401
+ function formatBlockLabel(key) {
2402
+ return formatText(key, { textCase: "title" });
2403
+ }
2404
+ function schemaStructureDepth(schema, allSchemas, visiting = /* @__PURE__ */ new Set()) {
2405
+ if (visiting.has(schema.kind)) return 0;
2406
+ visiting.add(schema.kind);
2407
+ let max = 0;
2408
+ for (const field of Object.values(schema.fields)) {
2409
+ max = Math.max(max, fieldStructureDepth(field, allSchemas, visiting));
2410
+ }
2411
+ visiting.delete(schema.kind);
2412
+ return max;
2413
+ }
2414
+ function fieldStructureDepth(field, allSchemas, visiting) {
2415
+ switch (field.type) {
2416
+ case "array": {
2417
+ let itemMax = 0;
2418
+ for (const itemKind of field.itemKinds) {
2419
+ const itemSchema = allSchemas[itemKind];
2420
+ itemMax = Math.max(
2421
+ itemMax,
2422
+ itemSchema ? 1 + schemaStructureDepth(itemSchema, allSchemas, visiting) : 1
2423
+ );
2424
+ }
2425
+ return itemMax;
2426
+ }
2427
+ case "object": {
2428
+ const ref = allSchemas[field.kind];
2429
+ return ref ? 1 + schemaStructureDepth(ref, allSchemas, visiting) : 1;
2430
+ }
2431
+ case "inline_object": {
2432
+ let nested = 0;
2433
+ for (const child of Object.values(field.fields)) {
2434
+ nested = Math.max(
2435
+ nested,
2436
+ fieldStructureDepth(child, allSchemas, visiting)
2437
+ );
2438
+ }
2439
+ return nested > 0 ? 1 + nested : 1;
2440
+ }
2441
+ default:
2442
+ return 0;
2443
+ }
2444
+ }
2445
+ function schemaLayoutMode(schema, allSchemas) {
2446
+ const depth = schemaStructureDepth(schema, allSchemas);
2447
+ if (depth <= 0) return "flat";
2448
+ if (depth === 1) return "grid";
2449
+ return "nested";
2450
+ }
2451
+
2452
+ exports.IR_ENVELOPE_CACHE_VERSION = IR_ENVELOPE_CACHE_VERSION;
2453
+ exports.IR_ENVELOPE_KEY = IR_ENVELOPE_KEY;
2454
+ exports.IR_VERSION = IR_VERSION;
2455
+ exports.IrTree = IrTree;
2456
+ exports.JSON_DISCRIMINATOR = JSON_DISCRIMINATOR;
2457
+ exports.JsonStreamTokenizer = JsonStreamTokenizer;
2458
+ exports.KIND_KEY = KIND_KEY;
2459
+ exports.KindStreamParser = KindStreamParser;
2460
+ exports.buildCompliantKindSnapshot = buildCompliantKindSnapshot;
2461
+ exports.classifyInboundEnvelopeMetadata = classifyInboundEnvelopeMetadata;
2462
+ exports.createFingerprinter = createFingerprinter;
2463
+ exports.createKindStreamParser = createKindStreamParser;
2464
+ exports.emptyValueForFieldSchema = emptyValueForFieldSchema;
2465
+ exports.envelopeCacheFromEnvelopes = envelopeCacheFromEnvelopes;
2466
+ exports.envelopeFromCompleteValue = envelopeFromCompleteValue;
2467
+ exports.fenceDiscriminator = fenceDiscriminator;
2468
+ exports.fingerprintText = fingerprintText;
2469
+ exports.formatBlockLabel = formatBlockLabel;
2470
+ exports.irPathIsUnderOrEqual = irPathIsUnderOrEqual;
2471
+ exports.irPathKey = irPathKey;
2472
+ exports.irPathLabel = irPathLabel;
2473
+ exports.irPathsEqual = irPathsEqual;
2474
+ exports.isCanonicalBlockIR = isCanonicalBlockIR;
2475
+ exports.isEmptyResidue = isEmptyResidue;
2476
+ exports.isIrEnvelopeCache = isIrEnvelopeCache;
2477
+ exports.isJsonAnyField = isJsonAnyField;
2478
+ exports.isScalarArrayType = isScalarArrayType;
2479
+ exports.mergeResidueIntoValue = mergeResidueIntoValue;
2480
+ exports.normalizeJsonRegion = normalizeJsonRegion;
2481
+ exports.readEnvelope = readEnvelope;
2482
+ exports.readObjectKind = readObjectKind;
2483
+ exports.reconstructRegionValue = reconstructRegionValue;
2484
+ exports.reuseEnvelopeIfCurrent = reuseEnvelopeIfCurrent;
2485
+ exports.sanitizeInboundEnvelopeMetadata = sanitizeInboundEnvelopeMetadata;
2486
+ exports.scalarArrayItemType = scalarArrayItemType;
2487
+ exports.schemaLayoutMode = schemaLayoutMode;
2488
+ exports.schemaStructureDepth = schemaStructureDepth;
2489
+ exports.setJsonRootKeyLookup = setJsonRootKeyLookup;
2490
+ exports.stripKindDeep = stripKindDeep;
2491
+ exports.xmlDiscriminator = xmlDiscriminator;
2492
+ //# sourceMappingURL=core.cjs.map
2493
+ //# sourceMappingURL=core.cjs.map