@rohal12/spindle 0.64.31 → 0.64.33

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.
@@ -655,7 +655,7 @@ function peg$parse(input, options) {
655
655
  return lexeme("text", location(), { value });
656
656
  }
657
657
  function peg$f24() {
658
- return completionMode || offset() <= lastCommentClose;
658
+ return completionMode || findDelimiter("-->", offset()) >= 0;
659
659
  }
660
660
  function peg$f25(value) {
661
661
  const node = lexeme("text", location(), { value });
@@ -712,8 +712,8 @@ function peg$parse(input, options) {
712
712
  fail("Unclosed link: [[ without ]]", location(), "unclosed-link");
713
713
  }
714
714
  function peg$f37(start) {
715
- const close = input.indexOf("]]", start);
716
- const nested = input.indexOf("[[", start);
715
+ const close = findDelimiter("]]", start);
716
+ const nested = findDelimiter("[[", start);
717
717
  linkTextEnd = Math.min(close < 0 ? input.length : close, nested < 0 ? input.length : nested);
718
718
  return true;
719
719
  }
@@ -3573,7 +3573,7 @@ function peg$parse(input, options) {
3573
3573
  const textMode = options.text === true;
3574
3574
  const completionMode = options.completion === true;
3575
3575
  const hooks = options.hooks;
3576
- const lastCommentClose = input.lastIndexOf("-->");
3576
+ const findDelimiter = options.findDelimiter;
3577
3577
  /** End of the stretch a `.|n|` repetition consumes (see skipTo). */
3578
3578
  let skipEnd = -1;
3579
3579
  /** Whether the attribute whose value is being read holds code. */
@@ -3710,7 +3710,11 @@ function consumesOptionClauses(macro) {
3710
3710
  const name = macro.name.toLowerCase();
3711
3711
  return macro.source === "builtin" && !macro.widget && (name === "listbox" || name === "cycle");
3712
3712
  }
3713
- new NameMap();
3713
+ // src/registry.ts
3714
+ var registry = new NameMap();
3715
+ function getMacro(name) {
3716
+ return registry.get(name);
3717
+ }
3714
3718
  new NameMap();
3715
3719
  new NameSet();
3716
3720
  /**
@@ -3870,6 +3874,10 @@ function isBlockMacro(name) {
3870
3874
  if (DEFINED_MACROS.has(name)) return DEFINED_BLOCK_MACROS.has(name);
3871
3875
  return isBuiltinBlockMacro(name);
3872
3876
  }
3877
+ /** Explicit implementations can also be invoked outside a companion owner. */
3878
+ function isStandaloneMacro(name) {
3879
+ return WIDGETS.has(name) || getMacro(name) !== void 0;
3880
+ }
3873
3881
  /** Built-in defaults without any process-global registrations or widgets. */
3874
3882
  function isBuiltinBlockMacro(name) {
3875
3883
  return BLOCK_MACROS.has(name);
@@ -4030,6 +4038,7 @@ var closes = (open, close) => open.type === close.type && lowerName(open) === lo
4030
4038
  function pairMarkup(tokens, options = {}) {
4031
4039
  const isBlock = options.isBlock ?? isBlockMacro;
4032
4040
  const isRaw = options.isRaw ?? isRawMacro;
4041
+ const isStandalone = options.isStandalone ?? isStandaloneMacro;
4033
4042
  const parentsOf = (name) => {
4034
4043
  if (options.branchParents) return options.branchParents(name);
4035
4044
  const registered = branchParents(name);
@@ -4109,7 +4118,7 @@ function pairMarkup(tokens, options = {}) {
4109
4118
  }
4110
4119
  continue;
4111
4120
  }
4112
- if (token.type === "macro" && !token.isClose && parentsOf(token.name).length > 0) {
4121
+ if (token.type === "macro" && !token.isClose && parentsOf(token.name).length > 0 && (!isStandalone(token.name) || last$1(stack)?.node.token.type === "macro" && parentsOf(token.name).includes(lowerName(last$1(stack).node.token)))) {
4113
4122
  const tag = token;
4114
4123
  const frame = last$1(stack);
4115
4124
  if (!frame) {
@@ -10377,6 +10386,201 @@ function completionIdentifier(source, cursor, goal = "expression") {
10377
10386
  previous = token;
10378
10387
  }
10379
10388
  }
10389
+ // src/components/macros/arg-utils.ts
10390
+ /**
10391
+ * Shared helpers for macros that split or read their raw argument text by
10392
+ * hand. Their lexical model is the expression lexer's (`js-lexer.ts`):
10393
+ * string, template and regex literals and comments are opaque (a backslash
10394
+ * inside a literal escapes the character after it, and `${…}` parts of a
10395
+ * template are code), `/` opens a regex only where an operand is expected,
10396
+ * and `(`/`[`/`{` nest.
10397
+ */
10398
+ /** True for a whitespace character. */
10399
+ function isWhitespace(ch) {
10400
+ return /\s/.test(ch);
10401
+ }
10402
+ function isOpener(ch) {
10403
+ return ch === "(" || ch === "[" || ch === "{";
10404
+ }
10405
+ function isCloser(ch) {
10406
+ return ch === ")" || ch === "]" || ch === "}";
10407
+ }
10408
+ /**
10409
+ * Undo the escapes allowed in a literal quoted macro argument: `\"`, `\'`
10410
+ * and `\\` become `"`, `'` and `\`. Other backslash sequences (`\n`, `\d`)
10411
+ * are kept as written, so code and regex text inside the string survive.
10412
+ */
10413
+ function unescapeQuoted(body) {
10414
+ return body.replace(/\\(["'\\])/g, "$1");
10415
+ }
10416
+ /**
10417
+ * Read the `"…"` or `'…'` string whose opening quote is at `start`.
10418
+ * Returns its unescaped value and the index just past the closing quote, or
10419
+ * `null` if there is no such quote at `start` or the string is unterminated.
10420
+ * With `tolerant`, an unterminated string instead extends to its scanned end.
10421
+ */
10422
+ function readQuoted(src, start, tolerant = false) {
10423
+ const quote = src[start];
10424
+ if (quote !== "\"" && quote !== "'") return null;
10425
+ const { end, closed } = scanStringLiteral(src, start);
10426
+ if (!closed && !tolerant) return null;
10427
+ return {
10428
+ value: unescapeQuoted(src.slice(start + 1, closed ? end - 1 : end)),
10429
+ end
10430
+ };
10431
+ }
10432
+ /**
10433
+ * The unescaped value of `src` when it is exactly one `"…"` or `'…'` string
10434
+ * (as with `readQuoted`), otherwise `null`.
10435
+ */
10436
+ function readWholeQuoted(src) {
10437
+ const quoted = readQuoted(src, 0);
10438
+ return quoted && quoted.end === src.length ? quoted.value : null;
10439
+ }
10440
+ /** A dialog body's passage name, optionally enclosed in matching quotes. */
10441
+ function readPassageBody(src) {
10442
+ const name = src.trim();
10443
+ return readWholeQuoted(name) ?? name;
10444
+ }
10445
+ /**
10446
+ * Strip an optional quote from each end of an unquoted-or-loosely-quoted
10447
+ * argument (`"Red`, `Red'`), leaving at least one character. This is the
10448
+ * lenient fallback for labels that are not one well-formed quoted string.
10449
+ */
10450
+ function stripLooseQuotes(src) {
10451
+ return /^["']?(.+?)["']?$/s.exec(src)?.[1] ?? src;
10452
+ }
10453
+ /** An operator character, or an operator keyword, at the end of code. */
10454
+ var TRAILING_OPERATOR_RE = /(?:[-+*/%&|^!~=<>?:,.]|(?:^|[^\w$@.])(?:typeof|void|new|delete|in|instanceof|await|yield))$/;
10455
+ /**
10456
+ * Whether `src` ends with an operator that still needs an operand (`$a +`,
10457
+ * `$a+`, `$x ==`, `typeof`), so it cannot be a complete value on its own.
10458
+ * Only code counts: the closing `/` of a regex literal is not division, a
10459
+ * variable reference (`$a`, `%name`, ...) is an operand, trailing comments are skipped,
10460
+ * and a postfix `++` or `--` completes its operand.
10461
+ */
10462
+ function endsWithOperator(src) {
10463
+ let end = -1;
10464
+ lexJs(src, {
10465
+ code(ch, i, nesting) {
10466
+ if (nesting === 0 && !isWhitespace(ch)) end = i + 1;
10467
+ },
10468
+ literal(text, _i, nesting) {
10469
+ const comment = text.startsWith("//") || text.startsWith("/*");
10470
+ if (nesting === 0 && !comment) end = -1;
10471
+ },
10472
+ variable(_sigil, _name, _i, nesting) {
10473
+ if (nesting === 0) end = -1;
10474
+ }
10475
+ });
10476
+ if (end < 0) return false;
10477
+ const code = src.slice(0, end);
10478
+ if (/(?:\+\+|--)$/.test(code)) return false;
10479
+ return TRAILING_OPERATOR_RE.test(code);
10480
+ }
10481
+ /**
10482
+ * Indices of the characters in `src` that satisfy `isSeparator` and sit at
10483
+ * depth 0: in code outside string, template and regex literals and comments,
10484
+ * and outside `()`, `[]` and `{}` pairs.
10485
+ */
10486
+ function topLevelIndices(src, isSeparator) {
10487
+ const indices = [];
10488
+ let depth = 0;
10489
+ lexJs(src, { code(ch, i, nesting) {
10490
+ if (nesting > 0) return;
10491
+ if (isOpener(ch)) depth++;
10492
+ else if (isCloser(ch)) depth--;
10493
+ else if (depth === 0 && isSeparator(ch)) indices.push(i);
10494
+ } });
10495
+ return indices;
10496
+ }
10497
+ /**
10498
+ * The segments of `src` between its depth-0 separators (see
10499
+ * `topLevelIndices`), as spans: untrimmed, and empty segments are kept, so
10500
+ * `n` separators always give `n + 1` segments.
10501
+ */
10502
+ function topLevelSpans(src, isSeparator) {
10503
+ const spans = [];
10504
+ let from = 0;
10505
+ for (const i of topLevelIndices(src, isSeparator)) {
10506
+ spans.push([from, i]);
10507
+ from = i + 1;
10508
+ }
10509
+ spans.push([from, src.length]);
10510
+ return spans;
10511
+ }
10512
+ /**
10513
+ * Split `src` at every depth-0 separator (see `topLevelIndices`). Segments
10514
+ * are returned as written, untrimmed, and empty segments are kept, so
10515
+ * `n` separators always give `n + 1` segments.
10516
+ */
10517
+ function splitTopLevel(src, isSeparator) {
10518
+ return topLevelSpans(src, isSeparator).map(([a, b]) => src.slice(a, b));
10519
+ }
10520
+ /**
10521
+ * Check whether a whitespace-delimited token looks like a standalone value
10522
+ * (not an operator or partial expression): it starts like a value and does
10523
+ * not end with an operator still waiting for its operand.
10524
+ */
10525
+ function isStandaloneValue(token) {
10526
+ return startsLikeValue(token) && !endsWithOperator(token);
10527
+ }
10528
+ function startsLikeValue(token) {
10529
+ const first = token[0];
10530
+ if (first === "\"" || first === "'" || first === "`") return true;
10531
+ if (/^[$_@]\w|^%[A-Za-z_]/.test(token)) return true;
10532
+ if (/^[+-]?(?:\d|\.\d)/.test(token)) return true;
10533
+ if (first === "(" || first === "[" || first === "{") return true;
10534
+ if (/^(?:true|false|null|undefined)(?![\w$])/.test(token)) return true;
10535
+ if (first === "!" && token.length > 1 && token[1] !== "=") return true;
10536
+ return false;
10537
+ }
10538
+ /**
10539
+ * Try to split a raw string on whitespace at depth 0 (respecting strings,
10540
+ * template literals, parentheses, brackets, and braces). Each resulting token
10541
+ * must pass `isStandaloneValue()` or the split is rejected and `null` is
10542
+ * returned. The spans are those of the tokens in `raw`.
10543
+ */
10544
+ function trySplitOnWhitespace(raw) {
10545
+ const args = topLevelSpans(raw, isWhitespace).filter(([a, b]) => b > a);
10546
+ if (args.length < 2) return null;
10547
+ for (const [a, b] of args) if (!isStandaloneValue(raw.slice(a, b))) return null;
10548
+ return args;
10549
+ }
10550
+ /** `span` less the whitespace at its ends. */
10551
+ function trimmed$1(src, [start, end]) {
10552
+ const text = src.slice(start, end);
10553
+ const lead = text.length - text.trimStart().length;
10554
+ return [start + lead, Math.max(start + lead, end - (text.length - text.trimEnd().length))];
10555
+ }
10556
+ /**
10557
+ * Where the arguments in `raw` are written (see `splitArgs`), as spans of
10558
+ * `raw`.
10559
+ */
10560
+ function splitArgSpans(raw) {
10561
+ const args = topLevelSpans(raw, (ch) => ch === ",").map((span) => trimmed$1(raw, span));
10562
+ const hasComma = args.length > 1;
10563
+ const last = args[args.length - 1];
10564
+ if (last[0] === last[1]) args.pop();
10565
+ if (!hasComma && args.length === 1) {
10566
+ const [start, end] = args[0];
10567
+ const split = trySplitOnWhitespace(raw.slice(start, end));
10568
+ if (split) return split.map(([a, b]) => [start + a, start + b]);
10569
+ }
10570
+ return args;
10571
+ }
10572
+ /**
10573
+ * Split rawArgs by commas, respecting parentheses, brackets, braces, and
10574
+ * strings. When no top-level commas are present, also supports adjacent quoted
10575
+ * string literals separated by whitespace (e.g. `"Label" "target"`).
10576
+ */
10577
+ function splitArgs(raw) {
10578
+ return splitArgSpans(raw).map(([a, b]) => raw.slice(a, b));
10579
+ }
10580
+ /** `text` as a regular expression source that matches it literally. */
10581
+ function escapeRegExp(text) {
10582
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
10583
+ }
10380
10584
  // src/markup/code-end.ts
10381
10585
  /**
10382
10586
  * A quote directly after a letter/digit is an apostrophe (don't), not a
@@ -10481,6 +10685,8 @@ function scanLenient(input, start) {
10481
10685
  * input (see `OnOpenCodeEnd`); the ends it finds are the same.
10482
10686
  */
10483
10687
  function jsCodeEnd(onOpenEnd) {
10688
+ let indexedInput = "";
10689
+ const rawClosers = /* @__PURE__ */ new Map();
10484
10690
  return {
10485
10691
  closeBrace(input, codeStart, lenientStart) {
10486
10692
  let ranOut = false;
@@ -10491,10 +10697,18 @@ function jsCodeEnd(onOpenEnd) {
10491
10697
  return end;
10492
10698
  },
10493
10699
  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;
10700
+ if (indexedInput !== input) {
10701
+ indexedInput = input;
10702
+ rawClosers.clear();
10703
+ }
10704
+ name = name.toLowerCase();
10705
+ const closer = `\\{/${escapeRegExp(name)}\\s*\\}`;
10706
+ let candidates = rawClosers.get(name);
10707
+ if (!candidates) {
10708
+ candidates = Array.from(input.matchAll(new RegExp(closer, "gi")), (m) => m.index);
10709
+ rawClosers.set(name, candidates);
10710
+ }
10711
+ const firstAt = candidates[upperBound(candidates, bodyStart - 1)] ?? -1;
10498
10712
  if (firstAt === -1) return -1;
10499
10713
  const at = new RegExp(closer, "iy");
10500
10714
  let ranOut = false;
@@ -10507,7 +10721,7 @@ function jsCodeEnd(onOpenEnd) {
10507
10721
  onRunOut: () => ranOut = true
10508
10722
  });
10509
10723
  if (end !== -1) return end;
10510
- if (onOpenEnd && (ranOut || new RegExp(`\\{/${name}\\s*$`, "i").test(input))) onOpenEnd(input, bodyStart);
10724
+ if (onOpenEnd && (ranOut || new RegExp(`\\{/${escapeRegExp(name)}\\s*$`, "i").test(input))) onOpenEnd(input, bodyStart);
10511
10725
  return firstAt;
10512
10726
  }
10513
10727
  };
@@ -10653,7 +10867,7 @@ var MarkupError = class extends Error {
10653
10867
  this.name = "MarkupError";
10654
10868
  }
10655
10869
  };
10656
- function run$1(source, startRule, options, completion = false) {
10870
+ function run$1(source, startRule, options, completion = false, findDelimiter = indexDelimiters(source)) {
10657
10871
  const hooks = {
10658
10872
  ...defaultHooks,
10659
10873
  ...options.hooks
@@ -10667,7 +10881,8 @@ function run$1(source, startRule, options, completion = false) {
10667
10881
  startRule,
10668
10882
  text: options.text === true,
10669
10883
  hooks,
10670
- completion
10884
+ completion,
10885
+ findDelimiter
10671
10886
  });
10672
10887
  } catch (err) {
10673
10888
  const { location, code } = err;
@@ -10679,6 +10894,20 @@ function run$1(source, startRule, options, completion = false) {
10679
10894
  throw err;
10680
10895
  }
10681
10896
  }
10897
+ /** Literal delimiter searches shared by suffix and prefix recovery attempts. */
10898
+ function indexDelimiters(source) {
10899
+ const positions = /* @__PURE__ */ new Map();
10900
+ return (delimiter, from, end = source.length) => {
10901
+ let offsets = positions.get(delimiter);
10902
+ if (!offsets) {
10903
+ offsets = [];
10904
+ for (let at = source.indexOf(delimiter); at >= 0; at = source.indexOf(delimiter, at + 1)) offsets.push(at);
10905
+ positions.set(delimiter, offsets);
10906
+ }
10907
+ const at = offsets[upperBound(offsets, from - 1)];
10908
+ return at !== void 0 && at + delimiter.length <= end ? at : -1;
10909
+ };
10910
+ }
10682
10911
  /**
10683
10912
  * Read markup that may be malformed: its tokens, their pairing and every
10684
10913
  * error (malformed tags, and closers and branches that pair with nothing),
@@ -10695,6 +10924,7 @@ function analyzeMarkup(source, options = {}) {
10695
10924
  isBlock: hooks.isBlock,
10696
10925
  isRaw: hooks.isRaw,
10697
10926
  branchParents: hooks.branchParents,
10927
+ isStandalone: hooks.isStandalone,
10698
10928
  source
10699
10929
  });
10700
10930
  if (errors.length === 0 && paired.errors.length === 0) return {
@@ -10779,6 +11009,7 @@ function scanMarkupTolerant(source, options = {}, completion = false) {
10779
11009
  const damage = [];
10780
11010
  let position;
10781
11011
  const codeEnd = indexCodeEnds(source);
11012
+ const findDelimiter = indexDelimiters(source);
10782
11013
  const customCloseBrace = options.hooks?.closeBrace;
10783
11014
  const lastBrace = source.lastIndexOf("}");
10784
11015
  /** `text` shifted by `base`, tokenized: the tokens or the error. */
@@ -10796,7 +11027,10 @@ function scanMarkupTolerant(source, options = {}, completion = false) {
10796
11027
  return run$1(text, "Tokens", {
10797
11028
  ...options,
10798
11029
  hooks
10799
- }, completion).map((token) => shiftOffsets(token, base));
11030
+ }, completion, (delimiter, from) => {
11031
+ const at = findDelimiter(delimiter, base + from, base + text.length);
11032
+ return at < 0 ? -1 : at - base;
11033
+ }).map((token) => shiftOffsets(token, base));
10800
11034
  } catch (error) {
10801
11035
  if (!(error instanceof MarkupError)) throw error;
10802
11036
  return error;
@@ -10947,201 +11181,6 @@ function ownEntries(sources, keep = () => true) {
10947
11181
  /** A namespace with no prototype holding the own entries of `sources`. */
10948
11182
  var createNamespace = (...sources) => ownEntries(sources);
10949
11183
  Object.freeze(createNamespace());
10950
- // src/components/macros/arg-utils.ts
10951
- /**
10952
- * Shared helpers for macros that split or read their raw argument text by
10953
- * hand. Their lexical model is the expression lexer's (`js-lexer.ts`):
10954
- * string, template and regex literals and comments are opaque (a backslash
10955
- * inside a literal escapes the character after it, and `${…}` parts of a
10956
- * template are code), `/` opens a regex only where an operand is expected,
10957
- * and `(`/`[`/`{` nest.
10958
- */
10959
- /** True for a whitespace character. */
10960
- function isWhitespace(ch) {
10961
- return /\s/.test(ch);
10962
- }
10963
- function isOpener(ch) {
10964
- return ch === "(" || ch === "[" || ch === "{";
10965
- }
10966
- function isCloser(ch) {
10967
- return ch === ")" || ch === "]" || ch === "}";
10968
- }
10969
- /**
10970
- * Undo the escapes allowed in a literal quoted macro argument: `\"`, `\'`
10971
- * and `\\` become `"`, `'` and `\`. Other backslash sequences (`\n`, `\d`)
10972
- * are kept as written, so code and regex text inside the string survive.
10973
- */
10974
- function unescapeQuoted(body) {
10975
- return body.replace(/\\(["'\\])/g, "$1");
10976
- }
10977
- /**
10978
- * Read the `"…"` or `'…'` string whose opening quote is at `start`.
10979
- * Returns its unescaped value and the index just past the closing quote, or
10980
- * `null` if there is no such quote at `start` or the string is unterminated.
10981
- * With `tolerant`, an unterminated string instead extends to its scanned end.
10982
- */
10983
- function readQuoted(src, start, tolerant = false) {
10984
- const quote = src[start];
10985
- if (quote !== "\"" && quote !== "'") return null;
10986
- const { end, closed } = scanStringLiteral(src, start);
10987
- if (!closed && !tolerant) return null;
10988
- return {
10989
- value: unescapeQuoted(src.slice(start + 1, closed ? end - 1 : end)),
10990
- end
10991
- };
10992
- }
10993
- /**
10994
- * The unescaped value of `src` when it is exactly one `"…"` or `'…'` string
10995
- * (as with `readQuoted`), otherwise `null`.
10996
- */
10997
- function readWholeQuoted(src) {
10998
- const quoted = readQuoted(src, 0);
10999
- return quoted && quoted.end === src.length ? quoted.value : null;
11000
- }
11001
- /** A dialog body's passage name, optionally enclosed in matching quotes. */
11002
- function readPassageBody(src) {
11003
- const name = src.trim();
11004
- return readWholeQuoted(name) ?? name;
11005
- }
11006
- /**
11007
- * Strip an optional quote from each end of an unquoted-or-loosely-quoted
11008
- * argument (`"Red`, `Red'`), leaving at least one character. This is the
11009
- * lenient fallback for labels that are not one well-formed quoted string.
11010
- */
11011
- function stripLooseQuotes(src) {
11012
- return /^["']?(.+?)["']?$/s.exec(src)?.[1] ?? src;
11013
- }
11014
- /** An operator character, or an operator keyword, at the end of code. */
11015
- var TRAILING_OPERATOR_RE = /(?:[-+*/%&|^!~=<>?:,.]|(?:^|[^\w$@.])(?:typeof|void|new|delete|in|instanceof|await|yield))$/;
11016
- /**
11017
- * Whether `src` ends with an operator that still needs an operand (`$a +`,
11018
- * `$a+`, `$x ==`, `typeof`), so it cannot be a complete value on its own.
11019
- * Only code counts: the closing `/` of a regex literal is not division, a
11020
- * variable reference (`$a`, `%name`, ...) is an operand, trailing comments are skipped,
11021
- * and a postfix `++` or `--` completes its operand.
11022
- */
11023
- function endsWithOperator(src) {
11024
- let end = -1;
11025
- lexJs(src, {
11026
- code(ch, i, nesting) {
11027
- if (nesting === 0 && !isWhitespace(ch)) end = i + 1;
11028
- },
11029
- literal(text, _i, nesting) {
11030
- const comment = text.startsWith("//") || text.startsWith("/*");
11031
- if (nesting === 0 && !comment) end = -1;
11032
- },
11033
- variable(_sigil, _name, _i, nesting) {
11034
- if (nesting === 0) end = -1;
11035
- }
11036
- });
11037
- if (end < 0) return false;
11038
- const code = src.slice(0, end);
11039
- if (/(?:\+\+|--)$/.test(code)) return false;
11040
- return TRAILING_OPERATOR_RE.test(code);
11041
- }
11042
- /**
11043
- * Indices of the characters in `src` that satisfy `isSeparator` and sit at
11044
- * depth 0: in code outside string, template and regex literals and comments,
11045
- * and outside `()`, `[]` and `{}` pairs.
11046
- */
11047
- function topLevelIndices(src, isSeparator) {
11048
- const indices = [];
11049
- let depth = 0;
11050
- lexJs(src, { code(ch, i, nesting) {
11051
- if (nesting > 0) return;
11052
- if (isOpener(ch)) depth++;
11053
- else if (isCloser(ch)) depth--;
11054
- else if (depth === 0 && isSeparator(ch)) indices.push(i);
11055
- } });
11056
- return indices;
11057
- }
11058
- /**
11059
- * The segments of `src` between its depth-0 separators (see
11060
- * `topLevelIndices`), as spans: untrimmed, and empty segments are kept, so
11061
- * `n` separators always give `n + 1` segments.
11062
- */
11063
- function topLevelSpans(src, isSeparator) {
11064
- const spans = [];
11065
- let from = 0;
11066
- for (const i of topLevelIndices(src, isSeparator)) {
11067
- spans.push([from, i]);
11068
- from = i + 1;
11069
- }
11070
- spans.push([from, src.length]);
11071
- return spans;
11072
- }
11073
- /**
11074
- * Split `src` at every depth-0 separator (see `topLevelIndices`). Segments
11075
- * are returned as written, untrimmed, and empty segments are kept, so
11076
- * `n` separators always give `n + 1` segments.
11077
- */
11078
- function splitTopLevel(src, isSeparator) {
11079
- return topLevelSpans(src, isSeparator).map(([a, b]) => src.slice(a, b));
11080
- }
11081
- /**
11082
- * Check whether a whitespace-delimited token looks like a standalone value
11083
- * (not an operator or partial expression): it starts like a value and does
11084
- * not end with an operator still waiting for its operand.
11085
- */
11086
- function isStandaloneValue(token) {
11087
- return startsLikeValue(token) && !endsWithOperator(token);
11088
- }
11089
- function startsLikeValue(token) {
11090
- const first = token[0];
11091
- if (first === "\"" || first === "'" || first === "`") return true;
11092
- if (/^[$_@]\w|^%[A-Za-z_]/.test(token)) return true;
11093
- if (/^[+-]?(?:\d|\.\d)/.test(token)) return true;
11094
- if (first === "(" || first === "[" || first === "{") return true;
11095
- if (/^(?:true|false|null|undefined)(?![\w$])/.test(token)) return true;
11096
- if (first === "!" && token.length > 1 && token[1] !== "=") return true;
11097
- return false;
11098
- }
11099
- /**
11100
- * Try to split a raw string on whitespace at depth 0 (respecting strings,
11101
- * template literals, parentheses, brackets, and braces). Each resulting token
11102
- * must pass `isStandaloneValue()` or the split is rejected and `null` is
11103
- * returned. The spans are those of the tokens in `raw`.
11104
- */
11105
- function trySplitOnWhitespace(raw) {
11106
- const args = topLevelSpans(raw, isWhitespace).filter(([a, b]) => b > a);
11107
- if (args.length < 2) return null;
11108
- for (const [a, b] of args) if (!isStandaloneValue(raw.slice(a, b))) return null;
11109
- return args;
11110
- }
11111
- /** `span` less the whitespace at its ends. */
11112
- function trimmed$1(src, [start, end]) {
11113
- const text = src.slice(start, end);
11114
- const lead = text.length - text.trimStart().length;
11115
- return [start + lead, Math.max(start + lead, end - (text.length - text.trimEnd().length))];
11116
- }
11117
- /**
11118
- * Where the arguments in `raw` are written (see `splitArgs`), as spans of
11119
- * `raw`.
11120
- */
11121
- function splitArgSpans(raw) {
11122
- const args = topLevelSpans(raw, (ch) => ch === ",").map((span) => trimmed$1(raw, span));
11123
- const hasComma = args.length > 1;
11124
- const last = args[args.length - 1];
11125
- if (last[0] === last[1]) args.pop();
11126
- if (!hasComma && args.length === 1) {
11127
- const [start, end] = args[0];
11128
- const split = trySplitOnWhitespace(raw.slice(start, end));
11129
- if (split) return split.map(([a, b]) => [start + a, start + b]);
11130
- }
11131
- return args;
11132
- }
11133
- /**
11134
- * Split rawArgs by commas, respecting parentheses, brackets, braces, and
11135
- * strings. When no top-level commas are present, also supports adjacent quoted
11136
- * string literals separated by whitespace (e.g. `"Label" "target"`).
11137
- */
11138
- function splitArgs(raw) {
11139
- return splitArgSpans(raw).map(([a, b]) => raw.slice(a, b));
11140
- }
11141
- /** `text` as a regular expression source that matches it literally. */
11142
- function escapeRegExp(text) {
11143
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11144
- }
11145
11184
  // src/components/macros/macro-args.ts
11146
11185
  /**
11147
11186
  * The macro argument layer: reads a macro's raw argument text into the
@@ -11321,14 +11360,28 @@ function trimmed(src, at) {
11321
11360
  function readGroup(params, src, args, { at: srcAt, spans, toolingSpans }) {
11322
11361
  let [text, at] = trimmed(src ?? "", srcAt);
11323
11362
  const alone = !params.some((p) => p.type !== "flag" && p.required);
11324
- for (const flag of params.filter((p) => p.type === "flag")) {
11325
- const rest = src === null ? null : takeFlag(text, flag.name, alone);
11326
- args[flag.name] = rest !== null;
11327
- if (rest) {
11328
- const flagSpan = rest[0] > 0 ? [0, text.indexOf(flag.name) + flag.name.length] : [text.lastIndexOf(flag.name), text.length];
11329
- toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
11330
- [text, at] = trimmed(slice(text, rest), at + rest[0]);
11363
+ const flags = params.filter((p) => p.type === "flag");
11364
+ for (const flag of flags) args[flag.name] = false;
11365
+ const byName = new Map(flags.map((flag) => [flag.name, flag]));
11366
+ while (text && byName.size) {
11367
+ const parts = terms(text);
11368
+ if (parts.length === 0) break;
11369
+ let changed = false;
11370
+ for (const name of [slice(text, parts[parts.length - 1]), slice(text, parts[0])]) {
11371
+ const flag = byName.get(name);
11372
+ if (!flag || args[flag.name]) continue;
11373
+ const rest = src === null ? null : takeFlag(text, flag.name, alone);
11374
+ if (rest) {
11375
+ args[flag.name] = true;
11376
+ byName.delete(flag.name);
11377
+ changed = true;
11378
+ const flagSpan = rest[0] > 0 ? [0, text.indexOf(flag.name) + flag.name.length] : [text.lastIndexOf(flag.name), text.length];
11379
+ toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
11380
+ [text, at] = trimmed(slice(text, rest), at + rest[0]);
11381
+ break;
11382
+ }
11331
11383
  }
11384
+ if (!changed) break;
11332
11385
  }
11333
11386
  const positional = params.filter((p) => p.type !== "flag");
11334
11387
  if (positional.length === 0) return;
@@ -11583,13 +11636,13 @@ function parseOrError(code, goal) {
11583
11636
  parses?.set(key, result);
11584
11637
  return result;
11585
11638
  }
11586
- /** Where character `index` of the code or text of `piece` is in the source. */
11639
+ /** Where boundary `index` of a piece's code, text or name is in the source. */
11587
11640
  function pieceOffset(piece, index) {
11588
11641
  return piece.sourceOffsets?.[index] ?? piece.offset + index;
11589
11642
  }
11590
11643
  /** How much of a piece's own text or code there is (not its source extent). */
11591
11644
  function extentOf(piece) {
11592
- return piece.kind === "code" ? piece.code.length : piece.kind === "text" ? piece.text.length : piece.length;
11645
+ return piece.kind === "code" ? piece.code.length : piece.kind === "text" ? piece.text.length : piece.kind === "passage" ? piece.name.length : piece.length;
11593
11646
  }
11594
11647
  /** Macros whose whole argument text is one expression: branch conditions. */
11595
11648
  var CONDITION_MACROS = /* @__PURE__ */ new Set([
@@ -11691,6 +11744,7 @@ function parameterLookup(macros) {
11691
11744
  lookup.source = (name) => sources.get(name);
11692
11745
  const definitions = new NameMap(effectiveNamedDefinitions([...list.filter((macro) => !macro.widget), ...list.filter((macro) => macro.widget)]).map((macro) => [macro.name, macro]));
11693
11746
  lookup.pairing = {
11747
+ isStandalone: (name) => widgets.has(name) || sources.get(name) === "user",
11694
11748
  isBlock: (name) => definitions.get(name)?.block ?? isBuiltinBlockMacro(name),
11695
11749
  isRaw: (name) => isRawMacro(name, widgets.has(name)),
11696
11750
  branchParents: branchParentLookup([...definitions.values()].map((macro) => ({
@@ -11786,13 +11840,17 @@ function* codeAndText(src, tokens, parametersOf) {
11786
11840
  if (close > t + 1) {
11787
11841
  const text = src.slice(token.end, tokens[close].start);
11788
11842
  const written = text.trim();
11843
+ const at = token.end + text.indexOf(written);
11844
+ const nameValue = readPassageBody(written);
11845
+ const sourceOffsets = readWholeQuoted(written) !== null ? escapeOffsets(written.slice(1, -1), at + 1, nameValue, "quotes", true) : void 0;
11789
11846
  yield {
11790
11847
  kind: "passage",
11791
- name: readPassageBody(written),
11792
- offset: token.end + text.indexOf(written),
11848
+ name: nameValue,
11849
+ offset: at,
11793
11850
  length: written.length,
11794
11851
  macro: name,
11795
- label: src.slice(token.start, token.end)
11852
+ label: src.slice(token.start, token.end),
11853
+ ...sourceOffsets && { sourceOffsets }
11796
11854
  };
11797
11855
  }
11798
11856
  }
@@ -11882,7 +11940,7 @@ function nestedPiece(piece, toRoot, where) {
11882
11940
  nested: true,
11883
11941
  where
11884
11942
  };
11885
- if (piece.kind === "passage" || piece.kind === "argument-error") {
11943
+ if (piece.kind === "argument-error") {
11886
11944
  const length = toRoot(piece.offset + piece.length) - offset;
11887
11945
  return {
11888
11946
  ...piece,
@@ -11892,7 +11950,7 @@ function nestedPiece(piece, toRoot, where) {
11892
11950
  }
11893
11951
  const extent = extentOf(piece);
11894
11952
  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;
11895
- return sourceOffsets ? {
11953
+ const mapped = sourceOffsets ? {
11896
11954
  ...piece,
11897
11955
  ...nested,
11898
11956
  sourceOffsets
@@ -11900,6 +11958,10 @@ function nestedPiece(piece, toRoot, where) {
11900
11958
  ...piece,
11901
11959
  ...nested
11902
11960
  };
11961
+ return mapped.kind === "passage" ? {
11962
+ ...mapped,
11963
+ length: toRoot(piece.offset + mapped.length) - offset
11964
+ } : mapped;
11903
11965
  }
11904
11966
  /** An escape sequence of a JavaScript string literal (with its backslash). */
11905
11967
  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;
@@ -11928,9 +11990,10 @@ function escapeAt(raw, i, escapes) {
11928
11990
  * written as `raw` from `at` on (its escapes are those of `escapes`), is in
11929
11991
  * the source, and where the text ends. A character that an escape stands for
11930
11992
  * is where the escape begins. None when the text is where its length says, or
11931
- * is not that string.
11993
+ * is not that string. With `includeLinear`, return the map even without
11994
+ * escapes (a passage piece's offset includes the opening quote).
11932
11995
  */
11933
- function escapeOffsets(raw, at, value, escapes) {
11996
+ function escapeOffsets(raw, at, value, escapes, includeLinear = false) {
11934
11997
  const offsets = [];
11935
11998
  let escaped = false;
11936
11999
  let i = 0;
@@ -11946,8 +12009,14 @@ function escapeOffsets(raw, at, value, escapes) {
11946
12009
  escaped = true;
11947
12010
  i += escape.length;
11948
12011
  }
12012
+ while (raw[i] === "\\") {
12013
+ const escape = escapeAt(raw, i, escapes);
12014
+ if (!escape || escape.text.length !== 0) break;
12015
+ escaped = true;
12016
+ i += escape.length;
12017
+ }
11949
12018
  offsets.push(at + i);
11950
- return escaped ? offsets : void 0;
12019
+ return escaped || includeLinear ? offsets : void 0;
11951
12020
  }
11952
12021
  /** The code and text in the arguments `args` (at `offset`) of `macro`. */
11953
12022
  function* argPieces(args, offset, params, macro, label, navigation = []) {
@@ -12015,20 +12084,21 @@ function* valuePieces(args, offset, params, values, spans, macro, label, escapes
12015
12084
  const [start, end] = span;
12016
12085
  const written = args.slice(start, end);
12017
12086
  /** The name as written (quotes included), at the argument. */
12018
- const passage = (passageName) => ({
12087
+ const passage = (passageName, at, mode = escapes) => ({
12019
12088
  kind: "passage",
12020
12089
  name: passageName,
12021
12090
  offset: offset + start,
12022
12091
  length: end - start,
12023
12092
  macro: name,
12024
12093
  label,
12094
+ sourceOffsets: escapeOffsets(args.slice(at - offset), at, passageName, mode, true),
12025
12095
  ...navigation.includes(param.name) && { navigation: true }
12026
12096
  });
12027
12097
  const goal = codeGoal(param);
12028
12098
  if (param.type === "passage") {
12029
12099
  const target = passageTarget(value);
12030
12100
  if (target.kind === "name") {
12031
- yield passage(target.name);
12101
+ yield passage(target.name, offset + start + 1, "javascript");
12032
12102
  continue;
12033
12103
  }
12034
12104
  }
@@ -12061,7 +12131,7 @@ function* valuePieces(args, offset, params, values, spans, macro, label, escapes
12061
12131
  };
12062
12132
  if (sourceOffsets) piece.sourceOffsets = sourceOffsets;
12063
12133
  yield piece;
12064
- } else if (holds === "passage") yield passage(value);
12134
+ } else if (holds === "passage") yield passage(value, at);
12065
12135
  else if (holds === "markup") {
12066
12136
  const piece = textPiece(value, at, `In the ${param.name} of {${macro}}: `);
12067
12137
  if (sourceOffsets) piece.sourceOffsets = sourceOffsets;
@@ -12615,6 +12685,7 @@ function validateMarkup(passages, options) {
12615
12685
  const diagnostics = [];
12616
12686
  const positions = /* @__PURE__ */ new Map();
12617
12687
  const hooks = {
12688
+ ...options.parametersOf?.pairing?.isStandalone && { isStandalone: options.parametersOf.pairing.isStandalone },
12618
12689
  ...options.isBlockMacro && { isBlock: options.isBlockMacro },
12619
12690
  ...options.branchParents && { branchParents: options.branchParents },
12620
12691
  isRaw: (name) => isRawMacro(name, options.parametersOf ? options.parametersOf.widget?.(name) !== void 0 : void 0)
@@ -13929,29 +14000,46 @@ var Bindings = class {
13929
14000
  */
13930
14001
  statementEnd(from) {
13931
14002
  const { code } = this;
13932
- const start = this.forward(from);
13933
- const block = this.byOpen.get(start);
13934
- if (block?.kind === "{") return Math.min(block.close + 1, code.length);
13935
- const word = this.wordAt(start);
13936
- if (/^(?:if|for|while|with)$/.test(word)) {
13937
- let paren = this.forward(start + word.length);
13938
- if (word === "for" && this.wordAt(paren) === "await") paren = this.forward(paren + 5);
13939
- const header = this.byOpen.get(paren);
13940
- if (header) {
13941
- const end = this.statementEnd(header.close + 1);
14003
+ const pendingIf = [];
14004
+ statements: while (true) {
14005
+ const start = this.forward(from);
14006
+ const block = this.byOpen.get(start);
14007
+ let end;
14008
+ if (block?.kind === "{") end = Math.min(block.close + 1, code.length);
14009
+ else {
14010
+ const word = this.wordAt(start);
14011
+ if (/^(?:if|for|while|with)$/.test(word)) {
14012
+ let paren = this.forward(start + word.length);
14013
+ if (word === "for" && this.wordAt(paren) === "await") paren = this.forward(paren + 5);
14014
+ const header = this.byOpen.get(paren);
14015
+ if (header) {
14016
+ pendingIf.push(word === "if");
14017
+ from = header.close + 1;
14018
+ continue;
14019
+ }
14020
+ }
14021
+ for (end = start; end < code.length; end++) {
14022
+ const c = code.charAt(end);
14023
+ if (c === ";") {
14024
+ end++;
14025
+ break;
14026
+ }
14027
+ if (CLOSERS[c]) break;
14028
+ const group = this.byOpen.get(end);
14029
+ if (group) end = group.close;
14030
+ else if (c === "\n" && this.startsStatement(end)) break;
14031
+ }
14032
+ }
14033
+ while (pendingIf.length) {
14034
+ const isIf = pendingIf.pop();
13942
14035
  const next = this.forward(end);
13943
- return word === "if" && this.wordAt(next) === "else" ? this.statementEnd(next + 4) : end;
14036
+ if (isIf && this.wordAt(next) === "else") {
14037
+ from = next + 4;
14038
+ continue statements;
14039
+ }
13944
14040
  }
14041
+ return end;
13945
14042
  }
13946
- for (let end = start; end < code.length; end++) {
13947
- const c = code.charAt(end);
13948
- if (c === ";") return end + 1;
13949
- if (CLOSERS[c]) return end;
13950
- const group = this.byOpen.get(end);
13951
- if (group) end = group.close;
13952
- else if (c === "\n" && this.startsStatement(end)) return end;
13953
- }
13954
- return code.length;
13955
14043
  }
13956
14044
  /** Whether the line break at `index` ends a statement, and one follows. */
13957
14045
  startsStatement(index) {
@@ -25829,15 +25917,26 @@ function joinSpans(text, spans, sentinel) {
25829
25917
  }
25830
25918
  return out + text.slice(last);
25831
25919
  }
25920
+ /** Collapse the trailing blank lines without probing every whitespace suffix. */
25921
+ function trimBlankLines(text) {
25922
+ let end = text.length;
25923
+ let newline = false;
25924
+ while (end > 0 && /[ \t\n]/.test(text[end - 1])) {
25925
+ newline || (newline = text[end - 1] === "\n");
25926
+ end--;
25927
+ }
25928
+ return newline ? text.slice(0, end) + "\n" : text;
25929
+ }
25832
25930
  async function formatLf(text, options) {
25833
25931
  const { prettier, prettierOptions } = options;
25834
25932
  let body = text;
25835
25933
  if (options.kind === "script" || options.kind === "stylesheet") {
25836
25934
  const format = options.kind === "script" ? formatJS : formatCSS;
25837
25935
  const code = body.trim();
25838
- return (await format(code, prettier, prettierOptions) ?? code).trim().replace(/\n*$/, "\n");
25936
+ return (await format(code, prettier, prettierOptions) ?? code).trim() + "\n";
25839
25937
  }
25840
25938
  const isBlock = options.isBlock ?? defaultIsBlock(body, options.blockMacros);
25939
+ if (analyzeMarkup(body, { hooks: { isBlock } }).errors.some((error) => error.code === "nesting-limit")) return text;
25841
25940
  const isDedenting = options.isDedentingSubMacro ?? ((name) => DEFAULT_DEDENTING.has(name.toLowerCase()));
25842
25941
  const sentinel = newlineSentinel(body);
25843
25942
  const literalSentinel = newlineSentinel(body + sentinel);
@@ -25845,13 +25944,13 @@ async function formatLf(text, options) {
25845
25944
  const literalMarkers = /* @__PURE__ */ new Set();
25846
25945
  const fenced = markdownLines(body, isBlock, /* @__PURE__ */ new Set(["codeFenced"]));
25847
25946
  const literalHtml = whitespaceSensitiveLines(body, isBlock);
25848
- body = body.split("\n").map((line, index) => {
25947
+ body = trimBlankLines(body.split("\n").map((line, index) => {
25849
25948
  if (!fenced.has(index) && !literalHtml.has(index)) return line;
25850
25949
  const marker = `${literalSentinel}L${literalLines.size}${literalSentinel}`;
25851
25950
  literalLines.set(marker, line);
25852
25951
  literalMarkers.add(marker);
25853
25952
  return (line.match(/^[ \t]*/)?.[0] ?? "") + marker;
25854
- }).join("\n").replace(/(?:[ \t]*\n)+[ \t]*$/, "\n");
25953
+ }).join("\n"));
25855
25954
  const lines = [];
25856
25955
  /** Indices in lines whose trailing two spaces are a hard line break. */
25857
25956
  const hardBreakLines = /* @__PURE__ */ new Set();
@@ -25908,8 +26007,10 @@ async function formatLf(text, options) {
25908
26007
  lines.push(line);
25909
26008
  }
25910
26009
  }
25911
- let output = lines.map((l, i) => hardBreakLines.has(i) || preservedLines.has(i) ? l : l.replace(/\s+$/, "")).join("\n");
25912
- output = output.replace(/\n*$/, "\n");
26010
+ let output = lines.map((l, i) => hardBreakLines.has(i) || preservedLines.has(i) ? l : l.trimEnd()).join("\n");
26011
+ let end = output.length;
26012
+ while (end > 0 && output[end - 1] === "\n") end--;
26013
+ output = output.slice(0, end) + "\n";
25913
26014
  return replaceAll(output.split("\n").map((line) => literalLines.get(line.trim()) ?? line).join("\n"), sentinel, "\n");
25914
26015
  }
25915
26016
  /** Literal HTML and opaque SVG, whose text can inherit significant whitespace. */
@@ -26075,7 +26176,7 @@ function indentMacros(lines, isBlock, isDedenting, literalMarkers) {
26075
26176
  col = body.keepOriginal ? line.col : base + (body.keepRelative ? line.col - (isRoot ? 0 : body.minCol) : 0);
26076
26177
  }
26077
26178
  outCol.push(col);
26078
- const hardBreak = / {2,}$/.test(lines[i]) && info[i + 1] ? " " : "";
26179
+ const hardBreak = lines[i].endsWith(" ") && info[i + 1] ? " " : "";
26079
26180
  result.push(" ".repeat(col) + line.text + hardBreak);
26080
26181
  }
26081
26182
  return result;
@@ -26326,6 +26427,7 @@ function tokenizationOptions(options) {
26326
26427
  isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0),
26327
26428
  isBlock: blockLookup(macros),
26328
26429
  branchParents: branchParentLookup(macros),
26430
+ isStandalone: parametersOf.pairing.isStandalone,
26329
26431
  ...options.hooks
26330
26432
  }
26331
26433
  };