libyay 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +190 -13
  2. package/package.json +6 -3
  3. package/yay.js +3110 -1398
package/yay.js CHANGED
@@ -1,18 +1,101 @@
1
1
  "use strict";
2
2
 
3
+ const KEY_CHARACTER = /^[A-Za-z0-9_-]$/;
4
+ const LOWER_HEX = /^[0-9a-f]*$/;
5
+ const UNICODE_ESCAPE = /^[0-9A-Fa-f]{1,6}$/;
6
+ const HEX_PAIR = /^[0-9A-Fa-f]{2}/;
7
+ const UPPERCASE = /[A-Z]/;
8
+ const UNICODE_SPACE =
9
+ /[\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/;
10
+
11
+ // The old inline reader scans its whole remaining text at every level. Keep
12
+ // the one-pass depth error for a pathological malformed flood too large for
13
+ // that scan, rather than turn the fallback into a quadratic denial of service.
14
+ const MAX_DEPTH_FALLBACK_LENGTH = 4096;
15
+
16
+ // The ASCII characters a reference's text may hold, "%" aside, which must
17
+ // begin a percent-encoding.
18
+ const URI_ASCII = new Uint8Array(128);
19
+ for (const ch of "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=") {
20
+ URI_ASCII[ch.charCodeAt(0)] = 1;
21
+ }
22
+
23
+ const SIMPLE_ESCAPES = Object.freeze({
24
+ "\\": "\\",
25
+ "/": "/",
26
+ b: "\b",
27
+ f: "\f",
28
+ n: "\n",
29
+ r: "\r",
30
+ t: "\t",
31
+ });
32
+
3
33
  /**
4
34
  * Parses a YAY document string and returns the corresponding JavaScript value.
5
35
  * @param {string} source - UTF-8 YAY document
6
- * @param {string} [filename] - Optional filename for error messages
7
- * @returns {unknown} - Parsed value (null, bigint, number, boolean, string, Array, object, Uint8Array)
36
+ * @param {ParseOptions} [options] - Decoding hooks and error-message options
37
+ * @returns {unknown} - Parsed YAY value, including symbol and tagged records
8
38
  */
9
- function parseYay(source, filename) {
10
- const ctx = { filename: filename || undefined };
39
+ function parseYay(source, options = {}) {
40
+ if (typeof options === "string") {
41
+ throw new TypeError(
42
+ "parseYay options must be an object; pass a filename as { filename }",
43
+ );
44
+ }
45
+ if (
46
+ options.decodeReference !== undefined &&
47
+ typeof options.decodeReference !== "function"
48
+ ) {
49
+ throw new TypeError("decodeReference must be a function");
50
+ }
51
+ if (
52
+ options.decodeSymbol !== undefined &&
53
+ typeof options.decodeSymbol !== "function"
54
+ ) {
55
+ throw new TypeError("decodeSymbol must be a function");
56
+ }
57
+ if (
58
+ options.bytes !== undefined &&
59
+ options.bytes !== "plain" &&
60
+ options.bytes !== "immutable" &&
61
+ typeof options.bytes !== "function"
62
+ ) {
63
+ throw new TypeError('bytes must be "plain", "immutable", or a function');
64
+ }
65
+ const ctx = {
66
+ filename: options.filename || undefined,
67
+ decodeReference: options.decodeReference,
68
+ decodeSymbol: options.decodeSymbol || symbol,
69
+ bytes: options.bytes,
70
+ };
11
71
  const lines = scan(source, ctx);
12
72
  const tokens = outlineLex(lines);
13
73
  return parseRoot(tokens, ctx);
14
74
  }
15
75
 
76
+ const TEXT_ENCODER =
77
+ typeof TextEncoder !== "undefined" ? new TextEncoder() : undefined;
78
+ const TEXT_DECODER =
79
+ typeof TextDecoder !== "undefined" ? new TextDecoder() : undefined;
80
+
81
+ /**
82
+ * Give a parsed string its own storage. A slice of a line, which is itself a
83
+ * slice of the source, keeps the whole source alive for as long as the value
84
+ * survives. V8 already copies very short slices; the rest are copied once.
85
+ * @param {string} s
86
+ * @returns {string}
87
+ */
88
+ function detachString(s) {
89
+ if (s.length <= 13) return s;
90
+ if (typeof Buffer !== "undefined") {
91
+ return Buffer.from(s, "utf8").toString("utf8");
92
+ }
93
+ if (TEXT_ENCODER !== undefined && TEXT_DECODER !== undefined) {
94
+ return TEXT_DECODER.decode(TEXT_ENCODER.encode(s));
95
+ }
96
+ return s.split("").join("");
97
+ }
98
+
16
99
  function locSuffix(ctx, line, col) {
17
100
  if (!ctx.filename) return "";
18
101
  const oneBasedLine = line + 1;
@@ -22,6 +105,45 @@ function locSuffix(ctx, line, col) {
22
105
  );
23
106
  }
24
107
 
108
+ /**
109
+ * A location for an error that must name one even without a filename.
110
+ * @param {ParseContext} ctx
111
+ * @param {number} line
112
+ * @param {number} col
113
+ */
114
+ function requiredLocSuffix(ctx, line, col) {
115
+ const oneBasedLine = line + 1;
116
+ const oneBasedCol = col + 1;
117
+ return (
118
+ " at " +
119
+ oneBasedLine +
120
+ ":" +
121
+ oneBasedCol +
122
+ (ctx.filename ? " of <" + ctx.filename + ">" : "")
123
+ );
124
+ }
125
+
126
+ /**
127
+ * Throw a parser error at a source location.
128
+ * @param {ParseContext} ctx
129
+ * @param {string} message
130
+ * @param {number} line
131
+ * @param {number} col
132
+ * @param {boolean=} appendLocation
133
+ * @returns {never}
134
+ */
135
+ function fail(ctx, message, line, col, appendLocation = true) {
136
+ const error = new Error(
137
+ message + (appendLocation ? locSuffix(ctx, line, col) : ""),
138
+ );
139
+ Object.defineProperties(error, {
140
+ line: { value: line + 1 },
141
+ column: { value: col + 1 },
142
+ filename: { value: ctx.filename },
143
+ });
144
+ throw error;
145
+ }
146
+
25
147
  /**
26
148
  * Check whether a code point is allowed in a YAY document.
27
149
  * @param {number} cp
@@ -38,40 +160,63 @@ function isAllowedCodePoint(cp) {
38
160
  }
39
161
 
40
162
  /**
41
- * Strip inline comments from a string.
42
- * Returns the value part (trimmed) without the comment.
163
+ * Strip an inline comment from a value. A comment after a value takes two
164
+ * spaces before its "#"; one space is refused.
43
165
  * @param {string} s
166
+ * @param {ParseContext} ctx
167
+ * @param {number} lineNum
168
+ * @param {number} col
169
+ * @param {ReturnType<typeof scanTopLevel>=} syntax
44
170
  * @returns {string}
45
171
  */
46
- function stripInlineComment(s) {
47
- let inDouble = false;
48
- let inSingle = false;
49
- let escape = false;
172
+ function stripInlineComment(
173
+ s,
174
+ ctx = {},
175
+ lineNum = 0,
176
+ col = 0,
177
+ syntax = scanTopLevel(s),
178
+ ) {
179
+ if (syntax.comment === undefined) return s;
180
+ checkCommentSpacing(s, syntax.comment, ctx, lineNum, col);
181
+ return s.slice(0, syntax.comment).trimEnd();
182
+ }
50
183
 
51
- for (let i = 0; i < s.length; i++) {
52
- const c = s[i];
53
- if (escape) {
54
- escape = false;
55
- continue;
56
- }
57
- if (c === "\\") {
58
- escape = true;
59
- continue;
60
- }
61
- if (c === '"' && !inSingle) {
62
- inDouble = !inDouble;
63
- } else if (c === "'" && !inDouble) {
64
- inSingle = !inSingle;
65
- } else if (c === "#" && !inDouble && !inSingle) {
66
- return s.slice(0, i).trimEnd();
67
- }
184
+ /**
185
+ * Refuse a comment, at s[hash], that has one space before it rather than
186
+ * two.
187
+ * @param {string} s
188
+ * @param {number} hash
189
+ * @param {ParseContext} ctx
190
+ * @param {number} lineNum
191
+ * @param {number} col
192
+ */
193
+ function checkCommentSpacing(s, hash, ctx, lineNum, col) {
194
+ if (hash >= 1 && s[hash - 1] === " " && (hash < 2 || s[hash - 2] !== " ")) {
195
+ throw new Error(
196
+ "Expected two spaces before a comment" +
197
+ locSuffix(ctx, lineNum, col + hash),
198
+ );
68
199
  }
69
- return s;
70
200
  }
71
201
 
202
+ /**
203
+ * @typedef {Object} ParseOptions
204
+ * @property {string=} filename - Optional filename for error messages
205
+ * @property {(uri: string) => unknown=} decodeReference - Turn a
206
+ * reference's URI text into the caller's value
207
+ * @property {(name: string) => unknown=} decodeSymbol - Turn a symbol's name
208
+ * into the caller's value; defaults to `symbol`
209
+ * @property {'plain'|'immutable'|((bytes: Uint8Array) => unknown)=} bytes -
210
+ * How to make a byte value: a plain Uint8Array by default, an immutable
211
+ * byteArray when asked, or a caller's hook
212
+ */
213
+
72
214
  /**
73
215
  * @typedef {Object} ParseContext
74
216
  * @property {string=} filename
217
+ * @property {(uri: string) => unknown=} decodeReference
218
+ * @property {(name: string) => unknown} decodeSymbol
219
+ * @property {'plain'|'immutable'|((bytes: Uint8Array) => unknown)=} bytes
75
220
  */
76
221
 
77
222
  /**
@@ -90,6 +235,23 @@ function stripInlineComment(s) {
90
235
  * @property {number=} col
91
236
  */
92
237
 
238
+ /**
239
+ * Skip blank-line tokens and, where a caller is between blocks, stop tokens.
240
+ * @param {Token[]} tokens
241
+ * @param {number} i
242
+ * @param {boolean=} includeStops
243
+ * @returns {number}
244
+ */
245
+ function skipBlank(tokens, i, includeStops = false) {
246
+ while (
247
+ i < tokens.length &&
248
+ (tokens[i].type === "break" || (includeStops && tokens[i].type === "stop"))
249
+ ) {
250
+ i++;
251
+ }
252
+ return i;
253
+ }
254
+
93
255
  // --- Scanner: source -> lines with { line, indent, leader, lineNum } ---
94
256
 
95
257
  /**
@@ -154,7 +316,11 @@ function scan(source, ctx = {}) {
154
316
  }
155
317
  }
156
318
  const lines = [];
157
- const lineStrings = source.split(/\n/);
319
+ const lineStrings = source.split("\n");
320
+ // While inside a block string, the column that ends it: the indent of a
321
+ // bare opener, or the key's column for a property opener. Its content
322
+ // lines are literal: no list leaders, no "-" or "*" checks, no comments.
323
+ let blockOpener = -1;
158
324
  for (let i = 0; i < lineStrings.length; i++) {
159
325
  const lineStr = lineStrings[i];
160
326
  if (lineStr.length > 0 && lineStr.charCodeAt(lineStr.length - 1) === 0x20) {
@@ -167,6 +333,13 @@ function scan(source, ctx = {}) {
167
333
  indent++;
168
334
  }
169
335
  const rest = lineStr.slice(indent);
336
+ if (blockOpener >= 0) {
337
+ if (lineStr.length === 0 || indent > blockOpener) {
338
+ lines.push({ line: rest, indent, leader: "", lineNum: i });
339
+ continue;
340
+ }
341
+ blockOpener = -1;
342
+ }
170
343
  if (rest.startsWith("#") && indent === 0) {
171
344
  continue; // comment only at column 0
172
345
  }
@@ -204,11 +377,25 @@ function scan(source, ctx = {}) {
204
377
  ) {
205
378
  throw new Error('Unexpected character "*"' + locSuffix(ctx, i, indent));
206
379
  }
380
+ if (isBareBlockOpener(line) || isBareBlockOpener(afterPrefix(line) ?? "")) {
381
+ blockOpener = indent;
382
+ } else if (line.endsWith(": `") || isTaggedPropertyOpener(line)) {
383
+ blockOpener = indent + (rest.length - line.length);
384
+ }
207
385
  lines.push({ line, indent, leader, lineNum: i });
208
386
  }
209
387
  return lines;
210
388
  }
211
389
 
390
+ /**
391
+ * Whether a line's content (after any list leader) is a bare "`" or
392
+ * "` text" block string opener.
393
+ * @param {string} line
394
+ */
395
+ function isBareBlockOpener(line) {
396
+ return line === "`" || line.startsWith("` ");
397
+ }
398
+
212
399
  // --- Outline Lexer: lines -> tokens { type, text, indent?, lineNum?, col? } ---
213
400
 
214
401
  /**
@@ -219,10 +406,10 @@ function outlineLex(lines) {
219
406
  const tokens = [];
220
407
  let stack = [0];
221
408
  let top = 0;
222
- let broken = false;
223
409
  for (const { line, indent, leader, lineNum } of lines) {
224
- // Close blocks on dedent.
225
- while (indent < top) {
410
+ // Close blocks on dedent. A blank line has no indent of its own, so it
411
+ // closes nothing.
412
+ while (line.length > 0 && indent < top) {
226
413
  tokens.push({ type: "stop", text: "" });
227
414
  stack.pop();
228
415
  top = stack[stack.length - 1];
@@ -237,7 +424,6 @@ function outlineLex(lines) {
237
424
  });
238
425
  stack.push(indent);
239
426
  top = indent;
240
- broken = false;
241
427
  } else if (leader.length > 0 && indent === top) {
242
428
  tokens.push({ type: "stop", text: "" });
243
429
  tokens.push({
@@ -247,14 +433,20 @@ function outlineLex(lines) {
247
433
  lineNum,
248
434
  col: indent,
249
435
  });
250
- broken = false;
251
436
  }
437
+ // Every blank line is a break, so that a block string keeps a run of
438
+ // blank lines.
252
439
  if (line.length > 0) {
253
- tokens.push({ type: "text", text: line, indent, lineNum, col: indent });
254
- broken = false;
255
- } else if (!broken) {
440
+ // The text's column follows the list leader, "- ", if any.
441
+ tokens.push({
442
+ type: "text",
443
+ text: line,
444
+ indent,
445
+ lineNum,
446
+ col: leader ? indent + 2 : indent,
447
+ });
448
+ } else {
256
449
  tokens.push({ type: "break", text: "", lineNum, col: indent });
257
- broken = true;
258
450
  }
259
451
  }
260
452
  while (stack.length > 1) {
@@ -266,18 +458,50 @@ function outlineLex(lines) {
266
458
 
267
459
  // --- Value parser: tokens -> value ---
268
460
 
461
+ /**
462
+ * Give an object a property of its own. Assignment would take a
463
+ * "__proto__" key for the prototype; YAY has no such key.
464
+ * @param {Record<string, unknown>} obj
465
+ * @param {string} key
466
+ * @param {unknown} value
467
+ */
468
+ function setOwn(obj, key, value) {
469
+ Object.defineProperty(obj, key, {
470
+ value,
471
+ writable: true,
472
+ enumerable: true,
473
+ configurable: true,
474
+ });
475
+ }
476
+
477
+ /**
478
+ * Record where a key first appears in an object, and refuse it the second
479
+ * time. Each key keeps its first position, not only its name, so that the
480
+ * error can say where the first one is.
481
+ * @param {Map<string, [number, number]>} seen
482
+ * @param {string} key
483
+ * @param {ParseContext} ctx
484
+ * @param {number} lineNum
485
+ * @param {number} col
486
+ */
487
+ function claimKey(seen, key, ctx, lineNum, col) {
488
+ const first = seen.get(key);
489
+ if (first !== undefined) {
490
+ throw new Error(
491
+ `Duplicate key "${key}" (first at ${first[0] + 1}:${first[1] + 1})` +
492
+ locSuffix(ctx, lineNum, col),
493
+ );
494
+ }
495
+ seen.set(key, [lineNum, col]);
496
+ }
497
+
269
498
  /**
270
499
  * @param {Token[]} tokens
271
500
  * @param {ParseContext} ctx
272
501
  * @returns {unknown}
273
502
  */
274
503
  function parseRoot(tokens, ctx = {}) {
275
- let i = 0;
276
- while (
277
- i < tokens.length &&
278
- (tokens[i].type === "stop" || tokens[i].type === "break")
279
- )
280
- i++;
504
+ let i = skipBlank(tokens, 0, true);
281
505
  if (i >= tokens.length) {
282
506
  throw new Error(
283
507
  "No value found in document" +
@@ -292,11 +516,38 @@ function parseRoot(tokens, ctx = {}) {
292
516
  (ctx.filename ? " at " + line + ":1 of <" + ctx.filename + ">" : ""),
293
517
  );
294
518
  }
519
+ // A tagged root block: the tags alone on the first line, the block below
520
+ // at column 0
521
+ if (t.type === "text" && t.text.startsWith("(")) {
522
+ const lineNum = t.lineNum ?? 0;
523
+ const col = t.col ?? 0;
524
+ const [, firstEnd] = parseTag(t.text, ctx, lineNum, col);
525
+ if (t.text[firstEnd] === ":") {
526
+ throw new Error("A key is a string" + locSuffix(ctx, lineNum, col));
527
+ }
528
+ let tags, rest;
529
+ try {
530
+ [tags, rest] = parsePrefix(t.text, ctx, lineNum, col);
531
+ } catch (error) {
532
+ if (skipBlank(tokens, i + 1, true) < tokens.length) throw error;
533
+ return parseScalar(t.text, ctx, lineNum, col);
534
+ }
535
+ if (rest !== "") throw prefixWithoutBlock(ctx, t.lineNum ?? 0, t.col ?? 0);
536
+ const j = skipBlank(tokens, i + 1, true);
537
+ if (j >= tokens.length) {
538
+ return parseScalar(t.text, ctx, t.lineNum ?? 0, t.col ?? 0);
539
+ }
540
+ if (!rootBlockFollows(tokens, j)) {
541
+ throw prefixOverInlineValue(ctx, t.lineNum ?? 0, t.col ?? 0);
542
+ }
543
+ return wrapPrefix(parseRoot(tokens.slice(j), ctx), tags);
544
+ }
295
545
  if (
296
546
  t.type === "text" &&
297
547
  findKeyColonOutsideQuotes(t.text) >= 0 &&
298
548
  (t.indent ?? 0) === 0 &&
299
- !t.text.startsWith("{")
549
+ !t.text.startsWith("{") &&
550
+ !t.text.startsWith("[")
300
551
  ) {
301
552
  const [value, next] = parseRootObject(tokens, i, ctx);
302
553
  return ensureAtEnd(value, tokens, next, ctx);
@@ -306,12 +557,7 @@ function parseRoot(tokens, ctx = {}) {
306
557
  }
307
558
 
308
559
  function ensureAtEnd(value, tokens, i, ctx = {}) {
309
- let j = i;
310
- while (
311
- j < tokens.length &&
312
- (tokens[j].type === "stop" || tokens[j].type === "break")
313
- )
314
- j++;
560
+ const j = skipBlank(tokens, i, true);
315
561
  if (j < tokens.length) {
316
562
  const t = tokens[j];
317
563
  const line = (t.lineNum ?? 0) + 1;
@@ -362,87 +608,89 @@ function parseValue(tokens, i, ctx = {}) {
362
608
  }
363
609
  }
364
610
  if (t.type === "text") {
365
- const raw = t.text;
366
- const s = raw;
611
+ const s = t.text;
612
+ const lineNum = t.lineNum ?? 0;
367
613
  const sCol = t.col ?? 0;
368
- if (s === "null") return [null, i + 1];
369
- if (s === "true") return [true, i + 1];
370
- if (s === "false") return [false, i + 1];
371
- if (s === "nan") return [NaN, i + 1];
372
- if (s === "infinity") return [Infinity, i + 1];
373
- if (s === "-infinity") return [-Infinity, i + 1];
374
- const num = parseNumber(s, ctx, t.lineNum ?? 0, sCol);
375
- if (num !== undefined) return [num, i + 1];
376
- if (s === "`" || (s.startsWith("`") && s.length >= 2 && s[1] === " ")) {
614
+ const syntax = scanTopLevel(s);
615
+ // The block forms, which read the lines below
616
+ if (s === "`" || s.startsWith("` ")) {
377
617
  const firstLine = s.length > 2 ? s.slice(2) : "";
378
618
  // Use token's indent as base - block string content must be indented more
379
- return parseBlockStringWithIndent(
619
+ return collectBlockString(
380
620
  tokens,
381
621
  i,
382
622
  firstLine,
383
623
  false,
384
624
  t.indent ?? 0,
625
+ ctx,
385
626
  );
386
627
  }
387
- if (
388
- (s.startsWith('"') && s.length > 1) ||
389
- (s.startsWith("'") && s.length > 1)
390
- ) {
391
- return [parseQuotedString(s, ctx, t.lineNum ?? 0, sCol), i + 1];
392
- }
393
- if (s.startsWith("[")) {
394
- // Inline arrays must close on the same line.
395
- if (!s.endsWith("]")) {
396
- throw new Error(
397
- "Unexpected newline in inline array" +
398
- locSuffix(ctx, t.lineNum ?? 0, sCol),
399
- );
400
- }
401
- validateInlineArrayWhitespace(s, ctx, t.lineNum ?? 0, sCol);
402
- return [parseInlineArray(s, ctx, t.lineNum ?? 0, sCol), i + 1];
403
- }
404
628
  if (s.startsWith(">")) {
405
- let firstLine = s.slice(1);
406
- if (firstLine.startsWith(" ")) firstLine = firstLine.slice(1);
629
+ const firstCol = s.startsWith("> ") ? sCol + 2 : sCol + 1;
630
+ const firstLine = s.slice(firstCol - sCol);
407
631
  if (firstLine.length === 0) {
408
- throw new Error("Expected hex or comment in hex block");
632
+ fail(
633
+ ctx,
634
+ "Expected hex or comment in hex block",
635
+ lineNum,
636
+ firstCol,
637
+ false,
638
+ );
409
639
  }
410
- return parseBlockBytes(tokens, i, ctx, firstLine, t.indent ?? 0);
640
+ return parseBlockBytes(
641
+ tokens,
642
+ i,
643
+ ctx,
644
+ firstLine,
645
+ t.indent ?? 0,
646
+ firstCol,
647
+ );
411
648
  }
412
- if (s.startsWith("{")) {
413
- // Inline objects must close on the same line.
414
- if (!s.includes("}")) {
649
+ if (s.startsWith("[")) {
650
+ const close = syntax.closeBracket;
651
+ if (close >= 0 && s[close + 1] === ":") {
415
652
  throw new Error(
416
- "Unexpected newline in inline object" +
417
- locSuffix(ctx, t.lineNum ?? 0, sCol),
653
+ 'Unexpected character ":"' +
654
+ locSuffix(ctx, lineNum, sCol + close + 1),
418
655
  );
419
656
  }
420
- const inlineObj = parseInlineObject(s, ctx, t.lineNum ?? 0, sCol);
421
- if (inlineObj !== null) return [inlineObj, i + 1];
422
657
  }
423
- if (s.startsWith("<") && s.includes(">"))
424
- return [parseAngleBytes(s, ctx, t.lineNum, t.col), i + 1];
425
- if (s.startsWith("<")) {
426
- throw new Error(
427
- "Unmatched angle bracket" + locSuffix(ctx, t.lineNum ?? 0, sCol),
658
+ // A property on this line: "key: value" or "key:" over a block. An
659
+ // inline value with tags after it, an inline container, a quoted string
660
+ // and a reference or bytes never take a key here.
661
+ const bare = stripInlineComment(s, ctx, lineNum, sCol, syntax);
662
+ const first =
663
+ syntax.firstTag !== undefined && syntax.firstTag < bare.length
664
+ ? syntax.firstTag
665
+ : undefined;
666
+ const tagged =
667
+ first !== undefined &&
668
+ first > 0 &&
669
+ findKeyColonOutsideQuotes(bare, syntax, first) < 0;
670
+ if (
671
+ !tagged &&
672
+ !/^["'[{<]/.test(bare) &&
673
+ findKeyColonOutsideQuotes(bare, syntax, bare.length) >= 0
674
+ ) {
675
+ const keyValue = splitKeyValue(
676
+ bare,
677
+ sCol,
678
+ ctx,
679
+ lineNum,
680
+ undefined,
681
+ syntax,
428
682
  );
429
- }
430
- const keyValue = splitKeyValue(s, sCol, ctx, t.lineNum ?? 0);
431
- if (keyValue) {
432
683
  const { key, valuePart, valueCol } = keyValue;
433
684
  if (valuePart === "" && key.length > 0) {
434
685
  return parseObjectOrNamedArray(tokens, i, key, ctx);
435
686
  }
436
- // Note: "key: <" without closing ">" is invalid - inline byte arrays must be closed on the same line
437
687
  if (key.length > 0) {
438
- const value =
439
- valuePart === ""
440
- ? undefined
441
- : parseScalar(valuePart, ctx, t.lineNum ?? 0, valueCol);
688
+ const value = parseScalar(valuePart, ctx, lineNum, valueCol);
442
689
  return [{ [key]: value }, i + 1];
443
690
  }
444
691
  }
445
- return [parseScalar(s, ctx, t.lineNum ?? 0, sCol), i + 1];
692
+ // Every inline value reads as a property's does
693
+ return [parseScalar(s, ctx, lineNum, sCol, syntax), i + 1];
446
694
  }
447
695
  return [undefined, i + 1];
448
696
  }
@@ -453,10 +701,18 @@ function parseValue(tokens, i, ctx = {}) {
453
701
  * @param {ParseContext} ctx
454
702
  * @param {number} lineNum
455
703
  * @param {number|undefined} inlineCol - column of opening brace for inline objects
704
+ * @param {ReturnType<typeof scanTopLevel>=} syntax
456
705
  * @returns {{key: string, valuePart: string, valueCol: number}|null}
457
706
  */
458
- function splitKeyValue(s, sCol, ctx, lineNum, inlineCol) {
459
- const colonIdx = findKeyColonOutsideQuotes(s);
707
+ function splitKeyValue(
708
+ s,
709
+ sCol,
710
+ ctx,
711
+ lineNum,
712
+ inlineCol,
713
+ syntax = scanTopLevel(s),
714
+ ) {
715
+ const colonIdx = findKeyColonOutsideQuotes(s, syntax);
460
716
  if (colonIdx < 0) return null;
461
717
  const keyRaw = s.slice(0, colonIdx);
462
718
  if (keyRaw.endsWith(" ")) {
@@ -472,21 +728,25 @@ function splitKeyValue(s, sCol, ctx, lineNum, inlineCol) {
472
728
  const col = sCol + Math.max(0, keyRaw.length - 1);
473
729
  throw new Error("Unterminated string" + locSuffix(ctx, lineNum, col));
474
730
  }
475
- key =
476
- quote === '"'
477
- ? parseQuotedString(keyRaw, ctx, lineNum, sCol)
478
- : keyRaw.slice(1, -1);
731
+ key = parseQuotedString(keyRaw, ctx, lineNum, sCol);
479
732
  } else {
480
733
  if (keyRaw.length === 0) {
481
734
  throw new Error("Missing key" + locSuffix(ctx, lineNum, sCol + colonIdx));
482
735
  }
736
+ if (
737
+ keyRaw.startsWith("<") &&
738
+ keyRaw.endsWith(">") &&
739
+ inlineCol === undefined
740
+ ) {
741
+ // A reference or bytes is a value, never a key: the colon is stray.
742
+ // In an inline object, "<" is a bad key's first character, below.
743
+ throw new Error(
744
+ 'Unexpected character ":"' + locSuffix(ctx, lineNum, sCol + colonIdx),
745
+ );
746
+ }
483
747
  for (let i = 0; i < keyRaw.length; i++) {
484
748
  const c = keyRaw[i];
485
- const isAlpha = (c >= "a" && c <= "z") || (c >= "A" && c <= "Z");
486
- const isDigit = c >= "0" && c <= "9";
487
- const isUnderscore = c === "_";
488
- const isHyphen = c === "-";
489
- if (!isAlpha && !isDigit && !isUnderscore && !isHyphen) {
749
+ if (!KEY_CHARACTER.test(c)) {
490
750
  // First character invalid = "Invalid key", subsequent = "Invalid key character"
491
751
  const errMsg = i === 0 ? "Invalid key" : "Invalid key character";
492
752
  // For inline objects, report column of opening brace; otherwise report character position
@@ -495,6 +755,7 @@ function splitKeyValue(s, sCol, ctx, lineNum, inlineCol) {
495
755
  throw new Error(errMsg + locSuffix(ctx, lineNum, errCol));
496
756
  }
497
757
  }
758
+ key = detachString(keyRaw);
498
759
  }
499
760
  const valueSlice = s.slice(colonIdx + 1);
500
761
  let valuePart = valueSlice;
@@ -519,45 +780,16 @@ function splitKeyValue(s, sCol, ctx, lineNum, inlineCol) {
519
780
 
520
781
  /**
521
782
  * @param {string} s
783
+ * @param {ReturnType<typeof scanTopLevel>=} syntax
784
+ * @param {number=} end
522
785
  * @returns {number}
523
786
  */
524
- function findKeyColonOutsideQuotes(s) {
525
- let inSingle = false;
526
- let inDouble = false;
527
- let escape = false;
528
- for (let i = 0; i < s.length; i++) {
529
- const ch = s[i];
530
- if (escape) {
531
- escape = false;
532
- continue;
533
- }
534
- if (inSingle) {
535
- if (ch === "\\") {
536
- escape = true;
537
- } else if (ch === "'") {
538
- inSingle = false;
539
- }
540
- continue;
541
- }
542
- if (inDouble) {
543
- if (ch === "\\") {
544
- escape = true;
545
- } else if (ch === '"') {
546
- inDouble = false;
547
- }
548
- continue;
549
- }
550
- if (ch === "'") {
551
- inSingle = true;
552
- continue;
553
- }
554
- if (ch === '"') {
555
- inDouble = true;
556
- continue;
557
- }
558
- if (ch === ":") return i;
559
- }
560
- return -1;
787
+ function findKeyColonOutsideQuotes(
788
+ s,
789
+ syntax = scanTopLevel(s),
790
+ end = s.length,
791
+ ) {
792
+ return syntax.colon !== undefined && syntax.colon < end ? syntax.colon : -1;
561
793
  }
562
794
 
563
795
  /**
@@ -574,6 +806,74 @@ function isPropertyBlockLeaderOnly(valuePart, leader) {
574
806
  return valuePart[i] === "#";
575
807
  }
576
808
 
809
+ /**
810
+ * Split an inline container body at its top-level commas. Quotes, tags, and
811
+ * references are already opaque in the shared syntax scan.
812
+ * @param {string} body
813
+ * @param {ParseContext} ctx
814
+ * @param {number} lineNum
815
+ * @param {number} col
816
+ * @param {{angles?: boolean, validateArrays?: boolean}=} options
817
+ * @returns {{text: string, start: number}[]}
818
+ */
819
+ function splitTopLevelCommas(
820
+ body,
821
+ ctx,
822
+ lineNum,
823
+ col,
824
+ { angles = false, validateArrays = false } = {},
825
+ ) {
826
+ const { masked } = scanTopLevel(body, true);
827
+ const parts = [];
828
+ let start = 0;
829
+ let braceDepth = 0;
830
+ let bracketDepth = 0;
831
+ let angleDepth = 0;
832
+ for (let i = 0; i < masked.length; i++) {
833
+ const c = masked[i];
834
+ if (validateArrays && c === "[" && body[i + 1] === " ") {
835
+ fail(ctx, 'Unexpected space after "["', lineNum, col + i + 1);
836
+ }
837
+ if (validateArrays && c === "]" && body[i - 1] === " ") {
838
+ fail(ctx, 'Unexpected space before "]"', lineNum, col + i - 1);
839
+ }
840
+ if (validateArrays && c === ",") {
841
+ if (i > 0 && body[i - 1] === " ") {
842
+ fail(ctx, 'Unexpected space before ","', lineNum, col + i - 1);
843
+ }
844
+ if (i + 1 < body.length && body[i + 1] !== " " && body[i + 1] !== "]") {
845
+ fail(ctx, 'Expected space after ","', lineNum, col + i);
846
+ }
847
+ if (body[i + 1] === " " && body[i + 2] === " ") {
848
+ fail(ctx, 'Unexpected space after ","', lineNum, col + i + 2);
849
+ }
850
+ }
851
+ if (c === "{") braceDepth++;
852
+ else if (c === "}" && braceDepth > 0) braceDepth--;
853
+ else if (c === "[") bracketDepth++;
854
+ else if (c === "]" && bracketDepth > 0) bracketDepth--;
855
+ else if (angles && c === "<") angleDepth++;
856
+ else if (angles && c === ">" && angleDepth > 0) angleDepth--;
857
+ else if (
858
+ c === "," &&
859
+ braceDepth === 0 &&
860
+ bracketDepth === 0 &&
861
+ angleDepth === 0
862
+ ) {
863
+ if (!validateArrays && i > 0 && body[i - 1] === " ") {
864
+ fail(ctx, 'Unexpected space before ","', lineNum, col + i - 1);
865
+ }
866
+ if (i + 1 >= body.length || body[i + 1] !== " ") {
867
+ fail(ctx, 'Expected space after ","', lineNum, col + i);
868
+ }
869
+ parts.push({ text: body.slice(start, i), start });
870
+ start = i + 2;
871
+ }
872
+ }
873
+ parts.push({ text: body.slice(start), start });
874
+ return parts;
875
+ }
876
+
577
877
  /**
578
878
  * @param {string} s
579
879
  * @param {ParseContext} ctx
@@ -581,7 +881,13 @@ function isPropertyBlockLeaderOnly(valuePart, leader) {
581
881
  * @param {number} col
582
882
  * @returns {Record<string, unknown>|null}
583
883
  */
584
- function parseInlineObject(s, ctx = {}, lineNum = 0, col = 0) {
884
+ function parseInlineObjectSlow(s, ctx = {}, lineNum = 0, col = 0) {
885
+ return nested(ctx, lineNum, col, () =>
886
+ parseInlineObjectSlowBody(s, ctx, lineNum, col),
887
+ );
888
+ }
889
+
890
+ function parseInlineObjectSlowBody(s, ctx, lineNum, col) {
585
891
  if (!s.startsWith("{")) return null;
586
892
  if (!s.includes("}")) {
587
893
  return null;
@@ -604,77 +910,10 @@ function parseInlineObject(s, ctx = {}, lineNum = 0, col = 0) {
604
910
  );
605
911
  }
606
912
  const body = s.slice(1, -1);
607
- const parts = [];
608
- let start = 0;
609
- let inSingle = false;
610
- let inDouble = false;
611
- let escape = false;
612
- let braceDepth = 0;
613
- let bracketDepth = 0;
614
- for (let i = 0; i < body.length; i++) {
615
- const ch = body[i];
616
- if (escape) {
617
- escape = false;
618
- continue;
619
- }
620
- if (inSingle) {
621
- if (ch === "\\") {
622
- escape = true;
623
- } else if (ch === "'") {
624
- inSingle = false;
625
- }
626
- continue;
627
- }
628
- if (inDouble) {
629
- if (ch === "\\") {
630
- escape = true;
631
- } else if (ch === '"') {
632
- inDouble = false;
633
- }
634
- continue;
635
- }
636
- if (ch === "'") {
637
- inSingle = true;
638
- continue;
639
- }
640
- if (ch === '"') {
641
- inDouble = true;
642
- continue;
643
- }
644
- if (ch === "{") {
645
- braceDepth++;
646
- continue;
647
- }
648
- if (ch === "}") {
649
- if (braceDepth > 0) braceDepth--;
650
- continue;
651
- }
652
- if (ch === "[") {
653
- bracketDepth++;
654
- continue;
655
- }
656
- if (ch === "]") {
657
- if (bracketDepth > 0) bracketDepth--;
658
- continue;
659
- }
660
- if (ch === "," && braceDepth === 0 && bracketDepth === 0) {
661
- if (i > 0 && body[i - 1] === " ") {
662
- throw new Error(
663
- 'Unexpected space before ","' +
664
- locSuffix(ctx, lineNum, col + 1 + i - 1),
665
- );
666
- }
667
- if (i + 1 >= body.length || body[i + 1] !== " ") {
668
- throw new Error(
669
- 'Expected space after ","' + locSuffix(ctx, lineNum, col + 1 + i),
670
- );
671
- }
672
- parts.push({ text: body.slice(start, i), start });
673
- start = i + 2;
674
- }
675
- }
676
- parts.push({ text: body.slice(start), start });
913
+ const parts = splitTopLevelCommas(body, ctx, lineNum, col + 1);
677
914
  const obj = {};
915
+ /** @type {Map<string, [number, number]>} */
916
+ const seen = new Map();
678
917
  for (const part of parts) {
679
918
  if (part.text.length === 0) {
680
919
  throw new Error("Missing key" + locSuffix(ctx, lineNum, col + 1));
@@ -687,598 +926,1107 @@ function parseInlineObject(s, ctx = {}, lineNum = 0, col = 0) {
687
926
  );
688
927
  }
689
928
  const { key, valuePart, valueCol } = keyValue;
929
+ claimKey(seen, key, ctx, lineNum, partCol);
690
930
  if (valuePart === "") {
691
931
  throw new Error("Missing value" + locSuffix(ctx, lineNum, valueCol));
692
932
  }
693
- obj[key] = parseScalar(valuePart, ctx, lineNum, valueCol);
933
+ setOwn(obj, key, parseScalar(valuePart, ctx, lineNum, valueCol));
694
934
  }
695
935
  return obj;
696
936
  }
697
937
 
698
- /**
699
- * @param {string} s
700
- * @param {ParseContext} ctx
701
- * @param {number} lineNum
702
- * @param {number} col
703
- * @returns {unknown}
704
- */
705
- function parseScalar(s, ctx = {}, lineNum = 0, col = 0) {
706
- // Strip inline comments first
707
- s = stripInlineComment(s);
938
+ function parseInlineArraySlow(s, ctx = {}, lineNum = 0, col = 0) {
939
+ return nested(ctx, lineNum, col, () =>
940
+ parseInlineArraySlowBody(s, ctx, lineNum, col),
941
+ );
942
+ }
708
943
 
709
- if (s === "null") return null;
710
- if (s === "true") return true;
711
- if (s === "false") return false;
712
- if (s === "nan") return NaN;
713
- if (s === "infinity") return Infinity;
714
- if (s === "-infinity") return -Infinity;
715
- const num = parseNumber(s, ctx, lineNum, col);
716
- if (num !== undefined) return num;
717
- if (s.startsWith('"')) {
718
- if (!s.endsWith('"') || s.length < 2) {
719
- throw new Error(
720
- "Unterminated string" + locSuffix(ctx, lineNum, col + s.length),
721
- );
722
- }
723
- return parseQuotedString(s, ctx, lineNum, col);
944
+ function parseInlineArraySlowBody(s, ctx, lineNum, col) {
945
+ if (!s.startsWith("[")) return [];
946
+ if (!s.endsWith("]")) {
947
+ throw new Error("Unterminated inline array" + locSuffix(ctx, lineNum, col));
948
+ }
949
+ if (s === "[]") return [];
950
+ if (s[1] === " ") {
951
+ throw new Error(
952
+ 'Unexpected space after "["' + locSuffix(ctx, lineNum, col + 1),
953
+ );
954
+ }
955
+ if (s[s.length - 2] === " ") {
956
+ throw new Error(
957
+ 'Unexpected space before "]"' +
958
+ locSuffix(ctx, lineNum, col + s.length - 2),
959
+ );
724
960
  }
725
- if (s.startsWith("'")) {
726
- if (!s.endsWith("'") || s.length < 2) {
961
+ const body = s.slice(1, -1);
962
+ const parts = splitTopLevelCommas(body, ctx, lineNum, col + 1, {
963
+ angles: true,
964
+ validateArrays: true,
965
+ });
966
+ const arr = [];
967
+ for (const part of parts) {
968
+ if (part.text.length === 0) {
727
969
  throw new Error(
728
- "Unterminated string" + locSuffix(ctx, lineNum, col + s.length),
970
+ "Missing array element" + locSuffix(ctx, lineNum, col + 1 + part.start),
729
971
  );
730
972
  }
731
- return s.slice(1, -1);
973
+ const partCol = col + 1 + part.start;
974
+ arr.push(parseScalar(part.text, ctx, lineNum, partCol));
732
975
  }
733
- if (s.startsWith("[")) return parseInlineArray(s, ctx, lineNum, col);
734
- if (s.startsWith("{")) return parseInlineObject(s, ctx, lineNum, col);
735
- if (s.startsWith("<")) return parseAngleBytes(s, ctx, lineNum, col);
736
- // Bare words are not valid - strings must be quoted
737
- const firstChar = s.charAt(0) || "?";
738
- throw new Error(
739
- `Unexpected character "${firstChar}"` + locSuffix(ctx, lineNum, col),
740
- );
976
+ return arr;
977
+ }
978
+
979
+ function parseInlineObject(s, ctx = {}, lineNum = 0, col = 0) {
980
+ return parseInlineObjectBody(s, ctx, lineNum, col);
981
+ }
982
+
983
+ function parseInlineObjectBody(s, ctx, lineNum, col) {
984
+ if (!s.startsWith("{")) return null;
985
+ if (!s.includes("}")) {
986
+ return null;
987
+ }
988
+ if (!s.endsWith("}")) {
989
+ throw new Error(
990
+ "Unexpected inline object content" + locSuffix(ctx, lineNum, col),
991
+ );
992
+ }
993
+ if (s === "{}") return {};
994
+ if (s[1] === " ") {
995
+ throw new Error(
996
+ 'Unexpected space after "{"' + locSuffix(ctx, lineNum, col + 1),
997
+ );
998
+ }
999
+ if (s[s.length - 2] === " ") {
1000
+ throw new Error(
1001
+ 'Unexpected space before "}"' +
1002
+ locSuffix(ctx, lineNum, col + s.length - 2),
1003
+ );
1004
+ }
1005
+ const [obj, next] = parseInlineObjectAt(s, 0, ctx, lineNum, col);
1006
+ if (next !== s.length) {
1007
+ throw new Error(
1008
+ "Unexpected inline object content" + locSuffix(ctx, lineNum, col),
1009
+ );
1010
+ }
1011
+ return obj;
741
1012
  }
742
1013
 
743
1014
  /**
1015
+ * Parse an inline object beginning at s[open], in one pass. Values are read
1016
+ * by their own parser, so nested containers are not rescanned at every
1017
+ * level. Returns the value and the index after the closing brace.
744
1018
  * @param {string} s
745
- * @returns {number|bigint|undefined}
746
- */
747
- /**
748
- * @param {string} s
1019
+ * @param {number} open
749
1020
  * @param {ParseContext} ctx
750
1021
  * @param {number} lineNum
751
1022
  * @param {number} col
752
- * @returns {number|bigint|undefined}
1023
+ * @returns {[Record<string, unknown>, number]}
753
1024
  */
754
- function parseNumber(s, ctx = {}, lineNum = 0, col = 0) {
755
- // Check for uppercase E in exponent (must be lowercase)
756
- // Only check if this looks like a number (starts with digit, minus, or dot)
757
- const firstNonSpace = s.replace(/^ */, "")[0];
758
- if (
759
- (firstNonSpace >= "0" && firstNonSpace <= "9") ||
760
- firstNonSpace === "-" ||
761
- firstNonSpace === "."
762
- ) {
763
- const eIdx = s.indexOf("E");
764
- if (eIdx >= 0) {
1025
+ function parseInlineObjectAt(s, open, ctx, lineNum, col) {
1026
+ return nested(ctx, lineNum, col + open, () =>
1027
+ parseInlineObjectAtBody(s, open, ctx, lineNum, col),
1028
+ );
1029
+ }
1030
+
1031
+ function parseInlineObjectAtBody(s, open, ctx, lineNum, col) {
1032
+ const obj = {};
1033
+ /** @type {Map<string, [number, number]>} */
1034
+ const seen = new Map();
1035
+ let i = open + 1;
1036
+ if (s.charCodeAt(i) === 0x7d) return [obj, i + 1];
1037
+ if (s.charCodeAt(i) === 0x20) {
1038
+ fail(ctx, 'Unexpected space after "{"', lineNum, col + i);
1039
+ }
1040
+ for (;;) {
1041
+ if (i >= s.length) {
765
1042
  throw new Error(
766
- "Uppercase exponent (use lowercase 'e')" +
767
- locSuffix(ctx, lineNum, col + eIdx),
1043
+ "Unexpected newline in inline object" +
1044
+ locSuffix(ctx, lineNum, col + open),
768
1045
  );
769
1046
  }
770
- }
771
-
772
- let hasDigit = false;
773
- let hasExponent = false;
774
- for (let i = 0; i < s.length; i++) {
775
- const c = s[i];
776
- if (c === " ") continue;
777
- if (c >= "0" && c <= "9") {
778
- hasDigit = true;
779
- continue;
1047
+ const c = s.charCodeAt(i);
1048
+ if (c === 0x7d || c === 0x2c) {
1049
+ throw new Error("Missing key" + locSuffix(ctx, lineNum, col + i));
780
1050
  }
781
- if (c === ".") continue;
782
- if (c === "-" && i === 0) continue;
783
- // Allow 'e' for exponent notation (E already rejected above)
784
- if (c === "e" && hasDigit && !hasExponent) {
785
- hasExponent = true;
786
- continue;
1051
+ const colon = findInlineKeyColon(s, i);
1052
+ if (colon < 0) {
1053
+ throw new Error(
1054
+ "Expected colon after key" + locSuffix(ctx, lineNum, col),
1055
+ );
787
1056
  }
788
- // Allow +/- after exponent
789
- if ((c === "+" || c === "-") && hasExponent) {
790
- const prev = i > 0 ? s[i - 1] : "";
791
- if (prev === "e") continue;
1057
+ const partCol = col + i;
1058
+ const key = parseInlineKeyAt(s, i, colon, ctx, lineNum, col, col + open);
1059
+ claimKey(seen, key, ctx, lineNum, partCol);
1060
+ let valueIndex = colon + 1;
1061
+ if (valueIndex >= s.length) {
1062
+ throw new Error(
1063
+ "Missing value" + locSuffix(ctx, lineNum, col + valueIndex),
1064
+ );
792
1065
  }
793
- // Not a numeric candidate.
794
- return undefined;
795
- }
796
- if (!hasDigit) return undefined;
797
- for (let i = 0; i < s.length; i++) {
798
- if (s[i] !== " ") continue;
799
- const prev = i > 0 ? s[i - 1] : "";
800
- const next = i + 1 < s.length ? s[i + 1] : "";
801
- const isDigitPrev = prev >= "0" && prev <= "9";
802
- const isDigitNext = next >= "0" && next <= "9";
803
- if (!(isDigitPrev && isDigitNext)) {
1066
+ if (s.charCodeAt(valueIndex) === 0x20) {
1067
+ if (s.charCodeAt(valueIndex + 1) === 0x20) {
1068
+ fail(ctx, 'Unexpected space after ":"', lineNum, col + valueIndex + 1);
1069
+ }
1070
+ valueIndex++;
1071
+ } else if (
1072
+ s.charCodeAt(valueIndex) !== 0x2c &&
1073
+ s.charCodeAt(valueIndex) !== 0x7d
1074
+ ) {
1075
+ fail(ctx, 'Expected space after ":"', lineNum, col + colon);
1076
+ }
1077
+ if (
1078
+ valueIndex >= s.length ||
1079
+ s.charCodeAt(valueIndex) === 0x7d ||
1080
+ s.charCodeAt(valueIndex) === 0x2c
1081
+ ) {
804
1082
  throw new Error(
805
- "Unexpected space in number" + locSuffix(ctx, lineNum, col + i),
1083
+ "Missing value" + locSuffix(ctx, lineNum, col + valueIndex),
806
1084
  );
807
1085
  }
1086
+ const [value, next] = parseInlineValueAt(
1087
+ s,
1088
+ valueIndex,
1089
+ ctx,
1090
+ lineNum,
1091
+ col,
1092
+ 0x7d,
1093
+ );
1094
+ setOwn(obj, key, value);
1095
+ if (next >= s.length) {
1096
+ throw new Error(
1097
+ "Unexpected newline in inline object" +
1098
+ locSuffix(ctx, lineNum, col + open),
1099
+ );
1100
+ }
1101
+ const after = s.charCodeAt(next);
1102
+ if (after === 0x7d) {
1103
+ if (s.charCodeAt(next - 1) === 0x20) {
1104
+ fail(ctx, 'Unexpected space before "}"', lineNum, col + next - 1);
1105
+ }
1106
+ return [obj, next + 1];
1107
+ }
1108
+ if (after === 0x2c) {
1109
+ if (s.charCodeAt(next - 1) === 0x20) {
1110
+ fail(ctx, 'Unexpected space before ","', lineNum, col + next - 1);
1111
+ }
1112
+ if (next + 1 >= s.length || s.charCodeAt(next + 1) !== 0x20) {
1113
+ fail(ctx, 'Expected space after ","', lineNum, col + next);
1114
+ }
1115
+ if (s.charCodeAt(next + 2) === 0x20) {
1116
+ fail(ctx, 'Unexpected space after ","', lineNum, col + next + 2);
1117
+ }
1118
+ i = next + 2;
1119
+ continue;
1120
+ }
1121
+ if (after === 0x20) {
1122
+ if (s.charCodeAt(next + 1) === 0x7d) {
1123
+ fail(ctx, 'Unexpected space before "}"', lineNum, col + next);
1124
+ }
1125
+ if (s.charCodeAt(next + 1) === 0x2c) {
1126
+ fail(ctx, 'Unexpected space before ","', lineNum, col + next);
1127
+ }
1128
+ }
1129
+ throw new Error(
1130
+ `Unexpected character "${s[next]}"` + locSuffix(ctx, lineNum, col + next),
1131
+ );
808
1132
  }
809
- const compact = s.replace(/ /g, "");
810
- if (/^-?\d+$/.test(compact)) return BigInt(compact);
811
- // Float patterns: with decimal point, or with exponent, or both
812
- if (
813
- /^-?\d*\.\d*([eE][+-]?\d+)?$/.test(compact) ||
814
- /^-?\d+[eE][+-]?\d+$/.test(compact)
815
- ) {
816
- const n = Number(compact);
817
- if (!isNaN(n)) return n;
818
- }
819
- return undefined;
820
1133
  }
821
1134
 
822
1135
  /**
1136
+ * Find the colon that separates an inline object's key from its value.
1137
+ * Quotes, tags, and references are opaque, as they are to the syntax scan.
823
1138
  * @param {string} s
824
- * @param {ParseContext} ctx
825
- * @param {number} lineNum
826
- * @param {number} col
827
- * @returns {string}
1139
+ * @param {number} start
1140
+ * @returns {number}
828
1141
  */
829
- function parseQuotedString(s, ctx = {}, lineNum = 0, col = 0) {
830
- if (s.startsWith('"')) return parseJsonQuotedString(s, ctx, lineNum, col);
831
- if (s.startsWith("'")) return s.slice(1, -1);
832
- return s;
1142
+ function findInlineKeyColon(s, start) {
1143
+ const n = s.length;
1144
+ let i = start;
1145
+ while (i < n) {
1146
+ const c = s.charCodeAt(i);
1147
+ if (c === 0x22 || c === 0x27) {
1148
+ i++;
1149
+ while (i < n) {
1150
+ const q = s.charCodeAt(i);
1151
+ if (q === 0x5c) {
1152
+ i += 2;
1153
+ continue;
1154
+ }
1155
+ i++;
1156
+ if (q === c) break;
1157
+ }
1158
+ continue;
1159
+ }
1160
+ if (c === 0x3c && isReferenceStartAt(s, i)) {
1161
+ const end = s.indexOf(">", i);
1162
+ i = end < 0 ? n : end + 1;
1163
+ continue;
1164
+ }
1165
+ if (c === 0x28) {
1166
+ i++;
1167
+ while (i < n) {
1168
+ const q = s.charCodeAt(i);
1169
+ if (q === 0x29) {
1170
+ i++;
1171
+ break;
1172
+ }
1173
+ i += q === 0x5c ? 2 : 1;
1174
+ }
1175
+ continue;
1176
+ }
1177
+ if (c === 0x3a) return i;
1178
+ i++;
1179
+ }
1180
+ return -1;
833
1181
  }
834
1182
 
835
1183
  /**
836
- * Minimal JSON string parser for deterministic errors.
1184
+ * Read an inline object's key, from start to its colon, with the checks the
1185
+ * shared key reader makes for a block object.
837
1186
  * @param {string} s
1187
+ * @param {number} start
1188
+ * @param {number} colon
838
1189
  * @param {ParseContext} ctx
839
1190
  * @param {number} lineNum
840
1191
  * @param {number} col
841
1192
  * @returns {string}
842
1193
  */
843
- function parseJsonQuotedString(s, ctx = {}, lineNum = 0, col = 0) {
844
- if (s.length < 2 || s[0] !== '"') return s;
845
- if (s[s.length - 1] !== '"') {
846
- const index = Math.max(0, s.length - 1);
1194
+ function parseInlineKeyAt(s, start, colon, ctx, lineNum, col, inlineCol) {
1195
+ const keyRaw = s.slice(start, colon);
1196
+ const sCol = col + start;
1197
+ if (keyRaw.endsWith(" ")) {
847
1198
  throw new Error(
848
- "Unterminated string" + locSuffix(ctx, lineNum, col + index),
1199
+ 'Unexpected space before ":"' +
1200
+ locSuffix(ctx, lineNum, sCol + keyRaw.length - 1),
849
1201
  );
850
1202
  }
851
- let out = "";
852
- for (let i = 1; i < s.length - 1; i++) {
853
- const ch = s[i];
854
- if (ch === "\\") {
855
- // Escapes follow JSON rules; report the offending escape character.
856
- if (i + 1 >= s.length - 1) {
857
- throw new Error(
858
- "Bad escaped character" + locSuffix(ctx, lineNum, col + i + 1),
859
- );
860
- }
861
- const esc = s[i + 1];
862
- switch (esc) {
863
- case '"':
864
- out += '"';
865
- i++;
866
- break;
867
- case "\\":
868
- out += "\\";
869
- i++;
870
- break;
871
- case "/":
872
- out += "/";
873
- i++;
874
- break;
875
- case "b":
876
- out += "\b";
877
- i++;
878
- break;
879
- case "f":
880
- out += "\f";
881
- i++;
882
- break;
883
- case "n":
884
- out += "\n";
885
- i++;
886
- break;
887
- case "r":
888
- out += "\r";
889
- i++;
890
- break;
891
- case "t":
892
- out += "\t";
893
- i++;
894
- break;
895
- case "u": {
896
- // YAY uses \u{XXXXXX} syntax (variable-length with braces)
897
- const braceStart = i + 2;
898
- const uCol = col + i + 1; // Column of 'u' for "Bad escaped character"
899
- const braceCol = col + braceStart; // Column of '{' for other errors
900
- if (braceStart >= s.length - 1 || s[braceStart] !== "{") {
901
- // Old-style \uXXXX syntax is not supported
902
- throw new Error(
903
- "Bad escaped character" + locSuffix(ctx, lineNum, uCol),
904
- );
905
- }
906
- // Find closing brace
907
- let braceEnd = braceStart + 1;
908
- while (braceEnd < s.length - 1 && s[braceEnd] !== "}") {
909
- braceEnd++;
910
- }
911
- if (braceEnd >= s.length - 1 || s[braceEnd] !== "}") {
912
- throw new Error(
913
- "Bad Unicode escape" + locSuffix(ctx, lineNum, braceCol),
914
- );
915
- }
916
- const hexStart = braceStart + 1;
917
- if (hexStart === braceEnd) {
918
- throw new Error(
919
- "Bad Unicode escape" + locSuffix(ctx, lineNum, braceCol),
920
- );
921
- }
922
- // Check for too many hex digits (max 6)
923
- if (braceEnd - hexStart > 6) {
924
- throw new Error(
925
- "Bad Unicode escape" + locSuffix(ctx, lineNum, braceCol),
926
- );
927
- }
928
- let hex = "";
929
- for (let j = hexStart; j < braceEnd; j++) {
930
- const c = s[j];
931
- if (!/[0-9a-fA-F]/.test(c)) {
932
- throw new Error(
933
- "Bad Unicode escape" + locSuffix(ctx, lineNum, braceCol),
934
- );
935
- }
936
- hex += c;
937
- }
938
- const code = parseInt(hex, 16);
939
- if (code >= 0xd800 && code <= 0xdfff) {
940
- throw new Error(
941
- "Illegal surrogate" + locSuffix(ctx, lineNum, braceCol),
942
- );
943
- }
944
- if (code > 0x10ffff) {
945
- throw new Error(
946
- "Unicode code point out of range" +
947
- locSuffix(ctx, lineNum, braceCol),
948
- );
949
- }
950
- out += String.fromCodePoint(code);
951
- i = braceEnd; // Loop will increment to braceEnd + 1
952
- break;
953
- }
954
- default:
955
- throw new Error(
956
- "Bad escaped character" + locSuffix(ctx, lineNum, col + i + 1),
957
- );
958
- }
959
- } else {
960
- // Unescaped control characters are illegal in JSON strings.
961
- const code = ch.charCodeAt(0);
962
- if (code < 0x20) {
963
- throw new Error(
964
- "Bad character in string" + locSuffix(ctx, lineNum, col + i),
965
- );
966
- }
967
- out += ch;
1203
+ if (keyRaw.startsWith('"') || keyRaw.startsWith("'")) {
1204
+ const quote = keyRaw[0];
1205
+ if (keyRaw.length < 2 || keyRaw[keyRaw.length - 1] !== quote) {
1206
+ throw new Error(
1207
+ "Unterminated string" +
1208
+ locSuffix(ctx, lineNum, sCol + keyRaw.length - 1),
1209
+ );
968
1210
  }
1211
+ return parseQuotedString(keyRaw, ctx, lineNum, sCol);
969
1212
  }
970
- return out;
1213
+ if (keyRaw.length === 0) {
1214
+ throw new Error("Missing key" + locSuffix(ctx, lineNum, col + colon));
1215
+ }
1216
+ for (let i = 0; i < keyRaw.length; i++) {
1217
+ if (!KEY_CHARACTER.test(keyRaw[i])) {
1218
+ const message = i === 0 ? "Invalid key" : "Invalid key character";
1219
+ const errCol = i === 0 ? inlineCol : sCol + i;
1220
+ throw new Error(message + locSuffix(ctx, lineNum, errCol));
1221
+ }
1222
+ }
1223
+ return detachString(keyRaw);
971
1224
  }
972
1225
 
973
1226
  /**
1227
+ * Parse one inline value beginning at s[i], in one pass. A leaf value is
1228
+ * read from its whole text with the shared scalar reader; a container is
1229
+ * read by its own cursor, so its body is not rescanned. Returns the value
1230
+ * and the index of what follows its suffix, the delimiter or the offending
1231
+ * character.
974
1232
  * @param {string} s
1233
+ * @param {number} i
975
1234
  * @param {ParseContext} ctx
976
1235
  * @param {number} lineNum
977
1236
  * @param {number} col
978
- * @returns {unknown[]}
1237
+ * @param {number} closeCode
1238
+ * @returns {[unknown, number]}
979
1239
  */
980
- function parseInlineArray(s, ctx = {}, lineNum = 0, col = 0) {
981
- if (!s.startsWith("[")) return [];
982
- if (!s.endsWith("]")) {
983
- throw new Error("Unterminated inline array" + locSuffix(ctx, lineNum, col));
1240
+ function parseInlineValueAt(s, i, ctx, lineNum, col, closeCode) {
1241
+ const c = s.charCodeAt(i);
1242
+ let value;
1243
+ let next;
1244
+ if (c === 0x5b) {
1245
+ [value, next] = parseInlineArrayAt(s, i, ctx, lineNum, col);
1246
+ const [tags, n] = parseSuffix(s.slice(next), ctx, lineNum, col + next);
1247
+ return [wrapTags(value, tags), next + n];
984
1248
  }
985
- if (s === "[]") return [];
986
- if (s[1] === " ") {
987
- throw new Error(
988
- 'Unexpected space after "["' + locSuffix(ctx, lineNum, col + 1),
989
- );
1249
+ if (c === 0x7b) {
1250
+ [value, next] = parseInlineObjectAt(s, i, ctx, lineNum, col);
1251
+ const [tags, n] = parseSuffix(s.slice(next), ctx, lineNum, col + next);
1252
+ return [wrapTags(value, tags), next + n];
990
1253
  }
991
- if (s[s.length - 2] === " ") {
992
- throw new Error(
993
- 'Unexpected space before "]"' +
994
- locSuffix(ctx, lineNum, col + s.length - 2),
995
- );
1254
+ next = findInlineValueEnd(s, i, closeCode, closeCode === 0x5d);
1255
+ if (next < s.length) {
1256
+ const delimiter = s.charCodeAt(next);
1257
+ if (delimiter === 0x2c && s.charCodeAt(next - 1) === 0x20) {
1258
+ fail(ctx, 'Unexpected space before ","', lineNum, col + next - 1);
1259
+ }
1260
+ if (delimiter === closeCode && s.charCodeAt(next - 1) === 0x20) {
1261
+ fail(
1262
+ ctx,
1263
+ `Unexpected space before "${s[next]}"`,
1264
+ lineNum,
1265
+ col + next - 1,
1266
+ );
1267
+ }
996
1268
  }
997
- const body = s.slice(1, -1);
998
- const parts = [];
999
- let start = 0;
1000
- let inSingle = false;
1001
- let inDouble = false;
1002
- let escape = false;
1269
+ return [parseScalar(s.slice(i, next), ctx, lineNum, col + i), next];
1270
+ }
1271
+
1272
+ /**
1273
+ * The end of an inline value's own text: its next top-level comma, or the
1274
+ * container's closing character. Quotes, tags, references, and nested
1275
+ * containers are skipped structurally.
1276
+ * @param {string} s
1277
+ * @param {number} start
1278
+ * @param {number} closeCode
1279
+ * @param {boolean} angles
1280
+ * @returns {number}
1281
+ */
1282
+ function findInlineValueEnd(s, start, closeCode, angles) {
1283
+ const n = s.length;
1284
+ let i = start;
1285
+ let quote = 0;
1003
1286
  let braceDepth = 0;
1004
1287
  let bracketDepth = 0;
1005
1288
  let angleDepth = 0;
1006
- for (let i = 0; i < body.length; i++) {
1007
- const ch = body[i];
1008
- if (escape) {
1009
- escape = false;
1010
- continue;
1011
- }
1012
- if (inSingle) {
1013
- if (ch === "\\") {
1014
- escape = true;
1015
- } else if (ch === "'") {
1016
- inSingle = false;
1017
- }
1018
- continue;
1019
- }
1020
- if (inDouble) {
1021
- if (ch === "\\") {
1022
- escape = true;
1023
- } else if (ch === '"') {
1024
- inDouble = false;
1289
+ while (i < n) {
1290
+ const c = s.charCodeAt(i);
1291
+ if (quote !== 0) {
1292
+ if (c === 0x5c) {
1293
+ i += 2;
1294
+ continue;
1025
1295
  }
1296
+ if (c === quote) quote = 0;
1297
+ i++;
1026
1298
  continue;
1027
1299
  }
1028
- if (ch === "'") {
1029
- inSingle = true;
1300
+ if (c === 0x22 || c === 0x27) {
1301
+ quote = c;
1302
+ i++;
1030
1303
  continue;
1031
1304
  }
1032
- if (ch === '"') {
1033
- inDouble = true;
1305
+ if (c === 0x3c && isReferenceStartAt(s, i)) {
1306
+ const end = s.indexOf(">", i);
1307
+ i = end < 0 ? n : end + 1;
1034
1308
  continue;
1035
1309
  }
1036
- if (ch === "{") {
1037
- braceDepth++;
1310
+ if (c === 0x28) {
1311
+ i++;
1312
+ while (i < n) {
1313
+ const q = s.charCodeAt(i);
1314
+ if (q === 0x29) {
1315
+ i++;
1316
+ break;
1317
+ }
1318
+ i += q === 0x5c ? 2 : 1;
1319
+ }
1038
1320
  continue;
1039
1321
  }
1040
- if (ch === "}") {
1041
- if (braceDepth > 0) braceDepth--;
1042
- continue;
1322
+ if (angles) {
1323
+ if (c === 0x3c) angleDepth++;
1324
+ else if (c === 0x3e && angleDepth > 0) angleDepth--;
1043
1325
  }
1044
- if (ch === "[") {
1326
+ if (c === 0x7b) {
1327
+ braceDepth++;
1328
+ } else if (c === 0x7d && braceDepth > 0) {
1329
+ braceDepth--;
1330
+ } else if (c === 0x5b) {
1045
1331
  bracketDepth++;
1046
- continue;
1047
- }
1048
- if (ch === "]") {
1049
- if (bracketDepth > 0) bracketDepth--;
1050
- continue;
1051
- }
1052
- if (ch === "<") {
1053
- angleDepth++;
1054
- continue;
1055
- }
1056
- if (ch === ">") {
1057
- if (angleDepth > 0) angleDepth--;
1058
- continue;
1332
+ } else if (c === 0x5d && bracketDepth > 0) {
1333
+ bracketDepth--;
1334
+ } else if (braceDepth === 0 && bracketDepth === 0 && angleDepth === 0) {
1335
+ if (c === 0x2c) return i;
1336
+ if (c === closeCode) return i;
1059
1337
  }
1060
- if (
1061
- ch === "," &&
1062
- braceDepth === 0 &&
1063
- bracketDepth === 0 &&
1064
- angleDepth === 0
1065
- ) {
1066
- if (i > 0 && body[i - 1] === " ") {
1067
- throw new Error(
1068
- 'Unexpected space before ","' +
1069
- locSuffix(ctx, lineNum, col + 1 + i - 1),
1070
- );
1071
- }
1072
- if (i + 1 >= body.length || body[i + 1] !== " ") {
1338
+ i++;
1339
+ }
1340
+ return n;
1341
+ }
1342
+
1343
+ /**
1344
+ * @param {string} s
1345
+ * @param {ParseContext} ctx
1346
+ * @param {number} lineNum
1347
+ * @param {number} col
1348
+ * @returns {unknown}
1349
+ */
1350
+ function parseScalar(
1351
+ s,
1352
+ ctx = {},
1353
+ lineNum = 0,
1354
+ col = 0,
1355
+ syntax = scanTopLevel(s),
1356
+ ) {
1357
+ // Strip inline comments first
1358
+ s = stripInlineComment(s, ctx, lineNum, col, syntax);
1359
+ const first =
1360
+ syntax.firstTag !== undefined && syntax.firstTag < s.length
1361
+ ? syntax.firstTag
1362
+ : undefined;
1363
+ if (first !== undefined) {
1364
+ if (first === 0) {
1365
+ const [name, n] = parseTag(s, ctx, lineNum, col);
1366
+ const [tags, m] = parseSuffix(s.slice(n), ctx, lineNum, col + n);
1367
+ if (n + m !== s.length) {
1073
1368
  throw new Error(
1074
- 'Expected space after ","' + locSuffix(ctx, lineNum, col + 1 + i),
1369
+ "Unexpected text after a tag" + locSuffix(ctx, lineNum, col + n),
1075
1370
  );
1076
1371
  }
1077
- parts.push({ text: body.slice(start, i), start });
1078
- start = i + 2;
1372
+ return wrapTags(decodeSymbolText(name, ctx), tags);
1079
1373
  }
1080
- }
1081
- parts.push({ text: body.slice(start), start });
1082
- const arr = [];
1083
- for (const part of parts) {
1084
- if (part.text.length === 0) {
1374
+ const atomEnd = s.slice(0, first).trimEnd().length;
1375
+ const [tags, n] = parseSuffix(
1376
+ s.slice(atomEnd),
1377
+ ctx,
1378
+ lineNum,
1379
+ col + atomEnd,
1380
+ );
1381
+ if (atomEnd + n !== s.length) {
1085
1382
  throw new Error(
1086
- "Missing array element" + locSuffix(ctx, lineNum, col + 1 + part.start),
1383
+ `Unexpected character "${s[atomEnd + n]}"` +
1384
+ locSuffix(ctx, lineNum, col + atomEnd + n),
1087
1385
  );
1088
1386
  }
1089
- const partCol = col + 1 + part.start;
1090
- arr.push(parseScalar(part.text, ctx, lineNum, partCol));
1387
+ const atom = s.slice(0, atomEnd);
1388
+ return wrapTags(parseScalarAtom(atom, ctx, lineNum, col), tags);
1091
1389
  }
1092
- return arr;
1390
+ return parseScalarAtom(s, ctx, lineNum, col);
1391
+ }
1392
+
1393
+ /**
1394
+ * Whether a huge malformed flood hit the depth limit. The old reader would
1395
+ * rescan a remainder this large at every level, so keep the first error.
1396
+ * @param {unknown} error
1397
+ * @param {string} s
1398
+ */
1399
+ function isHugeDepthError(error, s) {
1400
+ return (
1401
+ s.length > MAX_DEPTH_FALLBACK_LENGTH &&
1402
+ error instanceof Error &&
1403
+ error.message.startsWith("Inline nesting deeper than")
1404
+ );
1093
1405
  }
1094
1406
 
1095
1407
  /**
1408
+ * Parse an inline array with the one-pass reader, falling back to the
1409
+ * original substring reader when the one-pass reader refuses it. The
1410
+ * fallback preserves the reading and errors of an ordinary malformed
1411
+ * document, while valid documents never pay for it.
1096
1412
  * @param {string} s
1097
1413
  * @param {ParseContext} ctx
1098
1414
  * @param {number} lineNum
1099
1415
  * @param {number} col
1416
+ * @returns {unknown[]}
1100
1417
  */
1101
- function validateInlineArrayWhitespace(s, ctx = {}, lineNum = 0, col = 0) {
1102
- let inSingle = false;
1103
- let inDouble = false;
1104
- let escape = false;
1105
- let depth = 0;
1106
- for (let i = 0; i < s.length; i++) {
1107
- const ch = s[i];
1108
- if (escape) {
1109
- escape = false;
1110
- continue;
1111
- }
1112
- if (inSingle) {
1113
- if (ch === "\\") {
1114
- escape = true;
1115
- } else if (ch === "'") {
1116
- inSingle = false;
1117
- }
1118
- continue;
1418
+ function parseInlineArrayWithFallback(s, ctx, lineNum, col) {
1419
+ if (ctx.inlineSlow) return parseInlineArraySlow(s, ctx, lineNum, col);
1420
+ try {
1421
+ return parseInlineArray(s, ctx, lineNum, col);
1422
+ } catch (error) {
1423
+ if (isHugeDepthError(error, s)) throw error;
1424
+ const previous = ctx.inlineSlow;
1425
+ ctx.inlineSlow = true;
1426
+ try {
1427
+ return parseInlineArraySlow(s, ctx, lineNum, col);
1428
+ } finally {
1429
+ ctx.inlineSlow = previous;
1119
1430
  }
1120
- if (inDouble) {
1121
- if (ch === "\\") {
1122
- escape = true;
1123
- } else if (ch === '"') {
1124
- inDouble = false;
1125
- }
1126
- continue;
1127
- }
1128
- if (ch === "'") {
1129
- inSingle = true;
1130
- continue;
1131
- }
1132
- if (ch === '"') {
1133
- inDouble = true;
1134
- continue;
1431
+ }
1432
+ }
1433
+
1434
+ /**
1435
+ * Parse an inline object with the one-pass reader, falling back as
1436
+ * parseInlineArrayWithFallback does.
1437
+ * @param {string} s
1438
+ * @param {ParseContext} ctx
1439
+ * @param {number} lineNum
1440
+ * @param {number} col
1441
+ * @returns {Record<string, unknown>|null}
1442
+ */
1443
+ function parseInlineObjectWithFallback(s, ctx, lineNum, col) {
1444
+ if (ctx.inlineSlow) return parseInlineObjectSlow(s, ctx, lineNum, col);
1445
+ try {
1446
+ return parseInlineObject(s, ctx, lineNum, col);
1447
+ } catch (error) {
1448
+ if (isHugeDepthError(error, s)) throw error;
1449
+ const previous = ctx.inlineSlow;
1450
+ ctx.inlineSlow = true;
1451
+ try {
1452
+ return parseInlineObjectSlow(s, ctx, lineNum, col);
1453
+ } finally {
1454
+ ctx.inlineSlow = previous;
1135
1455
  }
1136
- if (ch === "[") {
1137
- depth++;
1138
- if (i + 1 < s.length && s[i + 1] === " ") {
1456
+ }
1457
+ }
1458
+
1459
+ function parseScalarAtom(s, ctx = {}, lineNum = 0, col = 0) {
1460
+ if (s === "null") return null;
1461
+ if (s === "undefined") return undefined;
1462
+ if (s === "true") return true;
1463
+ if (s === "false") return false;
1464
+ if (s === "nan") return NaN;
1465
+ if (s === "infinity") return Infinity;
1466
+ if (s === "-infinity") return -Infinity;
1467
+ const num = parseNumber(s, ctx, lineNum, col);
1468
+ if (num !== undefined) return num;
1469
+ if (s.startsWith('"')) {
1470
+ if (s.length < 2 || !s.endsWith('"')) {
1471
+ // Closed early, with more after it, or never closed
1472
+ let k = 1;
1473
+ while (k < s.length && s[k] !== '"') k += s[k] === "\\" ? 2 : 1;
1474
+ if (k < s.length) {
1139
1475
  throw new Error(
1140
- 'Unexpected space after "["' + locSuffix(ctx, lineNum, col + i + 1),
1476
+ `Unexpected character "${s[0]}"` + locSuffix(ctx, lineNum, col),
1141
1477
  );
1142
1478
  }
1143
- continue;
1144
1479
  }
1145
- if (ch === "]") {
1146
- if (i > 0 && s[i - 1] === " ") {
1147
- throw new Error(
1148
- 'Unexpected space before "]"' + locSuffix(ctx, lineNum, col + i - 1),
1149
- );
1150
- }
1151
- if (depth > 0) depth--;
1152
- continue;
1480
+ return parseQuotedString(s, ctx, lineNum, col);
1481
+ }
1482
+ if (s.startsWith("'")) return parseSingleQuotedString(s, ctx, lineNum, col);
1483
+ if (s.startsWith("[")) {
1484
+ // Inline arrays must close on the same line.
1485
+ if (!s.endsWith("]")) {
1486
+ throw new Error(
1487
+ "Unexpected newline in inline array" + locSuffix(ctx, lineNum, col),
1488
+ );
1153
1489
  }
1154
- if (ch === ",") {
1155
- if (i > 0 && s[i - 1] === " ") {
1156
- throw new Error(
1157
- 'Unexpected space before ","' + locSuffix(ctx, lineNum, col + i - 1),
1158
- );
1159
- }
1160
- if (i + 1 < s.length && s[i + 1] !== " " && s[i + 1] !== "]") {
1161
- let lookaheadDepth = depth;
1162
- let inS = false;
1163
- let inD = false;
1164
- let esc = false;
1165
- let nextIsClosingWithSpace = false;
1166
- for (let j = i + 1; j < s.length; j++) {
1167
- const cj = s[j];
1168
- if (esc) {
1169
- esc = false;
1170
- continue;
1171
- }
1172
- if (inS) {
1173
- if (cj === "\\") esc = true;
1174
- else if (cj === "'") inS = false;
1175
- continue;
1176
- }
1177
- if (inD) {
1178
- if (cj === "\\") esc = true;
1179
- else if (cj === '"') inD = false;
1180
- continue;
1181
- }
1182
- if (cj === "'") {
1183
- inS = true;
1184
- continue;
1185
- }
1186
- if (cj === '"') {
1187
- inD = true;
1188
- continue;
1189
- }
1190
- if (cj === "[") {
1191
- lookaheadDepth++;
1192
- continue;
1193
- }
1194
- if (cj === "]") {
1195
- if (lookaheadDepth === depth) {
1196
- nextIsClosingWithSpace = j > 0 && s[j - 1] === " ";
1197
- break;
1198
- }
1199
- if (lookaheadDepth > 0) lookaheadDepth--;
1200
- continue;
1201
- }
1202
- if (cj === "," && lookaheadDepth === depth) {
1203
- break;
1204
- }
1205
- }
1206
- if (!nextIsClosingWithSpace) {
1207
- throw new Error(
1208
- 'Expected space after ","' + locSuffix(ctx, lineNum, col + i),
1209
- );
1210
- }
1211
- }
1212
- if (i + 2 < s.length && s[i + 1] === " " && s[i + 2] === " ") {
1213
- throw new Error(
1214
- 'Unexpected space after ","' + locSuffix(ctx, lineNum, col + i + 2),
1215
- );
1216
- }
1490
+ return parseInlineArrayWithFallback(s, ctx, lineNum, col);
1491
+ }
1492
+ if (s.startsWith("{")) {
1493
+ // Inline objects must close on the same line.
1494
+ if (!s.includes("}")) {
1495
+ throw new Error(
1496
+ "Unexpected newline in inline object" + locSuffix(ctx, lineNum, col),
1497
+ );
1498
+ }
1499
+ return parseInlineObjectWithFallback(s, ctx, lineNum, col);
1500
+ }
1501
+ if (isReferenceStart(s)) {
1502
+ const [uri, n] = parseReference(s, ctx, lineNum, col);
1503
+ if (n !== s.length) {
1504
+ throw new Error(
1505
+ `Unexpected character "${s[n]}"` + locSuffix(ctx, lineNum, col + n),
1506
+ );
1217
1507
  }
1508
+ return decodeReferenceText(uri, ctx, lineNum, col);
1218
1509
  }
1510
+ if (s.startsWith("<")) return parseAngleBytes(s, ctx, lineNum, col);
1511
+ // The keyword with more glued to it, as `undefinedx`: the error is at
1512
+ // the first character past the keyword, as the other ports report it.
1513
+ if (s.startsWith("undefined") && s.length > "undefined".length) {
1514
+ const n = "undefined".length;
1515
+ throw new Error(
1516
+ `Unexpected character "${s[n]}"` + locSuffix(ctx, lineNum, col + n),
1517
+ );
1518
+ }
1519
+ // Bare words are not valid - strings must be quoted
1520
+ const firstChar = s.charAt(0) || "?";
1521
+ throw new Error(
1522
+ `Unexpected character "${firstChar}"` + locSuffix(ctx, lineNum, col),
1523
+ );
1219
1524
  }
1525
+
1526
+ /**
1527
+ * @param {string} s
1528
+ * @returns {number|bigint|undefined}
1529
+ */
1220
1530
  /**
1221
1531
  * @param {string} s
1222
1532
  * @param {ParseContext} ctx
1223
1533
  * @param {number} lineNum
1224
1534
  * @param {number} col
1225
- * @returns {Uint8Array}
1535
+ * @returns {number|bigint|undefined}
1226
1536
  */
1227
- function parseAngleBytes(s, ctx = {}, lineNum = 0, col = 0) {
1228
- if (!s.endsWith(">")) {
1229
- throw new Error("Unmatched angle bracket" + locSuffix(ctx, lineNum, col));
1230
- }
1231
- if (s === "<>") return new Uint8Array(0);
1232
- if (s.length > 2 && s[1] === " ") {
1233
- throw new Error(
1234
- 'Unexpected space after "<"' + locSuffix(ctx, lineNum, col + 1),
1235
- );
1236
- }
1237
- if (s.length > 2 && s[s.length - 2] === " ") {
1238
- throw new Error(
1239
- 'Unexpected space before ">"' +
1240
- locSuffix(ctx, lineNum, col + s.length - 2),
1241
- );
1537
+ function parseNumber(s, ctx = {}, lineNum = 0, col = 0) {
1538
+ // Check for uppercase E in exponent (must be lowercase)
1539
+ // Only check if this looks like a number (starts with digit, minus, or dot)
1540
+ // Reject a non-number on its first character without copying the string.
1541
+ let firstIndex = 0;
1542
+ while (s.charCodeAt(firstIndex) === 0x20) firstIndex++;
1543
+ const firstCode = s.charCodeAt(firstIndex);
1544
+ if (!(
1545
+ (firstCode >= 0x30 && firstCode <= 0x39) ||
1546
+ firstCode === 0x2d ||
1547
+ firstCode === 0x2e
1548
+ )) {
1549
+ return undefined;
1242
1550
  }
1243
- const inner = s.slice(1, -1);
1244
- // Check for uppercase hex digits
1245
- for (let i = 0; i < inner.length; i++) {
1246
- const c = inner[i];
1247
- if (c >= "A" && c <= "F") {
1551
+ const firstNonSpace = s[firstIndex];
1552
+ if (
1553
+ (firstNonSpace >= "0" && firstNonSpace <= "9") ||
1554
+ firstNonSpace === "-" ||
1555
+ firstNonSpace === "."
1556
+ ) {
1557
+ const eIdx = s.indexOf("E");
1558
+ if (eIdx >= 0) {
1248
1559
  throw new Error(
1249
- "Uppercase hex digit (use lowercase)" +
1250
- locSuffix(ctx, lineNum, col + 1 + i),
1560
+ "Uppercase exponent (use lowercase 'e')" +
1561
+ locSuffix(ctx, lineNum, col + eIdx),
1251
1562
  );
1252
1563
  }
1253
1564
  }
1254
- const hex = inner.replace(/\s/g, "");
1255
- if (hex.length % 2 !== 0)
1256
- throw new Error(
1257
- "Odd number of hex digits in byte literal" + locSuffix(ctx, lineNum, col),
1258
- );
1259
- if (!/^[0-9a-f]*$/.test(hex))
1260
- throw new Error("Invalid hex digit" + locSuffix(ctx, lineNum, col));
1261
- return Uint8Array.fromHex
1262
- ? Uint8Array.fromHex(hex)
1263
- : hexToUint8Array(hex, ctx, lineNum, col);
1264
- }
1265
1565
 
1266
- function hexToUint8Array(hex, ctx, lineNum, col) {
1267
- const bytes = new Uint8Array(hex.length / 2);
1268
- for (let j = 0; j < bytes.length; j++) {
1269
- const pair = hex.slice(j * 2, j * 2 + 2);
1270
- const val = parseInt(pair, 16);
1271
- if (isNaN(val)) {
1272
- throw new Error("Invalid hex digit" + locSuffix(ctx, lineNum, col));
1566
+ let hasDigit = false;
1567
+ let hasExponent = false;
1568
+ for (let i = 0; i < s.length; i++) {
1569
+ const c = s[i];
1570
+ if (c === " ") continue;
1571
+ if (c >= "0" && c <= "9") {
1572
+ hasDigit = true;
1573
+ continue;
1574
+ }
1575
+ if (c === ".") continue;
1576
+ if (c === "-" && i === 0) continue;
1577
+ // Allow 'e' for exponent notation (E already rejected above)
1578
+ if (c === "e" && hasDigit && !hasExponent) {
1579
+ hasExponent = true;
1580
+ continue;
1273
1581
  }
1274
- bytes[j] = val;
1582
+ // Allow +/- after exponent
1583
+ if ((c === "+" || c === "-") && hasExponent) {
1584
+ const prev = i > 0 ? s[i - 1] : "";
1585
+ if (prev === "e") continue;
1586
+ }
1587
+ // Not a numeric candidate.
1588
+ return undefined;
1589
+ }
1590
+ if (!hasDigit) return undefined;
1591
+ for (let i = 0; i < s.length; i++) {
1592
+ if (s[i] !== " ") continue;
1593
+ const prev = i > 0 ? s[i - 1] : "";
1594
+ const next = i + 1 < s.length ? s[i + 1] : "";
1595
+ const isDigitPrev = prev >= "0" && prev <= "9";
1596
+ const isDigitNext = next >= "0" && next <= "9";
1597
+ if (!(isDigitPrev && isDigitNext)) {
1598
+ throw new Error(
1599
+ "Unexpected space in number" + locSuffix(ctx, lineNum, col + i),
1600
+ );
1601
+ }
1602
+ }
1603
+ const compact = s.indexOf(" ") < 0 ? s : s.replace(/ /g, "");
1604
+ if (/^-?\d+$/.test(compact)) return BigInt(compact);
1605
+ // Float patterns: with decimal point, or with exponent, or both
1606
+ if (
1607
+ /^-?\d*\.\d*([eE][+-]?\d+)?$/.test(compact) ||
1608
+ /^-?\d+[eE][+-]?\d+$/.test(compact)
1609
+ ) {
1610
+ const n = Number(compact);
1611
+ if (!isNaN(n)) return n;
1275
1612
  }
1276
- return bytes;
1613
+ return undefined;
1277
1614
  }
1278
1615
 
1279
1616
  /**
1280
- * @param {Token[]} tokens
1281
- * @param {number} i
1617
+ * @param {string} s
1618
+ * @param {ParseContext} ctx
1619
+ * @param {number} lineNum
1620
+ * @param {number} col
1621
+ * @returns {string}
1622
+ */
1623
+ function parseQuotedString(s, ctx = {}, lineNum = 0, col = 0) {
1624
+ if (s.startsWith('"')) return parseJsonQuotedString(s, ctx, lineNum, col);
1625
+ if (s.startsWith("'")) return parseSingleQuotedString(s, ctx, lineNum, col);
1626
+ return s;
1627
+ }
1628
+
1629
+ /**
1630
+ * The deepest inline arrays and objects may nest, one in another. Deeper
1631
+ * nesting is refused rather than overflowing the stack.
1632
+ */
1633
+ const MAX_INLINE_DEPTH = 256;
1634
+
1635
+ /**
1636
+ * Read one level of inline nesting with read(), refusing more than
1637
+ * MAX_INLINE_DEPTH levels.
1638
+ * @template T
1639
+ * @param {ParseContext & {depth?: number}} ctx
1640
+ * @param {number} lineNum
1641
+ * @param {number} col
1642
+ * @param {() => T} read
1643
+ * @returns {T}
1644
+ */
1645
+ function nested(ctx, lineNum, col, read) {
1646
+ const depth = (ctx.depth ?? 0) + 1;
1647
+ if (depth > MAX_INLINE_DEPTH) {
1648
+ throw new Error(
1649
+ `Inline nesting deeper than ${MAX_INLINE_DEPTH} levels` +
1650
+ locSuffix(ctx, lineNum, col),
1651
+ );
1652
+ }
1653
+ ctx.depth = depth;
1654
+ try {
1655
+ return read();
1656
+ } finally {
1657
+ ctx.depth = depth - 1;
1658
+ }
1659
+ }
1660
+
1661
+ /**
1662
+ * Read a single-quoted string, the whole of s. Its only escapes are \' and
1663
+ * \\; any other backslash is literal.
1664
+ * @param {string} s
1665
+ * @param {ParseContext} ctx
1666
+ * @param {number} lineNum
1667
+ * @param {number} col
1668
+ * @returns {string}
1669
+ */
1670
+ function parseSingleQuotedString(s, ctx = {}, lineNum = 0, col = 0) {
1671
+ const parts = [];
1672
+ let run = 1;
1673
+ for (let i = 1; i < s.length; i++) {
1674
+ const c = s[i];
1675
+ if (c === "\\" && (s[i + 1] === "'" || s[i + 1] === "\\")) {
1676
+ if (run < i) parts.push(s.slice(run, i));
1677
+ parts.push(s[i + 1]);
1678
+ run = i + 2;
1679
+ i++;
1680
+ } else if (c === "'") {
1681
+ if (i !== s.length - 1) {
1682
+ throw new Error(
1683
+ 'Unexpected character "\'"' + locSuffix(ctx, lineNum, col),
1684
+ );
1685
+ }
1686
+ parts.push(s.slice(run, i));
1687
+ if (parts.length === 1) return detachString(parts[0]);
1688
+ return parts.join("");
1689
+ }
1690
+ }
1691
+ throw new Error(
1692
+ "Unterminated string" + locSuffix(ctx, lineNum, col + s.length - 1),
1693
+ );
1694
+ }
1695
+
1696
+ /**
1697
+ * Read the escape beginning at s[index]. A quoted string escapes its quote;
1698
+ * a tag escapes its closing parenthesis. Both otherwise use the same JSON
1699
+ * escapes and YAY's braced Unicode escape.
1700
+ * @param {string} s
1701
+ * @param {number} index
1702
+ * @param {string} terminator
1703
+ * @param {ParseContext} ctx
1704
+ * @param {number} lineNum
1705
+ * @param {number} col
1706
+ * @returns {[string, number]}
1707
+ */
1708
+ function readEscape(s, index, terminator, ctx, lineNum, col) {
1709
+ const escape = s[index + 1];
1710
+ if (escape === terminator) return [terminator, index + 2];
1711
+ if (escape !== undefined && Object.hasOwn(SIMPLE_ESCAPES, escape)) {
1712
+ return [SIMPLE_ESCAPES[escape], index + 2];
1713
+ }
1714
+ if (escape !== "u" || s[index + 2] !== "{") {
1715
+ fail(ctx, "Bad escaped character", lineNum, col + index + 1);
1716
+ }
1717
+ const close = s.indexOf("}", index + 3);
1718
+ const hex = close < 0 ? "" : s.slice(index + 3, close);
1719
+ if (!UNICODE_ESCAPE.test(hex)) {
1720
+ fail(ctx, "Bad Unicode escape", lineNum, col + index + 2);
1721
+ }
1722
+ const code = parseInt(hex, 16);
1723
+ if (code >= 0xd800 && code <= 0xdfff) {
1724
+ fail(ctx, "Illegal surrogate", lineNum, col + index + 2);
1725
+ }
1726
+ if (code > 0x10ffff) {
1727
+ fail(ctx, "Unicode code point out of range", lineNum, col + index + 2);
1728
+ }
1729
+ return [String.fromCodePoint(code), close + 1];
1730
+ }
1731
+
1732
+ /**
1733
+ * Minimal JSON string parser for deterministic errors.
1734
+ * @param {string} s
1735
+ * @param {ParseContext} ctx
1736
+ * @param {number} lineNum
1737
+ * @param {number} col
1738
+ * @returns {string}
1739
+ */
1740
+ function parseJsonQuotedString(s, ctx = {}, lineNum = 0, col = 0) {
1741
+ if (s.length < 2 || s[0] !== '"') return s;
1742
+ if (s[s.length - 1] !== '"') {
1743
+ const index = Math.max(0, s.length - 1);
1744
+ throw new Error(
1745
+ "Unterminated string" + locSuffix(ctx, lineNum, col + index),
1746
+ );
1747
+ }
1748
+ // Collect runs of plain characters by slice and join them once, rather
1749
+ // than consing one character (or one slice) at a time, which leaves a rope
1750
+ // that retains many times the string's size.
1751
+ const parts = [];
1752
+ let run = 1;
1753
+ for (let i = 1; i < s.length - 1; i++) {
1754
+ const code = s.charCodeAt(i);
1755
+ if (code !== 0x5c) {
1756
+ // Unescaped control characters are illegal in JSON strings.
1757
+ if (code < 0x20) {
1758
+ throw new Error(
1759
+ "Bad character in string" + locSuffix(ctx, lineNum, col + i),
1760
+ );
1761
+ }
1762
+ continue;
1763
+ }
1764
+ if (run < i) parts.push(s.slice(run, i));
1765
+ const [value, next] = readEscape(s, i, '"', ctx, lineNum, col);
1766
+ parts.push(value);
1767
+ i = next - 1;
1768
+ run = i + 1;
1769
+ }
1770
+ if (run === 1) {
1771
+ return detachString(s.slice(1, -1));
1772
+ }
1773
+ parts.push(s.slice(run, s.length - 1));
1774
+ return parts.join("");
1775
+ }
1776
+
1777
+ /**
1778
+ * @param {string} s
1779
+ * @param {ParseContext} ctx
1780
+ * @param {number} lineNum
1781
+ * @param {number} col
1782
+ * @returns {unknown[]}
1783
+ */
1784
+ function parseInlineArray(s, ctx = {}, lineNum = 0, col = 0) {
1785
+ return parseInlineArrayBody(s, ctx, lineNum, col);
1786
+ }
1787
+
1788
+ function parseInlineArrayBody(s, ctx, lineNum, col) {
1789
+ if (!s.startsWith("[")) return [];
1790
+ if (!s.endsWith("]")) {
1791
+ throw new Error("Unterminated inline array" + locSuffix(ctx, lineNum, col));
1792
+ }
1793
+ if (s === "[]") return [];
1794
+ if (s[1] === " ") {
1795
+ throw new Error(
1796
+ 'Unexpected space after "["' + locSuffix(ctx, lineNum, col + 1),
1797
+ );
1798
+ }
1799
+ if (s[s.length - 2] === " ") {
1800
+ throw new Error(
1801
+ 'Unexpected space before "]"' +
1802
+ locSuffix(ctx, lineNum, col + s.length - 2),
1803
+ );
1804
+ }
1805
+ const [arr, next] = parseInlineArrayAt(s, 0, ctx, lineNum, col);
1806
+ if (next !== s.length) {
1807
+ throw new Error(
1808
+ `Unexpected character "${s[next]}"` + locSuffix(ctx, lineNum, col + next),
1809
+ );
1810
+ }
1811
+ return arr;
1812
+ }
1813
+
1814
+ /**
1815
+ * Parse an inline array beginning at s[open], in one pass. Returns the array
1816
+ * and the index after its closing bracket.
1817
+ * @param {string} s
1818
+ * @param {number} open
1819
+ * @param {ParseContext} ctx
1820
+ * @param {number} lineNum
1821
+ * @param {number} col
1822
+ * @returns {[unknown[], number]}
1823
+ */
1824
+ function parseInlineArrayAt(s, open, ctx, lineNum, col) {
1825
+ return nested(ctx, lineNum, col + open, () =>
1826
+ parseInlineArrayAtBody(s, open, ctx, lineNum, col),
1827
+ );
1828
+ }
1829
+
1830
+ function parseInlineArrayAtBody(s, open, ctx, lineNum, col) {
1831
+ const arr = [];
1832
+ let i = open + 1;
1833
+ if (s.charCodeAt(i) === 0x5d) return [arr, i + 1];
1834
+ if (s.charCodeAt(i) === 0x20) {
1835
+ fail(ctx, 'Unexpected space after "["', lineNum, col + i);
1836
+ }
1837
+ for (;;) {
1838
+ if (i >= s.length) {
1839
+ throw new Error(
1840
+ "Unexpected newline in inline array" +
1841
+ locSuffix(ctx, lineNum, col + open),
1842
+ );
1843
+ }
1844
+ const c = s.charCodeAt(i);
1845
+ if (c === 0x5d || c === 0x2c) {
1846
+ throw new Error(
1847
+ "Missing array element" + locSuffix(ctx, lineNum, col + i),
1848
+ );
1849
+ }
1850
+ const [value, next] = parseInlineValueAt(s, i, ctx, lineNum, col, 0x5d);
1851
+ arr.push(value);
1852
+ if (next >= s.length) {
1853
+ throw new Error(
1854
+ "Unexpected newline in inline array" +
1855
+ locSuffix(ctx, lineNum, col + open),
1856
+ );
1857
+ }
1858
+ const after = s.charCodeAt(next);
1859
+ if (after === 0x5d) {
1860
+ if (s.charCodeAt(next - 1) === 0x20) {
1861
+ fail(ctx, 'Unexpected space before "]"', lineNum, col + next - 1);
1862
+ }
1863
+ return [arr, next + 1];
1864
+ }
1865
+ if (after === 0x2c) {
1866
+ if (s.charCodeAt(next - 1) === 0x20) {
1867
+ fail(ctx, 'Unexpected space before ","', lineNum, col + next - 1);
1868
+ }
1869
+ if (next + 1 >= s.length || s.charCodeAt(next + 1) !== 0x20) {
1870
+ fail(ctx, 'Expected space after ","', lineNum, col + next);
1871
+ }
1872
+ if (s.charCodeAt(next + 2) === 0x20) {
1873
+ fail(ctx, 'Unexpected space after ","', lineNum, col + next + 2);
1874
+ }
1875
+ i = next + 2;
1876
+ continue;
1877
+ }
1878
+ if (after === 0x20) {
1879
+ if (s.charCodeAt(next + 1) === 0x5d) {
1880
+ fail(ctx, 'Unexpected space before "]"', lineNum, col + next);
1881
+ }
1882
+ if (s.charCodeAt(next + 1) === 0x2c) {
1883
+ fail(ctx, 'Unexpected space before ","', lineNum, col + next);
1884
+ }
1885
+ }
1886
+ throw new Error(
1887
+ `Unexpected character "${s[next]}"` + locSuffix(ctx, lineNum, col + next),
1888
+ );
1889
+ }
1890
+ }
1891
+
1892
+ /**
1893
+ * @param {string} s
1894
+ * @param {ParseContext} ctx
1895
+ * @param {number} lineNum
1896
+ * @param {number} col
1897
+ * @returns {Uint8Array}
1898
+ */
1899
+ function parseAngleBytes(s, ctx = {}, lineNum = 0, col = 0) {
1900
+ if (!s.endsWith(">")) {
1901
+ throw new Error("Unmatched angle bracket" + locSuffix(ctx, lineNum, col));
1902
+ }
1903
+ if (s === "<>") return applyBytesHook(new Uint8Array(0), ctx);
1904
+ if (s.length > 2 && s[1] === " ") {
1905
+ throw new Error(
1906
+ 'Unexpected space after "<"' + locSuffix(ctx, lineNum, col + 1),
1907
+ );
1908
+ }
1909
+ if (s.length > 2 && s[s.length - 2] === " ") {
1910
+ throw new Error(
1911
+ 'Unexpected space before ">"' +
1912
+ locSuffix(ctx, lineNum, col + s.length - 2),
1913
+ );
1914
+ }
1915
+ const inner = s.slice(1, -1);
1916
+ // Check for uppercase hex digits
1917
+ for (let i = 0; i < inner.length; i++) {
1918
+ const c = inner[i];
1919
+ if (c >= "A" && c <= "F") {
1920
+ throw new Error(
1921
+ "Uppercase hex digit (use lowercase)" +
1922
+ locSuffix(ctx, lineNum, col + 1 + i),
1923
+ );
1924
+ }
1925
+ }
1926
+ return hexToBytes(inner.replace(/\s/g, ""), ctx, lineNum, col);
1927
+ }
1928
+
1929
+ /**
1930
+ * Decode lowercase hex, inline or block, the spaces already removed.
1931
+ * Uppercase digits are refused where they are written, before this.
1932
+ * @param {string} hex
1933
+ * @param {ParseContext} ctx
1934
+ * @param {number} lineNum
1935
+ * @param {number} col
1936
+ * @returns {Uint8Array}
1937
+ */
1938
+ function hexToBytes(hex, ctx, lineNum, col) {
1939
+ if (hex.length % 2 !== 0)
1940
+ throw new Error(
1941
+ "Odd number of hex digits in byte literal" + locSuffix(ctx, lineNum, col),
1942
+ );
1943
+ if (!LOWER_HEX.test(hex))
1944
+ throw new Error("Invalid hex digit" + locSuffix(ctx, lineNum, col));
1945
+ const bytes = new Uint8Array(hex.length / 2);
1946
+ for (let j = 0, k = 0; j < bytes.length; j++, k += 2) {
1947
+ const a = hex.charCodeAt(k);
1948
+ const b = hex.charCodeAt(k + 1);
1949
+ bytes[j] =
1950
+ ((a <= 0x39 ? a - 0x30 : a - 0x57) << 4) |
1951
+ (b <= 0x39 ? b - 0x30 : b - 0x57);
1952
+ }
1953
+ return applyBytesHook(bytes, ctx);
1954
+ }
1955
+
1956
+ /**
1957
+ * Make a byte value from the parser's plain Uint8Array, by the caller's
1958
+ * choice. The default is the plain Uint8Array. "immutable" makes the
1959
+ * byteArray that the locked @endo/pass-style accepts; a function is the
1960
+ * caller's own hook.
1961
+ * @param {Uint8Array} bytes
1962
+ * @param {ParseContext} ctx
1963
+ * @returns {unknown}
1964
+ */
1965
+ function applyBytesHook(bytes, ctx = {}) {
1966
+ const option = ctx.bytes;
1967
+ if (option === undefined || option === "plain") return bytes;
1968
+ if (typeof option === "function") return option(bytes);
1969
+ if (option === "immutable") return immutableBytes(bytes);
1970
+ throw new TypeError('bytes must be "plain", "immutable", or a function');
1971
+ }
1972
+
1973
+ /**
1974
+ * Make a hardened immutable ArrayBuffer holding a copy of bytes. Detect the
1975
+ * Immutable ArrayBuffer proposal at call time, so a shim loaded after this
1976
+ * module, as @endo/init loads @endo/immutable-arraybuffer, serves. Fail
1977
+ * loudly where the environment has neither native support nor the shim.
1978
+ *
1979
+ * The locked @endo/pass-style (1.8.2) accepts a hardened immutable
1980
+ * ArrayBuffer as its byteArray, not a Uint8Array view over one, so this is
1981
+ * the passable form while that remains the locked version.
1982
+ * @param {Uint8Array} bytes
1983
+ * @returns {ArrayBuffer}
1984
+ */
1985
+ function immutableBytes(bytes) {
1986
+ const copy = bytes.slice().buffer;
1987
+ if (typeof copy.transferToImmutable === "function") {
1988
+ return Object.freeze(copy.transferToImmutable());
1989
+ }
1990
+ if (typeof copy.sliceToImmutable === "function") {
1991
+ return Object.freeze(copy.sliceToImmutable());
1992
+ }
1993
+ throw new Error(
1994
+ "Immutable bytes are unavailable: load @endo/immutable-arraybuffer " +
1995
+ "(or @endo/init) or use the plain bytes",
1996
+ );
1997
+ }
1998
+
1999
+ /**
2000
+ * Read one line of block bytes: hex, then an optional comment after two
2001
+ * spaces, or a comment alone. Returns the hex without its spaces.
2002
+ * @param {string} text
2003
+ * @param {ParseContext} ctx
2004
+ * @param {number} lineNum
2005
+ * @param {number} col
2006
+ * @returns {string}
2007
+ */
2008
+ function blockHexLine(text, ctx, lineNum, col) {
2009
+ if (text.startsWith("#")) return "";
2010
+ let body = text;
2011
+ const hash = text.indexOf("#");
2012
+ if (hash >= 0) {
2013
+ checkCommentSpacing(text, hash, ctx, lineNum, col);
2014
+ if (text[hash - 1] === " ") body = text.slice(0, hash).trimEnd();
2015
+ }
2016
+ for (let i = 0; i < body.length; i++) {
2017
+ if (body[i] >= "A" && body[i] <= "F") {
2018
+ throw new Error(
2019
+ "Uppercase hex digit (use lowercase)" +
2020
+ locSuffix(ctx, lineNum, col + i),
2021
+ );
2022
+ }
2023
+ }
2024
+ return body.replace(/ /g, "");
2025
+ }
2026
+
2027
+ /**
2028
+ * @param {Token[]} tokens
2029
+ * @param {number} i
1282
2030
  * @param {ParseContext} ctx
1283
2031
  * @returns {[unknown[], number]}
1284
2032
  */
@@ -1292,822 +2040,1786 @@ function parseListArray(tokens, i, ctx = {}, minIndent = -1) {
1292
2040
  const listIndent = tokens[i].indent ?? 0;
1293
2041
  // Stop if we encounter a list item at a lower indent than expected
1294
2042
  if (minIndent >= 0 && listIndent < minIndent) break;
1295
- i++;
1296
- while (i < tokens.length && tokens[i].type === "break") i++;
2043
+ i = skipBlank(tokens, i + 1);
1297
2044
  if (i >= tokens.length) break;
1298
- const next = tokens[i];
1299
- if (
1300
- next.type === "text" &&
1301
- next.text === "" &&
1302
- i + 1 < tokens.length &&
1303
- tokens[i + 1].type === "start" &&
1304
- tokens[i + 1].text === "-"
1305
- ) {
1306
- const [value, j] = parseListArray(tokens, i + 1, ctx);
1307
- arr.push(value);
1308
- i = j;
1309
- } else if (next.type === "start" && next.text === "-") {
1310
- const [value, j] = parseListArray(tokens, i, ctx);
1311
- arr.push(value);
1312
- i = j;
1313
- } else if (
1314
- next.type === "text" &&
1315
- (next.indent ?? 0) >= listIndent &&
1316
- isInlineBullet(next.text)
1317
- ) {
1318
- // Inline bullet list inside a multiline list item.
1319
- const group = [];
1320
- let j = i;
1321
- for (;;) {
2045
+ const [value, j, some] = parseListItem(tokens, i, listIndent, ctx);
2046
+ if (some !== false) arr.push(value);
2047
+ i = j;
2048
+ // Skip stops and breaks between items
2049
+ i = skipBlank(tokens, i, true);
2050
+ }
2051
+ return [arr, i];
2052
+ }
2053
+
2054
+ /**
2055
+ * Parse one list item's content, at tokens[i], after its "-".
2056
+ * @param {Token[]} tokens
2057
+ * @param {number} i
2058
+ * @param {number} listIndent
2059
+ * @param {ParseContext} ctx
2060
+ * @returns {[unknown, number, boolean?]} the value, the next index, and
2061
+ * false when the item holds no value
2062
+ */
2063
+ function parseListItem(tokens, i, listIndent, ctx) {
2064
+ const next = tokens[i];
2065
+ // A tagged block: the item's content follows the tags
2066
+ if (next.type === "text" && next.text.startsWith("(")) {
2067
+ const lineNum = next.lineNum ?? 0;
2068
+ const col = next.col ?? 0;
2069
+ const [tags, rest] = parsePrefix(next.text, ctx, lineNum, col);
2070
+ if (rest === "") {
2071
+ const j = skipBlank(tokens, i + 1);
2072
+ if (
2073
+ j >= tokens.length ||
2074
+ tokens[j].type === "stop" ||
2075
+ (tokens[j].indent ?? 0) <= listIndent
2076
+ ) {
2077
+ return parseValue(tokens, i, ctx);
2078
+ }
2079
+ if (!listBlockFollows(tokens, j, listIndent)) {
2080
+ throw prefixOverInlineValue(ctx, lineNum, col);
2081
+ }
2082
+ const [value, k] = parseListItem(tokens, j, listIndent, ctx);
2083
+ return [wrapPrefix(value, tags), k];
2084
+ }
2085
+ if (!prefixTakes(rest)) throw prefixOverInlineValue(ctx, lineNum, col);
2086
+ // Swap the one token in place and restore it, rather than copying the
2087
+ // whole token array for each tagged item (which is quadratic in the
2088
+ // number of items).
2089
+ const token = tokens[i];
2090
+ tokens[i] = {
2091
+ ...next,
2092
+ text: rest,
2093
+ col: col + next.text.length - rest.length,
2094
+ };
2095
+ let value, k;
2096
+ try {
2097
+ [value, k] = parseListItem(tokens, i, listIndent, ctx);
2098
+ } finally {
2099
+ tokens[i] = token;
2100
+ }
2101
+ return [wrapPrefix(value, tags), k];
2102
+ }
2103
+ if (
2104
+ next.type === "text" &&
2105
+ next.text === "" &&
2106
+ i + 1 < tokens.length &&
2107
+ tokens[i + 1].type === "start" &&
2108
+ tokens[i + 1].text === "-"
2109
+ ) {
2110
+ return parseListArray(tokens, i + 1, ctx);
2111
+ } else if (next.type === "start" && next.text === "-") {
2112
+ return parseListArray(tokens, i, ctx);
2113
+ } else if (
2114
+ next.type === "text" &&
2115
+ (next.indent ?? 0) >= listIndent &&
2116
+ isInlineBullet(next.text)
2117
+ ) {
2118
+ // Inline bullet list inside a multiline list item.
2119
+ const group = [];
2120
+ let j = i;
2121
+ for (;;) {
2122
+ if (
2123
+ j < tokens.length &&
2124
+ tokens[j].type === "text" &&
2125
+ (tokens[j].indent ?? 0) >= listIndent &&
2126
+ isInlineBullet(tokens[j].text)
2127
+ ) {
2128
+ const valStr = parseInlineBulletValue(
2129
+ tokens[j].text,
2130
+ ctx,
2131
+ tokens[j].lineNum ?? 0,
2132
+ tokens[j].col ?? 0,
2133
+ );
2134
+ group.push(
2135
+ parseNestedInlineBullet(
2136
+ valStr,
2137
+ ctx,
2138
+ tokens[j].lineNum ?? 0,
2139
+ (tokens[j].col ?? 0) + 2,
2140
+ ),
2141
+ );
2142
+ j++;
2143
+ } else if (
2144
+ j < tokens.length &&
2145
+ tokens[j].type === "start" &&
2146
+ tokens[j].text === "-" &&
2147
+ (tokens[j].indent ?? 0) > listIndent &&
2148
+ j + 1 < tokens.length &&
2149
+ tokens[j + 1].type === "text" &&
2150
+ isInlineBullet(tokens[j + 1].text)
2151
+ ) {
2152
+ const valStr = parseInlineBulletValue(
2153
+ tokens[j + 1].text,
2154
+ ctx,
2155
+ tokens[j + 1].lineNum ?? 0,
2156
+ tokens[j + 1].col ?? 0,
2157
+ );
2158
+ group.push(
2159
+ parseNestedInlineBullet(
2160
+ valStr,
2161
+ ctx,
2162
+ tokens[j + 1].lineNum ?? 0,
2163
+ (tokens[j + 1].col ?? 0) + 2,
2164
+ ),
2165
+ );
2166
+ j += 2;
2167
+ } else {
2168
+ break;
2169
+ }
2170
+ }
2171
+ // If next token is start(-) at deeper indent, same list continues with nested bullets (e.g. "- - a" then " - b").
2172
+ while (
2173
+ j < tokens.length &&
2174
+ tokens[j].type === "start" &&
2175
+ tokens[j].text === "-" &&
2176
+ (tokens[j].indent ?? 0) > listIndent
2177
+ ) {
2178
+ j++;
2179
+ j = skipBlank(tokens, j);
2180
+ if (j >= tokens.length) break;
2181
+ const [subVal, nextJ] = parseValue(tokens, j, ctx);
2182
+ group.push(subVal);
2183
+ j = nextJ;
2184
+ while (j < tokens.length && tokens[j].type === "stop") j++;
2185
+ }
2186
+ return [group, j];
2187
+ } else if (
2188
+ next.type === "text" &&
2189
+ !next.text.startsWith("[") &&
2190
+ !next.text.startsWith("{") &&
2191
+ findKeyColonOutsideQuotes(next.text) >= 0
2192
+ ) {
2193
+ const nextIndent = next.indent ?? 0;
2194
+ const inlineIndent = nextIndent === listIndent ? nextIndent : undefined;
2195
+ const baseIndent = inlineIndent !== undefined ? nextIndent + 2 : nextIndent;
2196
+ const [obj, nextIndex] = parseObjectBlock(
2197
+ tokens,
2198
+ i,
2199
+ baseIndent,
2200
+ ctx,
2201
+ inlineIndent,
2202
+ );
2203
+ return [obj, nextIndex];
2204
+ } else if (next.type === "text" || next.type === "start") {
2205
+ const [value, j] = parseValue(tokens, i, ctx);
2206
+ const k = skipBlank(tokens, j);
2207
+ const afterBreak = k < tokens.length ? tokens[k] : null;
2208
+ if (
2209
+ afterBreak &&
2210
+ afterBreak.type === "start" &&
2211
+ afterBreak.text === "-" &&
2212
+ (afterBreak.indent ?? 0) > listIndent
2213
+ ) {
2214
+ const group = [value];
2215
+ i = k;
2216
+ while (
2217
+ i < tokens.length &&
2218
+ tokens[i].type === "start" &&
2219
+ tokens[i].text === "-" &&
2220
+ (tokens[i].indent ?? 0) > listIndent
2221
+ ) {
2222
+ i = skipBlank(tokens, i + 1);
2223
+ if (i >= tokens.length) break;
2224
+ const [subVal, nextI] = parseValue(tokens, i, ctx);
2225
+ group.push(subVal);
2226
+ i = nextI;
2227
+ while (i < tokens.length && tokens[i].type === "stop") i++;
2228
+ }
2229
+ return [group, i];
2230
+ }
2231
+ return [value, j];
2232
+ }
2233
+ return [undefined, i + 1, false];
2234
+ }
2235
+
2236
+ /**
2237
+ * Parse a block string with an optional base indent constraint.
2238
+ * @param {Token[]} tokens
2239
+ * @param {number} i
2240
+ * @param {string|undefined} firstLine
2241
+ * @param {boolean} inPropertyContext
2242
+ * @param {number} baseIndent - If >= 0, stop collecting when indent <= baseIndent
2243
+ * @param {ParseContext} ctx
2244
+ * @returns {[string, number]}
2245
+ */
2246
+ function collectBlockString(
2247
+ tokens,
2248
+ i,
2249
+ firstLine,
2250
+ inPropertyContext,
2251
+ baseIndent,
2252
+ ctx,
2253
+ ) {
2254
+ const startToken = tokens[i];
2255
+ const lines = [];
2256
+ if (firstLine !== undefined) {
2257
+ lines.push(firstLine);
2258
+ i++;
2259
+ } else {
2260
+ i++;
2261
+ }
2262
+ // Collect continuation lines with their indent so we can strip minimum indent (for property block strings).
2263
+ const continuationLines = [];
2264
+ while (
2265
+ i < tokens.length &&
2266
+ (tokens[i].type === "text" || tokens[i].type === "break")
2267
+ ) {
2268
+ if (tokens[i].type === "break") {
2269
+ continuationLines.push({ indent: undefined, text: "" });
2270
+ i++;
2271
+ } else {
2272
+ // If we have a base indent constraint, stop when we see a line at or below that indent
2273
+ if (baseIndent >= 0 && (tokens[i].indent ?? 0) <= baseIndent) {
2274
+ break;
2275
+ }
2276
+ continuationLines.push({
2277
+ indent: tokens[i].indent ?? 0,
2278
+ text: tokens[i].text,
2279
+ });
2280
+ i++;
2281
+ }
2282
+ }
2283
+ const minIndent = continuationLines
2284
+ .filter((x) => x.indent !== undefined)
2285
+ .reduce((min, x) => (x.indent < min ? x.indent : min), Infinity);
2286
+ const effectiveMin = minIndent === Infinity ? 0 : minIndent;
2287
+ for (const { indent, text } of continuationLines) {
2288
+ if (indent === undefined) {
2289
+ lines.push("");
2290
+ } else {
2291
+ // Token text is already after indent; add back (indent - minIndent) spaces for relative indent.
2292
+ const extraSpaces = indent - effectiveMin;
2293
+ lines.push((extraSpaces > 0 ? " ".repeat(extraSpaces) : "") + text);
2294
+ }
2295
+ }
2296
+ // Trim leading and trailing empty lines; then one leading newline and one trailing newline.
2297
+ let start = 0;
2298
+ while (start < lines.length && lines[start] === "") start++;
2299
+ let end = lines.length;
2300
+ while (end > start && lines[end - 1] === "") end--;
2301
+ const trimmed = lines.slice(start, end);
2302
+ // When block starts with quote on its own line (firstLine === ''), output has a leading newline.
2303
+ // But NOT in property context.
2304
+ const leadingNewline =
2305
+ firstLine === "" && trimmed.length > 0 && !inPropertyContext;
2306
+ const body =
2307
+ (leadingNewline ? "\n" : "") +
2308
+ trimmed.join("\n") +
2309
+ (trimmed.length > 0 ? "\n" : "");
2310
+ // Empty block strings are not allowed - use "" for empty string
2311
+ if (body === "") {
2312
+ fail(
2313
+ ctx,
2314
+ 'Empty block string not allowed (use "" or "\\n" explicitly)',
2315
+ startToken.lineNum ?? 0,
2316
+ startToken.col ?? 0,
2317
+ false,
2318
+ );
2319
+ }
2320
+ return [body, i];
2321
+ }
2322
+
2323
+ /**
2324
+ * Parse concatenated quoted strings (multiple quoted strings on consecutive lines).
2325
+ * Returns null if there's only one string (single string on new line is invalid).
2326
+ * @param {Token[]} tokens
2327
+ * @param {number} i
2328
+ * @param {number} baseIndent
2329
+ * @param {ParseContext} ctx
2330
+ * @returns {[string, number] | null}
2331
+ */
2332
+ function parseConcatenatedStrings(tokens, i, baseIndent, ctx = {}) {
2333
+ const parts = [];
2334
+ const startI = i;
2335
+
2336
+ while (i < tokens.length) {
2337
+ const t = tokens[i];
2338
+
2339
+ if (t.type === "break" || t.type === "stop") {
2340
+ i++;
2341
+ continue;
2342
+ }
2343
+
2344
+ if (t.type !== "text" || (t.indent ?? 0) < baseIndent) {
2345
+ break;
2346
+ }
2347
+
2348
+ const trimmed = t.text.trim();
2349
+
2350
+ // Check if this line is a quoted string
2351
+ const isDoubleQuoted =
2352
+ trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2;
2353
+ const isSingleQuoted =
2354
+ trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2;
2355
+
2356
+ if (!isDoubleQuoted && !isSingleQuoted) {
2357
+ break;
2358
+ }
2359
+
2360
+ // Parse the quoted string
2361
+ const parsed = parseQuotedString(trimmed, ctx, t.lineNum ?? 0, t.col ?? 0);
2362
+ parts.push(parsed);
2363
+ i++;
2364
+ }
2365
+
2366
+ // Require at least 2 strings for concatenation
2367
+ // A single string on a new line is invalid (use inline syntax instead)
2368
+ if (parts.length < 2) {
2369
+ return null;
2370
+ }
2371
+
2372
+ return [parts.join(""), i];
2373
+ }
2374
+
2375
+ /**
2376
+ * @param {string} text
2377
+ * @returns {boolean}
2378
+ */
2379
+ function isInlineBullet(text) {
2380
+ let i = 0;
2381
+ while (i < text.length && text[i] === " ") i++;
2382
+ return (
2383
+ i < text.length &&
2384
+ text[i] === "-" &&
2385
+ i + 1 < text.length &&
2386
+ text[i + 1] === " "
2387
+ );
2388
+ }
2389
+
2390
+ /**
2391
+ * @param {string} text
2392
+ * @param {ParseContext} ctx
2393
+ * @param {number} lineNum
2394
+ * @param {number} col
2395
+ * @returns {string}
2396
+ */
2397
+ function parseInlineBulletValue(text, ctx = {}, lineNum = 0, col = 0) {
2398
+ let i = 0;
2399
+ while (i < text.length && text[i] === " ") i++;
2400
+ if (i >= text.length || text[i] !== "-") return "";
2401
+ const dashIndex = i;
2402
+ const afterDash = dashIndex + 1;
2403
+ if (afterDash >= text.length || text[afterDash] !== " ") return "";
2404
+ if (afterDash + 1 < text.length && text[afterDash + 1] === " ") {
2405
+ throw new Error(
2406
+ 'Unexpected space after "-"' +
2407
+ locSuffix(ctx, lineNum, col + afterDash + 1),
2408
+ );
2409
+ }
2410
+ return text.slice(afterDash + 1);
2411
+ }
2412
+
2413
+ /**
2414
+ * Recursively parse an inline bullet value, handling nested "- " prefixes.
2415
+ * Returns the parsed value (could be a nested array or a scalar).
2416
+ */
2417
+ function parseNestedInlineBullet(text, ctx = {}, lineNum = 0, col = 0) {
2418
+ // Check if the text itself is another inline bullet
2419
+ if (isInlineBullet(text)) {
2420
+ const innerText = parseInlineBulletValue(text, ctx, lineNum, col);
2421
+ const innerValue = parseNestedInlineBullet(
2422
+ innerText,
2423
+ ctx,
2424
+ lineNum,
2425
+ col + 2,
2426
+ );
2427
+ return [innerValue];
2428
+ }
2429
+ // Otherwise, parse as a scalar
2430
+ return parseScalar(text, ctx, lineNum, col);
2431
+ }
2432
+
2433
+ // Note: parseMultilineBytes for '*' syntax was removed as dead code.
2434
+ // The scanner rejects '*' syntax, so this function was unreachable.
2435
+
2436
+ /**
2437
+ * @param {Token[]} tokens
2438
+ * @param {number} i
2439
+ * @param {ParseContext} ctx
2440
+ * @param {string} firstLineRaw
2441
+ * @param {number} baseIndent
2442
+ * @returns {[Uint8Array, number]}
2443
+ */
2444
+ function parseBlockBytes(
2445
+ tokens,
2446
+ i,
2447
+ ctx = {},
2448
+ firstLineRaw,
2449
+ baseIndent,
2450
+ firstCol = 0,
2451
+ ) {
2452
+ const startToken = tokens[i];
2453
+ const lineNum = startToken.lineNum ?? 0;
2454
+ const col = startToken.col ?? 0;
2455
+ let hex = "";
2456
+ if (firstLineRaw) {
2457
+ hex += blockHexLine(firstLineRaw, ctx, lineNum, firstCol);
2458
+ }
2459
+ i++;
2460
+ while (i < tokens.length) {
2461
+ const t = tokens[i];
2462
+ if (t.type === "break") {
2463
+ i++;
2464
+ continue;
2465
+ }
2466
+ if (t.type === "text" && (t.indent ?? 0) > baseIndent) {
2467
+ hex += blockHexLine(t.text, ctx, t.lineNum ?? 0, t.col ?? 0);
2468
+ i++;
2469
+ continue;
2470
+ }
2471
+ break;
2472
+ }
2473
+ return [hexToBytes(hex, ctx, lineNum, col), i];
2474
+ }
2475
+
2476
+ // Note: parseMultilineAngleBytes was removed as dead code.
2477
+ // The "< hex" syntax (without closing ">") is invalid - inline byte arrays must be closed on the same line.
2478
+
2479
+ /**
2480
+ * Read the value of one object property. The three object readers differ only
2481
+ * in how an empty value chooses the following block, captured by emptyMode.
2482
+ * @param {Token[]} tokens
2483
+ * @param {number} i
2484
+ * @param {{key: string, valuePart: string, valueCol: number}} keyValue
2485
+ * @param {ParseContext} ctx
2486
+ * @param {{baseIndent: number, blockIndent?: number, emptyMode: "root"|"named"|"block"}} options
2487
+ * @returns {[unknown, number]}
2488
+ */
2489
+ function parsePropertyValue(
2490
+ tokens,
2491
+ i,
2492
+ keyValue,
2493
+ ctx,
2494
+ { baseIndent, blockIndent = baseIndent, emptyMode },
2495
+ ) {
2496
+ const token = tokens[i];
2497
+ const lineNum = token.lineNum ?? 0;
2498
+ let valuePart = keyValue.valuePart;
2499
+ let tags = null;
2500
+ if (valuePart.startsWith("(")) {
2501
+ const symbolText = valuePart;
2502
+ try {
2503
+ [tags, valuePart] = parsePrefix(
2504
+ valuePart,
2505
+ ctx,
2506
+ lineNum,
2507
+ keyValue.valueCol,
2508
+ );
2509
+ } catch {
2510
+ return [
2511
+ parseScalar(symbolText, ctx, lineNum, keyValue.valueCol),
2512
+ i + 1,
2513
+ ];
2514
+ }
2515
+ if (valuePart === "" && !propertyBlockFollows(tokens, i, baseIndent)) {
2516
+ const following = tokens[skipBlank(tokens, i + 1, true)];
2517
+ if (
2518
+ following &&
2519
+ (following.indent ?? 0) > baseIndent &&
2520
+ following.type === "text"
2521
+ ) {
2522
+ throw prefixOverInlineValue(ctx, lineNum, keyValue.valueCol);
2523
+ }
2524
+ return [
2525
+ parseScalar(symbolText, ctx, lineNum, keyValue.valueCol),
2526
+ i + 1,
2527
+ ];
2528
+ }
2529
+ if (!prefixTakes(valuePart)) {
2530
+ throw prefixOverInlineValue(ctx, lineNum, keyValue.valueCol);
2531
+ }
2532
+ }
2533
+
2534
+ let value;
2535
+ let next;
2536
+ if (valuePart.startsWith(">")) {
2537
+ if (!isPropertyBlockLeaderOnly(valuePart, ">")) {
2538
+ fail(
2539
+ ctx,
2540
+ "Expected newline after block leader in property",
2541
+ lineNum,
2542
+ keyValue.valueCol,
2543
+ false,
2544
+ );
2545
+ }
2546
+ [value, next] = parseBlockBytes(tokens, i, ctx, "", baseIndent);
2547
+ } else if (valuePart === "{}") {
2548
+ value = {};
2549
+ next = i + 1;
2550
+ } else if (valuePart.startsWith("`")) {
2551
+ if (valuePart !== "`") {
2552
+ fail(
2553
+ ctx,
2554
+ "Expected newline after block leader in property",
2555
+ lineNum,
2556
+ keyValue.valueCol,
2557
+ false,
2558
+ );
2559
+ }
2560
+ [value, next] = collectBlockString(tokens, i, "", true, blockIndent, ctx);
2561
+ } else if (valuePart === "") {
2562
+ if (emptyMode === "root") {
2563
+ const [valueObject, after] = parseObjectOrNamedArray(
2564
+ tokens,
2565
+ i,
2566
+ keyValue.key,
2567
+ ctx,
2568
+ );
2569
+ value = valueObject[keyValue.key];
2570
+ next = after;
2571
+ } else {
2572
+ next = skipBlank(tokens, i + 1, emptyMode === "block");
2573
+ const following = tokens[next];
2574
+ if (emptyMode === "block") {
2575
+ if (
2576
+ !following ||
2577
+ (following.indent ?? 0) < baseIndent ||
2578
+ ((following.indent ?? 0) === baseIndent && following.type !== "start")
2579
+ ) {
2580
+ if (tags) {
2581
+ throw prefixWithoutBlock(ctx, lineNum, keyValue.valueCol);
2582
+ }
2583
+ fail(
2584
+ ctx,
2585
+ "Expected value after property",
2586
+ lineNum,
2587
+ (token.col ?? 0) + keyValue.key.length + 1,
2588
+ );
2589
+ }
2590
+ }
2591
+ if (following?.type === "start" && following.text === "-") {
2592
+ [value, next] = parseListArray(
2593
+ tokens,
2594
+ next,
2595
+ ctx,
2596
+ emptyMode === "block" ? baseIndent : -1,
2597
+ );
2598
+ } else {
2599
+ const parentIndent =
2600
+ emptyMode === "block" ? baseIndent : (token.indent ?? 0);
1322
2601
  if (
1323
- j < tokens.length &&
1324
- tokens[j].type === "text" &&
1325
- (tokens[j].indent ?? 0) >= listIndent &&
1326
- isInlineBullet(tokens[j].text)
2602
+ following?.type === "text" &&
2603
+ (following.indent ?? 0) > parentIndent
1327
2604
  ) {
1328
- const valStr = parseInlineBulletValue(
1329
- tokens[j].text,
2605
+ [value, next] = parseObjectBlock(
2606
+ tokens,
2607
+ next,
2608
+ following.indent ?? 0,
1330
2609
  ctx,
1331
- tokens[j].lineNum ?? 0,
1332
- tokens[j].col ?? 0,
1333
2610
  );
1334
- group.push(
1335
- parseNestedInlineBullet(
1336
- valStr,
1337
- ctx,
1338
- tokens[j].lineNum ?? 0,
1339
- (tokens[j].col ?? 0) + 2,
1340
- ),
1341
- );
1342
- j++;
1343
- } else if (
1344
- j < tokens.length &&
1345
- tokens[j].type === "start" &&
1346
- tokens[j].text === "-" &&
1347
- (tokens[j].indent ?? 0) > listIndent &&
1348
- j + 1 < tokens.length &&
1349
- tokens[j + 1].type === "text" &&
1350
- isInlineBullet(tokens[j + 1].text)
1351
- ) {
1352
- const valStr = parseInlineBulletValue(
1353
- tokens[j + 1].text,
2611
+ } else if (emptyMode === "named") {
2612
+ fail(
1354
2613
  ctx,
1355
- tokens[j + 1].lineNum ?? 0,
1356
- tokens[j + 1].col ?? 0,
1357
- );
1358
- group.push(
1359
- parseNestedInlineBullet(
1360
- valStr,
1361
- ctx,
1362
- tokens[j + 1].lineNum ?? 0,
1363
- (tokens[j + 1].col ?? 0) + 2,
1364
- ),
2614
+ "Expected value after property",
2615
+ lineNum,
2616
+ (token.col ?? 0) + keyValue.key.length + 1,
1365
2617
  );
1366
- j += 2;
1367
- } else {
1368
- break;
1369
2618
  }
1370
2619
  }
1371
- // If next token is start(-) at deeper indent, same list continues with nested bullets (e.g. "- - a" then " - b").
1372
- while (
1373
- j < tokens.length &&
1374
- tokens[j].type === "start" &&
1375
- tokens[j].text === "-" &&
1376
- (tokens[j].indent ?? 0) > listIndent
1377
- ) {
1378
- j++;
1379
- while (j < tokens.length && tokens[j].type === "break") j++;
1380
- if (j >= tokens.length) break;
1381
- const [subVal, nextJ] = parseValue(tokens, j, ctx);
1382
- group.push(subVal);
1383
- j = nextJ;
1384
- while (j < tokens.length && tokens[j].type === "stop") j++;
1385
- }
1386
- arr.push(group);
1387
- i = j;
1388
- } else if (
1389
- next.type === "text" &&
1390
- findKeyColonOutsideQuotes(next.text) >= 0
2620
+ }
2621
+ } else {
2622
+ value = parseScalar(valuePart, ctx, lineNum, keyValue.valueCol);
2623
+ next = i + 1;
2624
+ }
2625
+
2626
+ if (tags) {
2627
+ if (isMissingBlock(value)) {
2628
+ throw prefixWithoutBlock(ctx, lineNum, keyValue.valueCol);
2629
+ }
2630
+ value = wrapPrefix(value, tags);
2631
+ }
2632
+ return [value, next];
2633
+ }
2634
+
2635
+ /**
2636
+ * @param {Token[]} tokens
2637
+ * @param {number} i
2638
+ * @param {string} key
2639
+ * @param {ParseContext} ctx
2640
+ * @returns {[Record<string, unknown>, number]}
2641
+ */
2642
+ function parseObjectOrNamedArray(tokens, i, key, ctx = {}) {
2643
+ const keyToken = tokens[i];
2644
+ const keyCol = keyToken.col ?? keyToken.indent ?? 0;
2645
+ i = skipBlank(tokens, i + 1, true);
2646
+ const baseIndent = i < tokens.length ? (tokens[i].indent ?? 0) : 0;
2647
+ const first = i < tokens.length ? tokens[i] : null;
2648
+ // A block array may stand at the key's column. Every other block value
2649
+ // must be indented deeper, so a sibling item or property is no value.
2650
+ if (
2651
+ !first ||
2652
+ (first.indent ?? 0) < keyCol ||
2653
+ ((first.indent ?? 0) === keyCol && first.type !== "start")
2654
+ ) {
2655
+ const col = (keyToken.col ?? 0) + key.length + 1;
2656
+ throw new Error(
2657
+ "Expected value after property" +
2658
+ locSuffix(ctx, keyToken.lineNum ?? 0, col),
2659
+ );
2660
+ }
2661
+ if (first && first.type === "start" && first.text === "-") {
2662
+ const [arr, next] = parseListArray(tokens, i, ctx);
2663
+ return [{ [key]: arr }, next];
2664
+ }
2665
+ // Note: '*' syntax for multiline bytes is rejected by the scanner
2666
+ // Note: "key: <" without closing ">" is invalid - inline byte arrays must be closed on the same line
2667
+ // Reject a block string leader or a lone quote on a separate line
2668
+ if (
2669
+ first &&
2670
+ first.type === "text" &&
2671
+ (first.text.trim() === "`" || first.text === '"')
2672
+ ) {
2673
+ throw new Error(
2674
+ "Unexpected indent" + locSuffix(ctx, first.lineNum ?? 0, 0),
2675
+ );
2676
+ }
2677
+ // Concatenated quoted strings (multiple quoted strings on consecutive lines).
2678
+ // A quoted line with a colon outside its quotes is a property with a quoted
2679
+ // key, which opens a nested object.
2680
+ if (first && first.type === "text") {
2681
+ const trimmed = first.text.trim();
2682
+ if (
2683
+ ((trimmed.startsWith('"') &&
2684
+ trimmed.endsWith('"') &&
2685
+ trimmed.length >= 2) ||
2686
+ (trimmed.startsWith("'") &&
2687
+ trimmed.endsWith("'") &&
2688
+ trimmed.length >= 2)) &&
2689
+ !splitKeyValue(first.text, first.col ?? 0, ctx, first.lineNum ?? 0)
1391
2690
  ) {
1392
- const nextIndent = next.indent ?? 0;
1393
- const inlineIndent = nextIndent === listIndent ? nextIndent : undefined;
1394
- const baseIndent =
1395
- inlineIndent !== undefined ? nextIndent + 2 : nextIndent;
1396
- const [obj, nextIndex] = parseObjectBlock(
1397
- tokens,
1398
- i,
1399
- baseIndent,
1400
- ctx,
1401
- inlineIndent,
2691
+ const result = parseConcatenatedStrings(tokens, i, baseIndent, ctx);
2692
+ if (result !== null) {
2693
+ const [concatStr, next] = result;
2694
+ return [{ [key]: concatStr }, next];
2695
+ }
2696
+ // Single string on new line is invalid - fall through to error
2697
+ throw new Error(
2698
+ "Unexpected indent" + locSuffix(ctx, first.lineNum ?? 0, 0),
1402
2699
  );
1403
- arr.push(obj);
1404
- i = nextIndex;
1405
- } else if (next.type === "text" || next.type === "start") {
1406
- const [value, j] = parseValue(tokens, i, ctx);
1407
- let k = j;
1408
- while (k < tokens.length && tokens[k].type === "break") k++;
1409
- const afterBreak = k < tokens.length ? tokens[k] : null;
1410
- if (
1411
- afterBreak &&
1412
- afterBreak.type === "start" &&
1413
- afterBreak.text === "-" &&
1414
- (afterBreak.indent ?? 0) > listIndent
1415
- ) {
1416
- const group = [value];
1417
- i = k;
1418
- while (
1419
- i < tokens.length &&
1420
- tokens[i].type === "start" &&
1421
- tokens[i].text === "-" &&
1422
- (tokens[i].indent ?? 0) > listIndent
1423
- ) {
2700
+ }
2701
+ }
2702
+ const obj = {};
2703
+ /** @type {Map<string, [number, number]>} */
2704
+ const seen = new Map();
2705
+ while (i < tokens.length) {
2706
+ const t = tokens[i];
2707
+ if (t.type === "stop") {
2708
+ i++;
2709
+ continue;
2710
+ }
2711
+ if (t.type === "text") {
2712
+ const s = t.text;
2713
+ // Reject inline values on separate line (they look like keys starting with special chars)
2714
+ if (s.startsWith("{") || s.startsWith("[") || s.startsWith("<")) {
2715
+ throw new Error(
2716
+ "Unexpected indent" + locSuffix(ctx, t.lineNum ?? 0, 0),
2717
+ );
2718
+ }
2719
+ const keyValue = splitKeyValue(s, t.col ?? 0, ctx, t.lineNum ?? 0);
2720
+ if (keyValue) {
2721
+ const k = keyValue.key;
2722
+ if ((t.indent ?? 0) < baseIndent) break;
2723
+ if ((t.indent ?? 0) <= baseIndent) {
2724
+ claimKey(seen, k, ctx, t.lineNum ?? 0, t.col ?? 0);
2725
+ }
2726
+ if (k && (t.indent ?? 0) <= baseIndent) {
2727
+ const [value, next] = parsePropertyValue(tokens, i, keyValue, ctx, {
2728
+ baseIndent: t.indent ?? 0,
2729
+ emptyMode: "named",
2730
+ });
2731
+ setOwn(obj, k, value);
2732
+ i = next;
2733
+ } else {
1424
2734
  i++;
1425
- while (i < tokens.length && tokens[i].type === "break") i++;
1426
- if (i >= tokens.length) break;
1427
- const [subVal, nextI] = parseValue(tokens, i, ctx);
1428
- group.push(subVal);
1429
- i = nextI;
1430
- while (i < tokens.length && tokens[i].type === "stop") i++;
1431
2735
  }
1432
- arr.push(group);
1433
2736
  } else {
1434
- arr.push(value);
1435
- i = j;
2737
+ // Text without colon in nested object context is invalid
2738
+ // (e.g., inline array/object/bytes/string on separate line)
2739
+ throw new Error(
2740
+ "Unexpected indent" + locSuffix(ctx, t.lineNum ?? 0, 0),
2741
+ );
1436
2742
  }
1437
2743
  } else {
1438
2744
  i++;
1439
2745
  }
1440
- // Skip stops and breaks between items
1441
- while (
1442
- i < tokens.length &&
1443
- (tokens[i].type === "stop" || tokens[i].type === "break")
1444
- )
2746
+ }
2747
+ return [{ [key]: Object.keys(obj).length ? obj : undefined }, i];
2748
+ }
2749
+
2750
+ /**
2751
+ * @param {Token[]} tokens
2752
+ * @param {number} i
2753
+ * @param {number} baseIndent
2754
+ * @param {ParseContext} ctx
2755
+ * @param {number=} inlineIndent
2756
+ * @returns {[Record<string, unknown>, number]}
2757
+ */
2758
+ function parseObjectBlock(tokens, i, baseIndent, ctx = {}, inlineIndent) {
2759
+ const obj = {};
2760
+ /** @type {Map<string, [number, number]>} */
2761
+ const seen = new Map();
2762
+ let firstText = true;
2763
+ while (i < tokens.length) {
2764
+ const t = tokens[i];
2765
+ if (inlineIndent !== undefined) {
2766
+ if (t.type === "stop") break;
2767
+ if (t.type === "start" && (t.indent ?? 0) <= inlineIndent) break;
2768
+ }
2769
+ if (t.type === "stop") {
2770
+ i++;
2771
+ continue;
2772
+ }
2773
+ // A list leader outdented past this object begins the next item of an
2774
+ // enclosing list.
2775
+ if (t.type === "start" && (t.indent ?? 0) < baseIndent) break;
2776
+ if (t.type !== "text") {
1445
2777
  i++;
2778
+ continue;
2779
+ }
2780
+ let indent = t.indent ?? 0;
2781
+ if (firstText && inlineIndent !== undefined && indent === inlineIndent) {
2782
+ indent = baseIndent;
2783
+ }
2784
+ firstText = false;
2785
+ if (indent < baseIndent) break;
2786
+ if (indent > baseIndent) {
2787
+ i++;
2788
+ continue;
2789
+ }
2790
+ const keyValue = splitKeyValue(t.text, t.col ?? 0, ctx, t.lineNum ?? 0);
2791
+ if (!keyValue) {
2792
+ i++;
2793
+ continue;
2794
+ }
2795
+ const k = keyValue.key;
2796
+ claimKey(seen, k, ctx, t.lineNum ?? 0, t.col ?? 0);
2797
+ const [value, next] = parsePropertyValue(tokens, i, keyValue, ctx, {
2798
+ baseIndent,
2799
+ blockIndent: indent,
2800
+ emptyMode: "block",
2801
+ });
2802
+ setOwn(obj, k, value);
2803
+ i = next;
1446
2804
  }
1447
- return [arr, i];
2805
+ return [obj, i];
1448
2806
  }
1449
2807
 
2808
+ // Root as object (multiple key: value lines at indent 0)
1450
2809
  /**
1451
- * Parse a block string with an optional base indent constraint.
1452
2810
  * @param {Token[]} tokens
1453
2811
  * @param {number} i
1454
- * @param {string|undefined} firstLine
1455
- * @param {boolean} inPropertyContext
1456
- * @param {number} baseIndent - If >= 0, stop collecting when indent <= baseIndent
1457
- * @returns {[string, number]}
2812
+ * @param {ParseContext} ctx
2813
+ * @returns {[Record<string, unknown>, number]}
1458
2814
  */
1459
- function parseBlockStringWithIndent(
1460
- tokens,
1461
- i,
1462
- firstLine,
1463
- inPropertyContext,
1464
- baseIndent,
1465
- ) {
1466
- const lines = [];
1467
- if (firstLine !== undefined) {
1468
- lines.push(firstLine);
1469
- i++;
1470
- } else {
1471
- i++;
2815
+ function parseRootObject(tokens, i, ctx = {}) {
2816
+ const obj = {};
2817
+ /** @type {Map<string, [number, number]>} */
2818
+ const seen = new Map();
2819
+ const baseIndent = 0;
2820
+ while (i < tokens.length) {
2821
+ const t = tokens[i];
2822
+ if (t.type === "stop") {
2823
+ i++;
2824
+ continue;
2825
+ }
2826
+ if (t.type === "text") {
2827
+ const s = t.text;
2828
+ const keyValue = splitKeyValue(s, t.col ?? 0, ctx, t.lineNum ?? 0);
2829
+ if (keyValue && (t.indent ?? 0) === baseIndent) {
2830
+ const k = keyValue.key;
2831
+ claimKey(seen, k, ctx, t.lineNum ?? 0, t.col ?? 0);
2832
+ const [value, next] = parsePropertyValue(tokens, i, keyValue, ctx, {
2833
+ baseIndent,
2834
+ emptyMode: "root",
2835
+ });
2836
+ setOwn(obj, k, value);
2837
+ i = next;
2838
+ } else if ((t.indent ?? 0) > baseIndent) {
2839
+ // A line indented under a property that took no block, placed at
2840
+ // the line's start as every other unexpected indent is
2841
+ throw new Error(
2842
+ "Unexpected indent" + locSuffix(ctx, t.lineNum ?? 0, 0),
2843
+ );
2844
+ } else {
2845
+ i++;
2846
+ }
2847
+ } else {
2848
+ i++;
2849
+ }
1472
2850
  }
1473
- // Collect continuation lines with their indent so we can strip minimum indent (for property block strings).
1474
- const continuationLines = [];
1475
- while (
1476
- i < tokens.length &&
1477
- (tokens[i].type === "text" || tokens[i].type === "break")
2851
+ return [obj, i];
2852
+ }
2853
+
2854
+ // --- Well-formed strings ---
2855
+
2856
+ /**
2857
+ * Whether a value is a string of Unicode scalar values: no unpaired UTF-16
2858
+ * surrogate. The shape of Endo's `isWellFormedString` (@endo/pass-style
2859
+ * `string.js`): the `typeof` guard first, since `isWellFormed` applies
2860
+ * ToString to its receiver and would pass a non-string that coerces to a
2861
+ * well-formed string; without `String.prototype.isWellFormed`, the string
2862
+ * iterator, which yields a code point in U+D800..U+DFFF only for an unpaired
2863
+ * surrogate.
2864
+ * @param {unknown} str
2865
+ * @returns {str is string}
2866
+ */
2867
+ function isWellFormedString(str) {
2868
+ if (typeof str !== "string") return false;
2869
+ if (typeof String.prototype.isWellFormed === "function") {
2870
+ return str.isWellFormed();
2871
+ }
2872
+ for (const ch of str) {
2873
+ const cp = /** @type {number} */ (ch.codePointAt(0));
2874
+ if (cp >= 0xd800 && cp <= 0xdfff) return false;
2875
+ }
2876
+ return true;
2877
+ }
2878
+
2879
+ /**
2880
+ * Refuse a string that is not well formed, with the readers' message.
2881
+ * @param {string} str
2882
+ * @param {string} what - what the string is, for the message
2883
+ */
2884
+ function checkWellFormed(str, what) {
2885
+ if (!isWellFormedString(str)) {
2886
+ throw new TypeError(`Illegal surrogate in ${what}: ${JSON.stringify(str)}`);
2887
+ }
2888
+ }
2889
+
2890
+ /**
2891
+ * Refuse a value that carries a string that is not well formed anywhere in
2892
+ * it: a string, a record key, or a name held in a non-enumerable property,
2893
+ * as an Endo tagged value's tag and a symbol record's name are held in
2894
+ * `Symbol.toStringTag`. Every own property is walked, by descriptor, so no
2895
+ * getter runs; bytes are not walked. A value seen before is not walked
2896
+ * again, so a cycle ends.
2897
+ * @param {unknown} value
2898
+ * @param {string} path
2899
+ * @param {WeakSet<object>} seen
2900
+ */
2901
+ function checkWellFormedDeep(value, path = "$", seen = new WeakSet()) {
2902
+ if (typeof value === "string") {
2903
+ checkWellFormed(value, `the string at ${path}`);
2904
+ return;
2905
+ }
2906
+ if (value === null || typeof value !== "object") return;
2907
+ if (seen.has(value)) return;
2908
+ seen.add(value);
2909
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return;
2910
+ for (const key of Reflect.ownKeys(value)) {
2911
+ const descriptor = /** @type {PropertyDescriptor} */ (
2912
+ Object.getOwnPropertyDescriptor(value, key)
2913
+ );
2914
+ if (typeof key === "string") {
2915
+ checkWellFormed(key, `a key at ${path}`);
2916
+ }
2917
+ if (!("value" in descriptor)) continue;
2918
+ if (key === Symbol.toStringTag) {
2919
+ if (typeof descriptor.value === "string") {
2920
+ checkWellFormed(descriptor.value, `the name or tag at ${path}`);
2921
+ }
2922
+ continue;
2923
+ }
2924
+ if (typeof key === "symbol") continue;
2925
+ if (Array.isArray(value) && key === "length") continue;
2926
+ checkWellFormedDeep(
2927
+ descriptor.value,
2928
+ Array.isArray(value)
2929
+ ? `${path}[${key}]`
2930
+ : `${path}[${JSON.stringify(key)}]`,
2931
+ seen,
2932
+ );
2933
+ }
2934
+ }
2935
+
2936
+ // --- Tagged values ---
2937
+
2938
+ const PASS_STYLE = Symbol.for("passStyle");
2939
+
2940
+ /**
2941
+ * A symbol record: a name distinguished from a string, in the shape Endo's
2942
+ * reified symbols use. The record is shallowly frozen and has no payload.
2943
+ * @param {string} name
2944
+ * @returns {object}
2945
+ */
2946
+ function symbol(name) {
2947
+ if (typeof name !== "string") {
2948
+ throw new TypeError("A symbol's name must be a string");
2949
+ }
2950
+ checkWellFormed(name, "a symbol's name");
2951
+ return Object.freeze(
2952
+ Object.create(Object.prototype, {
2953
+ [PASS_STYLE]: { value: "symbol" },
2954
+ [Symbol.toStringTag]: { value: name },
2955
+ }),
2956
+ );
2957
+ }
2958
+
2959
+ /**
2960
+ * @param {unknown} value
2961
+ * @returns {boolean}
2962
+ */
2963
+ function isSymbol(value) {
2964
+ if (
2965
+ value === null ||
2966
+ typeof value !== "object" ||
2967
+ Object.getPrototypeOf(value) !== Object.prototype ||
2968
+ !Object.isFrozen(value)
2969
+ ) {
2970
+ return false;
2971
+ }
2972
+ const descriptors = Object.getOwnPropertyDescriptors(value);
2973
+ const passStyle = descriptors[PASS_STYLE];
2974
+ const name = descriptors[Symbol.toStringTag];
2975
+ return (
2976
+ Reflect.ownKeys(descriptors).length === 2 &&
2977
+ passStyle?.value === "symbol" &&
2978
+ passStyle.enumerable === false &&
2979
+ passStyle.writable === false &&
2980
+ passStyle.configurable === false &&
2981
+ typeof name?.value === "string" &&
2982
+ name.enumerable === false &&
2983
+ name.writable === false &&
2984
+ name.configurable === false
2985
+ );
2986
+ }
2987
+
2988
+ /**
2989
+ * A tagged value: a tag, any string, and one payload, any YAY value.
2990
+ * The outer record is frozen, ready for a hardened environment to harden its
2991
+ * payload and accept it as Endo pass data.
2992
+ * @param {string} tag
2993
+ * @param {unknown} payload
2994
+ * @returns {object}
2995
+ */
2996
+ function tagged(tag, payload) {
2997
+ if (typeof tag !== "string") {
2998
+ throw new TypeError("A tag must be a string");
2999
+ }
3000
+ checkWellFormed(tag, "a tag");
3001
+ checkWellFormedDeep(payload, "payload");
3002
+ return taggedRecord(tag, payload);
3003
+ }
3004
+
3005
+ /**
3006
+ * The tagged record, unchecked: for the parser, whose tags and strings the
3007
+ * scanner has already checked, so that a deeply tagged document is not
3008
+ * walked once per tag.
3009
+ * @param {string} tag
3010
+ * @param {unknown} payload
3011
+ * @returns {object}
3012
+ */
3013
+ function taggedRecord(tag, payload) {
3014
+ return Object.freeze(
3015
+ Object.create(Object.prototype, {
3016
+ [PASS_STYLE]: { value: "tagged" },
3017
+ [Symbol.toStringTag]: { value: tag },
3018
+ payload: { value: payload, enumerable: true },
3019
+ }),
3020
+ );
3021
+ }
3022
+
3023
+ /**
3024
+ * @param {unknown} value
3025
+ * @returns {boolean}
3026
+ */
3027
+ function isTagged(value) {
3028
+ if (
3029
+ value === null ||
3030
+ typeof value !== "object" ||
3031
+ Object.getPrototypeOf(value) !== Object.prototype ||
3032
+ !Object.isFrozen(value)
1478
3033
  ) {
1479
- if (tokens[i].type === "break") {
1480
- continuationLines.push({ indent: undefined, text: "" });
3034
+ return false;
3035
+ }
3036
+ const descriptors = Object.getOwnPropertyDescriptors(value);
3037
+ const passStyle = descriptors[PASS_STYLE];
3038
+ const tag = descriptors[Symbol.toStringTag];
3039
+ const payload = descriptors.payload;
3040
+ return (
3041
+ Reflect.ownKeys(descriptors).length === 3 &&
3042
+ passStyle?.value === "tagged" &&
3043
+ passStyle.enumerable === false &&
3044
+ passStyle.writable === false &&
3045
+ passStyle.configurable === false &&
3046
+ typeof tag?.value === "string" &&
3047
+ tag.enumerable === false &&
3048
+ tag.writable === false &&
3049
+ tag.configurable === false &&
3050
+ payload !== undefined &&
3051
+ "value" in payload &&
3052
+ payload.enumerable === true &&
3053
+ payload.writable === false &&
3054
+ payload.configurable === false
3055
+ );
3056
+ }
3057
+
3058
+ /**
3059
+ * Scan syntax that may contain quotes, tags, and references once. The masked
3060
+ * text replaces their payloads with "x", unit for unit, so structural scans
3061
+ * can use the original offsets without reimplementing quote awareness.
3062
+ * @param {string} s
3063
+ * @param {boolean=} mask - build the masked text, for a caller that scans it
3064
+ * @returns {{masked: string|undefined, firstTag: number|undefined, comment: number|undefined, colon: number|undefined, closeBracket: number}}
3065
+ */
3066
+ function scanTopLevel(s, mask = false) {
3067
+ /** @type {[number, number][]|undefined} */
3068
+ const masks = mask ? [] : undefined;
3069
+ let firstTag;
3070
+ let comment;
3071
+ let colon;
3072
+ let closeBracket = -1;
3073
+ let quote = 0;
3074
+ let quoteStart = 0;
3075
+ let depth = 0;
3076
+ let bracketDepth = 0;
3077
+ let commentEscape = false;
3078
+ let i = 0;
3079
+ const n = s.length;
3080
+ while (i < n) {
3081
+ const c = s.charCodeAt(i);
3082
+ if (quote !== 0) {
3083
+ if (c === 0x5c) {
3084
+ i += Math.min(2, n - i);
3085
+ continue;
3086
+ }
3087
+ if (c === quote) {
3088
+ if (masks !== undefined) masks.push([quoteStart, i]);
3089
+ quote = 0;
3090
+ }
1481
3091
  i++;
1482
- } else {
1483
- // If we have a base indent constraint, stop when we see a line at or below that indent
1484
- if (baseIndent >= 0 && (tokens[i].indent ?? 0) <= baseIndent) {
1485
- break;
3092
+ continue;
3093
+ }
3094
+ // A reference's text is no syntax either
3095
+ if (c === 0x3c && isReferenceStartAt(s, i)) {
3096
+ const end = s.indexOf(">", i);
3097
+ if (end >= 0) {
3098
+ if (masks !== undefined) masks.push([i + 1, end]);
3099
+ i = end + 1;
3100
+ continue;
1486
3101
  }
1487
- continuationLines.push({
1488
- indent: tokens[i].indent ?? 0,
1489
- text: tokens[i].text,
1490
- });
3102
+ }
3103
+ if (c === 0x22 || c === 0x27) {
3104
+ quote = c;
3105
+ quoteStart = i + 1;
3106
+ } else if (c === 0x5b || c === 0x7b) {
3107
+ depth++;
3108
+ if (c === 0x5b) bracketDepth++;
3109
+ } else if (c === 0x5d || c === 0x7d) {
3110
+ depth--;
3111
+ if (c === 0x5d) {
3112
+ bracketDepth--;
3113
+ if (bracketDepth === 0 && closeBracket < 0) closeBracket = i;
3114
+ }
3115
+ } else if (c === 0x28) {
3116
+ if (depth === 0 && firstTag === undefined) firstTag = i;
3117
+ const tagStart = i + 1;
1491
3118
  i++;
3119
+ while (i < n && s.charCodeAt(i) !== 0x29) {
3120
+ i += s.charCodeAt(i) === 0x5c ? Math.min(2, n - i) : 1;
3121
+ }
3122
+ if (masks !== undefined) masks.push([tagStart, i]);
3123
+ continue;
3124
+ } else if (c === 0x3a && colon === undefined) {
3125
+ colon = i;
3126
+ }
3127
+ if (comment === undefined) {
3128
+ if (commentEscape) {
3129
+ commentEscape = false;
3130
+ } else if (c === 0x5c) {
3131
+ commentEscape = true;
3132
+ } else if (c === 0x23) {
3133
+ comment = i;
3134
+ }
1492
3135
  }
3136
+ i++;
1493
3137
  }
1494
- const minIndent = continuationLines
1495
- .filter((x) => x.indent !== undefined)
1496
- .reduce((min, x) => (x.indent < min ? x.indent : min), Infinity);
1497
- const effectiveMin = minIndent === Infinity ? 0 : minIndent;
1498
- for (const { indent, text } of continuationLines) {
1499
- if (indent === undefined) {
1500
- lines.push("");
1501
- } else {
1502
- // Token text is already after indent; add back (indent - minIndent) spaces for relative indent.
1503
- const extraSpaces = indent - effectiveMin;
1504
- lines.push((extraSpaces > 0 ? " ".repeat(extraSpaces) : "") + text);
1505
- }
3138
+ if (masks === undefined) {
3139
+ return { masked: undefined, firstTag, comment, colon, closeBracket };
1506
3140
  }
1507
- // Trim leading and trailing empty lines; then one leading newline and one trailing newline.
1508
- let start = 0;
1509
- while (start < lines.length && lines[start] === "") start++;
1510
- let end = lines.length;
1511
- while (end > start && lines[end - 1] === "") end--;
1512
- const trimmed = lines.slice(start, end);
1513
- // When block starts with quote on its own line (firstLine === ''), output has a leading newline.
1514
- // But NOT in property context.
1515
- const leadingNewline =
1516
- firstLine === "" && trimmed.length > 0 && !inPropertyContext;
1517
- const body =
1518
- (leadingNewline ? "\n" : "") +
1519
- trimmed.join("\n") +
1520
- (trimmed.length > 0 ? "\n" : "");
1521
- // Empty block strings are not allowed - use "" for empty string
1522
- if (body === "") {
1523
- throw new Error(
1524
- 'Empty block string not allowed (use "" or "\\n" explicitly)',
1525
- );
3141
+ if (quote !== 0) masks.push([quoteStart, n]);
3142
+ let masked = s;
3143
+ if (masks.length > 0) {
3144
+ const chunks = [];
3145
+ let start = 0;
3146
+ for (const [from, to] of masks) {
3147
+ chunks.push(s.slice(start, from), "x".repeat(to - from));
3148
+ start = to;
3149
+ }
3150
+ chunks.push(s.slice(start));
3151
+ masked = chunks.join("");
1526
3152
  }
1527
- return [body, i];
3153
+ return { masked, firstTag, comment, colon, closeBracket };
1528
3154
  }
1529
3155
 
1530
3156
  /**
1531
- * Parse concatenated quoted strings (multiple quoted strings on consecutive lines).
1532
- * Returns null if there's only one string (single string on new line is invalid).
1533
- * @param {Token[]} tokens
1534
- * @param {number} i
1535
- * @param {number} baseIndent
3157
+ * Parse one tag at the start of s, which begins with "(". Returns the tag
3158
+ * and the number of units consumed, the closing ")" included. The tag is
3159
+ * escaped as a double-quoted string is, with \) in the place of \".
3160
+ * @param {string} s
1536
3161
  * @param {ParseContext} ctx
1537
- * @returns {[string, number] | null}
3162
+ * @param {number} lineNum
3163
+ * @param {number} col
3164
+ * @returns {[string, number]}
1538
3165
  */
1539
- function parseConcatenatedStrings(tokens, i, baseIndent, ctx = {}) {
1540
- const parts = [];
1541
- const startI = i;
1542
-
1543
- while (i < tokens.length) {
1544
- const t = tokens[i];
1545
-
1546
- if (t.type === "break" || t.type === "stop") {
3166
+ function parseTag(s, ctx, lineNum, col) {
3167
+ let out = "";
3168
+ let i = 1;
3169
+ while (i < s.length) {
3170
+ const c = s[i];
3171
+ if (c === ")") return [out, i + 1];
3172
+ if (c === "\t") {
3173
+ throw new Error(
3174
+ "Tab not allowed (use spaces)" + locSuffix(ctx, lineNum, col + i),
3175
+ );
3176
+ }
3177
+ if (c !== "\\") {
3178
+ out += c;
1547
3179
  i++;
1548
3180
  continue;
1549
3181
  }
3182
+ const [value, next] = readEscape(s, i, ")", ctx, lineNum, col);
3183
+ out += value;
3184
+ i = next;
3185
+ }
3186
+ throw new Error("Unterminated string" + locSuffix(ctx, lineNum, col));
3187
+ }
1550
3188
 
1551
- if (t.type !== "text" || (t.indent ?? 0) < baseIndent) {
1552
- break;
3189
+ /**
3190
+ * Parse a run of tags after a value: each one space, then a tag. Returns the
3191
+ * tags, innermost first, and the number of units consumed. A tag fused to
3192
+ * its value or after two spaces is refused.
3193
+ * @param {string} s
3194
+ * @param {ParseContext} ctx
3195
+ * @param {number} lineNum
3196
+ * @param {number} col
3197
+ * @returns {[string[], number]}
3198
+ */
3199
+ function parseSuffix(s, ctx, lineNum, col) {
3200
+ const tags = [];
3201
+ let pos = 0;
3202
+ for (;;) {
3203
+ let spaces = 0;
3204
+ while (s[pos + spaces] === " ") spaces++;
3205
+ if (s[pos + spaces] !== "(") break;
3206
+ if (spaces !== 1) {
3207
+ throw new Error(
3208
+ (spaces === 0
3209
+ ? "Expected one space before a tag"
3210
+ : 'Unexpected space before "("') + locSuffix(ctx, lineNum, col + pos),
3211
+ );
1553
3212
  }
3213
+ const [tag, n] = parseTag(s.slice(pos + 1), ctx, lineNum, col + pos + 1);
3214
+ tags.push(tag);
3215
+ pos += 1 + n;
3216
+ }
3217
+ return [tags, pos];
3218
+ }
1554
3219
 
1555
- const trimmed = t.text.trim();
3220
+ /**
3221
+ * Parse a run of tags before a block: tags separated by one space. Returns
3222
+ * the tags, outermost first, and what follows the last one (after its
3223
+ * space, or a comment, which is the empty string).
3224
+ * @param {string} s
3225
+ * @param {ParseContext} ctx
3226
+ * @param {number} lineNum
3227
+ * @param {number} col
3228
+ * @returns {[string[], string]}
3229
+ */
3230
+ function parsePrefix(s, ctx, lineNum, col) {
3231
+ const [first, n] = parseTag(s, ctx, lineNum, col);
3232
+ const [tags, m] = parseSuffix(s.slice(n), ctx, lineNum, col + n);
3233
+ tags.unshift(first);
3234
+ const rest = s.slice(n + m);
3235
+ if (rest === "" || rest.startsWith(" #")) return [tags, ""];
3236
+ if (rest.startsWith(" ") && !rest.startsWith(" ")) {
3237
+ return [tags, rest.slice(1)];
3238
+ }
3239
+ throw new Error(
3240
+ 'Unexpected space after ")"' + locSuffix(ctx, lineNum, col + n + m),
3241
+ );
3242
+ }
1556
3243
 
1557
- // Check if this line is a quoted string
1558
- const isDoubleQuoted =
1559
- trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2;
1560
- const isSingleQuoted =
1561
- trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2;
3244
+ /**
3245
+ * Wrap a payload in tags, innermost first.
3246
+ * @param {unknown} value
3247
+ * @param {string[]} tags
3248
+ */
3249
+ function wrapTags(value, tags) {
3250
+ return tags.reduce((v, tag) => taggedRecord(tag, v), value);
3251
+ }
1562
3252
 
1563
- if (!isDoubleQuoted && !isSingleQuoted) {
1564
- break;
1565
- }
3253
+ /**
3254
+ * Wrap a payload in a prefix's tags, outermost first.
3255
+ * @param {unknown} value
3256
+ * @param {string[]} tags
3257
+ */
3258
+ function wrapPrefix(value, tags) {
3259
+ return wrapTags(value, [...tags].reverse());
3260
+ }
1566
3261
 
1567
- // Parse the quoted string
1568
- const parsed = parseQuotedString(trimmed, ctx, t.lineNum ?? 0, t.col ?? 0);
1569
- parts.push(parsed);
1570
- i++;
1571
- }
3262
+ /**
3263
+ * Is rest, what follows a prefix, a block it may introduce on its own line?
3264
+ * @param {string} rest
3265
+ */
3266
+ function prefixTakes(rest) {
3267
+ return rest === "" || rest.startsWith("`") || rest.startsWith(">");
3268
+ }
1572
3269
 
1573
- // Require at least 2 strings for concatenation
1574
- // A single string on a new line is invalid (use inline syntax instead)
1575
- if (parts.length < 2) {
3270
+ /**
3271
+ * The tags at the start of a line, and the rest, or null if the line does
3272
+ * not begin with well-formed tags. For the scanner, which finds block
3273
+ * openers before the parser reports errors.
3274
+ * @param {string} s
3275
+ * @returns {string|null}
3276
+ */
3277
+ function afterPrefix(s) {
3278
+ if (!s.startsWith("(")) return null;
3279
+ try {
3280
+ return parsePrefix(s, {}, 0, 0)[1];
3281
+ } catch {
1576
3282
  return null;
1577
3283
  }
3284
+ }
1578
3285
 
1579
- return [parts.join(""), i];
3286
+ /**
3287
+ * Whether a line is a property whose tags introduce a block string, as in
3288
+ * "key: (tag) `".
3289
+ * @param {string} line
3290
+ */
3291
+ function isTaggedPropertyOpener(line) {
3292
+ const colon = findKeyColonOutsideQuotes(line);
3293
+ if (colon < 0 || !line.startsWith(" (", colon + 1)) return false;
3294
+ return afterPrefix(line.slice(colon + 2)) === "`";
1580
3295
  }
1581
3296
 
1582
3297
  /**
1583
- * @param {string} text
1584
- * @returns {boolean}
3298
+ * Whether what a property's prefix tagged is no block: nothing, or the empty
3299
+ * list a property reads when the next line is a sibling item.
3300
+ * @param {unknown} value
1585
3301
  */
1586
- function isInlineBullet(text) {
1587
- let i = 0;
1588
- while (i < text.length && text[i] === " ") i++;
3302
+ function isMissingBlock(value) {
1589
3303
  return (
1590
- i < text.length &&
1591
- text[i] === "-" &&
1592
- i + 1 < text.length &&
1593
- text[i + 1] === " "
3304
+ value === undefined ||
3305
+ value === null ||
3306
+ (Array.isArray(value) && value.length === 0)
1594
3307
  );
1595
3308
  }
1596
3309
 
1597
3310
  /**
1598
- * @param {string} text
3311
+ * The error for a prefix that introduces no block.
1599
3312
  * @param {ParseContext} ctx
1600
3313
  * @param {number} lineNum
1601
3314
  * @param {number} col
1602
- * @returns {string}
1603
3315
  */
1604
- function parseInlineBulletValue(text, ctx = {}, lineNum = 0, col = 0) {
1605
- let i = 0;
1606
- while (i < text.length && text[i] === " ") i++;
1607
- if (i >= text.length || text[i] !== "-") return "";
1608
- const dashIndex = i;
1609
- const afterDash = dashIndex + 1;
1610
- if (afterDash >= text.length || text[afterDash] !== " ") return "";
1611
- if (afterDash + 1 < text.length && text[afterDash + 1] === " ") {
1612
- throw new Error(
1613
- 'Unexpected space after "-"' +
1614
- locSuffix(ctx, lineNum, col + afterDash + 1),
1615
- );
3316
+ function prefixWithoutBlock(ctx, lineNum, col) {
3317
+ return new Error(
3318
+ "A tag before a value needs a block below it; write the tag after an inline value" +
3319
+ locSuffix(ctx, lineNum, col),
3320
+ );
3321
+ }
3322
+
3323
+ /**
3324
+ * The error for a prefix whose following line is an inline value. A tag line
3325
+ * without a following block is a symbol instead.
3326
+ * @param {ParseContext} ctx
3327
+ * @param {number} lineNum
3328
+ * @param {number} col
3329
+ */
3330
+ function prefixOverInlineValue(ctx, lineNum, col) {
3331
+ return new Error(
3332
+ "A tag before an inline value is refused; a tag alone is a symbol" +
3333
+ locSuffix(ctx, lineNum, col),
3334
+ );
3335
+ }
3336
+
3337
+ /** Whether tokens[i] begins a root block rather than an inline value. */
3338
+ function rootBlockFollows(tokens, i) {
3339
+ const token = tokens[i];
3340
+ if (token?.type === "start" && token.text === "-") return true;
3341
+ if (token?.type !== "text") return false;
3342
+ const text = token.text;
3343
+ if (text === "`" || text.startsWith("` ") || text.startsWith(">")) {
3344
+ return true;
1616
3345
  }
1617
- return text.slice(afterDash + 1);
3346
+ if (
3347
+ findKeyColonOutsideQuotes(text) >= 0 &&
3348
+ !text.startsWith("{") &&
3349
+ !text.startsWith("[")
3350
+ ) {
3351
+ return true;
3352
+ }
3353
+ if (!text.startsWith("(")) return false;
3354
+ let rest;
3355
+ try {
3356
+ [, rest] = parsePrefix(text, {}, 0, 0);
3357
+ } catch {
3358
+ return false;
3359
+ }
3360
+ if (rest !== "") return false;
3361
+ const next = skipBlank(tokens, i + 1, true);
3362
+ return next < tokens.length && rootBlockFollows(tokens, next);
3363
+ }
3364
+
3365
+ /** Whether tokens[i] begins a block belonging to a list item at listIndent. */
3366
+ function listBlockFollows(tokens, i, listIndent) {
3367
+ const token = tokens[i];
3368
+ if (!token || (token.indent ?? 0) <= listIndent) return false;
3369
+ if (token.type === "start" && token.text === "-") return true;
3370
+ if (token.type !== "text") return false;
3371
+ if (
3372
+ findKeyColonOutsideQuotes(token.text) >= 0 &&
3373
+ !token.text.startsWith("{") &&
3374
+ !token.text.startsWith("[")
3375
+ ) {
3376
+ return true;
3377
+ }
3378
+ if (!token.text.startsWith("(")) return false;
3379
+ let rest;
3380
+ try {
3381
+ [, rest] = parsePrefix(token.text, {}, 0, 0);
3382
+ } catch {
3383
+ return false;
3384
+ }
3385
+ if (rest !== "") return prefixTakes(rest);
3386
+ const next = skipBlank(tokens, i + 1);
3387
+ return next < tokens.length && listBlockFollows(tokens, next, listIndent);
1618
3388
  }
1619
3389
 
3390
+ /** Whether a property's following token begins its block value. */
3391
+ function propertyBlockFollows(tokens, i, baseIndent) {
3392
+ const next = skipBlank(tokens, i + 1, true);
3393
+ if (next >= tokens.length) return false;
3394
+ const token = tokens[next];
3395
+ if (token.type === "start" && token.text === "-") {
3396
+ return (token.indent ?? 0) >= baseIndent;
3397
+ }
3398
+ if (token.type !== "text" || (token.indent ?? 0) <= baseIndent) {
3399
+ return false;
3400
+ }
3401
+ const trimmed = token.text.trim();
3402
+ if (trimmed.startsWith('"') || trimmed.startsWith("'")) return true;
3403
+ return (
3404
+ findKeyColonOutsideQuotes(token.text) >= 0 &&
3405
+ !token.text.startsWith("{") &&
3406
+ !token.text.startsWith("[")
3407
+ );
3408
+ }
3409
+
3410
+ // --- References ---
3411
+
1620
3412
  /**
1621
- * Recursively parse an inline bullet value, handling nested "- " prefixes.
1622
- * Returns the parsed value (could be a nested array or a scalar).
3413
+ * A reference: a URI or IRI, held as written; it designates, and is never
3414
+ * dereferenced. Instances are frozen. Two are equal when their texts are,
3415
+ * code unit for code unit, and a reference never equals a string or a plain
3416
+ * object.
1623
3417
  */
1624
- function parseNestedInlineBullet(text, ctx = {}, lineNum = 0, col = 0) {
1625
- // Check if the text itself is another inline bullet
1626
- if (isInlineBullet(text)) {
1627
- const innerText = parseInlineBulletValue(text, ctx, lineNum, col);
1628
- const innerValue = parseNestedInlineBullet(
1629
- innerText,
1630
- ctx,
1631
- lineNum,
1632
- col + 2,
1633
- );
1634
- return [innerValue];
3418
+ class Reference {
3419
+ /**
3420
+ * @param {string} uri
3421
+ */
3422
+ constructor(uri) {
3423
+ if (typeof uri !== "string") {
3424
+ throw new TypeError("A reference must be a string");
3425
+ }
3426
+ checkReferenceText(uri);
3427
+ this.reference = uri;
3428
+ Object.freeze(this);
1635
3429
  }
1636
- // Otherwise, parse as a scalar
1637
- return parseScalar(text, ctx, lineNum, col);
1638
3430
  }
1639
3431
 
1640
- // Note: parseMultilineBytes for '*' syntax was removed as dead code.
1641
- // The scanner rejects '*' syntax, so this function was unreachable.
3432
+ /**
3433
+ * Refuse a string that is not a reference's text, by the parser's own rule:
3434
+ * a lowercase scheme, a colon, URI or IRI characters, and well-formed
3435
+ * percent-encodings.
3436
+ * @param {string} uri
3437
+ */
3438
+ function checkReferenceText(uri) {
3439
+ checkWellFormed(uri, "a reference");
3440
+ const text = "<" + uri + ">";
3441
+ let n = -1;
3442
+ let why = "it needs a scheme and a colon";
3443
+ if (isReferenceStart(text)) {
3444
+ try {
3445
+ [, n] = parseReference(text, {}, 0, 0);
3446
+ } catch (error) {
3447
+ why = /** @type {Error} */ (error).message;
3448
+ }
3449
+ }
3450
+ if (n !== text.length) {
3451
+ if (n >= 0) why = 'Unexpected character ">" in reference';
3452
+ throw new TypeError(`Not a reference: ${JSON.stringify(uri)} (${why})`);
3453
+ }
3454
+ }
3455
+
3456
+ /**
3457
+ * Make a reference, as `yay -t js` writes it and as a caller may use it for
3458
+ * `decodeReference`.
3459
+ * @param {string} uri
3460
+ * @returns {Reference}
3461
+ */
3462
+ function reference(uri) {
3463
+ return new Reference(uri);
3464
+ }
3465
+
3466
+ /**
3467
+ * @param {unknown} value
3468
+ * @returns {value is Reference}
3469
+ */
3470
+ function isReference(value) {
3471
+ return value instanceof Reference;
3472
+ }
3473
+
3474
+ /**
3475
+ * The length of the scheme, colon included, if s (the text after "<")
3476
+ * begins [A-Za-z][A-Za-z0-9+.-]*":". Uppercase letters are matched so that
3477
+ * the reader can name an uppercase scheme rather than call it bad hex.
3478
+ * @param {string} s
3479
+ * @returns {number|undefined}
3480
+ */
3481
+ function schemeLength(s) {
3482
+ return schemeLengthAt(s, 0);
3483
+ }
3484
+
3485
+ /**
3486
+ * The length of the scheme, colon included, beginning at s[at].
3487
+ * @param {string} s
3488
+ * @param {number} at
3489
+ * @returns {number|undefined}
3490
+ */
3491
+ function schemeLengthAt(s, at) {
3492
+ const c0 = s.charCodeAt(at) | 0x20;
3493
+ if (!(c0 >= 0x61 && c0 <= 0x7a)) return undefined;
3494
+ for (let i = at + 1; i < s.length; i++) {
3495
+ const c = s.charCodeAt(i);
3496
+ if (c === 0x3a) return i - at + 1;
3497
+ const l = c | 0x20;
3498
+ if (!(
3499
+ (l >= 0x61 && l <= 0x7a) ||
3500
+ (c >= 0x30 && c <= 0x39) ||
3501
+ c === 0x2b ||
3502
+ c === 0x2e ||
3503
+ c === 0x2d
3504
+ )) {
3505
+ return undefined;
3506
+ }
3507
+ }
3508
+ return undefined;
3509
+ }
3510
+
3511
+ /**
3512
+ * Whether s begins with "<" and a scheme, so is a reference.
3513
+ * @param {string} s
3514
+ */
3515
+ function isReferenceStart(s) {
3516
+ return isReferenceStartAt(s, 0);
3517
+ }
3518
+
3519
+ /**
3520
+ * Whether a reference begins at s[at].
3521
+ * @param {string} s
3522
+ * @param {number} at
3523
+ */
3524
+ function isReferenceStartAt(s, at) {
3525
+ return s.charCodeAt(at) === 0x3c && schemeLengthAt(s, at + 1) !== undefined;
3526
+ }
3527
+
3528
+ /**
3529
+ * Whether the character c may appear in a reference (RFC 3986 and RFC
3530
+ * 3987), "%" aside, which must begin a percent-encoding.
3531
+ * @param {string} c
3532
+ */
3533
+ function isUriChar(c) {
3534
+ const cp = c.codePointAt(0) ?? 0;
3535
+ if (cp < 0x80) return URI_ASCII[cp] === 1;
3536
+ return cp >= 0xa0 && !UNICODE_SPACE.test(c) && cp !== 0xfffe && cp !== 0xffff;
3537
+ }
1642
3538
 
1643
3539
  /**
1644
- * @param {Token[]} tokens
1645
- * @param {number} i
3540
+ * Parse a reference at the start of s, which begins with "<" and a scheme.
3541
+ * Returns the URI text and the number of units consumed, the ">" included.
3542
+ * The text between the brackets is the URI, verbatim.
3543
+ * @param {string} s
1646
3544
  * @param {ParseContext} ctx
1647
- * @param {string} firstLineRaw
1648
- * @param {number} baseIndent
1649
- * @returns {[Uint8Array, number]}
3545
+ * @param {number} lineNum
3546
+ * @param {number} col
3547
+ * @returns {[string, number]}
1650
3548
  */
1651
- function parseBlockBytes(tokens, i, ctx = {}, firstLineRaw, baseIndent) {
1652
- const startToken = tokens[i];
1653
- const lineNum = startToken.lineNum ?? 0;
1654
- const col = startToken.col ?? 0;
1655
- let hex = "";
1656
- if (firstLineRaw !== undefined) {
1657
- hex += firstLineRaw.replace(/#.*$/, "").replace(/\s/g, "").toLowerCase();
1658
- i++;
1659
- } else {
1660
- i++;
3549
+ function parseReference(s, ctx, lineNum, col) {
3550
+ const schemeEnd = /** @type {number} */ (schemeLengthAt(s, 1));
3551
+ const scheme = s.slice(1, schemeEnd);
3552
+ if (UPPERCASE.test(scheme)) {
3553
+ throw new Error(
3554
+ `Uppercase scheme "${scheme}" in reference (use lowercase)` +
3555
+ locSuffix(ctx, lineNum, col),
3556
+ );
1661
3557
  }
1662
- while (i < tokens.length) {
1663
- const t = tokens[i];
1664
- if (t.type === "break") {
3558
+ let i = schemeEnd;
3559
+ const n = s.length;
3560
+ while (i < n) {
3561
+ const u = s.charCodeAt(i);
3562
+ if (u === 0x3e) {
3563
+ return [detachString(s.slice(1, i)), i + 1];
3564
+ }
3565
+ if (u < 0x80) {
3566
+ if (u === 0x25) {
3567
+ if (!(
3568
+ isHexDigit(s.charCodeAt(i + 1)) && isHexDigit(s.charCodeAt(i + 2))
3569
+ )) {
3570
+ throw new Error(
3571
+ "Bad percent-encoding in reference (use % and two hex digits)" +
3572
+ locSuffix(ctx, lineNum, col + i),
3573
+ );
3574
+ }
3575
+ } else if (URI_ASCII[u] !== 1) {
3576
+ const c = s[i];
3577
+ const message =
3578
+ c === " "
3579
+ ? "Unexpected space in reference"
3580
+ : c === "\t"
3581
+ ? "Tab not allowed in reference"
3582
+ : `Unexpected character "${c}" in reference`;
3583
+ throw new Error(message + locSuffix(ctx, lineNum, col + i));
3584
+ }
1665
3585
  i++;
1666
3586
  continue;
1667
3587
  }
1668
- if (t.type === "text" && (t.indent ?? 0) > baseIndent) {
1669
- hex += t.text.replace(/#.*$/, "").replace(/\s/g, "").toLowerCase();
1670
- i++;
1671
- continue;
3588
+ const c = String.fromCodePoint(/** @type {number} */ (s.codePointAt(i)));
3589
+ if (!isUriChar(c)) {
3590
+ throw new Error(
3591
+ `Unexpected character "${c}" in reference` +
3592
+ locSuffix(ctx, lineNum, col + i),
3593
+ );
1672
3594
  }
1673
- break;
3595
+ i += c.length;
1674
3596
  }
1675
- if (hex.length % 2 !== 0)
3597
+ throw new Error("Unmatched angle bracket" + locSuffix(ctx, lineNum, col));
3598
+ }
3599
+
3600
+ /**
3601
+ * Turn a reference's validated URI text into the caller's value. No default
3602
+ * reference: a document with a reference and no hook is refused, naming the
3603
+ * reference and its location.
3604
+ * @param {string} uri
3605
+ * @param {ParseContext} ctx
3606
+ * @param {number} lineNum
3607
+ * @param {number} col
3608
+ * @returns {unknown}
3609
+ */
3610
+ function decodeReferenceText(uri, ctx, lineNum, col) {
3611
+ const decode = ctx.decodeReference;
3612
+ if (typeof decode !== "function") {
1676
3613
  throw new Error(
1677
- "Odd number of hex digits in byte literal" + locSuffix(ctx, lineNum, col),
3614
+ `Reference ${JSON.stringify(uri)} needs a decodeReference hook` +
3615
+ requiredLocSuffix(ctx, lineNum, col),
1678
3616
  );
1679
- if (!/^[0-9a-f]*$/.test(hex))
1680
- throw new Error("Invalid hex digit" + locSuffix(ctx, lineNum, col));
1681
- const result = Uint8Array.fromHex
1682
- ? Uint8Array.fromHex(hex)
1683
- : hexToUint8Array(hex, ctx, lineNum, col);
1684
- return [result, i];
3617
+ }
3618
+ return decode(uri);
1685
3619
  }
1686
3620
 
1687
- // Note: parseMultilineAngleBytes was removed as dead code.
1688
- // The "< hex" syntax (without closing ">") is invalid - inline byte arrays must be closed on the same line.
1689
-
1690
3621
  /**
1691
- * @param {Token[]} tokens
1692
- * @param {number} i
1693
- * @param {string} key
3622
+ * Turn a symbol name into the caller's representation. parseYay installs
3623
+ * `symbol` as the default hook.
3624
+ * @param {string} name
1694
3625
  * @param {ParseContext} ctx
1695
- * @returns {[Record<string, unknown>, number]}
3626
+ * @returns {unknown}
1696
3627
  */
1697
- function parseObjectOrNamedArray(tokens, i, key, ctx = {}) {
1698
- const keyToken = tokens[i];
1699
- const keyValue = splitKeyValue(
1700
- keyToken.text,
1701
- keyToken.col ?? 0,
1702
- ctx,
1703
- keyToken.lineNum ?? 0,
3628
+ function decodeSymbolText(name, ctx) {
3629
+ return ctx.decodeSymbol(name);
3630
+ }
3631
+
3632
+ /**
3633
+ * Whether a code unit is an ASCII hex digit.
3634
+ * @param {number} c
3635
+ */
3636
+ function isHexDigit(c) {
3637
+ return (
3638
+ (c >= 0x30 && c <= 0x39) ||
3639
+ (c >= 0x61 && c <= 0x66) ||
3640
+ (c >= 0x41 && c <= 0x46)
1704
3641
  );
1705
- i++;
1706
- while (
1707
- i < tokens.length &&
1708
- (tokens[i].type === "break" || tokens[i].type === "stop")
1709
- )
1710
- i++;
1711
- const baseIndent = i < tokens.length ? (tokens[i].indent ?? 0) : 0;
1712
- const first = i < tokens.length ? tokens[i] : null;
1713
- // Check for empty property with no nested content
1714
- if (
1715
- !first ||
1716
- (first.type === "text" && (first.indent ?? 0) <= (keyToken.indent ?? 0))
1717
- ) {
1718
- // Check if the next token is a sibling property (same indent) or parent (lower indent)
1719
- // If so, this property has no value which is invalid
1720
- if (
1721
- !first ||
1722
- (first.type === "text" &&
1723
- splitKeyValue(first.text, first.col ?? 0, ctx, first.lineNum ?? 0))
1724
- ) {
1725
- const col = (keyToken.col ?? 0) + key.length + 1;
1726
- throw new Error(
1727
- "Expected value after property" +
1728
- locSuffix(ctx, keyToken.lineNum ?? 0, col),
1729
- );
1730
- }
1731
- }
1732
- if (first && first.type === "start" && first.text === "-") {
1733
- const [arr] = parseListArray(tokens, i);
1734
- return [{ [key]: arr }, skipToNextKey(tokens, i, baseIndent)];
1735
- }
1736
- // Note: '*' syntax for multiline bytes is rejected by the scanner
1737
- // Note: "key: <" without closing ">" is invalid - inline byte arrays must be closed on the same line
1738
- if (first && first.type === "text" && first.text === '"') {
1739
- const [body, next] = parseBlockStringWithIndent(
1740
- tokens,
1741
- i,
1742
- undefined,
1743
- false,
1744
- -1,
1745
- );
1746
- return [{ [key]: body }, next];
3642
+ }
3643
+
3644
+ // --- The CapData bridge ---
3645
+
3646
+ /**
3647
+ * Walk a YSON value, mapping each string that begins with "$" (a
3648
+ * reference, or a slot) through f. A tagged value's tag is a string, never
3649
+ * a reference, so only its payload is walked.
3650
+ * @param {unknown} value
3651
+ * @param {(s: string, path: string) => string} f
3652
+ * @param {string} path
3653
+ * @returns {unknown}
3654
+ */
3655
+ function mapDollars(value, f, path = "$") {
3656
+ if (typeof value === "string") {
3657
+ return value.startsWith("$") ? f(value, path) : value;
1747
3658
  }
1748
- // Reject block string leader on separate line - must be on same line as key
1749
- if (first && first.type === "text" && first.text.trim() === "`") {
1750
- throw new Error(
1751
- "Unexpected indent" + locSuffix(ctx, first.lineNum ?? 0, 0),
1752
- );
3659
+ if (Array.isArray(value)) {
3660
+ return value.map((v, i) => mapDollars(v, f, `${path}[${i}]`));
1753
3661
  }
1754
- // Concatenated quoted strings (multiple quoted strings on consecutive lines)
1755
- if (first && first.type === "text") {
1756
- const trimmed = first.text.trim();
1757
- if (
1758
- (trimmed.startsWith('"') &&
1759
- trimmed.endsWith('"') &&
1760
- trimmed.length >= 2) ||
1761
- (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2)
1762
- ) {
1763
- const result = parseConcatenatedStrings(tokens, i, baseIndent, ctx);
1764
- if (result !== null) {
1765
- const [concatStr, next] = result;
1766
- return [{ [key]: concatStr }, next];
1767
- }
1768
- // Single string on new line is invalid - fall through to error
1769
- throw new Error(
1770
- "Unexpected indent" + locSuffix(ctx, first.lineNum ?? 0, 0),
3662
+ if (value !== null && typeof value === "object") {
3663
+ const out = {};
3664
+ for (const [k, v] of Object.entries(value)) {
3665
+ setOwn(
3666
+ out,
3667
+ k,
3668
+ k === "#tag" && "payload" in value
3669
+ ? v
3670
+ : mapDollars(v, f, `${path}[${JSON.stringify(k)}]`),
1771
3671
  );
1772
3672
  }
3673
+ return out;
1773
3674
  }
1774
- const obj = {};
1775
- while (i < tokens.length) {
1776
- const t = tokens[i];
1777
- if (t.type === "stop") {
1778
- i++;
1779
- continue;
1780
- }
1781
- if (t.type === "text") {
1782
- const s = t.text;
1783
- // Reject inline values on separate line (they look like keys starting with special chars)
1784
- if (s.startsWith("{") || s.startsWith("[") || s.startsWith("<")) {
1785
- throw new Error(
1786
- "Unexpected indent" + locSuffix(ctx, t.lineNum ?? 0, 0),
1787
- );
1788
- }
1789
- const keyValue = splitKeyValue(s, t.col ?? 0, ctx, t.lineNum ?? 0);
1790
- if (keyValue) {
1791
- const k = keyValue.key;
1792
- const vPart = keyValue.valuePart;
1793
- if ((t.indent ?? 0) < baseIndent) break;
1794
- if (k && (t.indent ?? 0) <= baseIndent && obj.hasOwnProperty(k)) break;
1795
- if (k && (t.indent ?? 0) <= baseIndent && !obj.hasOwnProperty(k)) {
1796
- if (vPart === "{}") {
1797
- obj[k] = {};
1798
- i++;
1799
- } else if (vPart.startsWith(">")) {
1800
- // Block bytes in property context
1801
- if (!isPropertyBlockLeaderOnly(vPart, ">")) {
1802
- throw new Error(
1803
- "Expected newline after block leader in property",
1804
- );
1805
- }
1806
- const [bytes, next] = parseBlockBytes(
1807
- tokens,
1808
- i,
1809
- ctx,
1810
- "",
1811
- t.indent ?? 0,
1812
- );
1813
- obj[k] = bytes;
1814
- i = next;
1815
- } else if (vPart.trim() === "`") {
1816
- // Block string in property context: backtick alone on line
1817
- const [body, next] = parseBlockStringWithIndent(
1818
- tokens,
1819
- i,
1820
- "",
1821
- true,
1822
- t.indent ?? 0,
1823
- );
1824
- obj[k] = body;
1825
- i = next;
1826
- } else if (vPart === "") {
1827
- i++;
1828
- while (i < tokens.length && tokens[i].type === "break") i++;
1829
- const nextT = tokens[i];
1830
- // Note: '*' syntax for multiline bytes is rejected by the scanner
1831
- if (nextT && nextT.type === "text" && nextT.text === '"') {
1832
- const [body, next] = parseBlockStringWithIndent(
1833
- tokens,
1834
- i,
1835
- undefined,
1836
- false,
1837
- -1,
1838
- );
1839
- obj[k] = body;
1840
- i = next;
1841
- } else if (nextT && nextT.type === "start" && nextT.text === "-") {
1842
- const [arr, next] = parseListArray(tokens, i);
1843
- obj[k] = arr;
1844
- i = next;
1845
- } else if (
1846
- nextT &&
1847
- nextT.type === "text" &&
1848
- (nextT.indent ?? 0) > (t.indent ?? 0)
1849
- ) {
1850
- const [child, next] = parseObjectBlock(
1851
- tokens,
1852
- i,
1853
- nextT.indent ?? 0,
1854
- ctx,
1855
- );
1856
- obj[k] = child;
1857
- i = next;
1858
- } else {
1859
- // Empty property with no nested content is invalid
1860
- throw new Error(
1861
- "Expected value after property" +
1862
- locSuffix(ctx, t.lineNum ?? 0, (t.col ?? 0) + k.length + 1),
1863
- );
1864
- }
1865
- } else {
1866
- // Inline value (scalar, array, object, bytes)
1867
- obj[k] = parseScalar(vPart, ctx, t.lineNum ?? 0, keyValue.valueCol);
1868
- i++;
1869
- }
1870
- } else {
1871
- i++;
1872
- }
1873
- } else {
1874
- // Text without colon in nested object context is invalid
1875
- // (e.g., inline array/object/bytes/string on separate line)
1876
- throw new Error(
1877
- "Unexpected indent" + locSuffix(ctx, t.lineNum ?? 0, 0),
1878
- );
1879
- }
1880
- } else {
1881
- i++;
1882
- }
1883
- }
1884
- return [{ [key]: Object.keys(obj).length ? obj : undefined }, i];
3675
+ return value;
1885
3676
  }
1886
3677
 
1887
- function skipToNextKey(tokens, i, baseIndent) {
1888
- while (
1889
- i < tokens.length &&
1890
- tokens[i].type !== "stop" &&
1891
- (tokens[i].indent ?? 0) > baseIndent
1892
- )
1893
- i++;
1894
- while (i < tokens.length && tokens[i].type === "stop") i++;
1895
- return i;
3678
+ /**
3679
+ * JSON text for a JSON value, as JSON.stringify writes it but for negative
3680
+ * zero, which JSON.stringify writes as 0 and YSON and smallcaps write and
3681
+ * read as -0.
3682
+ * @param {unknown} value
3683
+ * @returns {string}
3684
+ */
3685
+ function stringifyJson(value) {
3686
+ if (Object.is(value, -0)) return "-0";
3687
+ if (Array.isArray(value)) {
3688
+ return `[${value.map(stringifyJson).join(",")}]`;
3689
+ }
3690
+ if (value !== null && typeof value === "object") {
3691
+ const members = Object.entries(value).map(
3692
+ ([k, v]) => `${JSON.stringify(k)}:${stringifyJson(v)}`,
3693
+ );
3694
+ return `{${members.join(",")}}`;
3695
+ }
3696
+ return JSON.stringify(value);
1896
3697
  }
1897
3698
 
1898
3699
  /**
1899
- * @param {Token[]} tokens
1900
- * @param {number} i
1901
- * @param {number} baseIndent
1902
- * @param {ParseContext} ctx
1903
- * @param {number=} inlineIndent
1904
- * @returns {[Record<string, unknown>, number]}
3700
+ * From YSON to CapData: each distinct reference goes to `slots` in order of
3701
+ * first appearance, and the body names it `$0`, `$1`, ... as smallcaps
3702
+ * names a remotable. The URI is checked against YAY's reference rule before
3703
+ * the decode hook sees it, and the hook's result goes to `slots`. Without
3704
+ * a hook, a YSON document with a reference is refused, naming the reference
3705
+ * and its JSON path.
3706
+ * @param {string} yson
3707
+ * @param {{decodeReference?: (uri: string) => unknown}=} options
3708
+ * @returns {{body: string, slots: unknown[]}}
1905
3709
  */
1906
- function parseObjectBlock(tokens, i, baseIndent, ctx = {}, inlineIndent) {
1907
- const obj = {};
1908
- let firstText = true;
1909
- while (i < tokens.length) {
1910
- const t = tokens[i];
1911
- if (inlineIndent !== undefined) {
1912
- if (t.type === "stop") break;
1913
- if (t.type === "start" && (t.indent ?? 0) <= inlineIndent) break;
1914
- }
1915
- if (t.type === "stop") {
1916
- i++;
1917
- continue;
1918
- }
1919
- if (t.type !== "text") {
1920
- i++;
1921
- continue;
1922
- }
1923
- let indent = t.indent ?? 0;
1924
- if (firstText && inlineIndent !== undefined && indent === inlineIndent) {
1925
- indent = baseIndent;
1926
- }
1927
- firstText = false;
1928
- if (indent < baseIndent) break;
1929
- if (indent > baseIndent) {
1930
- i++;
1931
- continue;
1932
- }
1933
- const keyValue = splitKeyValue(t.text, t.col ?? 0, ctx, t.lineNum ?? 0);
1934
- if (!keyValue) {
1935
- i++;
1936
- continue;
1937
- }
1938
- const k = keyValue.key;
1939
- const vPart = keyValue.valuePart;
1940
- // Note: "key: <" without closing ">" is invalid - inline byte arrays must be closed on the same line
1941
- if (vPart.startsWith(">")) {
1942
- if (!isPropertyBlockLeaderOnly(vPart, ">")) {
1943
- throw new Error("Expected newline after block leader in property");
1944
- }
1945
- const [bytes, j] = parseBlockBytes(tokens, i, ctx, "", baseIndent);
1946
- obj[k] = bytes;
1947
- i = j;
1948
- continue;
3710
+ function ysonToCapData(yson, options = {}) {
3711
+ const decodeReference = options.decodeReference;
3712
+ if (decodeReference !== undefined && typeof decodeReference !== "function") {
3713
+ throw new TypeError("decodeReference must be a function");
3714
+ }
3715
+ /** @type {unknown[]} */
3716
+ const slots = [];
3717
+ const index = new Map();
3718
+ const parsed = JSON.parse(yson);
3719
+ checkWellFormedDeep(parsed);
3720
+ const body = mapDollars(parsed, (s, path) => {
3721
+ const uri = s.slice(1);
3722
+ if (!isReferenceStart(`<${uri}`)) {
3723
+ throw new Error(
3724
+ `A reference needs a scheme: ${JSON.stringify(s)} at ${path}`,
3725
+ );
1949
3726
  }
1950
- if (vPart === "{}") {
1951
- obj[k] = {};
1952
- i++;
1953
- continue;
3727
+ const text = `<${uri}>`;
3728
+ let consumed;
3729
+ try {
3730
+ [, consumed] = parseReference(text, {}, 0, 0);
3731
+ } catch (error) {
3732
+ throw new Error(`${/** @type {Error} */ (error).message} at ${path}`);
1954
3733
  }
1955
- // Block string in property context: backtick alone on line
1956
- if (vPart.trim() === "`") {
1957
- const [body, next] = parseBlockStringWithIndent(
1958
- tokens,
1959
- i,
1960
- "",
1961
- true,
1962
- t.indent ?? 0,
3734
+ if (consumed !== text.length) {
3735
+ throw new Error(
3736
+ `Unexpected character ">" in reference: ${JSON.stringify(s)} at ${path}`,
1963
3737
  );
1964
- obj[k] = body;
1965
- i = next;
1966
- continue;
1967
3738
  }
1968
- if (vPart === "") {
1969
- i++;
1970
- while (
1971
- i < tokens.length &&
1972
- (tokens[i].type === "break" || tokens[i].type === "stop")
1973
- )
1974
- i++;
1975
- const nextT = tokens[i];
1976
- if (nextT && nextT.type === "start" && nextT.text === "-") {
1977
- // Pass baseIndent as minIndent so nested arrays stop at the object's level
1978
- const [arr, next] = parseListArray(tokens, i, ctx, baseIndent);
1979
- obj[k] = arr;
1980
- i = next;
1981
- continue;
1982
- }
1983
- // Note: "key: <" without closing ">" is invalid - inline byte arrays must be closed on the same line
1984
- // Note: A line with just '"' is not valid - block strings use backtick (`)
1985
- if (nextT && nextT.type === "text" && (nextT.indent ?? 0) > baseIndent) {
1986
- const [child, next] = parseObjectBlock(
1987
- tokens,
1988
- i,
1989
- nextT.indent ?? 0,
1990
- ctx,
3739
+ let slot = index.get(uri);
3740
+ if (slot === undefined) {
3741
+ if (typeof decodeReference !== "function") {
3742
+ throw new Error(
3743
+ `Reference ${JSON.stringify(uri)} needs a decodeReference hook ` +
3744
+ `at ${path}`,
1991
3745
  );
1992
- obj[k] = child;
1993
- i = next;
1994
- continue;
1995
3746
  }
1996
- // Empty property with no nested content is handled by parseObjectOrNamedArray
1997
- // which throws an error before we reach here
1998
- continue;
3747
+ slot = slots.length;
3748
+ index.set(uri, slot);
3749
+ slots.push(decodeReference(uri));
1999
3750
  }
2000
- // Inline value (scalar, array, object, bytes)
2001
- obj[k] = parseScalar(vPart, ctx, t.lineNum ?? 0, keyValue.valueCol);
2002
- i++;
2003
- }
2004
- return [obj, i];
3751
+ return `$${slot}`;
3752
+ });
3753
+ return { body: `#${stringifyJson(body)}`, slots };
2005
3754
  }
2006
3755
 
2007
- // Root as object (multiple key: value lines at indent 0)
2008
3756
  /**
2009
- * @param {Token[]} tokens
2010
- * @param {number} i
2011
- * @param {ParseContext} ctx
2012
- * @returns {[Record<string, unknown>, number]}
3757
+ * From CapData to YSON: the reverse of ysonToCapData. Each `$n` (with or
3758
+ * without smallcaps' interface, `$n.Alleged: x`, which YAY does not keep)
3759
+ * becomes `"$" + slots[n]`. A slot that is already URI text is checked and
3760
+ * used; any other slot is the caller's value, which the encode hook turns
3761
+ * back into URI text. URI text is checked after the hook returns. A body
3762
+ * with promises (`&n`) is refused.
3763
+ * @param {{body: string, slots: unknown[]}} capData
3764
+ * @param {{encodeReference?: (value: unknown) => string}=} options
3765
+ * @returns {string}
2013
3766
  */
2014
- function parseRootObject(tokens, i, ctx = {}) {
2015
- const obj = {};
2016
- const baseIndent = 0;
2017
- while (i < tokens.length) {
2018
- const t = tokens[i];
2019
- if (t.type === "stop") {
2020
- i++;
2021
- continue;
2022
- }
2023
- if (t.type === "text") {
2024
- const s = t.text;
2025
- const keyValue = splitKeyValue(s, t.col ?? 0, ctx, t.lineNum ?? 0);
2026
- if (keyValue && (t.indent ?? 0) === baseIndent) {
2027
- const k = keyValue.key;
2028
- const vPart = keyValue.valuePart;
2029
- // Note: "key: <" without closing ">" is invalid - inline byte arrays must be closed on the same line
2030
- if (vPart.startsWith(">")) {
2031
- if (!isPropertyBlockLeaderOnly(vPart, ">")) {
2032
- throw new Error("Expected newline after block leader in property");
2033
- }
2034
- const [bytes, j] = parseBlockBytes(tokens, i, ctx, "", baseIndent);
2035
- obj[k] = bytes;
2036
- i = j;
2037
- } else if (vPart === "{}") {
2038
- obj[k] = {};
2039
- i++;
2040
- // Note: "key: \"" is an unterminated string error, not a block string
2041
- // Block strings use backtick (`) not double-quote (")
2042
- } else if (vPart.startsWith("`")) {
2043
- if (!isPropertyBlockLeaderOnly(vPart, "`")) {
2044
- throw new Error("Expected newline after block leader in property");
2045
- }
2046
- i++;
2047
- while (
2048
- i < tokens.length &&
2049
- (tokens[i].type === "break" || tokens[i].type === "stop")
2050
- )
2051
- i++;
2052
- const nextT = tokens[i];
2053
- if (nextT && nextT.type === "text" && nextT.text === "`") {
2054
- // Empty block string (just opening and closing backticks) is not allowed
2055
- throw new Error(
2056
- 'Empty block string not allowed (use "" or "\\n" explicitly)',
2057
- );
2058
- } else {
2059
- const withIndent = [];
2060
- while (
2061
- i < tokens.length &&
2062
- ((tokens[i].type === "text" &&
2063
- (tokens[i].indent ?? 0) > baseIndent) ||
2064
- tokens[i].type === "break")
2065
- ) {
2066
- if (tokens[i].type === "break") {
2067
- withIndent.push({ indent: undefined, text: "" });
2068
- i++;
2069
- } else {
2070
- withIndent.push({
2071
- indent: tokens[i].indent ?? 0,
2072
- text: tokens[i].text,
2073
- });
2074
- i++;
2075
- }
2076
- }
2077
- const minIndent = withIndent
2078
- .filter((x) => x.indent !== undefined)
2079
- .reduce((min, x) => (x.indent < min ? x.indent : min), Infinity);
2080
- const effectiveMin = minIndent === Infinity ? 0 : minIndent;
2081
- const bodyLines = withIndent.map(({ indent, text }) =>
2082
- indent === undefined
2083
- ? ""
2084
- : (indent - effectiveMin > 0
2085
- ? " ".repeat(indent - effectiveMin)
2086
- : "") + text,
2087
- );
2088
- let endLine = bodyLines.length;
2089
- while (endLine > 0 && bodyLines[endLine - 1] === "") endLine--;
2090
- const trimmedLines = bodyLines.slice(0, endLine);
2091
- obj[k] =
2092
- trimmedLines.join("\n") + (trimmedLines.length > 0 ? "\n" : "");
2093
- }
2094
- } else if (vPart === "") {
2095
- const [valueObj, next] = parseObjectOrNamedArray(tokens, i, k, ctx);
2096
- obj[k] = valueObj[k];
2097
- i = next;
2098
- } else {
2099
- // Inline value (scalar, array, object, bytes)
2100
- obj[k] = parseScalar(vPart, ctx, t.lineNum ?? 0, keyValue.valueCol);
2101
- i++;
2102
- }
2103
- } else {
2104
- i++;
2105
- }
3767
+ function capDataToYson({ body, slots }, options = {}) {
3768
+ const encodeReference = options.encodeReference;
3769
+ if (encodeReference !== undefined && typeof encodeReference !== "function") {
3770
+ throw new TypeError("encodeReference must be a function");
3771
+ }
3772
+ if (!body.startsWith("#")) {
3773
+ throw new Error("Expected a smallcaps body, beginning with #");
3774
+ }
3775
+ const value = JSON.parse(body.slice(1));
3776
+ // A string, key, tag or symbol name with a lone surrogate has no YAY form
3777
+ checkWellFormedDeep(value);
3778
+ const check = (v) => {
3779
+ if (typeof v === "string" && v.startsWith("&")) {
3780
+ throw new Error(`A promise has no YAY form: ${JSON.stringify(v)}`);
3781
+ }
3782
+ if (Array.isArray(v)) v.forEach(check);
3783
+ else if (v !== null && typeof v === "object") {
3784
+ Object.values(v).forEach(check);
3785
+ }
3786
+ };
3787
+ check(value);
3788
+ const yson = mapDollars(value, (s) => {
3789
+ const match = /^\$(0|[1-9][0-9]*)(\..*)?$/.exec(s);
3790
+ const n = match ? Number(match[1]) : -1;
3791
+ if (n < 0 || n >= slots.length) {
3792
+ throw new Error(`No slot for ${JSON.stringify(s)}`);
3793
+ }
3794
+ const slot = slots[n];
3795
+ let uri;
3796
+ if (typeof encodeReference === "function") {
3797
+ uri = encodeReference(slot);
3798
+ } else if (typeof slot === "string") {
3799
+ uri = slot;
2106
3800
  } else {
2107
- i++;
3801
+ throw new Error(`Reference slot ${n} needs an encodeReference hook`);
2108
3802
  }
2109
- }
2110
- return [obj, i];
3803
+ if (typeof uri !== "string") {
3804
+ throw new TypeError(`encodeReference must return a string for slot ${n}`);
3805
+ }
3806
+ // A slot is a reference's text, as YSON's "$" strings are
3807
+ checkReferenceText(uri);
3808
+ return `$${uri}`;
3809
+ });
3810
+ return stringifyJson(yson);
2111
3811
  }
2112
3812
 
2113
- export { parseYay };
3813
+ export {
3814
+ parseYay,
3815
+ isWellFormedString,
3816
+ symbol,
3817
+ isSymbol,
3818
+ tagged,
3819
+ isTagged,
3820
+ reference,
3821
+ isReference,
3822
+ Reference,
3823
+ ysonToCapData,
3824
+ capDataToYson,
3825
+ };