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