squiffy-compiler 7.0.0-beta.6 → 7.0.0-beta.8

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.
Files changed (46) hide show
  1. package/dist/analyse.d.ts +12 -1
  2. package/dist/analyse.js +156 -9
  3. package/dist/compiler.d.ts +5 -3
  4. package/dist/compiler.js +3 -2
  5. package/dist/css-urls.d.ts +4 -0
  6. package/dist/css-urls.js +59 -0
  7. package/dist/emit.d.ts +18 -1
  8. package/dist/emit.js +46 -0
  9. package/dist/infix-expressions.d.ts +19 -0
  10. package/dist/infix-expressions.js +713 -0
  11. package/dist/language-service.d.ts +1 -0
  12. package/dist/language-service.js +34 -15
  13. package/dist/node.d.ts +2 -1
  14. package/dist/node.js +1 -0
  15. package/dist/parse.d.ts +4 -0
  16. package/dist/parse.js +29 -0
  17. package/dist/project.d.ts +31 -0
  18. package/dist/project.js +98 -0
  19. package/dist/quest/convert.js +67 -11
  20. package/dist/quest/scripts.js +13 -9
  21. package/dist/quest/text.js +17 -8
  22. package/dist/section-labels.d.ts +4 -0
  23. package/dist/section-labels.js +64 -0
  24. package/dist/setters.d.ts +4 -0
  25. package/dist/setters.js +11 -9
  26. package/dist/story-graph.d.ts +2 -0
  27. package/dist/story-graph.js +61 -16
  28. package/dist/syntax.d.ts +24 -3
  29. package/dist/templates.d.ts +6 -0
  30. package/dist/templates.js +128 -0
  31. package/dist/text.d.ts +3 -1
  32. package/dist/text.js +45 -11
  33. package/dist/twine/audio.d.ts +21 -0
  34. package/dist/twine/audio.js +80 -0
  35. package/dist/twine/convert.d.ts +45 -3
  36. package/dist/twine/convert.js +305 -37
  37. package/dist/twine/expression.d.ts +21 -1
  38. package/dist/twine/expression.js +105 -8
  39. package/dist/twine/harlowe.d.ts +9 -0
  40. package/dist/twine/harlowe.js +461 -86
  41. package/dist/twine/settings.d.ts +9 -0
  42. package/dist/twine/settings.js +322 -0
  43. package/dist/twine/sugarcube.d.ts +3 -0
  44. package/dist/twine/sugarcube.js +438 -114
  45. package/package.json +9 -2
  46. package/syntaxes/squiffy.tmLanguage.json +8 -3
@@ -1,7 +1,7 @@
1
1
  // Converts the text of a Quest gamebook page, which is HTML with Quest's text processor commands
2
2
  // in it ({if ...}, {once:...}, {page:...} and so on), into Squiffy text.
3
3
  import { attributeRef, display, print, quote, Unconvertible } from "../twine/expression.js";
4
- import { sectionLink, urlLink } from "../twine/convert.js";
4
+ import { escapeLinkBrackets, sectionLink, urlLink } from "../twine/convert.js";
5
5
  // Finds the next {...} the way Quest does: the first {, and the } that matches it, counting the
6
6
  // ones in between. Undefined if there isn't one.
7
7
  function nextCommand(text, from) {
@@ -70,10 +70,11 @@ function convertCommand(section, ctx, mode) {
70
70
  case "command:":
71
71
  case "page:":
72
72
  return convertPageLink(section, ctx, mode);
73
+ // Quest remembers each of these by its own text, as {{#once}} remembers each of its own
73
74
  case "once:":
74
- return `{{#if ${print(visits(ctx))} = 1}}${nested(section.substring(5))}{{/if}}`;
75
+ return `{{#once}}${nested(section.substring(5))}{{/once}}`;
75
76
  case "notfirst:":
76
- return `{{#if ${print(visits(ctx))} > 1}}${nested(section.substring(9))}{{/if}}`;
77
+ return `{{#once}}{{else}}${nested(section.substring(9))}{{/once}}`;
77
78
  case "random:":
78
79
  return convertRandom(section.substring(7), ctx);
79
80
  case "img:": {
@@ -94,7 +95,7 @@ function convertCommand(section, ctx, mode) {
94
95
  }
95
96
  // A passage link shows the popup's text when it's clicked
96
97
  const name = ctx.addPassage(link, convertQuestText(content, ctx, "block"));
97
- return `[${nested(link).replace(/\]/g, "]").replace(/\[/g, "[")}](${name})`;
98
+ return `[${escapeLinkBrackets(nested(link))}](${name})`;
98
99
  }
99
100
  case "either ":
100
101
  case "eval:":
@@ -136,9 +137,6 @@ function literalBraces(inner) {
136
137
  export function objectAttribute(object, attribute) {
137
138
  return object == "game" ? attribute : `${object}_${attribute}`;
138
139
  }
139
- function visits(ctx) {
140
- return { k: "call", fn: "visits", args: [{ k: "str", v: ctx.section }] };
141
- }
142
140
  // {if flag:text}, {if not flag:text}, {if counter>5:text}, {if game.flag:text}, {if Page3.visited:text}
143
141
  function convertIf(section, ctx, mode) {
144
142
  const command = section.substring(3);
@@ -168,7 +166,18 @@ function convertIf(section, ctx, mode) {
168
166
  const rhs = /^-?\d+(\.\d+)?$/.test(rhsText) ? { k: "num", v: Number(rhsText) } : { k: "str", v: rhsText };
169
167
  expr = { k: "bin", op: operator == "<>" ? "!=" : operator, l: lhs, r: rhs };
170
168
  }
171
- return `{{#if ${print(expr)}}}${text}{{/if}}`;
169
+ return `{{#if ${printCondition(expr, mode)}}}${text}{{/if}}`;
170
+ }
171
+ // A condition, as it's written in an {{#if}}. A link's text goes in a text="..." string, where
172
+ // the compiler writes a " as \", which the condition can't then read, so text in it is quoted
173
+ // with single quotes.
174
+ function printCondition(expr, mode) {
175
+ if (mode == "block")
176
+ return print(expr);
177
+ const printed = print(expr, { preferSingle: true });
178
+ if (printed.includes("\""))
179
+ throw new Unconvertible("a condition in a link's text can't compare with text that has a quote mark in it");
180
+ return printed;
172
181
  }
173
182
  // A flag or counter, game.attribute, or page.visited, in an {if}
174
183
  function reference(name, ctx) {
@@ -0,0 +1,4 @@
1
+ import type { SectionNode, SquiffyFile } from "./syntax.js";
2
+ export declare function sectionDetail(node: SectionNode): string | undefined;
3
+ export declare const capitalise: (text: string) => string;
4
+ export declare function sectionLabels(files: Iterable<SquiffyFile>, nameOf: (node: SectionNode) => string | undefined): Map<string, string>;
@@ -0,0 +1,64 @@
1
+ // What messages call sections, so that a section without a name of its own isn't called by the
2
+ // name the compiler gives it. Used by the compiler's warnings, the story graph's and the CLI's.
3
+ // What the outline calls a section without a name of its own
4
+ export function sectionDetail(node) {
5
+ if (node.kind == "preamble")
6
+ return "(Start)";
7
+ if (node.header?.type == "continue")
8
+ return `+++${node.header.text}`;
9
+ if (node.header?.type == "separator")
10
+ return "---";
11
+ return undefined;
12
+ }
13
+ const ORDINALS = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"];
14
+ const ordinal = (n) => ORDINALS[n - 1] ?? `${n}th`;
15
+ export const capitalise = (text) => text.charAt(0).toUpperCase() + text.slice(1);
16
+ // What messages call each section, by name. A section without a name of its own is called by its
17
+ // +++ or --- line, not the name the compiler gives it (_continue1, ...), which the author never
18
+ // wrote and can't search for. As a story can have lots of "+++Continue..." lines, it also says
19
+ // which named section it comes after, and which one it is if there are several:
20
+ // 'the section "cave"', 'the "+++Continue..." after "cave"', 'the second "---" after "cave"',
21
+ // 'the third "+++Next"' (before any named section), 'the text before the first section'.
22
+ export function sectionLabels(files, nameOf) {
23
+ const labels = new Map();
24
+ for (const tree of files) {
25
+ // The sections without names of their own since the last named one
26
+ let after;
27
+ let run = [];
28
+ const finish = () => {
29
+ const total = new Map();
30
+ for (const { detail } of run)
31
+ total.set(detail, (total.get(detail) ?? 0) + 1);
32
+ const seen = new Map();
33
+ for (const { name, detail } of run) {
34
+ const n = (seen.get(detail) ?? 0) + 1;
35
+ seen.set(detail, n);
36
+ const which = total.get(detail) > 1 ? `${ordinal(n)} ` : "";
37
+ const where = after !== undefined ? ` after "${after}"` : "";
38
+ labels.set(name, `the ${which}"${detail}"${where}`);
39
+ }
40
+ run = [];
41
+ };
42
+ for (const node of [tree.preamble, ...tree.sections]) {
43
+ if (node.type != "section")
44
+ continue;
45
+ const name = nameOf(node);
46
+ if (name === undefined)
47
+ continue;
48
+ if (node.kind == "preamble") {
49
+ labels.set(name, "the text before the first section");
50
+ continue;
51
+ }
52
+ const detail = sectionDetail(node);
53
+ if (detail === undefined) {
54
+ finish();
55
+ after = name;
56
+ labels.set(name, `the section "${name}"`);
57
+ continue;
58
+ }
59
+ run.push({ name, detail });
60
+ }
61
+ finish();
62
+ }
63
+ return labels;
64
+ }
package/dist/setters.d.ts CHANGED
@@ -23,6 +23,10 @@ export interface AtAttribute {
23
23
  range: Range;
24
24
  }
25
25
  export declare function findAtAttributes(file: SquiffyFile): AtAttribute[];
26
+ export declare function splitWithOffsets(setters: string): {
27
+ text: string;
28
+ offset: number;
29
+ }[];
26
30
  export declare function attributesSetIn(file: SquiffyFile, text: string): Set<string>;
27
31
  export interface UnquotedText {
28
32
  text: string;
package/dist/setters.js CHANGED
@@ -16,7 +16,7 @@
16
16
  // Conversion isn't idempotent: a converted @set best = score would be converted again to
17
17
  // @set best = "score". So it's only for stories without a squiffy.json.
18
18
  import { parse } from "./parse.js";
19
- // The same as the tokenizer's numbers and literals in runtime/src/infixExpressions.ts
19
+ // The same as the tokenizer's numbers and literals in infix-expressions.ts
20
20
  const numberPattern = /^-?\d+(\.\d+)?$/;
21
21
  const reservedWords = new Set(["and", "or", "not", "true", "false", "null", "undefined"]);
22
22
  // Text as a quoted string. preferSingle is for setters inside a set="..." string, where double
@@ -180,7 +180,7 @@ export function convertSetters(script) {
180
180
  // A link's setters: everything after the first comma of its target. For a next link, the target
181
181
  // is just the setters part, e.g. ", gold=1".
182
182
  function convertLink(link, lines, replace, problem) {
183
- if (link.form === "unnamed")
183
+ if (link.form === "unnamed" || link.form === "input")
184
184
  return 0;
185
185
  const comma = link.target.indexOf(",");
186
186
  if (comma === -1)
@@ -242,7 +242,7 @@ export function findAtAttributes(file) {
242
242
  for (const link of container.links) {
243
243
  const comma = link.target.indexOf(",");
244
244
  const { targetRange } = link;
245
- if (link.form === "unnamed" || comma === -1 || targetRange.start.line !== targetRange.end.line)
245
+ if (link.form === "unnamed" || link.form === "input" || comma === -1 || targetRange.start.line !== targetRange.end.line)
246
246
  continue;
247
247
  scan(link.target.substring(comma + 1), targetRange.start.line, targetRange.start.character + comma + 1);
248
248
  }
@@ -251,8 +251,9 @@ export function findAtAttributes(file) {
251
251
  return result;
252
252
  }
253
253
  // Splits a list of setters with the rules of a story that uses expressions (as splitSetters in
254
- // runtime/src/infixExpressions.ts does): on commas outside quotes and brackets. Keeps offsets.
255
- function splitWithOffsets(setters) {
254
+ // infix-expressions.ts does): on commas outside quotes, brackets and objects. Keeps
255
+ // offsets.
256
+ export function splitWithOffsets(setters) {
256
257
  const result = [];
257
258
  let depth = 0;
258
259
  let quote = null;
@@ -267,9 +268,9 @@ function splitWithOffsets(setters) {
267
268
  }
268
269
  else if (c === "\"" || c === "'")
269
270
  quote = c;
270
- else if (c === "(")
271
+ else if (c === "(" || c === "[" || c === "{")
271
272
  depth++;
272
- else if (c === ")")
273
+ else if (c === ")" || c === "]" || c === "}")
273
274
  depth = Math.max(0, depth - 1);
274
275
  else if (i === setters.length || (c === "," && depth === 0)) {
275
276
  result.push({ text: setters.slice(start, i), offset: start });
@@ -304,7 +305,7 @@ function setterSites(file) {
304
305
  for (const link of container.links) {
305
306
  const comma = link.target.indexOf(",");
306
307
  const { targetRange } = link;
307
- if (link.form === "unnamed" || comma === -1 || targetRange.start.line !== targetRange.end.line)
308
+ if (link.form === "unnamed" || link.form === "input" || comma === -1 || targetRange.start.line !== targetRange.end.line)
308
309
  continue;
309
310
  addList(link.target.substring(comma + 1), targetRange.start.line, targetRange.start.character + comma + 1, false);
310
311
  }
@@ -344,7 +345,8 @@ export function findUnquotedText(file, isSet) {
344
345
  const result = [];
345
346
  for (const site of setterSites(file)) {
346
347
  // Only plain "=": text with +=, -=, *= or /= is an error whatever it's written as
347
- const match = /^(\s*)(\w+)(\s*=(?!=)\s*)(.*?)\s*$/.exec(site.text);
348
+ // The attribute can be a value inside an object, as in hero.name = Ann (#442)
349
+ const match = /^(\s*)(\w+(?:\.\w+)*)(\s*=(?!=)\s*)(.*?)\s*$/.exec(site.text);
348
350
  if (!match)
349
351
  continue;
350
352
  const [, leading, attribute, eq, value] = match;
@@ -10,6 +10,7 @@ export interface GraphNode {
10
10
  name: string;
11
11
  section?: string;
12
12
  detail?: string;
13
+ label?: string;
13
14
  location: Location;
14
15
  contentEnd: Position;
15
16
  start?: boolean;
@@ -64,3 +65,4 @@ export interface GraphSource {
64
65
  }
65
66
  export declare function buildStoryGraph(source: GraphSource): StoryGraph;
66
67
  export declare function storyGraphDiagnostics(graph: StoryGraph): Diagnostic[];
68
+ export declare function firstScreenSoundDiagnostics(source: GraphSource): Diagnostic[];
@@ -1,20 +1,22 @@
1
1
  // The whole story as a directed graph: its sections and passages, and the links between them,
2
2
  // with which can be reached from the start and which sections are dead ends. The language
3
3
  // service builds it from its index (see getStoryGraph), for the story map and for the
4
- // "unreachable section" and "dead end" diagnostics.
4
+ // "unreachable section" and "dead end" diagnostics, and the "sound on the first screen" one.
5
+ import { capitalise, sectionDetail, sectionLabels } from "./section-labels.js";
5
6
  export const sectionId = (name) => `section:${name}`;
6
7
  export const passageId = (section, name) => `passage:${section}/${name}`;
7
8
  const NAVIGATION = new Set(["section-link", "goto", "script"]);
8
9
  const collapsed = (position) => ({ start: position, end: position });
9
10
  const comparePositions = (a, b) => a.line - b.line || a.character - b.character;
10
- // The parts of a container's text inside {{#if}} or {{#unless}} blocks
11
+ // The parts of a container's text inside {{#if}} or {{#unless}} blocks, or {{#every}} (#451),
12
+ // whose text is shown later, if the player is still there
11
13
  function conditionalRanges(container) {
12
14
  const ranges = [];
13
15
  const open = [];
14
16
  for (const statement of container.body) {
15
17
  if (statement.type != "text")
16
18
  continue;
17
- for (const match of statement.text.matchAll(/\{\{~?\s*([#/])(if|unless)\b/g)) {
19
+ for (const match of statement.text.matchAll(/\{\{~?\s*([#/])(if|unless|every)\b/g)) {
18
20
  const position = { line: statement.range.start.line, character: match.index };
19
21
  if (match[1] == "#") {
20
22
  open.push(position);
@@ -31,16 +33,6 @@ function conditionalRanges(container) {
31
33
  ranges.push({ start, end: container.range.end });
32
34
  return ranges;
33
35
  }
34
- // What the outline calls a section without a name of its own
35
- function sectionDetail(node) {
36
- if (node.kind == "preamble")
37
- return "(Start)";
38
- if (node.header?.type == "continue")
39
- return `+++${node.header.text}`;
40
- if (node.header?.type == "separator")
41
- return "---";
42
- return undefined;
43
- }
44
36
  // The end of a section's or passage's own text, leaving out blank lines and its passages
45
37
  function contentEnd(container) {
46
38
  const ownEnd = container.type == "section" && container.passages.length
@@ -141,6 +133,11 @@ export function buildStoryGraph(source) {
141
133
  }
142
134
  }
143
135
  }
136
+ for (const [name, label] of sectionLabels(source.files.values(), node => source.nodeNames.get(node))) {
137
+ const node = nodeById.get(sectionId(name));
138
+ if (node)
139
+ node.label = label;
140
+ }
144
141
  // The link a +++ line adds to the section before it
145
142
  for (const [file, tree] of source.files) {
146
143
  const all = [tree.preamble, ...tree.sections];
@@ -197,7 +194,7 @@ export function buildStoryGraph(source) {
197
194
  if (dynamic)
198
195
  unknown.add(from);
199
196
  const resolvedName = target?.name;
200
- const setters = link.form != "next" && link.target.trim() == resolvedName
197
+ const setters = link.form == "input" || (link.form != "next" && link.target.trim() == resolvedName)
201
198
  ? []
202
199
  : link.target.split(",").slice(1).map(s => s.trim()).filter(Boolean);
203
200
  const text = link.text ?? link.target.trim().split(",")[0].trim();
@@ -351,7 +348,7 @@ export function storyGraphDiagnostics(graph) {
351
348
  range: node.location.range,
352
349
  severity: "warning",
353
350
  code: "squiffy/unreachable-section",
354
- message: `The section "${node.name}" can't be reached from the start of the story, as nothing the player can reach links to it.`,
351
+ message: `${capitalise(node.label ?? `the section "${node.name}"`)} can't be reached from the start of the story, as nothing the player can reach links to it.`,
355
352
  });
356
353
  }
357
354
  else if (node.deadEnd) {
@@ -360,9 +357,57 @@ export function storyGraphDiagnostics(graph) {
360
357
  range: node.location.range,
361
358
  severity: "warning",
362
359
  code: "squiffy/dead-end",
363
- message: `The section "${node.name}" has no way out, as it has no links to another section. If it's one of the story's endings, add @end to say so.`,
360
+ message: `${capitalise(node.label ?? `the section "${node.name}"`)} has no way out, as it has no links to another section. If it's one of the story's endings, add @end to say so.`,
364
361
  });
365
362
  }
366
363
  }
367
364
  return diagnostics;
368
365
  }
366
+ // {{music "file"}} or {{sound "file"}}, as emit.ts finds them
367
+ const SOUND_HELPER = /\{\{~?\s*(music|sound)\s+(["'])([^"'{}]+)\2/g;
368
+ // Sound on the story's first screen: browsers don't let a page play sound until the player has
369
+ // clicked something, so music there waits for their first click, and a sound played once there
370
+ // isn't heard at all. That's the start section's own @music, @sound, {{music}} and {{sound}},
371
+ // and the master section's @music and @sound, which play with every section, the first too.
372
+ // (Its passages, and the start section's, are shown by a click, so they're fine.)
373
+ export function firstScreenSoundDiagnostics(source) {
374
+ const diagnostics = [];
375
+ const report = (file, range, kind, value, master) => {
376
+ const where = master ? "The master section plays this with every section, including the story's first screen, but browsers" : "Browsers";
377
+ const what = kind == "music"
378
+ ? `so "${value}" won't start until the player's first click`
379
+ : `so "${value}" won't be heard on the story's first screen`;
380
+ diagnostics.push({
381
+ file,
382
+ range,
383
+ severity: "warning",
384
+ code: "squiffy/sound-on-first-screen",
385
+ message: `${where} don't play sound until the player has clicked something, ${what}. Begin the story with a title screen and a link such as "Begin", and play it in the section that link goes to.`,
386
+ });
387
+ };
388
+ const check = (name, master) => {
389
+ const section = source.sections.get(name);
390
+ if (!section?.node)
391
+ return;
392
+ for (const statement of section.node.body) {
393
+ if (statement.type == "sound") {
394
+ if (statement.value != "stop")
395
+ report(section.file, statement.range, statement.directive, statement.value, master);
396
+ }
397
+ else if (statement.type == "text" && !master) {
398
+ for (const match of statement.text.matchAll(SOUND_HELPER)) {
399
+ const before = statement.text.substring(0, match.index);
400
+ const lines = before.split("\n");
401
+ const line = statement.range.start.line + lines.length - 1;
402
+ const character = (lines.length == 1 ? statement.range.start.character : 0) + lines[lines.length - 1].length;
403
+ const range = { start: { line, character }, end: { line, character: character + match[0].length } };
404
+ report(section.file, range, match[1], match[3], false);
405
+ }
406
+ }
407
+ }
408
+ };
409
+ if (source.start != "")
410
+ check(source.start, false);
411
+ check("", true);
412
+ return diagnostics;
413
+ }
package/dist/syntax.d.ts CHANGED
@@ -7,7 +7,7 @@ export interface Range {
7
7
  end: Position;
8
8
  }
9
9
  export type DiagnosticSeverity = "error" | "warning" | "hint";
10
- export type DiagnosticCode = "squiffy/passage-without-section" | "squiffy/text-in-ui-block" | "squiffy/content-before-section" | "squiffy/v5-syntax" | "squiffy/at-attribute" | "squiffy/unquoted-text" | "squiffy/built-in-attribute" | "squiffy/external-files-unavailable" | "squiffy/no-next-section" | "squiffy/unknown-embed" | "squiffy/unknown-goto" | "squiffy/unknown-deactivate" | "squiffy/unknown-section-link" | "squiffy/unknown-passage-link" | "squiffy/duplicate-section" | "squiffy/duplicate-passage" | "squiffy/not-in-main-file" | "squiffy/repeat-not-in-passage" | "squiffy/redundant-import" | "squiffy/project-file" | "squiffy/unreachable-section" | "squiffy/dead-end";
10
+ export type DiagnosticCode = "squiffy/passage-without-section" | "squiffy/text-in-ui-block" | "squiffy/content-before-section" | "squiffy/v5-syntax" | "squiffy/at-attribute" | "squiffy/unquoted-text" | "squiffy/built-in-attribute" | "squiffy/external-files-unavailable" | "squiffy/no-next-section" | "squiffy/unknown-embed" | "squiffy/unknown-goto" | "squiffy/unknown-deactivate" | "squiffy/unknown-section-link" | "squiffy/unknown-passage-link" | "squiffy/duplicate-section" | "squiffy/duplicate-passage" | "squiffy/not-in-main-file" | "squiffy/repeat-not-in-passage" | "squiffy/transition" | "squiffy/redundant-import" | "squiffy/project-file" | "squiffy/unreachable-section" | "squiffy/dead-end" | "squiffy/sound-on-first-screen" | "squiffy/template-syntax";
11
11
  export interface Diagnostic {
12
12
  file: string;
13
13
  range: Range;
@@ -121,6 +121,27 @@ export interface EndNode {
121
121
  type: "end";
122
122
  range: Range;
123
123
  }
124
+ export interface SoundNode {
125
+ type: "sound";
126
+ directive: "music" | "sound";
127
+ value: string;
128
+ valueRange: Range;
129
+ range: Range;
130
+ }
131
+ export interface ClassNode {
132
+ type: "class";
133
+ value: string;
134
+ valueRange: Range;
135
+ range: Range;
136
+ }
137
+ export interface TransitionNode {
138
+ type: "transition";
139
+ directive: "transition" | "leave";
140
+ value: string;
141
+ valueRange: Range;
142
+ time?: string;
143
+ range: Range;
144
+ }
124
145
  export interface AttributeNode {
125
146
  type: "attribute";
126
147
  directive: "set" | "unset" | "inc" | "dec";
@@ -140,11 +161,11 @@ export interface TextNode {
140
161
  text: string;
141
162
  range: Range;
142
163
  }
143
- export type StatementNode = SeparatorNode | TitleNode | StartNode | ImportNode | UiBlockStartNode | UiFileNode | ClearNode | RepeatNode | EndNode | AttributeNode | JsNode | TextNode;
164
+ export type StatementNode = SeparatorNode | TitleNode | StartNode | ImportNode | UiBlockStartNode | UiFileNode | ClearNode | RepeatNode | EndNode | AttributeNode | SoundNode | ClassNode | TransitionNode | JsNode | TextNode;
144
165
  export interface LinkNode {
145
166
  type: "link";
146
167
  linkType: "section" | "passage";
147
- form: "named" | "unnamed" | "next";
168
+ form: "named" | "unnamed" | "next" | "input";
148
169
  text?: string;
149
170
  target: string;
150
171
  range: Range;
@@ -0,0 +1,6 @@
1
+ export interface TemplateError {
2
+ start: number;
3
+ end: number;
4
+ message: string;
5
+ }
6
+ export declare function findTemplateError(text: string): TemplateError | null;
@@ -0,0 +1,128 @@
1
+ // Finds Handlebars syntax errors in a section's or passage's text, which the runtime would
2
+ // otherwise only report when the text is shown ("Template error: Parse error on line 6...").
3
+ //
4
+ // The text is parsed the way the runtime's text processor compiles it: after the compiler has
5
+ // turned links into helpers, and after rewriteInfixExpressions. (The runtime also adds a __body=
6
+ // to each {{#every}} first, but that's only ever a string parameter, so it can't make a
7
+ // difference to whether the text parses.)
8
+ import Handlebars from "handlebars";
9
+ import { findTagEnd, InfixRewriteError, mapRewrittenPosition, rewriteInfixExpressions } from "./infix-expressions.js";
10
+ const lexer = Handlebars.Parser.lexer;
11
+ export function findTemplateError(text) {
12
+ if (!text.includes("{{"))
13
+ return null;
14
+ const edits = [];
15
+ let rewritten;
16
+ try {
17
+ rewritten = rewriteInfixExpressions(text, edits);
18
+ }
19
+ catch (e) {
20
+ // An expression it can't read, e.g. {{set "gold" gold +}}
21
+ if (!(e instanceof InfixRewriteError))
22
+ throw e;
23
+ const end = e.end + (text.startsWith("~}}", e.end) ? 3 : 2);
24
+ return { start: e.start, end, message: `${describeTag(text.slice(e.start, end))} isn't valid: ${e.message}` };
25
+ }
26
+ try {
27
+ Handlebars.parse(rewritten);
28
+ return null;
29
+ }
30
+ catch (e) {
31
+ const error = e;
32
+ const lineStarts = [0];
33
+ for (let i = 0; i < rewritten.length; i++) {
34
+ if (rewritten[i] == "\n")
35
+ lineStarts.push(i + 1);
36
+ }
37
+ const offset = (line, column) => mapRewrittenPosition(edits, Math.min((lineStarts[line - 1] ?? rewritten.length) + column, rewritten.length));
38
+ if (error.lineNumber !== undefined) {
39
+ return handlebarsError(text, error.message, offset(error.lineNumber, error.column ?? 0));
40
+ }
41
+ const loc = lexer.yylloc;
42
+ const pos = loc ? offset(loc.first_line, loc.first_column) : 0;
43
+ return parseError(text, error.message, pos);
44
+ }
45
+ }
46
+ // "unless doesn't match if - 1:3", or "Invalid path: a/this - 1:31"
47
+ function handlebarsError(text, message, pos) {
48
+ message = message.replace(/ - \d+:\d+$/, "");
49
+ const tag = tagAt(text, pos) ?? { start: pos, end: pos };
50
+ const tagText = describeTag(text.slice(tag.start, tag.end));
51
+ const mismatch = /^(.+) doesn't match (.+)$/.exec(message);
52
+ if (mismatch) {
53
+ return { ...tag, message: `${tagText} is closed by {{/${mismatch[2]}}}, but it needs a {{/${mismatch[1]}}}` };
54
+ }
55
+ return { ...tag, message: `${tagText} isn't valid Handlebars: ${message}` };
56
+ }
57
+ function parseError(text, message, pos) {
58
+ // The last line says what the parser expected, e.g. "Expecting 'ID', 'STRING', ..., got 'INVALID'"
59
+ const got = /got '([^']+)'\s*$/.exec(message)?.[1];
60
+ if (got == "EOF") {
61
+ const open = unclosedBlock(text);
62
+ if (open) {
63
+ return { ...open, message: `${describeTag(text.slice(open.start, open.end))} has no {{/${open.name}}} to close it` };
64
+ }
65
+ }
66
+ const tag = tagAt(text, pos);
67
+ if (!tag) {
68
+ const end = Math.min(pos + 1, text.length);
69
+ return { start: Math.min(pos, end), end, message: "this text isn't valid Handlebars" + (got ? ` (it found ${got == "EOF" ? "the end of the text" : `'${got}'`} where it didn't expect it)` : "") };
70
+ }
71
+ const tagText = text.slice(tag.start, tag.end);
72
+ return { ...tag, message: `${describeTag(tagText)} isn't valid Handlebars${hint(tagText)}` };
73
+ }
74
+ // Suggests {{= ...}} for what looks like an expression in a plain {{...}}, e.g. {{round + 1}}
75
+ function hint(tagText) {
76
+ const inner = tagText.replace(/^\{\{\{?~?\s*/, "").replace(/\s*~?\}?\}\}$/, "");
77
+ if (/^[#/=!>^&]|^else\b/.test(inner))
78
+ return "";
79
+ if (!/\s(?:[-+*/%<>?]|[=!<>]=|&&|\|\||and|or|contains)\s/.test(` ${inner} `))
80
+ return "";
81
+ return `. To show the result of an expression, start it with "=": {{= ${inner}}}`;
82
+ }
83
+ // The {{...}} tag that pos is in, if any
84
+ function tagAt(text, pos) {
85
+ let start = text.lastIndexOf("{{", pos);
86
+ if (start == -1)
87
+ return null;
88
+ if (text[start - 1] == "{")
89
+ start--;
90
+ const bodyStart = text.startsWith("{{{", start) ? start + 3 : start + 2;
91
+ const close = findTagEnd(text, bodyStart);
92
+ if (close == -1) {
93
+ const lineEnd = text.indexOf("\n", start);
94
+ return { start, end: lineEnd == -1 ? text.length : lineEnd };
95
+ }
96
+ let end = close + (text.startsWith("~}}", close) ? 3 : 2);
97
+ if (text[end] == "}" && bodyStart == start + 3)
98
+ end++;
99
+ if (pos >= end && pos > start)
100
+ return null;
101
+ return { start, end };
102
+ }
103
+ // The innermost {{#block}} with no {{/block}} after it
104
+ function unclosedBlock(text) {
105
+ const tags = /(\\*)\{\{~?\s*([#/])\s*([^\s}~]+)/g;
106
+ const open = [];
107
+ let match;
108
+ while ((match = tags.exec(text)) !== null) {
109
+ if (match[1].length % 2 == 1)
110
+ continue;
111
+ const start = match.index + match[1].length;
112
+ if (match[2] == "#") {
113
+ const close = findTagEnd(text, start + 2);
114
+ const end = close == -1 ? text.length : close + (text.startsWith("~}}", close) ? 3 : 2);
115
+ open.push({ start, end, name: match[3].replace(/^>/, "") });
116
+ }
117
+ else {
118
+ const index = open.map(o => o.name).lastIndexOf(match[3]);
119
+ if (index != -1)
120
+ open.length = index;
121
+ }
122
+ }
123
+ return open.pop() ?? null;
124
+ }
125
+ function describeTag(tagText) {
126
+ const oneLine = tagText.replace(/\s*\n\s*/g, " ");
127
+ return oneLine.length > 60 ? oneLine.substring(0, 57) + "..." : oneLine;
128
+ }
package/dist/text.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export interface TextLink {
2
2
  linkType: "section" | "passage";
3
- form: "named" | "unnamed" | "next";
3
+ form: "named" | "unnamed" | "next" | "input";
4
4
  text?: string;
5
5
  target: string;
6
6
  start: number;
@@ -29,6 +29,8 @@ export interface TransformResult {
29
29
  gotos: TextGoto[];
30
30
  deactivates: TextDeactivate[];
31
31
  noNextSection: NoNextSection[];
32
+ mapStart: (pos: number) => number;
33
+ mapEnd: (pos: number) => number;
32
34
  }
33
35
  export declare const balancedTarget: string;
34
36
  export declare function transformText(text: string, getNextSectionName: () => string | null, expressions?: boolean): TransformResult;