squiffy-compiler 6.0.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 (62) hide show
  1. package/README.md +10 -2
  2. package/dist/analyse.d.ts +96 -0
  3. package/dist/analyse.js +951 -0
  4. package/dist/compiler.d.ts +32 -40
  5. package/dist/compiler.js +26 -691
  6. package/dist/css-urls.d.ts +4 -0
  7. package/dist/css-urls.js +59 -0
  8. package/dist/emit.d.ts +71 -0
  9. package/dist/emit.js +192 -0
  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 +90 -0
  17. package/dist/language-service.js +883 -0
  18. package/dist/node.d.ts +23 -0
  19. package/dist/node.js +122 -0
  20. package/dist/parse.d.ts +22 -0
  21. package/dist/parse.js +316 -0
  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 +198 -0
  41. package/dist/syntax.js +8 -0
  42. package/dist/templates.d.ts +17 -0
  43. package/dist/templates.js +180 -0
  44. package/dist/text.d.ts +44 -0
  45. package/dist/text.js +348 -0
  46. package/dist/twine/audio.d.ts +21 -0
  47. package/dist/twine/audio.js +80 -0
  48. package/dist/twine/convert.d.ts +131 -0
  49. package/dist/twine/convert.js +1057 -0
  50. package/dist/twine/expression.d.ts +88 -0
  51. package/dist/twine/expression.js +318 -0
  52. package/dist/twine/harlowe.d.ts +27 -0
  53. package/dist/twine/harlowe.js +2341 -0
  54. package/dist/twine/settings.d.ts +9 -0
  55. package/dist/twine/settings.js +322 -0
  56. package/dist/twine/story.d.ts +24 -0
  57. package/dist/twine/story.js +231 -0
  58. package/dist/twine/sugarcube.d.ts +40 -0
  59. package/dist/twine/sugarcube.js +2172 -0
  60. package/dist/v5.js +2 -1
  61. package/package.json +35 -6
  62. package/syntaxes/squiffy.tmLanguage.json +1003 -0
@@ -0,0 +1,9 @@
1
+ import type { PlayerSetting } from "../project.js";
2
+ export interface SettingsProblem {
3
+ text: string;
4
+ reason: string;
5
+ }
6
+ export declare function sugarCubeSettings(script: string): {
7
+ settings: PlayerSetting[];
8
+ problems: SettingsProblem[];
9
+ };
@@ -0,0 +1,322 @@
1
+ // SugarCube's player settings (#452), from the story's JavaScript: Setting.addToggle(),
2
+ // Setting.addList() and Setting.addRange() become squiffy.json's "settings". The story reads them
3
+ // as settings.name, as in SugarCube. Their onInit and onChange functions can't come with them, as
4
+ // they're JavaScript written for SugarCube, but each setting puts classes on the story's element,
5
+ // which the stylesheet can use instead.
6
+ //
7
+ // Only literal values are read: text, numbers, true and false, lists of those, and a list held in a
8
+ // variable the script sets to one, as in `var settingFontSize = ["100%", "125%"]`.
9
+ const isCode = (v) => !!v && typeof v == "object" && !Array.isArray(v) && "code" in v && Object.keys(v).length == 1;
10
+ const isName = (v) => !!v && typeof v == "object" && !Array.isArray(v) && "name" in v && Object.keys(v).length == 1;
11
+ export function sugarCubeSettings(script) {
12
+ const settings = [];
13
+ const problems = [];
14
+ const calls = /\bSetting\s*\.\s*add(Toggle|List|Range|Header|Value)\s*\(/g;
15
+ for (const match of script.matchAll(calls)) {
16
+ const kind = match[1];
17
+ const start = match.index + match[0].length;
18
+ let args;
19
+ try {
20
+ args = new LiteralParser(script, start).arguments();
21
+ }
22
+ catch {
23
+ problems.push({ text: `Setting.add${kind}()`, reason: "This setting couldn't be read, so it isn't in Squiffy's Settings dialog." });
24
+ continue;
25
+ }
26
+ // How the import report names it
27
+ const callText = typeof args[0] == "string" ? `Setting.add${kind}(${JSON.stringify(args[0])})` : `Setting.add${kind}()`;
28
+ if (kind == "Header" || kind == "Value") {
29
+ if (kind == "Header")
30
+ problems.push({ text: callText, reason: "Squiffy's Settings dialog has no headings, so this has been left out." });
31
+ continue;
32
+ }
33
+ const [name, options] = args;
34
+ if (typeof name != "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
35
+ problems.push({ text: callText, reason: "A setting's name in Squiffy is letters, digits and underscores, so this has been left out." });
36
+ continue;
37
+ }
38
+ if (settings.some(s => s.name == name))
39
+ continue;
40
+ const o = options && typeof options == "object" && !Array.isArray(options) && !isCode(options) && !isName(options)
41
+ ? options : {};
42
+ const label = typeof o.label == "string" && o.label.trim() ? stripHtml(o.label) : name;
43
+ const description = typeof o.desc == "string" && o.desc.trim() ? stripHtml(o.desc) : undefined;
44
+ const base = { name, label, ...(description ? { description } : {}) };
45
+ if (kind == "Toggle") {
46
+ settings.push({ ...base, type: "toggle", ...(typeof o.default == "boolean" ? { default: o.default } : {}) });
47
+ }
48
+ else if (kind == "List") {
49
+ const list = isName(o.list) ? arrayNamed(script, o.list.name) : o.list;
50
+ const options = Array.isArray(list) ? list.map(optionOf) : null;
51
+ if (!options?.length || options.some(option => !option)) {
52
+ problems.push({ text: callText, reason: "This setting's list of options couldn't be read, so it isn't in Squiffy's Settings dialog." });
53
+ continue;
54
+ }
55
+ const unique = options.filter((option, i, all) => all.findIndex(o => o.value == option.value) == i);
56
+ const defaultValue = o.default === undefined || o.default === null ? undefined : String(o.default);
57
+ settings.push({
58
+ ...base, type: "list", options: unique,
59
+ ...(defaultValue !== undefined && unique.some(option => option.value == defaultValue) ? { default: defaultValue } : {}),
60
+ });
61
+ }
62
+ else {
63
+ const { min, max, step } = o;
64
+ if (typeof min != "number" || typeof max != "number" || min > max) {
65
+ problems.push({ text: callText, reason: "This setting's min and max couldn't be read, so it isn't in Squiffy's Settings dialog." });
66
+ continue;
67
+ }
68
+ settings.push({
69
+ ...base, type: "range", min, max,
70
+ ...(typeof step == "number" && step > 0 ? { step } : {}),
71
+ ...(typeof o.default == "number" && o.default >= min && o.default <= max ? { default: o.default } : {}),
72
+ });
73
+ }
74
+ if (o.onInit !== undefined || o.onChange !== undefined) {
75
+ const setting = settings[settings.length - 1];
76
+ const example = setting.type == "toggle" ? `setting-${name}`
77
+ : setting.type == "list" ? `setting-${name}-${setting.options[0].value.replace(/[^A-Za-z0-9_-]+/g, "-")}`
78
+ : `setting-${name}-${setting.default ?? setting.min}`;
79
+ problems.push({
80
+ text: callText,
81
+ reason: `This setting's onInit and onChange are SugarCube JavaScript, which Squiffy doesn't run. The setting puts a class on the story's element instead, such as ${example}, which the stylesheet can use.`,
82
+ });
83
+ }
84
+ }
85
+ return { settings, problems };
86
+ }
87
+ function optionOf(item) {
88
+ if (typeof item == "string" && item.trim())
89
+ return { value: item, label: item };
90
+ if (typeof item == "number" || typeof item == "boolean")
91
+ return { value: String(item), label: String(item) };
92
+ return null;
93
+ }
94
+ const stripHtml = (text) => text.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim();
95
+ // The list a variable is set to in the script, e.g. var sizes = ["Small", "Large"], or
96
+ // setup.sizes = [...]
97
+ function arrayNamed(script, name) {
98
+ const escaped = name.replace(/[.$]/g, m => "\\" + m);
99
+ const declaration = new RegExp(`(?:\\b(?:var|let|const)\\s+|(?<![\\w.$]))${escaped}\\s*=\\s*(?=\\[)`, "g");
100
+ const match = declaration.exec(script);
101
+ if (!match)
102
+ return undefined;
103
+ try {
104
+ return new LiteralParser(script, match.index + match[0].length).value(false);
105
+ }
106
+ catch {
107
+ return undefined;
108
+ }
109
+ }
110
+ // Reads JavaScript literals from a script. Anything else, such as a function, is skipped over and
111
+ // kept as code, so the arguments around it can still be read.
112
+ class LiteralParser {
113
+ constructor(s, i) {
114
+ Object.defineProperty(this, "s", {
115
+ enumerable: true,
116
+ configurable: true,
117
+ writable: true,
118
+ value: s
119
+ });
120
+ Object.defineProperty(this, "i", {
121
+ enumerable: true,
122
+ configurable: true,
123
+ writable: true,
124
+ value: i
125
+ });
126
+ }
127
+ // A call's arguments, up to its closing bracket
128
+ arguments() {
129
+ const args = [];
130
+ this.space();
131
+ if (this.accept(")"))
132
+ return args;
133
+ do {
134
+ this.space();
135
+ if (this.peek() == ")")
136
+ break;
137
+ args.push(this.value());
138
+ this.space();
139
+ } while (this.accept(","));
140
+ this.expect(")");
141
+ return args;
142
+ }
143
+ // A value, which is code if there's more to it, e.g. a sum. In a statement (not wholeExpression),
144
+ // what comes after it isn't looked at.
145
+ value(wholeExpression = true) {
146
+ this.space();
147
+ const c = this.peek();
148
+ const start = this.i;
149
+ let v;
150
+ if (c == "\"" || c == "'" || c == "`")
151
+ v = this.string();
152
+ else if (c == "[")
153
+ v = this.array();
154
+ else if (c == "{")
155
+ v = this.object();
156
+ else if (/[-+\d.]/.test(c) && /^[-+]?(\d|\.\d)/.test(this.s.substring(this.i, this.i + 3)))
157
+ v = this.number();
158
+ else {
159
+ const word = /^[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*/.exec(this.s.substring(this.i));
160
+ if (word && !["function", "async", "new"].includes(word[0])) {
161
+ this.i += word[0].length;
162
+ const name = word[0].replace(/\s+/g, "");
163
+ v = name == "true" ? true : name == "false" ? false : name == "null" || name == "undefined" ? null : { name };
164
+ }
165
+ else
166
+ v = { code: "" };
167
+ }
168
+ // Anything more, e.g. an arrow function's body or a sum, makes it code
169
+ if (!wholeExpression && !isCode(v))
170
+ return v;
171
+ this.space();
172
+ if (!this.atEnd()) {
173
+ this.skipExpression();
174
+ return { code: this.s.substring(start, this.i) };
175
+ }
176
+ return v;
177
+ }
178
+ atEnd() {
179
+ const c = this.peek();
180
+ return c == "," || c == ")" || c == "]" || c == "}" || c == "";
181
+ }
182
+ // Skips to the end of the expression: the next comma or closing bracket outside any brackets
183
+ skipExpression() {
184
+ let depth = 0;
185
+ while (this.i < this.s.length) {
186
+ const c = this.peek();
187
+ if (c == "\"" || c == "'" || c == "`") {
188
+ this.string();
189
+ continue;
190
+ }
191
+ if (c == "/" && (this.s[this.i + 1] == "/" || this.s[this.i + 1] == "*")) {
192
+ this.space();
193
+ continue;
194
+ }
195
+ if (c == "(" || c == "[" || c == "{")
196
+ depth++;
197
+ else if (c == ")" || c == "]" || c == "}") {
198
+ if (depth == 0)
199
+ return;
200
+ depth--;
201
+ }
202
+ else if (c == "," && depth == 0)
203
+ return;
204
+ this.i++;
205
+ }
206
+ throw new Error("Unfinished expression");
207
+ }
208
+ string() {
209
+ const quote = this.s[this.i++];
210
+ let out = "";
211
+ let template = false;
212
+ while (this.i < this.s.length) {
213
+ const c = this.s[this.i++];
214
+ if (c == quote)
215
+ return template ? { code: out } : out;
216
+ if (c == "\\") {
217
+ const e = this.s[this.i++];
218
+ out += e == "n" ? "\n" : e == "t" ? "\t" : e;
219
+ }
220
+ else {
221
+ if (quote == "`" && c == "$" && this.s[this.i] == "{")
222
+ template = true;
223
+ out += c;
224
+ }
225
+ }
226
+ throw new Error("Unfinished string");
227
+ }
228
+ number() {
229
+ const match = /^[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/i.exec(this.s.substring(this.i));
230
+ this.i += match[0].length;
231
+ return Number(match[0]);
232
+ }
233
+ array() {
234
+ this.expect("[");
235
+ const items = [];
236
+ this.space();
237
+ while (!this.accept("]")) {
238
+ items.push(this.value());
239
+ this.space();
240
+ if (!this.accept(",")) {
241
+ this.expect("]");
242
+ break;
243
+ }
244
+ this.space();
245
+ }
246
+ return items;
247
+ }
248
+ object() {
249
+ this.expect("{");
250
+ const result = {};
251
+ this.space();
252
+ while (!this.accept("}")) {
253
+ const c = this.peek();
254
+ let key;
255
+ if (c == "\"" || c == "'") {
256
+ const k = this.string();
257
+ if (typeof k != "string")
258
+ throw new Error("Bad key");
259
+ key = k;
260
+ }
261
+ else {
262
+ const word = /^[A-Za-z_$][\w$]*/.exec(this.s.substring(this.i));
263
+ if (!word)
264
+ throw new Error("Bad key");
265
+ key = word[0];
266
+ this.i += key.length;
267
+ }
268
+ this.space();
269
+ if (this.accept(":")) {
270
+ result[key] = this.value();
271
+ }
272
+ else if (this.peek() == "(") {
273
+ // A method, e.g. onChange() { ... }
274
+ const start = this.i;
275
+ this.skipExpression();
276
+ result[key] = { code: this.s.substring(start, this.i) };
277
+ }
278
+ else {
279
+ // Shorthand, e.g. { list }
280
+ result[key] = { name: key };
281
+ }
282
+ this.space();
283
+ if (!this.accept(",")) {
284
+ this.expect("}");
285
+ break;
286
+ }
287
+ this.space();
288
+ }
289
+ return result;
290
+ }
291
+ // Skips spaces and comments
292
+ space() {
293
+ for (;;) {
294
+ const rest = this.s.substring(this.i, this.i + 2);
295
+ if (/^\s/.test(rest))
296
+ this.i++;
297
+ else if (rest == "//") {
298
+ const end = this.s.indexOf("\n", this.i);
299
+ this.i = end < 0 ? this.s.length : end;
300
+ }
301
+ else if (rest == "/*") {
302
+ const end = this.s.indexOf("*/", this.i + 2);
303
+ this.i = end < 0 ? this.s.length : end + 2;
304
+ }
305
+ else
306
+ return;
307
+ }
308
+ }
309
+ peek() {
310
+ return this.s[this.i] ?? "";
311
+ }
312
+ accept(c) {
313
+ if (this.s[this.i] != c)
314
+ return false;
315
+ this.i++;
316
+ return true;
317
+ }
318
+ expect(c) {
319
+ if (!this.accept(c))
320
+ throw new Error(`Expected ${c}`);
321
+ }
322
+ }
@@ -0,0 +1,24 @@
1
+ export interface TwinePassage {
2
+ name: string;
3
+ tags: string[];
4
+ text: string;
5
+ position?: [number, number];
6
+ size?: [number, number];
7
+ }
8
+ export type TwineFormat = "harlowe" | "sugarcube" | "other";
9
+ export interface TwineStory {
10
+ title: string;
11
+ formatName: string;
12
+ formatVersion: string;
13
+ format: TwineFormat;
14
+ start?: string;
15
+ passages: TwinePassage[];
16
+ stylesheet: string;
17
+ script: string;
18
+ }
19
+ export declare class TwineParseError extends Error {
20
+ }
21
+ export declare function formatOf(name: string): TwineFormat;
22
+ export declare function isTwineSource(text: string): boolean;
23
+ export declare function parseTwine(text: string): TwineStory;
24
+ export declare function decodeEntities(s: string): string;
@@ -0,0 +1,231 @@
1
+ // Reads a Twine story from Twee (Twee 3, and the older Twee 1/2 that Twine 1 and Tweego read)
2
+ // or from Twine's HTML (Twine 2's published or archive HTML, and Twine 1's), into one shape for
3
+ // the converters.
4
+ export class TwineParseError extends Error {
5
+ }
6
+ export function formatOf(name) {
7
+ const lower = name.toLowerCase();
8
+ if (lower.startsWith("harlowe"))
9
+ return "harlowe";
10
+ // Twine 1's formats (Sugarcane, Jonah) have <<macros>> like SugarCube's, which grew out of them
11
+ if (lower.startsWith("sugarcube") || lower == "sugarcane" || lower == "jonah" || lower == "")
12
+ return "sugarcube";
13
+ return "other";
14
+ }
15
+ // Whether some text looks like a Twine story, rather than any other HTML or text file
16
+ export function isTwineSource(text) {
17
+ return /<tw-storydata[\s>]/i.test(text) || /<div[^>]*\bid=["']storeArea["']/i.test(text) || /^::\s*\S/m.test(text);
18
+ }
19
+ export function parseTwine(text) {
20
+ if (/<tw-storydata[\s>]/i.test(text))
21
+ return parseTwine2Html(text);
22
+ if (/<div[^>]*\bid=["']storeArea["']/i.test(text))
23
+ return parseTwine1Html(text);
24
+ if (/^::/m.test(text))
25
+ return parseTwee(text);
26
+ throw new TwineParseError("This doesn't look like a Twine story: there's no story data in it.");
27
+ }
28
+ const entities = { amp: "&", lt: "<", gt: ">", quot: "\"", apos: "'", nbsp: " " };
29
+ export function decodeEntities(s) {
30
+ return s.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (match, entity) => {
31
+ if (entity[0] == "#") {
32
+ const code = entity[1] == "x" || entity[1] == "X" ? parseInt(entity.substring(2), 16) : parseInt(entity.substring(1), 10);
33
+ return Number.isFinite(code) ? String.fromCodePoint(code) : match;
34
+ }
35
+ return entities[entity.toLowerCase()] ?? match;
36
+ });
37
+ }
38
+ function attributes(tag) {
39
+ const result = {};
40
+ const regex = /([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g;
41
+ let match;
42
+ while ((match = regex.exec(tag))) {
43
+ result[match[1].toLowerCase()] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");
44
+ }
45
+ return result;
46
+ }
47
+ // "x,y" or "width,height", as Twine writes them
48
+ function pair(value) {
49
+ if (typeof value != "string")
50
+ return undefined;
51
+ const parts = value.split(",").map(n => Number(n.trim()));
52
+ return parts.length == 2 && parts.every(n => Number.isFinite(n)) ? [parts[0], parts[1]] : undefined;
53
+ }
54
+ // The passage's place on Twine's map, if it has one
55
+ function place(position, size) {
56
+ const p = pair(position);
57
+ if (!p)
58
+ return {};
59
+ const s = pair(size);
60
+ return s && s[0] > 0 && s[1] > 0 ? { position: p, size: s } : { position: p };
61
+ }
62
+ function splitTags(tags) {
63
+ return (tags ?? "").split(/\s+/).filter(t => t.length > 0);
64
+ }
65
+ // Separates the passages that hold the story's CSS and JavaScript, as Twine 1 and Twee do with
66
+ // tags, from the passages of the story itself.
67
+ function splitSpecial(passages, stylesheet, script) {
68
+ return passages.filter(p => {
69
+ if (p.tags.includes("stylesheet")) {
70
+ stylesheet.push(p.text);
71
+ return false;
72
+ }
73
+ if (p.tags.includes("script")) {
74
+ script.push(p.text);
75
+ return false;
76
+ }
77
+ return !p.tags.includes("Twine.private") && !p.tags.includes("annotation");
78
+ });
79
+ }
80
+ function parseTwine2Html(html) {
81
+ const storyTag = /<tw-storydata\b[^>]*>/i.exec(html);
82
+ const story = attributes(storyTag[0]);
83
+ const body = html.substring(storyTag.index + storyTag[0].length);
84
+ const end = body.search(/<\/tw-storydata>/i);
85
+ const data = end == -1 ? body : body.substring(0, end);
86
+ const stylesheet = [];
87
+ const script = [];
88
+ for (const match of data.matchAll(/<style\b([^>]*)>([\s\S]*?)<\/style>/gi)) {
89
+ if (/twine-user-stylesheet|text\/twine-css/i.test(match[1]))
90
+ stylesheet.push(decodeEntities(match[2]));
91
+ }
92
+ for (const match of data.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) {
93
+ if (/twine-user-script|text\/twine-javascript/i.test(match[1]))
94
+ script.push(decodeEntities(match[2]));
95
+ }
96
+ let start;
97
+ const passages = [];
98
+ for (const match of data.matchAll(/<tw-passagedata\b([^>]*)>([\s\S]*?)<\/tw-passagedata>/gi)) {
99
+ const a = attributes(match[1]);
100
+ const passage = { name: a.name ?? "", tags: splitTags(a.tags), text: decodeEntities(match[2]), ...place(a.position, a.size) };
101
+ if (a.pid !== undefined && a.pid == story.startnode)
102
+ start = passage.name;
103
+ passages.push(passage);
104
+ }
105
+ const formatName = story.format ?? "";
106
+ return {
107
+ title: story.name ?? "",
108
+ formatName,
109
+ formatVersion: story["format-version"] ?? "",
110
+ format: formatOf(formatName),
111
+ start,
112
+ passages: splitSpecial(passages, stylesheet, script),
113
+ stylesheet: stylesheet.join("\n\n").trim(),
114
+ script: script.join("\n\n").trim(),
115
+ };
116
+ }
117
+ function parseTwine1Html(html) {
118
+ const start = html.search(/<div[^>]*\bid=["']storeArea["']/i);
119
+ const data = html.substring(start);
120
+ const passages = [];
121
+ for (const match of data.matchAll(/<div\b([^>]*\btiddler=[^>]*)>([^<]*)<\/div>/gi)) {
122
+ const a = attributes(match[1]);
123
+ // Twine 1 escapes newlines and backslashes in passage text
124
+ const text = decodeEntities(match[2]).replace(/\\(.)/g, (_m, c) => c == "n" ? "\n" : c == "t" ? "\t" : c == "s" ? " " : c);
125
+ passages.push({ name: a.tiddler ?? "", tags: splitTags(a.tags), text, ...place(a["twine-position"], undefined) });
126
+ }
127
+ return fromTwee1Passages(passages);
128
+ }
129
+ // Twine 1 and Twee 1/2 keep the title and settings in passages
130
+ function fromTwee1Passages(all) {
131
+ const stylesheet = [];
132
+ const script = [];
133
+ const special = new Map();
134
+ const passages = splitSpecial(all, stylesheet, script).filter(p => {
135
+ if (["StoryTitle", "StorySettings", "StoryIncludes", "StoryData"].includes(p.name)) {
136
+ special.set(p.name, p.text);
137
+ return false;
138
+ }
139
+ return true;
140
+ });
141
+ let formatName = "";
142
+ let formatVersion = "";
143
+ let start;
144
+ const storyData = special.get("StoryData");
145
+ if (storyData) {
146
+ try {
147
+ const data = JSON.parse(storyData);
148
+ formatName = data.format ?? "";
149
+ formatVersion = data["format-version"] ?? "";
150
+ start = data.start;
151
+ }
152
+ catch {
153
+ // Treated as if there were no StoryData
154
+ }
155
+ }
156
+ if (!start && passages.some(p => p.name == "Start"))
157
+ start = "Start";
158
+ return {
159
+ title: (special.get("StoryTitle") ?? "").trim(),
160
+ formatName,
161
+ formatVersion,
162
+ format: formatOf(formatName),
163
+ start,
164
+ passages,
165
+ stylesheet: stylesheet.join("\n\n").trim(),
166
+ script: script.join("\n\n").trim(),
167
+ };
168
+ }
169
+ // Twee: each passage starts with a line ":: Name [tags] {metadata}". In names, \ escapes
170
+ // [ ] { } and \ itself. A line in a passage that would start with :: is written \::.
171
+ function parseTwee(text) {
172
+ const lines = text.replace(/\r\n?/g, "\n").split("\n");
173
+ const passages = [];
174
+ let current = null;
175
+ const finish = () => {
176
+ if (!current)
177
+ return;
178
+ // Twee separates passages with blank lines, which aren't part of the passage
179
+ while (current.lines.length && current.lines[current.lines.length - 1].trim() == "")
180
+ current.lines.pop();
181
+ const { lines, ...header } = current;
182
+ passages.push({ ...header, text: lines.join("\n") });
183
+ };
184
+ for (const line of lines) {
185
+ if (line.startsWith("::")) {
186
+ finish();
187
+ const header = parseTweeHeader(line.substring(2));
188
+ current = { ...header, lines: [] };
189
+ }
190
+ else if (current) {
191
+ current.lines.push(line.startsWith("\\::") ? line.substring(1) : line);
192
+ }
193
+ }
194
+ finish();
195
+ return fromTwee1Passages(passages);
196
+ }
197
+ // Twee 3 puts the passage's place on the map in its metadata, e.g. {"position":"600,400","size":"100,200"}
198
+ function parseTweeHeader(header) {
199
+ let name = "";
200
+ let i = 0;
201
+ const s = header.trimStart();
202
+ for (; i < s.length; i++) {
203
+ const c = s[i];
204
+ if (c == "\\" && i + 1 < s.length) {
205
+ name += s[++i];
206
+ }
207
+ else if (c == "[" || c == "{") {
208
+ break;
209
+ }
210
+ else {
211
+ name += c;
212
+ }
213
+ }
214
+ let tags = [];
215
+ const rest = s.substring(i);
216
+ const tagMatch = /^\[((?:\\.|[^\]])*)\]/.exec(rest);
217
+ if (tagMatch)
218
+ tags = splitTags(tagMatch[1].replace(/\\(.)/g, "$1"));
219
+ const metadata = rest.substring(tagMatch?.[0].length ?? 0).trim();
220
+ let placed = {};
221
+ if (metadata.startsWith("{")) {
222
+ try {
223
+ const data = JSON.parse(metadata);
224
+ placed = place(data?.position, data?.size);
225
+ }
226
+ catch {
227
+ // Metadata that isn't JSON is left out
228
+ }
229
+ }
230
+ return { name: name.trim(), tags, ...placed };
231
+ }
@@ -0,0 +1,40 @@
1
+ import type { Expr } from "./expression.js";
2
+ import type { StoryAudio } from "./audio.js";
3
+ import type { ConvertedPassage, PassageContext } from "./convert.js";
4
+ export declare class SugarCubeExpressions {
5
+ readonly ctx: PassageContext;
6
+ constructor(ctx: PassageContext);
7
+ attribute(name: string, temp: boolean): string;
8
+ variable(name: string, temp: boolean): Expr;
9
+ inContainerWidget: boolean;
10
+ parse(source: string): Expr;
11
+ statements(source: string): Statement[];
12
+ passageName(source: string): {
13
+ name: string;
14
+ } | {
15
+ expr: Expr;
16
+ };
17
+ }
18
+ export type Statement = {
19
+ kind: "set" | "inc" | "dec";
20
+ name: string;
21
+ value: Expr;
22
+ op?: "*=" | "/=";
23
+ } | {
24
+ kind: "append" | "remove";
25
+ name: string;
26
+ value: Expr;
27
+ } | {
28
+ kind: "unset";
29
+ name: string;
30
+ } | {
31
+ kind: "forget";
32
+ names: string[];
33
+ };
34
+ export declare function sugarCubeAudio(story: PassageContext["story"]): StoryAudio;
35
+ export declare function sugarCubeWidgets(story: PassageContext["story"]): Map<string, string>;
36
+ export declare function convertSugarCubeWidgets(text: string, ctx: PassageContext): {
37
+ section: string;
38
+ converted: ConvertedPassage;
39
+ }[];
40
+ export declare function convertSugarCubePassage(text: string, ctx: PassageContext): ConvertedPassage;