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,1057 @@
1
+ // Converts a Twine story (#378) into a Squiffy story: each passage becomes a section, and the
2
+ // passage's macros, in Harlowe or SugarCube, become Squiffy's {{...}} helpers, @set and links.
3
+ // Like the Squiffy 5 converter (v5.ts), this is a pure function with no I/O: the CLI and the
4
+ // editor write the files it returns. Anything that can't be converted is kept as a comment in
5
+ // the story and listed as a problem, so the author can deal with it by hand.
6
+ import { attributeRef, print, quote, Unconvertible } from "./expression.js";
7
+ import { convertHarlowePassage, harloweAudioPassages, harloweMacros } from "./harlowe.js";
8
+ import { convertSugarCubePassage, convertSugarCubeWidgets, sugarCubeWidgets } from "./sugarcube.js";
9
+ import { parseTwine } from "./story.js";
10
+ import { sugarCubeSettings } from "./settings.js";
11
+ import { formatProjectFile } from "../project.js";
12
+ // The Squiffy names that would be read as a helper, rather than an attribute, in {{name}} and
13
+ // expressions, and the ones Squiffy sets itself
14
+ export const reservedAttributes = new Set([
15
+ "get", "set", "unset", "inc", "dec", "seen", "visits", "at", "goto", "embed", "array", "random", "contains",
16
+ "length", "append", "prepend", "pop", "remove", "section", "passage", "label", "replace", "rotate", "sequence",
17
+ "live", "animate", "eq", "ne", "gt", "gte", "lt", "lte", "and", "or", "not", "add", "sub", "mul", "div", "mod",
18
+ "round", "floor", "ceil", "abs", "min", "max", "upper", "lower", "capitalise", "capitalize", "cond",
19
+ "join", "sort", "shuffle", "slice", "first", "last", "indexof", "count", "range",
20
+ "if", "unless", "each", "with", "lookup", "log", "else", "this", "turns", "previous", "previous_section",
21
+ "true", "false", "null", "undefined", "music", "stopmusic", "sound", "stopsounds",
22
+ "addclass", "removeclass", "toggleclass", "hasclass", "content", "restart", "saves", "settings", "style",
23
+ "passages", "sections", "tags", "lastvisited",
24
+ ]);
25
+ export class StoryContext {
26
+ constructor(twine, passages) {
27
+ Object.defineProperty(this, "twine", {
28
+ enumerable: true,
29
+ configurable: true,
30
+ writable: true,
31
+ value: twine
32
+ });
33
+ Object.defineProperty(this, "problems", {
34
+ enumerable: true,
35
+ configurable: true,
36
+ writable: true,
37
+ value: []
38
+ });
39
+ // Twine passage name -> Squiffy section name
40
+ Object.defineProperty(this, "sectionNames", {
41
+ enumerable: true,
42
+ configurable: true,
43
+ writable: true,
44
+ value: new Map()
45
+ });
46
+ Object.defineProperty(this, "usedSectionNames", {
47
+ enumerable: true,
48
+ configurable: true,
49
+ writable: true,
50
+ value: new Set()
51
+ });
52
+ Object.defineProperty(this, "usedLabels", {
53
+ enumerable: true,
54
+ configurable: true,
55
+ writable: true,
56
+ value: new Set()
57
+ });
58
+ // Sections added by the converter, as Squiffy text, to go at the end of the story
59
+ Object.defineProperty(this, "extraSections", {
60
+ enumerable: true,
61
+ configurable: true,
62
+ writable: true,
63
+ value: []
64
+ });
65
+ Object.defineProperty(this, "permanentVars", {
66
+ enumerable: true,
67
+ configurable: true,
68
+ writable: true,
69
+ value: new Set()
70
+ });
71
+ Object.defineProperty(this, "passagesByName", {
72
+ enumerable: true,
73
+ configurable: true,
74
+ writable: true,
75
+ value: new Map()
76
+ });
77
+ // <style>s and <script>s from passages, for the story's CSS and JavaScript files (#455)
78
+ Object.defineProperty(this, "passageStyles", {
79
+ enumerable: true,
80
+ configurable: true,
81
+ writable: true,
82
+ value: []
83
+ });
84
+ Object.defineProperty(this, "passageScripts", {
85
+ enumerable: true,
86
+ configurable: true,
87
+ writable: true,
88
+ value: []
89
+ });
90
+ // The attributes for the keys SugarCube's memorize(), recall() and forget() use, which are
91
+ // squiffy.json's "persistent" (#539)
92
+ Object.defineProperty(this, "persistent", {
93
+ enumerable: true,
94
+ configurable: true,
95
+ writable: true,
96
+ value: new Set()
97
+ });
98
+ Object.defineProperty(this, "problemKeys", {
99
+ enumerable: true,
100
+ configurable: true,
101
+ writable: true,
102
+ value: new Set()
103
+ });
104
+ // SugarCube's setup.x values that passages set, e.g. in StoryInit, which become properties of
105
+ // a setup attribute. Those the story's JavaScript sets stay as they are, since an attribute
106
+ // wouldn't have them.
107
+ Object.defineProperty(this, "setupValues", {
108
+ enumerable: true,
109
+ configurable: true,
110
+ writable: true,
111
+ value: new Set()
112
+ });
113
+ Object.defineProperty(this, "trimmed", {
114
+ enumerable: true,
115
+ configurable: true,
116
+ writable: true,
117
+ value: void 0
118
+ });
119
+ Object.defineProperty(this, "cache", {
120
+ enumerable: true,
121
+ configurable: true,
122
+ writable: true,
123
+ value: new Map()
124
+ });
125
+ // Problems that are the same wherever they happen, listed once for the story, with the code
126
+ // they happened for
127
+ Object.defineProperty(this, "notes", {
128
+ enumerable: true,
129
+ configurable: true,
130
+ writable: true,
131
+ value: new Map()
132
+ });
133
+ // The loops being converted to {{#each}}, innermost last, with the Twine variables (with their
134
+ // $ or _) that stand for each one's item and position. numbers: its items are numbers, as in
135
+ // a loop that counts. A link's body (see linkBody) is an entry with setters, and no variables.
136
+ Object.defineProperty(this, "loops", {
137
+ enumerable: true,
138
+ configurable: true,
139
+ writable: true,
140
+ value: []
141
+ });
142
+ for (const p of passages) {
143
+ this.passagesByName.set(p.name, p);
144
+ }
145
+ // Passages keep their names where they can: a name that's only taken once it's been
146
+ // tidied up (Room [1] and Room (1)) gets a number, avoiding every other passage's name
147
+ const wanted = passages.map(p => sanitiseName(p.name) || "Untitled");
148
+ const counts = new Map();
149
+ for (const name of wanted)
150
+ counts.set(name, (counts.get(name) ?? 0) + 1);
151
+ passages.forEach((p, n) => {
152
+ if (counts.get(wanted[n]) == 1) {
153
+ this.sectionNames.set(p.name, wanted[n]);
154
+ this.usedSectionNames.add(wanted[n]);
155
+ }
156
+ });
157
+ // Then the passages whose names were already right, then the rest
158
+ passages.forEach((p, n) => {
159
+ if (!this.sectionNames.has(p.name) && p.name == wanted[n] && !this.usedSectionNames.has(p.name)) {
160
+ this.sectionNames.set(p.name, p.name);
161
+ this.usedSectionNames.add(p.name);
162
+ }
163
+ });
164
+ for (const p of passages) {
165
+ if (!this.sectionNames.has(p.name))
166
+ this.sectionNames.set(p.name, this.uniqueSectionName(p.name));
167
+ }
168
+ }
169
+ // Records a problem, once for each passage
170
+ addProblem(problem) {
171
+ const key = `${problem.passage}\u0000${problem.text}\u0000${problem.reason}`;
172
+ if (this.problemKeys.has(key))
173
+ return;
174
+ this.problemKeys.add(key);
175
+ this.problems.push(problem);
176
+ }
177
+ notePermanentVar(name) {
178
+ this.permanentVars.add(name);
179
+ }
180
+ noteSetupValues(text) {
181
+ for (const set of text.matchAll(/<<set\s([\s\S]*?)>>/g)) {
182
+ for (const m of set[1].matchAll(/(?<![\w.$])setup\.([A-Za-z_]\w*)\s*(?:to\b|=(?!=))/g)) {
183
+ if (!new RegExp(`(?<![\\w.$])setup\\.${m[1]}\\s*=(?!=)`).test(this.twine.script))
184
+ this.setupValues.add(m[1]);
185
+ }
186
+ }
187
+ }
188
+ // The Squiffy section for a Twine passage, or undefined if there's no such passage
189
+ sectionFor(passageName) {
190
+ // Twine passage names can start or end with spaces, which links often leave out
191
+ return this.sectionNames.get(passageName) ?? this.trimmedNames().get(passageName.trim());
192
+ }
193
+ trimmedNames() {
194
+ if (!this.trimmed) {
195
+ this.trimmed = new Map();
196
+ for (const [name, section] of this.sectionNames) {
197
+ if (!this.trimmed.has(name.trim()))
198
+ this.trimmed.set(name.trim(), section);
199
+ }
200
+ }
201
+ return this.trimmed;
202
+ }
203
+ // A value worked out once for the story, e.g. by a format's converter
204
+ cached(key, make) {
205
+ if (!this.cache.has(key))
206
+ this.cache.set(key, make());
207
+ return this.cache.get(key);
208
+ }
209
+ note(key, text, reason) {
210
+ let note = this.notes.get(key);
211
+ if (!note) {
212
+ note = { reason, texts: new Set() };
213
+ this.notes.set(key, note);
214
+ }
215
+ note.texts.add(text);
216
+ }
217
+ noteProblems() {
218
+ return [...this.notes.values()].map(n => ({ text: [...n.texts].join(", "), reason: n.reason + "." }));
219
+ }
220
+ // A Squiffy section name for a passage name that isn't known (a broken link): it's
221
+ // tidied up the same way, so the editor shows the broken link as it was meant
222
+ sectionForUnknown(passageName) {
223
+ return this.sectionFor(passageName) ?? sanitiseName(passageName);
224
+ }
225
+ uniqueSectionName(hint) {
226
+ const base = sanitiseName(hint) || "Untitled";
227
+ let name = base;
228
+ for (let n = 2; this.usedSectionNames.has(name); n++)
229
+ name = `${base} ${n}`;
230
+ this.usedSectionNames.add(name);
231
+ return name;
232
+ }
233
+ newLabel(hint) {
234
+ const base = hint.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").substring(0, 24) || "label";
235
+ let name = base;
236
+ for (let n = 2; this.usedLabels.has(name); n++)
237
+ name = `${base}-${n}`;
238
+ this.usedLabels.add(name);
239
+ return name;
240
+ }
241
+ inLoop(vars, array, convert, numbers = false) {
242
+ this.loops.push({ vars, array, numbers });
243
+ try {
244
+ return convert();
245
+ }
246
+ finally {
247
+ this.loops.pop();
248
+ }
249
+ }
250
+ // Whether a loop is being converted, or a link's body inside one
251
+ get inAnyLoop() {
252
+ return this.loops.length > 0;
253
+ }
254
+ // Converts the body of a link, which runs when it's clicked, after its loop has finished. In
255
+ // there, the loop's item and position are attributes, which the link sets to that item's (#448).
256
+ // Returns the setters for the link.
257
+ linkBody(convert) {
258
+ if (!this.loops.length || this.loops[this.loops.length - 1].setters)
259
+ return { result: convert(), setters: [] };
260
+ const setters = new Map();
261
+ this.loops.push({ vars: new Map(), setters });
262
+ try {
263
+ return { result: convert(), setters: [...setters.values()] };
264
+ }
265
+ finally {
266
+ this.loops.pop();
267
+ }
268
+ }
269
+ loopVariable(name, temporary) {
270
+ const key = (temporary ? "_" : "$") + name;
271
+ for (let i = this.loops.length - 1; i >= 0; i--) {
272
+ const loop = this.loops[i];
273
+ if (loop.setters) {
274
+ // In a link's body: the variables of the link's own loop are attributes now
275
+ const own = this.loops[i - 1];
276
+ const kind = own.vars.get(key);
277
+ if (kind) {
278
+ const attribute = this.attributeName(name, temporary);
279
+ // Like a link's other setters, an item is text, unless the loop counts
280
+ const value = kind == "index" ? "{{@index}}" : own.numbers ? "{{this}}" : "'{{this}}'";
281
+ loop.setters.set(attribute, `${attribute} = ${value}`);
282
+ return { k: "var", name: attribute };
283
+ }
284
+ if (this.loops.slice(0, i - 1).some(l => l.vars.has(key))) {
285
+ throw new Unconvertible("a link in a loop inside another loop that uses the outer loop's item");
286
+ }
287
+ return undefined;
288
+ }
289
+ const kind = loop.vars.get(key);
290
+ if (kind)
291
+ return { k: "loop", kind, up: this.loops.length - 1 - i, array: loop.array, numbers: loop.numbers };
292
+ }
293
+ return undefined;
294
+ }
295
+ // A Twine variable's value: its attribute, or inside a loop, the loop's item or position
296
+ variable(name, temporary) {
297
+ return this.loopVariable(name, temporary) ?? { k: "var", name: this.attribute(name, temporary) };
298
+ }
299
+ // The Squiffy attribute for a Twine variable, given without its $ or _: a temporary (_)
300
+ // variable keeps its name unless a story variable ($) has the same name
301
+ attribute(name, temporary) {
302
+ if (this.loopVariable(name, temporary))
303
+ throw new Unconvertible("changing a loop's variable inside the loop");
304
+ return this.attributeName(name, temporary);
305
+ }
306
+ // The persistent attribute for a key given to memorize(), recall() or forget()
307
+ persistentAttribute(key) {
308
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(key))
309
+ throw new Unconvertible(`memorize(), recall() or forget() with a key that isn't a name ("${key}")`);
310
+ const name = this.attributeName(key, false);
311
+ this.persistent.add(name);
312
+ return name;
313
+ }
314
+ attributeName(name, temporary) {
315
+ let result = name;
316
+ if (temporary && this.permanentVars.has(name))
317
+ result = "temp_" + name;
318
+ if (reservedAttributes.has(result))
319
+ result += "_";
320
+ return result;
321
+ }
322
+ }
323
+ const reservedSectionChars = /[[\]{}|"]/g;
324
+ // Twine allows anything in a passage name, but in Squiffy some characters would break a link,
325
+ // e.g. [[text]](a, b) sets an attribute b, and ] or | would end the link early
326
+ export function sanitiseName(name) {
327
+ let result = name
328
+ .replace(/\[/g, "(").replace(/\]/g, ")")
329
+ .replace(/\{/g, "(").replace(/\}/g, ")")
330
+ .replace(reservedSectionChars, "")
331
+ .replace(/,/g, "")
332
+ .replace(/\s+/g, " ")
333
+ .trim();
334
+ // A name ending in > would be a link to the next section
335
+ result = result.replace(/>+$/, "").trim();
336
+ // Brackets in a link's target have to balance
337
+ let depth = 0;
338
+ let balanced = true;
339
+ for (const c of result) {
340
+ if (c == "(")
341
+ depth++;
342
+ else if (c == ")" && --depth < 0)
343
+ balanced = false;
344
+ }
345
+ if (!balanced || depth != 0)
346
+ result = result.replace(/[()]/g, "").replace(/\s+/g, " ").trim();
347
+ // @ at the start of a passage name means something to Squiffy, so keep sections clear of it
348
+ if (result.startsWith("@"))
349
+ result = result.substring(1).trim();
350
+ return result;
351
+ }
352
+ // Text that came from the story, made safe to put in Squiffy text: square brackets would be
353
+ // links, {{ a helper, and some characters at the start of a line mean something to the compiler
354
+ export function escapeText(text) {
355
+ return text
356
+ .replace(/\[/g, "&#91;")
357
+ .replace(/\]/g, "&#93;")
358
+ .replace(/\{\{/g, "&#123;{")
359
+ .replace(/\}\}/g, "}&#125;");
360
+ }
361
+ // A link to a section. text is Squiffy text (already escaped); target is a Squiffy section name.
362
+ // Square brackets in a link's text, which would end the link, as entities. Those in a {{...}} are
363
+ // kept, as the compiler leaves them alone, and an expression needs them, as in {{#if [my flag]}}.
364
+ export function escapeLinkBrackets(text) {
365
+ return text.split(/(\{\{[\s\S]*?\}\})/).map((part, i) => i % 2 ? part : part.replace(/\]/g, "&#93;").replace(/\[/g, "&#91;")).join("");
366
+ }
367
+ export function sectionLink(text, target, setters = []) {
368
+ const linkText = text == null ? null : escapeLinkBrackets(text);
369
+ if (setters.length == 0 && (linkText == null || linkText == target) && !target.endsWith(">")) {
370
+ return `[[${target}]]`;
371
+ }
372
+ return `[[${linkText ?? target}]](${[target, ...setters].join(", ")})`;
373
+ }
374
+ // A link to a web page, from a Twine link like [[https://example.com]]
375
+ export function isUrl(target) {
376
+ return /^(https?|mailto):/i.test(target.trim());
377
+ }
378
+ export function urlLink(text, url) {
379
+ const href = url.trim().replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/\[/g, "%5B").replace(/\]/g, "%5D");
380
+ return `<a href="${href}" target="_blank">${text}</a>`;
381
+ }
382
+ // A link to a section whose name is worked out as the story runs
383
+ export function dynamicSectionLink(text, target, setters = []) {
384
+ // quote() would break the {{this}} of a loop's item
385
+ if (setters.some(s => s.includes("{{")))
386
+ throw new Unconvertible("a link in a loop, to a passage worked out as the story runs, that sets a variable to the loop's item");
387
+ const set = setters.length ? ` set=${quote(setters.join(", "))}` : "";
388
+ return `{{section ${print(target)} text=${quote(text)}${set}}}`;
389
+ }
390
+ export function passageLink(text, target, setters = []) {
391
+ const linkText = text.replace(/\]/g, "&#93;").replace(/\[/g, "&#91;");
392
+ return `[${linkText}](${[target, ...setters].join(", ")})`;
393
+ }
394
+ // A Squiffy setter, as in @set or a link, for name = value
395
+ export function setter(name, op, value, inLink) {
396
+ return `${attributeRef(name)} ${op} ${print(value, { preferSingle: inLink, inLink })}`;
397
+ }
398
+ // A comment in the story, for Twine code that couldn't be converted. Handlebars comments can't
399
+ // contain --}}, and line breaks would let the compiler read a line of it as something else.
400
+ export function comment(text) {
401
+ const clean = text.replace(/--\}\}/g, "-- }}").replace(/\s*\n\s*/g, " ").trim();
402
+ return `{{!-- Twine: ${clean} --}}`;
403
+ }
404
+ // SugarCube's passages for its sidebar that become panels beside the story (#443), in the order
405
+ // SugarCube shows them, with the labels of the buttons they have on a narrow screen
406
+ const sugarCubePanels = { StoryBanner: "Banner", StoryCaption: "Status" };
407
+ // Passages a format treats specially, which aren't part of the story as sections
408
+ // (StorySubtitle, StoryAuthor and so on are kept, as their text might be included elsewhere)
409
+ const sugarCubeSpecial = new Set(["StoryMenu", "StoryInterface", "StoryShare", "StoryTitle", "StoryData", "StorySettings"]);
410
+ // The problems as a text file, to keep with the converted story: the ones about the whole story,
411
+ // then each passage's, in the order of the story
412
+ export function formatTwineProblems(result, sourceName) {
413
+ const lines = [
414
+ `Converted ${sourceName ?? "a Twine story"}${result.format ? ` (${result.format})` : ""} to Squiffy: ${result.passages} passage${result.passages == 1 ? "" : "s"}.`,
415
+ "",
416
+ ];
417
+ if (result.problems.length == 0) {
418
+ lines.push("Everything was converted.");
419
+ return lines.join("\n") + "\n";
420
+ }
421
+ lines.push(`${result.problems.length} thing${result.problems.length == 1 ? "" : "s"} couldn't be converted exactly. Where something couldn't be converted at all, the story has the`, "Twine code in a comment, {{!-- Twine: ... --}}, so you can search for \"Twine:\" to find them.", "");
422
+ let passage = "\u0000";
423
+ for (const p of result.problems) {
424
+ if (p.passage !== passage) {
425
+ passage = p.passage;
426
+ lines.push(passage === undefined ? "The whole story:" : `${passage}:`);
427
+ }
428
+ lines.push(` ${p.text}`, ` ${p.reason}`);
429
+ }
430
+ return lines.join("\n") + "\n";
431
+ }
432
+ export function convertTwine(source, options = {}) {
433
+ return convertTwineStory(parseTwine(source), options);
434
+ }
435
+ export function convertTwineStory(twine, options = {}) {
436
+ const name = options.name ?? "story";
437
+ const harlowe = twine.format == "harlowe";
438
+ const problems = [];
439
+ if (twine.format == "other") {
440
+ problems.push({
441
+ text: twine.formatName,
442
+ reason: `The story uses the ${twine.formatName} story format. Only Harlowe and SugarCube stories can be converted, so its passages have been converted as if it were SugarCube.`,
443
+ });
444
+ }
445
+ // Passages that are part of every passage, or that run at the start, rather than sections
446
+ const headers = [];
447
+ const footers = [];
448
+ const startup = [];
449
+ const widgets = [];
450
+ const skipped = [];
451
+ const panelPassages = [];
452
+ const storyPassages = [];
453
+ const seenNames = new Set();
454
+ for (const p of twine.passages) {
455
+ if (seenNames.has(p.name)) {
456
+ problems.push({ passage: p.name, text: p.name, reason: "There's more than one passage with this name. Only the first has been converted." });
457
+ continue;
458
+ }
459
+ seenNames.add(p.name);
460
+ if (harlowe) {
461
+ if (p.tags.includes("header"))
462
+ headers.push(p);
463
+ else if (p.tags.includes("footer"))
464
+ footers.push(p);
465
+ else if (p.tags.includes("startup"))
466
+ startup.push(p);
467
+ else if (p.tags.some(t => t.startsWith("debug-")))
468
+ skipped.push(p);
469
+ // The Harlowe Audio Library's tracks and settings, which are read where they're used
470
+ else if (harloweAudioPassages.has(p.name))
471
+ continue;
472
+ else
473
+ storyPassages.push(p);
474
+ }
475
+ else {
476
+ if (p.name == "PassageHeader" || p.name == "PassageReady")
477
+ headers.push(p);
478
+ else if (p.name == "PassageFooter" || p.name == "PassageDone")
479
+ footers.push(p);
480
+ else if (p.name == "StoryInit")
481
+ startup.push(p);
482
+ else if (p.tags.includes("widget"))
483
+ widgets.push(p);
484
+ else if (sugarCubeSpecial.has(p.name))
485
+ skipped.push(p);
486
+ else if (p.name in sugarCubePanels)
487
+ panelPassages.push(p);
488
+ else {
489
+ if (["StorySubtitle", "StoryAuthor", "StoryDisplayTitle"].includes(p.name)) {
490
+ problems.push({ passage: p.name, text: p.name, reason: "Squiffy has no sidebar, so this passage is an ordinary section, which nothing links to." });
491
+ }
492
+ storyPassages.push(p);
493
+ }
494
+ }
495
+ }
496
+ // Footers are embedded at the end of every section, so they need sections of their own
497
+ const sectionPassages = [...storyPassages, ...footers];
498
+ // Temporary variables keep their names unless a story variable has the same name
499
+ const story = new StoryContext(twine, sectionPassages);
500
+ for (const p of twine.passages) {
501
+ for (const m of p.text.matchAll(/\$([A-Za-z_]\w*)/g))
502
+ story.notePermanentVar(m[1]);
503
+ if (!harlowe)
504
+ story.noteSetupValues(p.text);
505
+ }
506
+ // Widgets become sections, which calls to them embed. They're named before anything's
507
+ // converted, so calls know where they go.
508
+ sugarCubeWidgets(story);
509
+ // Harlowe's custom macros (#450) too
510
+ if (harlowe)
511
+ harloweMacros(story);
512
+ for (const p of skipped) {
513
+ problems.push({
514
+ passage: p.name, text: p.name,
515
+ reason: p.name == "StoryMenu"
516
+ ? "Squiffy has no sidebar, so this passage has been left out. Its links go to passages, which a panel can't do, but a panel can show a passage in the master section [[]] from a button in the header: see \"panels\" in squiffy.json."
517
+ : "This special passage has been left out.",
518
+ });
519
+ }
520
+ const context = (passage, section, extraPassages, kind) => ({
521
+ story,
522
+ passage,
523
+ kind,
524
+ section,
525
+ unconvertible(text, reason) {
526
+ story.addProblem({ passage: passage.name, text: oneLine(text), reason });
527
+ return comment(text);
528
+ },
529
+ approximate(text, reason) {
530
+ story.addProblem({ passage: passage.name, text: oneLine(text), reason });
531
+ },
532
+ addPassage(hint, content) {
533
+ const reserved = this.reservePassage(hint);
534
+ reserved.fill(content);
535
+ return reserved.name;
536
+ },
537
+ reservePassage(hint) {
538
+ const base = sanitisePassageName(hint) || "more";
539
+ let name = base;
540
+ for (let n = 2; extraPassages.some(p => p.startsWith(`[${name}]:\n`)) || name == section; n++)
541
+ name = `${base} ${n}`;
542
+ const index = extraPassages.length;
543
+ extraPassages.push(`[${name}]:\n`);
544
+ return {
545
+ name,
546
+ fill: content => {
547
+ // Left out, rather than empty, if it can't be converted
548
+ extraPassages[index] = "";
549
+ extraPassages[index] = `[${name}]:\n${generated(content)}`;
550
+ },
551
+ };
552
+ },
553
+ addSection(hint, content) {
554
+ const name = story.uniqueSectionName(hint);
555
+ this.fillSection(name, content);
556
+ return name;
557
+ },
558
+ fillSection(name, content) {
559
+ story.extraSections.push(`[[${name}]]:\n${generated(content)}`);
560
+ },
561
+ newLabel: hint => story.newLabel(hint),
562
+ });
563
+ const convert = (passage, section, extraPassages, kind) => {
564
+ const ctx = context(passage, section, extraPassages, kind);
565
+ try {
566
+ return harlowe ? convertHarlowePassage(passage.text, ctx) : convertSugarCubePassage(passage.text, ctx);
567
+ }
568
+ catch (e) {
569
+ if (!(e instanceof Unconvertible))
570
+ throw e;
571
+ return { directives: [], body: ctx.unconvertible(passage.text, `This passage couldn't be converted: ${e.message}.`) };
572
+ }
573
+ };
574
+ const startPassage = twine.start && story.sectionFor(twine.start) ? twine.start : storyPassages[0]?.name;
575
+ const startSection = startPassage === undefined ? undefined : story.sectionFor(startPassage);
576
+ // The master section: one screen per passage, as in Twine, and the header passages
577
+ const masterPassages = [];
578
+ const master = { directives: ["@clear"], body: "" };
579
+ for (const p of headers) {
580
+ const converted = convert(p, "", masterPassages, "header");
581
+ master.directives.push(...converted.directives);
582
+ if (converted.body.trim())
583
+ master.body += converted.body.trim() + "\n";
584
+ }
585
+ // SugarCube's sidebar passages, as panels beside the story, rendered again after each passage
586
+ sortPanelPassages(panelPassages);
587
+ const panels = [];
588
+ for (const p of panelPassages) {
589
+ const converted = convert(p, "", masterPassages, "panel");
590
+ let passageName = p.name;
591
+ for (let n = 2; masterPassages.some(text => text.startsWith(`[${passageName}]:\n`)); n++)
592
+ passageName = `${p.name} ${n}`;
593
+ const body = converted.body.trim();
594
+ if (converted.directives.length) {
595
+ story.addProblem({ passage: p.name, text: converted.directives.join(" "), reason: "A panel only shows its text, so this doesn't run." });
596
+ }
597
+ if (/\[\[|\]\(|\{\{(section|passage)\b/.test(body)) {
598
+ story.addProblem({ passage: p.name, text: p.name, reason: "This is a panel beside the story, where links don't work." });
599
+ }
600
+ masterPassages.push(`[${passageName}]:\n${finishText(body)}`.trimEnd());
601
+ panels.push({ passage: passageName, label: sugarCubePanels[p.name], position: "side" });
602
+ }
603
+ // Passages that run once at the start
604
+ const init = { directives: [], body: "" };
605
+ for (const p of startup) {
606
+ const converted = convert(p, startSection ?? "", [], "startup");
607
+ init.directives.push(...converted.directives);
608
+ if (converted.body.trim())
609
+ init.body += converted.body.trim() + "\n";
610
+ }
611
+ const footerEmbeds = footers.map(p => `{{embed ${quote(story.sectionFor(p.name))}}}`);
612
+ const sections = [];
613
+ for (const p of sectionPassages) {
614
+ const section = story.sectionFor(p.name);
615
+ const extraPassages = [];
616
+ const converted = convert(p, section, extraPassages, footers.includes(p) ? "footer" : "story");
617
+ const directives = [...converted.directives];
618
+ // Its tags (#449), which Twine puts on the page for the stylesheet
619
+ const classes = footers.includes(p) ? [] : tagClasses(p.tags);
620
+ if (classes.length)
621
+ directives.push(`@class ${classes.join(" ")}`);
622
+ // And as @tag, so the story can list its passages by them, as with (passages tagged="x") (#527)
623
+ const tags = tagClasses(p.tags);
624
+ if (tags.length)
625
+ directives.push(`@tag ${tags.join(" ")}`);
626
+ let body = converted.body.trim();
627
+ if (p.name == startPassage && (init.directives.length || init.body)) {
628
+ directives.unshift(...init.directives);
629
+ body = (init.body + body).trim();
630
+ }
631
+ if (!footers.includes(p) && footerEmbeds.length) {
632
+ body = (body + "\n" + footerEmbeds.join("\n")).trim();
633
+ }
634
+ sections.push([`[[${section}]]:\n${block({ directives, body })}`.trimEnd(), ...extraPassages.filter(p => p)].join("\n\n"));
635
+ }
636
+ for (const p of widgets) {
637
+ const extraPassages = [];
638
+ let converted;
639
+ try {
640
+ converted = convertSugarCubeWidgets(p.text, context(p, "", extraPassages, "widget"));
641
+ }
642
+ catch (e) {
643
+ if (!(e instanceof Unconvertible))
644
+ throw e;
645
+ problems.push({ passage: p.name, text: p.name, reason: `This widget passage couldn't be converted: ${e.message}.` });
646
+ continue;
647
+ }
648
+ for (const w of converted) {
649
+ sections.push([`[[${w.section}]]:\n${block(w.converted)}`, ...extraPassages.filter(p => p)].join("\n\n"));
650
+ extraPassages.length = 0;
651
+ }
652
+ }
653
+ const files = {};
654
+ const header = [];
655
+ if (twine.title)
656
+ header.push(`@title ${twine.title.replace(/\s+/g, " ").trim()}`);
657
+ if (startSection !== undefined)
658
+ header.push(`@start ${startSection}`);
659
+ // The stylesheet, with the <style>s from passages (#455). squiffy.json makes it part of the story.
660
+ const passageStyles = story.passageStyles.filter(s => s.css).map(s => `/* From the passage "${s.passage.replace(/\*\//g, "* /")}" */\n${s.css}`);
661
+ const stylesheet = [twine.stylesheet, ...passageStyles].filter(s => s).join("\n\n");
662
+ if (stylesheet) {
663
+ const tagged = convertTagSelectors(stylesheet);
664
+ const converted = convertTwineSelectors(tagged);
665
+ files[`${name}.css`] = converted.css + "\n";
666
+ const reason = [`The story's stylesheet is in ${name}.css${passageStyles.length ? ", with the <style>s from its passages" : ""}.`];
667
+ if (converted.translated.length) {
668
+ reason.push(`Its rules for Twine's ${list(converted.translated)} are now for Squiffy's own page, sections and links.`);
669
+ }
670
+ if (converted.untranslated.length) {
671
+ // SugarCube's sidebar and dialogs can have a dozen, so only the first few are named
672
+ const shown = converted.untranslated.length > 5 ? [...converted.untranslated.slice(0, 4), `${converted.untranslated.length - 4} more`] : converted.untranslated;
673
+ reason.push(`Its rules for ${list(shown)} have nothing to match in Squiffy.`);
674
+ }
675
+ if (tagged != stylesheet)
676
+ reason.push("Its rules for passage tags now use the classes that @class puts on the story's element.");
677
+ reason.push("Check how it looks.");
678
+ problems.push({ text: `${name}.css`, reason: reason.join(" ") });
679
+ }
680
+ // SugarCube's player settings (#452), from the story's JavaScript
681
+ const settings = !harlowe && twine.script ? sugarCubeSettings(twine.script) : { settings: [], problems: [] };
682
+ problems.push(...settings.problems);
683
+ // The story's JavaScript is left out of it, as it was written for another story format
684
+ const exclude = [];
685
+ // With the <script>s from passages that can't run in Squiffy as they are (#455)
686
+ const passageScripts = story.passageScripts.map(s => `// From the passage "${s.passage}"\n${s.js}`);
687
+ const javaScript = [twine.script, ...passageScripts].filter(s => s).join("\n\n");
688
+ if (javaScript) {
689
+ files[`${name}.js`] = javaScript + "\n";
690
+ exclude.push(`${name}.js`);
691
+ problems.push({
692
+ text: `${name}.js`,
693
+ reason: `The story's JavaScript is in ${name}.js, but it isn't part of the story yet, since it was written for ${twine.formatName || "Twine"}. To use it, change it to work with Squiffy, then remove "${name}.js" from "exclude" in squiffy.json (in the editor, choose Include in story from its menu in the files list).`,
694
+ });
695
+ }
696
+ const masterPassageText = masterPassages.length ? "\n\n" + masterPassages.join("\n\n") : "";
697
+ const script = [
698
+ header.join("\n"),
699
+ `[[]]:\n${block(master)}${masterPassageText}`,
700
+ ...sections,
701
+ ...story.extraSections,
702
+ ].filter(s => s.length).join("\n\n") + "\n";
703
+ files[`${name}.squiffy`] = script;
704
+ const map = mapPositions(sectionPassages, story);
705
+ files["squiffy.json"] = formatProjectFile({ main: `${name}.squiffy`, exclude, panels, settings: settings.settings, persistent: [...story.persistent], ...(map ? { map } : {}) });
706
+ return {
707
+ title: twine.title,
708
+ format: `${twine.formatName} ${twine.formatVersion}`.trim(),
709
+ files,
710
+ main: `${name}.squiffy`,
711
+ passages: sectionPassages.length,
712
+ problems: [...problems, ...story.noteProblems(), ...story.problems],
713
+ };
714
+ }
715
+ // SugarCube's sidebar passages in the order SugarCube shows them
716
+ function sortPanelPassages(passages) {
717
+ const order = Object.keys(sugarCubePanels);
718
+ passages.sort((a, b) => order.indexOf(a.name) - order.indexOf(b.name));
719
+ }
720
+ // Where the sections go on the editor's story map, so it looks like the story's map in Twine.
721
+ // Twine's boxes are 100 by 100, on a grid of 25, and usually 125 apart; the map's are short and
722
+ // wide, up to 190 across, so the map is stretched sideways to keep them from overlapping (which
723
+ // leaves only a handful overlapping in real games). Undefined if the story's passages have no
724
+ // places on the map, or have never been arranged.
725
+ const MAP_STRETCH = 1.6;
726
+ function mapPositions(passages, story) {
727
+ const placed = passages.filter(p => p.position);
728
+ if (!placed.length || unarranged(story.twine.passages))
729
+ return undefined;
730
+ const centres = placed.map(p => {
731
+ const [w, h] = p.size ?? [100, 100];
732
+ return { name: story.sectionFor(p.name), x: p.position[0] + w / 2, y: p.position[1] + h / 2 };
733
+ });
734
+ const left = Math.min(...centres.map(c => c.x));
735
+ const top = Math.min(...centres.map(c => c.y));
736
+ const sections = {};
737
+ for (const c of centres)
738
+ sections[c.name] = [Math.round((c.x - left) * MAP_STRETCH), Math.round(c.y - top)];
739
+ return { sections, passages: {} };
740
+ }
741
+ // Whether the passages are where Twine or Tweego put them when the story was made from Twee
742
+ // without positions: in rows of ten, 125 apart. A map like that says nothing about the story, and
743
+ // the editor's own layout is better. It still counts if the author's moved one or two.
744
+ function unarranged(passages) {
745
+ const positions = passages.flatMap(p => p.position ? [p.position] : []);
746
+ if (positions.length < 10)
747
+ return false;
748
+ const left = Math.min(...positions.map(p => p[0]));
749
+ const top = Math.min(...positions.map(p => p[1]));
750
+ const onGrid = positions.filter(([x, y]) => (x - left) % 125 == 0 && (y - top) % 125 == 0 && x - left < 1250);
751
+ const columns = new Set(onGrid.map(([x]) => x));
752
+ return columns.size == 10 && onGrid.length >= positions.length * 0.9;
753
+ }
754
+ // Tags that mean something to Harlowe, SugarCube or Twine itself, rather than ones the story
755
+ // gave its passages
756
+ const SPECIAL_TAGS = new Set(["header", "footer", "startup", "widget", "nobr", "init", "stylesheet", "script"]);
757
+ // A passage's tags, which become @class (#449): Harlowe and SugarCube put them on the page
758
+ export function tagClasses(tags) {
759
+ return [...new Set(tags.filter(t => !SPECIAL_TAGS.has(t) && !t.startsWith("debug-") && !t.startsWith("Twine.")))];
760
+ }
761
+ // A class name in a CSS selector, escaped if it needs to be
762
+ function cssClass(name) {
763
+ if (/^-?[A-Za-z_][\w-]*$/.test(name))
764
+ return "." + name;
765
+ return "." + [...name].map((c, i) => {
766
+ if (/[\w-]/.test(c) && !(i == 0 && /\d/.test(c)))
767
+ return c;
768
+ if (/\d/.test(c))
769
+ return `\\${c.charCodeAt(0).toString(16)} `;
770
+ return "\\" + c;
771
+ }).join("");
772
+ }
773
+ // Rules for passage tags (#449), e.g. tw-story[tags~="dark"] in Harlowe or
774
+ // body[data-tags~="dark"] in SugarCube, become rules for the classes @class puts on the story's
775
+ // element, as do SugarCube's classes on the body (from tags, or <<addclass "body">>). In Twine,
776
+ // tw-story, html and body are the whole page, so they become body:has(.dark), and the passage
777
+ // becomes the story's element.
778
+ export function convertTagSelectors(css) {
779
+ return css
780
+ .replace(/(\b(?:tw-story|html|body)|tw-passage|\.passage|#passages|#story)?((?:\[\s*(?:data-)?tags\s*~=\s*(["']?)[^"'\]\s]+\3\s*\])+)/g, (_, element, attributes) => {
781
+ const classes = [...attributes.matchAll(/~=\s*(["']?)([^"'\]\s]+)\1/g)].map(m => cssClass(m[2])).join("");
782
+ return element && /^(?:tw-story|html|body)$/.test(element) ? `body:has(${classes})` : classes;
783
+ })
784
+ .replace(/(^|[\s,>+~(}])body((?:\.[\w-]+)+)/g, "$1body:has($2)");
785
+ }
786
+ // The <script> or <style> at src[i], and where it ends
787
+ export function readHtmlBlock(src, i) {
788
+ const open = /^<(script|style)\b([^>]*)>/i.exec(src.substring(i));
789
+ if (!open)
790
+ return undefined;
791
+ const tag = open[1].toLowerCase();
792
+ const close = src.toLowerCase().indexOf(`</${tag}>`, i + open[0].length);
793
+ const end = close == -1 ? src.length : close + tag.length + 3;
794
+ const content = src.substring(i + open[0].length, close == -1 ? src.length : close);
795
+ return { block: { t: "html", tag, raw: src.substring(i, end), attributes: open[2], content }, end };
796
+ }
797
+ // JavaScript that uses the story format's own objects, such as SugarCube's State and setup, or
798
+ // jQuery, which Squiffy doesn't have
799
+ const formatJavaScript = /\b(?:State|setup|Engine|Story|Config|Macro|Save|UI|UIBar|Dialog|Settings?|SimpleAudio|Wikifier|Template|LoadScreen|Scripting|Harlowe|SugarCube|V|T)\s*\.|\b(?:variables|temporary|visited|visitedTags|passage|previous|tags|turns|jQuery|either|random|randomFloat|lastVisited|memorize|recall|forget)\s*\(|\$\s*\(|\$\.\w/;
800
+ // A <style> in a passage goes in the story's stylesheet. A <script> at the start of a passage
801
+ // (top) runs when its section is shown, once its text is on the page, as it would in Twine, and
802
+ // the directive that does that is returned. One that uses the story format's JavaScript, or is
803
+ // inside a macro or hook so it only ran some of the time, goes in the story's JavaScript file,
804
+ // which isn't part of the story.
805
+ export function passageHtmlBlock(ctx, block, top) {
806
+ const story = ctx.story;
807
+ if (block.tag == "style") {
808
+ story.passageStyles.push({ passage: ctx.passage.name, css: block.content.trim() });
809
+ ctx.approximate("<style>", "This is in the story's stylesheet now, so it applies all the time, not only while this passage is shown.");
810
+ return { text: "" };
811
+ }
812
+ if (/\bsrc\s*=/i.test(block.attributes)) {
813
+ return { text: ctx.unconvertible(block.raw, "A <script> that loads a file isn't run by Squiffy. Add the file to the story's folder instead.") };
814
+ }
815
+ const js = block.content.replace(/^\s*\n|\s+$/g, "");
816
+ if (!js.trim())
817
+ return { text: "" };
818
+ if (!top || formatJavaScript.test(js)) {
819
+ story.passageScripts.push({ passage: ctx.passage.name, js });
820
+ ctx.approximate("<script>", top
821
+ ? "This <script> uses the story format's JavaScript, which Squiffy doesn't have, so it's in the story's JavaScript file, which isn't part of the story."
822
+ : "This <script> only ran some of the time, so it's in the story's JavaScript file, which isn't part of the story.");
823
+ return { text: "" };
824
+ }
825
+ ctx.approximate("<script>", "This runs when the section is shown, once its text is on the page. Check it still works.");
826
+ // A blank line would end the JavaScript, so blank lines are left out
827
+ const lines = dedent(js).split("\n").filter(l => l.trim());
828
+ return { text: "", directive: [" squiffy.ui.afterWrite(() => {", ...lines.map(l => " " + l), " });"].join("\n") };
829
+ }
830
+ // A passage's nodes, with the <script>s that aren't inside a macro or hook taken out and their
831
+ // JavaScript added to its directives
832
+ export function topScripts(ctx, nodes, directives) {
833
+ return nodes.map(n => {
834
+ if (n.t != "html" || n.tag != "script")
835
+ return n;
836
+ const { text, directive } = passageHtmlBlock(ctx, n, true);
837
+ if (directive)
838
+ directives.push(directive);
839
+ return { t: "raw", s: text };
840
+ });
841
+ }
842
+ // Lines with the indent they all have taken off
843
+ function dedent(text) {
844
+ const lines = text.split("\n");
845
+ const indent = Math.min(...lines.filter(l => l.trim()).map(l => /^[ \t]*/.exec(l)[0].length));
846
+ return lines.map(l => l.substring(Math.min(indent, /^[ \t]*/.exec(l)[0].length))).join("\n");
847
+ }
848
+ // Twine's elements in a stylesheet, and the Squiffy elements their rules are for now (#455). In
849
+ // Harlowe, tw-story is the whole page and tw-passage the passage; in SugarCube, #story holds
850
+ // #passages, which holds the .passage. A Twine passage is a Squiffy section.
851
+ const twineSelectors = [
852
+ [/(?<![\w#.-])tw-story(?![\w-])/g, "body", "tw-story"],
853
+ [/(?<![\w#.-])tw-passage(?![\w-])/g, ".squiffy-output-section", "tw-passage"],
854
+ [/(?<![\w#.-])tw-link(?![\w-])/g, ".squiffy-link", "tw-link"],
855
+ [/\.enchantment-link(?![\w-])/g, ".squiffy-link", ".enchantment-link"],
856
+ [/(?<![\w#.-])tw-sidebar(?![\w-])/g, "#squiffy-header", "tw-sidebar"],
857
+ [/#story(?![\w-])/g, "#squiffy-container", "#story"],
858
+ [/#passages(?![\w-])/g, "#squiffy", "#passages"],
859
+ [/\.passage(?![\w-])/g, ".squiffy-output-section", ".passage"],
860
+ [/\.(?:link-internal|macro-link)(?![\w-])/g, ".squiffy-link", ".link-internal"],
861
+ ];
862
+ // Twine's elements that have nothing like them in Squiffy
863
+ const otherTwineSelectors = /(?<![\w#.-])tw-[\w-]+|#(?:ui-[\w-]+|menu[\w-]*|story-[\w-]+)(?![\w-])/g;
864
+ // A stylesheet with its rules for Twine's elements changed to be for Squiffy's (#455), and the
865
+ // Twine elements it had rules for, changed or not. Only selectors change, not what's in the rules.
866
+ export function convertTwineSelectors(css) {
867
+ const translated = new Set();
868
+ const untranslated = new Set();
869
+ const selector = (text) => {
870
+ for (const [pattern, squiffy, twine] of twineSelectors) {
871
+ text = text.replace(pattern, () => {
872
+ translated.add(twine);
873
+ return squiffy;
874
+ });
875
+ }
876
+ for (const m of text.matchAll(otherTwineSelectors))
877
+ untranslated.add(m[0]);
878
+ return text;
879
+ };
880
+ let out = "";
881
+ let prelude = "";
882
+ // Whether each block that's open is a rule's declarations, or holds rules, like @media
883
+ const blocks = [];
884
+ for (let i = 0; i < css.length; i++) {
885
+ const c = css[i];
886
+ const inRule = blocks.length > 0 && blocks[blocks.length - 1];
887
+ let skip = 0;
888
+ if (c == "/" && css[i + 1] == "*") {
889
+ const end = css.indexOf("*/", i + 2);
890
+ skip = (end == -1 ? css.length : end + 2) - i;
891
+ }
892
+ else if (c == "\"" || c == "'") {
893
+ let j = i + 1;
894
+ while (j < css.length && css[j] != c && css[j] != "\n")
895
+ j += css[j] == "\\" ? 2 : 1;
896
+ skip = j + 1 - i;
897
+ }
898
+ if (skip) {
899
+ // A comment or string goes into the prelude, so a selector isn't changed inside one
900
+ if (inRule)
901
+ out += css.substring(i, i + skip);
902
+ else
903
+ prelude += css.substring(i, i + skip);
904
+ i += skip - 1;
905
+ continue;
906
+ }
907
+ if (inRule) {
908
+ if (c == "{")
909
+ blocks.push(true);
910
+ else if (c == "}")
911
+ blocks.pop();
912
+ out += c;
913
+ continue;
914
+ }
915
+ if (c == "{") {
916
+ const atRule = prelude.trimStart().startsWith("@");
917
+ out += (atRule ? prelude : selectorOutsideComments(prelude, selector)) + c;
918
+ prelude = "";
919
+ blocks.push(!atRule);
920
+ }
921
+ else if (c == "}" || c == ";") {
922
+ out += prelude + c;
923
+ prelude = "";
924
+ if (c == "}")
925
+ blocks.pop();
926
+ }
927
+ else
928
+ prelude += c;
929
+ }
930
+ return { css: out + prelude, translated: [...translated], untranslated: [...untranslated] };
931
+ }
932
+ // "a, b and c"
933
+ function list(items) {
934
+ return items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
935
+ }
936
+ // A selector changed, leaving its comments and strings as they are
937
+ function selectorOutsideComments(text, change) {
938
+ return text.split(/(\/\*[\s\S]*?(?:\*\/|$)|"(?:[^"\\\n]|\\.)*"?|'(?:[^'\\\n]|\\.)*'?)/).map((part, n) => n % 2 ? part : change(part)).join("");
939
+ }
940
+ // The text of a section or passage: its directives, then its text
941
+ function block(content) {
942
+ const c = typeof content == "string" ? { directives: [], body: content } : content;
943
+ // JavaScript goes after the directives, before the text
944
+ const js = (d) => /^\s/.test(d);
945
+ return [...c.directives.filter(d => !js(d)), ...c.directives.filter(js), finishText(c.body)].filter(l => l.length).join("\n");
946
+ }
947
+ // A passage or section made for a link. It's shown on its own, after the link's loop has finished,
948
+ // so it can't use the loop's item or position: StoryContext.linkBody makes them attributes instead.
949
+ function generated(content) {
950
+ const c = typeof content == "string" ? { directives: [], body: content } : content;
951
+ // Directives are expressions, rather than text with {{...}} in it
952
+ if (c.directives.some(d => usesOuterLoop(`{{${d}}}`)) || usesOuterLoop(c.body)) {
953
+ throw new Unconvertible("a link in a loop that does more than set variables to the loop's item");
954
+ }
955
+ return block(c);
956
+ }
957
+ // Whether Squiffy text uses the item or position of a loop it isn't in
958
+ export function usesOuterLoop(text) {
959
+ let depth = 0;
960
+ // Comments keep the Twine code, which can have "this" in it
961
+ for (const tag of text.replace(/\{\{!--[\s\S]*?--\}\}/g, "").matchAll(/\{\{([\s\S]*?)\}\}/g)) {
962
+ // Text in quotes isn't a reference
963
+ const inner = tag[1].replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/g, "\"\"");
964
+ if (inner.startsWith("/each")) {
965
+ depth--;
966
+ continue;
967
+ }
968
+ for (const ref of inner.matchAll(/(?<![\w$@.])((?:\.\.\/)*)this\b|@((?:\.\.\/)*)index\b/g)) {
969
+ const up = (ref[1] ?? ref[2] ?? "").length / 3;
970
+ if (up >= depth)
971
+ return true;
972
+ }
973
+ if (inner.startsWith("#each"))
974
+ depth++;
975
+ }
976
+ return false;
977
+ }
978
+ // A name for a generated passage, from a link's text, which can have markup in it
979
+ function sanitisePassageName(name) {
980
+ const plain = name
981
+ .replace(/\{\{[\s\S]*?\}\}/g, "")
982
+ .replace(/\([\w-]+:[^()]*(\([^()]*\)[^()]*)*\)/g, "")
983
+ .replace(/<[^>]*>|&#?\w+;|''|\/\/|[*_~^]/g, "")
984
+ .replace(/[$_]\w+/g, "")
985
+ .replace(/[[\]]/g, " ");
986
+ let result = sanitiseName(plain).replace(/:/g, "").trim();
987
+ if (result.length > 40)
988
+ result = result.substring(0, 40).replace(/\s+\S*$/, "");
989
+ return result.trim();
990
+ }
991
+ function oneLine(text) {
992
+ const line = text.replace(/\s+/g, " ").trim();
993
+ return line.length > 120 ? line.substring(0, 117) + "..." : line;
994
+ }
995
+ // Directives the compiler would read at the start of a line
996
+ const directiveLine = /^@(title|import|start|set|unset|inc|dec|ui|clear|end|class)\b/;
997
+ // Lines that only hold helpers that write nothing
998
+ const silentHelper = /\{\{(?:!--[\s\S]*?--|![^}]*|~?\s*(?:#if|#unless|#once|#firsttime|else|\/if|\/unless|\/once|\/firsttime|set|unset|inc|dec|goto|clear|music|stopmusic|sound|stopsounds|addclass|removeclass|toggleclass|append|prepend|remove|#label|\/label|#replace|\/replace|#animate|\/animate)\b(?:[^{}]|\{\{[^{}]*\}\})*)\}\}/g;
999
+ function isSilent(line) {
1000
+ return line.replace(silentHelper, "").trim() == "";
1001
+ }
1002
+ // Markdown that starts a block, which can't be joined to the line before with <br>
1003
+ function isBlockLine(line) {
1004
+ return /^(#{1,6}\s|[*+-]\s|\d+\.\s|<hr>|<\/?(div|p|ul|ol|li|table|tr|td|th|h\d|blockquote|pre|center|section|article|br)\b)/i.test(line)
1005
+ || /<\/(div|p|ul|ol|table|h\d|blockquote|pre|center|section|article)>\s*$/i.test(line);
1006
+ }
1007
+ // Tidies converted passage text into lines the compiler reads as text. In Twine, each line
1008
+ // break in a passage is a line break in the story, but in Markdown a single line break is just a
1009
+ // space, so lines that follow each other get a <br>.
1010
+ export function finishText(text) {
1011
+ const lines = text.replace(/\r/g, "").split("\n").map(line => {
1012
+ let l = line.trim();
1013
+ if (/^-{3,}$/.test(l))
1014
+ return "<hr>";
1015
+ if (directiveLine.test(l))
1016
+ l = "&#64;" + l.substring(1);
1017
+ if (l.startsWith("+++"))
1018
+ l = "&#43;" + l.substring(1);
1019
+ if (l.startsWith(">"))
1020
+ l = "&gt;" + l.substring(1);
1021
+ // A link on its own followed by a colon would be read as a section or passage header
1022
+ if (/^\[.*\]:$/.test(l))
1023
+ l = l.substring(0, l.length - 1) + "&#58;";
1024
+ return l;
1025
+ });
1026
+ // Collapse runs of blank lines
1027
+ const collapsed = [];
1028
+ for (const line of lines) {
1029
+ if (line == "" && (collapsed.length == 0 || collapsed[collapsed.length - 1] == ""))
1030
+ continue;
1031
+ collapsed.push(line);
1032
+ }
1033
+ while (collapsed.length && collapsed[collapsed.length - 1] == "")
1034
+ collapsed.pop();
1035
+ for (let i = 0; i < collapsed.length - 1; i++) {
1036
+ const line = collapsed[i];
1037
+ if (line == "" || isSilent(line) || isBlockLine(line) || line.endsWith("<br>"))
1038
+ continue;
1039
+ // The next line that writes something, if it's straight after this one
1040
+ let j = i + 1;
1041
+ while (j < collapsed.length && collapsed[j] != "" && isSilent(collapsed[j]))
1042
+ j++;
1043
+ if (j >= collapsed.length || collapsed[j] == "" || isBlockLine(collapsed[j]))
1044
+ continue;
1045
+ collapsed[i] = line + "<br>";
1046
+ }
1047
+ // A backslash before {{ would stop Handlebars reading it as a helper
1048
+ return tidyMarkup(collapsed.join("\n")).replace(/\\(?=\{\{)/g, "&#92;");
1049
+ }
1050
+ // Turns simple HTML emphasis into Markdown, which is easier to read and edit
1051
+ function tidyMarkup(text) {
1052
+ return text
1053
+ .replace(/<b>([^<>*\n\s](?:[^<>*\n]*[^<>*\n\s])?)<\/b>/g, "**$1**")
1054
+ .replace(/<strong>([^<>*\n\s](?:[^<>*\n]*[^<>*\n\s])?)<\/strong>/g, "**$1**")
1055
+ .replace(/<i>([^<>*_\n\s](?:[^<>*_\n]*[^<>*_\n\s])?)<\/i>/g, "_$1_")
1056
+ .replace(/<em>([^<>*_\n\s](?:[^<>*_\n]*[^<>*_\n\s])?)<\/em>/g, "_$1_");
1057
+ }