squiffy-compiler 7.0.0-beta.5 → 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.
package/dist/project.js CHANGED
@@ -3,15 +3,49 @@
3
3
  // { "version": 1, "main": "story.squiffy", "exclude": ["drafts/**"] }
4
4
  //
5
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.
6
+ // .squiffy, .css and .js file in the folder and its subfolders, except those `exclude` matches:
7
+ // the main file first, then the rest in path order. These are the rules the CLI, the Vite plugin,
8
+ // the language service and the editor all share. They're pure functions, so each can supply its own file list.
9
9
  export const PROJECT_FILENAME = "squiffy.json";
10
10
  // The newest project file format this version of Squiffy understands. It counts the file
11
11
  // format, not the Squiffy release, and only goes up when the meaning of a project changes.
12
12
  export const PROJECT_FILE_VERSION = 1;
13
13
  // Where the project file's JSON schema is published
14
14
  export const PROJECT_SCHEMA_URL = "https://squiffystory.com/schema/squiffy.json";
15
+ // The icons a panel's button can have. The runtime has the same list (PANEL_ICONS).
16
+ export const PANEL_ICONS = ["bag", "person", "map", "help", "info", "list", "book", "star", "heart"];
17
+ // The published page's text in English, which squiffy.json's "strings" can replace
18
+ export const PAGE_STRINGS = {
19
+ back: "Back",
20
+ restart: "Restart",
21
+ restartConfirm: "Are you sure you want to restart?",
22
+ switchToDark: "Switch to dark mode",
23
+ switchToLight: "Switch to light mode",
24
+ // The Saved games dialog, opened by the Save button. [name] and [time] are filled in.
25
+ saves: "Saved games",
26
+ saveName: "Name (optional)",
27
+ save: "Save",
28
+ noSaves: "No saved games yet.",
29
+ savedGame: "Saved game",
30
+ savedToday: "Today, [time]",
31
+ savedYesterday: "Yesterday, [time]",
32
+ load: "Load",
33
+ loadConfirm: "Load \"[name]\"? You'll lose anything you've done since you last saved.",
34
+ saveOptions: "Options for [name]",
35
+ overwrite: "Overwrite",
36
+ overwriteConfirm: "Overwrite \"[name]\"?",
37
+ rename: "Rename",
38
+ newName: "New name",
39
+ saveToFile: "Save to file",
40
+ loadFromFile: "Load from file",
41
+ delete: "Delete",
42
+ deleteConfirm: "Delete \"[name]\"? This can't be undone.",
43
+ cancel: "Cancel",
44
+ close: "Close",
45
+ wrongStory: "This saved game is for a different story.",
46
+ notASave: "This file isn't a saved game.",
47
+ cantSave: "The game couldn't be saved. Try Save to file instead.",
48
+ };
15
49
  // Parses and checks a squiffy.json. An error is a sentence to show the author as is.
16
50
  export function parseProjectFile(text) {
17
51
  const fail = (error) => ({ success: false, error });
@@ -54,20 +88,78 @@ export function parseProjectFile(text) {
54
88
  if (!Array.isArray(exclude) || exclude.some(pattern => typeof pattern != "string")) {
55
89
  return fail(`${PROJECT_FILENAME}'s "exclude" should be a list of file patterns, such as ["drafts/**"].`);
56
90
  }
91
+ const id = data.id;
92
+ if (id !== undefined && (typeof id != "string" || !id.trim())) {
93
+ return fail(`${PROJECT_FILENAME}'s "id" should be text that identifies the story, such as "${EXAMPLE_ID}".`);
94
+ }
57
95
  const backButton = data.backButton;
58
96
  if (backButton !== undefined && typeof backButton != "boolean") {
59
97
  return fail(`${PROJECT_FILENAME}'s "backButton" should be true or false.`);
60
98
  }
99
+ const saveButton = data.saveButton;
100
+ if (saveButton !== undefined && typeof saveButton != "boolean") {
101
+ return fail(`${PROJECT_FILENAME}'s "saveButton" should be true or false.`);
102
+ }
103
+ const strings = data.strings;
104
+ if (strings !== undefined && (!isObject(strings) || Object.values(strings).some(value => typeof value != "string"))) {
105
+ return fail(`${PROJECT_FILENAME}'s "strings" should be an object of text, such as { "restart": "Recommencer" }.`);
106
+ }
107
+ const panels = parsePanels(data.panels);
108
+ if (typeof panels == "string")
109
+ return fail(panels);
61
110
  const map = parseMapPositions(data.map);
62
111
  return {
63
112
  success: true,
64
113
  project: {
65
114
  version, main: mainPath, exclude: exclude,
115
+ ...(id !== undefined ? { id: id.trim() } : {}),
66
116
  ...(map ? { map } : {}),
67
117
  ...(backButton !== undefined ? { backButton } : {}),
118
+ ...(saveButton !== undefined ? { saveButton } : {}),
119
+ ...(strings !== undefined ? { strings: pickPageStrings(strings) } : {}),
120
+ ...(panels !== undefined ? { panels } : {}),
68
121
  },
69
122
  };
70
123
  }
124
+ // The page strings Squiffy knows about. Others are left out, so a story written for a newer Squiffy,
125
+ // with strings this one doesn't have, still builds.
126
+ function pickPageStrings(strings) {
127
+ return Object.fromEntries(Object.entries(strings).filter(([name]) => Object.prototype.hasOwnProperty.call(PAGE_STRINGS, name)));
128
+ }
129
+ // squiffy.json's "panels", or an error to show the author
130
+ function parsePanels(value) {
131
+ if (value === undefined)
132
+ return undefined;
133
+ const example = "{ \"passage\": \"inventory\", \"label\": \"Inventory\" }";
134
+ if (!Array.isArray(value))
135
+ return `${PROJECT_FILENAME}'s "panels" should be a list, such as [${example}].`;
136
+ const panels = [];
137
+ for (const [i, item] of value.entries()) {
138
+ const which = `${PROJECT_FILENAME}'s panel ${i + 1}`;
139
+ if (!isObject(item))
140
+ return `${which} should be an object, such as ${example}.`;
141
+ if (typeof item.passage != "string" || !item.passage.trim()) {
142
+ return `${which} needs a "passage": the name of a passage in the master section [[]].`;
143
+ }
144
+ if (typeof item.label != "string" || !item.label.trim()) {
145
+ return `${which} needs a "label", for its button, such as "Inventory".`;
146
+ }
147
+ if (item.position !== undefined && item.position !== "side" && item.position !== "button") {
148
+ return `${which}'s "position" should be "side" or "button".`;
149
+ }
150
+ if (item.icon !== undefined && !PANEL_ICONS.includes(item.icon)) {
151
+ return `${which}'s "icon" should be one of ${PANEL_ICONS.map(icon => `"${icon}"`).join(", ")}.`;
152
+ }
153
+ panels.push({
154
+ passage: item.passage.trim(),
155
+ label: item.label.trim(),
156
+ ...(item.position !== undefined ? { position: item.position } : {}),
157
+ ...(item.icon !== undefined ? { icon: item.icon } : {}),
158
+ });
159
+ }
160
+ return panels;
161
+ }
162
+ const EXAMPLE_ID = "0b7c6d9e-3f1a-4e2b-9c5d-8a7f6e5d4c3b";
71
163
  const isPosition = (value) => Array.isArray(value) && value.length == 2 && value.every(n => typeof n == "number" && Number.isFinite(n));
72
164
  const isObject = (value) => !!value && typeof value == "object" && !Array.isArray(value);
73
165
  // The story map's positions. Only the editor uses them, so anything that isn't a position is
@@ -155,39 +247,77 @@ export function isExcluded(path, exclude) {
155
247
  return false;
156
248
  });
157
249
  }
158
- // Folders whose .squiffy files are never part of a story, whatever `exclude` says:
159
- // node_modules, and folders whose names start with "." (.git, .vscode and the like).
250
+ // Folders whose files are never part of a story, whatever `exclude` says: node_modules, and
251
+ // folders whose names start with "." (.git, .vscode and the like).
160
252
  export function isAlwaysSkipped(path) {
161
253
  const folders = path.split("/").slice(0, -1);
162
254
  return folders.some(folder => folder == "node_modules" || folder.startsWith("."));
163
255
  }
256
+ // The folder, next to squiffy.json, that the CLI builds a project's published files into. Its
257
+ // files are never part of the story.
258
+ export const BUILD_FOLDER = "build";
259
+ // The files that Squiffy 6, and Squiffy 7 without a squiffy.json, write next to the main file
260
+ // when publishing a story, with its index.html. With an index.html beside them, they're taken to
261
+ // be an old build, and aren't part of the story unless it @imports them.
262
+ const OLD_BUILD_FILES = ["story.js", "style.css", "squiffy.runtime.js", "squiffy.runtime.global.js"];
263
+ // The kinds of file that are part of a story
264
+ export const isSquiffyPath = (path) => path.endsWith(".squiffy");
265
+ export const isStylesheetPath = (path) => path.endsWith(".css");
266
+ export const isScriptPath = (path) => path.endsWith(".js");
267
+ export const isStoryFilePath = (path) => isSquiffyPath(path) || isStylesheetPath(path) || isScriptPath(path);
164
268
  // Sorts paths by code point, so the order is the same everywhere, whatever the locale.
165
269
  export const comparePaths = (a, b) => a < b ? -1 : a > b ? 1 : 0;
166
- // Which of a project's files make up the story. `paths` are relative to the project file's folder,
167
- // with "/" separators, as from a recursive listing of the folder; anything that isn't a .squiffy
168
- // file is ignored. Pass `skip` to leave out more folders, such as a build's output folder.
270
+ // Which of a project's files make up the story: its .squiffy files, stylesheets and scripts.
271
+ // `paths` are relative to the project file's folder, with "/" separators, as from a recursive
272
+ // listing of the folder; files of other kinds are ignored. Pass `skip` to leave out more files
273
+ // or folders, such as a build's output folder.
169
274
  export function getStoryFiles(project, paths, skip = []) {
170
275
  const included = [];
276
+ const stylesheets = [];
277
+ const scripts = [];
171
278
  const excluded = [];
172
- const skipped = skip.map(folder => normalisePath(folder)).filter(folder => folder !== null);
173
- for (const path of new Set(paths)) {
174
- if (!path.endsWith(".squiffy") || path == project.main || isAlwaysSkipped(path))
279
+ const all = new Set(paths);
280
+ const skipped = [BUILD_FOLDER, ...skip].map(folder => normalisePath(folder)).filter(folder => folder !== null);
281
+ const mainSlash = project.main.lastIndexOf("/");
282
+ const mainFolder = mainSlash < 0 ? "" : project.main.substring(0, mainSlash + 1);
283
+ const oldBuild = all.has(mainFolder + "index.html") ? new Set(OLD_BUILD_FILES.map(file => mainFolder + file)) : new Set();
284
+ for (const path of all) {
285
+ if (!isStoryFilePath(path) || path == project.main || isAlwaysSkipped(path) || oldBuild.has(path))
175
286
  continue;
176
- if (skipped.some(folder => path.startsWith(folder + "/")))
287
+ if (skipped.some(folder => path == folder || path.startsWith(folder + "/")))
177
288
  continue;
178
- (isExcluded(path, project.exclude) ? excluded : included).push(path);
289
+ if (isExcluded(path, project.exclude))
290
+ excluded.push(path);
291
+ else if (isSquiffyPath(path))
292
+ included.push(path);
293
+ else if (isStylesheetPath(path))
294
+ stylesheets.push(path);
295
+ else
296
+ scripts.push(path);
179
297
  }
180
- return { main: project.main, included: included.sort(comparePaths), excluded: excluded.sort(comparePaths) };
298
+ return {
299
+ main: project.main,
300
+ included: included.sort(comparePaths),
301
+ stylesheets: stylesheets.sort(comparePaths),
302
+ scripts: scripts.sort(comparePaths),
303
+ excluded: excluded.sort(comparePaths),
304
+ };
181
305
  }
182
- // The text of a new project file
306
+ // The story's files after the main file, in the order the compiler takes them (see
307
+ // AnalyseSettings.storyFiles): its .squiffy files, then its stylesheets, then its scripts.
308
+ export const storyFileList = (story) => [...story.included, ...story.stylesheets, ...story.scripts];
309
+ // The text of a new project file. It's given a new random id, unless one is passed in.
183
310
  export function formatProjectFile(project) {
184
311
  const json = {
185
312
  $schema: PROJECT_SCHEMA_URL,
186
313
  version: PROJECT_FILE_VERSION,
314
+ id: project.id ?? crypto.randomUUID(),
187
315
  main: project.main,
188
316
  };
189
317
  if (project.exclude?.length)
190
318
  json.exclude = project.exclude;
319
+ if (project.panels?.length)
320
+ json.panels = project.panels;
191
321
  const text = JSON.stringify(json, null, 2) + "\n";
192
322
  return project.map ? updateProjectFile(text, { map: project.map }) : text;
193
323
  }
@@ -0,0 +1,50 @@
1
+ export declare class QuestParseError extends Error {
2
+ }
3
+ export interface XmlElement {
4
+ name: string;
5
+ attrs: Record<string, string>;
6
+ children: XmlElement[];
7
+ text: string;
8
+ }
9
+ export declare function parseXml(source: string): XmlElement;
10
+ export type QuestValue = {
11
+ type: "string";
12
+ value: string;
13
+ } | {
14
+ type: "boolean";
15
+ value: boolean;
16
+ } | {
17
+ type: "number";
18
+ value: number;
19
+ } | {
20
+ type: "script";
21
+ value: string;
22
+ } | {
23
+ type: "stringdictionary";
24
+ value: [string, string][];
25
+ } | {
26
+ type: "stringlist";
27
+ value: string[];
28
+ } | {
29
+ type: "other";
30
+ typeName: string;
31
+ value: string;
32
+ };
33
+ export declare function readValue(element: XmlElement): QuestValue;
34
+ export interface QuestObject {
35
+ name: string;
36
+ inherits: string[];
37
+ attributes: Map<string, QuestValue>;
38
+ children: QuestObject[];
39
+ }
40
+ export interface QuestGame {
41
+ aslVersion: string;
42
+ gamebook: boolean;
43
+ game: QuestObject;
44
+ gameDefaults: Map<string, QuestValue>;
45
+ pages: QuestObject[];
46
+ start?: string;
47
+ javascript: string[];
48
+ }
49
+ export declare function parseQuestGame(source: string): QuestGame;
50
+ export declare function isQuestSource(source: string): boolean;
@@ -0,0 +1,181 @@
1
+ // Reads a Quest 5 game file (.aslx), and the parts of a gamebook in it that the converter needs.
2
+ // A saved game has the whole of Quest's core library in it, as well as the author's pages, so this
3
+ // only reads the game, its pages, and the library's defaults for the game's settings.
4
+ export class QuestParseError extends Error {
5
+ }
6
+ // A small XML reader: ASLX is plain XML, without namespaces or a DTD
7
+ export function parseXml(source) {
8
+ let pos = 0;
9
+ const root = { name: "", attrs: {}, children: [], text: "" };
10
+ const stack = [root];
11
+ const top = () => stack[stack.length - 1];
12
+ while (pos < source.length) {
13
+ const lt = source.indexOf("<", pos);
14
+ if (lt == -1) {
15
+ top().text += decodeEntities(source.substring(pos));
16
+ break;
17
+ }
18
+ if (lt > pos)
19
+ top().text += decodeEntities(source.substring(pos, lt));
20
+ if (source.startsWith("<!--", lt)) {
21
+ pos = endOf(source, "-->", lt);
22
+ }
23
+ else if (source.startsWith("<![CDATA[", lt)) {
24
+ const end = source.indexOf("]]>", lt);
25
+ if (end == -1)
26
+ throw new QuestParseError("The file ends inside a CDATA section.");
27
+ top().text += source.substring(lt + 9, end);
28
+ pos = end + 3;
29
+ }
30
+ else if (source.startsWith("<?", lt)) {
31
+ pos = endOf(source, "?>", lt);
32
+ }
33
+ else if (source.startsWith("<!", lt)) {
34
+ pos = endOf(source, ">", lt);
35
+ }
36
+ else if (source.startsWith("</", lt)) {
37
+ const end = source.indexOf(">", lt);
38
+ if (end == -1)
39
+ throw new QuestParseError("The file ends inside a tag.");
40
+ const name = source.substring(lt + 2, end).trim();
41
+ // Close up to the matching element, so a stray closing tag doesn't lose the rest
42
+ const index = stack.map(e => e.name).lastIndexOf(name);
43
+ if (index > 0)
44
+ stack.length = index;
45
+ pos = end + 1;
46
+ }
47
+ else {
48
+ const tag = /^<([A-Za-z_][\w.:-]*)((?:\s+[\w.:-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>/.exec(source.substring(lt, lt + 4096));
49
+ if (!tag) {
50
+ // Not a tag: a < in text
51
+ top().text += "<";
52
+ pos = lt + 1;
53
+ continue;
54
+ }
55
+ const attrs = {};
56
+ for (const a of tag[2].matchAll(/([\w.:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) {
57
+ attrs[a[1]] = decodeEntities(a[2] ?? a[3]);
58
+ }
59
+ const element = { name: tag[1], attrs, children: [], text: "" };
60
+ top().children.push(element);
61
+ if (tag[3] != "/")
62
+ stack.push(element);
63
+ pos = lt + tag[0].length;
64
+ }
65
+ }
66
+ return root;
67
+ }
68
+ function endOf(source, terminator, from) {
69
+ const end = source.indexOf(terminator, from);
70
+ if (end == -1)
71
+ throw new QuestParseError("The file ends too soon.");
72
+ return end + terminator.length;
73
+ }
74
+ const namedEntities = { lt: "<", gt: ">", amp: "&", quot: "\"", apos: "'" };
75
+ function decodeEntities(text) {
76
+ return text.replace(/&(#x[0-9a-fA-F]+|#\d+|\w+);/g, (match, entity) => {
77
+ if (entity.startsWith("#x"))
78
+ return String.fromCodePoint(parseInt(entity.substring(2), 16));
79
+ if (entity.startsWith("#"))
80
+ return String.fromCodePoint(parseInt(entity.substring(1), 10));
81
+ return namedEntities[entity] ?? match;
82
+ });
83
+ }
84
+ // Reads an object's attribute from its element: <name type="...">value</name>, or
85
+ // <attr name="name" type="...">. An element with no type and nothing in it is true.
86
+ export function readValue(element) {
87
+ const type = element.attrs.type;
88
+ const text = element.text;
89
+ switch (type) {
90
+ case undefined:
91
+ case "":
92
+ if (element.children.length == 0 && text.trim() == "")
93
+ return { type: "boolean", value: true };
94
+ return { type: "string", value: text };
95
+ case "string":
96
+ return { type: "string", value: text };
97
+ case "boolean":
98
+ return { type: "boolean", value: text.trim().toLowerCase() != "false" };
99
+ case "int":
100
+ case "double":
101
+ return { type: "number", value: Number(text.trim()) || 0 };
102
+ case "script":
103
+ return { type: "script", value: text };
104
+ case "stringdictionary":
105
+ return {
106
+ type: "stringdictionary",
107
+ value: element.children.filter(c => c.name == "item").map(item => [
108
+ item.children.find(c => c.name == "key")?.text ?? item.attrs.key ?? "",
109
+ item.children.find(c => c.name == "value")?.text ?? "",
110
+ ]),
111
+ };
112
+ case "simplestringlist":
113
+ return { type: "stringlist", value: text.split(/[;\n]/).map(s => s.trim()).filter(s => s) };
114
+ case "stringlist":
115
+ case "list":
116
+ return { type: "stringlist", value: element.children.filter(c => c.name == "value").map(c => c.text) };
117
+ default:
118
+ return { type: "other", typeName: type, value: text };
119
+ }
120
+ }
121
+ function readObject(element) {
122
+ const attributes = new Map();
123
+ const inherits = [];
124
+ const children = [];
125
+ for (const child of element.children) {
126
+ if (child.name == "inherit") {
127
+ if (child.attrs.name)
128
+ inherits.push(child.attrs.name);
129
+ }
130
+ else if (child.name == "object") {
131
+ children.push(readObject(child));
132
+ }
133
+ else if (child.name == "attr") {
134
+ if (child.attrs.name)
135
+ attributes.set(child.attrs.name, readValue(child));
136
+ }
137
+ else {
138
+ attributes.set(child.name, readValue(child));
139
+ }
140
+ }
141
+ return { name: element.attrs.name ?? "", inherits, attributes, children };
142
+ }
143
+ export function parseQuestGame(source) {
144
+ const root = parseXml(source.replace(/^\uFEFF/, ""));
145
+ const asl = root.children.find(e => e.name == "asl");
146
+ if (!asl)
147
+ throw new QuestParseError("This isn't a Quest game: there's no <asl> element in it.");
148
+ const gameElement = asl.children.find(e => e.name == "game");
149
+ if (!gameElement)
150
+ throw new QuestParseError("This isn't a Quest game: there's no <game> element in it.");
151
+ const game = readObject(gameElement);
152
+ const gameDefaults = new Map();
153
+ const defaultGame = asl.children.find(e => e.name == "type" && e.attrs.name == "defaultgame");
154
+ if (defaultGame) {
155
+ for (const [name, value] of readObject(defaultGame).attributes)
156
+ gameDefaults.set(name, value);
157
+ }
158
+ const style = game.attributes.get("_editorstyle") ?? gameDefaults.get("_editorstyle");
159
+ const gamebook = (style?.type == "string" && style.value.trim() == "gamebook")
160
+ || asl.children.some(e => e.name == "include" && /^GamebookCore\.aslx$/i.test(e.attrs.ref ?? ""));
161
+ const pages = [];
162
+ let start;
163
+ const isPlayer = (o) => o.name == "player" || o.inherits.includes("defaultplayer");
164
+ const collect = (objects) => {
165
+ for (const o of objects) {
166
+ if (isPlayer(o))
167
+ continue;
168
+ pages.push(o);
169
+ if (o.children.some(isPlayer))
170
+ start ?? (start = o.name);
171
+ collect(o.children);
172
+ }
173
+ };
174
+ collect(asl.children.filter(e => e.name == "object").map(readObject));
175
+ const javascript = asl.children.filter(e => e.name == "javascript" && e.attrs.src).map(e => e.attrs.src);
176
+ return { aslVersion: asl.attrs.version ?? "", gamebook, game, gameDefaults, pages, start, javascript };
177
+ }
178
+ // Whether some text is a Quest game file
179
+ export function isQuestSource(source) {
180
+ return /<asl\s+version\s*=/.test(source.substring(0, 2000));
181
+ }
@@ -0,0 +1,20 @@
1
+ export interface QuestConversionProblem {
2
+ page?: string;
3
+ text: string;
4
+ reason: string;
5
+ }
6
+ export interface QuestConversionResult {
7
+ title: string;
8
+ format: string;
9
+ files: Record<string, string>;
10
+ main: string;
11
+ pages: number;
12
+ assets: string[];
13
+ problems: QuestConversionProblem[];
14
+ }
15
+ export interface QuestConversionOptions {
16
+ name?: string;
17
+ files?: string[];
18
+ }
19
+ export declare function convertQuestGamebook(source: string, options?: QuestConversionOptions): QuestConversionResult;
20
+ export declare function formatQuestProblems(result: QuestConversionResult, sourceName?: string): string;