squiffy-compiler 7.0.0-beta.1 → 7.0.0-beta.11

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 (61) hide show
  1. package/README.md +10 -2
  2. package/dist/analyse.d.ts +20 -1
  3. package/dist/analyse.js +457 -26
  4. package/dist/compiler.d.ts +20 -0
  5. package/dist/compiler.js +9 -1
  6. package/dist/css-urls.d.ts +4 -0
  7. package/dist/css-urls.js +59 -0
  8. package/dist/emit.d.ts +28 -0
  9. package/dist/emit.js +79 -1
  10. package/dist/helpers.d.ts +1 -0
  11. package/dist/helpers.js +14 -0
  12. package/dist/ignore.d.ts +8 -0
  13. package/dist/ignore.js +71 -0
  14. package/dist/infix-expressions.d.ts +19 -0
  15. package/dist/infix-expressions.js +713 -0
  16. package/dist/language-service.d.ts +14 -1
  17. package/dist/language-service.js +266 -52
  18. package/dist/node.d.ts +23 -0
  19. package/dist/node.js +122 -0
  20. package/dist/parse.d.ts +5 -0
  21. package/dist/parse.js +62 -4
  22. package/dist/project.d.ts +129 -0
  23. package/dist/project.js +488 -0
  24. package/dist/quest/aslx.d.ts +51 -0
  25. package/dist/quest/aslx.js +184 -0
  26. package/dist/quest/convert.d.ts +20 -0
  27. package/dist/quest/convert.js +552 -0
  28. package/dist/quest/script.d.ts +92 -0
  29. package/dist/quest/script.js +453 -0
  30. package/dist/quest/scripts.d.ts +24 -0
  31. package/dist/quest/scripts.js +506 -0
  32. package/dist/quest/text.d.ts +18 -0
  33. package/dist/quest/text.js +323 -0
  34. package/dist/section-labels.d.ts +4 -0
  35. package/dist/section-labels.js +64 -0
  36. package/dist/setters.d.ts +49 -0
  37. package/dist/setters.js +477 -0
  38. package/dist/story-graph.d.ts +71 -0
  39. package/dist/story-graph.js +445 -0
  40. package/dist/syntax.d.ts +56 -4
  41. package/dist/templates.d.ts +17 -0
  42. package/dist/templates.js +180 -0
  43. package/dist/text.d.ts +9 -2
  44. package/dist/text.js +99 -39
  45. package/dist/twine/audio.d.ts +21 -0
  46. package/dist/twine/audio.js +80 -0
  47. package/dist/twine/convert.d.ts +131 -0
  48. package/dist/twine/convert.js +1057 -0
  49. package/dist/twine/expression.d.ts +88 -0
  50. package/dist/twine/expression.js +318 -0
  51. package/dist/twine/harlowe.d.ts +27 -0
  52. package/dist/twine/harlowe.js +2341 -0
  53. package/dist/twine/settings.d.ts +9 -0
  54. package/dist/twine/settings.js +322 -0
  55. package/dist/twine/story.d.ts +24 -0
  56. package/dist/twine/story.js +231 -0
  57. package/dist/twine/sugarcube.d.ts +40 -0
  58. package/dist/twine/sugarcube.js +2172 -0
  59. package/dist/v5.js +2 -1
  60. package/package.json +23 -5
  61. package/syntaxes/squiffy.tmLanguage.json +1003 -0
@@ -1,6 +1,9 @@
1
1
  import { Analysis } from "./analyse.js";
2
2
  import type { Diagnostic, Position, Range } from "./syntax.js";
3
+ import { ProjectFile } from "./project.js";
4
+ import { StoryGraph } from "./story-graph.js";
3
5
  export type { Diagnostic, Position, Range } from "./syntax.js";
6
+ export type { GraphEdge, GraphEdgeKind, GraphNode, StoryGraph } from "./story-graph.js";
4
7
  export interface ProjectFiles {
5
8
  list(): Promise<{
6
9
  path: string;
@@ -11,6 +14,13 @@ export interface LanguageServiceOptions {
11
14
  files: ProjectFiles;
12
15
  mainFile: string;
13
16
  }
17
+ export interface ProjectInfo {
18
+ projectFile?: ProjectFile;
19
+ error?: string;
20
+ mainFile: string;
21
+ storyFiles: string[];
22
+ excludedFiles: string[];
23
+ }
14
24
  export interface TextEdit {
15
25
  range: Range;
16
26
  newText: string;
@@ -30,7 +40,7 @@ export interface DocumentSymbol {
30
40
  }
31
41
  export interface CompletionItem {
32
42
  label: string;
33
- kind: "section" | "passage" | "attribute" | "snippet";
43
+ kind: "section" | "passage" | "attribute" | "snippet" | "directive";
34
44
  insertText?: string;
35
45
  detail?: string;
36
46
  range: Range;
@@ -62,8 +72,10 @@ export interface LanguageService {
62
72
  updateFile(path: string, text: string | undefined): void;
63
73
  fileChanged(path: string): void;
64
74
  setMainFile(path: string): void;
75
+ getProjectInfo(): Promise<ProjectInfo>;
65
76
  getAnalysis(): Promise<Analysis>;
66
77
  getDiagnostics(path: string): Promise<Diagnostic[]>;
78
+ getAllDiagnostics(): Promise<Diagnostic[]>;
67
79
  getDocumentSymbols(path: string): Promise<DocumentSymbol[]>;
68
80
  getDefinition(path: string, position: Position): Promise<Location | undefined>;
69
81
  getReferences(path: string, position: Position, includeDeclaration?: boolean): Promise<Location[]>;
@@ -73,5 +85,6 @@ export interface LanguageService {
73
85
  getFoldingRanges(path: string): Promise<FoldingRange[]>;
74
86
  getCodeActions(path: string, range: Range): Promise<CodeAction[]>;
75
87
  getSectionAt(path: string, position: Position): Promise<SectionAt | undefined>;
88
+ getStoryGraph(): Promise<StoryGraph>;
76
89
  }
77
90
  export declare function createLanguageService(options: LanguageServiceOptions): LanguageService;
@@ -1,12 +1,40 @@
1
1
  // The Squiffy language service: outline, diagnostics, go to definition, references, rename,
2
- // completion, hover, folding, quick fixes and "which section is this", for a multi-file project.
2
+ // completion, hover, folding, quick fixes, "which section is this" and the story graph, for a
3
+ // multi-file project.
3
4
  // It has no UI or DOM dependencies, so the web editor, the desktop app (from a Web Worker) and an
4
5
  // LSP adapter for VS Code can all call it directly.
5
6
  //
6
7
  // Positions and ranges are zero-based { line, character }, following LSP conventions.
7
8
  import { analyse, ParseCache } from "./analyse.js";
9
+ import { getStoryFiles, globToRegExp, parseProjectFile, PROJECT_FILENAME, storyFileList } from "./project.js";
8
10
  import { convertV5Syntax, findV5Syntax } from "./v5.js";
11
+ import { findUnquotedText, splitWithOffsets } from "./setters.js";
12
+ import { ignoredDiagnostics } from "./ignore.js";
13
+ import { buildStoryGraph, firstScreenSoundDiagnostics, storyGraphDiagnostics } from "./story-graph.js";
9
14
  const sameSymbol = (a, b) => a.kind == b.kind && a.name == b.name && (a.kind == "section" || a.section == b.section);
15
+ const usageRange = (usage) => (usage.link ?? usage.embed ?? usage.goto ?? usage.deactivate).range;
16
+ // Directives, for completion, with what they do
17
+ const DIRECTIVES = [
18
+ ["title", "Sets the story's title"],
19
+ ["start", "Sets the section the story starts at"],
20
+ ["import", "Adds another file to the story"],
21
+ ["set", "Sets an attribute"],
22
+ ["unset", "Sets an attribute to false"],
23
+ ["inc", "Adds to an attribute"],
24
+ ["dec", "Subtracts from an attribute"],
25
+ ["clear", "Clears the screen"],
26
+ ["repeat", "Lets the player click this passage's links again"],
27
+ ["end", "Marks this section as an ending"],
28
+ ["music", "Plays music until it's changed, or stops it with @music stop"],
29
+ ["sound", "Plays a sound once, or stops the sounds playing with @sound stop"],
30
+ ["class", "Puts classes on the story while this section is shown, for its stylesheet"],
31
+ ["tag", "Tags this section or passage, so the story can list them with (passages tagged=\"...\")"],
32
+ ["transition", "How this section or passage appears, such as @transition fade 1s"],
33
+ ["leave", "How the old text goes when this clears the screen, such as @leave fade 1s"],
34
+ ["ui", "JavaScript for the story's user interface"],
35
+ ];
36
+ // The warnings with a quick fix that adds a squiffy-ignore comment
37
+ const IGNORE_ACTION_CODES = new Set(["squiffy/unknown-name", "squiffy/sound-on-first-screen", "squiffy/unreachable-section"]);
10
38
  const contains = (range, pos) => comparePositions(range.start, pos) <= 0 && comparePositions(pos, range.end) <= 0;
11
39
  function comparePositions(a, b) {
12
40
  return a.line - b.line || a.character - b.character;
@@ -22,8 +50,9 @@ function resolveName(target, has) {
22
50
  }
23
51
  // The name a broken link was trying to reach
24
52
  const intendedName = (target) => target.trim().split(",")[0].trim();
53
+ // The attribute a setter sets, e.g. gold in gold += 1, or hero.hp in hero.hp = 10 (#442)
25
54
  function attributeName(expression) {
26
- return expression.replace(/^\s*not\s+/, "").split(/[-+]?=/)[0].trim();
55
+ return /^\s*(?:not\s+)?(\w+(?:\.\w+)*)/.exec(expression)?.[1] ?? "";
27
56
  }
28
57
  function resolvePath(baseDir, relative) {
29
58
  const parts = baseDir ? baseDir.split("/") : [];
@@ -50,35 +79,6 @@ function relativePath(fromDir, path) {
50
79
  common++;
51
80
  return [...from.slice(common).map(() => ".."), ...to.slice(common)].join("/");
52
81
  }
53
- // "*" and "?" match within one path segment; "**" matches across segments.
54
- function globToRegExp(pattern) {
55
- let out = "";
56
- for (let i = 0; i < pattern.length; i++) {
57
- const c = pattern[i];
58
- if (c == "*") {
59
- if (pattern[i + 1] == "*") {
60
- i++;
61
- if (pattern[i + 1] == "/") {
62
- i++;
63
- out += "(?:.*/)?";
64
- }
65
- else {
66
- out += ".*";
67
- }
68
- }
69
- else {
70
- out += "[^/]*";
71
- }
72
- }
73
- else if (c == "?") {
74
- out += "[^/]";
75
- }
76
- else {
77
- out += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
78
- }
79
- }
80
- return new RegExp(`^${out}$`);
81
- }
82
82
  const endOfText = (text) => {
83
83
  const lines = text.split("\n");
84
84
  return { line: lines.length - 1, character: lines[lines.length - 1].length };
@@ -111,19 +111,17 @@ export function createLanguageService(options) {
111
111
  }
112
112
  // The compiler's ExternalFiles, resolving @import patterns and @ui paths against the main
113
113
  // file's folder and never importing a file twice, as the CLI does.
114
- function externalFiles(texts) {
114
+ function externalFiles(texts, mainFile, storyFiles) {
115
115
  const baseDir = dirname(mainFile);
116
116
  const included = new Set([mainFile]);
117
- const matched = new Set();
117
+ const matched = new Set(storyFiles);
118
118
  return {
119
119
  async getMatchingFilenames(pattern) {
120
120
  const resolved = resolvePath(baseDir, pattern);
121
121
  if (resolved === null)
122
122
  return [];
123
123
  const regex = globToRegExp(resolved);
124
- const paths = new Set((await files.list()).map(f => f.path));
125
- for (const open of openFiles.keys())
126
- paths.add(open);
124
+ const paths = await listPaths();
127
125
  const result = [...paths].filter(p => regex.test(p) && !included.has(p)).sort();
128
126
  for (const p of result)
129
127
  matched.add(p);
@@ -146,8 +144,35 @@ export function createLanguageService(options) {
146
144
  getLocalFilename: (filename) => relativePath(baseDir, filename),
147
145
  };
148
146
  }
147
+ async function listPaths() {
148
+ const paths = new Set((await files.list()).map(f => f.path));
149
+ for (const open of openFiles.keys())
150
+ paths.add(open);
151
+ return paths;
152
+ }
153
+ async function getProject() {
154
+ const fallback = { mainFile, storyFiles: [], excludedFiles: [] };
155
+ const paths = await listPaths();
156
+ if (!paths.has(PROJECT_FILENAME))
157
+ return fallback;
158
+ let text;
159
+ try {
160
+ text = await readFile(PROJECT_FILENAME);
161
+ }
162
+ catch {
163
+ return fallback;
164
+ }
165
+ const parsed = parseProjectFile(text);
166
+ if (!parsed.success)
167
+ return { ...fallback, error: parsed.error };
168
+ const project = parsed.project;
169
+ const story = getStoryFiles(project, paths);
170
+ return { projectFile: project, mainFile: project.main, storyFiles: storyFileList(story), excludedFiles: story.excluded };
171
+ }
149
172
  async function buildIndex() {
150
173
  const texts = new Map();
174
+ const project = await getProject();
175
+ const mainFile = project.mainFile;
151
176
  let script = "";
152
177
  try {
153
178
  script = await readFile(mainFile);
@@ -159,12 +184,26 @@ export function createLanguageService(options) {
159
184
  const analysis = await analyse({
160
185
  script,
161
186
  scriptBaseFilename: mainFile,
162
- externalFiles: externalFiles(texts),
187
+ externalFiles: externalFiles(texts, mainFile, project.storyFiles),
163
188
  parseCache,
164
189
  recover: true,
190
+ ...(project.projectFile ? { storyFiles: project.storyFiles } : {}),
191
+ expressions: !!project.projectFile,
165
192
  });
193
+ if (project.error) {
194
+ // A broken squiffy.json stops the story building, as it does in the CLI
195
+ analysis.success = false;
196
+ analysis.diagnostics.unshift({
197
+ file: PROJECT_FILENAME,
198
+ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } },
199
+ severity: "error",
200
+ code: "squiffy/project-file",
201
+ message: project.error,
202
+ });
203
+ }
166
204
  const index = {
167
205
  analysis,
206
+ project,
168
207
  files: new Map(),
169
208
  texts,
170
209
  sectionNames: analysis.sections.map(s => s.name),
@@ -188,6 +227,14 @@ export function createLanguageService(options) {
188
227
  if (section.node)
189
228
  index.nodeNames.set(section.node, section.name);
190
229
  }
230
+ // An attribute, and for a value inside an object, the object too: hero.hp adds hero
231
+ const addAttribute = (name) => {
232
+ const parts = name.split(".");
233
+ for (let i = 1; i <= parts.length; i++) {
234
+ if (parts[i - 1])
235
+ index.attributes.add(parts.slice(0, i).join("."));
236
+ }
237
+ };
191
238
  for (const [path, file] of index.files) {
192
239
  for (const node of [file.preamble, ...file.sections]) {
193
240
  if (node.type == "snippet") {
@@ -197,21 +244,24 @@ export function createLanguageService(options) {
197
244
  for (const container of [node, ...node.passages]) {
198
245
  for (const link of container.links) {
199
246
  index.usages.push({ file: path, container, sectionNode: node, link });
200
- const setters = link.target.split(",").slice(1);
247
+ const comma = link.target.indexOf(",");
248
+ const setters = comma == -1 ? [] : splitWithOffsets(link.target.substring(comma + 1)).map(part => part.text);
201
249
  for (const setter of setters) {
202
- const name = attributeName(setter);
203
- if (name)
204
- index.attributes.add(name);
250
+ addAttribute(attributeName(setter));
205
251
  }
206
252
  }
207
253
  for (const embed of container.embeds) {
208
254
  index.usages.push({ file: path, container, sectionNode: node, embed });
209
255
  }
256
+ for (const goto of container.gotos) {
257
+ index.usages.push({ file: path, container, sectionNode: node, goto });
258
+ }
259
+ for (const deactivate of container.deactivates) {
260
+ index.usages.push({ file: path, container, sectionNode: node, deactivate });
261
+ }
210
262
  for (const statement of container.body) {
211
263
  if (statement.type == "attribute") {
212
- const name = attributeName(statement.value);
213
- if (name)
214
- index.attributes.add(name);
264
+ addAttribute(attributeName(statement.value));
215
265
  }
216
266
  else if (statement.type == "js") {
217
267
  for (const match of statement.code.matchAll(/\bset\(\s*["']([^"']+)["']/g)) {
@@ -243,6 +293,27 @@ export function createLanguageService(options) {
243
293
  return undefined;
244
294
  }
245
295
  }
296
+ function getGraph(index) {
297
+ if (!index.graph) {
298
+ const source = {
299
+ files: index.files,
300
+ sections: index.sections,
301
+ nodeNames: index.nodeNames,
302
+ usages: index.usages,
303
+ start: index.analysis.start,
304
+ resolve: (usage) => resolveUsage(index, usage),
305
+ };
306
+ const graph = buildStoryGraph(source);
307
+ const diagnostics = [...storyGraphDiagnostics(graph), ...firstScreenSoundDiagnostics(source)];
308
+ const ignored = ignoredDiagnostics(index.analysis.files, diagnostics);
309
+ index.graph = { graph, diagnostics: diagnostics.filter(d => !ignored.has(d)) };
310
+ }
311
+ return index.graph;
312
+ }
313
+ // The analysis's diagnostics, and the story graph's
314
+ function allDiagnostics(index) {
315
+ return [...index.analysis.diagnostics, ...getGraph(index).diagnostics];
316
+ }
246
317
  // The passages a passage link or embed in this section can reach
247
318
  function passagesOf(index, sectionNode) {
248
319
  const name = index.nodeNames.get(sectionNode);
@@ -257,8 +328,20 @@ export function createLanguageService(options) {
257
328
  return { kind: "passage", section: sectionName, name };
258
329
  if (index.sections.has(name))
259
330
  return { kind: "section", name };
331
+ // Like the runtime, the master section's passages can be embedded from any section
332
+ if (index.sections.get("")?.passages.has(name))
333
+ return { kind: "passage", section: "", name };
260
334
  return undefined;
261
335
  }
336
+ if (usage.goto) {
337
+ const name = usage.goto.name;
338
+ return name && index.sections.has(name) ? { kind: "section", name } : undefined;
339
+ }
340
+ if (usage.deactivate) {
341
+ const name = usage.deactivate.name;
342
+ const passages = passagesOf(index, usage.sectionNode);
343
+ return sectionName !== undefined && passages?.has(name) ? { kind: "passage", section: sectionName, name } : undefined;
344
+ }
262
345
  const link = usage.link;
263
346
  if (link.linkType == "section") {
264
347
  if (link.form == "next") {
@@ -274,7 +357,12 @@ export function createLanguageService(options) {
274
357
  if (sectionName === undefined || !passages)
275
358
  return undefined;
276
359
  const name = resolveName(link.target, n => passages.has(n));
277
- return name === undefined ? undefined : { kind: "passage", section: sectionName, name };
360
+ if (name !== undefined)
361
+ return { kind: "passage", section: sectionName, name };
362
+ // Like the runtime, a passage link can go to one of the master section's passages
363
+ const masterPassages = index.sections.get("")?.passages;
364
+ const masterName = masterPassages && resolveName(link.target, n => masterPassages.has(n));
365
+ return masterName === undefined ? undefined : { kind: "passage", section: "", name: masterName };
278
366
  }
279
367
  // Where a symbol is defined: the name in its header.
280
368
  function definitionOf(index, symbol) {
@@ -291,12 +379,12 @@ export function createLanguageService(options) {
291
379
  return undefined;
292
380
  return { file: section.file, range: passage.nameRange };
293
381
  }
294
- // What's at a position: a link, an embed, or the name in a section or passage header.
382
+ // What's at a position: a link, an embed, a goto, or the name in a section or passage header.
295
383
  async function symbolAt(index, path, position) {
296
384
  for (const usage of index.usages) {
297
385
  if (usage.file != path)
298
386
  continue;
299
- const range = usage.link?.range ?? usage.embed.range;
387
+ const range = usageRange(usage);
300
388
  if (!contains(range, position))
301
389
  continue;
302
390
  const symbol = resolveUsage(index, usage);
@@ -330,6 +418,10 @@ export function createLanguageService(options) {
330
418
  function nameRangeInLink(index, usage, name) {
331
419
  if (usage.embed)
332
420
  return usage.embed.nameRange;
421
+ if (usage.goto)
422
+ return usage.goto.nameRange;
423
+ if (usage.deactivate)
424
+ return usage.deactivate.nameRange;
333
425
  const link = usage.link;
334
426
  if (link.form == "next")
335
427
  return undefined;
@@ -353,7 +445,7 @@ export function createLanguageService(options) {
353
445
  for (const usage of index.usages) {
354
446
  const target = resolveUsage(index, usage);
355
447
  if (target && sameSymbol(target, symbol)) {
356
- result.push({ file: usage.file, range: usage.link?.range ?? usage.embed.range });
448
+ result.push({ file: usage.file, range: usageRange(usage) });
357
449
  }
358
450
  }
359
451
  return result;
@@ -377,6 +469,26 @@ export function createLanguageService(options) {
377
469
  }
378
470
  return { section: current, passage };
379
471
  }
472
+ // The master section, [[]]:, if the story has one
473
+ function masterSection(index) {
474
+ for (const [file, tree] of index.files) {
475
+ for (const node of tree.sections) {
476
+ if (node.type == "section" && node.header?.type == "section-header" && node.header.name == "")
477
+ return { file, node };
478
+ }
479
+ }
480
+ return undefined;
481
+ }
482
+ // Adds a squiffy-ignore comment to a section: before its text, as a line of text before
483
+ // @set and JavaScript would stop them being read as such, or after them if it has no text
484
+ function ignoreCommentEdit(section, lines, comment) {
485
+ const text = section.body.find(n => n.type == "text");
486
+ if (text)
487
+ return { range: lineRange(text.range.start.line, 0, 0), newText: `${comment}\n` };
488
+ const last = section.body[section.body.length - 1] ?? section.header;
489
+ const line = last.range.end.line;
490
+ return { range: lineRange(line, lines[line].length, lines[line].length), newText: `\n${comment}` };
491
+ }
380
492
  function firstLines(node, count) {
381
493
  return node.body.filter(n => n.type == "text").map(n => n.text).join("\n").trim().split("\n").slice(0, count).join("\n");
382
494
  }
@@ -396,12 +508,18 @@ export function createLanguageService(options) {
396
508
  mainFile = path;
397
509
  changed();
398
510
  },
511
+ async getProjectInfo() {
512
+ return (await getIndex()).project;
513
+ },
399
514
  async getAnalysis() {
400
515
  return (await getIndex()).analysis;
401
516
  },
402
517
  async getDiagnostics(path) {
403
518
  const index = await getIndex();
404
- return index.analysis.diagnostics.filter(d => d.file == path);
519
+ return allDiagnostics(index).filter(d => d.file == path);
520
+ },
521
+ async getAllDiagnostics() {
522
+ return allDiagnostics(await getIndex());
405
523
  },
406
524
  async getDocumentSymbols(path) {
407
525
  const index = await getIndex();
@@ -435,7 +553,7 @@ export function createLanguageService(options) {
435
553
  // Only a section if the story made it one (the main file's _default section)
436
554
  if (storyName === undefined)
437
555
  continue;
438
- symbols.push({ name: storyName, kind: "section", range: node.range, selectionRange: node.range, children: passageSymbols(node) });
556
+ symbols.push({ name: storyName, kind: "section", detail: "(Start)", range: node.range, selectionRange: node.range, children: passageSymbols(node) });
439
557
  continue;
440
558
  }
441
559
  const header = node.header;
@@ -521,9 +639,30 @@ export function createLanguageService(options) {
521
639
  .map(name => ({ label: name, kind: "passage", range: replace(typed) }));
522
640
  };
523
641
  let match;
524
- if ((match = /\{\{~?\s*embed\s+["']([^"']*)$/.exec(prefix))) {
642
+ if ((match = /\{\{~?\s*#?embed\s+["']([^"']*)$/.exec(prefix))) {
525
643
  return [...passageItems(match[1]), ...sectionItems(match[1])];
526
644
  }
645
+ // {{seen "name"}}, (visits "name") etc., which take a section or passage (#377)
646
+ if ((match = /(?:\{\{~?|\()\s*(?:seen|visits)\s+["']([^"']*)$/.exec(prefix))) {
647
+ return [...passageItems(match[1]), ...sectionItems(match[1])];
648
+ }
649
+ // (passages "section") and (tags "name") (#527)
650
+ if ((match = /(?:\{\{~?|\()\s*passages\s+["']([^"']*)$/.exec(prefix))) {
651
+ return sectionItems(match[1]);
652
+ }
653
+ if ((match = /(?:\{\{~?|\()\s*tags\s+["']([^"']*)$/.exec(prefix))) {
654
+ return [...passageItems(match[1]), ...sectionItems(match[1])];
655
+ }
656
+ if ((match = /\{\{~?\s*goto\s+["']([^"']*)$/.exec(prefix))) {
657
+ return sectionItems(match[1]);
658
+ }
659
+ if ((match = /\{\{~?\s*deactivate\s+["']([^"']*)$/.exec(prefix))) {
660
+ return passageItems(match[1]);
661
+ }
662
+ // A text box that goes somewhere when Enter is pressed (#454)
663
+ if ((match = /<input\b[^>]*\sdata-(section|passage)\s*=\s*["']([^"']*)$/i.exec(prefix))) {
664
+ return match[1].toLowerCase() == "section" ? sectionItems(match[2]) : passageItems(match[2]);
665
+ }
527
666
  if ((match = /\[\[[^\]]*\]\]\(([^),]*)$/.exec(prefix))) {
528
667
  return sectionItems(match[1]);
529
668
  }
@@ -536,6 +675,11 @@ export function createLanguageService(options) {
536
675
  if ((match = /(?<![![])\[([^[\]]*)$/.exec(prefix))) {
537
676
  return passageItems(match[1]);
538
677
  }
678
+ if ((match = /^\s*(@\w*)$/.exec(prefix))) {
679
+ return DIRECTIVES.map(([name, detail]) => ({
680
+ label: `@${name}`, kind: "directive", detail, range: replace(match[1]),
681
+ }));
682
+ }
539
683
  if ((match = /^\s*@(?:set|unset|inc|dec)\s+(?:not\s+)?([^\s=]*)$/.exec(prefix))) {
540
684
  return [...index.attributes].sort().map(name => ({ label: name, kind: "attribute", range: replace(match[1]) }));
541
685
  }
@@ -598,7 +742,7 @@ export function createLanguageService(options) {
598
742
  if (!tree)
599
743
  return [];
600
744
  const actions = [];
601
- const diagnostics = index.analysis.diagnostics.filter(d => d.file == path && overlaps(d.range, range));
745
+ const diagnostics = allDiagnostics(index).filter(d => d.file == path && overlaps(d.range, range));
602
746
  const v5 = findV5Syntax(tree.text);
603
747
  const lines = tree.text.replace(/\r/g, "").split("\n");
604
748
  for (const diagnostic of diagnostics) {
@@ -625,6 +769,23 @@ export function createLanguageService(options) {
625
769
  actions.push({ title: `Create passage '${name}'`, kind: "quickfix", diagnostic, edit });
626
770
  }
627
771
  }
772
+ else if (diagnostic.code == "squiffy/at-attribute") {
773
+ const start = diagnostic.range.start;
774
+ const name = lines[start.line].substring(start.character + 1, diagnostic.range.end.character);
775
+ const edit = {};
776
+ addEdit(edit, path, { range: { start, end: { line: start.line, character: start.character + 1 } }, newText: "" });
777
+ actions.push({ title: `Change to ${name}`, kind: "quickfix", diagnostic, edit });
778
+ }
779
+ else if (diagnostic.code == "squiffy/unquoted-text") {
780
+ const start = diagnostic.range.start;
781
+ const found = findUnquotedText(tree.file, () => false)
782
+ .find(u => comparePositions(u.range.start, start) == 0);
783
+ if (!found?.quoted)
784
+ continue;
785
+ const edit = {};
786
+ addEdit(edit, path, { range: found.range, newText: found.quoted });
787
+ actions.push({ title: `Change to ${found.quoted}`, kind: "quickfix", diagnostic, edit });
788
+ }
628
789
  else if (diagnostic.code == "squiffy/v5-syntax") {
629
790
  const line = diagnostic.range.start.line;
630
791
  const match = v5.find(m => m.line == line + 1
@@ -640,6 +801,56 @@ export function createLanguageService(options) {
640
801
  actions.push({ title: `Convert to ${match.suggestion}`, kind: "quickfix", diagnostic, edit });
641
802
  }
642
803
  }
804
+ for (const diagnostic of diagnostics) {
805
+ if (diagnostic.code != "squiffy/dead-end")
806
+ continue;
807
+ const { section } = containerAt(tree.file, diagnostic.range.start);
808
+ if (!section)
809
+ continue;
810
+ // A line after the header, or at the top of the file for the text before the first section
811
+ const line = section.header ? section.header.range.start.line + 1 : 0;
812
+ const edit = {};
813
+ addEdit(edit, path, line < lines.length
814
+ ? { range: lineRange(line, 0, 0), newText: "@end\n" }
815
+ : { range: lineRange(line - 1, lines[line - 1].length, lines[line - 1].length), newText: "\n@end" });
816
+ actions.push({ title: "Mark this section as an ending", kind: "quickfix", diagnostic, edit });
817
+ }
818
+ for (const diagnostic of diagnostics) {
819
+ if (diagnostic.code != "squiffy/redundant-import")
820
+ continue;
821
+ // Remove the whole line, including its line break
822
+ const line = diagnostic.range.start.line;
823
+ const end = line + 1 < lines.length ? { line: line + 1, character: 0 } : { line, character: lines[line].length };
824
+ const start = line + 1 < lines.length || line == 0 ? { line, character: 0 } : { line: line - 1, character: lines[line - 1].length };
825
+ const edit = {};
826
+ addEdit(edit, path, { range: { start, end }, newText: "" });
827
+ actions.push({ title: "Remove this @import", kind: "quickfix", diagnostic, edit });
828
+ }
829
+ // A warning that may be what the author meant can be turned off with a squiffy-ignore
830
+ // comment, in the section it's in, and an unknown name in the master section too,
831
+ // which turns it off everywhere. (Any warning can, but for the others there's a fix.)
832
+ for (const diagnostic of diagnostics) {
833
+ if (!IGNORE_ACTION_CODES.has(diagnostic.code))
834
+ continue;
835
+ const { section } = containerAt(tree.file, diagnostic.range.start);
836
+ const code = diagnostic.code.replace(/^squiffy\//, "");
837
+ const comment = `{{!-- squiffy-ignore ${code}${diagnostic.subject ? ` ${diagnostic.subject}` : ""} --}}`;
838
+ const what = diagnostic.code == "squiffy/unknown-name" ? `{{${diagnostic.subject}}}` : "this warning";
839
+ if (section?.header && !(section.header.type == "section-header" && section.header.name == "")) {
840
+ const edit = {};
841
+ addEdit(edit, path, ignoreCommentEdit(section, lines, comment));
842
+ actions.push({ title: `Ignore ${what} in this section`, kind: "quickfix", diagnostic, edit });
843
+ }
844
+ if (diagnostic.code == "squiffy/unknown-name") {
845
+ const master = masterSection(index);
846
+ const masterText = master && index.texts.get(master.file);
847
+ if (!master || masterText === undefined)
848
+ continue;
849
+ const edit = {};
850
+ addEdit(edit, master.file, ignoreCommentEdit(master.node, masterText.replace(/\r/g, "").split("\n"), comment));
851
+ actions.push({ title: `Ignore ${what} everywhere`, kind: "quickfix", diagnostic, edit });
852
+ }
853
+ }
643
854
  if (diagnostics.some(d => d.code == "squiffy/v5-syntax")) {
644
855
  const converted = convertV5Syntax(tree.text);
645
856
  if (converted.converted > 0) {
@@ -650,6 +861,9 @@ export function createLanguageService(options) {
650
861
  }
651
862
  return actions;
652
863
  },
864
+ async getStoryGraph() {
865
+ return getGraph(await getIndex()).graph;
866
+ },
653
867
  async getSectionAt(path, position) {
654
868
  const index = await getIndex();
655
869
  const tree = await getFile(index, path);
package/dist/node.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { type PageStrings, type Panel, type PlayerSetting } from "./project.js";
2
+ export interface StoryOnDisk {
3
+ mainFile: string;
4
+ storyFiles?: string[];
5
+ projectFile?: string;
6
+ note?: string;
7
+ expressions: boolean;
8
+ backButton?: boolean;
9
+ strings?: PageStrings;
10
+ saveButton?: boolean;
11
+ projectId?: string;
12
+ panels?: Panel[];
13
+ settings?: PlayerSetting[];
14
+ persistent?: string[];
15
+ }
16
+ export declare class StoryNotFoundError extends Error {
17
+ }
18
+ export interface FindStoryOptions {
19
+ skip?: string[];
20
+ }
21
+ export declare const listSquiffyFiles: (folder: string) => Promise<string[]>;
22
+ export declare const listStoryFiles: (folder: string) => Promise<string[]>;
23
+ export declare function findStory(input: string, options?: FindStoryOptions): Promise<StoryOnDisk>;