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

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 (43) hide show
  1. package/README.md +10 -2
  2. package/dist/analyse.d.ts +3 -0
  3. package/dist/analyse.js +73 -12
  4. package/dist/compiler.d.ts +12 -2
  5. package/dist/compiler.js +6 -2
  6. package/dist/emit.d.ts +6 -0
  7. package/dist/emit.js +17 -1
  8. package/dist/language-service.js +36 -5
  9. package/dist/node.d.ts +8 -1
  10. package/dist/node.js +19 -5
  11. package/dist/parse.js +18 -2
  12. package/dist/project.d.ts +56 -0
  13. package/dist/project.js +159 -17
  14. package/dist/quest/aslx.d.ts +50 -0
  15. package/dist/quest/aslx.js +181 -0
  16. package/dist/quest/convert.d.ts +20 -0
  17. package/dist/quest/convert.js +475 -0
  18. package/dist/quest/script.d.ts +92 -0
  19. package/dist/quest/script.js +453 -0
  20. package/dist/quest/scripts.d.ts +24 -0
  21. package/dist/quest/scripts.js +501 -0
  22. package/dist/quest/text.d.ts +17 -0
  23. package/dist/quest/text.js +305 -0
  24. package/dist/setters.d.ts +6 -0
  25. package/dist/setters.js +43 -0
  26. package/dist/story-graph.d.ts +3 -1
  27. package/dist/story-graph.js +12 -3
  28. package/dist/syntax.d.ts +22 -2
  29. package/dist/text.d.ts +4 -0
  30. package/dist/text.js +28 -21
  31. package/dist/twine/convert.d.ts +82 -0
  32. package/dist/twine/convert.js +744 -0
  33. package/dist/twine/expression.d.ts +68 -0
  34. package/dist/twine/expression.js +215 -0
  35. package/dist/twine/harlowe.d.ts +18 -0
  36. package/dist/twine/harlowe.js +1912 -0
  37. package/dist/twine/story.d.ts +24 -0
  38. package/dist/twine/story.js +231 -0
  39. package/dist/twine/sugarcube.d.ts +34 -0
  40. package/dist/twine/sugarcube.js +1621 -0
  41. package/dist/v5.js +2 -1
  42. package/package.json +3 -2
  43. package/syntaxes/squiffy.tmLanguage.json +1 -1
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
- ## Local development
1
+ # squiffy-compiler
2
2
 
3
- `npm run dev -- examples/helloworld/helloworld.squiffy`
3
+ Compiles Squiffy story files into JavaScript. See [the main README](../README.md) and the [docs](https://squiffystory.com).
4
+
5
+ ## Tests
6
+
7
+ ```bash
8
+ npm test
9
+ ```
10
+
11
+ `test/fixtures/` has a small story for each feature. `compiler.test.ts` compiles each of them, and the complete stories in `../examples`, and compares the output with its snapshots. The fixtures have no `squiffy.json`, so they use Squiffy 6's rules for setters. `warnings/` has stories that should produce warnings.
package/dist/analyse.d.ts CHANGED
@@ -35,6 +35,8 @@ export interface Analysis {
35
35
  sections: SectionSymbol[];
36
36
  start: string;
37
37
  expressions: boolean;
38
+ stylesheets: string[];
39
+ scripts: string[];
38
40
  }
39
41
  export declare class Story {
40
42
  sections: Record<string, Section>;
@@ -69,6 +71,7 @@ export declare class Passage extends TextContainer {
69
71
  name: string;
70
72
  line: number;
71
73
  node: PassageNode;
74
+ repeat: boolean;
72
75
  constructor(name: string, line: number, node: PassageNode);
73
76
  }
74
77
  export interface AnalysisInternals {
package/dist/analyse.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { parse } from "./parse.js";
2
2
  import { positionMapper, transformText } from "./text.js";
3
- import { PROJECT_FILENAME } from "./project.js";
3
+ import { isScriptPath, isSquiffyPath, isStylesheetPath, PROJECT_FILENAME } from "./project.js";
4
4
  import { findV5Syntax } from "./v5.js";
5
- import { attributesSetIn, findAtAttributes, findUnquotedText } from "./setters.js";
5
+ import { attributesSetIn, BUILT_IN_ATTRIBUTES, findAtAttributes, findBuiltInAttributeSets, findUnquotedText } from "./setters.js";
6
6
  // Caches the syntax tree of each file by filename, reparsing a file only when its text changes.
7
7
  export class ParseCache {
8
8
  constructor() {
@@ -183,6 +183,13 @@ export class Passage extends TextContainer {
183
183
  writable: true,
184
184
  value: node
185
185
  });
186
+ // @repeat: its links stay clickable (#104)
187
+ Object.defineProperty(this, "repeat", {
188
+ enumerable: true,
189
+ configurable: true,
190
+ writable: true,
191
+ value: false
192
+ });
186
193
  }
187
194
  }
188
195
  export const analysisInternals = new WeakMap();
@@ -212,6 +219,23 @@ export async function analyse(settings) {
212
219
  // The .squiffy files processed so far, so a story file the main file has already @imported
213
220
  // isn't processed again
214
221
  const processed = new Set();
222
+ // Files read by @ui, which in folder mode aren't added to the page as scripts too
223
+ const uiFiles = new Set();
224
+ // The .css and .js files added to the page so far, named as getMatchingFilenames names them
225
+ const stylesheetFiles = [];
226
+ const scriptFiles = [];
227
+ // Adds a stylesheet or script to the page. An @import adds it every time, as in Squiffy 6, but
228
+ // folder mode only adds one that isn't there already.
229
+ const addPageFile = (filename, externalFiles, imported) => {
230
+ const [names, local] = isStylesheetPath(filename)
231
+ ? [stylesheetFiles, story.stylesheets]
232
+ : [scriptFiles, story.scripts];
233
+ if (names.includes(filename) && !imported)
234
+ return;
235
+ if (!names.includes(filename))
236
+ names.push(filename);
237
+ local.push(externalFiles.getLocalFilename(filename));
238
+ };
215
239
  async function processFile(text, filename, isFirst) {
216
240
  const file = cache.parse(text, filename);
217
241
  files.push(file);
@@ -317,6 +341,13 @@ export async function analyse(settings) {
317
341
  return true;
318
342
  case "ui-file":
319
343
  if (settings.externalFiles) {
344
+ // In folder mode, the file isn't also added to the page as a script, so it
345
+ // doesn't run twice. Its name is looked up before it's read, as reading it
346
+ // can leave it out of getMatchingFilenames.
347
+ if (storyFiles) {
348
+ for (const match of await settings.externalFiles.getMatchingFilenames(node.path))
349
+ uiFiles.add(match);
350
+ }
320
351
  story.uiJs.push(await settings.externalFiles.getContent(node.path));
321
352
  }
322
353
  else {
@@ -334,6 +365,14 @@ export async function analyse(settings) {
334
365
  passage.clear = true;
335
366
  }
336
367
  return true;
368
+ case "repeat":
369
+ if (!passage) {
370
+ report("warning", "squiffy/repeat-not-in-passage", filename, lineRange(node), "@repeat only works in a passage, so this was ignored.", lineCount);
371
+ }
372
+ else {
373
+ passage.repeat = true;
374
+ }
375
+ return true;
337
376
  case "end":
338
377
  // Only for the language service's dead end check
339
378
  if (!passage) {
@@ -362,23 +401,18 @@ export async function analyse(settings) {
362
401
  return true;
363
402
  }
364
403
  const matches = await settings.externalFiles.getMatchingFilenames(node.pattern);
365
- const squiffyMatches = matches.filter(m => m.endsWith(".squiffy"));
366
- if (storyFiles && squiffyMatches.length && squiffyMatches.length == matches.length
367
- && squiffyMatches.every(m => storyFiles.has(m))) {
368
- report("hint", "squiffy/redundant-import", filename, lineRange(node), `${squiffyMatches.length == 1 ? "This file is" : "These files are"} already part of the story, as ${PROJECT_FILENAME} includes every .squiffy file in the folder, so this @import isn't needed.`, lineCount);
404
+ if (storyFiles && matches.length && matches.every(m => storyFiles.has(m))) {
405
+ report("hint", "squiffy/redundant-import", filename, lineRange(node), `${matches.length == 1 ? "This file is" : "These files are"} already part of the story, as ${PROJECT_FILENAME} includes every .squiffy, .css and .js file in the folder, so this @import isn't needed.`, lineCount);
369
406
  }
370
407
  for (const importFilename of matches) {
371
- if (importFilename.endsWith(".squiffy")) {
408
+ if (isSquiffyPath(importFilename)) {
372
409
  const content = await settings.externalFiles.getContent(importFilename);
373
410
  const success = await processFile(content, importFilename, false);
374
411
  if (!success && !settings.recover)
375
412
  return false;
376
413
  }
377
- else if (importFilename.endsWith(".js")) {
378
- story.scripts.push(settings.externalFiles.getLocalFilename(importFilename));
379
- }
380
- else if (importFilename.endsWith(".css")) {
381
- story.stylesheets.push(settings.externalFiles.getLocalFilename(importFilename));
414
+ else if (isStylesheetPath(importFilename) || isScriptPath(importFilename)) {
415
+ addPageFile(importFilename, settings.externalFiles, true);
382
416
  }
383
417
  }
384
418
  return true;
@@ -545,6 +579,20 @@ export async function analyse(settings) {
545
579
  warn("squiffy/unknown-embed", embed.start, embed.end, `${where} there is an embed of {{embed "${embed.name}"}}, but no section or passage with that name exists`);
546
580
  }
547
581
  }
582
+ // {{goto}} only goes to sections
583
+ for (const goto of result.gotos) {
584
+ if (!goto.name || !(goto.name in story.sections)) {
585
+ const passage = goto.name in section.passages ? ` ({{goto}} can't go to a passage: use {{embed "${goto.name}"}} to show it here)` : "";
586
+ warn("squiffy/unknown-goto", goto.start, goto.end, `${where} there is a {{goto "${goto.name}"}}, but no section with that name exists${passage}`);
587
+ }
588
+ }
589
+ // {{deactivate}} disables links to a passage in this section, or in the master section
590
+ const masterPassages = story.sections[""]?.passages ?? {};
591
+ for (const deactivate of result.deactivates) {
592
+ if (!(deactivate.name in section.passages) && !(deactivate.name in masterPassages)) {
593
+ warn("squiffy/unknown-deactivate", deactivate.start, deactivate.end, `${where} there is a {{deactivate "${deactivate.name}"}}, but no passage with that name exists in this section`);
594
+ }
595
+ }
548
596
  }
549
597
  // With recover, processFile carries on after errors, so check for them too
550
598
  let success = await processFile(settings.script, settings.scriptBaseFilename, true);
@@ -558,6 +606,11 @@ export async function analyse(settings) {
558
606
  report("warning", "squiffy/external-files-unavailable", settings.scriptBaseFilename, { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } }, "The story's other files were ignored, as other files can't be loaded here", 1);
559
607
  break;
560
608
  }
609
+ if (!isSquiffyPath(storyFile)) {
610
+ if (!uiFiles.has(storyFile))
611
+ addPageFile(storyFile, settings.externalFiles, false);
612
+ continue;
613
+ }
561
614
  const content = await settings.externalFiles.getContent(storyFile);
562
615
  success = await processFile(content, storyFile, false) && success;
563
616
  }
@@ -581,6 +634,12 @@ export async function analyse(settings) {
581
634
  if (settings.expressions) {
582
635
  warnAboutUnquotedText();
583
636
  }
637
+ // A story setting an attribute that Squiffy sets itself, such as turns (#377)
638
+ files.forEach((file, i) => {
639
+ for (const found of findBuiltInAttributeSets(file, texts[i])) {
640
+ report("warning", "squiffy/built-in-attribute", file.filename, found.range, `Squiffy sets ${found.name} itself: it's ${BUILT_IN_ATTRIBUTES.get(found.name)}. Use a different name for your own attribute.`, found.range.start.line + 1);
641
+ }
642
+ });
584
643
  const analysis = {
585
644
  success,
586
645
  files,
@@ -593,6 +652,8 @@ export async function analyse(settings) {
593
652
  })),
594
653
  start: story.start,
595
654
  expressions: settings.expressions ?? false,
655
+ stylesheets: stylesheetFiles,
656
+ scripts: scriptFiles,
596
657
  };
597
658
  analysisInternals.set(analysis, { story, legacyErrors, legacyWarnings });
598
659
  return analysis;
@@ -1,9 +1,17 @@
1
1
  import { ExternalFiles, ParseCache } from "./analyse.js";
2
2
  import { CompileSuccess } from "./emit.js";
3
3
  import type { Diagnostic } from "./syntax.js";
4
+ import type { Panel } from "./project.js";
4
5
  export { findV5Syntax, convertV5Syntax } from "./v5.js";
5
6
  export type { V5SyntaxMatch, V5ConversionProblem, V5ConversionResult } from "./v5.js";
6
7
  export { convertSetters, convertSetter } from "./setters.js";
8
+ export { convertTwine, convertTwineStory, formatTwineProblems } from "./twine/convert.js";
9
+ export type { TwineConversionResult, TwineConversionProblem, TwineConversionOptions } from "./twine/convert.js";
10
+ export { parseTwine, isTwineSource, TwineParseError } from "./twine/story.js";
11
+ export type { TwineStory, TwinePassage } from "./twine/story.js";
12
+ export { convertQuestGamebook, formatQuestProblems } from "./quest/convert.js";
13
+ export type { QuestConversionResult, QuestConversionProblem, QuestConversionOptions } from "./quest/convert.js";
14
+ export { isQuestSource, QuestParseError } from "./quest/aslx.js";
7
15
  export type { SetterConversion, SetterConversionProblem, SetterConversionResult } from "./setters.js";
8
16
  export { parse } from "./parse.js";
9
17
  export { analyse, ParseCache } from "./analyse.js";
@@ -11,8 +19,8 @@ export type { AnalyseSettings, Analysis, ExternalFiles, SectionSymbol, PassageSy
11
19
  export { emit } from "./emit.js";
12
20
  export type { EmitSettings, Output, UiInfo, CompileSuccess } from "./emit.js";
13
21
  export { formatDiagnostic } from "./syntax.js";
14
- export { PROJECT_FILENAME, PROJECT_FILE_VERSION, PROJECT_SCHEMA_URL, parseProjectFile, getStoryFiles, isExcluded, isAlwaysSkipped, formatProjectFile, updateProjectFile, } from "./project.js";
15
- export type { MapPositions, ProjectFile, ParsedProjectFile, StoryFiles } from "./project.js";
22
+ export { PROJECT_FILENAME, PROJECT_FILE_VERSION, PROJECT_SCHEMA_URL, parseProjectFile, getStoryFiles, isExcluded, isAlwaysSkipped, formatProjectFile, updateProjectFile, PAGE_STRINGS, PANEL_ICONS, storyFileList, BUILD_FOLDER, } from "./project.js";
23
+ export type { MapPositions, PageStringName, PageStrings, Panel, PanelIcon, ProjectFile, ParsedProjectFile, StoryFiles } from "./project.js";
16
24
  export type * from "./syntax.js";
17
25
  interface CompilerSettings {
18
26
  scriptBaseFilename?: string;
@@ -23,6 +31,8 @@ interface CompilerSettings {
23
31
  parseCache?: ParseCache;
24
32
  storyFiles?: string[];
25
33
  expressions?: boolean;
34
+ projectId?: string;
35
+ panels?: Panel[];
26
36
  }
27
37
  export interface CompileError {
28
38
  success: false;
package/dist/compiler.js CHANGED
@@ -2,6 +2,10 @@ import { analyse, analysisInternals } from "./analyse.js";
2
2
  import { emit } from "./emit.js";
3
3
  export { findV5Syntax, convertV5Syntax } from "./v5.js";
4
4
  export { convertSetters, convertSetter } from "./setters.js";
5
+ export { convertTwine, convertTwineStory, formatTwineProblems } from "./twine/convert.js";
6
+ export { parseTwine, isTwineSource, TwineParseError } from "./twine/story.js";
7
+ export { convertQuestGamebook, formatQuestProblems } from "./quest/convert.js";
8
+ export { isQuestSource, QuestParseError } from "./quest/aslx.js";
5
9
  // The compiler works in three stages, which can also be used separately:
6
10
  // - parse() turns one file into a syntax tree, with a source range on every node
7
11
  // - analyse() resolves @imports, builds the story's sections and passages, and reports diagnostics
@@ -10,7 +14,7 @@ export { parse } from "./parse.js";
10
14
  export { analyse, ParseCache } from "./analyse.js";
11
15
  export { emit } from "./emit.js";
12
16
  export { formatDiagnostic } from "./syntax.js";
13
- export { PROJECT_FILENAME, PROJECT_FILE_VERSION, PROJECT_SCHEMA_URL, parseProjectFile, getStoryFiles, isExcluded, isAlwaysSkipped, formatProjectFile, updateProjectFile, } from "./project.js";
17
+ export { PROJECT_FILENAME, PROJECT_FILE_VERSION, PROJECT_SCHEMA_URL, parseProjectFile, getStoryFiles, isExcluded, isAlwaysSkipped, formatProjectFile, updateProjectFile, PAGE_STRINGS, PANEL_ICONS, storyFileList, BUILD_FOLDER, } from "./project.js";
14
18
  export async function compile(settings) {
15
19
  const analysis = await analyse(settings);
16
20
  const { legacyErrors, legacyWarnings } = analysisInternals.get(analysis);
@@ -26,5 +30,5 @@ export async function compile(settings) {
26
30
  diagnostics: analysis.diagnostics,
27
31
  };
28
32
  }
29
- return emit(analysis, { globalJs: settings.globalJs });
33
+ return emit(analysis, { globalJs: settings.globalJs, projectId: settings.projectId, panels: settings.panels });
30
34
  }
package/dist/emit.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Analysis } from "./analyse.js";
2
2
  import type { Diagnostic } from "./syntax.js";
3
+ import type { Panel } from "./project.js";
3
4
  export interface Output {
4
5
  story: OutputStory;
5
6
  js: string[][];
@@ -7,8 +8,10 @@ export interface Output {
7
8
  interface OutputStory {
8
9
  start: string;
9
10
  id: string | null;
11
+ projectId?: string;
10
12
  uiJsIndex?: number;
11
13
  expressions?: boolean;
14
+ panels?: Panel[];
12
15
  sections: Record<string, OutputSection>;
13
16
  }
14
17
  interface OutputSection {
@@ -22,6 +25,7 @@ interface OutputSection {
22
25
  interface OutputPassage {
23
26
  text?: string;
24
27
  clear?: boolean;
28
+ repeat?: boolean;
25
29
  attributes?: string[];
26
30
  jsIndex?: number;
27
31
  }
@@ -32,6 +36,8 @@ export interface UiInfo {
32
36
  }
33
37
  export interface EmitSettings {
34
38
  globalJs?: boolean;
39
+ projectId?: string;
40
+ panels?: Panel[];
35
41
  }
36
42
  export interface CompileSuccess {
37
43
  success: true;
package/dist/emit.js CHANGED
@@ -22,6 +22,12 @@ export function emit(analysis, settings = {}) {
22
22
  if (analysis.expressions) {
23
23
  output.story.expressions = true;
24
24
  }
25
+ if (settings.projectId) {
26
+ output.story.projectId = settings.projectId;
27
+ }
28
+ if (settings.panels?.length) {
29
+ output.story.panels = settings.panels;
30
+ }
25
31
  if (story.uiJs.length > 0) {
26
32
  output.js.push(story.uiJs);
27
33
  output.story.uiJsIndex = output.js.length - 1;
@@ -44,7 +50,8 @@ export function emit(analysis, settings = {}) {
44
50
  if ("@last" in section.passages) {
45
51
  let passageCount = 0;
46
52
  for (const passageName of Object.keys(section.passages)) {
47
- if (passageName.length > 0 && passageName?.substring(0, 1) !== "@") {
53
+ // A passage with @repeat doesn't count, as clicking it doesn't use it up
54
+ if (passageName.length > 0 && passageName?.substring(0, 1) !== "@" && !section.passages[passageName].repeat) {
48
55
  passageCount++;
49
56
  }
50
57
  }
@@ -60,6 +67,9 @@ export function emit(analysis, settings = {}) {
60
67
  if (passage.clear) {
61
68
  outputPassage.clear = true;
62
69
  }
70
+ if (passage.repeat) {
71
+ outputPassage.repeat = true;
72
+ }
63
73
  outputPassage.text = passage.output;
64
74
  if (passage.attributes.length > 0) {
65
75
  outputPassage.attributes = passage.attributes;
@@ -83,12 +93,18 @@ export function emit(analysis, settings = {}) {
83
93
  outputJs.push("export const story = {};");
84
94
  }
85
95
  outputJs.push(`story.id = ${JSON.stringify(output.story.id, null, 4)};`);
96
+ if (output.story.projectId) {
97
+ outputJs.push(`story.projectId = ${JSON.stringify(output.story.projectId)};`);
98
+ }
86
99
  if (output.story.uiJsIndex !== undefined) {
87
100
  outputJs.push(`story.uiJsIndex = ${output.story.uiJsIndex};`);
88
101
  }
89
102
  if (output.story.expressions) {
90
103
  outputJs.push("story.expressions = true;");
91
104
  }
105
+ if (output.story.panels) {
106
+ outputJs.push(`story.panels = ${JSON.stringify(output.story.panels, null, 4)};`);
107
+ }
92
108
  outputJs.push(`story.start = ${JSON.stringify(output.story.start, null, 4)};`);
93
109
  outputJs.push(`story.sections = ${JSON.stringify(output.story.sections, null, 4)};`);
94
110
  outputJs.push("story.js = [");
@@ -6,11 +6,12 @@
6
6
  //
7
7
  // Positions and ranges are zero-based { line, character }, following LSP conventions.
8
8
  import { analyse, ParseCache } from "./analyse.js";
9
- import { getStoryFiles, globToRegExp, parseProjectFile, PROJECT_FILENAME } from "./project.js";
9
+ import { getStoryFiles, globToRegExp, parseProjectFile, PROJECT_FILENAME, storyFileList } from "./project.js";
10
10
  import { convertV5Syntax, findV5Syntax } from "./v5.js";
11
11
  import { findUnquotedText } from "./setters.js";
12
12
  import { buildStoryGraph, storyGraphDiagnostics } from "./story-graph.js";
13
13
  const sameSymbol = (a, b) => a.kind == b.kind && a.name == b.name && (a.kind == "section" || a.section == b.section);
14
+ const usageRange = (usage) => (usage.link ?? usage.embed ?? usage.goto ?? usage.deactivate).range;
14
15
  // Directives, for completion, with what they do
15
16
  const DIRECTIVES = [
16
17
  ["title", "Sets the story's title"],
@@ -21,6 +22,7 @@ const DIRECTIVES = [
21
22
  ["inc", "Adds to an attribute"],
22
23
  ["dec", "Subtracts from an attribute"],
23
24
  ["clear", "Clears the screen"],
25
+ ["repeat", "Lets the player click this passage's links again"],
24
26
  ["end", "Marks this section as an ending"],
25
27
  ["ui", "JavaScript for the story's user interface"],
26
28
  ];
@@ -155,7 +157,7 @@ export function createLanguageService(options) {
155
157
  return { ...fallback, error: parsed.error };
156
158
  const project = parsed.project;
157
159
  const story = getStoryFiles(project, paths);
158
- return { projectFile: project, mainFile: project.main, storyFiles: story.included, excludedFiles: story.excluded };
160
+ return { projectFile: project, mainFile: project.main, storyFiles: storyFileList(story), excludedFiles: story.excluded };
159
161
  }
160
162
  async function buildIndex() {
161
163
  const texts = new Map();
@@ -234,6 +236,12 @@ export function createLanguageService(options) {
234
236
  for (const embed of container.embeds) {
235
237
  index.usages.push({ file: path, container, sectionNode: node, embed });
236
238
  }
239
+ for (const goto of container.gotos) {
240
+ index.usages.push({ file: path, container, sectionNode: node, goto });
241
+ }
242
+ for (const deactivate of container.deactivates) {
243
+ index.usages.push({ file: path, container, sectionNode: node, deactivate });
244
+ }
237
245
  for (const statement of container.body) {
238
246
  if (statement.type == "attribute") {
239
247
  const name = attributeName(statement.value);
@@ -304,6 +312,15 @@ export function createLanguageService(options) {
304
312
  return { kind: "section", name };
305
313
  return undefined;
306
314
  }
315
+ if (usage.goto) {
316
+ const name = usage.goto.name;
317
+ return name && index.sections.has(name) ? { kind: "section", name } : undefined;
318
+ }
319
+ if (usage.deactivate) {
320
+ const name = usage.deactivate.name;
321
+ const passages = passagesOf(index, usage.sectionNode);
322
+ return sectionName !== undefined && passages?.has(name) ? { kind: "passage", section: sectionName, name } : undefined;
323
+ }
307
324
  const link = usage.link;
308
325
  if (link.linkType == "section") {
309
326
  if (link.form == "next") {
@@ -336,12 +353,12 @@ export function createLanguageService(options) {
336
353
  return undefined;
337
354
  return { file: section.file, range: passage.nameRange };
338
355
  }
339
- // What's at a position: a link, an embed, or the name in a section or passage header.
356
+ // What's at a position: a link, an embed, a goto, or the name in a section or passage header.
340
357
  async function symbolAt(index, path, position) {
341
358
  for (const usage of index.usages) {
342
359
  if (usage.file != path)
343
360
  continue;
344
- const range = usage.link?.range ?? usage.embed.range;
361
+ const range = usageRange(usage);
345
362
  if (!contains(range, position))
346
363
  continue;
347
364
  const symbol = resolveUsage(index, usage);
@@ -375,6 +392,10 @@ export function createLanguageService(options) {
375
392
  function nameRangeInLink(index, usage, name) {
376
393
  if (usage.embed)
377
394
  return usage.embed.nameRange;
395
+ if (usage.goto)
396
+ return usage.goto.nameRange;
397
+ if (usage.deactivate)
398
+ return usage.deactivate.nameRange;
378
399
  const link = usage.link;
379
400
  if (link.form == "next")
380
401
  return undefined;
@@ -398,7 +419,7 @@ export function createLanguageService(options) {
398
419
  for (const usage of index.usages) {
399
420
  const target = resolveUsage(index, usage);
400
421
  if (target && sameSymbol(target, symbol)) {
401
- result.push({ file: usage.file, range: usage.link?.range ?? usage.embed.range });
422
+ result.push({ file: usage.file, range: usageRange(usage) });
402
423
  }
403
424
  }
404
425
  return result;
@@ -572,6 +593,16 @@ export function createLanguageService(options) {
572
593
  if ((match = /\{\{~?\s*embed\s+["']([^"']*)$/.exec(prefix))) {
573
594
  return [...passageItems(match[1]), ...sectionItems(match[1])];
574
595
  }
596
+ // {{seen "name"}}, (visits "name") etc., which take a section or passage (#377)
597
+ if ((match = /(?:\{\{~?|\()\s*(?:seen|visits)\s+["']([^"']*)$/.exec(prefix))) {
598
+ return [...passageItems(match[1]), ...sectionItems(match[1])];
599
+ }
600
+ if ((match = /\{\{~?\s*goto\s+["']([^"']*)$/.exec(prefix))) {
601
+ return sectionItems(match[1]);
602
+ }
603
+ if ((match = /\{\{~?\s*deactivate\s+["']([^"']*)$/.exec(prefix))) {
604
+ return passageItems(match[1]);
605
+ }
575
606
  if ((match = /\[\[[^\]]*\]\]\(([^),]*)$/.exec(prefix))) {
576
607
  return sectionItems(match[1]);
577
608
  }
package/dist/node.d.ts CHANGED
@@ -1,14 +1,21 @@
1
+ import { type PageStrings, type Panel } from "./project.js";
1
2
  export interface StoryOnDisk {
2
3
  mainFile: string;
3
4
  storyFiles?: string[];
4
5
  projectFile?: string;
5
6
  note?: string;
6
7
  expressions: boolean;
8
+ backButton?: boolean;
9
+ strings?: PageStrings;
10
+ saveButton?: boolean;
11
+ projectId?: string;
12
+ panels?: Panel[];
7
13
  }
8
14
  export declare class StoryNotFoundError extends Error {
9
15
  }
10
16
  export interface FindStoryOptions {
11
17
  skip?: string[];
12
18
  }
13
- export declare function listSquiffyFiles(folder: string): Promise<string[]>;
19
+ export declare const listSquiffyFiles: (folder: string) => Promise<string[]>;
20
+ export declare const listStoryFiles: (folder: string) => Promise<string[]>;
14
21
  export declare function findStory(input: string, options?: FindStoryOptions): Promise<StoryOnDisk>;
package/dist/node.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // rest of the compiler stays free of Node dependencies.
5
5
  import fs from "fs/promises";
6
6
  import path from "path";
7
- import { getStoryFiles, isAlwaysSkipped, parseProjectFile, PROJECT_FILENAME } from "./project.js";
7
+ import { getStoryFiles, isAlwaysSkipped, isSquiffyPath, isStoryFilePath, parseProjectFile, PROJECT_FILENAME, storyFileList, } from "./project.js";
8
8
  // A problem finding the story, with a message to show the author as is
9
9
  export class StoryNotFoundError extends Error {
10
10
  }
@@ -37,7 +37,11 @@ async function findProjectFile(folder) {
37
37
  }
38
38
  // Every .squiffy file in a folder and its subfolders, relative to it with "/" separators, without
39
39
  // looking inside the folders that are never part of a story.
40
- export async function listSquiffyFiles(folder) {
40
+ export const listSquiffyFiles = (folder) => listFiles(folder, isSquiffyPath);
41
+ // Every .squiffy, .css and .js file in a folder and its subfolders, as listSquiffyFiles, and any
42
+ // index.html, which getStoryFiles needs to see to leave out an old build
43
+ export const listStoryFiles = (folder) => listFiles(folder, name => isStoryFilePath(name) || name == "index.html");
44
+ async function listFiles(folder, include) {
41
45
  const result = [];
42
46
  const walk = async (relative) => {
43
47
  const entries = await fs.readdir(path.join(folder, relative), { withFileTypes: true });
@@ -47,7 +51,7 @@ export async function listSquiffyFiles(folder) {
47
51
  if (!isAlwaysSkipped(`${child}/x`))
48
52
  await walk(child);
49
53
  }
50
- else if (entry.name.endsWith(".squiffy")) {
54
+ else if (include(entry.name)) {
51
55
  result.push(child);
52
56
  }
53
57
  }
@@ -69,8 +73,18 @@ async function folderStory(projectFile, options) {
69
73
  if (!await exists(mainFile)) {
70
74
  throw new StoryNotFoundError(`The main file in ${projectFile}, ${project.main}, doesn't exist.`);
71
75
  }
72
- const story = getStoryFiles(project, await listSquiffyFiles(root), options.skip);
73
- return { mainFile, storyFiles: story.included.map(file => path.resolve(root, file)), projectFile, expressions: true };
76
+ // Absolute paths to skip are made relative to the project, and any outside it are ignored
77
+ const skip = (options.skip ?? []).map(file => path.isAbsolute(file) ? path.relative(root, file).split(path.sep).join("/") : file)
78
+ .filter(file => file && !file.startsWith("..") && !path.isAbsolute(file));
79
+ const story = getStoryFiles(project, await listStoryFiles(root), skip);
80
+ return {
81
+ mainFile, storyFiles: storyFileList(story).map(file => path.resolve(root, file)), projectFile, expressions: true,
82
+ ...(project.backButton !== undefined ? { backButton: project.backButton } : {}),
83
+ ...(project.strings !== undefined ? { strings: project.strings } : {}),
84
+ ...(project.saveButton !== undefined ? { saveButton: project.saveButton } : {}),
85
+ ...(project.id !== undefined ? { projectId: project.id } : {}),
86
+ ...(project.panels !== undefined ? { panels: project.panels } : {}),
87
+ };
74
88
  }
75
89
  // Finds the story to build from what the author gave: a folder with a squiffy.json in it, or a
76
90
  // .squiffy file.
package/dist/parse.js CHANGED
@@ -123,6 +123,7 @@ export function parse(text, filename) {
123
123
  body: [],
124
124
  links: [],
125
125
  embeds: [],
126
+ gotos: [], deactivates: [],
126
127
  };
127
128
  section.passages.push(passage);
128
129
  textStarted = false;
@@ -158,6 +159,9 @@ export function parse(text, filename) {
158
159
  haveSection = true;
159
160
  add({ type: "clear", range });
160
161
  }
162
+ else if (stripLine == "@repeat") {
163
+ add({ type: "repeat", range });
164
+ }
161
165
  else if (stripLine == "@end") {
162
166
  if (!passage)
163
167
  haveSection = true;
@@ -232,9 +236,9 @@ export function parse(text, filename) {
232
236
  return file;
233
237
  }
234
238
  function newSection(kind, range) {
235
- return { type: "section", kind, range, body: [], passages: [], links: [], embeds: [] };
239
+ return { type: "section", kind, range, body: [], passages: [], links: [], embeds: [], gotos: [], deactivates: [] };
236
240
  }
237
- // Fills in the links and embeds in a section's or passage's text.
241
+ // Fills in the links, embeds and gotos in a section's or passage's text.
238
242
  function findLinks(node, lines) {
239
243
  const textNodes = node.body.filter((n) => n.type == "text");
240
244
  if (!textNodes.length)
@@ -262,4 +266,16 @@ function findLinks(node, lines) {
262
266
  range: toRange(embed.start, embed.end),
263
267
  nameRange: toRange(embed.nameStart, embed.nameEnd),
264
268
  }));
269
+ node.gotos = result.gotos.map((goto) => ({
270
+ type: "goto",
271
+ name: goto.name,
272
+ range: toRange(goto.start, goto.end),
273
+ nameRange: toRange(goto.nameStart, goto.nameEnd),
274
+ }));
275
+ node.deactivates = result.deactivates.map((deactivate) => ({
276
+ type: "deactivate",
277
+ name: deactivate.name,
278
+ range: toRange(deactivate.start, deactivate.end),
279
+ nameRange: toRange(deactivate.nameStart, deactivate.nameEnd),
280
+ }));
265
281
  }
package/dist/project.d.ts CHANGED
@@ -3,10 +3,55 @@ export declare const PROJECT_FILE_VERSION = 1;
3
3
  export declare const PROJECT_SCHEMA_URL = "https://squiffystory.com/schema/squiffy.json";
4
4
  export interface ProjectFile {
5
5
  version: number;
6
+ id?: string;
6
7
  main: string;
7
8
  exclude: string[];
8
9
  map?: MapPositions;
10
+ backButton?: boolean;
11
+ saveButton?: boolean;
12
+ strings?: PageStrings;
13
+ panels?: Panel[];
9
14
  }
15
+ export declare const PANEL_ICONS: readonly ["bag", "person", "map", "help", "info", "list", "book", "star", "heart"];
16
+ export type PanelIcon = typeof PANEL_ICONS[number];
17
+ export interface Panel {
18
+ passage: string;
19
+ label: string;
20
+ position?: "side" | "button";
21
+ icon?: PanelIcon;
22
+ }
23
+ export type PageStringName = keyof typeof PAGE_STRINGS;
24
+ export type PageStrings = Partial<Record<PageStringName, string>>;
25
+ export declare const PAGE_STRINGS: {
26
+ back: string;
27
+ restart: string;
28
+ restartConfirm: string;
29
+ switchToDark: string;
30
+ switchToLight: string;
31
+ saves: string;
32
+ saveName: string;
33
+ save: string;
34
+ noSaves: string;
35
+ savedGame: string;
36
+ savedToday: string;
37
+ savedYesterday: string;
38
+ load: string;
39
+ loadConfirm: string;
40
+ saveOptions: string;
41
+ overwrite: string;
42
+ overwriteConfirm: string;
43
+ rename: string;
44
+ newName: string;
45
+ saveToFile: string;
46
+ loadFromFile: string;
47
+ delete: string;
48
+ deleteConfirm: string;
49
+ cancel: string;
50
+ close: string;
51
+ wrongStory: string;
52
+ notASave: string;
53
+ cantSave: string;
54
+ };
10
55
  export interface MapPositions {
11
56
  sections: Record<string, [number, number]>;
12
57
  passages: Record<string, Record<string, [number, number]>>;
@@ -22,16 +67,27 @@ export declare function parseProjectFile(text: string): ParsedProjectFile;
22
67
  export declare function globToRegExp(pattern: string): RegExp;
23
68
  export declare function isExcluded(path: string, exclude: string[]): boolean;
24
69
  export declare function isAlwaysSkipped(path: string): boolean;
70
+ export declare const BUILD_FOLDER = "build";
71
+ export declare const isSquiffyPath: (path: string) => boolean;
72
+ export declare const isStylesheetPath: (path: string) => boolean;
73
+ export declare const isScriptPath: (path: string) => boolean;
74
+ export declare const isStoryFilePath: (path: string) => boolean;
25
75
  export interface StoryFiles {
26
76
  main: string;
27
77
  included: string[];
78
+ stylesheets: string[];
79
+ scripts: string[];
28
80
  excluded: string[];
29
81
  }
30
82
  export declare const comparePaths: (a: string, b: string) => 1 | 0 | -1;
31
83
  export declare function getStoryFiles(project: ProjectFile, paths: Iterable<string>, skip?: string[]): StoryFiles;
84
+ export declare const storyFileList: (story: StoryFiles) => string[];
32
85
  export declare function formatProjectFile(project: {
33
86
  main: string;
34
87
  exclude?: string[];
88
+ map?: MapPositions;
89
+ id?: string;
90
+ panels?: Panel[];
35
91
  }): string;
36
92
  export declare function updateProjectFile(text: string, changes: {
37
93
  main?: string;