@rohal12/twee-ts 1.15.3 → 1.16.0

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