@rohal12/spindle 0.62.5 → 0.62.7

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.
@@ -10,6 +10,46 @@ var __exportAll = (all, no_symbols) => {
10
10
  return target;
11
11
  };
12
12
  //#endregion
13
+ //#region src/utils/macro-names.ts
14
+ /**
15
+ * Macro and widget names are case-insensitive: `{StatusBar}` invokes the
16
+ * widget defined as `statusbar`. A NameMap keys its entries by the lowercased
17
+ * name.
18
+ */
19
+ var NameMap = class extends Map {
20
+ get(name) {
21
+ return super.get(name.toLowerCase());
22
+ }
23
+ set(name, value) {
24
+ return super.set(name.toLowerCase(), value);
25
+ }
26
+ has(name) {
27
+ return super.has(name.toLowerCase());
28
+ }
29
+ delete(name) {
30
+ return super.delete(name.toLowerCase());
31
+ }
32
+ };
33
+ /** A set of macro or widget names (see NameMap). */
34
+ var NameSet = class {
35
+ constructor(names = []) {
36
+ this.names = new NameMap();
37
+ for (const name of names) this.add(name);
38
+ }
39
+ add(name) {
40
+ this.names.set(name, true);
41
+ }
42
+ has(name) {
43
+ return this.names.has(name);
44
+ }
45
+ delete(name) {
46
+ this.names.delete(name);
47
+ }
48
+ clear() {
49
+ this.names.clear();
50
+ }
51
+ };
52
+ //#endregion
13
53
  //#region src/markup/tokens.ts
14
54
  /** Variable sigils: story ($), temporary (_), local (@), transient (%). */
15
55
  var SIGIL_SCOPES = {
@@ -3591,46 +3631,6 @@ function peg$parse(input, options) {
3591
3631
  else peg$throw();
3592
3632
  }
3593
3633
  //#endregion
3594
- //#region src/utils/macro-names.ts
3595
- /**
3596
- * Macro and widget names are case-insensitive: `{StatusBar}` invokes the
3597
- * widget defined as `statusbar`. A NameMap keys its entries by the lowercased
3598
- * name.
3599
- */
3600
- var NameMap = class extends Map {
3601
- get(name) {
3602
- return super.get(name.toLowerCase());
3603
- }
3604
- set(name, value) {
3605
- return super.set(name.toLowerCase(), value);
3606
- }
3607
- has(name) {
3608
- return super.has(name.toLowerCase());
3609
- }
3610
- delete(name) {
3611
- return super.delete(name.toLowerCase());
3612
- }
3613
- };
3614
- /** A set of macro or widget names (see NameMap). */
3615
- var NameSet = class {
3616
- constructor(names = []) {
3617
- this.names = new NameMap();
3618
- for (const name of names) this.add(name);
3619
- }
3620
- add(name) {
3621
- this.names.set(name, true);
3622
- }
3623
- has(name) {
3624
- return this.names.has(name);
3625
- }
3626
- delete(name) {
3627
- this.names.delete(name);
3628
- }
3629
- clear() {
3630
- this.names.clear();
3631
- }
3632
- };
3633
- //#endregion
3634
3634
  //#region src/markup/ast.ts
3635
3635
  /**
3636
3636
  * The passage AST (built by parse.ts), and the registry of block macros:
@@ -9572,6 +9572,39 @@ function parseWithAst(src, goal) {
9572
9572
  }
9573
9573
  }
9574
9574
  /**
9575
+ * Read `src` as a reference path: a variable with any number of `.name` and
9576
+ * `[expression]` members after it (`$data["field"]`, `@list[_i].x`), and
9577
+ * nothing else. Returns null for any other code (`$a + 1`, `$a.b()`, `$a,
9578
+ * $b`, `$a = 1`), and throws a `CodeSyntaxError` for code that is not
9579
+ * well-formed.
9580
+ */
9581
+ function parseReferencePath(src) {
9582
+ const { ast } = parseWithAst(src, "expression");
9583
+ let node = ast.type === "ChainExpression" ? ast.expression : ast;
9584
+ let nested = false;
9585
+ while (node.type === "MemberExpression") {
9586
+ node = node.object;
9587
+ nested = true;
9588
+ }
9589
+ if (node.type !== "Identifier") return null;
9590
+ const sigil = sigilOf(node, src);
9591
+ if (!sigil || node.start !== 0) return null;
9592
+ return {
9593
+ sigil: sigil[0],
9594
+ name: sigil[1],
9595
+ nested
9596
+ };
9597
+ }
9598
+ /** Decode one dot-member identifier, including keywords and Unicode names. */
9599
+ function parseMemberIdentifier(src) {
9600
+ const { ast } = parseWithAst(`x.${src}`, "expression");
9601
+ if (ast.type !== "MemberExpression" || ast.computed) return null;
9602
+ const object = ast.object;
9603
+ const property = ast.property;
9604
+ if (object.type !== "Identifier" || object.start !== 0 || object.end !== 1 || property.type !== "Identifier" || property.start !== 2 || property.end !== src.length + 2) return null;
9605
+ return property.name;
9606
+ }
9607
+ /**
9575
9608
  * Parse `src` as `goal`, reading `%` as `percentAt` says where it says, and
9576
9609
  * noting where it read a transient in `transientsRead`.
9577
9610
  */
@@ -10254,9 +10287,13 @@ function indexCodeEnds(input) {
10254
10287
  if (open !== void 0) possible.add(open);
10255
10288
  } else if (/['"`/\\]/.test(c)) uncertain();
10256
10289
  }
10257
- return (start) => {
10258
- if (start > lastBrace) return -1;
10259
- return possible.has(start - 1) ? defaultCodeEnd.closeBrace(input, start, start) : parsedCodeEnd(input, start, "expression");
10290
+ return (start, codeStart = start, limit = input.length) => {
10291
+ if (start > lastBrace || codeStart >= limit) return -1;
10292
+ const source = limit === input.length ? input : input.slice(0, limit);
10293
+ if (input[start - 1] !== "{" || possible.has(start - 1) || input.slice(start, codeStart).includes("{")) return defaultCodeEnd.closeBrace(source, codeStart, start);
10294
+ const base = Math.max(0, codeStart - 1);
10295
+ const end = parsedCodeEnd(source.slice(base), codeStart - base, "expression");
10296
+ return end < 0 ? -1 : base + end;
10260
10297
  };
10261
10298
  }
10262
10299
  //#endregion
@@ -10336,10 +10373,14 @@ var MarkupError = class extends Error {
10336
10373
  }
10337
10374
  };
10338
10375
  function run$1(source, startRule, options, completion = false) {
10339
- const hooks = options.hooks ? {
10376
+ const hooks = {
10340
10377
  ...defaultHooks,
10341
10378
  ...options.hooks
10342
- } : defaultHooks;
10379
+ };
10380
+ if (!options.hooks?.closeBrace) {
10381
+ const codeEnd = indexCodeEnds(source);
10382
+ hooks.closeBrace = (_input, codeStart, lenientStart) => codeEnd(lenientStart, codeStart);
10383
+ }
10343
10384
  try {
10344
10385
  return peg$parse(source, {
10345
10386
  startRule,
@@ -10411,7 +10452,7 @@ function pairingError(position, error) {
10411
10452
  * macros and elements are no error here. Throws a MarkupError for a
10412
10453
  * malformed tag, such as an unclosed `{`, `[[` or attribute value.
10413
10454
  */
10414
- function tokenizeMarkup(source, options = {}) {
10455
+ function tokenizeMarkup$1(source, options = {}) {
10415
10456
  return run$1(source, "Tokens", options);
10416
10457
  }
10417
10458
  /**
@@ -10434,7 +10475,7 @@ function parseSelectors(source, at = 0) {
10434
10475
  * started. Tokens and errors have offsets in `source`; for well-formed
10435
10476
  * markup the tokens are those of `tokenizeMarkup` and there are no errors.
10436
10477
  */
10437
- function tokenizeMarkupTolerant(source, options = {}) {
10478
+ function tokenizeMarkupTolerant$1(source, options = {}) {
10438
10479
  const { tokens, errors } = scanMarkupTolerant(source, options);
10439
10480
  return {
10440
10481
  tokens,
@@ -10451,16 +10492,19 @@ function scanMarkupTolerant(source, options = {}, completion = false) {
10451
10492
  const errors = [];
10452
10493
  const damage = [];
10453
10494
  let position;
10495
+ const codeEnd = indexCodeEnds(source);
10496
+ const customCloseBrace = options.hooks?.closeBrace;
10454
10497
  const lastBrace = source.lastIndexOf("}");
10455
- const { closeBrace } = {
10456
- ...defaultHooks,
10457
- ...options.hooks
10458
- };
10459
10498
  /** `text` shifted by `base`, tokenized: the tokens or the error. */
10460
10499
  const attempt = (text, base) => {
10461
10500
  const hooks = {
10462
10501
  ...options.hooks,
10463
- closeBrace: (input, codeStart, lenientStart) => base + Math.min(codeStart, lenientStart) > lastBrace ? -1 : closeBrace(input, codeStart, lenientStart)
10502
+ closeBrace: (input, codeStart, lenientStart) => {
10503
+ if (base + Math.min(codeStart, lenientStart) > lastBrace) return -1;
10504
+ if (customCloseBrace) return customCloseBrace(input, codeStart, lenientStart);
10505
+ const end = codeEnd(base + lenientStart, base + codeStart, base + text.length);
10506
+ return end < 0 ? -1 : end - base;
10507
+ }
10464
10508
  };
10465
10509
  try {
10466
10510
  return run$1(text, "Tokens", {
@@ -10590,6 +10634,39 @@ function noPassageError(name, from) {
10590
10634
  }
10591
10635
  listeners.subscribe;
10592
10636
  //#endregion
10637
+ //#region src/utils/namespace.ts
10638
+ /** The variable name no namespace can hold. */
10639
+ var RESERVED_NAME = "__proto__";
10640
+ /**
10641
+ * Why `name` (without its sigil) cannot be a variable name, or undefined if
10642
+ * it can. `label` is the name as the author wrote it (e.g. `$__proto__`).
10643
+ */
10644
+ function variableNameError(name, label = name) {
10645
+ return name === "__proto__" ? `"${label}" cannot be used as a variable name (${RESERVED_NAME} is reserved)` : void 0;
10646
+ }
10647
+ /** Whether a property key is an array index (`"0"`, `"12"`; not `"01"`). */
10648
+ var isArrayIndex = (key) => /^(?:0|[1-9]\d*)$/.test(key);
10649
+ /** Whether `obj` holds `key` as an own property. */
10650
+ var hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
10651
+ /**
10652
+ * A record with no prototype holding the own entries of `sources`, or only
10653
+ * those whose value passes `keep`.
10654
+ */
10655
+ function ownEntries(sources, keep = () => true) {
10656
+ const record = Object.create(null);
10657
+ for (const source of sources) {
10658
+ if (!source) continue;
10659
+ for (const key of Object.keys(source)) {
10660
+ const value = source[key];
10661
+ if (keep(value)) record[key] = value;
10662
+ }
10663
+ }
10664
+ return record;
10665
+ }
10666
+ /** A namespace with no prototype holding the own entries of `sources`. */
10667
+ var createNamespace = (...sources) => ownEntries(sources);
10668
+ Object.freeze(createNamespace());
10669
+ //#endregion
10593
10670
  //#region src/components/macros/arg-utils.ts
10594
10671
  /**
10595
10672
  * Shared helpers for macros that split or read their raw argument text by
@@ -11074,6 +11151,62 @@ function evaluatePassageName(expr, evaluate, { storyData, currentPassage }) {
11074
11151
  return name;
11075
11152
  }
11076
11153
  /**
11154
+ * The variable a `storeVar` macro binds: its first term, as written. Custom
11155
+ * macros may bind one without declaring parameters.
11156
+ */
11157
+ function readBoundVariable(rawArgs) {
11158
+ const src = rawArgs.trim();
11159
+ const first = terms(src)[0];
11160
+ return first ? slice(src, first) : "";
11161
+ }
11162
+ /**
11163
+ * Read the first term as the runtime's story-variable binding. Quotes are
11164
+ * stripped, but this is an identifier path, not a JavaScript string literal:
11165
+ * only identifier escapes are decoded. Returns null for a missing binding;
11166
+ * throws for rejected namespaces, invalid escapes and reserved path names.
11167
+ * The full span excludes quotes and includes the sigil when written.
11168
+ */
11169
+ function parseBoundVariable(rawArgs) {
11170
+ const term = readBoundVariable(rawArgs);
11171
+ if (!term) return null;
11172
+ const lead = rawArgs.length - rawArgs.trimStart().length;
11173
+ const offsets = [];
11174
+ for (let i = 0; i < term.length; i++) if (term[i] !== "\"" && term[i] !== "'") offsets.push(lead + i);
11175
+ const firstToken = term.replace(/["']/g, "");
11176
+ const kind = {
11177
+ "%": "transient variables",
11178
+ _: "temporary variables",
11179
+ "@": "locals"
11180
+ }[firstToken.charAt(0)];
11181
+ if (kind) throw new Error(`${kind} (${firstToken}) cannot be bound to input macros`);
11182
+ const explicitSigil = firstToken.startsWith("$");
11183
+ if (!explicitSigil && firstToken.split(".")[0].includes("\\")) throw new Error("Escaped binding identifiers require a literal $ story-variable sigil");
11184
+ const segments = firstToken.replace(/^\$/, "").split(".").map((segment, index) => {
11185
+ if (!segment.includes("\\")) return segment;
11186
+ if (index > 0) {
11187
+ const name = parseMemberIdentifier(segment);
11188
+ if (name === null) throw new Error("Invalid bound identifier");
11189
+ return name;
11190
+ }
11191
+ const reference = parseReferencePath(`$${segment}`);
11192
+ if (!reference || reference.nested) throw new Error("Invalid bound identifier");
11193
+ return reference.name;
11194
+ });
11195
+ if (segments.includes("__proto__")) throw new Error(`"$${segments.join(".")}" cannot be bound: ${RESERVED_NAME} is reserved`);
11196
+ const rootStart = explicitSigil ? 1 : 0;
11197
+ const rootEnd = firstToken.indexOf(".", rootStart);
11198
+ const nameEnd = rootEnd < 0 ? firstToken.length : rootEnd;
11199
+ return {
11200
+ name: segments[0],
11201
+ path: segments.slice(1),
11202
+ explicitSigil,
11203
+ start: offsets[0] ?? lead,
11204
+ end: offsets.length ? offsets[offsets.length - 1] + 1 : lead,
11205
+ nameStart: offsets[rootStart] ?? lead + rootStart,
11206
+ nameEnd: offsets[nameEnd - 1] === void 0 ? lead : offsets[nameEnd - 1] + 1
11207
+ };
11208
+ }
11209
+ /**
11077
11210
  * The runtime's argument grouping, tolerant of missing or unclosed strings.
11078
11211
  * Includes quotes, flags, separators and option keywords; offsets are into
11079
11212
  * rawArgs. Absent arguments have no span. Options also have their enclosing
@@ -11113,39 +11246,6 @@ function subMacroParameters(name) {
11113
11246
  return SUB_MACRO_PARAMETERS.get(name.toLowerCase());
11114
11247
  }
11115
11248
  //#endregion
11116
- //#region src/utils/namespace.ts
11117
- /** The variable name no namespace can hold. */
11118
- var RESERVED_NAME = "__proto__";
11119
- /**
11120
- * Why `name` (without its sigil) cannot be a variable name, or undefined if
11121
- * it can. `label` is the name as the author wrote it (e.g. `$__proto__`).
11122
- */
11123
- function variableNameError(name, label = name) {
11124
- return name === "__proto__" ? `"${label}" cannot be used as a variable name (${RESERVED_NAME} is reserved)` : void 0;
11125
- }
11126
- /** Whether a property key is an array index (`"0"`, `"12"`; not `"01"`). */
11127
- var isArrayIndex = (key) => /^(?:0|[1-9]\d*)$/.test(key);
11128
- /** Whether `obj` holds `key` as an own property. */
11129
- var hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
11130
- /**
11131
- * A record with no prototype holding the own entries of `sources`, or only
11132
- * those whose value passes `keep`.
11133
- */
11134
- function ownEntries(sources, keep = () => true) {
11135
- const record = Object.create(null);
11136
- for (const source of sources) {
11137
- if (!source) continue;
11138
- for (const key of Object.keys(source)) {
11139
- const value = source[key];
11140
- if (keep(value)) record[key] = value;
11141
- }
11142
- }
11143
- return record;
11144
- }
11145
- /** A namespace with no prototype holding the own entries of `sources`. */
11146
- var createNamespace = (...sources) => ownEntries(sources);
11147
- Object.freeze(createNamespace());
11148
- //#endregion
11149
11249
  //#region src/code-check.ts
11150
11250
  /** While a pass runs: the code it parsed so far, by goal and source. */
11151
11251
  var parses = null;
@@ -11204,9 +11304,13 @@ function widgetParameters(params, holds = {}) {
11204
11304
  ...hasOwn(holds, name) ? { holds: holds[name] } : {}
11205
11305
  }));
11206
11306
  }
11307
+ /** Whether builtin-only interpretation still belongs to this implementation. */
11308
+ function usesBuiltinSemantics(name, parametersOf) {
11309
+ return parametersOf.widget?.(name) === void 0 && parametersOf.source?.(name) !== "user";
11310
+ }
11207
11311
  /** A raw body is executable only while the builtin implementation owns it. */
11208
11312
  function executesRawBody(name, parametersOf) {
11209
- return isRawMacro(name, parametersOf.widget?.(name) !== void 0) && parametersOf.source?.(name) !== "user";
11313
+ return isRawMacro(name, false) && usesBuiltinSemantics(name, parametersOf);
11210
11314
  }
11211
11315
  /**
11212
11316
  * `params` with each `string` and `text` parameter (options too) saying
@@ -11239,12 +11343,13 @@ function parameterLookup(macros) {
11239
11343
  for (const { name, parameters: params, interpolate, widget, source } of macros) {
11240
11344
  sources.set(name, source ?? "user");
11241
11345
  if (params) parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
11346
+ else parameters.delete(name);
11242
11347
  if (widget) widgets.set(name, widgetParameters(widget.params, widget.holds) ?? []);
11243
11348
  }
11244
11349
  const lookup = (name) => {
11245
11350
  if (widgets.has(name)) return void 0;
11246
11351
  let params = parameters.get(name);
11247
- if (!params) {
11352
+ if (!params && sources.get(name) !== "user") {
11248
11353
  const sub = subMacroParameters(name);
11249
11354
  if (sub) parameters.set(name, params = withHolds(sub, "text"));
11250
11355
  }
@@ -11331,7 +11436,7 @@ function* codeAndText(src, tokens, parametersOf) {
11331
11436
  continue;
11332
11437
  }
11333
11438
  const args = token.rawArgs;
11334
- if (PASSAGE_BODIES.has(name) && !widget) {
11439
+ if (PASSAGE_BODIES.has(name) && usesBuiltinSemantics(name, parametersOf)) {
11335
11440
  const close = closeOfTextBody(t, name);
11336
11441
  if (close > t + 1) {
11337
11442
  const text = src.slice(token.end, tokens[close].start);
@@ -11349,7 +11454,7 @@ function* codeAndText(src, tokens, parametersOf) {
11349
11454
  if (!args) continue;
11350
11455
  const label = `{${token.name} ${args}}`;
11351
11456
  const argsAt = token.argsStart;
11352
- if (CONDITION_MACROS.has(name) && !widget) {
11457
+ if (CONDITION_MACROS.has(name) && usesBuiltinSemantics(name, parametersOf)) {
11353
11458
  yield {
11354
11459
  kind: "code",
11355
11460
  code: args,
@@ -11709,7 +11814,7 @@ var LITERAL = { kind: "literal" };
11709
11814
  function completionContext(source, cursor, macros = []) {
11710
11815
  if (!Number.isInteger(cursor) || cursor < 0 || cursor > source.length) throw new RangeError("cursor must be a UTF-16 offset within source");
11711
11816
  const parametersOf = parameterLookup(macros);
11712
- const codeContext = (code, goal, map) => {
11817
+ const codeContext = (code, goal, map, containers) => {
11713
11818
  const probe = code.length + 1;
11714
11819
  let executable = false;
11715
11820
  lexJs(code + " __spindle_cursor__", {
@@ -11729,15 +11834,16 @@ function completionContext(source, cursor, macros = []) {
11729
11834
  goal,
11730
11835
  offset,
11731
11836
  cursor: code.length,
11837
+ ...containers.length ? { containers } : {},
11732
11838
  ...offsets.some((at, i) => at !== offset + i) ? { sourceOffsets: offsets } : {}
11733
11839
  };
11734
11840
  };
11735
- const read = (src, map, text = false, depth = 0, sigilsOnly = false) => {
11841
+ const read = (src, map, text = false, depth = 0, sigilsOnly = false, containers = []) => {
11736
11842
  if (depth >= 64) return LITERAL;
11737
11843
  if (sigilsOnly) {
11738
11844
  let at = 0;
11739
11845
  for (const part of splitSigilTemplate(src, true)) if ("expr" in part) {
11740
- if (at + 1 + part.expr.length === src.length) return codeContext(part.expr, "expression", (i) => map(at + 1 + i));
11846
+ if (at + 1 + part.expr.length === src.length) return codeContext(part.expr, "expression", (i) => map(at + 1 + i), containers);
11741
11847
  at += part.expr.length + 2;
11742
11848
  } else at += ("text" in part ? part.text : part.verbatim).length;
11743
11849
  return LITERAL;
@@ -11748,13 +11854,21 @@ function completionContext(source, cursor, macros = []) {
11748
11854
  });
11749
11855
  const token = tokens[tokens.length - 1];
11750
11856
  if (!token || token.end !== src.length) return LITERAL;
11751
- const codeAt = (code, at, goal = "expression") => codeContext(code, goal, (i) => map(at + i));
11752
- const nested = (value, at, offsets, onlySigils = false) => read(value, (i) => map(offsets?.[i] ?? at + i), true, depth + 1, onlySigils);
11857
+ const codeAt = (code, at, goal = "expression") => codeContext(code, goal, (i) => map(at + i), containers);
11858
+ const nested = (value, at, offsets, onlySigils = false, container) => read(value, (i) => map(offsets?.[i] ?? at + i), true, depth + 1, onlySigils, container ? [...containers, container] : containers);
11753
11859
  if (token.type === "variable" && token.nameEnd === src.length) return codeAt(src.slice(token.nameStart - 1), token.nameStart - 1);
11754
11860
  if (token.type === "expression" && token.expressionEnd === src.length) return codeAt(token.expression, token.expressionStart);
11755
11861
  if (token.type === "html") {
11756
- for (const { name, value, at } of attributeValues(src, token)) if (at + value.length === src.length) return nested(value, at, void 0, isCodeAttribute(name));
11757
- } else if (token.type === "link" && token.displayEnd === src.length) return nested(token.display, token.displayStart);
11862
+ for (const { name, value, at } of attributeValues(src, token)) if (at + value.length === src.length) {
11863
+ const span = token.attributeSpans.find((span) => span.valueStart === at);
11864
+ return nested(value, at, void 0, isCodeAttribute(name), {
11865
+ kind: "attribute",
11866
+ name,
11867
+ quote: span?.quote ?? null,
11868
+ code: isCodeAttribute(name)
11869
+ });
11870
+ }
11871
+ } else if (token.type === "link" && token.displayEnd === src.length) return nested(token.display, token.displayStart, void 0, false, { kind: "link-label" });
11758
11872
  else if (token.type === "text" && !token.comment) {
11759
11873
  const opener = tokens[tokens.length - 2];
11760
11874
  if (opener?.type === "macro" && !opener.isClose && executesRawBody(opener.name, parametersOf)) return codeAt(token.value, token.start, "statements");
@@ -11762,7 +11876,7 @@ function completionContext(source, cursor, macros = []) {
11762
11876
  const name = token.name.toLowerCase();
11763
11877
  const args = token.rawArgs;
11764
11878
  const widget = parametersOf.widget?.(name);
11765
- if (!widget && [
11879
+ if (usesBuiltinSemantics(name, parametersOf) && [
11766
11880
  "if",
11767
11881
  "elseif",
11768
11882
  "case"
@@ -11776,9 +11890,14 @@ function completionContext(source, cursor, macros = []) {
11776
11890
  if (scanStringLiteral(raw, 0).closed) return LITERAL;
11777
11891
  const value = escapes === "javascript" ? stringLiteralValue(raw + raw[0]) : quoted.value;
11778
11892
  if (value == null) return LITERAL;
11893
+ const container = {
11894
+ kind: "string",
11895
+ quote: raw[0],
11896
+ escapes
11897
+ };
11779
11898
  const offsets = escapeOffsets(raw.slice(1), at + 1, value, escapes);
11780
- if (holds === "expression" || holds === "statements") return codeContext(value, holds, (i) => map(offsets?.[i] ?? at + 1 + i));
11781
- return holds === "markup" ? nested(value, at + 1, offsets) : LITERAL;
11899
+ if (holds === "expression" || holds === "statements") return codeContext(value, holds, (i) => map(offsets?.[i] ?? at + 1 + i), [...containers, container]);
11900
+ return holds === "markup" ? nested(value, at + 1, offsets, false, container) : LITERAL;
11782
11901
  };
11783
11902
  if (widget) {
11784
11903
  const spans = splitArgSpans(args);
@@ -11960,7 +12079,7 @@ function widgetDefinitions$1(passages, parametersOf = registeredParameters) {
11960
12079
  if (passage.name !== "StoryInit" && !passage.tags?.includes("widget")) continue;
11961
12080
  const open = [];
11962
12081
  const done = [];
11963
- for (const token of tokenizeMarkupTolerant(passage.content, { hooks }).tokens) if (token.type === "macro" && token.name.toLowerCase() === "widget") {
12082
+ for (const token of tokenizeMarkupTolerant$1(passage.content, { hooks }).tokens) if (token.type === "macro" && token.name.toLowerCase() === "widget") {
11964
12083
  if (!token.isClose) open.push({
11965
12084
  token,
11966
12085
  isBlock: false
@@ -12151,7 +12270,7 @@ function validateMarkup(passages, options) {
12151
12270
  continue;
12152
12271
  }
12153
12272
  try {
12154
- const tokens = tokenizeMarkup(passage.content, { hooks });
12273
+ const tokens = tokenizeMarkup$1(passage.content, { hooks });
12155
12274
  addWidgets(tokens);
12156
12275
  if (!reported) continue;
12157
12276
  parseMarkup(passage.content, { hooks });
@@ -12660,9 +12779,9 @@ function tokensOf(text, textMode, { tolerant, parametersOf } = {}) {
12660
12779
  text: textMode,
12661
12780
  hooks: parametersOf && { isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0) }
12662
12781
  };
12663
- if (tolerant) return tokenizeMarkupTolerant(text, options).tokens;
12782
+ if (tolerant) return tokenizeMarkupTolerant$1(text, options).tokens;
12664
12783
  try {
12665
- return tokenizeMarkup(text, options);
12784
+ return tokenizeMarkup$1(text, options);
12666
12785
  } catch (err) {
12667
12786
  if (err instanceof MarkupError) return [];
12668
12787
  throw err;
@@ -12674,8 +12793,6 @@ function declarationRegex(sigil) {
12674
12793
  }
12675
12794
  /** A `$name` or `%name` reference with its dot path, at a sigil the lexer found. */
12676
12795
  var VAR_PATH_RE = /([$%])(\w+(?:\.\w+)*)/y;
12677
- /** Quoted first argument of an input macro naming a story variable. */
12678
- var QUOTED_VAR_ARG_RE = /^["']\$(\w+(?:\.\w+)*)["']?$/;
12679
12796
  var VALID_VAR_TYPES = /* @__PURE__ */ new Set([
12680
12797
  "number",
12681
12798
  "string",
@@ -13042,6 +13159,30 @@ function scanSelectors(content, token, at, emit, options) {
13042
13159
  storeVarMacros: NO_STORE_VAR_MACROS
13043
13160
  });
13044
13161
  }
13162
+ /** Read a runtime binding and map its editable spans into the passage. */
13163
+ function boundReference(token, at, all) {
13164
+ try {
13165
+ const binding = parseBoundVariable(token.rawArgs);
13166
+ if (!binding || !all && !binding.explicitSigil) return void 0;
13167
+ const mapped = {
13168
+ ...binding,
13169
+ start: at(token.argsStart + binding.start),
13170
+ end: at(token.argsStart + binding.end),
13171
+ nameStart: at(token.argsStart + binding.nameStart),
13172
+ nameEnd: at(token.argsStart + binding.nameEnd)
13173
+ };
13174
+ return {
13175
+ sigil: "$",
13176
+ name: binding.name,
13177
+ path: binding.path,
13178
+ start: mapped.start,
13179
+ end: mapped.end,
13180
+ binding: mapped
13181
+ };
13182
+ } catch {
13183
+ return;
13184
+ }
13185
+ }
13045
13186
  /** Report the `$var` references in the tokens of `content`. */
13046
13187
  function collectTokenRefs(content, tokens, at, emit, options) {
13047
13188
  const { storeVarMacros, parametersOf } = options;
@@ -13070,24 +13211,12 @@ function collectTokenRefs(content, tokens, at, emit, options) {
13070
13211
  else scanInterpolations(value, valueIn, emit, options);
13071
13212
  }
13072
13213
  else if (token.type === "macro" && !token.isClose) {
13073
- scanArgs(token, parametersOf, at, emit, options);
13214
+ const binding = storeVarMacros.has(token.name.toLowerCase()) && !parametersOf.widget?.(token.name) ? boundReference(token, at, options.all) : void 0;
13215
+ scanArgs(token, parametersOf, at, (ref) => {
13216
+ if (!binding || ref.start < binding.start || ref.start >= binding.end) emit(ref);
13217
+ }, options);
13074
13218
  scanSelectors(content, token, at, emit, options);
13075
- if (storeVarMacros.has(token.name.toLowerCase()) && !parametersOf.widget?.(token.name)) {
13076
- const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
13077
- const first = token.rawArgs.trim().split(/\s+/)[0] ?? "";
13078
- const quoted = QUOTED_VAR_ARG_RE.exec(first);
13079
- if (quoted) {
13080
- const [name, ...path] = quoted[1].split(".");
13081
- const start = token.argsStart + lead + 1;
13082
- emit({
13083
- sigil: "$",
13084
- name,
13085
- path,
13086
- start: at(start),
13087
- end: at(start + 1 + quoted[1].length)
13088
- });
13089
- } else if (!/^["'`]/.test(first)) scanCode(first, (i) => at(token.argsStart + lead + i), emit);
13090
- }
13219
+ if (binding) emit(binding);
13091
13220
  if (executesRawBody(token.name, parametersOf)) {
13092
13221
  let close = t + 1;
13093
13222
  while (close < tokens.length) {
@@ -24893,7 +25022,7 @@ function scanSpindleMarkup(text) {
24893
25022
  if (inAttribute) match.inAttribute = true;
24894
25023
  tokens.push(match);
24895
25024
  };
24896
- for (const t of tokenizeMarkupTolerant(text).tokens) if (t.type === "html") {
25025
+ for (const t of tokenizeMarkupTolerant$1(text).tokens) if (t.type === "html") {
24897
25026
  tags.push({
24898
25027
  start: t.start,
24899
25028
  end: t.end
@@ -24902,7 +25031,7 @@ function scanSpindleMarkup(text) {
24902
25031
  if (attribute.valueStart === void 0 || attribute.valueEnd === void 0) continue;
24903
25032
  const value = text.slice(attribute.valueStart, attribute.valueEnd);
24904
25033
  if (!value.includes("{")) continue;
24905
- for (const inner of tokenizeMarkupTolerant(value, { text: true }).tokens) if (inner.type === "macro" || inner.type === "variable" || inner.type === "expression") push({
25034
+ for (const inner of tokenizeMarkupTolerant$1(value, { text: true }).tokens) if (inner.type === "macro" || inner.type === "variable" || inner.type === "expression") push({
24906
25035
  start: attribute.valueStart + inner.start,
24907
25036
  end: attribute.valueStart + inner.end
24908
25037
  }, true);
@@ -25101,7 +25230,7 @@ var DEFAULT_DEDENTING = /* @__PURE__ */ new Set([
25101
25230
  /** The names of the macros the passage closes with `{/name}`: block macros it defines itself. */
25102
25231
  function closedMacroNames(text) {
25103
25232
  const found = /* @__PURE__ */ new Set();
25104
- for (const t of tokenizeMarkupTolerant(text).tokens) if (t.type === "macro" && t.isClose) found.add(t.name.toLowerCase());
25233
+ for (const t of tokenizeMarkupTolerant$1(text).tokens) if (t.type === "macro" && t.isClose) found.add(t.name.toLowerCase());
25105
25234
  return found;
25106
25235
  }
25107
25236
  /** The built-in block macros (and the block widgets the runtime has defined) plus those the passage closes. */
@@ -25424,7 +25553,7 @@ function macroTokensByLine(lines) {
25424
25553
  offset += line.length + 1;
25425
25554
  }
25426
25555
  let line = 0;
25427
- for (const token of tokenizeMarkupTolerant(lines.join("\n")).tokens) {
25556
+ for (const token of tokenizeMarkupTolerant$1(lines.join("\n")).tokens) {
25428
25557
  if (token.type !== "macro") continue;
25429
25558
  while (line + 1 < lines.length && starts[line + 1] <= token.start) line++;
25430
25559
  const lineStart = starts[line];
@@ -25517,7 +25646,7 @@ function wordWrap(text, maxLen, indent) {
25517
25646
  const lines = [];
25518
25647
  /** Whether the character is inside a token whose text must stay as written. */
25519
25648
  const inToken = new Array(text.length).fill(false);
25520
- for (const token of tokenizeMarkupTolerant(text).tokens) {
25649
+ for (const token of tokenizeMarkupTolerant$1(text).tokens) {
25521
25650
  if (token.type === "text") continue;
25522
25651
  inToken.fill(true, token.start, token.end);
25523
25652
  }
@@ -25644,6 +25773,28 @@ var transformCache = /* @__PURE__ */ new Map();
25644
25773
  * validator, with no Preact or DOM dependencies. pkg/tooling.js re-exports
25645
25774
  * them, binding the validator to its macro metadata.
25646
25775
  */
25776
+ function tokenizationOptions(options) {
25777
+ if (!options.macros) return options;
25778
+ const macros = [...options.macros];
25779
+ const parametersOf = parameterLookup(macros);
25780
+ return {
25781
+ ...options,
25782
+ hooks: {
25783
+ isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0),
25784
+ isBlock: blockLookup(macros),
25785
+ branchParents: (name) => branchParents(name, macros),
25786
+ ...options.hooks
25787
+ }
25788
+ };
25789
+ }
25790
+ /** Flat tokens with optional effective macro/widget metadata. */
25791
+ function tokenizeMarkup(source, options = {}) {
25792
+ return tokenizeMarkup$1(source, tokenizationOptions(options));
25793
+ }
25794
+ /** Metadata-aware flat tokens and recovery errors, in original source offsets. */
25795
+ function tokenizeMarkupTolerant(source, options = {}) {
25796
+ return tokenizeMarkupTolerant$1(source, tokenizationOptions(options));
25797
+ }
25647
25798
  /**
25648
25799
  * Validate the markup of a story's passages as Spindle does when the story
25649
25800
  * starts, against the given macros (built-in and user-defined): malformed
@@ -25739,10 +25890,12 @@ var NOT_MARKUP_TAGS = ["script", "stylesheet"];
25739
25890
  */
25740
25891
  function referenceOptions(macros, all = false, passages = []) {
25741
25892
  const list = [...macros];
25893
+ const effective = new NameMap();
25894
+ for (const macro of list) effective.set(macro.name, macro);
25742
25895
  const widgets = effectiveWidgetDefinitions(widgetDefinitions$1(passages, parameterLookup(list)));
25743
25896
  return {
25744
25897
  all,
25745
- storeVarMacros: new Set(list.filter((m) => m.storeVar).map((m) => m.name.toLowerCase())),
25898
+ storeVarMacros: new Set([...effective.values()].filter((m) => m.storeVar).map((m) => m.name.toLowerCase())),
25746
25899
  parametersOf: parameterLookup([...list, ...definedWidgetMacros(widgets)]),
25747
25900
  tolerant: true
25748
25901
  };
@@ -25752,13 +25905,15 @@ function referenceOptions(macros, all = false, passages = []) {
25752
25905
  * in source order, with the dotted path of fields accessed and where each is
25753
25906
  * written (offsets into `source`, UTF-16): `{$var}` displays, code in
25754
25907
  * expressions, conditions, `{do}` bodies and macro arguments, quoted names
25755
- * bound by input macros, and the markup in labels and HTML attributes. Prose
25908
+ * bound by input macros, and the markup in labels and HTML attributes. Input
25909
+ * bindings include decoded root/path names and editable `binding` spans. Prose
25756
25910
  * is literal text. Malformed tags are skipped, so it reads half-typed markup.
25757
25911
  * The macros are those the markup may use, built-in and user-defined.
25758
25912
  *
25759
25913
  * These are the references the story start checks. With `all: true`, the
25760
25914
  * list is complete (the checked ones are among it, in source order): it also
25761
- * has the variable a macro names in a `variable` parameter, such as the
25915
+ * has sigilless input bindings (`{textbox "name"}`), the variable a macro
25916
+ * names in a `variable` parameter, such as the
25762
25917
  * target of `{unset}` and `{computed}`, and the `{$name}` in the selectors of
25763
25918
  * a link, display or expression (`[[.c{$name} Go->T]]`). A rename or a find
25764
25919
  * of references needs these too.
@@ -25778,4 +25933,4 @@ function validateVariableReferences(passages, declarations, macros = []) {
25778
25933
  return checkVariableReferences(list.filter((p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t))), declarations, referenceOptions(macros, false, list));
25779
25934
  }
25780
25935
  //#endregion
25781
- export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, completionContext, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, isBlockMacro, isSigil, lexJs, lexTemplate, macroArgumentSpans, pairMarkup, parseCode, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };
25936
+ export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, completionContext, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, isBlockMacro, isSigil, lexJs, lexTemplate, macroArgumentSpans, pairMarkup, parseBoundVariable, parseCode, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };