@rohal12/twee-ts 1.15.2 → 1.15.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -5349,6 +5349,1101 @@ function storyToJSON(story) {
5349
5349
  obj.passages = storyPassages;
5350
5350
  return JSON.stringify(obj, null, 2);
5351
5351
  }
5352
+ const SINGLE_ESCAPES = /* @__PURE__ */ new Map([
5353
+ ["b", "\b"],
5354
+ ["f", "\f"],
5355
+ ["n", "\n"],
5356
+ ["r", "\r"],
5357
+ ["t", " "],
5358
+ ["v", "\v"]
5359
+ ]);
5360
+ const HEX_RE = /^[0-9A-Fa-f]+$/;
5361
+ const DIGIT_RE = /^[0-9]$/;
5362
+ const LINE_TERMINATORS = "\n\r\u2028\u2029";
5363
+ /**
5364
+ * The value of a quoted JavaScript string literal (quotes included), as strict-mode JavaScript
5365
+ * evaluates it: `\"`, `\'`, `\\`, `\n`, `\xHH`, `\uHHHH`, `\u{H…}`, line continuations, and a
5366
+ * backslash before any other character gives that character. Returns `undefined` for what
5367
+ * strict mode rejects, such as `\1` or a raw carriage return.
5368
+ */
5369
+ function evalStringLiteral(literal) {
5370
+ const quote = literal[0];
5371
+ const last = literal.length - 1;
5372
+ if (quote !== "\"" && quote !== "'" || last < 1 || literal[last] !== quote) return;
5373
+ return cookEscapes(literal.slice(1, last), quote);
5374
+ }
5375
+ /**
5376
+ * Decodes the body of a string literal, given its quote, or a piece of a template literal
5377
+ * (`quote` undefined), as strict-mode JavaScript does. A string may not hold its own quote or a
5378
+ * raw line feed or carriage return; a template piece may, and turns `\r\n` and `\r` into `\n`.
5379
+ */
5380
+ function cookEscapes(body, quote) {
5381
+ let value = "";
5382
+ let i = 0;
5383
+ while (i < body.length) {
5384
+ const ch = body.charAt(i);
5385
+ if (ch !== "\\") {
5386
+ if (quote !== void 0 && (ch === quote || ch === "\n" || ch === "\r")) return;
5387
+ if (ch === "\r") {
5388
+ value += "\n";
5389
+ i += body.charAt(i + 1) === "\n" ? 2 : 1;
5390
+ } else {
5391
+ value += ch;
5392
+ i += 1;
5393
+ }
5394
+ continue;
5395
+ }
5396
+ if (i + 1 >= body.length) return;
5397
+ const escaped = body.charAt(i + 1);
5398
+ i += 2;
5399
+ const single = SINGLE_ESCAPES.get(escaped);
5400
+ if (single !== void 0) {
5401
+ value += single;
5402
+ continue;
5403
+ }
5404
+ switch (escaped) {
5405
+ case "0":
5406
+ if (DIGIT_RE.test(body.charAt(i))) return;
5407
+ value += "\0";
5408
+ break;
5409
+ case "1":
5410
+ case "2":
5411
+ case "3":
5412
+ case "4":
5413
+ case "5":
5414
+ case "6":
5415
+ case "7":
5416
+ case "8":
5417
+ case "9": return;
5418
+ case "x": {
5419
+ const hex = body.slice(i, i + 2);
5420
+ if (hex.length !== 2 || !HEX_RE.test(hex)) return;
5421
+ value += String.fromCharCode(parseInt(hex, 16));
5422
+ i += 2;
5423
+ break;
5424
+ }
5425
+ case "u": {
5426
+ const unicode = readUnicodeEscape(body, i);
5427
+ if (unicode === void 0) return;
5428
+ value += unicode.char;
5429
+ i = unicode.end;
5430
+ break;
5431
+ }
5432
+ case "\r":
5433
+ if (body[i] === "\n") i += 1;
5434
+ break;
5435
+ case "\n":
5436
+ case "\u2028":
5437
+ case "\u2029": break;
5438
+ default: value += escaped;
5439
+ }
5440
+ }
5441
+ return value;
5442
+ }
5443
+ /** Reads the part of `\uHHHH` or `\u{H…}` after the `u`. */
5444
+ function readUnicodeEscape(body, from) {
5445
+ if (body[from] === "{") {
5446
+ const close = body.indexOf("}", from + 1);
5447
+ if (close === -1) return;
5448
+ const hex = body.slice(from + 1, close);
5449
+ if (!HEX_RE.test(hex)) return;
5450
+ const codePoint = parseInt(hex, 16);
5451
+ return codePoint > 1114111 ? void 0 : {
5452
+ char: String.fromCodePoint(codePoint),
5453
+ end: close + 1
5454
+ };
5455
+ }
5456
+ const hex = body.slice(from, from + 4);
5457
+ if (hex.length !== 4 || !HEX_RE.test(hex)) return;
5458
+ return {
5459
+ char: String.fromCharCode(parseInt(hex, 16)),
5460
+ end: from + 4
5461
+ };
5462
+ }
5463
+ const REGEX_KEYWORDS = /* @__PURE__ */ new Set([
5464
+ "await",
5465
+ "case",
5466
+ "delete",
5467
+ "do",
5468
+ "else",
5469
+ "in",
5470
+ "instanceof",
5471
+ "new",
5472
+ "of",
5473
+ "return",
5474
+ "throw",
5475
+ "typeof",
5476
+ "void",
5477
+ "yield"
5478
+ ]);
5479
+ const WORD_RE = /[$\p{ID_Continue}\u200c\u200d]+/uy;
5480
+ const WHITESPACE_RE = /\s/;
5481
+ const LINE_TERMINATOR_RE$1 = /[\n\r\u2028\u2029]/g;
5482
+ /**
5483
+ * The values of the string and template literals in JavaScript source. A template literal's
5484
+ * value keeps its text and has `SUBSTITUTION` where each `${…}` was; the strings inside a
5485
+ * substitution are values of their own. Comments and regular expression literals are skipped;
5486
+ * whether a `/` starts a regular expression is judged from the token before it. Malformed
5487
+ * source is read on as far as it can be.
5488
+ */
5489
+ function javaScriptStrings(source) {
5490
+ const strings = [];
5491
+ const frames = [{
5492
+ kind: "code",
5493
+ braces: 0
5494
+ }];
5495
+ let regexAllowed = true;
5496
+ let afterDot = false;
5497
+ const failedUntil = /* @__PURE__ */ new Map();
5498
+ let i = 0;
5499
+ while (i < source.length) {
5500
+ const frame = frames[frames.length - 1];
5501
+ if (frame === void 0) break;
5502
+ const ch = source.charAt(i);
5503
+ const next = source.charAt(i + 1);
5504
+ if (frame.kind === "template") {
5505
+ if (ch === "`" || ch === "$" && next === "{") {
5506
+ const piece = cookEscapes(source.slice(frame.pieceStart, i), void 0);
5507
+ const value = frame.value + (piece ?? "");
5508
+ const valid = frame.valid && piece !== void 0;
5509
+ frames.pop();
5510
+ if (ch === "`") {
5511
+ if (valid) strings.push(value);
5512
+ i += 1;
5513
+ regexAllowed = false;
5514
+ afterDot = false;
5515
+ } else {
5516
+ frames.push({
5517
+ kind: "template",
5518
+ value: value + "﷐",
5519
+ pieceStart: -1,
5520
+ valid
5521
+ });
5522
+ frames.push({
5523
+ kind: "code",
5524
+ braces: 0
5525
+ });
5526
+ i += 2;
5527
+ regexAllowed = true;
5528
+ afterDot = false;
5529
+ }
5530
+ } else i += ch === "\\" ? 2 : 1;
5531
+ continue;
5532
+ }
5533
+ if (ch === "/" && next === "/") {
5534
+ const lineEnd = searchFrom$1(LINE_TERMINATOR_RE$1, source, i + 2);
5535
+ i = lineEnd === -1 ? source.length : lineEnd;
5536
+ continue;
5537
+ }
5538
+ if (ch === "/" && next === "*") {
5539
+ const close = source.indexOf("*/", i + 2);
5540
+ i = close === -1 ? source.length : close + 2;
5541
+ continue;
5542
+ }
5543
+ if (ch === "/" && regexAllowed && i >= (failedUntil.get("/") ?? 0)) {
5544
+ const end = endOfRegularExpression(source, i);
5545
+ if (end.end !== void 0) {
5546
+ i = end.end;
5547
+ regexAllowed = false;
5548
+ afterDot = false;
5549
+ continue;
5550
+ }
5551
+ failedUntil.set("/", end.stop);
5552
+ }
5553
+ if ((ch === "\"" || ch === "'") && i >= (failedUntil.get(ch) ?? 0)) {
5554
+ const end = endOfJavaScriptString(source, i);
5555
+ if (end.end !== void 0) {
5556
+ const value = evalStringLiteral(source.slice(i, end.end));
5557
+ if (value !== void 0) strings.push(value);
5558
+ i = end.end;
5559
+ regexAllowed = false;
5560
+ afterDot = false;
5561
+ continue;
5562
+ }
5563
+ failedUntil.set(ch, end.stop);
5564
+ }
5565
+ if (ch === "`") {
5566
+ frames.push({
5567
+ kind: "template",
5568
+ value: "",
5569
+ pieceStart: i + 1,
5570
+ valid: true
5571
+ });
5572
+ i += 1;
5573
+ continue;
5574
+ }
5575
+ const word = wordAt(source, i);
5576
+ if (word !== null) {
5577
+ regexAllowed = !afterDot && REGEX_KEYWORDS.has(word[0]);
5578
+ afterDot = false;
5579
+ i += word[0].length;
5580
+ continue;
5581
+ }
5582
+ if ((ch === "+" || ch === "-") && next === ch) {
5583
+ regexAllowed = false;
5584
+ afterDot = false;
5585
+ i += 2;
5586
+ continue;
5587
+ }
5588
+ if (frame.kind === "code" && frames.length > 1 && (ch === "{" || ch === "}")) {
5589
+ if (ch === "{") frames[frames.length - 1] = {
5590
+ kind: "code",
5591
+ braces: frame.braces + 1
5592
+ };
5593
+ else if (frame.braces > 0) frames[frames.length - 1] = {
5594
+ kind: "code",
5595
+ braces: frame.braces - 1
5596
+ };
5597
+ else {
5598
+ frames.pop();
5599
+ const template = frames.pop();
5600
+ if (template?.kind === "template") frames.push({
5601
+ ...template,
5602
+ pieceStart: i + 1
5603
+ });
5604
+ i += 1;
5605
+ continue;
5606
+ }
5607
+ }
5608
+ if (!WHITESPACE_RE.test(ch)) {
5609
+ regexAllowed = !")]}".includes(ch);
5610
+ afterDot = ch === ".";
5611
+ }
5612
+ i += 1;
5613
+ }
5614
+ return strings;
5615
+ }
5616
+ /** The name, keyword or number that starts at `pos`, if one does. */
5617
+ function wordAt(source, pos) {
5618
+ const code = source.charCodeAt(pos);
5619
+ if (code < 128 && !(code >= 48 && code <= 57 || (code | 32) >= 97 && (code | 32) <= 122 || code === 95 || code === 36)) return null;
5620
+ WORD_RE.lastIndex = pos;
5621
+ return WORD_RE.exec(source);
5622
+ }
5623
+ /** Index of the first match of a global `re` at or after `from`, or -1. */
5624
+ function searchFrom$1(re, text, from) {
5625
+ re.lastIndex = from;
5626
+ const m = re.exec(text);
5627
+ return m === null ? -1 : m.index;
5628
+ }
5629
+ /**
5630
+ * Where a string literal that opens at `pos` ends, or, if it doesn't close on its line, where
5631
+ * the scan stopped. A string with the same quote that starts before that stop, inside this one,
5632
+ * doesn't close either.
5633
+ */
5634
+ function endOfJavaScriptString(source, pos) {
5635
+ const quote = source.charAt(pos);
5636
+ let i = pos + 1;
5637
+ while (i < source.length) {
5638
+ const ch = source.charAt(i);
5639
+ if (ch === quote) return {
5640
+ end: i + 1,
5641
+ stop: i
5642
+ };
5643
+ if (ch === "\n" || ch === "\r") return {
5644
+ end: void 0,
5645
+ stop: i
5646
+ };
5647
+ if (ch === "\\") i += source.startsWith("\r\n", i + 1) ? 3 : 2;
5648
+ else i += 1;
5649
+ }
5650
+ return {
5651
+ end: void 0,
5652
+ stop: source.length
5653
+ };
5654
+ }
5655
+ /**
5656
+ * Where a regular expression literal that opens at `pos` ends, flags included, or, if none
5657
+ * closes on the line, where the line ends. A `/` before that is then read as a division.
5658
+ */
5659
+ function endOfRegularExpression(source, pos) {
5660
+ let inClass = false;
5661
+ let i = pos + 1;
5662
+ while (i < source.length) {
5663
+ const ch = source.charAt(i);
5664
+ if (LINE_TERMINATORS.includes(ch)) return {
5665
+ end: void 0,
5666
+ stop: i
5667
+ };
5668
+ if (ch === "\\") {
5669
+ const escaped = source.charAt(i + 1);
5670
+ if (escaped === "" || LINE_TERMINATORS.includes(escaped)) return {
5671
+ end: void 0,
5672
+ stop: i + 1
5673
+ };
5674
+ i += 2;
5675
+ continue;
5676
+ }
5677
+ if (ch === "[") inClass = true;
5678
+ else if (ch === "]") inClass = false;
5679
+ else if (ch === "/" && !inClass) {
5680
+ WORD_RE.lastIndex = i + 1;
5681
+ const flags = WORD_RE.exec(source);
5682
+ return {
5683
+ end: i + 1 + (flags === null ? 0 : flags[0].length),
5684
+ stop: i
5685
+ };
5686
+ }
5687
+ i += 1;
5688
+ }
5689
+ return {
5690
+ end: void 0,
5691
+ stop: source.length
5692
+ };
5693
+ }
5694
+ //#endregion
5695
+ //#region src/sugarcube-macros.ts
5696
+ /**
5697
+ * Reads SugarCube 2 macro calls the way SugarCube 2.37.3 does, so the link check sees the same
5698
+ * passage names that `<<link>>` and `<<goto>>` use when the story plays.
5699
+ *
5700
+ * Each step follows a part of SugarCube's macro parser:
5701
+ * - `findMacroTags` finds where a tag starts and ends (the parser's `lookahead` pattern);
5702
+ * - `parseMacroArgs` splits the text after the macro name into arguments (`parseArgs`);
5703
+ * - quoted arguments are evaluated as strict-mode JavaScript strings (`evalStringLiteral`).
5704
+ *
5705
+ * Of the rest of the wikifier, only comments, `<script>` elements and `<<script>>` bodies are
5706
+ * told apart; other markup, such as verbatim text, is read as markup (see
5707
+ * `findMacroPassageLinks`).
5708
+ */
5709
+ const NAME_RE = /\/?[A-Za-z][\w-]*|[=-]/y;
5710
+ const SPACES_RE = /\s*/y;
5711
+ const LINE_TERMINATOR_RE = /[\n\r\u2028\u2029]/g;
5712
+ const SQUARE_BRACKET_OPEN_RE = /\[(?:[<>]?[Ii][Mm][Gg])?\[/y;
5713
+ const SPACE_RE = /[\s\u180e]/g;
5714
+ const NOT_SPACE_RE = /[^\s\u180e]/g;
5715
+ const VARIABLE_RE = /^[$_][$A-Z_a-z][$0-9A-Z_a-z]*/;
5716
+ const SETTINGS_OR_SETUP_RE = /^(?:settings|setup)[.[]/;
5717
+ const IMAGE_MARKUP_CHARS = "<>IiMmGg";
5718
+ /**
5719
+ * Macros that SugarCube doesn't split into arguments (`skipArgs` in 2.37.3), with their child
5720
+ * tags that do the same: `<<elseif>>` and `<<else>>` of `<<if>>`, and `<<optionsfrom>>` of
5721
+ * `<<cycle>>` and `<<listbox>>`. Their argument text is TwineScript, or for `<<capture>>`,
5722
+ * `<<unset>>` and `<<for>>` a syntax of their own; either way its strings are JavaScript strings.
5723
+ */
5724
+ const RAW_ARGUMENT_MACROS = /* @__PURE__ */ new Set([
5725
+ "break",
5726
+ "capture",
5727
+ "continue",
5728
+ "done",
5729
+ "else",
5730
+ "elseif",
5731
+ "for",
5732
+ "if",
5733
+ "nobr",
5734
+ "optionsfrom",
5735
+ "print",
5736
+ "=",
5737
+ "-",
5738
+ "run",
5739
+ "set",
5740
+ "silent",
5741
+ "silently",
5742
+ "stop",
5743
+ "switch",
5744
+ "unset",
5745
+ "waitforaudio"
5746
+ ]);
5747
+ /**
5748
+ * How deep strings inside macro arguments are read for further calls. Stories nest two or three
5749
+ * levels; the limit keeps the work linear in the size of the text on any input.
5750
+ */
5751
+ const MAX_STRING_DEPTH = 10;
5752
+ /** A context for reading `text`: the closer search may read four times it, plus an allowance. */
5753
+ function readContext(text) {
5754
+ return {
5755
+ depth: 0,
5756
+ budget: { left: 4 * text.length + 1e5 }
5757
+ };
5758
+ }
5759
+ function deeper(context) {
5760
+ return {
5761
+ depth: context.depth + 1,
5762
+ budget: context.budget
5763
+ };
5764
+ }
5765
+ /** Index of the first match of a global `re` at or after `from`, or -1. */
5766
+ function searchFrom(re, text, from) {
5767
+ re.lastIndex = from;
5768
+ const m = re.exec(text);
5769
+ return m === null ? -1 : m.index;
5770
+ }
5771
+ /**
5772
+ * Finds the macro tags in text, in order, trying a tag at every `<<` as SugarCube's macro
5773
+ * parser does. A tag that doesn't parse is skipped, and the search goes on after its `<<`.
5774
+ *
5775
+ * Gives the same tags as SugarCube's pattern, without its backtracking: that pattern takes
5776
+ * exponential time when no `>>` follows a `<<name`, which a script passage can contain (`1<<n`).
5777
+ */
5778
+ function findMacroTags(text) {
5779
+ return scanTags(text).map((scanned) => scanned.tag);
5780
+ }
5781
+ function scanTags(text) {
5782
+ const matchTagAt = tagMatcher(text);
5783
+ const tags = [];
5784
+ let start = text.indexOf("<<");
5785
+ while (start !== -1) {
5786
+ const scanned = matchTagAt(start);
5787
+ if (scanned === void 0) start = text.indexOf("<<", start + 2);
5788
+ else {
5789
+ tags.push(scanned);
5790
+ start = text.indexOf("<<", scanned.tag.end);
5791
+ }
5792
+ }
5793
+ return tags;
5794
+ }
5795
+ /**
5796
+ * Returns a function that matches a tag at a `<<` in `text`. It must be called for positions in
5797
+ * increasing order.
5798
+ *
5799
+ * The arguments may contain comments, backquoted expressions, quoted strings and link markup,
5800
+ * whose `>>` doesn't end the tag. SugarCube's pattern treats such a part as a unit only if a
5801
+ * `>>` still follows it, and otherwise as plain characters; `lastClose`, the last `>>` in the
5802
+ * text, answers that in constant time. Once a part is read as plain characters, a part of the
5803
+ * same kind that starts inside it can't end before `lastClose` either, in this tag or a later
5804
+ * one, so it isn't scanned again: `scanFrom` records where each kind may next be scanned. This
5805
+ * keeps the search linear. `onWork` is told how many characters each step reads. (Exported for
5806
+ * tests; the module is not part of the package's API.)
5807
+ */
5808
+ function tagMatcher(text, lastClose = text.lastIndexOf(">>"), onWork = () => {}) {
5809
+ const scanFrom = /* @__PURE__ */ new Map();
5810
+ return (start) => {
5811
+ NAME_RE.lastIndex = start + 2;
5812
+ const nameMatch = NAME_RE.exec(text);
5813
+ if (nameMatch === null) {
5814
+ onWork(2);
5815
+ return;
5816
+ }
5817
+ SPACES_RE.lastIndex = NAME_RE.lastIndex;
5818
+ SPACES_RE.exec(text);
5819
+ const argsStart = SPACES_RE.lastIndex;
5820
+ onWork(argsStart - start);
5821
+ let innerCall;
5822
+ let pos = argsStart;
5823
+ while (pos <= lastClose) {
5824
+ if (text.startsWith(">>", pos)) return {
5825
+ tag: {
5826
+ name: nameMatch[0],
5827
+ args: text.slice(argsStart, pos),
5828
+ start,
5829
+ end: pos + 2
5830
+ },
5831
+ innerCall
5832
+ };
5833
+ const kind = argumentPartKindAt(text, pos);
5834
+ const from = kind === void 0 ? void 0 : scanFrom.get(kind);
5835
+ if (kind !== void 0 && (from === void 0 || pos >= from)) {
5836
+ const part = scanArgumentPart(text, pos, kind);
5837
+ onWork(part.stop - pos);
5838
+ if (part.end !== void 0 && part.end <= lastClose) {
5839
+ pos = part.end;
5840
+ continue;
5841
+ }
5842
+ scanFrom.set(kind, part.stop);
5843
+ }
5844
+ if (innerCall === void 0 && startsPassageLinkCall(text, pos)) innerCall = pos;
5845
+ onWork(1);
5846
+ pos += 1;
5847
+ }
5848
+ };
5849
+ }
5850
+ /** Whether a `<<link` or `<<goto` tag, and not a longer macro name, starts at `pos`. */
5851
+ function startsPassageLinkCall(text, pos) {
5852
+ if (!text.startsWith("<<", pos)) return false;
5853
+ NAME_RE.lastIndex = pos + 2;
5854
+ const name = NAME_RE.exec(text)?.[0];
5855
+ return name === "link" || name === "goto";
5856
+ }
5857
+ /** The kind of argument part that opens at `pos`, if one does. */
5858
+ function argumentPartKindAt(text, pos) {
5859
+ const ch = text[pos];
5860
+ switch (ch) {
5861
+ case "/": {
5862
+ const next = text[pos + 1];
5863
+ return next === "*" ? "/*" : next === "/" ? "//" : void 0;
5864
+ }
5865
+ case "`":
5866
+ case "\"":
5867
+ case "'":
5868
+ case "[": return ch;
5869
+ default: return;
5870
+ }
5871
+ }
5872
+ function scanArgumentPart(text, pos, kind) {
5873
+ switch (kind) {
5874
+ case "/*": {
5875
+ const close = text.indexOf("*/", pos + 2);
5876
+ return close === -1 ? {
5877
+ end: void 0,
5878
+ stop: text.length
5879
+ } : {
5880
+ end: close + 2,
5881
+ stop: close
5882
+ };
5883
+ }
5884
+ case "//": {
5885
+ const lineEnd = searchFrom(LINE_TERMINATOR_RE, text, pos + 2);
5886
+ if (lineEnd === -1) return {
5887
+ end: void 0,
5888
+ stop: text.length
5889
+ };
5890
+ return {
5891
+ end: text[lineEnd] === "\n" ? lineEnd + 1 : void 0,
5892
+ stop: lineEnd
5893
+ };
5894
+ }
5895
+ case "`":
5896
+ case "\"":
5897
+ case "'": return scanQuoted(text, pos, kind);
5898
+ case "[": return scanSquareBracketed(text, pos);
5899
+ default: throw new Error(`unhandled argument part: ${String(kind)}`);
5900
+ }
5901
+ }
5902
+ /** A quoted part of a tag: a backslash escapes any character except a line terminator. */
5903
+ function scanQuoted(text, pos, quote) {
5904
+ let i = pos + 1;
5905
+ while (i < text.length) {
5906
+ const ch = text[i];
5907
+ if (ch === quote) return {
5908
+ end: i + 1,
5909
+ stop: i
5910
+ };
5911
+ if (ch === "\\") {
5912
+ const next = text[i + 1];
5913
+ if (next === void 0 || "\n\r\u2028\u2029".includes(next)) return {
5914
+ end: void 0,
5915
+ stop: i
5916
+ };
5917
+ i += 2;
5918
+ } else i += 1;
5919
+ }
5920
+ return {
5921
+ end: void 0,
5922
+ stop: text.length
5923
+ };
5924
+ }
5925
+ /** Link or image markup in a tag: up to the first `]]` on the same line, plus any further `]`. */
5926
+ function scanSquareBracketed(text, pos) {
5927
+ SQUARE_BRACKET_OPEN_RE.lastIndex = pos;
5928
+ if (!SQUARE_BRACKET_OPEN_RE.test(text)) return {
5929
+ end: void 0,
5930
+ stop: pos + 1
5931
+ };
5932
+ for (let i = SQUARE_BRACKET_OPEN_RE.lastIndex; i < text.length; i++) {
5933
+ const ch = text[i];
5934
+ if (ch === "\n" || ch === "\r") return {
5935
+ end: void 0,
5936
+ stop: i
5937
+ };
5938
+ if (ch === "]" && text[i + 1] === "]") {
5939
+ let end = i + 2;
5940
+ while (text[end] === "]") end += 1;
5941
+ return {
5942
+ end,
5943
+ stop: i
5944
+ };
5945
+ }
5946
+ }
5947
+ return {
5948
+ end: void 0,
5949
+ stop: text.length
5950
+ };
5951
+ }
5952
+ function lexMacroArgs(raw) {
5953
+ const args = [];
5954
+ let pos = searchFrom(NOT_SPACE_RE, raw, 0);
5955
+ while (pos !== -1) {
5956
+ const lexed = lexArgument(raw, pos);
5957
+ if (lexed === void 0) return;
5958
+ args.push(lexed.arg);
5959
+ pos = searchFrom(NOT_SPACE_RE, raw, lexed.end);
5960
+ }
5961
+ return args;
5962
+ }
5963
+ function lexArgument(raw, pos) {
5964
+ const first = raw[pos];
5965
+ switch (first) {
5966
+ case "`": {
5967
+ const end = slurpQuote(raw, pos + 1, "`");
5968
+ return end === void 0 ? void 0 : {
5969
+ arg: {
5970
+ kind: "expression",
5971
+ code: raw.slice(pos + 1, end - 1)
5972
+ },
5973
+ end
5974
+ };
5975
+ }
5976
+ case "\"":
5977
+ case "'": {
5978
+ const end = slurpQuote(raw, pos + 1, first);
5979
+ if (end === void 0) return;
5980
+ const value = evalStringLiteral(raw.slice(pos, end));
5981
+ return value === void 0 ? void 0 : {
5982
+ arg: {
5983
+ kind: "string",
5984
+ value
5985
+ },
5986
+ end
5987
+ };
5988
+ }
5989
+ case "[": {
5990
+ const end = lexSquareBracketed(raw, pos + 1);
5991
+ return end === void 0 ? void 0 : {
5992
+ arg: { kind: "markup" },
5993
+ end
5994
+ };
5995
+ }
5996
+ default: {
5997
+ const space = searchFrom(SPACE_RE, raw, pos + 1);
5998
+ const end = space === -1 ? raw.length : space;
5999
+ return {
6000
+ arg: {
6001
+ kind: "word",
6002
+ text: raw.slice(pos, end)
6003
+ },
6004
+ end
6005
+ };
6006
+ }
6007
+ }
6008
+ }
6009
+ /**
6010
+ * Reads a quoted argument from just after its opening quote. A newline, or a backslash before a
6011
+ * newline, ends it unterminated. Returns the index after the closing quote.
6012
+ */
6013
+ function slurpQuote(raw, from, endQuote) {
6014
+ let i = from;
6015
+ while (i < raw.length) {
6016
+ const ch = raw[i];
6017
+ if (ch === endQuote) return i + 1;
6018
+ if (ch === "\n") return;
6019
+ if (ch === "\\") {
6020
+ const next = raw[i + 1];
6021
+ if (next === void 0 || next === "\n") return;
6022
+ i += 2;
6023
+ } else i += 1;
6024
+ }
6025
+ }
6026
+ /**
6027
+ * Reads link or image markup from just after its first `[`, counting nested brackets.
6028
+ * Returns the index after the closing `]]`.
6029
+ */
6030
+ function lexSquareBracketed(raw, from) {
6031
+ let i = from;
6032
+ while (i < raw.length && IMAGE_MARKUP_CHARS.includes(raw.charAt(i))) i += 1;
6033
+ if (raw[i] !== "[") return;
6034
+ i += 1;
6035
+ let depth = 2;
6036
+ while (i < raw.length) {
6037
+ const ch = raw[i];
6038
+ i += 1;
6039
+ switch (ch) {
6040
+ case "\\": {
6041
+ const next = raw[i];
6042
+ if (next === void 0 || next === "\n") return;
6043
+ i += 1;
6044
+ break;
6045
+ }
6046
+ case "\n": return;
6047
+ case "[":
6048
+ depth += 1;
6049
+ break;
6050
+ case "]":
6051
+ depth -= 1;
6052
+ if (depth < 0) return;
6053
+ if (depth === 1 && raw[i] === "]") return i + 1;
6054
+ }
6055
+ }
6056
+ }
6057
+ /** An argument's value, following SugarCube's conversions. */
6058
+ function argValue(arg) {
6059
+ switch (arg.kind) {
6060
+ case "string": return {
6061
+ type: "string",
6062
+ value: arg.value
6063
+ };
6064
+ case "expression": return { type: "other" };
6065
+ case "markup": return { type: "markup" };
6066
+ case "word": return bareWord(arg.text);
6067
+ default: throw new Error(`unhandled macro argument: ${JSON.stringify(arg)}`);
6068
+ }
6069
+ }
6070
+ /** A bare word's value, following SugarCube's conversions. */
6071
+ function bareWord(word) {
6072
+ if (VARIABLE_RE.test(word) || SETTINGS_OR_SETUP_RE.test(word)) return { type: "other" };
6073
+ switch (word) {
6074
+ case "null": return { type: "null" };
6075
+ case "undefined":
6076
+ case "true":
6077
+ case "false": return { type: "other" };
6078
+ case "NaN": return {
6079
+ type: "number",
6080
+ value: NaN
6081
+ };
6082
+ default: {
6083
+ const value = Number(word);
6084
+ return Number.isNaN(value) ? {
6085
+ type: "string",
6086
+ value: word
6087
+ } : {
6088
+ type: "number",
6089
+ value
6090
+ };
6091
+ }
6092
+ }
6093
+ }
6094
+ /** The passage name an argument gives, if it can be known without playing the story. */
6095
+ function passageName(arg) {
6096
+ switch (arg.type) {
6097
+ case "string": return arg.value.includes("﷐") ? void 0 : arg.value;
6098
+ case "number": return String(arg.value);
6099
+ case "markup":
6100
+ case "null":
6101
+ case "other": return;
6102
+ default: throw new Error(`unhandled macro argument: ${JSON.stringify(arg)}`);
6103
+ }
6104
+ }
6105
+ /**
6106
+ * The argument that names the passage in a `<<link>>` or `<<goto>>` call:
6107
+ * - `<<link linkText [passageName]>>`, unless the first argument is link or image markup, which
6108
+ * then names the passage itself and any further argument is ignored;
6109
+ * - `<<goto passageName>>`.
6110
+ *
6111
+ * In text built from a template literal, a bare word with a `${…}` in it may become several
6112
+ * words in play, so no argument after it is known.
6113
+ */
6114
+ function passageArgument(macro, lexed) {
6115
+ const index = macro === "link" ? 1 : 0;
6116
+ if (lexed.slice(0, index + 1).some((arg) => arg.kind === "word" && arg.text.includes("﷐"))) return;
6117
+ const args = lexed.map(argValue);
6118
+ switch (macro) {
6119
+ case "link": {
6120
+ const [label, passage] = args;
6121
+ return label === void 0 || label.type === "markup" || label.type === "null" ? void 0 : passage;
6122
+ }
6123
+ case "goto": return args[0];
6124
+ default: throw new Error(`unhandled macro: ${String(macro)}`);
6125
+ }
6126
+ }
6127
+ function isPassageLinkMacro(name) {
6128
+ return name === "goto" || name === "link";
6129
+ }
6130
+ /** The passage a `<<link>>` or `<<goto>>` tag names itself, if it can be known before play. */
6131
+ function ownPassageLink(tag, lexed) {
6132
+ if (!isPassageLinkMacro(tag.name)) return;
6133
+ const arg = passageArgument(tag.name, lexed);
6134
+ const passage = arg === void 0 ? void 0 : passageName(arg);
6135
+ return passage === void 0 ? void 0 : {
6136
+ macro: tag.name,
6137
+ passage
6138
+ };
6139
+ }
6140
+ /**
6141
+ * The passages a tag names: its own, if it is a `<<link>>` or `<<goto>>` call, then those of the
6142
+ * calls inside the strings of its arguments, which the macro may print or pass on
6143
+ * (`<<set _out to '<<link "Go" "Room">><</link>>'>>`). The arguments of the macros SugarCube
6144
+ * doesn't split are read as JavaScript; in others, a backquoted expression is.
6145
+ */
6146
+ function tagPassageLinks(tag, context) {
6147
+ if (RAW_ARGUMENT_MACROS.has(tag.name)) return javaScriptPassageLinks(tag.args, context);
6148
+ const lexed = lexMacroArgs(tag.args);
6149
+ if (lexed === void 0) return [];
6150
+ const own = ownPassageLink(tag, lexed);
6151
+ const inner = lexed.flatMap((arg) => {
6152
+ switch (arg.kind) {
6153
+ case "string": return markupPassageLinks(arg.value, deeper(context));
6154
+ case "expression": return javaScriptPassageLinks(arg.code, context);
6155
+ case "markup":
6156
+ case "word": return [];
6157
+ default: throw new Error(`unhandled macro argument: ${JSON.stringify(arg)}`);
6158
+ }
6159
+ });
6160
+ return own === void 0 ? inner : [own, ...inner];
6161
+ }
6162
+ /**
6163
+ * The passage named by a `<<link>>` or `<<goto>>` that appears unquoted inside another tag's
6164
+ * arguments, at `start`. SugarCube never sees such an outer "tag" when its `<<` lies in text it
6165
+ * reads as something else, such as link markup (`[[<<-- Back|Prev]]`); the call inside it then
6166
+ * runs. The call ends where the outer tag ends.
6167
+ */
6168
+ function innerPassageLink(matchTagAt, start) {
6169
+ const inner = matchTagAt(start)?.tag;
6170
+ const lexed = inner === void 0 ? void 0 : lexMacroArgs(inner.args);
6171
+ return inner === void 0 || lexed === void 0 ? void 0 : ownPassageLink(inner, lexed);
6172
+ }
6173
+ const REGION_OPEN_RE = /\/\/|\/\*|\/%|<!--|<[Ss][Cc][Rr][Ii][Pp][Tt]/g;
6174
+ const HAS_SCRIPT_OPEN_RE = /<[Ss][Cc][Rr][Ii][Pp][Tt]/;
6175
+ const SCRIPT_CLOSE_RE = /<\/[Ss][Cc][Rr][Ii][Pp][Tt]>|[\r\u2028\u2029]/g;
6176
+ const COMMENT_CLOSE_RES = {
6177
+ "/*": /\*\/|[\r\u2028\u2029]/g,
6178
+ "/%": /%\/|[\r\u2028\u2029]/g,
6179
+ "<!--": /-->|[\r\u2028\u2029]/g
6180
+ };
6181
+ /**
6182
+ * Returns a function that finds where a comment that opens at `start` ends, as SugarCube's
6183
+ * `commentByBlock` parser reads it, or `undefined` if it isn't closed. Calls of one kind must come
6184
+ * in increasing order: a search that fails stops at a line terminator or the end, and a later one
6185
+ * of the same kind that starts before that stop fails too, so it isn't made.
6186
+ */
6187
+ function commentReader(text) {
6188
+ const failedUntil = /* @__PURE__ */ new Map();
6189
+ return (kind, start) => {
6190
+ if (start < (failedUntil.get(kind) ?? -1)) return;
6191
+ const re = COMMENT_CLOSE_RES[kind];
6192
+ re.lastIndex = start + kind.length;
6193
+ const m = re.exec(text);
6194
+ if (m !== null && m[0].length > 1) return m.index + m[0].length;
6195
+ failedUntil.set(kind, m === null ? text.length : m.index);
6196
+ };
6197
+ }
6198
+ /**
6199
+ * Returns a function that reads a `<script>` element whose opener starts at a position, as
6200
+ * SugarCube's `verbatimScriptTag` parser reads it: the opener up to its `>`, then the content
6201
+ * up to the first `<\/script>`. Calls must come in increasing order; each part of the text is
6202
+ * searched once.
6203
+ */
6204
+ function scriptElementReader(text) {
6205
+ let angle = -1;
6206
+ let noAngleAfter = Infinity;
6207
+ let failedBefore = -1;
6208
+ let noCloseAfter = Infinity;
6209
+ return (start) => {
6210
+ if (start + 7 >= noAngleAfter) return {
6211
+ openerEnd: void 0,
6212
+ close: void 0
6213
+ };
6214
+ if (angle < start + 7) {
6215
+ angle = text.indexOf(">", start + 7);
6216
+ if (angle === -1) {
6217
+ noAngleAfter = start + 7;
6218
+ return {
6219
+ openerEnd: void 0,
6220
+ close: void 0
6221
+ };
6222
+ }
6223
+ }
6224
+ const openerEnd = angle + 1;
6225
+ if (openerEnd < failedBefore || openerEnd >= noCloseAfter) return {
6226
+ openerEnd,
6227
+ close: void 0
6228
+ };
6229
+ SCRIPT_CLOSE_RE.lastIndex = openerEnd;
6230
+ const m = SCRIPT_CLOSE_RE.exec(text);
6231
+ if (m === null) {
6232
+ noCloseAfter = openerEnd;
6233
+ return {
6234
+ openerEnd,
6235
+ close: void 0
6236
+ };
6237
+ }
6238
+ if (m[0].length === 1) {
6239
+ failedBefore = m.index;
6240
+ return {
6241
+ openerEnd,
6242
+ close: void 0
6243
+ };
6244
+ }
6245
+ return {
6246
+ openerEnd,
6247
+ close: m.index
6248
+ };
6249
+ };
6250
+ }
6251
+ /**
6252
+ * Returns a function that finds the tag closing the `<<script>>` body that `opener` opens, as
6253
+ * SugarCube's `parseBody` finds it: scanning tags from every `<<` after the opener, without
6254
+ * skipping anything, for the first `<<\/script>>` or `<<endscript>>` that isn't matched by a
6255
+ * later `<<script>>`. (It doesn't reproduce parseBody's rejection of a closing tag with
6256
+ * arguments, nor its resuming inside the arguments of a tag whose name starts with `/` or
6257
+ * `end`.)
6258
+ *
6259
+ * The tags found from the start of the text are those parseBody finds from any opener among
6260
+ * them, so for such an opener the answer takes constant time. An opener the walk reached after
6261
+ * a comment may not be among them, when a tag that starts in the comment runs over it; then the
6262
+ * scan starts at the body and goes on until it finds the closer or reaches a tag of that list,
6263
+ * whose answers it then uses. All such scans in one reading of a passage, strings included, stop
6264
+ * once they have read four times as many characters as the passage has, plus a fixed allowance
6265
+ * (`budget`, see `readContext`); on input built to make them read more, the openers after that
6266
+ * are taken as unclosed. That keeps the time linear. (Exported for tests; the module is not part
6267
+ * of the package's API.)
6268
+ */
6269
+ function scriptBodyCloser(text, budget) {
6270
+ const tags = findMacroTags(text);
6271
+ const indexByStart = new Map(tags.map((tag, index) => [tag.start, index]));
6272
+ const lastClose = text.lastIndexOf(">>");
6273
+ const spend = (characters) => {
6274
+ budget.left -= characters;
6275
+ };
6276
+ const step = (tag) => tag.name === "script" ? 1 : tag.name === "/script" || tag.name === "endscript" ? -1 : 0;
6277
+ const balance = [0];
6278
+ tags.forEach((tag, k) => balance.push((balance[k] ?? 0) + step(tag)));
6279
+ const firstBelow = [];
6280
+ const candidates = [];
6281
+ for (let k = balance.length - 1; k >= 0; k--) {
6282
+ const here = balance[k] ?? 0;
6283
+ let top = candidates[candidates.length - 1];
6284
+ while (top !== void 0 && (balance[top] ?? 0) >= here) {
6285
+ candidates.pop();
6286
+ top = candidates[candidates.length - 1];
6287
+ }
6288
+ firstBelow[k] = top;
6289
+ candidates.push(k);
6290
+ }
6291
+ /**
6292
+ * The closer when `open` bodies are open just before `tags[index]`: each hop to
6293
+ * `firstBelow` closes one. `open` is at most one more than the openers scanned to get here.
6294
+ */
6295
+ const closeFrom = (index, open) => {
6296
+ let k = index;
6297
+ for (let left = open; left > 0 && k !== void 0; left--) k = firstBelow[k];
6298
+ return k === void 0 ? void 0 : tags[k - 1];
6299
+ };
6300
+ return (opener) => {
6301
+ const index = indexByStart.get(opener.start);
6302
+ if (index !== void 0) return closeFrom(index + 1, 1);
6303
+ const matchTagAt = tagMatcher(text, lastClose, spend);
6304
+ let open = 1;
6305
+ let from = opener.end;
6306
+ while (budget.left >= 0) {
6307
+ const start = text.indexOf("<<", from);
6308
+ spend((start === -1 ? text.length : start) - from);
6309
+ if (start === -1) return;
6310
+ const known = indexByStart.get(start);
6311
+ if (known !== void 0) return closeFrom(known, open);
6312
+ const tag = matchTagAt(start)?.tag;
6313
+ if (tag === void 0) {
6314
+ from = start + 2;
6315
+ continue;
6316
+ }
6317
+ open += step(tag);
6318
+ if (open === 0) return tag;
6319
+ from = tag.end;
6320
+ }
6321
+ };
6322
+ }
6323
+ /** Adds `more` to the end of `links`, without spreading, which fails for very long lists. */
6324
+ function append(links, more) {
6325
+ for (const link of more) links.push(link);
6326
+ }
6327
+ /**
6328
+ * The passages that `<<link>>` and `<<goto>>` calls in passage markup name. Calls whose passage
6329
+ * is known only in play (a variable or an expression) are left out. A tag's own passage comes
6330
+ * before those of the calls inside its arguments' strings.
6331
+ *
6332
+ * The markup is walked in order, as SugarCube's wikifier walks it, with a tag tried at each
6333
+ * `<<` the walk reaches. Of the wikifier's other parsers, only those whose text holds no call
6334
+ * are told apart: comments (`/* … *` + `/`, `/% … %/`, `<!-- … -->`), whose calls never run,
6335
+ * and `<script>` elements and `<<script>>` bodies, which are JavaScript: only the calls in their
6336
+ * strings are read (see `findJavaScriptPassageLinks`). Everything else, verbatim text included,
6337
+ * is read as markup.
6338
+ *
6339
+ * Where this differs from SugarCube:
6340
+ * - a comment or a `<<script>>` body is skipped whole, even where `parseBody` ends a container
6341
+ * such as `<<if>>` at a closing tag inside it and the rest then runs;
6342
+ * - a `/*`, `<!--` or `<script` inside other markup that holds no call, such as link markup or a
6343
+ * `<style>` element, still starts a comment or an element;
6344
+ * - a `<<` in such other markup still starts a tag. When that tag runs over a `<<link` or
6345
+ * `<<goto` outside the parts of its arguments that the tag pattern reads as units, that call
6346
+ * is still read (see `innerPassageLink`), even where the tag's arguments would be JavaScript,
6347
+ * as the check always read it. One that such a part covers is lost: a quoted string, or a `//`
6348
+ * part up to a line feed (italics, a URL) when a `>>` follows later; and a `<<script>>` body
6349
+ * the tag runs over is read as markup. The same recovery also reads a call inside a stray tag
6350
+ * that SugarCube does see, and rejects as an unknown macro (`<<Back <<goto R>>`);
6351
+ * - a `<<script>>` body's end is found as `parseBody` finds it, except that parseBody rejects a
6352
+ * closing tag with arguments, and resumes inside the arguments of a tag whose name starts with
6353
+ * `/` or `end`;
6354
+ * - the lines of a `<<nobr>>` body, and of every passage when a story sets
6355
+ * `Config.passages.nobr`, are not joined before they are read (see `storyInspect` for passages
6356
+ * tagged `nobr`).
6357
+ */
6358
+ function findMacroPassageLinks(text) {
6359
+ return markupPassageLinks(text, readContext(text));
6360
+ }
6361
+ function markupPassageLinks(text, context) {
6362
+ if (context.depth > MAX_STRING_DEPTH || !text.includes("<<") && !HAS_SCRIPT_OPEN_RE.test(text)) return [];
6363
+ const matchTagAt = tagMatcher(text);
6364
+ const matchInnerTagAt = tagMatcher(text);
6365
+ const readComment = commentReader(text);
6366
+ const readScriptElement = scriptElementReader(text);
6367
+ let findScriptCloser;
6368
+ const links = [];
6369
+ /** Reads the region `opener` opens, adding the calls in a `<script>` element; returns where the walk goes on. */
6370
+ const regionEnd = (opener) => {
6371
+ const start = opener.index;
6372
+ const kind = opener[0];
6373
+ switch (kind) {
6374
+ case "//": return start + 2;
6375
+ case "/*":
6376
+ case "/%":
6377
+ case "<!--": return readComment(kind, start) ?? start + kind.length;
6378
+ default: {
6379
+ const element = readScriptElement(start);
6380
+ if (element.openerEnd === void 0) return start + 1;
6381
+ if (element.close === void 0) return element.openerEnd;
6382
+ append(links, javaScriptPassageLinks(text.slice(element.openerEnd, element.close), context));
6383
+ return element.close + 9;
6384
+ }
6385
+ }
6386
+ };
6387
+ let macro = -2;
6388
+ let region;
6389
+ let pos = 0;
6390
+ for (;;) {
6391
+ if (macro !== -1 && macro < pos) macro = text.indexOf("<<", pos);
6392
+ if (region !== null && (region === void 0 || region.index < pos)) {
6393
+ REGION_OPEN_RE.lastIndex = pos;
6394
+ region = REGION_OPEN_RE.exec(text);
6395
+ }
6396
+ if (region !== null && (macro === -1 || region.index < macro)) {
6397
+ pos = regionEnd(region);
6398
+ continue;
6399
+ }
6400
+ if (macro === -1) return links;
6401
+ const scanned = matchTagAt(macro);
6402
+ if (scanned === void 0) {
6403
+ pos = macro + 2;
6404
+ continue;
6405
+ }
6406
+ const { tag, innerCall } = scanned;
6407
+ append(links, tagPassageLinks(tag, context));
6408
+ if (innerCall !== void 0) {
6409
+ const inner = innerPassageLink(matchInnerTagAt, innerCall);
6410
+ if (inner !== void 0) links.push(inner);
6411
+ }
6412
+ pos = tag.end;
6413
+ if (tag.name === "script") {
6414
+ findScriptCloser ??= scriptBodyCloser(text, context.budget);
6415
+ const closer = findScriptCloser(tag);
6416
+ if (closer !== void 0) {
6417
+ append(links, javaScriptPassageLinks(text.slice(tag.end, closer.start), context));
6418
+ pos = closer.end;
6419
+ }
6420
+ }
6421
+ }
6422
+ }
6423
+ /**
6424
+ * The passages that `<<link>>` and `<<goto>>` calls in the strings of JavaScript source name,
6425
+ * such as a script passage or a `<<script>>` body: `$.wiki('<<goto "Room">>')`. Code outside
6426
+ * the strings isn't markup, so a call put together while the story plays, such as
6427
+ * `'<<goto "' + target + '">>'`, names no passage here.
6428
+ */
6429
+ function findJavaScriptPassageLinks(source) {
6430
+ return javaScriptPassageLinks(source, readContext(source));
6431
+ }
6432
+ /**
6433
+ * What JavaScript source must contain for one of its string or template literals to hold a call
6434
+ * that is read. A value holding `<<`: each `<` in it is written as `<`, `\<`, `\x3c`, `\u003c` or
6435
+ * `\u{…}`, two can be next to each other with only line continuations between, and the first
6436
+ * is `<` or `\<` (then the source holds `<<` or `<\`) or one of the others. Or a value holding a
6437
+ * `<script>` element, whose own strings can make `<<` from escapes the outer string encodes.
6438
+ */
6439
+ const MAY_HOLD_MACRO_RE = /<<|<\\|\\x3c|\\u003c|\\u\{|<script/i;
6440
+ function javaScriptPassageLinks(source, context) {
6441
+ if (context.depth >= MAX_STRING_DEPTH || !MAY_HOLD_MACRO_RE.test(source)) return [];
6442
+ const inner = deeper(context);
6443
+ const links = [];
6444
+ for (const value of javaScriptStrings(source)) append(links, markupPassageLinks(value, inner));
6445
+ return links;
6446
+ }
5352
6447
  //#endregion
5353
6448
  //#region src/inspect.ts
5354
6449
  /**
@@ -5360,8 +6455,15 @@ function storyToJSON(story) {
5360
6455
  * - `[[Display Text|PassageName]]` (Twine 1 / Harlowe pipe)
5361
6456
  * - `<<goto "PassageName">>` (SugarCube macro)
5362
6457
  * - `<<link "Display" "PassageName">>` (SugarCube macro)
6458
+ *
6459
+ * SugarCube macro arguments may be double- or single-quoted, with backslash escapes, or bare
6460
+ * words; a passage named by a variable or an expression is known only in play and is skipped.
6461
+ * Macro calls are also read inside the quoted strings of other macros' arguments, and inside the
6462
+ * strings of `<<script>>` bodies and `<script>` elements; calls in comments are not read. A
6463
+ * script passage (`isScript`) is JavaScript, so its macro calls are read only inside its strings.
6464
+ * See `sugarcube-macros.ts` for the details and the known differences from SugarCube.
5363
6465
  */
5364
- function extractLinksFromText(text) {
6466
+ function extractLinksFromText(text, isScript) {
5365
6467
  const targets = /* @__PURE__ */ new Set();
5366
6468
  const wikiLinkRe = /\[\[([^\]]+)\]\]/g;
5367
6469
  let m;
@@ -5379,12 +6481,36 @@ function extractLinksFromText(text) {
5379
6481
  }
5380
6482
  targets.add(content.trim());
5381
6483
  }
5382
- const gotoRe = /<<goto\s+["']([^"']+)["']\s*>>/g;
5383
- while ((m = gotoRe.exec(text)) !== null) targets.add(m[1]);
5384
- const linkMacroRe = /<<link\s+["'][^"']*["']\s+["']([^"']+)["']\s*>>/g;
5385
- while ((m = linkMacroRe.exec(text)) !== null) targets.add(m[1]);
6484
+ const macroLinks = isScript ? findJavaScriptPassageLinks(text) : findMacroPassageLinks(text);
6485
+ for (const macro of ["goto", "link"]) for (const link of macroLinks) if (link.macro === macro) targets.add(link.passage);
5386
6486
  return [...targets];
5387
6487
  }
6488
+ /** Passages SugarCube runs from their raw text, never joining their lines. */
6489
+ const RAW_TEXT_PASSAGES = /* @__PURE__ */ new Set([
6490
+ "StoryInit",
6491
+ "PassageReady",
6492
+ "PassageDone"
6493
+ ]);
6494
+ /**
6495
+ * A passage's text as SugarCube reads it for its links. A passage tagged `nobr` has its line
6496
+ * breaks joined (`Passage.processText`): leading and trailing ones removed, each run inside made
6497
+ * one space. Script passages, `init`-tagged passages, StoryInit, PassageReady and PassageDone are
6498
+ * run from their raw text, so they keep theirs.
6499
+ */
6500
+ function textAsRead(p) {
6501
+ return hasTag(p, "nobr") && !hasTag(p, "script") && !hasTag(p, "init") && !RAW_TEXT_PASSAGES.has(p.name) ? joinLines(p.text) : p.text;
6502
+ }
6503
+ /**
6504
+ * What SugarCube's `text.replace(/^\n+|\n+$/g, '').replace(/\n+/g, ' ')` gives, without that
6505
+ * pattern's backtracking, which takes quadratic time on a long run of line feeds.
6506
+ */
6507
+ function joinLines(text) {
6508
+ let start = 0;
6509
+ while (text[start] === "\n") start += 1;
6510
+ let end = text.length;
6511
+ while (end > start && text[end - 1] === "\n") end -= 1;
6512
+ return text.slice(start, end).replace(/\n+/g, " ");
6513
+ }
5388
6514
  /**
5389
6515
  * Inspect a story and return its full structural map.
5390
6516
  *
@@ -5424,7 +6550,7 @@ function storyInspect(story) {
5424
6550
  }
5425
6551
  list.push(p.name);
5426
6552
  }
5427
- const targets = extractLinksFromText(p.text);
6553
+ const targets = extractLinksFromText(textAsRead(p), hasTag(p, "script"));
5428
6554
  links.set(p.name, targets);
5429
6555
  }
5430
6556
  const brokenLinks = [];