@rohal12/spindle 0.64.30 → 0.64.32

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.
@@ -10377,6 +10377,201 @@ function completionIdentifier(source, cursor, goal = "expression") {
10377
10377
  previous = token;
10378
10378
  }
10379
10379
  }
10380
+ // src/components/macros/arg-utils.ts
10381
+ /**
10382
+ * Shared helpers for macros that split or read their raw argument text by
10383
+ * hand. Their lexical model is the expression lexer's (`js-lexer.ts`):
10384
+ * string, template and regex literals and comments are opaque (a backslash
10385
+ * inside a literal escapes the character after it, and `${…}` parts of a
10386
+ * template are code), `/` opens a regex only where an operand is expected,
10387
+ * and `(`/`[`/`{` nest.
10388
+ */
10389
+ /** True for a whitespace character. */
10390
+ function isWhitespace(ch) {
10391
+ return /\s/.test(ch);
10392
+ }
10393
+ function isOpener(ch) {
10394
+ return ch === "(" || ch === "[" || ch === "{";
10395
+ }
10396
+ function isCloser(ch) {
10397
+ return ch === ")" || ch === "]" || ch === "}";
10398
+ }
10399
+ /**
10400
+ * Undo the escapes allowed in a literal quoted macro argument: `\"`, `\'`
10401
+ * and `\\` become `"`, `'` and `\`. Other backslash sequences (`\n`, `\d`)
10402
+ * are kept as written, so code and regex text inside the string survive.
10403
+ */
10404
+ function unescapeQuoted(body) {
10405
+ return body.replace(/\\(["'\\])/g, "$1");
10406
+ }
10407
+ /**
10408
+ * Read the `"…"` or `'…'` string whose opening quote is at `start`.
10409
+ * Returns its unescaped value and the index just past the closing quote, or
10410
+ * `null` if there is no such quote at `start` or the string is unterminated.
10411
+ * With `tolerant`, an unterminated string instead extends to its scanned end.
10412
+ */
10413
+ function readQuoted(src, start, tolerant = false) {
10414
+ const quote = src[start];
10415
+ if (quote !== "\"" && quote !== "'") return null;
10416
+ const { end, closed } = scanStringLiteral(src, start);
10417
+ if (!closed && !tolerant) return null;
10418
+ return {
10419
+ value: unescapeQuoted(src.slice(start + 1, closed ? end - 1 : end)),
10420
+ end
10421
+ };
10422
+ }
10423
+ /**
10424
+ * The unescaped value of `src` when it is exactly one `"…"` or `'…'` string
10425
+ * (as with `readQuoted`), otherwise `null`.
10426
+ */
10427
+ function readWholeQuoted(src) {
10428
+ const quoted = readQuoted(src, 0);
10429
+ return quoted && quoted.end === src.length ? quoted.value : null;
10430
+ }
10431
+ /** A dialog body's passage name, optionally enclosed in matching quotes. */
10432
+ function readPassageBody(src) {
10433
+ const name = src.trim();
10434
+ return readWholeQuoted(name) ?? name;
10435
+ }
10436
+ /**
10437
+ * Strip an optional quote from each end of an unquoted-or-loosely-quoted
10438
+ * argument (`"Red`, `Red'`), leaving at least one character. This is the
10439
+ * lenient fallback for labels that are not one well-formed quoted string.
10440
+ */
10441
+ function stripLooseQuotes(src) {
10442
+ return /^["']?(.+?)["']?$/s.exec(src)?.[1] ?? src;
10443
+ }
10444
+ /** An operator character, or an operator keyword, at the end of code. */
10445
+ var TRAILING_OPERATOR_RE = /(?:[-+*/%&|^!~=<>?:,.]|(?:^|[^\w$@.])(?:typeof|void|new|delete|in|instanceof|await|yield))$/;
10446
+ /**
10447
+ * Whether `src` ends with an operator that still needs an operand (`$a +`,
10448
+ * `$a+`, `$x ==`, `typeof`), so it cannot be a complete value on its own.
10449
+ * Only code counts: the closing `/` of a regex literal is not division, a
10450
+ * variable reference (`$a`, `%name`, ...) is an operand, trailing comments are skipped,
10451
+ * and a postfix `++` or `--` completes its operand.
10452
+ */
10453
+ function endsWithOperator(src) {
10454
+ let end = -1;
10455
+ lexJs(src, {
10456
+ code(ch, i, nesting) {
10457
+ if (nesting === 0 && !isWhitespace(ch)) end = i + 1;
10458
+ },
10459
+ literal(text, _i, nesting) {
10460
+ const comment = text.startsWith("//") || text.startsWith("/*");
10461
+ if (nesting === 0 && !comment) end = -1;
10462
+ },
10463
+ variable(_sigil, _name, _i, nesting) {
10464
+ if (nesting === 0) end = -1;
10465
+ }
10466
+ });
10467
+ if (end < 0) return false;
10468
+ const code = src.slice(0, end);
10469
+ if (/(?:\+\+|--)$/.test(code)) return false;
10470
+ return TRAILING_OPERATOR_RE.test(code);
10471
+ }
10472
+ /**
10473
+ * Indices of the characters in `src` that satisfy `isSeparator` and sit at
10474
+ * depth 0: in code outside string, template and regex literals and comments,
10475
+ * and outside `()`, `[]` and `{}` pairs.
10476
+ */
10477
+ function topLevelIndices(src, isSeparator) {
10478
+ const indices = [];
10479
+ let depth = 0;
10480
+ lexJs(src, { code(ch, i, nesting) {
10481
+ if (nesting > 0) return;
10482
+ if (isOpener(ch)) depth++;
10483
+ else if (isCloser(ch)) depth--;
10484
+ else if (depth === 0 && isSeparator(ch)) indices.push(i);
10485
+ } });
10486
+ return indices;
10487
+ }
10488
+ /**
10489
+ * The segments of `src` between its depth-0 separators (see
10490
+ * `topLevelIndices`), as spans: untrimmed, and empty segments are kept, so
10491
+ * `n` separators always give `n + 1` segments.
10492
+ */
10493
+ function topLevelSpans(src, isSeparator) {
10494
+ const spans = [];
10495
+ let from = 0;
10496
+ for (const i of topLevelIndices(src, isSeparator)) {
10497
+ spans.push([from, i]);
10498
+ from = i + 1;
10499
+ }
10500
+ spans.push([from, src.length]);
10501
+ return spans;
10502
+ }
10503
+ /**
10504
+ * Split `src` at every depth-0 separator (see `topLevelIndices`). Segments
10505
+ * are returned as written, untrimmed, and empty segments are kept, so
10506
+ * `n` separators always give `n + 1` segments.
10507
+ */
10508
+ function splitTopLevel(src, isSeparator) {
10509
+ return topLevelSpans(src, isSeparator).map(([a, b]) => src.slice(a, b));
10510
+ }
10511
+ /**
10512
+ * Check whether a whitespace-delimited token looks like a standalone value
10513
+ * (not an operator or partial expression): it starts like a value and does
10514
+ * not end with an operator still waiting for its operand.
10515
+ */
10516
+ function isStandaloneValue(token) {
10517
+ return startsLikeValue(token) && !endsWithOperator(token);
10518
+ }
10519
+ function startsLikeValue(token) {
10520
+ const first = token[0];
10521
+ if (first === "\"" || first === "'" || first === "`") return true;
10522
+ if (/^[$_@]\w|^%[A-Za-z_]/.test(token)) return true;
10523
+ if (/^[+-]?(?:\d|\.\d)/.test(token)) return true;
10524
+ if (first === "(" || first === "[" || first === "{") return true;
10525
+ if (/^(?:true|false|null|undefined)(?![\w$])/.test(token)) return true;
10526
+ if (first === "!" && token.length > 1 && token[1] !== "=") return true;
10527
+ return false;
10528
+ }
10529
+ /**
10530
+ * Try to split a raw string on whitespace at depth 0 (respecting strings,
10531
+ * template literals, parentheses, brackets, and braces). Each resulting token
10532
+ * must pass `isStandaloneValue()` or the split is rejected and `null` is
10533
+ * returned. The spans are those of the tokens in `raw`.
10534
+ */
10535
+ function trySplitOnWhitespace(raw) {
10536
+ const args = topLevelSpans(raw, isWhitespace).filter(([a, b]) => b > a);
10537
+ if (args.length < 2) return null;
10538
+ for (const [a, b] of args) if (!isStandaloneValue(raw.slice(a, b))) return null;
10539
+ return args;
10540
+ }
10541
+ /** `span` less the whitespace at its ends. */
10542
+ function trimmed$1(src, [start, end]) {
10543
+ const text = src.slice(start, end);
10544
+ const lead = text.length - text.trimStart().length;
10545
+ return [start + lead, Math.max(start + lead, end - (text.length - text.trimEnd().length))];
10546
+ }
10547
+ /**
10548
+ * Where the arguments in `raw` are written (see `splitArgs`), as spans of
10549
+ * `raw`.
10550
+ */
10551
+ function splitArgSpans(raw) {
10552
+ const args = topLevelSpans(raw, (ch) => ch === ",").map((span) => trimmed$1(raw, span));
10553
+ const hasComma = args.length > 1;
10554
+ const last = args[args.length - 1];
10555
+ if (last[0] === last[1]) args.pop();
10556
+ if (!hasComma && args.length === 1) {
10557
+ const [start, end] = args[0];
10558
+ const split = trySplitOnWhitespace(raw.slice(start, end));
10559
+ if (split) return split.map(([a, b]) => [start + a, start + b]);
10560
+ }
10561
+ return args;
10562
+ }
10563
+ /**
10564
+ * Split rawArgs by commas, respecting parentheses, brackets, braces, and
10565
+ * strings. When no top-level commas are present, also supports adjacent quoted
10566
+ * string literals separated by whitespace (e.g. `"Label" "target"`).
10567
+ */
10568
+ function splitArgs(raw) {
10569
+ return splitArgSpans(raw).map(([a, b]) => raw.slice(a, b));
10570
+ }
10571
+ /** `text` as a regular expression source that matches it literally. */
10572
+ function escapeRegExp(text) {
10573
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
10574
+ }
10380
10575
  // src/markup/code-end.ts
10381
10576
  /**
10382
10577
  * A quote directly after a letter/digit is an apostrophe (don't), not a
@@ -10481,6 +10676,8 @@ function scanLenient(input, start) {
10481
10676
  * input (see `OnOpenCodeEnd`); the ends it finds are the same.
10482
10677
  */
10483
10678
  function jsCodeEnd(onOpenEnd) {
10679
+ let indexedInput = "";
10680
+ const rawClosers = /* @__PURE__ */ new Map();
10484
10681
  return {
10485
10682
  closeBrace(input, codeStart, lenientStart) {
10486
10683
  let ranOut = false;
@@ -10491,10 +10688,18 @@ function jsCodeEnd(onOpenEnd) {
10491
10688
  return end;
10492
10689
  },
10493
10690
  rawBodyEnd(input, bodyStart, name) {
10494
- const closer = `\\{/${name}\\s*\\}`;
10495
- const first = new RegExp(closer, "gi");
10496
- first.lastIndex = bodyStart;
10497
- const firstAt = first.exec(input)?.index ?? -1;
10691
+ if (indexedInput !== input) {
10692
+ indexedInput = input;
10693
+ rawClosers.clear();
10694
+ }
10695
+ name = name.toLowerCase();
10696
+ const closer = `\\{/${escapeRegExp(name)}\\s*\\}`;
10697
+ let candidates = rawClosers.get(name);
10698
+ if (!candidates) {
10699
+ candidates = Array.from(input.matchAll(new RegExp(closer, "gi")), (m) => m.index);
10700
+ rawClosers.set(name, candidates);
10701
+ }
10702
+ const firstAt = candidates[upperBound(candidates, bodyStart - 1)] ?? -1;
10498
10703
  if (firstAt === -1) return -1;
10499
10704
  const at = new RegExp(closer, "iy");
10500
10705
  let ranOut = false;
@@ -10507,7 +10712,7 @@ function jsCodeEnd(onOpenEnd) {
10507
10712
  onRunOut: () => ranOut = true
10508
10713
  });
10509
10714
  if (end !== -1) return end;
10510
- if (onOpenEnd && (ranOut || new RegExp(`\\{/${name}\\s*$`, "i").test(input))) onOpenEnd(input, bodyStart);
10715
+ if (onOpenEnd && (ranOut || new RegExp(`\\{/${escapeRegExp(name)}\\s*$`, "i").test(input))) onOpenEnd(input, bodyStart);
10511
10716
  return firstAt;
10512
10717
  }
10513
10718
  };
@@ -10516,12 +10721,13 @@ function jsCodeEnd(onOpenEnd) {
10516
10721
  var defaultCodeEnd = jsCodeEnd();
10517
10722
  /**
10518
10723
  * Index possible brace ends for repeated recovery attempts in one template.
10519
- * Within plain code, nested braces must close first. At a quote, slash or
10520
- * escape we stop making lexical assumptions, but the remaining raw `}`s
10521
- * still bound how many pending braces could close. Indexing visits each
10522
- * opener once, so unmatched plain-code openers can skip suffix scans.
10724
+ * Within plain code, nested braces must close first. At a quote, slash,
10725
+ * escape or HTML-style comment we stop making lexical assumptions, but the
10726
+ * remaining raw `}`s still bound how many pending braces could close.
10727
+ * Indexing visits each opener once, so unmatched plain-code openers can
10728
+ * skip suffix scans.
10523
10729
  */
10524
- function indexCodeEnds(input) {
10730
+ function indexCodeEnds(input, closeBrace = defaultCodeEnd.closeBrace) {
10525
10731
  const possible = /* @__PURE__ */ new Set();
10526
10732
  const pending = [];
10527
10733
  let remaining = 0;
@@ -10541,17 +10747,39 @@ function indexCodeEnds(input) {
10541
10747
  remaining--;
10542
10748
  const open = pending.pop();
10543
10749
  if (open !== void 0) possible.add(open);
10544
- } else if (/['"`/\\]/.test(c)) uncertain();
10750
+ } else if (/['"`/\\]/.test(c) || input.startsWith("<!--", i) || input.startsWith("-->", i)) uncertain();
10545
10751
  }
10546
10752
  return (start, codeStart = start, limit = input.length) => {
10547
10753
  if (start > lastBrace || codeStart >= limit) return -1;
10548
10754
  const source = limit === input.length ? input : input.slice(0, limit);
10549
- if (input[start - 1] !== "{" || possible.has(start - 1) || input.slice(start, codeStart).includes("{")) return defaultCodeEnd.closeBrace(source, codeStart, start);
10755
+ if (input[start - 1] !== "{" || possible.has(start - 1) || input.slice(start, codeStart).includes("{")) return closeBrace(source, codeStart, start);
10550
10756
  const base = Math.max(0, codeStart - 1);
10551
10757
  const end = parsedCodeEnd(source.slice(base), codeStart - base, "expression");
10552
10758
  return end < 0 ? -1 : base + end;
10553
10759
  };
10554
10760
  }
10761
+ /**
10762
+ * Reusable strict expression-boundary queries over one immutable source.
10763
+ * Results match `findCodeEnd(input, start)`, without markup's lenient
10764
+ * fallback. The shared brace index prunes unmatched plain-code prefixes;
10765
+ * each queried start is cached independently, including failed queries.
10766
+ */
10767
+ function indexStrictCodeEnds(input) {
10768
+ const read = indexCodeEnds(input, (source, start) => {
10769
+ const base = Math.max(0, start - 1);
10770
+ const end = findCodeEnd(source.slice(base), start - base);
10771
+ return end < 0 ? -1 : base + end;
10772
+ });
10773
+ const ends = /* @__PURE__ */ new Map();
10774
+ return (start) => {
10775
+ let end = ends.get(start);
10776
+ if (end === void 0) {
10777
+ end = read(start);
10778
+ ends.set(start, end);
10779
+ }
10780
+ return end;
10781
+ };
10782
+ }
10555
10783
  // src/markup/code-attributes.ts
10556
10784
  /**
10557
10785
  * Attributes whose value is code with braces of its own, not text: event
@@ -10924,201 +11152,6 @@ function ownEntries(sources, keep = () => true) {
10924
11152
  /** A namespace with no prototype holding the own entries of `sources`. */
10925
11153
  var createNamespace = (...sources) => ownEntries(sources);
10926
11154
  Object.freeze(createNamespace());
10927
- // src/components/macros/arg-utils.ts
10928
- /**
10929
- * Shared helpers for macros that split or read their raw argument text by
10930
- * hand. Their lexical model is the expression lexer's (`js-lexer.ts`):
10931
- * string, template and regex literals and comments are opaque (a backslash
10932
- * inside a literal escapes the character after it, and `${…}` parts of a
10933
- * template are code), `/` opens a regex only where an operand is expected,
10934
- * and `(`/`[`/`{` nest.
10935
- */
10936
- /** True for a whitespace character. */
10937
- function isWhitespace(ch) {
10938
- return /\s/.test(ch);
10939
- }
10940
- function isOpener(ch) {
10941
- return ch === "(" || ch === "[" || ch === "{";
10942
- }
10943
- function isCloser(ch) {
10944
- return ch === ")" || ch === "]" || ch === "}";
10945
- }
10946
- /**
10947
- * Undo the escapes allowed in a literal quoted macro argument: `\"`, `\'`
10948
- * and `\\` become `"`, `'` and `\`. Other backslash sequences (`\n`, `\d`)
10949
- * are kept as written, so code and regex text inside the string survive.
10950
- */
10951
- function unescapeQuoted(body) {
10952
- return body.replace(/\\(["'\\])/g, "$1");
10953
- }
10954
- /**
10955
- * Read the `"…"` or `'…'` string whose opening quote is at `start`.
10956
- * Returns its unescaped value and the index just past the closing quote, or
10957
- * `null` if there is no such quote at `start` or the string is unterminated.
10958
- * With `tolerant`, an unterminated string instead extends to its scanned end.
10959
- */
10960
- function readQuoted(src, start, tolerant = false) {
10961
- const quote = src[start];
10962
- if (quote !== "\"" && quote !== "'") return null;
10963
- const { end, closed } = scanStringLiteral(src, start);
10964
- if (!closed && !tolerant) return null;
10965
- return {
10966
- value: unescapeQuoted(src.slice(start + 1, closed ? end - 1 : end)),
10967
- end
10968
- };
10969
- }
10970
- /**
10971
- * The unescaped value of `src` when it is exactly one `"…"` or `'…'` string
10972
- * (as with `readQuoted`), otherwise `null`.
10973
- */
10974
- function readWholeQuoted(src) {
10975
- const quoted = readQuoted(src, 0);
10976
- return quoted && quoted.end === src.length ? quoted.value : null;
10977
- }
10978
- /** A dialog body's passage name, optionally enclosed in matching quotes. */
10979
- function readPassageBody(src) {
10980
- const name = src.trim();
10981
- return readWholeQuoted(name) ?? name;
10982
- }
10983
- /**
10984
- * Strip an optional quote from each end of an unquoted-or-loosely-quoted
10985
- * argument (`"Red`, `Red'`), leaving at least one character. This is the
10986
- * lenient fallback for labels that are not one well-formed quoted string.
10987
- */
10988
- function stripLooseQuotes(src) {
10989
- return /^["']?(.+?)["']?$/s.exec(src)?.[1] ?? src;
10990
- }
10991
- /** An operator character, or an operator keyword, at the end of code. */
10992
- var TRAILING_OPERATOR_RE = /(?:[-+*/%&|^!~=<>?:,.]|(?:^|[^\w$@.])(?:typeof|void|new|delete|in|instanceof|await|yield))$/;
10993
- /**
10994
- * Whether `src` ends with an operator that still needs an operand (`$a +`,
10995
- * `$a+`, `$x ==`, `typeof`), so it cannot be a complete value on its own.
10996
- * Only code counts: the closing `/` of a regex literal is not division, a
10997
- * variable reference (`$a`, `%name`, ...) is an operand, trailing comments are skipped,
10998
- * and a postfix `++` or `--` completes its operand.
10999
- */
11000
- function endsWithOperator(src) {
11001
- let end = -1;
11002
- lexJs(src, {
11003
- code(ch, i, nesting) {
11004
- if (nesting === 0 && !isWhitespace(ch)) end = i + 1;
11005
- },
11006
- literal(text, _i, nesting) {
11007
- const comment = text.startsWith("//") || text.startsWith("/*");
11008
- if (nesting === 0 && !comment) end = -1;
11009
- },
11010
- variable(_sigil, _name, _i, nesting) {
11011
- if (nesting === 0) end = -1;
11012
- }
11013
- });
11014
- if (end < 0) return false;
11015
- const code = src.slice(0, end);
11016
- if (/(?:\+\+|--)$/.test(code)) return false;
11017
- return TRAILING_OPERATOR_RE.test(code);
11018
- }
11019
- /**
11020
- * Indices of the characters in `src` that satisfy `isSeparator` and sit at
11021
- * depth 0: in code outside string, template and regex literals and comments,
11022
- * and outside `()`, `[]` and `{}` pairs.
11023
- */
11024
- function topLevelIndices(src, isSeparator) {
11025
- const indices = [];
11026
- let depth = 0;
11027
- lexJs(src, { code(ch, i, nesting) {
11028
- if (nesting > 0) return;
11029
- if (isOpener(ch)) depth++;
11030
- else if (isCloser(ch)) depth--;
11031
- else if (depth === 0 && isSeparator(ch)) indices.push(i);
11032
- } });
11033
- return indices;
11034
- }
11035
- /**
11036
- * The segments of `src` between its depth-0 separators (see
11037
- * `topLevelIndices`), as spans: untrimmed, and empty segments are kept, so
11038
- * `n` separators always give `n + 1` segments.
11039
- */
11040
- function topLevelSpans(src, isSeparator) {
11041
- const spans = [];
11042
- let from = 0;
11043
- for (const i of topLevelIndices(src, isSeparator)) {
11044
- spans.push([from, i]);
11045
- from = i + 1;
11046
- }
11047
- spans.push([from, src.length]);
11048
- return spans;
11049
- }
11050
- /**
11051
- * Split `src` at every depth-0 separator (see `topLevelIndices`). Segments
11052
- * are returned as written, untrimmed, and empty segments are kept, so
11053
- * `n` separators always give `n + 1` segments.
11054
- */
11055
- function splitTopLevel(src, isSeparator) {
11056
- return topLevelSpans(src, isSeparator).map(([a, b]) => src.slice(a, b));
11057
- }
11058
- /**
11059
- * Check whether a whitespace-delimited token looks like a standalone value
11060
- * (not an operator or partial expression): it starts like a value and does
11061
- * not end with an operator still waiting for its operand.
11062
- */
11063
- function isStandaloneValue(token) {
11064
- return startsLikeValue(token) && !endsWithOperator(token);
11065
- }
11066
- function startsLikeValue(token) {
11067
- const first = token[0];
11068
- if (first === "\"" || first === "'" || first === "`") return true;
11069
- if (/^[$_@]\w|^%[A-Za-z_]/.test(token)) return true;
11070
- if (/^[+-]?(?:\d|\.\d)/.test(token)) return true;
11071
- if (first === "(" || first === "[" || first === "{") return true;
11072
- if (/^(?:true|false|null|undefined)(?![\w$])/.test(token)) return true;
11073
- if (first === "!" && token.length > 1 && token[1] !== "=") return true;
11074
- return false;
11075
- }
11076
- /**
11077
- * Try to split a raw string on whitespace at depth 0 (respecting strings,
11078
- * template literals, parentheses, brackets, and braces). Each resulting token
11079
- * must pass `isStandaloneValue()` or the split is rejected and `null` is
11080
- * returned. The spans are those of the tokens in `raw`.
11081
- */
11082
- function trySplitOnWhitespace(raw) {
11083
- const args = topLevelSpans(raw, isWhitespace).filter(([a, b]) => b > a);
11084
- if (args.length < 2) return null;
11085
- for (const [a, b] of args) if (!isStandaloneValue(raw.slice(a, b))) return null;
11086
- return args;
11087
- }
11088
- /** `span` less the whitespace at its ends. */
11089
- function trimmed$1(src, [start, end]) {
11090
- const text = src.slice(start, end);
11091
- const lead = text.length - text.trimStart().length;
11092
- return [start + lead, Math.max(start + lead, end - (text.length - text.trimEnd().length))];
11093
- }
11094
- /**
11095
- * Where the arguments in `raw` are written (see `splitArgs`), as spans of
11096
- * `raw`.
11097
- */
11098
- function splitArgSpans(raw) {
11099
- const args = topLevelSpans(raw, (ch) => ch === ",").map((span) => trimmed$1(raw, span));
11100
- const hasComma = args.length > 1;
11101
- const last = args[args.length - 1];
11102
- if (last[0] === last[1]) args.pop();
11103
- if (!hasComma && args.length === 1) {
11104
- const [start, end] = args[0];
11105
- const split = trySplitOnWhitespace(raw.slice(start, end));
11106
- if (split) return split.map(([a, b]) => [start + a, start + b]);
11107
- }
11108
- return args;
11109
- }
11110
- /**
11111
- * Split rawArgs by commas, respecting parentheses, brackets, braces, and
11112
- * strings. When no top-level commas are present, also supports adjacent quoted
11113
- * string literals separated by whitespace (e.g. `"Label" "target"`).
11114
- */
11115
- function splitArgs(raw) {
11116
- return splitArgSpans(raw).map(([a, b]) => raw.slice(a, b));
11117
- }
11118
- /** `text` as a regular expression source that matches it literally. */
11119
- function escapeRegExp(text) {
11120
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11121
- }
11122
11155
  // src/components/macros/macro-args.ts
11123
11156
  /**
11124
11157
  * The macro argument layer: reads a macro's raw argument text into the
@@ -11298,14 +11331,28 @@ function trimmed(src, at) {
11298
11331
  function readGroup(params, src, args, { at: srcAt, spans, toolingSpans }) {
11299
11332
  let [text, at] = trimmed(src ?? "", srcAt);
11300
11333
  const alone = !params.some((p) => p.type !== "flag" && p.required);
11301
- for (const flag of params.filter((p) => p.type === "flag")) {
11302
- const rest = src === null ? null : takeFlag(text, flag.name, alone);
11303
- args[flag.name] = rest !== null;
11304
- if (rest) {
11305
- const flagSpan = rest[0] > 0 ? [0, text.indexOf(flag.name) + flag.name.length] : [text.lastIndexOf(flag.name), text.length];
11306
- toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
11307
- [text, at] = trimmed(slice(text, rest), at + rest[0]);
11334
+ const flags = params.filter((p) => p.type === "flag");
11335
+ for (const flag of flags) args[flag.name] = false;
11336
+ const byName = new Map(flags.map((flag) => [flag.name, flag]));
11337
+ while (text && byName.size) {
11338
+ const parts = terms(text);
11339
+ if (parts.length === 0) break;
11340
+ let changed = false;
11341
+ for (const name of [slice(text, parts[parts.length - 1]), slice(text, parts[0])]) {
11342
+ const flag = byName.get(name);
11343
+ if (!flag || args[flag.name]) continue;
11344
+ const rest = src === null ? null : takeFlag(text, flag.name, alone);
11345
+ if (rest) {
11346
+ args[flag.name] = true;
11347
+ byName.delete(flag.name);
11348
+ changed = true;
11349
+ const flagSpan = rest[0] > 0 ? [0, text.indexOf(flag.name) + flag.name.length] : [text.lastIndexOf(flag.name), text.length];
11350
+ toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
11351
+ [text, at] = trimmed(slice(text, rest), at + rest[0]);
11352
+ break;
11353
+ }
11308
11354
  }
11355
+ if (!changed) break;
11309
11356
  }
11310
11357
  const positional = params.filter((p) => p.type !== "flag");
11311
11358
  if (positional.length === 0) return;
@@ -11560,13 +11607,13 @@ function parseOrError(code, goal) {
11560
11607
  parses?.set(key, result);
11561
11608
  return result;
11562
11609
  }
11563
- /** Where character `index` of the code or text of `piece` is in the source. */
11610
+ /** Where boundary `index` of a piece's code, text or name is in the source. */
11564
11611
  function pieceOffset(piece, index) {
11565
11612
  return piece.sourceOffsets?.[index] ?? piece.offset + index;
11566
11613
  }
11567
11614
  /** How much of a piece's own text or code there is (not its source extent). */
11568
11615
  function extentOf(piece) {
11569
- return piece.kind === "code" ? piece.code.length : piece.kind === "text" ? piece.text.length : piece.length;
11616
+ return piece.kind === "code" ? piece.code.length : piece.kind === "text" ? piece.text.length : piece.kind === "passage" ? piece.name.length : piece.length;
11570
11617
  }
11571
11618
  /** Macros whose whole argument text is one expression: branch conditions. */
11572
11619
  var CONDITION_MACROS = /* @__PURE__ */ new Set([
@@ -11763,13 +11810,17 @@ function* codeAndText(src, tokens, parametersOf) {
11763
11810
  if (close > t + 1) {
11764
11811
  const text = src.slice(token.end, tokens[close].start);
11765
11812
  const written = text.trim();
11813
+ const at = token.end + text.indexOf(written);
11814
+ const nameValue = readPassageBody(written);
11815
+ const sourceOffsets = readWholeQuoted(written) !== null ? escapeOffsets(written.slice(1, -1), at + 1, nameValue, "quotes", true) : void 0;
11766
11816
  yield {
11767
11817
  kind: "passage",
11768
- name: readPassageBody(written),
11769
- offset: token.end + text.indexOf(written),
11818
+ name: nameValue,
11819
+ offset: at,
11770
11820
  length: written.length,
11771
11821
  macro: name,
11772
- label: src.slice(token.start, token.end)
11822
+ label: src.slice(token.start, token.end),
11823
+ ...sourceOffsets && { sourceOffsets }
11773
11824
  };
11774
11825
  }
11775
11826
  }
@@ -11859,7 +11910,7 @@ function nestedPiece(piece, toRoot, where) {
11859
11910
  nested: true,
11860
11911
  where
11861
11912
  };
11862
- if (piece.kind === "passage" || piece.kind === "argument-error") {
11913
+ if (piece.kind === "argument-error") {
11863
11914
  const length = toRoot(piece.offset + piece.length) - offset;
11864
11915
  return {
11865
11916
  ...piece,
@@ -11869,7 +11920,7 @@ function nestedPiece(piece, toRoot, where) {
11869
11920
  }
11870
11921
  const extent = extentOf(piece);
11871
11922
  const sourceOffsets = piece.sourceOffsets ? piece.sourceOffsets.map(toRoot) : toRoot(piece.offset + extent) - offset !== extent ? Array.from({ length: extent + 1 }, (_, i) => toRoot(piece.offset + i)) : void 0;
11872
- return sourceOffsets ? {
11923
+ const mapped = sourceOffsets ? {
11873
11924
  ...piece,
11874
11925
  ...nested,
11875
11926
  sourceOffsets
@@ -11877,6 +11928,10 @@ function nestedPiece(piece, toRoot, where) {
11877
11928
  ...piece,
11878
11929
  ...nested
11879
11930
  };
11931
+ return mapped.kind === "passage" ? {
11932
+ ...mapped,
11933
+ length: toRoot(piece.offset + mapped.length) - offset
11934
+ } : mapped;
11880
11935
  }
11881
11936
  /** An escape sequence of a JavaScript string literal (with its backslash). */
11882
11937
  var JS_ESCAPE_RE = /\\(?:u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0-3][0-7]{0,2}|[4-7][0-7]?|\r\n|[^])/y;
@@ -11905,9 +11960,10 @@ function escapeAt(raw, i, escapes) {
11905
11960
  * written as `raw` from `at` on (its escapes are those of `escapes`), is in
11906
11961
  * the source, and where the text ends. A character that an escape stands for
11907
11962
  * is where the escape begins. None when the text is where its length says, or
11908
- * is not that string.
11963
+ * is not that string. With `includeLinear`, return the map even without
11964
+ * escapes (a passage piece's offset includes the opening quote).
11909
11965
  */
11910
- function escapeOffsets(raw, at, value, escapes) {
11966
+ function escapeOffsets(raw, at, value, escapes, includeLinear = false) {
11911
11967
  const offsets = [];
11912
11968
  let escaped = false;
11913
11969
  let i = 0;
@@ -11923,8 +11979,14 @@ function escapeOffsets(raw, at, value, escapes) {
11923
11979
  escaped = true;
11924
11980
  i += escape.length;
11925
11981
  }
11982
+ while (raw[i] === "\\") {
11983
+ const escape = escapeAt(raw, i, escapes);
11984
+ if (!escape || escape.text.length !== 0) break;
11985
+ escaped = true;
11986
+ i += escape.length;
11987
+ }
11926
11988
  offsets.push(at + i);
11927
- return escaped ? offsets : void 0;
11989
+ return escaped || includeLinear ? offsets : void 0;
11928
11990
  }
11929
11991
  /** The code and text in the arguments `args` (at `offset`) of `macro`. */
11930
11992
  function* argPieces(args, offset, params, macro, label, navigation = []) {
@@ -11992,20 +12054,21 @@ function* valuePieces(args, offset, params, values, spans, macro, label, escapes
11992
12054
  const [start, end] = span;
11993
12055
  const written = args.slice(start, end);
11994
12056
  /** The name as written (quotes included), at the argument. */
11995
- const passage = (passageName) => ({
12057
+ const passage = (passageName, at, mode = escapes) => ({
11996
12058
  kind: "passage",
11997
12059
  name: passageName,
11998
12060
  offset: offset + start,
11999
12061
  length: end - start,
12000
12062
  macro: name,
12001
12063
  label,
12064
+ sourceOffsets: escapeOffsets(args.slice(at - offset), at, passageName, mode, true),
12002
12065
  ...navigation.includes(param.name) && { navigation: true }
12003
12066
  });
12004
12067
  const goal = codeGoal(param);
12005
12068
  if (param.type === "passage") {
12006
12069
  const target = passageTarget(value);
12007
12070
  if (target.kind === "name") {
12008
- yield passage(target.name);
12071
+ yield passage(target.name, offset + start + 1, "javascript");
12009
12072
  continue;
12010
12073
  }
12011
12074
  }
@@ -12038,7 +12101,7 @@ function* valuePieces(args, offset, params, values, spans, macro, label, escapes
12038
12101
  };
12039
12102
  if (sourceOffsets) piece.sourceOffsets = sourceOffsets;
12040
12103
  yield piece;
12041
- } else if (holds === "passage") yield passage(value);
12104
+ } else if (holds === "passage") yield passage(value, at);
12042
12105
  else if (holds === "markup") {
12043
12106
  const piece = textPiece(value, at, `In the ${param.name} of {${macro}}: `);
12044
12107
  if (sourceOffsets) piece.sourceOffsets = sourceOffsets;
@@ -12288,9 +12351,8 @@ function readCompletion(source, cursor, macros, full, sourceLength = source.leng
12288
12351
  return read(source, (i) => i);
12289
12352
  }
12290
12353
  // src/widgets/ast-scanner.ts
12291
- /** The declared parameters of the macros registered so far. */
12292
- var registeredParameters = (name) => parameterLookup(getMacroRegistry())(name);
12293
- registeredParameters.source = getMacroParameters.source;
12354
+ /** Snapshot effective macro metadata once per scan. */
12355
+ var registeredParameters = () => parameterLookup(getMacroRegistry());
12294
12356
  /**
12295
12357
  * Whether the text of an attribute value or macro label renders a
12296
12358
  * `{@children}`: it is markup, parsed as the renderer parses it.
@@ -12317,7 +12379,7 @@ function textContainsChildren(text, parametersOf, hooks, budget = new MarkupExpa
12317
12379
  * are read from it); a token made from an AST has none. Discovery hooks
12318
12380
  * also apply inside these texts, before widgets have been registered.
12319
12381
  */
12320
- function tokenTextContainsChildren(token, parametersOf = registeredParameters, src = "", hooks, budget) {
12382
+ function tokenTextContainsChildren(token, parametersOf = registeredParameters(), src = "", hooks, budget) {
12321
12383
  for (const piece of codeAndText(src, [token], parametersOf)) if (piece.kind === "text" && textContainsChildren(piece.text, parametersOf, hooks, budget)) return true;
12322
12384
  return false;
12323
12385
  }
@@ -12328,7 +12390,7 @@ function tokenTextContainsChildren(token, parametersOf = registeredParameters, s
12328
12390
  * entered: its slot belongs to the innermost widget (as widgetDefinitions
12329
12391
  * reads it), and a definition renders nothing of its own.
12330
12392
  */
12331
- function astContainsChildren(nodes, parametersOf = registeredParameters, hooks, budget) {
12393
+ function astContainsChildren(nodes, parametersOf = registeredParameters(), hooks, budget) {
12332
12394
  const pending = [...nodes];
12333
12395
  while (pending.length) {
12334
12396
  const node = pending.pop();
@@ -12429,7 +12491,7 @@ function nameSpan(rawArgs) {
12429
12491
  * here as it is to the parser, and does not make a block widget (#387). In
12430
12492
  * nested definitions, it belongs to the innermost.
12431
12493
  */
12432
- function widgetDefinitions$1(passages, parametersOf = registeredParameters) {
12494
+ function widgetDefinitions$1(passages, parametersOf = registeredParameters()) {
12433
12495
  const list = [...passages];
12434
12496
  const scan = (replacesDo) => {
12435
12497
  const found = [];
@@ -25807,13 +25869,23 @@ function joinSpans(text, spans, sentinel) {
25807
25869
  }
25808
25870
  return out + text.slice(last);
25809
25871
  }
25872
+ /** Collapse the trailing blank lines without probing every whitespace suffix. */
25873
+ function trimBlankLines(text) {
25874
+ let end = text.length;
25875
+ let newline = false;
25876
+ while (end > 0 && /[ \t\n]/.test(text[end - 1])) {
25877
+ newline || (newline = text[end - 1] === "\n");
25878
+ end--;
25879
+ }
25880
+ return newline ? text.slice(0, end) + "\n" : text;
25881
+ }
25810
25882
  async function formatLf(text, options) {
25811
25883
  const { prettier, prettierOptions } = options;
25812
25884
  let body = text;
25813
25885
  if (options.kind === "script" || options.kind === "stylesheet") {
25814
25886
  const format = options.kind === "script" ? formatJS : formatCSS;
25815
25887
  const code = body.trim();
25816
- return (await format(code, prettier, prettierOptions) ?? code).trim().replace(/\n*$/, "\n");
25888
+ return (await format(code, prettier, prettierOptions) ?? code).trim() + "\n";
25817
25889
  }
25818
25890
  const isBlock = options.isBlock ?? defaultIsBlock(body, options.blockMacros);
25819
25891
  const isDedenting = options.isDedentingSubMacro ?? ((name) => DEFAULT_DEDENTING.has(name.toLowerCase()));
@@ -25823,13 +25895,13 @@ async function formatLf(text, options) {
25823
25895
  const literalMarkers = /* @__PURE__ */ new Set();
25824
25896
  const fenced = markdownLines(body, isBlock, /* @__PURE__ */ new Set(["codeFenced"]));
25825
25897
  const literalHtml = whitespaceSensitiveLines(body, isBlock);
25826
- body = body.split("\n").map((line, index) => {
25898
+ body = trimBlankLines(body.split("\n").map((line, index) => {
25827
25899
  if (!fenced.has(index) && !literalHtml.has(index)) return line;
25828
25900
  const marker = `${literalSentinel}L${literalLines.size}${literalSentinel}`;
25829
25901
  literalLines.set(marker, line);
25830
25902
  literalMarkers.add(marker);
25831
25903
  return (line.match(/^[ \t]*/)?.[0] ?? "") + marker;
25832
- }).join("\n").replace(/(?:[ \t]*\n)+[ \t]*$/, "\n");
25904
+ }).join("\n"));
25833
25905
  const lines = [];
25834
25906
  /** Indices in lines whose trailing two spaces are a hard line break. */
25835
25907
  const hardBreakLines = /* @__PURE__ */ new Set();
@@ -25886,8 +25958,10 @@ async function formatLf(text, options) {
25886
25958
  lines.push(line);
25887
25959
  }
25888
25960
  }
25889
- let output = lines.map((l, i) => hardBreakLines.has(i) || preservedLines.has(i) ? l : l.replace(/\s+$/, "")).join("\n");
25890
- output = output.replace(/\n*$/, "\n");
25961
+ let output = lines.map((l, i) => hardBreakLines.has(i) || preservedLines.has(i) ? l : l.trimEnd()).join("\n");
25962
+ let end = output.length;
25963
+ while (end > 0 && output[end - 1] === "\n") end--;
25964
+ output = output.slice(0, end) + "\n";
25891
25965
  return replaceAll(output.split("\n").map((line) => literalLines.get(line.trim()) ?? line).join("\n"), sentinel, "\n");
25892
25966
  }
25893
25967
  /** Literal HTML and opaque SVG, whose text can inherit significant whitespace. */
@@ -26053,7 +26127,7 @@ function indentMacros(lines, isBlock, isDedenting, literalMarkers) {
26053
26127
  col = body.keepOriginal ? line.col : base + (body.keepRelative ? line.col - (isRoot ? 0 : body.minCol) : 0);
26054
26128
  }
26055
26129
  outCol.push(col);
26056
- const hardBreak = / {2,}$/.test(lines[i]) && info[i + 1] ? " " : "";
26130
+ const hardBreak = lines[i].endsWith(" ") && info[i + 1] ? " " : "";
26057
26131
  result.push(" ".repeat(col) + line.text + hardBreak);
26058
26132
  }
26059
26133
  return result;
@@ -26558,4 +26632,4 @@ function validateVariableReferences(passages, declarations, macros = []) {
26558
26632
  const list = [...passages];
26559
26633
  return checkVariableReferences(list.filter((p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t))), declarations, referenceOptions(macros, false, list));
26560
26634
  }
26561
- export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, completionContext, completionTarget, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, isBlockMacro, isSigil, isSpecialPassage, lexJs, lexTemplate, macroArgumentSpans, macroCallAt, macroCalls, pairMarkup, parseBoundVariable, parseCode, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };
26635
+ export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, completionContext, completionTarget, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, indexStrictCodeEnds, isBlockMacro, isSigil, isSpecialPassage, lexJs, lexTemplate, macroArgumentSpans, macroCallAt, macroCalls, pairMarkup, parseBoundVariable, parseCode, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };