@3leaps/yamlprims 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -19,6 +19,9 @@ export const MAX_WASM_MEMORY_BYTES = 128 * 1024 * 1024;
19
19
  export const MAX_WASM_MEMORY_PAGES = 2048;
20
20
  export const WASM_HIGH_WATER_RECYCLE_BYTES = 16 * 1024 * 1024;
21
21
  export const MAX_SAFE_METADATA_INT = 9_007_199_254_740_991; // 2^53 - 1
22
+ export const DEFAULT_IJSON_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
23
+ export const DEFAULT_EMIT_MAX_TAG_BYTES = 1_024;
24
+ export const DEFAULT_EMIT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
22
25
  export const I128_MIN = -170141183460469231731687303715884105728n;
23
26
  export const I128_MAX = 170141183460469231731687303715884105727n;
24
27
  export const U128_MAX = 340282366920938463463374607431768211455n;
@@ -343,6 +346,163 @@ export function validateOptions(options) {
343
346
  }
344
347
  return { mergeKeys, unknownTags, limits };
345
348
  }
349
+ export function defaultIjsonOptions() {
350
+ return {
351
+ mergeKeys: "reject",
352
+ unknownTags: "reject",
353
+ limits: {
354
+ ...defaultLimits(),
355
+ maxOutputBytes: DEFAULT_IJSON_MAX_OUTPUT_BYTES,
356
+ },
357
+ };
358
+ }
359
+ export function validateIjsonOptions(options) {
360
+ if (options === undefined) {
361
+ return defaultIjsonOptions();
362
+ }
363
+ if (typeof options !== "object" || options === null || Array.isArray(options)) {
364
+ throw invalidOptionsError("options must be an object");
365
+ }
366
+ const hasMaxOut = options.limits !== undefined &&
367
+ typeof options.limits === "object" &&
368
+ options.limits !== null &&
369
+ (options.limits.maxOutputBytes !== undefined || options.limits.max_output_bytes !== undefined);
370
+ const hasUnknownTags = options.unknownTags !== undefined || options.unknown_tags !== undefined;
371
+ const validated = validateOptions(options);
372
+ return {
373
+ mergeKeys: validated.mergeKeys,
374
+ unknownTags: hasUnknownTags ? validated.unknownTags : "reject",
375
+ limits: {
376
+ ...validated.limits,
377
+ maxOutputBytes: hasMaxOut ? validated.limits.maxOutputBytes : DEFAULT_IJSON_MAX_OUTPUT_BYTES,
378
+ },
379
+ };
380
+ }
381
+ export function defaultEmitLimits() {
382
+ return {
383
+ maxDepth: 128,
384
+ maxNodes: 250_000,
385
+ maxScalarBytes: 1 * 1024 * 1024,
386
+ maxKeyBytes: 64 * 1024,
387
+ maxMappingEntries: 100_000,
388
+ maxTagBytes: DEFAULT_EMIT_MAX_TAG_BYTES,
389
+ maxDocuments: 1_024,
390
+ maxOutputBytes: DEFAULT_EMIT_MAX_OUTPUT_BYTES,
391
+ };
392
+ }
393
+ export function defaultEmitOptions() {
394
+ return {
395
+ compatQuoting: "yaml11_safe",
396
+ limits: defaultEmitLimits(),
397
+ };
398
+ }
399
+ const KNOWN_EMIT_OPTION_KEYS = new Set([
400
+ "compatQuoting",
401
+ "compat_quoting",
402
+ "limits",
403
+ ]);
404
+ const KNOWN_EMIT_LIMIT_KEYS = new Set([
405
+ "maxDepth",
406
+ "maxNodes",
407
+ "maxScalarBytes",
408
+ "maxKeyBytes",
409
+ "maxMappingEntries",
410
+ "maxTagBytes",
411
+ "maxDocuments",
412
+ "maxOutputBytes",
413
+ "max_depth",
414
+ "max_nodes",
415
+ "max_scalar_bytes",
416
+ "max_key_bytes",
417
+ "max_mapping_entries",
418
+ "max_tag_bytes",
419
+ "max_documents",
420
+ "max_output_bytes",
421
+ ]);
422
+ function pickEmitLimit(input, camel, snake, fallback) {
423
+ if (!input)
424
+ return fallback;
425
+ const c = input[camel];
426
+ const s = input[snake];
427
+ if (c !== undefined && s !== undefined && c !== s) {
428
+ throw invalidOptionsError(`conflicting emit limit values for ${String(camel)}`);
429
+ }
430
+ const chosen = c !== undefined ? c : s !== undefined ? s : fallback;
431
+ if (typeof chosen !== "number" || !Number.isInteger(chosen) || !Number.isSafeInteger(chosen)) {
432
+ throw invalidOptionsError(`emit limit ${String(camel)} must be a safe integer`);
433
+ }
434
+ return chosen;
435
+ }
436
+ export function validateEmitOptions(options) {
437
+ if (options === undefined) {
438
+ return defaultEmitOptions();
439
+ }
440
+ if (typeof options !== "object" || options === null || Array.isArray(options)) {
441
+ throw invalidOptionsError("emit options must be an object");
442
+ }
443
+ for (const k of Object.keys(options)) {
444
+ if (!KNOWN_EMIT_OPTION_KEYS.has(k)) {
445
+ throw invalidOptionsError(`unknown emit option key: ${k}`);
446
+ }
447
+ }
448
+ if (options.compatQuoting !== undefined &&
449
+ options.compat_quoting !== undefined &&
450
+ options.compatQuoting !== options.compat_quoting) {
451
+ throw invalidOptionsError("conflicting compatQuoting options");
452
+ }
453
+ const rawCq = options.compatQuoting ?? options.compat_quoting ?? "yaml11_safe";
454
+ const compatQuoting = rawCq === "yaml11-safe" ? "yaml11_safe" : rawCq === "core-only" ? "core_only" : rawCq;
455
+ if (compatQuoting !== "yaml11_safe" && compatQuoting !== "core_only") {
456
+ throw invalidOptionsError("invalid compatQuoting option");
457
+ }
458
+ const limIn = options.limits;
459
+ if (limIn !== undefined) {
460
+ if (typeof limIn !== "object" || limIn === null || Array.isArray(limIn)) {
461
+ throw invalidOptionsError("emit limits must be an object");
462
+ }
463
+ for (const k of Object.keys(limIn)) {
464
+ if (!KNOWN_EMIT_LIMIT_KEYS.has(k)) {
465
+ throw invalidOptionsError(`unknown emit limit key: ${k}`);
466
+ }
467
+ }
468
+ }
469
+ const def = defaultEmitLimits();
470
+ const limits = {
471
+ maxDepth: pickEmitLimit(limIn, "maxDepth", "max_depth", def.maxDepth),
472
+ maxNodes: pickEmitLimit(limIn, "maxNodes", "max_nodes", def.maxNodes),
473
+ maxScalarBytes: pickEmitLimit(limIn, "maxScalarBytes", "max_scalar_bytes", def.maxScalarBytes),
474
+ maxKeyBytes: pickEmitLimit(limIn, "maxKeyBytes", "max_key_bytes", def.maxKeyBytes),
475
+ maxMappingEntries: pickEmitLimit(limIn, "maxMappingEntries", "max_mapping_entries", def.maxMappingEntries),
476
+ maxTagBytes: pickEmitLimit(limIn, "maxTagBytes", "max_tag_bytes", def.maxTagBytes),
477
+ maxDocuments: pickEmitLimit(limIn, "maxDocuments", "max_documents", def.maxDocuments),
478
+ maxOutputBytes: pickEmitLimit(limIn, "maxOutputBytes", "max_output_bytes", def.maxOutputBytes),
479
+ };
480
+ const all = [
481
+ limits.maxDepth,
482
+ limits.maxNodes,
483
+ limits.maxScalarBytes,
484
+ limits.maxKeyBytes,
485
+ limits.maxMappingEntries,
486
+ limits.maxTagBytes,
487
+ limits.maxDocuments,
488
+ limits.maxOutputBytes,
489
+ ];
490
+ if (all.some((v) => v < 1)) {
491
+ throw invalidOptionsError("every emit limit must be at least 1");
492
+ }
493
+ if (limits.maxDepth > 255) {
494
+ throw invalidOptionsError("max_depth must be at most 255");
495
+ }
496
+ if (limits.maxScalarBytes > limits.maxOutputBytes || limits.maxKeyBytes > limits.maxOutputBytes) {
497
+ throw invalidOptionsError("max_scalar_bytes and max_key_bytes must not exceed max_output_bytes");
498
+ }
499
+ return { compatQuoting, limits };
500
+ }
501
+ function serializeWasmEmitOptions(opts) {
502
+ const l = opts.limits;
503
+ const json = `{"compat_quoting":"${opts.compatQuoting}","limits":{"max_depth":${clampU32(l.maxDepth)},"max_nodes":${clampU32(l.maxNodes)},"max_scalar_bytes":${clampU32(l.maxScalarBytes)},"max_key_bytes":${clampU32(l.maxKeyBytes)},"max_mapping_entries":${clampU32(l.maxMappingEntries)},"max_tag_bytes":${clampU32(l.maxTagBytes)},"max_documents":${clampU32(l.maxDocuments)},"max_output_bytes":${clampU32(l.maxOutputBytes)}}}`;
504
+ return encoder.encode(json);
505
+ }
346
506
  function isDefaultOptions(opts) {
347
507
  const def = defaultOptions();
348
508
  return (opts.mergeKeys === def.mergeKeys &&
@@ -365,8 +525,8 @@ const decoder = new TextDecoder("utf-8", { fatal: true });
365
525
  function clampU32(n) {
366
526
  return n > 0xffffffff ? 0xffffffff : n;
367
527
  }
368
- function serializeWasmOptions(opts) {
369
- if (isDefaultOptions(opts)) {
528
+ function serializeWasmOptions(opts, alwaysSerialize = false) {
529
+ if (!alwaysSerialize && isDefaultOptions(opts)) {
370
530
  return new Uint8Array(0);
371
531
  }
372
532
  const l = opts.limits;
@@ -453,7 +613,7 @@ function runWasmLoad(inputBytes, opts, mode, simulateTrap = false) {
453
613
  if (instanceBusy) {
454
614
  throw notSourceError("internal", {}, "reentrant WASM execution is forbidden");
455
615
  }
456
- const optsBytes = serializeWasmOptions(opts);
616
+ const optsBytes = serializeWasmOptions(opts, mode === "ijson");
457
617
  const exports = getWasmExports();
458
618
  instanceBusy = true;
459
619
  let localTrapped = false;
@@ -499,7 +659,9 @@ function runWasmLoad(inputBytes, opts, mode, simulateTrap = false) {
499
659
  }
500
660
  const status = mode === "plain"
501
661
  ? exports.load_plain(inputBytes.byteLength, optsBytes.byteLength) >>> 0
502
- : exports.load_wire(inputBytes.byteLength, optsBytes.byteLength, mode === "wire-single" ? 1 : 0) >>> 0;
662
+ : mode === "ijson"
663
+ ? exports.load_ijson(inputBytes.byteLength, optsBytes.byteLength) >>> 0
664
+ : exports.load_wire(inputBytes.byteLength, optsBytes.byteLength, mode === "wire-single" ? 1 : 0) >>> 0;
503
665
  const outPtr = exports.output_ptr() >>> 0;
504
666
  const outLen = exports.output_len() >>> 0;
505
667
  const output = new Uint8Array(exports.memory.buffer, outPtr, outLen).slice();
@@ -526,6 +688,63 @@ function runWasmLoad(inputBytes, opts, mode, simulateTrap = false) {
526
688
  }
527
689
  }
528
690
  }
691
+ function runWasmEmit(wireBytes, opts) {
692
+ if (instanceBusy) {
693
+ throw notSourceError("internal", {}, "reentrant WASM execution is forbidden");
694
+ }
695
+ const optsBytes = serializeWasmEmitOptions(opts);
696
+ const exports = getWasmExports();
697
+ instanceBusy = true;
698
+ let localTrapped = false;
699
+ try {
700
+ const optPtr = exports.options_reserve(optsBytes.byteLength) >>> 0;
701
+ if (optPtr === 0) {
702
+ if (optsBytes.byteLength > MAX_OPTIONS_BYTES) {
703
+ throw invalidOptionsError("emit options payload exceeds WASM options limit");
704
+ }
705
+ activeInstance = null;
706
+ throw notSourceError("internal", {}, "WASM options reservation failed (linear memory ceiling exceeded)");
707
+ }
708
+ if (optsBytes.byteLength > 0) {
709
+ new Uint8Array(exports.memory.buffer, optPtr, optsBytes.byteLength).set(optsBytes);
710
+ }
711
+ const inPtr = exports.input_reserve(wireBytes.byteLength, MAX_WASM_INPUT_CEILING) >>> 0;
712
+ if (inPtr === 0) {
713
+ if (wireBytes.byteLength > MAX_WASM_INPUT_CEILING) {
714
+ throw notSourceError("limit_exceeded", { limit: "max_input_bytes", configured: MAX_WASM_INPUT_CEILING }, `WASM emission wire envelope exceeds ${MAX_WASM_INPUT_CEILING} bytes`);
715
+ }
716
+ activeInstance = null;
717
+ throw notSourceError("internal", {}, "WASM input reservation failed (linear memory ceiling exceeded)");
718
+ }
719
+ if (wireBytes.byteLength > 0) {
720
+ new Uint8Array(exports.memory.buffer, inPtr, wireBytes.byteLength).set(wireBytes);
721
+ }
722
+ const status = exports.emit_wire(wireBytes.byteLength, optsBytes.byteLength) >>> 0;
723
+ const outPtr = exports.output_ptr() >>> 0;
724
+ const outLen = exports.output_len() >>> 0;
725
+ const output = new Uint8Array(exports.memory.buffer, outPtr, outLen).slice();
726
+ return { status, output };
727
+ }
728
+ catch (err) {
729
+ if (err instanceof WebAssembly.RuntimeError) {
730
+ localTrapped = true;
731
+ instanceTrapped = true;
732
+ activeInstance = null;
733
+ throw notSourceError("internal", {}, `WASM runtime trap: ${err.message}`);
734
+ }
735
+ throw err;
736
+ }
737
+ finally {
738
+ instanceBusy = false;
739
+ if (!localTrapped && !instanceTrapped && activeInstance !== null) {
740
+ exports.release();
741
+ releaseCallCount += 1;
742
+ if (exports.memory.buffer.byteLength > WASM_HIGH_WATER_RECYCLE_BYTES) {
743
+ activeInstance = null;
744
+ }
745
+ }
746
+ }
747
+ }
529
748
  function createWasmTestHarness() {
530
749
  return {
531
750
  module: wasmModule,
@@ -736,129 +955,727 @@ export function containsNan(node) {
736
955
  }
737
956
  return false;
738
957
  }
739
- export function keyEq(a, b) {
740
- if (a.kind !== b.kind)
741
- return false;
742
- switch (a.kind) {
743
- case "null":
744
- return true;
745
- case "bool":
746
- return a.value === b.value;
747
- case "int":
748
- return a.value === b.value;
749
- case "float": {
750
- const bf = b;
751
- if (Number.isNaN(a.value) || Number.isNaN(bf.value))
958
+ const CORE_TAG_URIS = new Set([
959
+ "tag:yaml.org,2002:null",
960
+ "tag:yaml.org,2002:bool",
961
+ "tag:yaml.org,2002:int",
962
+ "tag:yaml.org,2002:float",
963
+ "tag:yaml.org,2002:str",
964
+ "tag:yaml.org,2002:seq",
965
+ "tag:yaml.org,2002:map",
966
+ ]);
967
+ function isTagUriByte(b) {
968
+ return ((b >= 0x30 && b <= 0x39) ||
969
+ (b >= 0x41 && b <= 0x5a) ||
970
+ (b >= 0x61 && b <= 0x7a) ||
971
+ b === 0x2d || // -
972
+ b === 0x3b || // ;
973
+ b === 0x2f || // /
974
+ b === 0x3f || // ?
975
+ b === 0x3a || // :
976
+ b === 0x40 || // @
977
+ b === 0x26 || // &
978
+ b === 0x3d || // =
979
+ b === 0x2b || // +
980
+ b === 0x24 || // $
981
+ b === 0x2c || // ,
982
+ b === 0x5f || // _
983
+ b === 0x2e || // .
984
+ b === 0x21 || // !
985
+ b === 0x7e || // ~
986
+ b === 0x2a || // *
987
+ b === 0x27 || // '
988
+ b === 0x28 || // (
989
+ b === 0x29 || // )
990
+ b === 0x5b || // [
991
+ b === 0x5d || // ]
992
+ b === 0x23 // #
993
+ );
994
+ }
995
+ function isValidTagChars(s) {
996
+ const bytes = encoder.encode(s);
997
+ let i = 0;
998
+ while (i < bytes.length) {
999
+ const b = bytes[i];
1000
+ if (b === 0x25) {
1001
+ if (i + 2 >= bytes.length)
752
1002
  return false;
753
- return normFloatBits(a.value) === normFloatBits(bf.value);
754
- }
755
- case "string":
756
- return a.value === b.value;
757
- case "sequence": {
758
- const bs = b;
759
- if (a.items.length !== bs.items.length)
1003
+ const h1 = bytes[i + 1];
1004
+ const h2 = bytes[i + 2];
1005
+ const isHex1 = (h1 >= 0x30 && h1 <= 0x39) || (h1 >= 0x41 && h1 <= 0x46) || (h1 >= 0x61 && h1 <= 0x66);
1006
+ const isHex2 = (h2 >= 0x30 && h2 <= 0x39) || (h2 >= 0x41 && h2 <= 0x46) || (h2 >= 0x61 && h2 <= 0x66);
1007
+ if (!isHex1 || !isHex2)
760
1008
  return false;
761
- for (let i = 0; i < a.items.length; i++) {
762
- if (!keyEq(a.items[i], bs.items[i]))
763
- return false;
764
- }
765
- return true;
1009
+ i += 3;
1010
+ continue;
766
1011
  }
767
- case "mapping": {
768
- const bm = b;
769
- if (a.entries.length !== bm.entries.length)
1012
+ if (b < 0x80) {
1013
+ if (!isTagUriByte(b))
770
1014
  return false;
771
- const used = new Uint8Array(bm.entries.length);
772
- for (const [ak, av] of a.entries) {
773
- let found = false;
774
- for (let j = 0; j < bm.entries.length; j++) {
775
- if (used[j])
776
- continue;
777
- const [bk, bv] = bm.entries[j];
778
- if (keyEq(ak, bk)) {
779
- if (!keyEq(av, bv))
780
- return false;
781
- used[j] = 1;
782
- found = true;
783
- break;
784
- }
785
- }
786
- if (!found)
787
- return false;
788
- }
789
- return true;
1015
+ i += 1;
1016
+ continue;
790
1017
  }
791
- case "tagged": {
792
- const bt = b;
793
- return a.tag.uri === bt.tag.uri && keyEq(a.value, bt.value);
1018
+ i += 1;
1019
+ }
1020
+ for (const cp of s) {
1021
+ const code = cp.codePointAt(0);
1022
+ if (code <= 0x20 ||
1023
+ (code >= 0x7f && code <= 0x9f) ||
1024
+ code === 0xfeff ||
1025
+ code === 0xfffe ||
1026
+ code === 0xffff) {
1027
+ return false;
794
1028
  }
795
1029
  }
1030
+ return true;
796
1031
  }
797
- export function mappingGet(mapping, key) {
798
- const entries = Array.isArray(mapping) ? mapping : mapping.entries;
799
- if (typeof key === "string") {
800
- for (const [k, v] of entries) {
801
- if (k.kind === "string" && k.value === key) {
802
- return v;
803
- }
804
- }
805
- return undefined;
1032
+ function isValidTagHandle(handle) {
1033
+ if (handle === "" || handle === "!" || handle === "!!")
1034
+ return true;
1035
+ if (handle.length < 3 || !handle.startsWith("!") || !handle.endsWith("!"))
1036
+ return false;
1037
+ const inner = handle.slice(1, -1);
1038
+ for (let i = 0; i < inner.length; i++) {
1039
+ const c = inner.charCodeAt(i);
1040
+ const ok = (c >= 0x30 && c <= 0x39) ||
1041
+ (c >= 0x41 && c <= 0x5a) ||
1042
+ (c >= 0x61 && c <= 0x7a) ||
1043
+ c === 0x2d;
1044
+ if (!ok)
1045
+ return false;
1046
+ }
1047
+ return true;
1048
+ }
1049
+ function isValidNonCoreTagUri(uri) {
1050
+ if (!uri || uri === "!" || CORE_TAG_URIS.has(uri))
1051
+ return false;
1052
+ try {
1053
+ assertWellFormedUnicode(uri, "tag.uri");
806
1054
  }
807
- for (const [k, v] of entries) {
808
- if (keyEq(k, key)) {
809
- return v;
1055
+ catch {
1056
+ return false;
1057
+ }
1058
+ if (uri.startsWith("!")) {
1059
+ return uri.length >= 2;
1060
+ }
1061
+ return /^[A-Za-z][A-Za-z0-9+.-]*:/.test(uri);
1062
+ }
1063
+ function isConsistentTagSpelling(uri, handle, suffix) {
1064
+ try {
1065
+ assertWellFormedUnicode(handle, "tag.handle");
1066
+ assertWellFormedUnicode(suffix, "tag.suffix");
1067
+ }
1068
+ catch {
1069
+ return false;
1070
+ }
1071
+ if (!isValidTagHandle(handle)) {
1072
+ return false;
1073
+ }
1074
+ if (handle === "")
1075
+ return suffix === uri;
1076
+ return suffix.length > 0 && uri.endsWith(suffix) && uri.length > suffix.length;
1077
+ }
1078
+ export function createTag(uri, handle = "", suffix) {
1079
+ if (typeof uri !== "string" || typeof handle !== "string") {
1080
+ throw invalidOptionsError("Tag fields must be strings");
1081
+ }
1082
+ const actualSuffix = suffix !== undefined ? suffix : handle === "" ? uri : "";
1083
+ if (typeof actualSuffix !== "string") {
1084
+ throw invalidOptionsError("Tag.suffix must be a string");
1085
+ }
1086
+ assertWellFormedUnicode(uri, "Tag.uri");
1087
+ assertWellFormedUnicode(handle, "Tag.handle");
1088
+ assertWellFormedUnicode(actualSuffix, "Tag.suffix");
1089
+ if (!isValidNonCoreTagUri(uri) || !isConsistentTagSpelling(uri, handle, actualSuffix)) {
1090
+ throw invalidOptionsError(`invalid Tag (${uri}, handle=${handle}, suffix=${actualSuffix})`);
1091
+ }
1092
+ return { uri, handle, suffix: actualSuffix };
1093
+ }
1094
+ export function createTaggedNode(tag, value, metadata) {
1095
+ const tagObj = typeof tag === "string" ? createTag(tag) : createTag(tag.uri, tag.handle ?? "", tag.suffix ?? tag.uri);
1096
+ if (!value || typeof value !== "object" || !("kind" in value)) {
1097
+ throw invalidOptionsError("Tagged value must be a Node");
1098
+ }
1099
+ if (tagObj.uri === "tag:yaml.org,2002:merge") {
1100
+ if (value.kind !== "string") {
1101
+ throw notSourceError("tag_kind_mismatch", {}, "tag:yaml.org,2002:merge may only wrap a String node");
810
1102
  }
811
1103
  }
812
- return undefined;
1104
+ else if (value.kind !== "string" && value.kind !== "sequence" && value.kind !== "mapping") {
1105
+ throw notSourceError("tag_kind_mismatch", {}, `Tagged node must wrap string, sequence, or mapping (found ${value.kind})`);
1106
+ }
1107
+ return {
1108
+ kind: "tagged",
1109
+ tag: tagObj,
1110
+ value,
1111
+ span: metadata?.span ?? null,
1112
+ via: metadata?.via ?? null,
1113
+ tagStart: metadata?.tagStart ?? null,
1114
+ };
813
1115
  }
814
- class WireJsonParser {
815
- s;
816
- pos = 0;
817
- maxDepth;
818
- constructor(s, maxDepth) {
819
- this.s = s;
820
- this.maxDepth = maxDepth;
1116
+ export function createDocument(root, yamlVersion = null, explicitStart = false) {
1117
+ if (!root || typeof root !== "object" || !("kind" in root)) {
1118
+ throw invalidOptionsError("Document.root must be a Node");
1119
+ }
1120
+ if (typeof explicitStart !== "boolean") {
1121
+ throw invalidOptionsError("Document.explicitStart must be a boolean");
1122
+ }
1123
+ if (yamlVersion !== null) {
1124
+ if (!Array.isArray(yamlVersion) ||
1125
+ yamlVersion.length !== 2 ||
1126
+ typeof yamlVersion[0] !== "number" ||
1127
+ typeof yamlVersion[1] !== "number" ||
1128
+ !Number.isInteger(yamlVersion[0]) ||
1129
+ !Number.isInteger(yamlVersion[1]) ||
1130
+ yamlVersion[0] !== 1 ||
1131
+ yamlVersion[1] < 0 ||
1132
+ yamlVersion[1] > 999_999_999) {
1133
+ throw notSourceError("unsupported_yaml_version", {}, `unsupported YAML directive version: ${JSON.stringify(yamlVersion)}`);
1134
+ }
1135
+ return { yamlVersion: [yamlVersion[0], yamlVersion[1]], explicitStart, root };
1136
+ }
1137
+ return { yamlVersion: null, explicitStart, root };
1138
+ }
1139
+ const MASK64 = 0xffffffffffffffffn;
1140
+ function obtainCsprngKeys() {
1141
+ const g = globalThis;
1142
+ if (g.crypto === undefined || typeof g.crypto.getRandomValues !== "function") {
1143
+ throw notSourceError("internal", {}, "cryptographic random source (globalThis.crypto.getRandomValues) is unavailable");
821
1144
  }
822
- parseRoot() {
823
- const val = this.parseValue(0);
824
- this.skipWs();
825
- if (this.pos !== this.s.length) {
826
- throw notSourceError("internal", {}, "trailing characters after wire JSON");
1145
+ const buf = new BigUint64Array(2);
1146
+ g.crypto.getRandomValues(buf);
1147
+ return [buf[0], buf[1]];
1148
+ }
1149
+ const SIP_KEYS = obtainCsprngKeys();
1150
+ function requireSipKeys() {
1151
+ const g = globalThis;
1152
+ if (g.crypto === undefined || typeof g.crypto.getRandomValues !== "function") {
1153
+ throw notSourceError("internal", {}, "cryptographic random source (globalThis.crypto.getRandomValues) is unavailable");
1154
+ }
1155
+ return SIP_KEYS;
1156
+ }
1157
+ function rotl64(x, b) {
1158
+ return ((x << b) | (x >> (64n - b))) & MASK64;
1159
+ }
1160
+ class SipHasher13 {
1161
+ v0;
1162
+ v1;
1163
+ v2;
1164
+ v3;
1165
+ constructor() {
1166
+ const [k0, k1] = requireSipKeys();
1167
+ this.v0 = (k0 ^ 0x736f6d6570736575n) & MASK64;
1168
+ this.v1 = (k1 ^ 0x646f72616e646f6dn) & MASK64;
1169
+ this.v2 = (k0 ^ 0x6c7967656e657261n) & MASK64;
1170
+ this.v3 = (k1 ^ 0x7465646279746573n) & MASK64;
1171
+ }
1172
+ round() {
1173
+ this.v0 = (this.v0 + this.v1) & MASK64;
1174
+ this.v1 = rotl64(this.v1, 13n) ^ this.v0;
1175
+ this.v0 = rotl64(this.v0, 32n);
1176
+ this.v2 = (this.v2 + this.v3) & MASK64;
1177
+ this.v3 = rotl64(this.v3, 16n) ^ this.v2;
1178
+ this.v0 = (this.v0 + this.v3) & MASK64;
1179
+ this.v3 = rotl64(this.v3, 21n) ^ this.v0;
1180
+ this.v2 = (this.v2 + this.v1) & MASK64;
1181
+ this.v1 = rotl64(this.v1, 17n) ^ this.v2;
1182
+ this.v2 = rotl64(this.v2, 32n);
1183
+ }
1184
+ writeU64(m) {
1185
+ const w = m & MASK64;
1186
+ this.v3 ^= w;
1187
+ this.round();
1188
+ this.v0 ^= w;
1189
+ }
1190
+ writeI128(v) {
1191
+ const neg = v < 0n ? 1n : 0n;
1192
+ const mag = v < 0n ? -v : v;
1193
+ this.writeU64((3n << 56n) | neg);
1194
+ this.writeU64(mag & MASK64);
1195
+ this.writeU64((mag >> 64n) & MASK64);
1196
+ }
1197
+ writeFloat(v) {
1198
+ if (Number.isNaN(v)) {
1199
+ this.writeU64((4n << 56n) | 1n);
1200
+ this.writeU64(0x7ff8000000000000n);
1201
+ }
1202
+ else {
1203
+ this.writeU64(4n << 56n);
1204
+ this.writeU64(normFloatBits(v));
827
1205
  }
828
- return val;
829
1206
  }
830
- skipWs() {
831
- while (this.pos < this.s.length) {
832
- const c = this.s.charCodeAt(this.pos);
833
- if (c === 0x20 || c === 0x09 || c === 0x0a || c === 0x0d) {
834
- this.pos++;
835
- }
836
- else {
837
- break;
1207
+ writeString(tag, s) {
1208
+ const len = s.length;
1209
+ this.writeU64((tag << 56n) | BigInt(len));
1210
+ let i = 0;
1211
+ for (; i + 4 <= len; i += 4) {
1212
+ const w = BigInt(s.charCodeAt(i)) |
1213
+ (BigInt(s.charCodeAt(i + 1)) << 16n) |
1214
+ (BigInt(s.charCodeAt(i + 2)) << 32n) |
1215
+ (BigInt(s.charCodeAt(i + 3)) << 48n);
1216
+ this.writeU64(w);
1217
+ }
1218
+ if (i < len) {
1219
+ let rem = 0n;
1220
+ let shift = 0n;
1221
+ for (; i < len; i++) {
1222
+ rem |= BigInt(s.charCodeAt(i)) << shift;
1223
+ shift += 16n;
838
1224
  }
1225
+ this.writeU64(rem);
839
1226
  }
840
1227
  }
841
- expectChar(code) {
842
- this.skipWs();
843
- if (this.pos >= this.s.length || this.s.charCodeAt(this.pos) !== code) {
844
- throw notSourceError("internal", {}, "malformed wire JSON");
845
- }
846
- this.pos++;
1228
+ finish() {
1229
+ this.v2 ^= 0xffn;
1230
+ this.round();
1231
+ this.round();
1232
+ this.round();
1233
+ return (this.v0 ^ this.v1 ^ this.v2 ^ this.v3) & MASK64;
847
1234
  }
848
- parseValue(depth) {
849
- if (depth > this.maxDepth) {
850
- throw notSourceError("internal", {}, "wire JSON nesting exceeds maximum depth");
1235
+ }
1236
+ function scalarKeyHash(n) {
1237
+ switch (n.kind) {
1238
+ case "null": {
1239
+ const h = new SipHasher13();
1240
+ h.writeU64(1n << 56n);
1241
+ return h.finish();
851
1242
  }
852
- this.skipWs();
853
- if (this.pos >= this.s.length) {
854
- throw notSourceError("internal", {}, "unexpected end of wire JSON");
1243
+ case "bool": {
1244
+ const h = new SipHasher13();
1245
+ h.writeU64((2n << 56n) | (n.value ? 1n : 0n));
1246
+ return h.finish();
855
1247
  }
856
- const c = this.s.charCodeAt(this.pos);
857
- if (c === 0x7b /* { */)
858
- return this.parseObject(depth + 1);
859
- if (c === 0x5b /* [ */)
860
- return this.parseArray(depth + 1);
861
- if (c === 0x22 /* " */)
1248
+ case "int": {
1249
+ const h = new SipHasher13();
1250
+ h.writeI128(n.value);
1251
+ return h.finish();
1252
+ }
1253
+ case "float": {
1254
+ const h = new SipHasher13();
1255
+ h.writeFloat(n.value);
1256
+ return h.finish();
1257
+ }
1258
+ case "string": {
1259
+ const h = new SipHasher13();
1260
+ h.writeString(5n, n.value);
1261
+ return h.finish();
1262
+ }
1263
+ default:
1264
+ return null;
1265
+ }
1266
+ }
1267
+ function keyHash(root) {
1268
+ const fast = scalarKeyHash(root);
1269
+ if (fast !== null)
1270
+ return fast;
1271
+ const work = [{ op: "eval", node: root }];
1272
+ const hashes = [];
1273
+ while (work.length > 0) {
1274
+ const frame = work.pop();
1275
+ if (frame.op === "finishTagged") {
1276
+ const innerH = hashes.pop();
1277
+ const h = new SipHasher13();
1278
+ h.writeString(6n, frame.uri);
1279
+ h.writeU64(innerH);
1280
+ hashes.push(h.finish());
1281
+ continue;
1282
+ }
1283
+ if (frame.op === "finishSeq") {
1284
+ const h = new SipHasher13();
1285
+ h.writeU64((7n << 56n) | BigInt(frame.count));
1286
+ const start = hashes.length - frame.count;
1287
+ for (let i = start; i < hashes.length; i++) {
1288
+ h.writeU64(hashes[i]);
1289
+ }
1290
+ hashes.length = start;
1291
+ hashes.push(h.finish());
1292
+ continue;
1293
+ }
1294
+ if (frame.op === "finishMap") {
1295
+ const start = hashes.length - frame.count * 2;
1296
+ let sum = 0n;
1297
+ let xor = 0n;
1298
+ for (let i = 0; i < frame.count; i++) {
1299
+ const kh = hashes[start + i * 2];
1300
+ const vh = hashes[start + i * 2 + 1];
1301
+ const eh = new SipHasher13();
1302
+ eh.writeU64(8n << 56n);
1303
+ eh.writeU64(kh);
1304
+ eh.writeU64(vh);
1305
+ const d = eh.finish();
1306
+ sum = (sum + d) & MASK64;
1307
+ xor ^= d;
1308
+ }
1309
+ hashes.length = start;
1310
+ const mh = new SipHasher13();
1311
+ mh.writeU64((9n << 56n) | BigInt(frame.count));
1312
+ mh.writeU64(sum);
1313
+ mh.writeU64(xor);
1314
+ hashes.push(mh.finish());
1315
+ continue;
1316
+ }
1317
+ const n = frame.node;
1318
+ const sh = scalarKeyHash(n);
1319
+ if (sh !== null) {
1320
+ hashes.push(sh);
1321
+ continue;
1322
+ }
1323
+ switch (n.kind) {
1324
+ case "tagged":
1325
+ work.push({ op: "finishTagged", uri: n.tag.uri });
1326
+ work.push({ op: "eval", node: n.value });
1327
+ break;
1328
+ case "sequence":
1329
+ work.push({ op: "finishSeq", count: n.items.length });
1330
+ for (let i = n.items.length - 1; i >= 0; i--) {
1331
+ work.push({ op: "eval", node: n.items[i] });
1332
+ }
1333
+ break;
1334
+ case "mapping":
1335
+ work.push({ op: "finishMap", count: n.entries.length });
1336
+ for (let i = n.entries.length - 1; i >= 0; i--) {
1337
+ const [k, v] = n.entries[i];
1338
+ work.push({ op: "eval", node: v });
1339
+ work.push({ op: "eval", node: k });
1340
+ }
1341
+ break;
1342
+ }
1343
+ }
1344
+ return hashes.pop();
1345
+ }
1346
+ class KeyIndex {
1347
+ buckets = new Map();
1348
+ checkAndInsert(key) {
1349
+ const h = keyHash(key);
1350
+ const bucket = this.buckets.get(h);
1351
+ if (bucket === undefined) {
1352
+ this.buckets.set(h, [key]);
1353
+ return true;
1354
+ }
1355
+ for (const existing of bucket) {
1356
+ if (keyEq(existing, key)) {
1357
+ return false;
1358
+ }
1359
+ }
1360
+ bucket.push(key);
1361
+ return true;
1362
+ }
1363
+ }
1364
+ export class Mapping {
1365
+ entries;
1366
+ constructor(entries = []) {
1367
+ const validated = [];
1368
+ const keyIndex = new KeyIndex();
1369
+ for (const [k, v] of entries) {
1370
+ if (containsNan(k)) {
1371
+ throw notSourceError("invalid_key", {}, "mapping key contains NaN");
1372
+ }
1373
+ if (!keyIndex.checkAndInsert(k)) {
1374
+ throw notSourceError("duplicate_key", {}, "duplicate mapping key");
1375
+ }
1376
+ validated.push([k, v]);
1377
+ }
1378
+ this.entries = validated;
1379
+ }
1380
+ get size() {
1381
+ return this.entries.length;
1382
+ }
1383
+ get(key) {
1384
+ return mappingGet(this.entries, key);
1385
+ }
1386
+ }
1387
+ export function keyEq(a, b) {
1388
+ const stack = [{ op: "cmp", x: a, y: b }];
1389
+ const backtrackStack = [];
1390
+ const backtrack = () => {
1391
+ while (backtrackStack.length > 0) {
1392
+ const bt = backtrackStack.pop();
1393
+ bt.used[bt.prevJ] = 0;
1394
+ stack.length = bt.savedLen;
1395
+ let idx = bt.nextCandIdx;
1396
+ while (idx < bt.cands.length && bt.used[bt.cands[idx]]) {
1397
+ idx++;
1398
+ }
1399
+ if (idx < bt.cands.length) {
1400
+ stack.push({
1401
+ op: "mapCand",
1402
+ collEntries: bt.collEntries,
1403
+ collIdx: bt.collIdx,
1404
+ ymEntries: bt.ymEntries,
1405
+ ymBuckets: bt.ymBuckets,
1406
+ used: bt.used,
1407
+ cands: bt.cands,
1408
+ candIdx: idx,
1409
+ });
1410
+ return true;
1411
+ }
1412
+ }
1413
+ return false;
1414
+ };
1415
+ while (stack.length > 0) {
1416
+ const frame = stack.pop();
1417
+ if (frame.op === "mapColl") {
1418
+ if (frame.collIdx >= frame.collEntries.length)
1419
+ continue;
1420
+ const [xk] = frame.collEntries[frame.collIdx];
1421
+ const cands = frame.ymBuckets.get(keyHash(xk)) ?? [];
1422
+ let candIdx = 0;
1423
+ while (candIdx < cands.length && frame.used[cands[candIdx]]) {
1424
+ candIdx++;
1425
+ }
1426
+ if (candIdx >= cands.length) {
1427
+ if (!backtrack())
1428
+ return false;
1429
+ continue;
1430
+ }
1431
+ stack.push({
1432
+ op: "mapCand",
1433
+ collEntries: frame.collEntries,
1434
+ collIdx: frame.collIdx,
1435
+ ymEntries: frame.ymEntries,
1436
+ ymBuckets: frame.ymBuckets,
1437
+ used: frame.used,
1438
+ cands,
1439
+ candIdx,
1440
+ });
1441
+ continue;
1442
+ }
1443
+ if (frame.op === "mapCand") {
1444
+ let candIdx = frame.candIdx;
1445
+ while (candIdx < frame.cands.length && frame.used[frame.cands[candIdx]]) {
1446
+ candIdx++;
1447
+ }
1448
+ if (candIdx >= frame.cands.length) {
1449
+ if (!backtrack())
1450
+ return false;
1451
+ continue;
1452
+ }
1453
+ const j = frame.cands[candIdx];
1454
+ const [xk, xv] = frame.collEntries[frame.collIdx];
1455
+ const [yk, yv] = frame.ymEntries[j];
1456
+ let nextCandIdx = candIdx + 1;
1457
+ while (nextCandIdx < frame.cands.length && frame.used[frame.cands[nextCandIdx]]) {
1458
+ nextCandIdx++;
1459
+ }
1460
+ if (nextCandIdx < frame.cands.length) {
1461
+ backtrackStack.push({
1462
+ savedLen: stack.length,
1463
+ collEntries: frame.collEntries,
1464
+ collIdx: frame.collIdx,
1465
+ ymEntries: frame.ymEntries,
1466
+ ymBuckets: frame.ymBuckets,
1467
+ used: frame.used,
1468
+ cands: frame.cands,
1469
+ nextCandIdx,
1470
+ prevJ: j,
1471
+ });
1472
+ }
1473
+ frame.used[j] = 1;
1474
+ if (frame.collIdx + 1 < frame.collEntries.length) {
1475
+ stack.push({
1476
+ op: "mapColl",
1477
+ collEntries: frame.collEntries,
1478
+ collIdx: frame.collIdx + 1,
1479
+ ymEntries: frame.ymEntries,
1480
+ ymBuckets: frame.ymBuckets,
1481
+ used: frame.used,
1482
+ });
1483
+ }
1484
+ stack.push({ op: "cmp", x: xv, y: yv });
1485
+ stack.push({ op: "cmp", x: xk, y: yk });
1486
+ continue;
1487
+ }
1488
+ const { x, y } = frame;
1489
+ if (x.kind !== y.kind) {
1490
+ if (!backtrack())
1491
+ return false;
1492
+ continue;
1493
+ }
1494
+ switch (x.kind) {
1495
+ case "null":
1496
+ break;
1497
+ case "bool":
1498
+ if (x.value !== y.value) {
1499
+ if (!backtrack())
1500
+ return false;
1501
+ }
1502
+ break;
1503
+ case "int":
1504
+ if (x.value !== y.value) {
1505
+ if (!backtrack())
1506
+ return false;
1507
+ }
1508
+ break;
1509
+ case "float": {
1510
+ const yf = y;
1511
+ if (Number.isNaN(x.value) || Number.isNaN(yf.value)) {
1512
+ if (!backtrack())
1513
+ return false;
1514
+ break;
1515
+ }
1516
+ if (normFloatBits(x.value) !== normFloatBits(yf.value)) {
1517
+ if (!backtrack())
1518
+ return false;
1519
+ }
1520
+ break;
1521
+ }
1522
+ case "string":
1523
+ if (x.value !== y.value) {
1524
+ if (!backtrack())
1525
+ return false;
1526
+ }
1527
+ break;
1528
+ case "sequence": {
1529
+ const ys = y;
1530
+ if (x.items.length !== ys.items.length) {
1531
+ if (!backtrack())
1532
+ return false;
1533
+ break;
1534
+ }
1535
+ for (let i = 0; i < x.items.length; i++) {
1536
+ stack.push({ op: "cmp", x: x.items[i], y: ys.items[i] });
1537
+ }
1538
+ break;
1539
+ }
1540
+ case "mapping": {
1541
+ const ym = y;
1542
+ if (x.entries.length !== ym.entries.length) {
1543
+ if (!backtrack())
1544
+ return false;
1545
+ break;
1546
+ }
1547
+ const ymBuckets = new Map();
1548
+ for (let j = 0; j < ym.entries.length; j++) {
1549
+ const [yk] = ym.entries[j];
1550
+ const h = keyHash(yk);
1551
+ const b = ymBuckets.get(h);
1552
+ if (b === undefined) {
1553
+ ymBuckets.set(h, [j]);
1554
+ }
1555
+ else {
1556
+ b.push(j);
1557
+ }
1558
+ }
1559
+ const used = new Uint8Array(ym.entries.length);
1560
+ const collEntries = [];
1561
+ let failed = false;
1562
+ for (const [xk, xv] of x.entries) {
1563
+ const cands = ymBuckets.get(keyHash(xk));
1564
+ if (!cands || cands.length === 0) {
1565
+ failed = true;
1566
+ break;
1567
+ }
1568
+ if (cands.length === 1) {
1569
+ const j = cands[0];
1570
+ if (used[j]) {
1571
+ failed = true;
1572
+ break;
1573
+ }
1574
+ used[j] = 1;
1575
+ const [yk, yv] = ym.entries[j];
1576
+ stack.push({ op: "cmp", x: xv, y: yv });
1577
+ stack.push({ op: "cmp", x: xk, y: yk });
1578
+ }
1579
+ else {
1580
+ collEntries.push([xk, xv]);
1581
+ }
1582
+ }
1583
+ if (failed) {
1584
+ if (!backtrack())
1585
+ return false;
1586
+ break;
1587
+ }
1588
+ if (collEntries.length > 0) {
1589
+ stack.push({
1590
+ op: "mapColl",
1591
+ collEntries,
1592
+ collIdx: 0,
1593
+ ymEntries: ym.entries,
1594
+ ymBuckets,
1595
+ used,
1596
+ });
1597
+ }
1598
+ break;
1599
+ }
1600
+ case "tagged": {
1601
+ const yt = y;
1602
+ if (x.tag.uri !== yt.tag.uri) {
1603
+ if (!backtrack())
1604
+ return false;
1605
+ break;
1606
+ }
1607
+ stack.push({ op: "cmp", x: x.value, y: yt.value });
1608
+ break;
1609
+ }
1610
+ }
1611
+ }
1612
+ return true;
1613
+ }
1614
+ export function mappingGet(mapping, key) {
1615
+ const entries = Array.isArray(mapping) ? mapping : mapping.entries;
1616
+ if (typeof key === "string") {
1617
+ for (const [k, v] of entries) {
1618
+ if (k.kind === "string" && k.value === key) {
1619
+ return v;
1620
+ }
1621
+ }
1622
+ return undefined;
1623
+ }
1624
+ for (const [k, v] of entries) {
1625
+ if (keyEq(k, key)) {
1626
+ return v;
1627
+ }
1628
+ }
1629
+ return undefined;
1630
+ }
1631
+ class WireJsonParser {
1632
+ s;
1633
+ pos = 0;
1634
+ maxDepth;
1635
+ constructor(s, maxDepth) {
1636
+ this.s = s;
1637
+ this.maxDepth = maxDepth;
1638
+ }
1639
+ parseRoot() {
1640
+ const val = this.parseValue(0);
1641
+ this.skipWs();
1642
+ if (this.pos !== this.s.length) {
1643
+ throw notSourceError("internal", {}, "trailing characters after wire JSON");
1644
+ }
1645
+ return val;
1646
+ }
1647
+ skipWs() {
1648
+ while (this.pos < this.s.length) {
1649
+ const c = this.s.charCodeAt(this.pos);
1650
+ if (c === 0x20 || c === 0x09 || c === 0x0a || c === 0x0d) {
1651
+ this.pos++;
1652
+ }
1653
+ else {
1654
+ break;
1655
+ }
1656
+ }
1657
+ }
1658
+ expectChar(code) {
1659
+ this.skipWs();
1660
+ if (this.pos >= this.s.length || this.s.charCodeAt(this.pos) !== code) {
1661
+ throw notSourceError("internal", {}, "malformed wire JSON");
1662
+ }
1663
+ this.pos++;
1664
+ }
1665
+ parseValue(depth) {
1666
+ if (depth > this.maxDepth) {
1667
+ throw notSourceError("internal", {}, "wire JSON nesting exceeds maximum depth");
1668
+ }
1669
+ this.skipWs();
1670
+ if (this.pos >= this.s.length) {
1671
+ throw notSourceError("internal", {}, "unexpected end of wire JSON");
1672
+ }
1673
+ const c = this.s.charCodeAt(this.pos);
1674
+ if (c === 0x7b /* { */)
1675
+ return this.parseObject(depth + 1);
1676
+ if (c === 0x5b /* [ */)
1677
+ return this.parseArray(depth + 1);
1678
+ if (c === 0x22 /* " */)
862
1679
  return { t: "str", v: this.parseString() };
863
1680
  if (c === 0x74 /* t */) {
864
1681
  if (this.s.startsWith("true", this.pos)) {
@@ -1123,180 +1940,373 @@ function decodeSpan(val, idx) {
1123
1940
  },
1124
1941
  };
1125
1942
  }
1126
- function decodeNode(val, ctx, depth) {
1127
- if (val.t !== "obj") {
1128
- throw notSourceError("internal", {}, "Node must be a JSON object");
1129
- }
1130
- if (ctx.nodesRemaining <= 0) {
1131
- throw notSourceError("internal", {}, "wire Node count exceeds max_nodes");
1132
- }
1133
- ctx.nodesRemaining -= 1;
1134
- const map = val.map;
1135
- const kind = expectStr(map.get("kind"), "Node.kind");
1136
- const spanVal = map.get("span");
1137
- const viaVal = map.get("via");
1138
- const tagStartVal = map.get("tag_start");
1139
- if (!spanVal || !viaVal || !tagStartVal) {
1140
- throw notSourceError("internal", {}, "Node missing location fields");
1141
- }
1142
- if (ctx.forbidLocations) {
1143
- if (spanVal.t !== "null" || viaVal.t !== "null" || tagStartVal.t !== "null") {
1144
- throw notSourceError("internal", {}, "PathKey must have null span, via and tag_start");
1145
- }
1943
+ function chargeOwnedBytes(ctx, delta) {
1944
+ ctx.ownedBytes += delta;
1945
+ if (ctx.ownedBytes > BigInt(ctx.opts.limits.maxOwnedBytes)) {
1946
+ throw notSourceError("limit_exceeded", { limit: "max_owned_bytes", configured: ctx.opts.limits.maxOwnedBytes }, `decoded tree exceeds max_owned_bytes (${ctx.opts.limits.maxOwnedBytes})`);
1146
1947
  }
1147
- const span = spanVal.t === "null" ? null : decodeSpan(spanVal, ctx.idx);
1148
- let via = null;
1149
- if (viaVal.t !== "null") {
1150
- if (viaVal.t !== "obj" || viaVal.map.size !== 1) {
1151
- throw notSourceError("internal", {}, "invalid Node.via");
1152
- }
1153
- const aliasSpan = viaVal.map.get("alias");
1154
- const mergeSpan = viaVal.map.get("merge");
1155
- if (aliasSpan) {
1156
- const s = decodeSpan(aliasSpan, ctx.idx);
1157
- via = { kind: "alias", alias: s, useSite: s };
1158
- }
1159
- else if (mergeSpan) {
1160
- const s = decodeSpan(mergeSpan, ctx.idx);
1161
- via = { kind: "merge", merge: s, directive: s };
1162
- }
1163
- else {
1164
- throw notSourceError("internal", {}, "unknown Via variant");
1165
- }
1166
- }
1167
- const tagStart = tagStartVal.t === "null" ? null : decodeLoc(tagStartVal, ctx.idx);
1168
- switch (kind) {
1169
- case "null": {
1170
- expectExactKeys(map, ["kind", "span", "via", "tag_start"]);
1171
- return { kind: "null", span, via, tagStart };
1172
- }
1173
- case "bool": {
1174
- expectExactKeys(map, ["kind", "value", "span", "via", "tag_start"]);
1175
- return {
1176
- kind: "bool",
1177
- value: expectBool(map.get("value"), "bool.value"),
1178
- span,
1179
- via,
1180
- tagStart,
1181
- };
1182
- }
1183
- case "int": {
1184
- expectExactKeys(map, ["kind", "value", "span", "via", "tag_start"]);
1185
- const raw = expectStr(map.get("value"), "int.value");
1186
- if (!/^(0|-?[1-9][0-9]*)$/.test(raw)) {
1187
- throw notSourceError("internal", {}, `non-canonical wire int: ${raw}`);
1188
- }
1189
- const big = BigInt(raw);
1190
- if (big < I128_MIN || big > U128_MAX) {
1191
- throw notSourceError("internal", {}, `wire int out of 128-bit range: ${raw}`);
1948
+ }
1949
+ function preflightDocKeyWeight(keyRoot, maxKeyBytes) {
1950
+ const maxKey = BigInt(maxKeyBytes);
1951
+ let total = 0n;
1952
+ const stack = [keyRoot];
1953
+ while (stack.length > 0) {
1954
+ const cur = stack.pop();
1955
+ total += NODE_OVERHEAD;
1956
+ if (total > maxKey) {
1957
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: maxKeyBytes }, `decoded mapping key exceeds max_key_bytes (${maxKeyBytes})`);
1958
+ }
1959
+ if (cur.kind === "string") {
1960
+ total += BigInt(encoder.encode(cur.value).byteLength);
1961
+ if (total > maxKey) {
1962
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: maxKeyBytes }, `decoded mapping key exceeds max_key_bytes (${maxKeyBytes})`);
1192
1963
  }
1193
- return { kind: "int", value: big, span, via, tagStart };
1194
1964
  }
1195
- case "float": {
1196
- expectExactKeys(map, ["kind", "bits", "span", "via", "tag_start"]);
1197
- const rawBits = expectStr(map.get("bits"), "float.bits");
1198
- if (!/^[0-9a-f]{16}$/.test(rawBits)) {
1199
- throw notSourceError("internal", {}, `invalid wire float bits: ${rawBits}`);
1965
+ else if (cur.kind === "tagged") {
1966
+ total += tagWeightBytes(cur.tag);
1967
+ if (total > maxKey) {
1968
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: maxKeyBytes }, `decoded mapping key exceeds max_key_bytes (${maxKeyBytes})`);
1200
1969
  }
1201
- const { value, canonicalBits } = bitsToFloat(rawBits);
1202
- return { kind: "float", value, bits: canonicalBits, span, via, tagStart };
1970
+ stack.push(cur.value);
1203
1971
  }
1204
- case "string": {
1205
- expectExactKeys(map, ["kind", "value", "span", "via", "tag_start"]);
1206
- const strVal = expectStr(map.get("value"), "string.value");
1207
- return { kind: "string", value: strVal, span, via, tagStart };
1972
+ else if (cur.kind === "sequence") {
1973
+ for (const it of cur.items)
1974
+ stack.push(it);
1208
1975
  }
1209
- case "sequence": {
1210
- expectExactKeys(map, ["kind", "items", "span", "via", "tag_start"]);
1211
- if (depth + 1 > ctx.opts.limits.maxDepth) {
1212
- throw notSourceError("internal", {}, "wire sequence depth exceeds max_depth");
1976
+ else if (cur.kind === "mapping") {
1977
+ total += BigInt(cur.entries.length) * ENTRY_OVERHEAD;
1978
+ if (total > maxKey) {
1979
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: maxKeyBytes }, `decoded mapping key exceeds max_key_bytes (${maxKeyBytes})`);
1213
1980
  }
1214
- const itemsVal = map.get("items");
1215
- if (itemsVal.t !== "arr") {
1216
- throw notSourceError("internal", {}, "sequence.items must be an array");
1981
+ for (const [k, v] of cur.entries) {
1982
+ stack.push(v, k);
1217
1983
  }
1218
- const items = itemsVal.items.map((it) => decodeNode(it, ctx, depth + 1));
1219
- return { kind: "sequence", items, span, via, tagStart };
1220
1984
  }
1221
- case "mapping": {
1222
- expectExactKeys(map, ["kind", "entries", "span", "via", "tag_start"]);
1223
- if (depth + 1 > ctx.opts.limits.maxDepth) {
1224
- throw notSourceError("internal", {}, "wire mapping depth exceeds max_depth");
1985
+ }
1986
+ }
1987
+ function decodeNode(rootVal, ctx, rootDepth, rootInKey = false) {
1988
+ const work = [{ op: "eval", val: rootVal, depth: rootDepth, inKey: rootInKey }];
1989
+ const results = [];
1990
+ while (work.length > 0) {
1991
+ const frame = work.pop();
1992
+ if (frame.op === "seqStep") {
1993
+ if (frame.idx > 0) {
1994
+ frame.items.push(results.pop());
1995
+ }
1996
+ if (frame.idx >= frame.rawItems.length) {
1997
+ results.push({
1998
+ kind: "sequence",
1999
+ items: frame.items,
2000
+ span: frame.span,
2001
+ via: frame.via,
2002
+ tagStart: frame.tagStart,
2003
+ });
1225
2004
  }
1226
- const entriesVal = map.get("entries");
1227
- if (entriesVal.t !== "arr") {
1228
- throw notSourceError("internal", {}, "mapping.entries must be an array");
2005
+ else {
2006
+ work.push({
2007
+ op: "seqStep",
2008
+ rawItems: frame.rawItems,
2009
+ idx: frame.idx + 1,
2010
+ nextDepth: frame.nextDepth,
2011
+ inKey: frame.inKey,
2012
+ items: frame.items,
2013
+ span: frame.span,
2014
+ via: frame.via,
2015
+ tagStart: frame.tagStart,
2016
+ });
2017
+ work.push({
2018
+ op: "eval",
2019
+ val: frame.rawItems[frame.idx],
2020
+ depth: frame.nextDepth,
2021
+ inKey: frame.inKey,
2022
+ });
1229
2023
  }
1230
- if (entriesVal.items.length > ctx.opts.limits.maxMappingEntries) {
1231
- throw notSourceError("internal", {}, "wire mapping entries exceed max_mapping_entries");
2024
+ continue;
2025
+ }
2026
+ if (frame.op === "mapStep") {
2027
+ if (frame.idx >= frame.rawEntries.length) {
2028
+ results.push({
2029
+ kind: "mapping",
2030
+ entries: frame.entries,
2031
+ span: frame.span,
2032
+ via: frame.via,
2033
+ tagStart: frame.tagStart,
2034
+ });
1232
2035
  }
1233
- const entries = [];
1234
- for (const item of entriesVal.items) {
2036
+ else {
2037
+ const item = frame.rawEntries[frame.idx];
1235
2038
  if (item.t !== "obj") {
1236
2039
  throw notSourceError("internal", {}, "mapping entry must be an object");
1237
2040
  }
1238
2041
  expectExactKeys(item.map, ["key", "value"]);
1239
- const k = decodeNode(item.map.get("key"), ctx, depth + 1);
1240
- const v = decodeNode(item.map.get("value"), ctx, depth + 1);
1241
- if (containsNan(k)) {
1242
- throw notSourceError("internal", {}, "wire mapping key contains NaN");
1243
- }
1244
- for (const [ek] of entries) {
1245
- if (keyEq(ek, k)) {
1246
- throw notSourceError("internal", {}, "wire mapping contains duplicate key");
1247
- }
1248
- }
1249
- entries.push([k, v]);
2042
+ work.push({
2043
+ op: "mapEntryDone",
2044
+ rawEntries: frame.rawEntries,
2045
+ nextIdx: frame.idx + 1,
2046
+ nextDepth: frame.nextDepth,
2047
+ inKey: frame.inKey,
2048
+ entries: frame.entries,
2049
+ keyIndex: frame.keyIndex,
2050
+ span: frame.span,
2051
+ via: frame.via,
2052
+ tagStart: frame.tagStart,
2053
+ });
2054
+ work.push({
2055
+ op: "eval",
2056
+ val: item.map.get("value"),
2057
+ depth: frame.nextDepth,
2058
+ inKey: frame.inKey,
2059
+ });
2060
+ work.push({
2061
+ op: "eval",
2062
+ val: item.map.get("key"),
2063
+ depth: frame.nextDepth,
2064
+ inKey: true,
2065
+ });
1250
2066
  }
1251
- return { kind: "mapping", entries, span, via, tagStart };
2067
+ continue;
1252
2068
  }
1253
- case "tagged": {
1254
- expectExactKeys(map, ["kind", "tag", "value", "span", "via", "tag_start"]);
1255
- const tagVal = map.get("tag");
1256
- if (tagVal.t !== "obj") {
1257
- throw notSourceError("internal", {}, "tagged.tag must be an object");
2069
+ if (frame.op === "mapEntryDone") {
2070
+ const v = results.pop();
2071
+ const k = results.pop();
2072
+ if (!ctx.forbidLocations) {
2073
+ preflightDocKeyWeight(k, ctx.opts.limits.maxKeyBytes);
2074
+ }
2075
+ if (containsNan(k)) {
2076
+ throw notSourceError("internal", {}, "wire mapping key contains NaN");
2077
+ }
2078
+ if (!frame.keyIndex.checkAndInsert(k)) {
2079
+ throw notSourceError("internal", {}, "wire mapping contains duplicate key");
1258
2080
  }
1259
- expectExactKeys(tagVal.map, ["uri", "handle", "suffix"]);
1260
- const uri = expectStr(tagVal.map.get("uri"), "tag.uri");
1261
- const handle = expectStr(tagVal.map.get("handle"), "tag.handle");
1262
- const suffix = expectStr(tagVal.map.get("suffix"), "tag.suffix");
1263
- if (uri.length === 0) {
1264
- throw notSourceError("internal", {}, "tag.uri must not be empty");
2081
+ frame.entries.push([k, v]);
2082
+ work.push({
2083
+ op: "mapStep",
2084
+ rawEntries: frame.rawEntries,
2085
+ idx: frame.nextIdx,
2086
+ nextDepth: frame.nextDepth,
2087
+ inKey: frame.inKey,
2088
+ entries: frame.entries,
2089
+ keyIndex: frame.keyIndex,
2090
+ span: frame.span,
2091
+ via: frame.via,
2092
+ tagStart: frame.tagStart,
2093
+ });
2094
+ continue;
2095
+ }
2096
+ if (frame.op === "finishTagged") {
2097
+ const inner = results.pop();
2098
+ if (frame.tag.uri === "tag:yaml.org,2002:merge") {
2099
+ if (frame.inKey || inner.kind !== "string") {
2100
+ throw notSourceError("internal", {}, "tag:yaml.org,2002:merge may only wrap a non-key String node in yamlprims-value/1");
2101
+ }
1265
2102
  }
1266
- // Tagged wrapper does not add collection depth; nested Tagged-in-Tagged is forbidden.
1267
- const inner = decodeNode(map.get("value"), ctx, depth);
1268
- if (inner.kind === "tagged") {
1269
- throw notSourceError("internal", {}, "nested Tagged-in-Tagged is invalid in yamlprims-value/1");
2103
+ else if (inner.kind !== "string" && inner.kind !== "sequence" && inner.kind !== "mapping") {
2104
+ throw notSourceError("internal", {}, "Tagged node in yamlprims-value/1 must wrap string, sequence, or mapping");
1270
2105
  }
1271
- return {
2106
+ results.push({
1272
2107
  kind: "tagged",
1273
- tag: { uri, handle, suffix },
2108
+ tag: frame.tag,
1274
2109
  value: inner,
1275
- span,
1276
- via,
1277
- tagStart,
1278
- };
2110
+ span: frame.span,
2111
+ via: frame.via,
2112
+ tagStart: frame.tagStart,
2113
+ });
2114
+ continue;
1279
2115
  }
1280
- default:
1281
- throw notSourceError("internal", {}, `unknown wire Node kind: ${kind}`);
1282
- }
1283
- }
1284
- function decodeErrorEnvelope(errObj, opts, sourceBytes) {
1285
- expectExactKeys(errObj, ["kind", "detail", "site", "related", "path", "message"]);
1286
- const kindStr = expectStr(errObj.get("kind"), "error.kind");
1287
- const detailVal = errObj.get("detail");
1288
- if (detailVal.t !== "obj") {
1289
- throw notSourceError("internal", {}, "error.detail must be an object");
1290
- }
1291
- let detail;
1292
- if (kindStr === "invalid_utf8") {
1293
- expectExactKeys(detailVal.map, ["invalid_len"]);
1294
- const il = detailVal.map.get("invalid_len");
1295
- if (il.t === "null") {
1296
- detail = { invalid_len: null };
2116
+ const { val, depth, inKey } = frame;
2117
+ if (val.t !== "obj") {
2118
+ throw notSourceError("internal", {}, "Node must be a JSON object");
2119
+ }
2120
+ if (ctx.nodesRemaining <= 0) {
2121
+ throw notSourceError("limit_exceeded", { limit: "max_nodes", configured: ctx.opts.limits.maxNodes }, `wire Node count exceeds max_nodes (${ctx.opts.limits.maxNodes})`);
2122
+ }
2123
+ ctx.nodesRemaining -= 1;
2124
+ chargeOwnedBytes(ctx, NODE_OVERHEAD);
2125
+ const map = val.map;
2126
+ const kind = expectStr(map.get("kind"), "Node.kind");
2127
+ const spanVal = map.get("span");
2128
+ const viaVal = map.get("via");
2129
+ const tagStartVal = map.get("tag_start");
2130
+ if (!spanVal || !viaVal || !tagStartVal) {
2131
+ throw notSourceError("internal", {}, "Node missing location fields");
2132
+ }
2133
+ if (ctx.forbidLocations) {
2134
+ if (spanVal.t !== "null" || viaVal.t !== "null" || tagStartVal.t !== "null") {
2135
+ throw notSourceError("internal", {}, "PathKey must have null span, via and tag_start");
2136
+ }
1297
2137
  }
1298
- else if (il.t === "int") {
1299
- detail = { invalid_len: il.v };
2138
+ const span = spanVal.t === "null" ? null : decodeSpan(spanVal, ctx.idx);
2139
+ let via = null;
2140
+ if (viaVal.t !== "null") {
2141
+ if (viaVal.t !== "obj" || viaVal.map.size !== 1) {
2142
+ throw notSourceError("internal", {}, "invalid Node.via");
2143
+ }
2144
+ const aliasSpan = viaVal.map.get("alias");
2145
+ const mergeSpan = viaVal.map.get("merge");
2146
+ if (aliasSpan) {
2147
+ const s = decodeSpan(aliasSpan, ctx.idx);
2148
+ via = { kind: "alias", alias: s, useSite: s };
2149
+ }
2150
+ else if (mergeSpan) {
2151
+ const s = decodeSpan(mergeSpan, ctx.idx);
2152
+ via = { kind: "merge", merge: s, directive: s };
2153
+ }
2154
+ else {
2155
+ throw notSourceError("internal", {}, "unknown Via variant");
2156
+ }
2157
+ }
2158
+ const tagStart = tagStartVal.t === "null" ? null : decodeLoc(tagStartVal, ctx.idx);
2159
+ switch (kind) {
2160
+ case "null": {
2161
+ expectExactKeys(map, ["kind", "span", "via", "tag_start"]);
2162
+ results.push({ kind: "null", span, via, tagStart });
2163
+ break;
2164
+ }
2165
+ case "bool": {
2166
+ expectExactKeys(map, ["kind", "value", "span", "via", "tag_start"]);
2167
+ results.push({
2168
+ kind: "bool",
2169
+ value: expectBool(map.get("value"), "bool.value"),
2170
+ span,
2171
+ via,
2172
+ tagStart,
2173
+ });
2174
+ break;
2175
+ }
2176
+ case "int": {
2177
+ expectExactKeys(map, ["kind", "value", "span", "via", "tag_start"]);
2178
+ const raw = expectStr(map.get("value"), "int.value");
2179
+ if (!/^(0|-?[1-9][0-9]*)$/.test(raw)) {
2180
+ throw notSourceError("internal", {}, `non-canonical wire int: ${raw}`);
2181
+ }
2182
+ const big = BigInt(raw);
2183
+ if (big < I128_MIN || big > U128_MAX) {
2184
+ throw notSourceError("internal", {}, `wire int out of 128-bit range: ${raw}`);
2185
+ }
2186
+ results.push({ kind: "int", value: big, span, via, tagStart });
2187
+ break;
2188
+ }
2189
+ case "float": {
2190
+ expectExactKeys(map, ["kind", "bits", "span", "via", "tag_start"]);
2191
+ const rawBits = expectStr(map.get("bits"), "float.bits");
2192
+ if (!/^[0-9a-f]{16}$/.test(rawBits)) {
2193
+ throw notSourceError("internal", {}, `invalid wire float bits: ${rawBits}`);
2194
+ }
2195
+ const { value, canonicalBits } = bitsToFloat(rawBits);
2196
+ results.push({ kind: "float", value, bits: canonicalBits, span, via, tagStart });
2197
+ break;
2198
+ }
2199
+ case "string": {
2200
+ expectExactKeys(map, ["kind", "value", "span", "via", "tag_start"]);
2201
+ const strVal = expectStr(map.get("value"), "string.value");
2202
+ const strBytes = encoder.encode(strVal).byteLength;
2203
+ if (strBytes > ctx.opts.limits.maxScalarBytes) {
2204
+ throw notSourceError("limit_exceeded", { limit: "max_scalar_bytes", configured: ctx.opts.limits.maxScalarBytes }, `wire string exceeds max_scalar_bytes (${ctx.opts.limits.maxScalarBytes})`);
2205
+ }
2206
+ chargeOwnedBytes(ctx, BigInt(strBytes));
2207
+ results.push({ kind: "string", value: strVal, span, via, tagStart });
2208
+ break;
2209
+ }
2210
+ case "sequence": {
2211
+ expectExactKeys(map, ["kind", "items", "span", "via", "tag_start"]);
2212
+ const itemsVal = map.get("items");
2213
+ if (itemsVal.t !== "arr") {
2214
+ throw notSourceError("internal", {}, "sequence.items must be an array");
2215
+ }
2216
+ if (!ctx.forbidLocations || itemsVal.items.length > 0) {
2217
+ if (depth + 1 > ctx.opts.limits.maxDepth) {
2218
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: ctx.opts.limits.maxDepth }, `wire sequence depth exceeds max_depth (${ctx.opts.limits.maxDepth})`);
2219
+ }
2220
+ }
2221
+ work.push({
2222
+ op: "seqStep",
2223
+ rawItems: itemsVal.items,
2224
+ idx: 0,
2225
+ nextDepth: depth + 1,
2226
+ inKey,
2227
+ items: [],
2228
+ span,
2229
+ via,
2230
+ tagStart,
2231
+ });
2232
+ break;
2233
+ }
2234
+ case "mapping": {
2235
+ expectExactKeys(map, ["kind", "entries", "span", "via", "tag_start"]);
2236
+ const entriesVal = map.get("entries");
2237
+ if (entriesVal.t !== "arr") {
2238
+ throw notSourceError("internal", {}, "mapping.entries must be an array");
2239
+ }
2240
+ if (!ctx.forbidLocations || entriesVal.items.length > 0) {
2241
+ if (depth + 1 > ctx.opts.limits.maxDepth) {
2242
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: ctx.opts.limits.maxDepth }, `wire mapping depth exceeds max_depth (${ctx.opts.limits.maxDepth})`);
2243
+ }
2244
+ }
2245
+ if (entriesVal.items.length > ctx.opts.limits.maxMappingEntries) {
2246
+ throw notSourceError("limit_exceeded", { limit: "max_mapping_entries", configured: ctx.opts.limits.maxMappingEntries }, `wire mapping entries exceed max_mapping_entries (${ctx.opts.limits.maxMappingEntries})`);
2247
+ }
2248
+ chargeOwnedBytes(ctx, BigInt(entriesVal.items.length) * ENTRY_OVERHEAD);
2249
+ work.push({
2250
+ op: "mapStep",
2251
+ rawEntries: entriesVal.items,
2252
+ idx: 0,
2253
+ nextDepth: depth + 1,
2254
+ inKey,
2255
+ entries: [],
2256
+ keyIndex: new KeyIndex(),
2257
+ span,
2258
+ via,
2259
+ tagStart,
2260
+ });
2261
+ break;
2262
+ }
2263
+ case "tagged": {
2264
+ expectExactKeys(map, ["kind", "tag", "value", "span", "via", "tag_start"]);
2265
+ const tagVal = map.get("tag");
2266
+ if (tagVal.t !== "obj") {
2267
+ throw notSourceError("internal", {}, "tagged.tag must be an object");
2268
+ }
2269
+ expectExactKeys(tagVal.map, ["uri", "handle", "suffix"]);
2270
+ const uri = expectStr(tagVal.map.get("uri"), "tag.uri");
2271
+ const handle = expectStr(tagVal.map.get("handle"), "tag.handle");
2272
+ const suffix = expectStr(tagVal.map.get("suffix"), "tag.suffix");
2273
+ if (!isValidNonCoreTagUri(uri) || !isConsistentTagSpelling(uri, handle, suffix)) {
2274
+ throw notSourceError("internal", {}, "invalid wire Tag on tagged node");
2275
+ }
2276
+ chargeOwnedBytes(ctx, tagWeightBytes({ uri, handle, suffix }));
2277
+ work.push({
2278
+ op: "finishTagged",
2279
+ tag: { uri, handle, suffix },
2280
+ inKey,
2281
+ span,
2282
+ via,
2283
+ tagStart,
2284
+ });
2285
+ work.push({ op: "eval", val: map.get("value"), depth, inKey });
2286
+ break;
2287
+ }
2288
+ default:
2289
+ throw notSourceError("internal", {}, `unknown wire Node kind: ${kind}`);
2290
+ }
2291
+ }
2292
+ return results.pop();
2293
+ }
2294
+ function decodeErrorEnvelope(errObj, opts, sourceBytes) {
2295
+ expectExactKeys(errObj, ["kind", "detail", "site", "related", "path", "message"]);
2296
+ const kindStr = expectStr(errObj.get("kind"), "error.kind");
2297
+ const detailVal = errObj.get("detail");
2298
+ if (detailVal.t !== "obj") {
2299
+ throw notSourceError("internal", {}, "error.detail must be an object");
2300
+ }
2301
+ let detail;
2302
+ if (kindStr === "invalid_utf8") {
2303
+ expectExactKeys(detailVal.map, ["invalid_len"]);
2304
+ const il = detailVal.map.get("invalid_len");
2305
+ if (il.t === "null") {
2306
+ detail = { invalid_len: null };
2307
+ }
2308
+ else if (il.t === "int") {
2309
+ detail = { invalid_len: il.v };
1300
2310
  }
1301
2311
  else {
1302
2312
  throw notSourceError("internal", {}, "invalid invalid_utf8.invalid_len");
@@ -1397,8 +2407,15 @@ function decodeErrorEnvelope(errObj, opts, sourceBytes) {
1397
2407
  throw notSourceError("internal", {}, "error.path must be an array");
1398
2408
  }
1399
2409
  if (pathVal.items.length > opts.limits.maxDepth) {
1400
- throw notSourceError("internal", {}, "error.path length exceeds max_depth");
2410
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: opts.limits.maxDepth }, `error.path length exceeds max_depth (${opts.limits.maxDepth})`);
1401
2411
  }
2412
+ const pathCtx = {
2413
+ opts,
2414
+ idx: null,
2415
+ nodesRemaining: opts.limits.maxNodes,
2416
+ ownedBytes: 0n,
2417
+ forbidLocations: true,
2418
+ };
1402
2419
  const path = [];
1403
2420
  for (const seg of pathVal.items) {
1404
2421
  if (seg.t !== "obj" || seg.map.size !== 1) {
@@ -1410,13 +2427,7 @@ function decodeErrorEnvelope(errObj, opts, sourceBytes) {
1410
2427
  path.push({ index: expectInt(idxSeg, "path.index") });
1411
2428
  }
1412
2429
  else if (keySeg) {
1413
- const ctx = {
1414
- opts,
1415
- idx: null,
1416
- nodesRemaining: opts.limits.maxNodes,
1417
- forbidLocations: true,
1418
- };
1419
- const keyNode = decodeNode(keySeg, ctx, 0);
2430
+ const keyNode = decodeNode(keySeg, pathCtx, 0, true);
1420
2431
  preflightKeyNode(keyNode, opts.limits);
1421
2432
  path.push({ key: keyNode });
1422
2433
  }
@@ -1438,8 +2449,8 @@ export function decodeWire(wireJson, options, sourceInput) {
1438
2449
  const opts = validateOptions(options);
1439
2450
  assertWellFormedUnicode(wireJson, "wireJson");
1440
2451
  const wireByteLen = encoder.encode(wireJson).byteLength;
1441
- if (wireByteLen > opts.limits.maxOutputBytes) {
1442
- throw notSourceError("output_limit_exceeded", { configured: opts.limits.maxOutputBytes }, `wire input exceeds max_output_bytes (${opts.limits.maxOutputBytes})`);
2452
+ if (wireByteLen > opts.limits.maxInputBytes) {
2453
+ throw notSourceError("limit_exceeded", { limit: "max_input_bytes", configured: opts.limits.maxInputBytes }, `wire input exceeds max_input_bytes (${opts.limits.maxInputBytes})`);
1443
2454
  }
1444
2455
  const sourceBytes = sourceInput !== undefined ? toInputBytes(sourceInput) : undefined;
1445
2456
  const maxJsonDepth = opts.limits.maxDepth * 4 + 32;
@@ -1462,13 +2473,14 @@ export function decodeWire(wireJson, options, sourceInput) {
1462
2473
  throw notSourceError("internal", {}, "documents must be an array");
1463
2474
  }
1464
2475
  if (docsVal.items.length > opts.limits.maxDocuments) {
1465
- throw notSourceError("internal", {}, "wire document count exceeds max_documents");
2476
+ throw notSourceError("limit_exceeded", { limit: "max_documents", configured: opts.limits.maxDocuments }, `wire document count exceeds max_documents (${opts.limits.maxDocuments})`);
1466
2477
  }
1467
2478
  const idx = sourceBytes !== undefined ? new Utf16Index(sourceBytes) : null;
1468
2479
  const ctx = {
1469
2480
  opts,
1470
2481
  idx,
1471
2482
  nodesRemaining: opts.limits.maxNodes,
2483
+ ownedBytes: 0n,
1472
2484
  forbidLocations: false,
1473
2485
  };
1474
2486
  const documents = [];
@@ -1485,13 +2497,13 @@ export function decodeWire(wireJson, options, sourceInput) {
1485
2497
  }
1486
2498
  const major = expectInt(yvVal.items[0], "yaml_version.major");
1487
2499
  const minor = expectInt(yvVal.items[1], "yaml_version.minor");
1488
- if (major > 0xffffffff || minor > 0xffffffff) {
1489
- throw notSourceError("internal", {}, "yaml_version exceeds u32 range");
2500
+ if (major !== 1 || minor > 999_999_999) {
2501
+ throw notSourceError("internal", {}, "unsupported yaml_version in wire Document");
1490
2502
  }
1491
2503
  yamlVersion = [major, minor];
1492
2504
  }
1493
2505
  const explicitStart = expectBool(d.map.get("explicit_start"), "explicit_start");
1494
- const rootNode = decodeNode(d.map.get("root"), ctx, 0);
2506
+ const rootNode = decodeNode(d.map.get("root"), ctx, 0, false);
1495
2507
  documents.push({ yamlVersion, explicitStart, root: rootNode });
1496
2508
  }
1497
2509
  return { kind: "documents", documents };
@@ -1646,109 +2658,7 @@ class BoundedWriter {
1646
2658
  throw notSourceError("output_limit_exceeded", { configured: this.maxBytes }, `encoded output exceeds max_output_bytes (${this.maxBytes})`);
1647
2659
  }
1648
2660
  }
1649
- function writeNodeValue(w, n, withSpans, st, depth) {
1650
- if (st.nodesRemaining <= 0) {
1651
- throw notSourceError("limit_exceeded", { limit: "max_nodes", configured: st.opts.limits.maxNodes }, "tree exceeds max_nodes");
1652
- }
1653
- st.nodesRemaining -= 1;
1654
- if (st.activeAncestors.has(n)) {
1655
- throw notSourceError("limit_exceeded", { limit: "max_depth", configured: st.opts.limits.maxDepth }, "cyclic node graph exceeds max_depth");
1656
- }
1657
- w.pushRaw('{"kind":');
1658
- w.pushString(n.kind);
1659
- switch (n.kind) {
1660
- case "null":
1661
- break;
1662
- case "bool":
1663
- w.pushRaw(n.value ? ',"value":true' : ',"value":false');
1664
- break;
1665
- case "int": {
1666
- if (typeof n.value !== "bigint" || n.value < I128_MIN || n.value > U128_MAX) {
1667
- throw notSourceError("integer_out_of_range", {}, "integer node out of 128-bit range");
1668
- }
1669
- w.pushRaw(',"value":');
1670
- w.pushString(n.value.toString(10));
1671
- break;
1672
- }
1673
- case "float": {
1674
- w.pushRaw(',"bits":');
1675
- w.pushString(floatToBits(n.value));
1676
- break;
1677
- }
1678
- case "string": {
1679
- w.pushRaw(',"value":');
1680
- w.pushString(n.value);
1681
- break;
1682
- }
1683
- case "sequence": {
1684
- if (depth + 1 > st.opts.limits.maxDepth) {
1685
- throw notSourceError("limit_exceeded", { limit: "max_depth", configured: st.opts.limits.maxDepth }, "sequence nesting exceeds max_depth");
1686
- }
1687
- st.activeAncestors.add(n);
1688
- w.pushRaw(',"items":[');
1689
- for (let i = 0; i < n.items.length; i++) {
1690
- if (i > 0)
1691
- w.pushRaw(",");
1692
- writeNode(w, n.items[i], withSpans, st, depth + 1);
1693
- }
1694
- w.pushRaw("]");
1695
- st.activeAncestors.delete(n);
1696
- break;
1697
- }
1698
- case "mapping": {
1699
- if (depth + 1 > st.opts.limits.maxDepth) {
1700
- throw notSourceError("limit_exceeded", { limit: "max_depth", configured: st.opts.limits.maxDepth }, "mapping nesting exceeds max_depth");
1701
- }
1702
- if (n.entries.length > st.opts.limits.maxMappingEntries) {
1703
- throw notSourceError("limit_exceeded", { limit: "max_mapping_entries", configured: st.opts.limits.maxMappingEntries }, "mapping entries exceed max_mapping_entries");
1704
- }
1705
- st.activeAncestors.add(n);
1706
- w.pushRaw(',"entries":[');
1707
- for (let i = 0; i < n.entries.length; i++) {
1708
- const [k, v] = n.entries[i];
1709
- if (containsNan(k)) {
1710
- throw notSourceError("invalid_key", {}, "mapping key contains NaN");
1711
- }
1712
- for (let j = 0; j < i; j++) {
1713
- if (keyEq(n.entries[j][0], k)) {
1714
- throw notSourceError("duplicate_key", {}, "duplicate mapping key");
1715
- }
1716
- }
1717
- if (i > 0)
1718
- w.pushRaw(",");
1719
- w.pushRaw('{"key":');
1720
- writeNode(w, k, withSpans, st, depth + 1);
1721
- w.pushRaw(',"value":');
1722
- writeNode(w, v, withSpans, st, depth + 1);
1723
- w.pushRaw("}");
1724
- }
1725
- w.pushRaw("]");
1726
- st.activeAncestors.delete(n);
1727
- break;
1728
- }
1729
- case "tagged": {
1730
- if (!n.tag || typeof n.tag.uri !== "string" || n.tag.uri.length === 0) {
1731
- throw notSourceError("internal", {}, "tagged node must have a non-empty tag.uri");
1732
- }
1733
- if (n.value.kind === "tagged") {
1734
- throw notSourceError("internal", {}, "nested Tagged-in-Tagged is invalid in yamlprims-value/1");
1735
- }
1736
- st.activeAncestors.add(n);
1737
- w.pushRaw(',"tag":{"uri":');
1738
- w.pushString(n.tag.uri);
1739
- w.pushRaw(',"handle":');
1740
- w.pushString(n.tag.handle ?? "");
1741
- w.pushRaw(',"suffix":');
1742
- w.pushString(n.tag.suffix ?? "");
1743
- w.pushRaw('},"value":');
1744
- writeNode(w, n.value, withSpans, st, depth);
1745
- st.activeAncestors.delete(n);
1746
- break;
1747
- }
1748
- }
1749
- }
1750
- function writeNode(w, n, withSpans, st, depth) {
1751
- writeNodeValue(w, n, withSpans, st, depth);
2661
+ function finishNodeLocations(w, n, withSpans) {
1752
2662
  w.pushRaw(',"span":');
1753
2663
  if (withSpans && n.span !== null && n.span !== undefined) {
1754
2664
  w.pushSpan(n.span);
@@ -1781,6 +2691,183 @@ function writeNode(w, n, withSpans, st, depth) {
1781
2691
  }
1782
2692
  w.pushRaw("}");
1783
2693
  }
2694
+ function runWriteNodeFrames(w, rootNode, withSpans, st, rootDepth, finishRootLocations) {
2695
+ const stack = [
2696
+ { op: "node", node: rootNode, depth: rootDepth, finishLoc: finishRootLocations },
2697
+ ];
2698
+ while (stack.length > 0) {
2699
+ const frame = stack.pop();
2700
+ switch (frame.op) {
2701
+ case "raw":
2702
+ w.pushRaw(frame.text);
2703
+ break;
2704
+ case "finishLoc":
2705
+ finishNodeLocations(w, frame.node, withSpans);
2706
+ break;
2707
+ case "leaveObj":
2708
+ st.activeAncestors.delete(frame.obj);
2709
+ break;
2710
+ case "seq": {
2711
+ if (frame.idx >= frame.items.length) {
2712
+ w.pushRaw("]");
2713
+ st.activeAncestors.delete(frame.owner);
2714
+ }
2715
+ else {
2716
+ if (frame.idx > 0)
2717
+ w.pushRaw(",");
2718
+ stack.push({
2719
+ op: "seq",
2720
+ items: frame.items,
2721
+ idx: frame.idx + 1,
2722
+ depth: frame.depth,
2723
+ owner: frame.owner,
2724
+ });
2725
+ stack.push({
2726
+ op: "node",
2727
+ node: frame.items[frame.idx],
2728
+ depth: frame.depth,
2729
+ finishLoc: true,
2730
+ });
2731
+ }
2732
+ break;
2733
+ }
2734
+ case "map": {
2735
+ if (frame.idx >= frame.entries.length) {
2736
+ w.pushRaw("]");
2737
+ st.activeAncestors.delete(frame.owner);
2738
+ }
2739
+ else {
2740
+ const [k, v] = frame.entries[frame.idx];
2741
+ if (containsNan(k)) {
2742
+ st.activeAncestors.delete(frame.owner);
2743
+ throw notSourceError("invalid_key", {}, "mapping key contains NaN");
2744
+ }
2745
+ if (!frame.keyIndex.checkAndInsert(k)) {
2746
+ st.activeAncestors.delete(frame.owner);
2747
+ throw notSourceError("duplicate_key", {}, "duplicate mapping key");
2748
+ }
2749
+ if (frame.idx > 0)
2750
+ w.pushRaw(",");
2751
+ w.pushRaw('{"key":');
2752
+ stack.push({
2753
+ op: "map",
2754
+ entries: frame.entries,
2755
+ idx: frame.idx + 1,
2756
+ depth: frame.depth,
2757
+ owner: frame.owner,
2758
+ keyIndex: frame.keyIndex,
2759
+ });
2760
+ stack.push({ op: "raw", text: "}" });
2761
+ stack.push({ op: "node", node: v, depth: frame.depth, finishLoc: true });
2762
+ stack.push({ op: "raw", text: ',"value":' });
2763
+ stack.push({ op: "node", node: k, depth: frame.depth, finishLoc: true });
2764
+ }
2765
+ break;
2766
+ }
2767
+ case "node": {
2768
+ const n = frame.node;
2769
+ const depth = frame.depth;
2770
+ if (st.nodesRemaining <= 0) {
2771
+ throw notSourceError("limit_exceeded", { limit: "max_nodes", configured: st.opts.limits.maxNodes }, "tree exceeds max_nodes");
2772
+ }
2773
+ st.nodesRemaining -= 1;
2774
+ if (st.activeAncestors.has(n)) {
2775
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: st.opts.limits.maxDepth }, "cyclic node graph exceeds max_depth");
2776
+ }
2777
+ if (frame.finishLoc) {
2778
+ stack.push({ op: "finishLoc", node: n });
2779
+ }
2780
+ w.pushRaw('{"kind":');
2781
+ w.pushString(n.kind);
2782
+ switch (n.kind) {
2783
+ case "null":
2784
+ break;
2785
+ case "bool":
2786
+ w.pushRaw(n.value ? ',"value":true' : ',"value":false');
2787
+ break;
2788
+ case "int": {
2789
+ if (typeof n.value !== "bigint" || n.value < I128_MIN || n.value > U128_MAX) {
2790
+ throw notSourceError("integer_out_of_range", {}, "integer node out of 128-bit range");
2791
+ }
2792
+ w.pushRaw(',"value":');
2793
+ w.pushString(n.value.toString(10));
2794
+ break;
2795
+ }
2796
+ case "float": {
2797
+ w.pushRaw(',"bits":');
2798
+ w.pushString(floatToBits(n.value));
2799
+ break;
2800
+ }
2801
+ case "string": {
2802
+ w.pushRaw(',"value":');
2803
+ w.pushString(n.value);
2804
+ break;
2805
+ }
2806
+ case "sequence": {
2807
+ if (depth + 1 > st.opts.limits.maxDepth) {
2808
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: st.opts.limits.maxDepth }, "sequence nesting exceeds max_depth");
2809
+ }
2810
+ st.activeAncestors.add(n);
2811
+ w.pushRaw(',"items":[');
2812
+ stack.push({
2813
+ op: "seq",
2814
+ items: n.items,
2815
+ idx: 0,
2816
+ depth: depth + 1,
2817
+ owner: n,
2818
+ });
2819
+ break;
2820
+ }
2821
+ case "mapping": {
2822
+ if (depth + 1 > st.opts.limits.maxDepth) {
2823
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: st.opts.limits.maxDepth }, "mapping nesting exceeds max_depth");
2824
+ }
2825
+ if (n.entries.length > st.opts.limits.maxMappingEntries) {
2826
+ throw notSourceError("limit_exceeded", { limit: "max_mapping_entries", configured: st.opts.limits.maxMappingEntries }, "mapping entries exceed max_mapping_entries");
2827
+ }
2828
+ st.activeAncestors.add(n);
2829
+ w.pushRaw(',"entries":[');
2830
+ stack.push({
2831
+ op: "map",
2832
+ entries: n.entries,
2833
+ idx: 0,
2834
+ depth: depth + 1,
2835
+ owner: n,
2836
+ keyIndex: new KeyIndex(),
2837
+ });
2838
+ break;
2839
+ }
2840
+ case "tagged": {
2841
+ if (!n.tag || typeof n.tag.uri !== "string" || n.tag.uri.length === 0) {
2842
+ throw notSourceError("internal", {}, "tagged node must have a non-empty tag.uri");
2843
+ }
2844
+ if (n.value.kind === "tagged") {
2845
+ throw notSourceError("internal", {}, "nested Tagged-in-Tagged is invalid in yamlprims-value/1");
2846
+ }
2847
+ st.activeAncestors.add(n);
2848
+ w.pushRaw(',"tag":{"uri":');
2849
+ w.pushString(n.tag.uri);
2850
+ w.pushRaw(',"handle":');
2851
+ w.pushString(n.tag.handle ?? "");
2852
+ w.pushRaw(',"suffix":');
2853
+ w.pushString(n.tag.suffix ?? "");
2854
+ w.pushRaw('},"value":');
2855
+ stack.push({ op: "leaveObj", obj: n });
2856
+ stack.push({ op: "node", node: n.value, depth, finishLoc: true });
2857
+ break;
2858
+ }
2859
+ }
2860
+ break;
2861
+ }
2862
+ }
2863
+ }
2864
+ }
2865
+ function writeNodeValue(w, n, withSpans, st, depth) {
2866
+ runWriteNodeFrames(w, n, withSpans, st, depth, false);
2867
+ }
2868
+ function writeNode(w, n, withSpans, st, depth) {
2869
+ runWriteNodeFrames(w, n, withSpans, st, depth, true);
2870
+ }
1784
2871
  export function encode(docs, options) {
1785
2872
  const opts = validateOptions(options);
1786
2873
  if (docs.length > opts.limits.maxDocuments) {
@@ -1999,9 +3086,18 @@ export function encodeError(err, options) {
1999
3086
  w.pushSpan(r.span);
2000
3087
  w.pushRaw("}");
2001
3088
  }
3089
+ const pathOpts = {
3090
+ mergeKeys: opts.mergeKeys,
3091
+ unknownTags: opts.unknownTags,
3092
+ limits: {
3093
+ ...opts.limits,
3094
+ maxDepth: 255,
3095
+ maxNodes: MAX_SAFE_METADATA_INT,
3096
+ },
3097
+ };
2002
3098
  const st = {
2003
- opts,
2004
- nodesRemaining: opts.limits.maxNodes,
3099
+ opts: pathOpts,
3100
+ nodesRemaining: MAX_SAFE_METADATA_INT,
2005
3101
  activeAncestors: new Set(),
2006
3102
  };
2007
3103
  w.pushRaw('],"path":[');
@@ -2052,7 +3148,70 @@ export function toPlain(nodeOrDoc, options) {
2052
3148
  const root = isDocument(nodeOrDoc) ? nodeOrDoc.root : nodeOrDoc;
2053
3149
  let nodesRemaining = opts.limits.maxNodes;
2054
3150
  const active = new Set();
2055
- function walk(n, depth) {
3151
+ const work = [{ op: "eval", node: root, depth: 0 }];
3152
+ const results = [];
3153
+ while (work.length > 0) {
3154
+ const frame = work.pop();
3155
+ if (frame.op === "seqStep") {
3156
+ if (frame.idx > 0) {
3157
+ frame.out.push(results.pop());
3158
+ }
3159
+ if (frame.idx >= frame.items.length) {
3160
+ active.delete(frame.owner);
3161
+ results.push(frame.out);
3162
+ }
3163
+ else {
3164
+ work.push({
3165
+ op: "seqStep",
3166
+ items: frame.items,
3167
+ idx: frame.idx + 1,
3168
+ nextDepth: frame.nextDepth,
3169
+ owner: frame.owner,
3170
+ out: frame.out,
3171
+ });
3172
+ work.push({ op: "eval", node: frame.items[frame.idx], depth: frame.nextDepth });
3173
+ }
3174
+ continue;
3175
+ }
3176
+ if (frame.op === "mapStep") {
3177
+ if (frame.pendingKey !== null) {
3178
+ frame.obj[frame.pendingKey] = results.pop();
3179
+ }
3180
+ if (frame.idx >= frame.entries.length) {
3181
+ active.delete(frame.owner);
3182
+ results.push(frame.obj);
3183
+ }
3184
+ else {
3185
+ const [k, v] = frame.entries[frame.idx];
3186
+ if (k.kind !== "string") {
3187
+ active.delete(frame.owner);
3188
+ throw lossError(k, "non-string key");
3189
+ }
3190
+ try {
3191
+ assertWellFormedUnicode(k.value, "mapping key");
3192
+ }
3193
+ catch (err) {
3194
+ active.delete(frame.owner);
3195
+ throw err;
3196
+ }
3197
+ if (Object.prototype.hasOwnProperty.call(frame.obj, k.value)) {
3198
+ active.delete(frame.owner);
3199
+ throw notSourceError("duplicate_key", {}, "duplicate mapping key");
3200
+ }
3201
+ work.push({
3202
+ op: "mapStep",
3203
+ entries: frame.entries,
3204
+ idx: frame.idx + 1,
3205
+ nextDepth: frame.nextDepth,
3206
+ owner: frame.owner,
3207
+ obj: frame.obj,
3208
+ pendingKey: k.value,
3209
+ });
3210
+ work.push({ op: "eval", node: v, depth: frame.nextDepth });
3211
+ }
3212
+ continue;
3213
+ }
3214
+ const { node: n, depth } = frame;
2056
3215
  if (nodesRemaining <= 0) {
2057
3216
  throw notSourceError("limit_exceeded", { limit: "max_nodes", configured: opts.limits.maxNodes }, "tree exceeds max_nodes");
2058
3217
  }
@@ -2062,72 +3221,108 @@ export function toPlain(nodeOrDoc, options) {
2062
3221
  }
2063
3222
  switch (n.kind) {
2064
3223
  case "null":
2065
- return null;
3224
+ results.push(null);
3225
+ break;
2066
3226
  case "bool":
2067
- return n.value;
3227
+ results.push(n.value);
3228
+ break;
2068
3229
  case "int": {
2069
3230
  const maxSafe = BigInt(MAX_SAFE_METADATA_INT);
2070
3231
  if (n.value < -maxSafe || n.value > maxSafe) {
2071
3232
  throw lossError(n, "integer outside safe integer range");
2072
3233
  }
2073
- return n.value === 0n ? 0 : Number(n.value);
3234
+ results.push(n.value === 0n ? 0 : Number(n.value));
3235
+ break;
2074
3236
  }
2075
3237
  case "float":
2076
- return n.value;
3238
+ results.push(n.value);
3239
+ break;
2077
3240
  case "string":
2078
3241
  assertWellFormedUnicode(n.value, "string node");
2079
- return n.value;
3242
+ results.push(n.value);
3243
+ break;
2080
3244
  case "sequence": {
2081
3245
  if (depth + 1 > opts.limits.maxDepth) {
2082
3246
  throw notSourceError("limit_exceeded", { limit: "max_depth", configured: opts.limits.maxDepth }, "sequence nesting exceeds max_depth");
2083
3247
  }
2084
3248
  active.add(n);
2085
- const out = n.items.map((it) => walk(it, depth + 1));
2086
- active.delete(n);
2087
- return out;
3249
+ work.push({
3250
+ op: "seqStep",
3251
+ items: n.items,
3252
+ idx: 0,
3253
+ nextDepth: depth + 1,
3254
+ owner: n,
3255
+ out: [],
3256
+ });
3257
+ break;
2088
3258
  }
2089
3259
  case "mapping": {
2090
3260
  if (depth + 1 > opts.limits.maxDepth) {
2091
3261
  throw notSourceError("limit_exceeded", { limit: "max_depth", configured: opts.limits.maxDepth }, "mapping nesting exceeds max_depth");
2092
3262
  }
2093
3263
  active.add(n);
2094
- const obj = Object.create(null);
2095
- for (const [k, v] of n.entries) {
2096
- if (k.kind !== "string") {
2097
- active.delete(n);
2098
- throw lossError(k, "non-string key");
2099
- }
2100
- try {
2101
- assertWellFormedUnicode(k.value, "mapping key");
2102
- }
2103
- catch (err) {
2104
- active.delete(n);
2105
- throw err;
2106
- }
2107
- if (Object.prototype.hasOwnProperty.call(obj, k.value)) {
2108
- active.delete(n);
2109
- throw notSourceError("duplicate_key", {}, "duplicate mapping key");
2110
- }
2111
- obj[k.value] = walk(v, depth + 1);
2112
- }
2113
- active.delete(n);
2114
- return obj;
3264
+ work.push({
3265
+ op: "mapStep",
3266
+ entries: n.entries,
3267
+ idx: 0,
3268
+ nextDepth: depth + 1,
3269
+ owner: n,
3270
+ obj: Object.create(null),
3271
+ pendingKey: null,
3272
+ });
3273
+ break;
2115
3274
  }
2116
3275
  case "tagged":
2117
3276
  throw lossError(n, "tagged value");
2118
3277
  }
2119
3278
  }
2120
- return walk(root, 0);
3279
+ return results.pop();
2121
3280
  }
2122
3281
  function formatPlainFloat(f) {
2123
- if (Object.is(f, -0)) {
2124
- return "-0.0";
3282
+ if (f === 0) {
3283
+ return Object.is(f, -0) ? "-0.0" : "0.0";
3284
+ }
3285
+ const prefix = f < 0 ? "-" : "";
3286
+ const s = String(Math.abs(f));
3287
+ let digits;
3288
+ let exp;
3289
+ const eIdx = s.search(/e/i);
3290
+ if (eIdx !== -1) {
3291
+ const mant = s.slice(0, eIdx);
3292
+ exp = Number.parseInt(s.slice(eIdx + 1), 10);
3293
+ digits = mant.replace(".", "");
3294
+ }
3295
+ else if (s.includes(".")) {
3296
+ if (s.startsWith("0.")) {
3297
+ let z = 0;
3298
+ while (2 + z < s.length && s.charCodeAt(2 + z) === 0x30) {
3299
+ z++;
3300
+ }
3301
+ digits = s.slice(2 + z);
3302
+ exp = -(z + 1);
3303
+ }
3304
+ else {
3305
+ const dotIdx = s.indexOf(".");
3306
+ digits = s.slice(0, dotIdx) + s.slice(dotIdx + 1);
3307
+ exp = dotIdx - 1;
3308
+ }
2125
3309
  }
2126
- const s = String(f);
2127
- if (!s.includes(".") && !s.includes("e") && !s.includes("E")) {
2128
- return s + ".0";
3310
+ else {
3311
+ digits = s.replace(/0+$/, "");
3312
+ exp = s.length - 1;
3313
+ }
3314
+ if (exp >= -4 && exp < 16) {
3315
+ if (exp >= 0) {
3316
+ const intDigits = exp + 1;
3317
+ if (digits.length <= intDigits) {
3318
+ return prefix + digits + "0".repeat(intDigits - digits.length) + ".0";
3319
+ }
3320
+ return prefix + digits.slice(0, intDigits) + "." + digits.slice(intDigits);
3321
+ }
3322
+ return prefix + "0." + "0".repeat(-exp - 1) + digits;
2129
3323
  }
2130
- return s.replace("e+", "e");
3324
+ const mant = digits.length === 1 ? digits : `${digits[0]}.${digits.slice(1)}`;
3325
+ return `${prefix}${mant}e${exp}`;
2131
3326
  }
2132
3327
  export function encodePlain(nodeOrDoc, options) {
2133
3328
  const opts = validateOptions(options);
@@ -2135,7 +3330,55 @@ export function encodePlain(nodeOrDoc, options) {
2135
3330
  const w = new BoundedWriter(opts.limits.maxOutputBytes);
2136
3331
  let nodesRemaining = opts.limits.maxNodes;
2137
3332
  const active = new Set();
2138
- function walk(n, depth) {
3333
+ const stack = [{ op: "eval", node: root, depth: 0 }];
3334
+ while (stack.length > 0) {
3335
+ const frame = stack.pop();
3336
+ if (frame.op === "seqStep") {
3337
+ if (frame.idx >= frame.items.length) {
3338
+ w.pushRaw("]");
3339
+ active.delete(frame.owner);
3340
+ }
3341
+ else {
3342
+ if (frame.idx > 0)
3343
+ w.pushRaw(",");
3344
+ stack.push({
3345
+ op: "seqStep",
3346
+ items: frame.items,
3347
+ idx: frame.idx + 1,
3348
+ nextDepth: frame.nextDepth,
3349
+ owner: frame.owner,
3350
+ });
3351
+ stack.push({ op: "eval", node: frame.items[frame.idx], depth: frame.nextDepth });
3352
+ }
3353
+ continue;
3354
+ }
3355
+ if (frame.op === "mapStep") {
3356
+ if (frame.idx >= frame.entries.length) {
3357
+ w.pushRaw("}");
3358
+ active.delete(frame.owner);
3359
+ }
3360
+ else {
3361
+ const [k, v] = frame.entries[frame.idx];
3362
+ if (k.kind !== "string") {
3363
+ active.delete(frame.owner);
3364
+ throw lossError(k, "non-string key");
3365
+ }
3366
+ if (frame.idx > 0)
3367
+ w.pushRaw(",");
3368
+ w.pushString(k.value);
3369
+ w.pushRaw(":");
3370
+ stack.push({
3371
+ op: "mapStep",
3372
+ entries: frame.entries,
3373
+ idx: frame.idx + 1,
3374
+ nextDepth: frame.nextDepth,
3375
+ owner: frame.owner,
3376
+ });
3377
+ stack.push({ op: "eval", node: v, depth: frame.nextDepth });
3378
+ }
3379
+ continue;
3380
+ }
3381
+ const { node: n, depth } = frame;
2139
3382
  if (nodesRemaining <= 0) {
2140
3383
  throw notSourceError("limit_exceeded", { limit: "max_nodes", configured: opts.limits.maxNodes }, "tree exceeds max_nodes");
2141
3384
  }
@@ -2168,13 +3411,13 @@ export function encodePlain(nodeOrDoc, options) {
2168
3411
  }
2169
3412
  active.add(n);
2170
3413
  w.pushRaw("[");
2171
- for (let i = 0; i < n.items.length; i++) {
2172
- if (i > 0)
2173
- w.pushRaw(",");
2174
- walk(n.items[i], depth + 1);
2175
- }
2176
- w.pushRaw("]");
2177
- active.delete(n);
3414
+ stack.push({
3415
+ op: "seqStep",
3416
+ items: n.items,
3417
+ idx: 0,
3418
+ nextDepth: depth + 1,
3419
+ owner: n,
3420
+ });
2178
3421
  break;
2179
3422
  case "mapping":
2180
3423
  if (depth + 1 > opts.limits.maxDepth) {
@@ -2182,29 +3425,46 @@ export function encodePlain(nodeOrDoc, options) {
2182
3425
  }
2183
3426
  active.add(n);
2184
3427
  w.pushRaw("{");
2185
- for (let i = 0; i < n.entries.length; i++) {
2186
- const [k, v] = n.entries[i];
2187
- if (k.kind !== "string") {
2188
- active.delete(n);
2189
- throw lossError(k, "non-string key");
2190
- }
2191
- if (i > 0)
2192
- w.pushRaw(",");
2193
- w.pushString(k.value);
2194
- w.pushRaw(":");
2195
- walk(v, depth + 1);
2196
- }
2197
- w.pushRaw("}");
2198
- active.delete(n);
3428
+ stack.push({
3429
+ op: "mapStep",
3430
+ entries: n.entries,
3431
+ idx: 0,
3432
+ nextDepth: depth + 1,
3433
+ owner: n,
3434
+ });
2199
3435
  break;
2200
3436
  case "tagged":
2201
3437
  throw lossError(n, "tagged value");
2202
3438
  }
2203
3439
  }
2204
- walk(root, 0);
2205
3440
  return w.finish();
2206
3441
  }
2207
3442
  // ---- Primary entrypoints -------------------------------------------------
3443
+ function widenBridgeOptions(opts, payloadByteLen) {
3444
+ const lim = opts.limits;
3445
+ const bridgeNodes = Math.max(lim.maxNodes, lim.maxExpandedNodes, 250_000);
3446
+ const bridgeOwned = Math.max(lim.maxOwnedBytes, Math.min(MAX_SAFE_METADATA_INT, payloadByteLen * 4 + 65_536));
3447
+ const bridgeScalar = Math.min(bridgeOwned, Math.max(lim.maxScalarBytes, payloadByteLen));
3448
+ const bridgeKey = Math.min(bridgeOwned, Math.max(lim.maxKeyBytes, payloadByteLen));
3449
+ return {
3450
+ mergeKeys: opts.mergeKeys,
3451
+ unknownTags: opts.unknownTags,
3452
+ limits: {
3453
+ maxInputBytes: Math.max(lim.maxInputBytes, lim.maxOutputBytes, payloadByteLen, 1),
3454
+ maxDepth: 255,
3455
+ maxNodes: bridgeNodes,
3456
+ maxExpandedNodes: Math.max(lim.maxExpandedNodes, bridgeNodes),
3457
+ maxAliasEvents: lim.maxAliasEvents,
3458
+ maxOwnedBytes: bridgeOwned,
3459
+ maxScalarBytes: bridgeScalar,
3460
+ maxKeyBytes: bridgeKey,
3461
+ maxMappingEntries: Math.max(lim.maxMappingEntries, 250_000),
3462
+ maxDocuments: Math.max(lim.maxDocuments, 1_024),
3463
+ maxOutputBytes: Math.max(lim.maxOutputBytes, payloadByteLen, 1),
3464
+ maxWarnings: lim.maxWarnings,
3465
+ },
3466
+ };
3467
+ }
2208
3468
  export function loadAll(input, options) {
2209
3469
  const opts = validateOptions(options);
2210
3470
  const inputBytes = toInputBytes(input);
@@ -2213,7 +3473,7 @@ export function loadAll(input, options) {
2213
3473
  throw decodeFallbackStatus2(output, opts.limits.maxOutputBytes);
2214
3474
  }
2215
3475
  const wireText = decoder.decode(output);
2216
- const decoded = decodeWire(wireText, opts, inputBytes);
3476
+ const decoded = decodeWire(wireText, widenBridgeOptions(opts, output.byteLength), inputBytes);
2217
3477
  if (decoded.kind === "error") {
2218
3478
  throw decoded.error;
2219
3479
  }
@@ -2227,7 +3487,7 @@ export function load(input, options) {
2227
3487
  throw decodeFallbackStatus2(output, opts.limits.maxOutputBytes);
2228
3488
  }
2229
3489
  const wireText = decoder.decode(output);
2230
- const decoded = decodeWire(wireText, opts, inputBytes);
3490
+ const decoded = decodeWire(wireText, widenBridgeOptions(opts, output.byteLength), inputBytes);
2231
3491
  if (decoded.kind === "error") {
2232
3492
  throw decoded.error;
2233
3493
  }
@@ -2257,7 +3517,7 @@ export function loadPlain(input, options) {
2257
3517
  }
2258
3518
  const text = decoder.decode(output);
2259
3519
  if (status === 1) {
2260
- const decoded = decodeWire(text, opts, inputBytes);
3520
+ const decoded = decodeWire(text, widenBridgeOptions(opts, output.byteLength), inputBytes);
2261
3521
  if (decoded.kind === "error") {
2262
3522
  throw decoded.error;
2263
3523
  }
@@ -2265,6 +3525,831 @@ export function loadPlain(input, options) {
2265
3525
  }
2266
3526
  return text;
2267
3527
  }
3528
+ function toIjsonInputBytes(input) {
3529
+ if (typeof input === "string") {
3530
+ for (let i = 0; i < input.length; i++) {
3531
+ const code = input.charCodeAt(i);
3532
+ if (code >= 0xd800 && code <= 0xdbff) {
3533
+ const next = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
3534
+ if (next < 0xdc00 || next > 0xdfff) {
3535
+ throw notSourceError("invalid_utf8", { invalid_len: null }, "input string contains an unpaired high surrogate");
3536
+ }
3537
+ i++;
3538
+ }
3539
+ else if (code >= 0xdc00 && code <= 0xdfff) {
3540
+ throw notSourceError("invalid_utf8", { invalid_len: null }, "input string contains an unpaired low surrogate");
3541
+ }
3542
+ }
3543
+ return encoder.encode(input);
3544
+ }
3545
+ if (input instanceof Uint8Array) {
3546
+ return input;
3547
+ }
3548
+ throw new TypeError("input must be a string or Uint8Array");
3549
+ }
3550
+ export function loadIjson(input, options) {
3551
+ const opts = validateIjsonOptions(options);
3552
+ const inputBytes = toIjsonInputBytes(input);
3553
+ const { status, output } = runWasmLoad(inputBytes, opts, "ijson");
3554
+ if (status === 2) {
3555
+ throw decodeFallbackStatus2(output, opts.limits.maxOutputBytes);
3556
+ }
3557
+ const text = decoder.decode(output);
3558
+ if (status === 1) {
3559
+ const decoded = decodeWire(text, widenBridgeOptions(opts, output.byteLength), inputBytes);
3560
+ if (decoded.kind === "error") {
3561
+ throw decoded.error;
3562
+ }
3563
+ throw notSourceError("internal", {}, "expected error envelope from load_ijson status 1");
3564
+ }
3565
+ return text;
3566
+ }
3567
+ // ---- Host emission & fromPlain (`spec-v1.5 §10.2`, `§11.3`, `§11.5`) -----
3568
+ function validateUtf8Str(s) {
3569
+ if (typeof s !== "string") {
3570
+ throw notSourceError("type", { expected: "string", found: typeof s }, `expected string, found ${typeof s}`);
3571
+ }
3572
+ for (let i = 0; i < s.length; i++) {
3573
+ const code = s.charCodeAt(i);
3574
+ if (code >= 0xd800 && code <= 0xdbff) {
3575
+ const next = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
3576
+ if (next < 0xdc00 || next > 0xdfff) {
3577
+ throw notSourceError("invalid_utf8", { invalid_len: null }, "string contains unpaired high surrogate");
3578
+ }
3579
+ i++;
3580
+ }
3581
+ else if (code >= 0xdc00 && code <= 0xdfff) {
3582
+ throw notSourceError("invalid_utf8", { invalid_len: null }, "string contains unpaired low surrogate");
3583
+ }
3584
+ }
3585
+ return encoder.encode(s);
3586
+ }
3587
+ function renderedTagMinBytes(uriBytes, uri) {
3588
+ const n = BigInt(uriBytes.byteLength);
3589
+ if (uri.startsWith("tag:yaml.org,2002:") && n > 18n) {
3590
+ return 2n + (n - 18n);
3591
+ }
3592
+ return n;
3593
+ }
3594
+ const NODE_META_KEYS = new Set(["kind", "span", "via", "tagStart"]);
3595
+ function hasOwn(obj, prop) {
3596
+ return Object.prototype.hasOwnProperty.call(obj, prop);
3597
+ }
3598
+ function isNodeObject(v) {
3599
+ if (!v || typeof v !== "object" || Array.isArray(v) || v instanceof Mapping || v instanceof Map) {
3600
+ return false;
3601
+ }
3602
+ const obj = v;
3603
+ if (!hasOwn(obj, "kind") || !hasOwn(obj, "span") || !hasOwn(obj, "via") || !hasOwn(obj, "tagStart")) {
3604
+ return false;
3605
+ }
3606
+ const k = obj.kind;
3607
+ if (typeof k !== "string")
3608
+ return false;
3609
+ const keys = Object.keys(obj);
3610
+ const checkKeys = (allowedExtra) => {
3611
+ for (const key of keys) {
3612
+ if (!NODE_META_KEYS.has(key) && !allowedExtra.includes(key)) {
3613
+ return false;
3614
+ }
3615
+ }
3616
+ return true;
3617
+ };
3618
+ switch (k) {
3619
+ case "null":
3620
+ return checkKeys(["value"]) && (!hasOwn(obj, "value") || obj.value === null);
3621
+ case "bool":
3622
+ case "int":
3623
+ case "string":
3624
+ return hasOwn(obj, "value") && checkKeys(["value"]);
3625
+ case "float":
3626
+ return hasOwn(obj, "value") && checkKeys(["value", "bits"]);
3627
+ case "sequence":
3628
+ return hasOwn(obj, "items") && Array.isArray(obj.items) && checkKeys(["items"]);
3629
+ case "mapping":
3630
+ return hasOwn(obj, "entries") && Array.isArray(obj.entries) && checkKeys(["entries"]);
3631
+ case "tagged":
3632
+ return hasOwn(obj, "tag") && hasOwn(obj, "value") && checkKeys(["tag", "value"]);
3633
+ default:
3634
+ return false;
3635
+ }
3636
+ }
3637
+ function isPlainObject(v) {
3638
+ if (!v || typeof v !== "object")
3639
+ return false;
3640
+ const proto = Object.getPrototypeOf(v);
3641
+ return proto === Object.prototype || proto === null;
3642
+ }
3643
+ function checkEmitKeyWeight(rawKey, limits) {
3644
+ const maxKey = BigInt(limits.maxKeyBytes);
3645
+ let total = 0n;
3646
+ const stack = [{ op: "eval", cur: rawKey, ancestors: new Set() }];
3647
+ while (stack.length > 0) {
3648
+ const frame = stack.pop();
3649
+ if (frame.op === "seqStep") {
3650
+ if (frame.idx < frame.items.length) {
3651
+ if (frame.checkHoles && !(frame.idx in frame.items)) {
3652
+ throw notSourceError("type", { expected: "YAML-serializable value", found: "undefined" }, "sparse array holes (undefined) are not YAML-serializable");
3653
+ }
3654
+ stack.push({
3655
+ op: "seqStep",
3656
+ items: frame.items,
3657
+ idx: frame.idx + 1,
3658
+ checkHoles: frame.checkHoles,
3659
+ ancestors: frame.ancestors,
3660
+ });
3661
+ stack.push({ op: "eval", cur: frame.items[frame.idx], ancestors: frame.ancestors });
3662
+ }
3663
+ continue;
3664
+ }
3665
+ if (frame.op === "mapPairsStep") {
3666
+ if (frame.idx < frame.pairs.length) {
3667
+ const [k, v] = frame.pairs[frame.idx];
3668
+ stack.push({
3669
+ op: "mapPairsStep",
3670
+ pairs: frame.pairs,
3671
+ idx: frame.idx + 1,
3672
+ ancestors: frame.ancestors,
3673
+ });
3674
+ stack.push({ op: "eval", cur: v, ancestors: frame.ancestors });
3675
+ stack.push({ op: "eval", cur: k, ancestors: frame.ancestors });
3676
+ }
3677
+ continue;
3678
+ }
3679
+ if (frame.op === "mapIterStep") {
3680
+ const next = frame.iter.next();
3681
+ if (!next.done) {
3682
+ const [k, v] = next.value;
3683
+ stack.push({ op: "mapIterStep", iter: frame.iter, ancestors: frame.ancestors });
3684
+ stack.push({ op: "eval", cur: v, ancestors: frame.ancestors });
3685
+ stack.push({ op: "eval", cur: k, ancestors: frame.ancestors });
3686
+ }
3687
+ continue;
3688
+ }
3689
+ if (frame.op === "objKeysStep") {
3690
+ if (frame.idx < frame.keys.length) {
3691
+ const k = frame.keys[frame.idx];
3692
+ const v = frame.obj[k];
3693
+ stack.push({
3694
+ op: "objKeysStep",
3695
+ obj: frame.obj,
3696
+ keys: frame.keys,
3697
+ idx: frame.idx + 1,
3698
+ ancestors: frame.ancestors,
3699
+ });
3700
+ stack.push({ op: "eval", cur: v, ancestors: frame.ancestors });
3701
+ stack.push({ op: "eval", cur: k, ancestors: frame.ancestors });
3702
+ }
3703
+ continue;
3704
+ }
3705
+ const { cur, ancestors } = frame;
3706
+ if (isNodeObject(cur)) {
3707
+ if (cur.kind === "string") {
3708
+ const sBytes = validateUtf8Str(cur.value);
3709
+ total += NODE_OVERHEAD + BigInt(sBytes.byteLength);
3710
+ if (total > maxKey) {
3711
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: limits.maxKeyBytes }, `mapping key exceeds max_key_bytes (${limits.maxKeyBytes})`);
3712
+ }
3713
+ continue;
3714
+ }
3715
+ if (cur.kind === "tagged") {
3716
+ if (!cur.tag || typeof cur.tag !== "object") {
3717
+ throw invalidOptionsError("Tagged node must hold a Tag object");
3718
+ }
3719
+ const uriBytes = validateUtf8Str(cur.tag.uri);
3720
+ total += NODE_OVERHEAD + 2n * BigInt(uriBytes.byteLength);
3721
+ if (total > maxKey) {
3722
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: limits.maxKeyBytes }, `mapping key exceeds max_key_bytes (${limits.maxKeyBytes})`);
3723
+ }
3724
+ if (ancestors.has(cur)) {
3725
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `cyclic mapping key exceeds max_depth (${limits.maxDepth})`);
3726
+ }
3727
+ const nextAnc = new Set(ancestors);
3728
+ nextAnc.add(cur);
3729
+ stack.push({ op: "eval", cur: cur.value, ancestors: nextAnc });
3730
+ continue;
3731
+ }
3732
+ if (cur.kind === "null" || cur.kind === "bool" || cur.kind === "int" || cur.kind === "float") {
3733
+ total += NODE_OVERHEAD;
3734
+ if (total > maxKey) {
3735
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: limits.maxKeyBytes }, `mapping key exceeds max_key_bytes (${limits.maxKeyBytes})`);
3736
+ }
3737
+ continue;
3738
+ }
3739
+ if (cur.kind === "sequence") {
3740
+ total += NODE_OVERHEAD;
3741
+ if (total > maxKey) {
3742
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: limits.maxKeyBytes }, `mapping key exceeds max_key_bytes (${limits.maxKeyBytes})`);
3743
+ }
3744
+ if (ancestors.has(cur) || ancestors.has(cur.items)) {
3745
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `cyclic mapping key exceeds max_depth (${limits.maxDepth})`);
3746
+ }
3747
+ const nextAnc = new Set(ancestors);
3748
+ nextAnc.add(cur);
3749
+ nextAnc.add(cur.items);
3750
+ stack.push({ op: "seqStep", items: cur.items, idx: 0, checkHoles: false, ancestors: nextAnc });
3751
+ continue;
3752
+ }
3753
+ if (cur.kind === "mapping") {
3754
+ total += NODE_OVERHEAD + BigInt(cur.entries.length) * ENTRY_OVERHEAD;
3755
+ if (total > maxKey) {
3756
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: limits.maxKeyBytes }, `mapping key exceeds max_key_bytes (${limits.maxKeyBytes})`);
3757
+ }
3758
+ if (ancestors.has(cur) || ancestors.has(cur.entries)) {
3759
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `cyclic mapping key exceeds max_depth (${limits.maxDepth})`);
3760
+ }
3761
+ const nextAnc = new Set(ancestors);
3762
+ nextAnc.add(cur);
3763
+ nextAnc.add(cur.entries);
3764
+ stack.push({ op: "mapPairsStep", pairs: cur.entries, idx: 0, ancestors: nextAnc });
3765
+ continue;
3766
+ }
3767
+ }
3768
+ if (typeof cur === "string") {
3769
+ const sBytes = validateUtf8Str(cur);
3770
+ total += NODE_OVERHEAD + BigInt(sBytes.byteLength);
3771
+ if (total > maxKey) {
3772
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: limits.maxKeyBytes }, `mapping key exceeds max_key_bytes (${limits.maxKeyBytes})`);
3773
+ }
3774
+ continue;
3775
+ }
3776
+ if (cur === null || typeof cur === "boolean" || typeof cur === "bigint" || typeof cur === "number") {
3777
+ total += NODE_OVERHEAD;
3778
+ if (total > maxKey) {
3779
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: limits.maxKeyBytes }, `mapping key exceeds max_key_bytes (${limits.maxKeyBytes})`);
3780
+ }
3781
+ continue;
3782
+ }
3783
+ if (Array.isArray(cur)) {
3784
+ total += NODE_OVERHEAD;
3785
+ if (total > maxKey) {
3786
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: limits.maxKeyBytes }, `mapping key exceeds max_key_bytes (${limits.maxKeyBytes})`);
3787
+ }
3788
+ if (ancestors.has(cur)) {
3789
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `cyclic mapping key exceeds max_depth (${limits.maxDepth})`);
3790
+ }
3791
+ const nextAnc = new Set(ancestors);
3792
+ nextAnc.add(cur);
3793
+ stack.push({ op: "seqStep", items: cur, idx: 0, checkHoles: true, ancestors: nextAnc });
3794
+ continue;
3795
+ }
3796
+ if (cur instanceof Mapping) {
3797
+ total += NODE_OVERHEAD + BigInt(cur.entries.length) * ENTRY_OVERHEAD;
3798
+ if (total > maxKey) {
3799
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: limits.maxKeyBytes }, `mapping key exceeds max_key_bytes (${limits.maxKeyBytes})`);
3800
+ }
3801
+ if (ancestors.has(cur)) {
3802
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `cyclic mapping key exceeds max_depth (${limits.maxDepth})`);
3803
+ }
3804
+ const nextAnc = new Set(ancestors);
3805
+ nextAnc.add(cur);
3806
+ stack.push({ op: "mapPairsStep", pairs: cur.entries, idx: 0, ancestors: nextAnc });
3807
+ continue;
3808
+ }
3809
+ if (cur instanceof Map) {
3810
+ total += NODE_OVERHEAD + BigInt(cur.size) * ENTRY_OVERHEAD;
3811
+ if (total > maxKey) {
3812
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: limits.maxKeyBytes }, `mapping key exceeds max_key_bytes (${limits.maxKeyBytes})`);
3813
+ }
3814
+ if (ancestors.has(cur)) {
3815
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `cyclic mapping key exceeds max_depth (${limits.maxDepth})`);
3816
+ }
3817
+ const nextAnc = new Set(ancestors);
3818
+ nextAnc.add(cur);
3819
+ stack.push({ op: "mapIterStep", iter: cur.entries(), ancestors: nextAnc });
3820
+ continue;
3821
+ }
3822
+ if (isPlainObject(cur)) {
3823
+ const keys = Object.keys(cur);
3824
+ total += NODE_OVERHEAD + BigInt(keys.length) * ENTRY_OVERHEAD;
3825
+ if (total > maxKey) {
3826
+ throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: limits.maxKeyBytes }, `mapping key exceeds max_key_bytes (${limits.maxKeyBytes})`);
3827
+ }
3828
+ if (ancestors.has(cur)) {
3829
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `cyclic mapping key exceeds max_depth (${limits.maxDepth})`);
3830
+ }
3831
+ const nextAnc = new Set(ancestors);
3832
+ nextAnc.add(cur);
3833
+ stack.push({ op: "objKeysStep", obj: cur, keys, idx: 0, ancestors: nextAnc });
3834
+ continue;
3835
+ }
3836
+ throw notSourceError("type", { expected: "YAML-serializable value", found: typeof cur }, `unsupported type for YAML emission: ${typeof cur}`);
3837
+ }
3838
+ }
3839
+ function convertAndPreflightNode(rootRaw, opts, state) {
3840
+ const limits = opts.limits;
3841
+ const active = new Set();
3842
+ const work = [
3843
+ { op: "eval", raw: rootRaw, depth: 0, inKey: false, isKeyRoot: false },
3844
+ ];
3845
+ const results = [];
3846
+ while (work.length > 0) {
3847
+ const frame = work.pop();
3848
+ switch (frame.op) {
3849
+ case "finishTagged": {
3850
+ active.delete(frame.owner);
3851
+ const cleanInner = results.pop();
3852
+ results.push({
3853
+ kind: "tagged",
3854
+ tag: { uri: frame.uri, handle: "", suffix: frame.uri },
3855
+ value: cleanInner,
3856
+ span: null,
3857
+ via: null,
3858
+ tagStart: null,
3859
+ });
3860
+ break;
3861
+ }
3862
+ case "seqStep": {
3863
+ if (frame.idx > 0) {
3864
+ frame.items.push(results.pop());
3865
+ }
3866
+ if (frame.idx >= frame.rawItems.length) {
3867
+ active.delete(frame.owner2);
3868
+ if (frame.owner1 !== null)
3869
+ active.delete(frame.owner1);
3870
+ results.push({ kind: "sequence", items: frame.items, span: null, via: null, tagStart: null });
3871
+ }
3872
+ else {
3873
+ if (frame.checkHoles && !(frame.idx in frame.rawItems)) {
3874
+ throw notSourceError("type", { expected: "YAML-serializable value", found: "undefined" }, "sparse array holes (undefined) are not YAML-serializable");
3875
+ }
3876
+ work.push({
3877
+ op: "seqStep",
3878
+ rawItems: frame.rawItems,
3879
+ idx: frame.idx + 1,
3880
+ nextDepth: frame.nextDepth,
3881
+ inKey: frame.inKey,
3882
+ checkHoles: frame.checkHoles,
3883
+ owner1: frame.owner1,
3884
+ owner2: frame.owner2,
3885
+ items: frame.items,
3886
+ });
3887
+ work.push({
3888
+ op: "eval",
3889
+ raw: frame.rawItems[frame.idx],
3890
+ depth: frame.nextDepth,
3891
+ inKey: frame.inKey,
3892
+ isKeyRoot: false,
3893
+ });
3894
+ }
3895
+ break;
3896
+ }
3897
+ case "mapIter": {
3898
+ if (frame.idx >= frame.rawPairs.length) {
3899
+ active.delete(frame.owner2);
3900
+ if (frame.owner1 !== null)
3901
+ active.delete(frame.owner1);
3902
+ results.push({ kind: "mapping", entries: frame.entries, span: null, via: null, tagStart: null });
3903
+ }
3904
+ else {
3905
+ const [rawK, rawV] = frame.rawPairs[frame.idx];
3906
+ work.push({
3907
+ op: "mapEntryDone",
3908
+ rawPairs: frame.rawPairs,
3909
+ nextIdx: frame.idx + 1,
3910
+ nextDepth: frame.nextDepth,
3911
+ inKey: frame.inKey,
3912
+ owner1: frame.owner1,
3913
+ owner2: frame.owner2,
3914
+ entries: frame.entries,
3915
+ keyIndex: frame.keyIndex,
3916
+ });
3917
+ work.push({ op: "eval", raw: rawV, depth: frame.nextDepth, inKey: frame.inKey, isKeyRoot: false });
3918
+ work.push({ op: "eval", raw: rawK, depth: frame.nextDepth, inKey: true, isKeyRoot: true });
3919
+ }
3920
+ break;
3921
+ }
3922
+ case "mapEntryDone": {
3923
+ const vNode = results.pop();
3924
+ const kNode = results.pop();
3925
+ if (!frame.keyIndex.checkAndInsert(kNode)) {
3926
+ throw notSourceError("duplicate_key", {}, "duplicate mapping key");
3927
+ }
3928
+ frame.entries.push([kNode, vNode]);
3929
+ work.push({
3930
+ op: "mapIter",
3931
+ rawPairs: frame.rawPairs,
3932
+ idx: frame.nextIdx,
3933
+ nextDepth: frame.nextDepth,
3934
+ inKey: frame.inKey,
3935
+ owner1: frame.owner1,
3936
+ owner2: frame.owner2,
3937
+ entries: frame.entries,
3938
+ keyIndex: frame.keyIndex,
3939
+ });
3940
+ break;
3941
+ }
3942
+ case "eval": {
3943
+ const { raw, depth, inKey, isKeyRoot } = frame;
3944
+ state.nodesVisited += 1;
3945
+ if (state.nodesVisited > limits.maxNodes) {
3946
+ throw notSourceError("limit_exceeded", { limit: "max_nodes", configured: limits.maxNodes }, `node count exceeds max_nodes (${limits.maxNodes})`);
3947
+ }
3948
+ state.ownedBytes += NODE_OVERHEAD;
3949
+ if (isKeyRoot) {
3950
+ checkEmitKeyWeight(raw, limits);
3951
+ }
3952
+ if (isNodeObject(raw)) {
3953
+ if (active.has(raw)) {
3954
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `cyclic node graph exceeds max_depth (${limits.maxDepth})`);
3955
+ }
3956
+ switch (raw.kind) {
3957
+ case "null":
3958
+ results.push({ kind: "null", span: null, via: null, tagStart: null });
3959
+ break;
3960
+ case "bool":
3961
+ if (typeof raw.value !== "boolean") {
3962
+ throw notSourceError("type", { expected: "boolean", found: typeof raw.value }, "expected boolean");
3963
+ }
3964
+ results.push({ kind: "bool", value: raw.value, span: null, via: null, tagStart: null });
3965
+ break;
3966
+ case "int":
3967
+ if (typeof raw.value !== "bigint") {
3968
+ throw notSourceError("type", { expected: "bigint", found: typeof raw.value }, "expected bigint");
3969
+ }
3970
+ if (raw.value < I128_MIN || raw.value > U128_MAX) {
3971
+ throw notSourceError("integer_out_of_range", {}, "integer outside 128-bit range");
3972
+ }
3973
+ results.push({ kind: "int", value: raw.value, span: null, via: null, tagStart: null });
3974
+ break;
3975
+ case "float": {
3976
+ if (typeof raw.value !== "number") {
3977
+ throw notSourceError("type", { expected: "number", found: typeof raw.value }, "expected number");
3978
+ }
3979
+ const rawBits = raw.bits !== undefined ? raw.bits : floatToBits(raw.value);
3980
+ if (typeof rawBits !== "string" || !/^[0-9a-f]{16}$/.test(rawBits)) {
3981
+ throw notSourceError("internal", {}, "invalid float bits on Node");
3982
+ }
3983
+ const { value, canonicalBits } = bitsToFloat(rawBits);
3984
+ if (Number.isNaN(value) || Number.isNaN(raw.value)) {
3985
+ if (inKey) {
3986
+ throw notSourceError("invalid_key", {}, "NaN float is not valid inside a mapping key");
3987
+ }
3988
+ results.push({
3989
+ kind: "float",
3990
+ value: Number.NaN,
3991
+ bits: CANONICAL_NAN_BITS,
3992
+ span: null,
3993
+ via: null,
3994
+ tagStart: null,
3995
+ });
3996
+ }
3997
+ else {
3998
+ results.push({ kind: "float", value, bits: canonicalBits, span: null, via: null, tagStart: null });
3999
+ }
4000
+ break;
4001
+ }
4002
+ case "string": {
4003
+ const sBytes = validateUtf8Str(raw.value);
4004
+ if (sBytes.byteLength > limits.maxScalarBytes) {
4005
+ throw notSourceError("limit_exceeded", { limit: "max_scalar_bytes", configured: limits.maxScalarBytes }, `scalar byte length exceeds max_scalar_bytes (${limits.maxScalarBytes})`);
4006
+ }
4007
+ state.minOutputBytes += BigInt(sBytes.byteLength);
4008
+ state.ownedBytes += BigInt(sBytes.byteLength);
4009
+ results.push({ kind: "string", value: raw.value, span: null, via: null, tagStart: null });
4010
+ break;
4011
+ }
4012
+ case "tagged": {
4013
+ if (!raw.tag || typeof raw.tag !== "object") {
4014
+ throw invalidOptionsError("Tagged node must hold a Tag object");
4015
+ }
4016
+ const uriBytes = validateUtf8Str(raw.tag.uri);
4017
+ validateUtf8Str(raw.tag.handle ?? "");
4018
+ validateUtf8Str(raw.tag.suffix ?? raw.tag.uri);
4019
+ if (uriBytes.byteLength > limits.maxTagBytes || !isValidNonCoreTagUri(raw.tag.uri)) {
4020
+ throw invalidOptionsError("Tagged node contains invalid or oversized Tag.uri");
4021
+ }
4022
+ const innerRaw = raw.value;
4023
+ const innerKind = isNodeObject(innerRaw) ? innerRaw.kind : null;
4024
+ if (raw.tag.uri === "tag:yaml.org,2002:merge") {
4025
+ if (inKey || innerKind !== "string") {
4026
+ throw notSourceError("tag_kind_mismatch", {}, "tag:yaml.org,2002:merge may only wrap a non-key String node");
4027
+ }
4028
+ }
4029
+ else if (innerKind !== "string" && innerKind !== "sequence" && innerKind !== "mapping") {
4030
+ throw notSourceError("tag_kind_mismatch", {}, "Tagged node must wrap String, Sequence, or Mapping");
4031
+ }
4032
+ state.minOutputBytes += renderedTagMinBytes(uriBytes, raw.tag.uri);
4033
+ state.ownedBytes += 2n * BigInt(uriBytes.byteLength);
4034
+ active.add(raw);
4035
+ work.push({ op: "finishTagged", uri: raw.tag.uri, owner: raw });
4036
+ work.push({ op: "eval", raw: innerRaw, depth, inKey, isKeyRoot: false });
4037
+ break;
4038
+ }
4039
+ case "sequence": {
4040
+ const nextDepth = depth + 1;
4041
+ if (nextDepth > limits.maxDepth) {
4042
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `collection nesting exceeds max_depth (${limits.maxDepth})`);
4043
+ }
4044
+ if (active.has(raw.items)) {
4045
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `cyclic sequence exceeds max_depth (${limits.maxDepth})`);
4046
+ }
4047
+ active.add(raw);
4048
+ active.add(raw.items);
4049
+ work.push({
4050
+ op: "seqStep",
4051
+ rawItems: raw.items,
4052
+ idx: 0,
4053
+ nextDepth,
4054
+ inKey,
4055
+ checkHoles: false,
4056
+ owner1: raw,
4057
+ owner2: raw.items,
4058
+ items: [],
4059
+ });
4060
+ break;
4061
+ }
4062
+ case "mapping": {
4063
+ const nextDepth = depth + 1;
4064
+ if (nextDepth > limits.maxDepth) {
4065
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `collection nesting exceeds max_depth (${limits.maxDepth})`);
4066
+ }
4067
+ if (raw.entries.length > limits.maxMappingEntries) {
4068
+ throw notSourceError("limit_exceeded", { limit: "max_mapping_entries", configured: limits.maxMappingEntries }, `mapping entry count exceeds max_mapping_entries (${limits.maxMappingEntries})`);
4069
+ }
4070
+ if (active.has(raw.entries)) {
4071
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `cyclic mapping exceeds max_depth (${limits.maxDepth})`);
4072
+ }
4073
+ state.ownedBytes += BigInt(raw.entries.length) * ENTRY_OVERHEAD;
4074
+ active.add(raw);
4075
+ active.add(raw.entries);
4076
+ work.push({
4077
+ op: "mapIter",
4078
+ rawPairs: raw.entries,
4079
+ idx: 0,
4080
+ nextDepth,
4081
+ inKey,
4082
+ owner1: raw,
4083
+ owner2: raw.entries,
4084
+ entries: [],
4085
+ keyIndex: new KeyIndex(),
4086
+ });
4087
+ break;
4088
+ }
4089
+ }
4090
+ break;
4091
+ }
4092
+ if (raw === null) {
4093
+ results.push({ kind: "null", span: null, via: null, tagStart: null });
4094
+ break;
4095
+ }
4096
+ if (typeof raw === "boolean") {
4097
+ results.push({ kind: "bool", value: raw, span: null, via: null, tagStart: null });
4098
+ break;
4099
+ }
4100
+ if (typeof raw === "bigint") {
4101
+ if (raw < I128_MIN || raw > U128_MAX) {
4102
+ throw notSourceError("integer_out_of_range", {}, "bigint outside 128-bit range");
4103
+ }
4104
+ results.push({ kind: "int", value: raw, span: null, via: null, tagStart: null });
4105
+ break;
4106
+ }
4107
+ if (typeof raw === "number") {
4108
+ if (Number.isSafeInteger(raw) && !Object.is(raw, -0)) {
4109
+ results.push({ kind: "int", value: BigInt(raw), span: null, via: null, tagStart: null });
4110
+ }
4111
+ else if (Number.isNaN(raw)) {
4112
+ if (inKey) {
4113
+ throw notSourceError("invalid_key", {}, "NaN float is not valid inside a mapping key");
4114
+ }
4115
+ results.push({
4116
+ kind: "float",
4117
+ value: Number.NaN,
4118
+ bits: CANONICAL_NAN_BITS,
4119
+ span: null,
4120
+ via: null,
4121
+ tagStart: null,
4122
+ });
4123
+ }
4124
+ else {
4125
+ results.push({ kind: "float", value: raw, bits: floatToBits(raw), span: null, via: null, tagStart: null });
4126
+ }
4127
+ break;
4128
+ }
4129
+ if (typeof raw === "string") {
4130
+ const sBytes = validateUtf8Str(raw);
4131
+ if (sBytes.byteLength > limits.maxScalarBytes) {
4132
+ throw notSourceError("limit_exceeded", { limit: "max_scalar_bytes", configured: limits.maxScalarBytes }, `scalar byte length exceeds max_scalar_bytes (${limits.maxScalarBytes})`);
4133
+ }
4134
+ state.minOutputBytes += BigInt(sBytes.byteLength);
4135
+ state.ownedBytes += BigInt(sBytes.byteLength);
4136
+ results.push({ kind: "string", value: raw, span: null, via: null, tagStart: null });
4137
+ break;
4138
+ }
4139
+ if (Array.isArray(raw)) {
4140
+ const nextDepth = depth + 1;
4141
+ if (nextDepth > limits.maxDepth) {
4142
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `collection nesting exceeds max_depth (${limits.maxDepth})`);
4143
+ }
4144
+ if (active.has(raw)) {
4145
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `cyclic sequence exceeds max_depth (${limits.maxDepth})`);
4146
+ }
4147
+ active.add(raw);
4148
+ work.push({
4149
+ op: "seqStep",
4150
+ rawItems: raw,
4151
+ idx: 0,
4152
+ nextDepth,
4153
+ inKey,
4154
+ checkHoles: true,
4155
+ owner1: null,
4156
+ owner2: raw,
4157
+ items: [],
4158
+ });
4159
+ break;
4160
+ }
4161
+ if (raw instanceof Mapping || raw instanceof Map || isPlainObject(raw)) {
4162
+ const nextDepth = depth + 1;
4163
+ if (nextDepth > limits.maxDepth) {
4164
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `collection nesting exceeds max_depth (${limits.maxDepth})`);
4165
+ }
4166
+ if (active.has(raw)) {
4167
+ throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, `cyclic mapping exceeds max_depth (${limits.maxDepth})`);
4168
+ }
4169
+ let rawPairs;
4170
+ if (raw instanceof Mapping) {
4171
+ if (raw.entries.length > limits.maxMappingEntries) {
4172
+ throw notSourceError("limit_exceeded", { limit: "max_mapping_entries", configured: limits.maxMappingEntries }, `mapping entry count exceeds max_mapping_entries (${limits.maxMappingEntries})`);
4173
+ }
4174
+ rawPairs = raw.entries;
4175
+ }
4176
+ else if (raw instanceof Map) {
4177
+ if (raw.size > limits.maxMappingEntries) {
4178
+ throw notSourceError("limit_exceeded", { limit: "max_mapping_entries", configured: limits.maxMappingEntries }, `mapping entry count exceeds max_mapping_entries (${limits.maxMappingEntries})`);
4179
+ }
4180
+ rawPairs = Array.from(raw.entries());
4181
+ }
4182
+ else {
4183
+ const keys = Object.keys(raw);
4184
+ if (keys.length > limits.maxMappingEntries) {
4185
+ throw notSourceError("limit_exceeded", { limit: "max_mapping_entries", configured: limits.maxMappingEntries }, `mapping entry count exceeds max_mapping_entries (${limits.maxMappingEntries})`);
4186
+ }
4187
+ rawPairs = keys.map((k) => [k, curVal(raw, k)]);
4188
+ }
4189
+ state.ownedBytes += BigInt(rawPairs.length) * ENTRY_OVERHEAD;
4190
+ active.add(raw);
4191
+ work.push({
4192
+ op: "mapIter",
4193
+ rawPairs,
4194
+ idx: 0,
4195
+ nextDepth,
4196
+ inKey,
4197
+ owner1: null,
4198
+ owner2: raw,
4199
+ entries: [],
4200
+ keyIndex: new KeyIndex(),
4201
+ });
4202
+ break;
4203
+ }
4204
+ throw notSourceError("type", {
4205
+ expected: "YAML-serializable value",
4206
+ found: raw === undefined
4207
+ ? "undefined"
4208
+ : typeof raw === "object"
4209
+ ? (raw.constructor?.name ?? "object")
4210
+ : typeof raw,
4211
+ }, `unsupported type for YAML emission: ${raw === undefined ? "undefined" : typeof raw}`);
4212
+ }
4213
+ }
4214
+ }
4215
+ return results.pop();
4216
+ }
4217
+ function curVal(obj, k) {
4218
+ return obj[k];
4219
+ }
4220
+ export function fromPlain(value, options) {
4221
+ const opts = validateEmitOptions(options);
4222
+ const state = {
4223
+ opts,
4224
+ nodesVisited: 0,
4225
+ minOutputBytes: 0n,
4226
+ ownedBytes: 0n,
4227
+ };
4228
+ return convertAndPreflightNode(value, opts, state);
4229
+ }
4230
+ function isDocumentObject(val) {
4231
+ if (!val || typeof val !== "object" || Array.isArray(val) || val instanceof Mapping || val instanceof Map) {
4232
+ return false;
4233
+ }
4234
+ const obj = val;
4235
+ const keys = Object.keys(obj);
4236
+ if (keys.length !== 3)
4237
+ return false;
4238
+ for (const k of keys) {
4239
+ if (k !== "root" && k !== "explicitStart" && k !== "yamlVersion") {
4240
+ return false;
4241
+ }
4242
+ }
4243
+ return (hasOwn(obj, "root") &&
4244
+ hasOwn(obj, "explicitStart") &&
4245
+ hasOwn(obj, "yamlVersion") &&
4246
+ isNodeObject(obj.root));
4247
+ }
4248
+ export function dumpAll(documents, options) {
4249
+ const opts = validateEmitOptions(options);
4250
+ if (!Array.isArray(documents)) {
4251
+ throw notSourceError("type", { expected: "array of documents", found: typeof documents }, "dumpAll expects an array of documents");
4252
+ }
4253
+ if (documents.length > opts.limits.maxDocuments) {
4254
+ throw notSourceError("limit_exceeded", { limit: "max_documents", configured: opts.limits.maxDocuments }, `document count exceeds max_documents (${opts.limits.maxDocuments})`);
4255
+ }
4256
+ if (documents.length === 0) {
4257
+ return "";
4258
+ }
4259
+ const state = {
4260
+ opts,
4261
+ nodesVisited: 0,
4262
+ minOutputBytes: 0n,
4263
+ ownedBytes: 0n,
4264
+ };
4265
+ const cleanDocs = [];
4266
+ for (const item of documents) {
4267
+ if (isDocumentObject(item)) {
4268
+ const checkedDoc = createDocument({ kind: "null", span: null, via: null, tagStart: null }, item.yamlVersion, item.explicitStart);
4269
+ const root = convertAndPreflightNode(item.root, opts, state);
4270
+ cleanDocs.push({
4271
+ yamlVersion: checkedDoc.yamlVersion,
4272
+ explicitStart: checkedDoc.explicitStart,
4273
+ root,
4274
+ });
4275
+ }
4276
+ else {
4277
+ const root = convertAndPreflightNode(item, opts, state);
4278
+ cleanDocs.push({ yamlVersion: null, explicitStart: false, root });
4279
+ }
4280
+ }
4281
+ if (state.minOutputBytes > BigInt(opts.limits.maxOutputBytes)) {
4282
+ throw notSourceError("output_limit_exceeded", { configured: opts.limits.maxOutputBytes }, `encoded output exceeds max_output_bytes (${opts.limits.maxOutputBytes})`);
4283
+ }
4284
+ if (state.ownedBytes > BigInt(MAX_WASM_INPUT_CEILING)) {
4285
+ throw notSourceError("limit_exceeded", { limit: "max_owned_bytes", configured: MAX_WASM_INPUT_CEILING }, `WASM emission logical owned weight exceeds ${MAX_WASM_INPUT_CEILING} bytes`);
4286
+ }
4287
+ const w = new BoundedWriter(MAX_WASM_INPUT_CEILING);
4288
+ const encSt = {
4289
+ opts: {
4290
+ mergeKeys: "reject",
4291
+ unknownTags: "preserve",
4292
+ limits: {
4293
+ ...defaultLimits(),
4294
+ maxDepth: opts.limits.maxDepth,
4295
+ maxNodes: opts.limits.maxNodes,
4296
+ maxMappingEntries: opts.limits.maxMappingEntries,
4297
+ maxDocuments: opts.limits.maxDocuments,
4298
+ maxOutputBytes: MAX_WASM_INPUT_CEILING,
4299
+ },
4300
+ },
4301
+ nodesRemaining: opts.limits.maxNodes,
4302
+ activeAncestors: new Set(),
4303
+ };
4304
+ let wireJson;
4305
+ try {
4306
+ w.pushRaw('{"format":"yamlprims-value","version":1,"documents":[');
4307
+ for (let i = 0; i < cleanDocs.length; i++) {
4308
+ if (i > 0)
4309
+ w.pushRaw(",");
4310
+ const d = cleanDocs[i];
4311
+ w.pushRaw('{"yaml_version":');
4312
+ if (d.yamlVersion !== null) {
4313
+ w.pushRaw(`[${d.yamlVersion[0]},${d.yamlVersion[1]}]`);
4314
+ }
4315
+ else {
4316
+ w.pushRaw("null");
4317
+ }
4318
+ w.pushRaw(d.explicitStart ? ',"explicit_start":true,"root":' : ',"explicit_start":false,"root":');
4319
+ writeNode(w, d.root, false, encSt, 0);
4320
+ w.pushRaw("}");
4321
+ }
4322
+ w.pushRaw("]}");
4323
+ wireJson = w.finish();
4324
+ }
4325
+ catch (err) {
4326
+ if (err instanceof YamlprimsError && err.kind === "output_limit_exceeded") {
4327
+ throw notSourceError("limit_exceeded", { limit: "max_input_bytes", configured: MAX_WASM_INPUT_CEILING }, `WASM emission wire envelope exceeds ${MAX_WASM_INPUT_CEILING} bytes`);
4328
+ }
4329
+ throw err;
4330
+ }
4331
+ const wireBytes = encoder.encode(wireJson);
4332
+ if (wireBytes.byteLength > MAX_WASM_INPUT_CEILING) {
4333
+ throw notSourceError("limit_exceeded", { limit: "max_input_bytes", configured: MAX_WASM_INPUT_CEILING }, `WASM emission wire envelope exceeds ${MAX_WASM_INPUT_CEILING} bytes`);
4334
+ }
4335
+ const { status, output } = runWasmEmit(wireBytes, opts);
4336
+ if (status === 2) {
4337
+ throw decodeFallbackStatus2(output, opts.limits.maxOutputBytes);
4338
+ }
4339
+ const text = decoder.decode(output);
4340
+ if (status === 1) {
4341
+ const errOpts = defaultOptions();
4342
+ const decoded = decodeWire(text, widenBridgeOptions(errOpts, output.byteLength));
4343
+ if (decoded.kind === "error") {
4344
+ throw decoded.error;
4345
+ }
4346
+ throw notSourceError("internal", {}, "expected error envelope from emit_wire status 1");
4347
+ }
4348
+ return text;
4349
+ }
4350
+ export function dump(value, options) {
4351
+ return dumpAll([value], options);
4352
+ }
2268
4353
  // Internal-only hook for in-repo linear-memory and trap tests (not part of the
2269
4354
  // public TypeScript declarations or supported package surface).
2270
4355
  Object.defineProperty(load, Symbol.for("yamlprims.internal.wasmTestHarness"), {