squiffy-compiler 6.0.1 → 7.0.0-beta.2

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.
package/dist/node.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ export interface StoryOnDisk {
2
+ mainFile: string;
3
+ storyFiles?: string[];
4
+ projectFile?: string;
5
+ note?: string;
6
+ }
7
+ export declare class StoryNotFoundError extends Error {
8
+ }
9
+ export interface FindStoryOptions {
10
+ skip?: string[];
11
+ }
12
+ export declare function listSquiffyFiles(folder: string): Promise<string[]>;
13
+ export declare function findStory(input: string, options?: FindStoryOptions): Promise<StoryOnDisk>;
package/dist/node.js ADDED
@@ -0,0 +1,105 @@
1
+ /// <reference types="node" />
2
+ // Finding a story on disk, for the CLI and the Vite plugin. This is the only part of the compiler
3
+ // that touches the file system, and it's a separate entry point (squiffy-compiler/node), so the
4
+ // rest of the compiler stays free of Node dependencies.
5
+ import fs from "fs/promises";
6
+ import path from "path";
7
+ import { getStoryFiles, isAlwaysSkipped, parseProjectFile, PROJECT_FILENAME } from "./project.js";
8
+ // A problem finding the story, with a message to show the author as is
9
+ export class StoryNotFoundError extends Error {
10
+ }
11
+ const exists = async (filename) => {
12
+ try {
13
+ await fs.access(filename);
14
+ return true;
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ };
20
+ const isDirectory = async (filename) => {
21
+ try {
22
+ return (await fs.stat(filename)).isDirectory();
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ };
28
+ // The nearest squiffy.json in a folder or the folders above it
29
+ async function findProjectFile(folder) {
30
+ for (let dir = path.resolve(folder);; dir = path.dirname(dir)) {
31
+ const candidate = path.join(dir, PROJECT_FILENAME);
32
+ if (await exists(candidate))
33
+ return candidate;
34
+ if (path.dirname(dir) == dir)
35
+ return undefined;
36
+ }
37
+ }
38
+ // Every .squiffy file in a folder and its subfolders, relative to it with "/" separators, without
39
+ // looking inside the folders that are never part of a story.
40
+ export async function listSquiffyFiles(folder) {
41
+ const result = [];
42
+ const walk = async (relative) => {
43
+ const entries = await fs.readdir(path.join(folder, relative), { withFileTypes: true });
44
+ for (const entry of entries) {
45
+ const child = relative ? `${relative}/${entry.name}` : entry.name;
46
+ if (entry.isDirectory()) {
47
+ if (!isAlwaysSkipped(`${child}/x`))
48
+ await walk(child);
49
+ }
50
+ else if (entry.name.endsWith(".squiffy")) {
51
+ result.push(child);
52
+ }
53
+ }
54
+ };
55
+ await walk("");
56
+ return result;
57
+ }
58
+ async function readProject(projectFile) {
59
+ const parsed = parseProjectFile(await fs.readFile(projectFile, "utf8"));
60
+ if (!parsed.success) {
61
+ throw new StoryNotFoundError(`${parsed.error} (${projectFile})`);
62
+ }
63
+ return parsed.project;
64
+ }
65
+ async function folderStory(projectFile, options) {
66
+ const root = path.dirname(projectFile);
67
+ const project = await readProject(projectFile);
68
+ const mainFile = path.resolve(root, project.main);
69
+ if (!await exists(mainFile)) {
70
+ throw new StoryNotFoundError(`The main file in ${projectFile}, ${project.main}, doesn't exist.`);
71
+ }
72
+ const story = getStoryFiles(project, await listSquiffyFiles(root), options.skip);
73
+ return { mainFile, storyFiles: story.included.map(file => path.resolve(root, file)), projectFile };
74
+ }
75
+ // Finds the story to build from what the author gave: a folder with a squiffy.json in it, or a
76
+ // .squiffy file.
77
+ //
78
+ // - A folder builds the project in its squiffy.json.
79
+ // - A project's main file (with a squiffy.json in its folder or above) builds the project.
80
+ // - Any other .squiffy file builds just that file and its @imports, as it would with no
81
+ // squiffy.json, with a note saying so. So several stories can share a folder.
82
+ export async function findStory(input, options = {}) {
83
+ const resolved = path.resolve(input);
84
+ if (await isDirectory(resolved)) {
85
+ const projectFile = path.join(resolved, PROJECT_FILENAME);
86
+ if (!await exists(projectFile)) {
87
+ throw new StoryNotFoundError(`There's no ${PROJECT_FILENAME} in ${resolved}. Give the story's .squiffy file instead, or add a ${PROJECT_FILENAME} to make the folder one story.`);
88
+ }
89
+ return folderStory(projectFile, options);
90
+ }
91
+ if (!await exists(resolved)) {
92
+ throw new StoryNotFoundError(`${input} doesn't exist.`);
93
+ }
94
+ const projectFile = await findProjectFile(path.dirname(resolved));
95
+ if (!projectFile)
96
+ return { mainFile: resolved };
97
+ const project = await readProject(projectFile);
98
+ if (path.resolve(path.dirname(projectFile), project.main) == resolved) {
99
+ return folderStory(projectFile, options);
100
+ }
101
+ return {
102
+ mainFile: resolved,
103
+ note: `Building just ${path.basename(resolved)}, as it isn't the main file in ${projectFile} (${project.main}).`,
104
+ };
105
+ }
@@ -0,0 +1,17 @@
1
+ import type { SquiffyFile } from "./syntax.js";
2
+ export declare const lineRegexes: {
3
+ section: RegExp;
4
+ snippet: RegExp;
5
+ passage: RegExp;
6
+ title: RegExp;
7
+ import: RegExp;
8
+ start: RegExp;
9
+ attributes: RegExp;
10
+ unset: RegExp;
11
+ inc: RegExp;
12
+ dec: RegExp;
13
+ js: RegExp;
14
+ continue: RegExp;
15
+ ui: RegExp;
16
+ };
17
+ export declare function parse(text: string, filename?: string): SquiffyFile;
package/dist/parse.js ADDED
@@ -0,0 +1,263 @@
1
+ import { positionMapper, transformText } from "./text.js";
2
+ export const lineRegexes = {
3
+ section: /^\[\[(.*)\]\]:$/,
4
+ snippet: /^\[snippet:\s*(.+)\]:$/,
5
+ passage: /^\[(.*)\]:$/,
6
+ title: /^@title (.*)$/,
7
+ import: /^@import (.*)$/,
8
+ start: /^@start (.*)$/,
9
+ attributes: /^@set (.*)$/,
10
+ unset: /^@unset (.*)$/,
11
+ inc: /^@inc (\S+)(?: (\d+))?$/,
12
+ dec: /^@dec (\S+)(?: (\d+))?$/,
13
+ js: /^(\t| {4})(.*)$/,
14
+ continue: /^\+\+\+(.*)$/,
15
+ ui: /^@ui (.*)$/,
16
+ };
17
+ // Parses one .squiffy file into a syntax tree. This never fails: problems such as a passage
18
+ // with no section are reported by analyse(), which knows how the file fits into the story.
19
+ //
20
+ // Each line is classified exactly as the compiler always has (see the if/else chain below,
21
+ // whose order matters). The tree is grouped as if this is the story's main file: in an imported
22
+ // file, content before the first section is ignored, and analyse() deals with that.
23
+ export function parse(text, filename) {
24
+ const lines = text.replace(/\r/g, "").split("\n");
25
+ const lineRange = (line) => ({
26
+ start: { line, character: 0 },
27
+ end: { line, character: lines[line].length },
28
+ });
29
+ // The range of a substring of a line, found by searching from the end, since every
30
+ // value this is used for runs to the end of the (trimmed) line.
31
+ const valueRange = (line, value) => {
32
+ const trimmedEnd = lines[line].trimEnd().length;
33
+ const start = Math.max(0, trimmedEnd - value.length);
34
+ return { start: { line, character: start }, end: { line, character: start + value.length } };
35
+ };
36
+ const nameRange = (line, name, prefix) => {
37
+ const lineText = lines[line];
38
+ const start = lineText.indexOf(name, lineText.indexOf(prefix) + prefix.length);
39
+ return { start: { line, character: start }, end: { line, character: start + name.length } };
40
+ };
41
+ const preamble = newSection("preamble", { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } });
42
+ const file = {
43
+ type: "file",
44
+ filename,
45
+ range: { start: { line: 0, character: 0 }, end: { line: lines.length - 1, character: lines[lines.length - 1].length } },
46
+ preamble,
47
+ sections: [],
48
+ };
49
+ let section = preamble;
50
+ let passage = null;
51
+ let snippet = null;
52
+ const snippetLines = [];
53
+ // Whether the compiler would have a current section at this point. In the main file, content
54
+ // before any section header creates the "_default" section.
55
+ let haveSection = false;
56
+ let textStarted = false;
57
+ let inUiBlock = false;
58
+ const endSnippet = () => {
59
+ if (snippet) {
60
+ snippet.content = snippetLines.join("\n");
61
+ snippetLines.length = 0;
62
+ snippet = null;
63
+ }
64
+ };
65
+ const startSection = (node) => {
66
+ endSnippet();
67
+ section = node;
68
+ passage = null;
69
+ file.sections.push(node);
70
+ };
71
+ const add = (node) => {
72
+ (passage ?? section).body.push(node);
73
+ };
74
+ for (let i = 0; i < lines.length; i++) {
75
+ const line = lines[i];
76
+ const stripLine = line.trim();
77
+ const range = lineRange(i);
78
+ const match = {};
79
+ for (const key of Object.keys(lineRegexes)) {
80
+ const result = lineRegexes[key].exec(key == "js" ? line : stripLine);
81
+ if (result) {
82
+ match[key] = result;
83
+ }
84
+ }
85
+ if (match.snippet) {
86
+ endSnippet();
87
+ const name = match.snippet[1];
88
+ snippet = {
89
+ type: "snippet",
90
+ name,
91
+ nameRange: nameRange(i, name, "snippet:"),
92
+ header: { type: "snippet-header", name, range },
93
+ range,
94
+ content: "",
95
+ };
96
+ file.sections.push(snippet);
97
+ passage = null;
98
+ haveSection = false;
99
+ textStarted = false;
100
+ }
101
+ else if (match.section) {
102
+ const name = match.section[1];
103
+ const node = newSection("named", range);
104
+ node.name = name;
105
+ node.nameRange = nameRange(i, name, "[[");
106
+ node.header = { type: "section-header", name, range };
107
+ startSection(node);
108
+ haveSection = true;
109
+ textStarted = false;
110
+ }
111
+ else if (snippet) {
112
+ snippetLines.push(line);
113
+ }
114
+ else if (match.passage) {
115
+ const name = match.passage[1];
116
+ const header = { type: "passage-header", name, range };
117
+ passage = {
118
+ type: "passage",
119
+ name,
120
+ nameRange: nameRange(i, name, "["),
121
+ header,
122
+ range,
123
+ body: [],
124
+ links: [],
125
+ embeds: [],
126
+ };
127
+ section.passages.push(passage);
128
+ textStarted = false;
129
+ }
130
+ else if (match.continue) {
131
+ const node = newSection("continue", range);
132
+ node.header = { type: "continue", text: match.continue[1], range };
133
+ startSection(node);
134
+ haveSection = true;
135
+ textStarted = false;
136
+ }
137
+ else if (stripLine == "---") {
138
+ inUiBlock = false;
139
+ if (!haveSection) {
140
+ add({ type: "separator", range });
141
+ }
142
+ else {
143
+ const node = newSection("separator", range);
144
+ node.header = { type: "separator", range };
145
+ startSection(node);
146
+ textStarted = false;
147
+ }
148
+ }
149
+ else if (stripLine == "@ui") {
150
+ inUiBlock = true;
151
+ add({ type: "ui-block-start", range });
152
+ }
153
+ else if (match.ui) {
154
+ add({ type: "ui-file", path: match.ui[1], pathRange: valueRange(i, match.ui[1]), range });
155
+ }
156
+ else if (stripLine == "@clear") {
157
+ if (!passage)
158
+ haveSection = true;
159
+ add({ type: "clear", range });
160
+ }
161
+ else if (stripLine == "@end") {
162
+ if (!passage)
163
+ haveSection = true;
164
+ add({ type: "end", range });
165
+ }
166
+ else if (match.title) {
167
+ add({ type: "title", value: match.title[1], valueRange: valueRange(i, match.title[1]), range });
168
+ }
169
+ else if (match.start) {
170
+ add({ type: "start", value: match.start[1], valueRange: valueRange(i, match.start[1]), range });
171
+ }
172
+ else if (match.import) {
173
+ add({ type: "import", pattern: match.import[1], patternRange: valueRange(i, match.import[1]), range });
174
+ }
175
+ else if (match.attributes || match.unset) {
176
+ haveSection = true;
177
+ const value = (match.attributes ?? match.unset)[1];
178
+ add({ type: "attribute", directive: match.attributes ? "set" : "unset", value, valueRange: valueRange(i, value), range });
179
+ }
180
+ else if (match.inc || match.dec) {
181
+ haveSection = true;
182
+ const m = (match.inc ?? match.dec);
183
+ const value = m[1];
184
+ const start = line.indexOf(value, line.indexOf("@") + 4);
185
+ add({
186
+ type: "attribute",
187
+ directive: match.inc ? "inc" : "dec",
188
+ value,
189
+ valueRange: { start: { line: i, character: start }, end: { line: i, character: start + value.length } },
190
+ ...(m[2] === undefined ? {} : { amount: m[2] }),
191
+ range,
192
+ });
193
+ }
194
+ else if (!textStarted && match.js) {
195
+ if (!inUiBlock && !passage)
196
+ haveSection = true;
197
+ const indent = match.js[1].length;
198
+ add({
199
+ type: "js",
200
+ code: match.js[2],
201
+ codeRange: { start: { line: i, character: indent }, end: { line: i, character: line.length } },
202
+ range,
203
+ });
204
+ }
205
+ else if (textStarted || stripLine.length > 0) {
206
+ add({ type: "text", text: line, range });
207
+ if (!inUiBlock) {
208
+ if (!passage)
209
+ haveSection = true;
210
+ textStarted = true;
211
+ }
212
+ }
213
+ // Otherwise it's a blank line before any text, which is ignored.
214
+ const end = range.end;
215
+ if (snippet)
216
+ snippet.range = { start: snippet.range.start, end };
217
+ else {
218
+ section.range = { start: section.range.start, end };
219
+ if (passage)
220
+ passage.range = { start: passage.range.start, end };
221
+ }
222
+ }
223
+ endSnippet();
224
+ for (const s of [preamble, ...file.sections]) {
225
+ if (s.type != "section")
226
+ continue;
227
+ findLinks(s, lines);
228
+ for (const p of s.passages) {
229
+ findLinks(p, lines);
230
+ }
231
+ }
232
+ return file;
233
+ }
234
+ function newSection(kind, range) {
235
+ return { type: "section", kind, range, body: [], passages: [], links: [], embeds: [] };
236
+ }
237
+ // Fills in the links and embeds in a section's or passage's text.
238
+ function findLinks(node, lines) {
239
+ const textNodes = node.body.filter((n) => n.type == "text");
240
+ if (!textNodes.length)
241
+ return;
242
+ const sources = textNodes.map(n => ({ line: n.range.start.line, length: lines[n.range.start.line].length }));
243
+ const toPosition = positionMapper(sources, textNodes.map(n => n.text.length));
244
+ const toRange = (start, end) => ({ start: toPosition(start), end: toPosition(end) });
245
+ // Which section comes next isn't known until the story is analysed, but all that matters
246
+ // here is that there is one, so that [[text>]] is treated as a link.
247
+ const result = transformText(textNodes.map(n => n.text).join("\n"), () => "");
248
+ node.links = result.links.map((link) => ({
249
+ type: "link",
250
+ linkType: link.linkType,
251
+ form: link.form,
252
+ ...(link.text === undefined ? {} : { text: link.text }),
253
+ target: link.target,
254
+ range: toRange(link.start, link.end),
255
+ targetRange: toRange(link.targetStart, link.targetEnd),
256
+ }));
257
+ node.embeds = result.embeds.map((embed) => ({
258
+ type: "embed",
259
+ name: embed.name,
260
+ range: toRange(embed.start, embed.end),
261
+ nameRange: toRange(embed.nameStart, embed.nameEnd),
262
+ }));
263
+ }
@@ -0,0 +1,40 @@
1
+ export declare const PROJECT_FILENAME = "squiffy.json";
2
+ export declare const PROJECT_FILE_VERSION = 1;
3
+ export declare const PROJECT_SCHEMA_URL = "https://squiffystory.com/schema/squiffy.json";
4
+ export interface ProjectFile {
5
+ version: number;
6
+ main: string;
7
+ exclude: string[];
8
+ map?: MapPositions;
9
+ }
10
+ export interface MapPositions {
11
+ sections: Record<string, [number, number]>;
12
+ passages: Record<string, Record<string, [number, number]>>;
13
+ }
14
+ export type ParsedProjectFile = {
15
+ success: true;
16
+ project: ProjectFile;
17
+ } | {
18
+ success: false;
19
+ error: string;
20
+ };
21
+ export declare function parseProjectFile(text: string): ParsedProjectFile;
22
+ export declare function globToRegExp(pattern: string): RegExp;
23
+ export declare function isExcluded(path: string, exclude: string[]): boolean;
24
+ export declare function isAlwaysSkipped(path: string): boolean;
25
+ export interface StoryFiles {
26
+ main: string;
27
+ included: string[];
28
+ excluded: string[];
29
+ }
30
+ export declare const comparePaths: (a: string, b: string) => 1 | 0 | -1;
31
+ export declare function getStoryFiles(project: ProjectFile, paths: Iterable<string>, skip?: string[]): StoryFiles;
32
+ export declare function formatProjectFile(project: {
33
+ main: string;
34
+ exclude?: string[];
35
+ }): string;
36
+ export declare function updateProjectFile(text: string, changes: {
37
+ main?: string;
38
+ exclude?: string[];
39
+ map?: MapPositions;
40
+ }): string | undefined;
@@ -0,0 +1,222 @@
1
+ // The squiffy.json project file, which makes a folder of .squiffy files one story:
2
+ //
3
+ // { "version": 1, "main": "story.squiffy", "exclude": ["drafts/**"] }
4
+ //
5
+ // Without it, a story is its main file plus whatever that @imports. With it, the story is every
6
+ // .squiffy file in the folder and its subfolders, except those `exclude` matches: the main file
7
+ // first, then the rest in path order. These are the rules the CLI, the Vite plugin, the language
8
+ // service and the editor all share. They're pure functions, so each can supply its own file list.
9
+ export const PROJECT_FILENAME = "squiffy.json";
10
+ // The newest project file format this version of Squiffy understands. It counts the file
11
+ // format, not the Squiffy release, and only goes up when the meaning of a project changes.
12
+ export const PROJECT_FILE_VERSION = 1;
13
+ // Where the project file's JSON schema is published
14
+ export const PROJECT_SCHEMA_URL = "https://squiffystory.com/schema/squiffy.json";
15
+ // Parses and checks a squiffy.json. An error is a sentence to show the author as is.
16
+ export function parseProjectFile(text) {
17
+ const fail = (error) => ({ success: false, error });
18
+ let json;
19
+ try {
20
+ json = JSON.parse(text);
21
+ }
22
+ catch (e) {
23
+ return fail(`${PROJECT_FILENAME} isn't valid JSON: ${e instanceof Error ? e.message : String(e)}`);
24
+ }
25
+ if (!json || typeof json != "object" || Array.isArray(json)) {
26
+ return fail(`${PROJECT_FILENAME} should contain an object, such as { "version": 1, "main": "story.squiffy" }.`);
27
+ }
28
+ const data = json;
29
+ const version = data.version;
30
+ if (version === undefined) {
31
+ return fail(`${PROJECT_FILENAME} needs a "version", which should be ${PROJECT_FILE_VERSION}.`);
32
+ }
33
+ if (typeof version != "number" || !Number.isInteger(version) || version < 1) {
34
+ return fail(`${PROJECT_FILENAME}'s "version" should be a whole number, such as ${PROJECT_FILE_VERSION}.`);
35
+ }
36
+ if (version > PROJECT_FILE_VERSION) {
37
+ return fail(`This story's ${PROJECT_FILENAME} is version ${version}, which needs a newer version of Squiffy.`);
38
+ }
39
+ const main = data.main;
40
+ if (main === undefined) {
41
+ return fail(`${PROJECT_FILENAME} needs a "main" file, such as "main": "story.squiffy".`);
42
+ }
43
+ if (typeof main != "string" || !main.trim()) {
44
+ return fail(`${PROJECT_FILENAME}'s "main" should be the name of a .squiffy file, such as "story.squiffy".`);
45
+ }
46
+ const mainPath = normalisePath(main);
47
+ if (mainPath === null) {
48
+ return fail(`${PROJECT_FILENAME}'s "main" should be a path inside the project's folder, not "${main}".`);
49
+ }
50
+ if (!mainPath.endsWith(".squiffy")) {
51
+ return fail(`${PROJECT_FILENAME}'s "main" should be a .squiffy file, not "${main}".`);
52
+ }
53
+ const exclude = data.exclude ?? [];
54
+ if (!Array.isArray(exclude) || exclude.some(pattern => typeof pattern != "string")) {
55
+ return fail(`${PROJECT_FILENAME}'s "exclude" should be a list of file patterns, such as ["drafts/**"].`);
56
+ }
57
+ const map = parseMapPositions(data.map);
58
+ return { success: true, project: { version, main: mainPath, exclude: exclude, ...(map ? { map } : {}) } };
59
+ }
60
+ const isPosition = (value) => Array.isArray(value) && value.length == 2 && value.every(n => typeof n == "number" && Number.isFinite(n));
61
+ const isObject = (value) => !!value && typeof value == "object" && !Array.isArray(value);
62
+ // The story map's positions. Only the editor uses them, so anything that isn't a position is
63
+ // left out rather than stopping the story from building.
64
+ function parseMapPositions(value) {
65
+ if (!isObject(value))
66
+ return undefined;
67
+ const sections = {};
68
+ const passages = {};
69
+ if (isObject(value.sections)) {
70
+ for (const [name, position] of Object.entries(value.sections)) {
71
+ if (isPosition(position))
72
+ sections[name] = position;
73
+ }
74
+ }
75
+ if (isObject(value.passages)) {
76
+ for (const [section, byName] of Object.entries(value.passages)) {
77
+ if (!isObject(byName))
78
+ continue;
79
+ for (const [name, position] of Object.entries(byName)) {
80
+ if (isPosition(position))
81
+ (passages[section] ?? (passages[section] = {}))[name] = position;
82
+ }
83
+ }
84
+ }
85
+ return { sections, passages };
86
+ }
87
+ // A project path with "/" separators and no "." segments, or null if it goes outside the folder
88
+ // or is absolute.
89
+ function normalisePath(path) {
90
+ const slashes = path.replace(/\\/g, "/");
91
+ if (slashes.startsWith("/") || /^[a-zA-Z]:/.test(slashes))
92
+ return null;
93
+ const parts = [];
94
+ for (const part of slashes.split("/")) {
95
+ if (part == "" || part == ".")
96
+ continue;
97
+ if (part == "..")
98
+ return null;
99
+ parts.push(part);
100
+ }
101
+ return parts.length ? parts.join("/") : null;
102
+ }
103
+ // "*" and "?" match within one path segment; "**" matches across segments.
104
+ export function globToRegExp(pattern) {
105
+ let out = "";
106
+ for (let i = 0; i < pattern.length; i++) {
107
+ const c = pattern[i];
108
+ if (c == "*") {
109
+ if (pattern[i + 1] == "*") {
110
+ i++;
111
+ if (pattern[i + 1] == "/") {
112
+ i++;
113
+ out += "(?:.*/)?";
114
+ }
115
+ else {
116
+ out += ".*";
117
+ }
118
+ }
119
+ else {
120
+ out += "[^/]*";
121
+ }
122
+ }
123
+ else if (c == "?") {
124
+ out += "[^/]";
125
+ }
126
+ else {
127
+ out += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
128
+ }
129
+ }
130
+ return new RegExp(`^${out}$`);
131
+ }
132
+ // Whether `exclude` leaves a file out of the story: a pattern matches it or one of its folders.
133
+ export function isExcluded(path, exclude) {
134
+ const parts = path.split("/");
135
+ return exclude.some(pattern => {
136
+ const normalised = normalisePath(pattern.trim());
137
+ if (normalised === null)
138
+ return false;
139
+ const regex = globToRegExp(normalised);
140
+ for (let i = 1; i <= parts.length; i++) {
141
+ if (regex.test(parts.slice(0, i).join("/")))
142
+ return true;
143
+ }
144
+ return false;
145
+ });
146
+ }
147
+ // Folders whose .squiffy files are never part of a story, whatever `exclude` says:
148
+ // node_modules, and folders whose names start with "." (.git, .vscode and the like).
149
+ export function isAlwaysSkipped(path) {
150
+ const folders = path.split("/").slice(0, -1);
151
+ return folders.some(folder => folder == "node_modules" || folder.startsWith("."));
152
+ }
153
+ // Sorts paths by code point, so the order is the same everywhere, whatever the locale.
154
+ export const comparePaths = (a, b) => a < b ? -1 : a > b ? 1 : 0;
155
+ // Which of a project's files make up the story. `paths` are relative to the project file's folder,
156
+ // with "/" separators, as from a recursive listing of the folder; anything that isn't a .squiffy
157
+ // file is ignored. Pass `skip` to leave out more folders, such as a build's output folder.
158
+ export function getStoryFiles(project, paths, skip = []) {
159
+ const included = [];
160
+ const excluded = [];
161
+ const skipped = skip.map(folder => normalisePath(folder)).filter(folder => folder !== null);
162
+ for (const path of new Set(paths)) {
163
+ if (!path.endsWith(".squiffy") || path == project.main || isAlwaysSkipped(path))
164
+ continue;
165
+ if (skipped.some(folder => path.startsWith(folder + "/")))
166
+ continue;
167
+ (isExcluded(path, project.exclude) ? excluded : included).push(path);
168
+ }
169
+ return { main: project.main, included: included.sort(comparePaths), excluded: excluded.sort(comparePaths) };
170
+ }
171
+ // The text of a new project file
172
+ export function formatProjectFile(project) {
173
+ const json = {
174
+ $schema: PROJECT_SCHEMA_URL,
175
+ version: PROJECT_FILE_VERSION,
176
+ main: project.main,
177
+ };
178
+ if (project.exclude?.length)
179
+ json.exclude = project.exclude;
180
+ return JSON.stringify(json, null, 2) + "\n";
181
+ }
182
+ // Changes a project file's text, keeping any other properties it has. Returns undefined if the
183
+ // text isn't a JSON object. A `map` with no positions removes it.
184
+ export function updateProjectFile(text, changes) {
185
+ let json;
186
+ try {
187
+ json = JSON.parse(text);
188
+ }
189
+ catch {
190
+ return undefined;
191
+ }
192
+ if (!json || typeof json != "object" || Array.isArray(json))
193
+ return undefined;
194
+ const data = { ...json };
195
+ if (changes.main !== undefined)
196
+ data.main = changes.main;
197
+ if (changes.exclude !== undefined) {
198
+ if (changes.exclude.length)
199
+ data.exclude = changes.exclude;
200
+ else
201
+ delete data.exclude;
202
+ }
203
+ if (changes.map !== undefined) {
204
+ const { sections, passages } = changes.map;
205
+ const used = Object.fromEntries(Object.entries(passages).filter(([, byName]) => Object.keys(byName).length));
206
+ // Anything else that's in "map" stays, but empty lists of positions don't
207
+ const map = { ...(isObject(data.map) ? data.map : {}) };
208
+ delete map.sections;
209
+ delete map.passages;
210
+ if (Object.keys(sections).length)
211
+ map.sections = sections;
212
+ if (Object.keys(used).length)
213
+ map.passages = used;
214
+ if (Object.keys(map).length)
215
+ data.map = map;
216
+ else
217
+ delete data.map;
218
+ }
219
+ const indent = /^\{\s*\n([ \t]+)/.exec(text)?.[1] ?? 2;
220
+ // Each position on one line, rather than an x and a y on lines of their own
221
+ return JSON.stringify(data, null, indent).replace(/\[\s+(-?[\d.e+-]+),\s+(-?[\d.e+-]+)\s+\]/g, "[$1, $2]") + "\n";
222
+ }