squiffy-compiler 7.0.0-beta.4 → 7.0.0-beta.5

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.
@@ -0,0 +1,626 @@
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 } from "./harlowe.js";
8
+ import { convertSugarCubePassage, convertSugarCubeWidgets, sugarCubeWidgets } from "./sugarcube.js";
9
+ import { parseTwine } from "./story.js";
10
+ import { formatProjectFile } from "../project.js";
11
+ // The Squiffy names that would be read as a helper, rather than an attribute, in {{name}} and
12
+ // expressions, and the ones Squiffy sets itself
13
+ const reservedAttributes = new Set([
14
+ "get", "set", "unset", "inc", "dec", "seen", "visits", "at", "goto", "embed", "array", "random", "contains",
15
+ "length", "append", "prepend", "pop", "remove", "section", "passage", "label", "replace", "rotate", "sequence",
16
+ "live", "animate", "eq", "ne", "gt", "gte", "lt", "lte", "and", "or", "not", "add", "sub", "mul", "div", "mod",
17
+ "if", "unless", "each", "with", "lookup", "log", "else", "this", "turns", "true", "false", "null", "undefined",
18
+ ]);
19
+ export class StoryContext {
20
+ constructor(twine, passages) {
21
+ Object.defineProperty(this, "twine", {
22
+ enumerable: true,
23
+ configurable: true,
24
+ writable: true,
25
+ value: twine
26
+ });
27
+ Object.defineProperty(this, "problems", {
28
+ enumerable: true,
29
+ configurable: true,
30
+ writable: true,
31
+ value: []
32
+ });
33
+ // Twine passage name -> Squiffy section name
34
+ Object.defineProperty(this, "sectionNames", {
35
+ enumerable: true,
36
+ configurable: true,
37
+ writable: true,
38
+ value: new Map()
39
+ });
40
+ Object.defineProperty(this, "usedSectionNames", {
41
+ enumerable: true,
42
+ configurable: true,
43
+ writable: true,
44
+ value: new Set()
45
+ });
46
+ Object.defineProperty(this, "usedLabels", {
47
+ enumerable: true,
48
+ configurable: true,
49
+ writable: true,
50
+ value: new Set()
51
+ });
52
+ // Sections added by the converter, as Squiffy text, to go at the end of the story
53
+ Object.defineProperty(this, "extraSections", {
54
+ enumerable: true,
55
+ configurable: true,
56
+ writable: true,
57
+ value: []
58
+ });
59
+ Object.defineProperty(this, "permanentVars", {
60
+ enumerable: true,
61
+ configurable: true,
62
+ writable: true,
63
+ value: new Set()
64
+ });
65
+ Object.defineProperty(this, "passagesByName", {
66
+ enumerable: true,
67
+ configurable: true,
68
+ writable: true,
69
+ value: new Map()
70
+ });
71
+ Object.defineProperty(this, "problemKeys", {
72
+ enumerable: true,
73
+ configurable: true,
74
+ writable: true,
75
+ value: new Set()
76
+ });
77
+ Object.defineProperty(this, "trimmed", {
78
+ enumerable: true,
79
+ configurable: true,
80
+ writable: true,
81
+ value: void 0
82
+ });
83
+ Object.defineProperty(this, "cache", {
84
+ enumerable: true,
85
+ configurable: true,
86
+ writable: true,
87
+ value: new Map()
88
+ });
89
+ // Problems that are the same wherever they happen, listed once for the story, with the code
90
+ // they happened for
91
+ Object.defineProperty(this, "notes", {
92
+ enumerable: true,
93
+ configurable: true,
94
+ writable: true,
95
+ value: new Map()
96
+ });
97
+ for (const p of passages) {
98
+ this.passagesByName.set(p.name, p);
99
+ }
100
+ // Passages keep their names where they can: a name that's only taken once it's been
101
+ // tidied up (Room [1] and Room (1)) gets a number, avoiding every other passage's name
102
+ const wanted = passages.map(p => sanitiseName(p.name) || "Untitled");
103
+ const counts = new Map();
104
+ for (const name of wanted)
105
+ counts.set(name, (counts.get(name) ?? 0) + 1);
106
+ passages.forEach((p, n) => {
107
+ if (counts.get(wanted[n]) == 1) {
108
+ this.sectionNames.set(p.name, wanted[n]);
109
+ this.usedSectionNames.add(wanted[n]);
110
+ }
111
+ });
112
+ // Then the passages whose names were already right, then the rest
113
+ passages.forEach((p, n) => {
114
+ if (!this.sectionNames.has(p.name) && p.name == wanted[n] && !this.usedSectionNames.has(p.name)) {
115
+ this.sectionNames.set(p.name, p.name);
116
+ this.usedSectionNames.add(p.name);
117
+ }
118
+ });
119
+ for (const p of passages) {
120
+ if (!this.sectionNames.has(p.name))
121
+ this.sectionNames.set(p.name, this.uniqueSectionName(p.name));
122
+ }
123
+ }
124
+ // Records a problem, once for each passage
125
+ addProblem(problem) {
126
+ const key = `${problem.passage}\u0000${problem.text}\u0000${problem.reason}`;
127
+ if (this.problemKeys.has(key))
128
+ return;
129
+ this.problemKeys.add(key);
130
+ this.problems.push(problem);
131
+ }
132
+ notePermanentVar(name) {
133
+ this.permanentVars.add(name);
134
+ }
135
+ // The Squiffy section for a Twine passage, or undefined if there's no such passage
136
+ sectionFor(passageName) {
137
+ // Twine passage names can start or end with spaces, which links often leave out
138
+ return this.sectionNames.get(passageName) ?? this.trimmedNames().get(passageName.trim());
139
+ }
140
+ trimmedNames() {
141
+ if (!this.trimmed) {
142
+ this.trimmed = new Map();
143
+ for (const [name, section] of this.sectionNames) {
144
+ if (!this.trimmed.has(name.trim()))
145
+ this.trimmed.set(name.trim(), section);
146
+ }
147
+ }
148
+ return this.trimmed;
149
+ }
150
+ // A value worked out once for the story, e.g. by a format's converter
151
+ cached(key, make) {
152
+ if (!this.cache.has(key))
153
+ this.cache.set(key, make());
154
+ return this.cache.get(key);
155
+ }
156
+ note(key, text, reason) {
157
+ let note = this.notes.get(key);
158
+ if (!note) {
159
+ note = { reason, texts: new Set() };
160
+ this.notes.set(key, note);
161
+ }
162
+ note.texts.add(text);
163
+ }
164
+ noteProblems() {
165
+ return [...this.notes.values()].map(n => ({ text: [...n.texts].join(", "), reason: n.reason + "." }));
166
+ }
167
+ // A Squiffy section name for a passage name that isn't known (a broken link): it's
168
+ // tidied up the same way, so the editor shows the broken link as it was meant
169
+ sectionForUnknown(passageName) {
170
+ return this.sectionFor(passageName) ?? sanitiseName(passageName);
171
+ }
172
+ uniqueSectionName(hint) {
173
+ const base = sanitiseName(hint) || "Untitled";
174
+ let name = base;
175
+ for (let n = 2; this.usedSectionNames.has(name); n++)
176
+ name = `${base} ${n}`;
177
+ this.usedSectionNames.add(name);
178
+ return name;
179
+ }
180
+ newLabel(hint) {
181
+ const base = hint.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").substring(0, 24) || "label";
182
+ let name = base;
183
+ for (let n = 2; this.usedLabels.has(name); n++)
184
+ name = `${base}-${n}`;
185
+ this.usedLabels.add(name);
186
+ return name;
187
+ }
188
+ // The Squiffy attribute for a Twine variable, given without its $ or _: a temporary (_)
189
+ // variable keeps its name unless a story variable ($) has the same name
190
+ attribute(name, temporary) {
191
+ let result = name;
192
+ if (temporary && this.permanentVars.has(name))
193
+ result = "temp_" + name;
194
+ if (reservedAttributes.has(result))
195
+ result += "_";
196
+ return result;
197
+ }
198
+ }
199
+ const reservedSectionChars = /[[\]{}|"]/g;
200
+ // Twine allows anything in a passage name, but in Squiffy some characters would break a link,
201
+ // e.g. [[text]](a, b) sets an attribute b, and ] or | would end the link early
202
+ export function sanitiseName(name) {
203
+ let result = name
204
+ .replace(/\[/g, "(").replace(/\]/g, ")")
205
+ .replace(/\{/g, "(").replace(/\}/g, ")")
206
+ .replace(reservedSectionChars, "")
207
+ .replace(/,/g, "")
208
+ .replace(/\s+/g, " ")
209
+ .trim();
210
+ // A name ending in > would be a link to the next section
211
+ result = result.replace(/>+$/, "").trim();
212
+ // Brackets in a link's target have to balance
213
+ let depth = 0;
214
+ let balanced = true;
215
+ for (const c of result) {
216
+ if (c == "(")
217
+ depth++;
218
+ else if (c == ")" && --depth < 0)
219
+ balanced = false;
220
+ }
221
+ if (!balanced || depth != 0)
222
+ result = result.replace(/[()]/g, "").replace(/\s+/g, " ").trim();
223
+ // @ at the start of a passage name means something to Squiffy, so keep sections clear of it
224
+ if (result.startsWith("@"))
225
+ result = result.substring(1).trim();
226
+ return result;
227
+ }
228
+ // Text that came from the story, made safe to put in Squiffy text: square brackets would be
229
+ // links, {{ a helper, and some characters at the start of a line mean something to the compiler
230
+ export function escapeText(text) {
231
+ return text
232
+ .replace(/\[/g, "&#91;")
233
+ .replace(/\]/g, "&#93;")
234
+ .replace(/\{\{/g, "&#123;{")
235
+ .replace(/\}\}/g, "}&#125;");
236
+ }
237
+ // A link to a section. text is Squiffy text (already escaped); target is a Squiffy section name.
238
+ export function sectionLink(text, target, setters = []) {
239
+ const linkText = text == null ? null : text.replace(/\]/g, "&#93;").replace(/\[/g, "&#91;");
240
+ if (setters.length == 0 && (linkText == null || linkText == target) && !target.endsWith(">")) {
241
+ return `[[${target}]]`;
242
+ }
243
+ return `[[${linkText ?? target}]](${[target, ...setters].join(", ")})`;
244
+ }
245
+ // A link to a web page, from a Twine link like [[https://example.com]]
246
+ export function isUrl(target) {
247
+ return /^(https?|mailto):/i.test(target.trim());
248
+ }
249
+ export function urlLink(text, url) {
250
+ const href = url.trim().replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/\[/g, "%5B").replace(/\]/g, "%5D");
251
+ return `<a href="${href}" target="_blank">${text}</a>`;
252
+ }
253
+ // A link to a section whose name is worked out as the story runs
254
+ export function dynamicSectionLink(text, target, setters = []) {
255
+ const set = setters.length ? ` set=${quote(setters.join(", "))}` : "";
256
+ return `{{section ${print(target)} text=${quote(text)}${set}}}`;
257
+ }
258
+ export function passageLink(text, target) {
259
+ const linkText = text.replace(/\]/g, "&#93;").replace(/\[/g, "&#91;");
260
+ return `[${linkText}](${target})`;
261
+ }
262
+ // A Squiffy setter, as in @set or a link, for name = value
263
+ export function setter(name, op, value, inLink) {
264
+ return `${attributeRef(name)} ${op} ${print(value, { preferSingle: inLink })}`;
265
+ }
266
+ // A comment in the story, for Twine code that couldn't be converted. Handlebars comments can't
267
+ // contain --}}, and line breaks would let the compiler read a line of it as something else.
268
+ export function comment(text) {
269
+ const clean = text.replace(/--\}\}/g, "-- }}").replace(/\s*\n\s*/g, " ").trim();
270
+ return `{{!-- Twine: ${clean} --}}`;
271
+ }
272
+ // Passages a format treats specially, which aren't part of the story as sections
273
+ // (StoryCaption, StoryBanner and so on are kept, as their text might be included elsewhere)
274
+ const sugarCubeSpecial = new Set(["StoryMenu", "StoryInterface", "StoryShare", "StoryTitle", "StoryData", "StorySettings"]);
275
+ // The problems as a text file, to keep with the converted story: the ones about the whole story,
276
+ // then each passage's, in the order of the story
277
+ export function formatTwineProblems(result, sourceName) {
278
+ const lines = [
279
+ `Converted ${sourceName ?? "a Twine story"}${result.format ? ` (${result.format})` : ""} to Squiffy: ${result.passages} passage${result.passages == 1 ? "" : "s"}.`,
280
+ "",
281
+ ];
282
+ if (result.problems.length == 0) {
283
+ lines.push("Everything was converted.");
284
+ return lines.join("\n") + "\n";
285
+ }
286
+ 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.", "");
287
+ let passage = "\u0000";
288
+ for (const p of result.problems) {
289
+ if (p.passage !== passage) {
290
+ passage = p.passage;
291
+ lines.push(passage === undefined ? "The whole story:" : `${passage}:`);
292
+ }
293
+ lines.push(` ${p.text}`, ` ${p.reason}`);
294
+ }
295
+ return lines.join("\n") + "\n";
296
+ }
297
+ export function convertTwine(source, options = {}) {
298
+ return convertTwineStory(parseTwine(source), options);
299
+ }
300
+ export function convertTwineStory(twine, options = {}) {
301
+ const name = options.name ?? "story";
302
+ const harlowe = twine.format == "harlowe";
303
+ const problems = [];
304
+ if (twine.format == "other") {
305
+ problems.push({
306
+ text: twine.formatName,
307
+ 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.`,
308
+ });
309
+ }
310
+ // Passages that are part of every passage, or that run at the start, rather than sections
311
+ const headers = [];
312
+ const footers = [];
313
+ const startup = [];
314
+ const widgets = [];
315
+ const skipped = [];
316
+ const storyPassages = [];
317
+ const seenNames = new Set();
318
+ for (const p of twine.passages) {
319
+ if (seenNames.has(p.name)) {
320
+ problems.push({ passage: p.name, text: p.name, reason: "There's more than one passage with this name. Only the first has been converted." });
321
+ continue;
322
+ }
323
+ seenNames.add(p.name);
324
+ if (harlowe) {
325
+ if (p.tags.includes("header"))
326
+ headers.push(p);
327
+ else if (p.tags.includes("footer"))
328
+ footers.push(p);
329
+ else if (p.tags.includes("startup"))
330
+ startup.push(p);
331
+ else if (p.tags.some(t => t.startsWith("debug-")))
332
+ skipped.push(p);
333
+ else
334
+ storyPassages.push(p);
335
+ }
336
+ else {
337
+ if (p.name == "PassageHeader" || p.name == "PassageReady")
338
+ headers.push(p);
339
+ else if (p.name == "PassageFooter" || p.name == "PassageDone")
340
+ footers.push(p);
341
+ else if (p.name == "StoryInit")
342
+ startup.push(p);
343
+ else if (p.tags.includes("widget"))
344
+ widgets.push(p);
345
+ else if (sugarCubeSpecial.has(p.name))
346
+ skipped.push(p);
347
+ else {
348
+ if (["StoryCaption", "StoryBanner", "StorySubtitle", "StoryAuthor", "StoryDisplayTitle"].includes(p.name)) {
349
+ problems.push({ passage: p.name, text: p.name, reason: "Squiffy has no sidebar or banner, so this passage is an ordinary section, which nothing links to." });
350
+ }
351
+ storyPassages.push(p);
352
+ }
353
+ }
354
+ }
355
+ // Footers are embedded at the end of every section, so they need sections of their own
356
+ const sectionPassages = [...storyPassages, ...footers];
357
+ // Temporary variables keep their names unless a story variable has the same name
358
+ const story = new StoryContext(twine, sectionPassages);
359
+ for (const p of twine.passages) {
360
+ for (const m of p.text.matchAll(/\$([A-Za-z_]\w*)/g))
361
+ story.notePermanentVar(m[1]);
362
+ }
363
+ // Widgets become sections, which calls to them embed. They're named before anything's
364
+ // converted, so calls know where they go.
365
+ sugarCubeWidgets(story);
366
+ for (const p of skipped) {
367
+ problems.push({
368
+ passage: p.name, text: p.name,
369
+ reason: p.name == "StoryMenu" ? "Squiffy has no sidebar, so this passage has been left out." : "This special passage has been left out.",
370
+ });
371
+ }
372
+ const context = (passage, section, extraPassages) => ({
373
+ story,
374
+ passage,
375
+ section,
376
+ unconvertible(text, reason) {
377
+ story.addProblem({ passage: passage.name, text: oneLine(text), reason });
378
+ return comment(text);
379
+ },
380
+ approximate(text, reason) {
381
+ story.addProblem({ passage: passage.name, text: oneLine(text), reason });
382
+ },
383
+ addPassage(hint, content) {
384
+ const reserved = this.reservePassage(hint);
385
+ reserved.fill(content);
386
+ return reserved.name;
387
+ },
388
+ reservePassage(hint) {
389
+ const base = sanitisePassageName(hint) || "more";
390
+ let name = base;
391
+ for (let n = 2; extraPassages.some(p => p.startsWith(`[${name}]:\n`)) || name == section; n++)
392
+ name = `${base} ${n}`;
393
+ const index = extraPassages.length;
394
+ extraPassages.push(`[${name}]:\n`);
395
+ return { name, fill: content => extraPassages[index] = `[${name}]:\n${block(content)}` };
396
+ },
397
+ addSection(hint, content) {
398
+ const name = story.uniqueSectionName(hint);
399
+ story.extraSections.push(`[[${name}]]:\n${block(content)}`);
400
+ return name;
401
+ },
402
+ newLabel: hint => story.newLabel(hint),
403
+ });
404
+ const convert = (passage, section, extraPassages) => {
405
+ const ctx = context(passage, section, extraPassages);
406
+ try {
407
+ return harlowe ? convertHarlowePassage(passage.text, ctx) : convertSugarCubePassage(passage.text, ctx);
408
+ }
409
+ catch (e) {
410
+ if (!(e instanceof Unconvertible))
411
+ throw e;
412
+ return { directives: [], body: ctx.unconvertible(passage.text, `This passage couldn't be converted: ${e.message}.`) };
413
+ }
414
+ };
415
+ const startPassage = twine.start && story.sectionFor(twine.start) ? twine.start : storyPassages[0]?.name;
416
+ const startSection = startPassage === undefined ? undefined : story.sectionFor(startPassage);
417
+ // The master section: one screen per passage, as in Twine, and the header passages
418
+ const masterPassages = [];
419
+ const master = { directives: ["@clear"], body: "" };
420
+ for (const p of headers) {
421
+ const converted = convert(p, "", masterPassages);
422
+ master.directives.push(...converted.directives);
423
+ if (converted.body.trim())
424
+ master.body += converted.body.trim() + "\n";
425
+ }
426
+ // Passages that run once at the start
427
+ const init = { directives: [], body: "" };
428
+ for (const p of startup) {
429
+ const converted = convert(p, startSection ?? "", []);
430
+ init.directives.push(...converted.directives);
431
+ if (converted.body.trim())
432
+ init.body += converted.body.trim() + "\n";
433
+ }
434
+ const footerEmbeds = footers.map(p => `{{embed ${quote(story.sectionFor(p.name))}}}`);
435
+ const sections = [];
436
+ for (const p of sectionPassages) {
437
+ const section = story.sectionFor(p.name);
438
+ const extraPassages = [];
439
+ const converted = convert(p, section, extraPassages);
440
+ const directives = [...converted.directives];
441
+ let body = converted.body.trim();
442
+ if (p.name == startPassage && (init.directives.length || init.body)) {
443
+ directives.unshift(...init.directives);
444
+ body = (init.body + body).trim();
445
+ }
446
+ if (!footers.includes(p) && footerEmbeds.length) {
447
+ body = (body + "\n" + footerEmbeds.join("\n")).trim();
448
+ }
449
+ sections.push([`[[${section}]]:\n${block({ directives, body })}`.trimEnd(), ...extraPassages].join("\n\n"));
450
+ }
451
+ for (const p of widgets) {
452
+ const extraPassages = [];
453
+ let converted;
454
+ try {
455
+ converted = convertSugarCubeWidgets(p.text, context(p, "", extraPassages));
456
+ }
457
+ catch (e) {
458
+ if (!(e instanceof Unconvertible))
459
+ throw e;
460
+ problems.push({ passage: p.name, text: p.name, reason: `This widget passage couldn't be converted: ${e.message}.` });
461
+ continue;
462
+ }
463
+ for (const w of converted) {
464
+ sections.push([`[[${w.section}]]:\n${block(w.converted)}`, ...extraPassages].join("\n\n"));
465
+ extraPassages.length = 0;
466
+ }
467
+ }
468
+ const files = {};
469
+ const header = [];
470
+ if (twine.title)
471
+ header.push(`@title ${twine.title.replace(/\s+/g, " ").trim()}`);
472
+ if (startSection !== undefined)
473
+ header.push(`@start ${startSection}`);
474
+ if (twine.stylesheet) {
475
+ files[`${name}.css`] = twine.stylesheet + "\n";
476
+ header.push(`@import ${name}.css`);
477
+ problems.push({
478
+ text: `${name}.css`,
479
+ reason: `The story's stylesheet is in ${name}.css. Its rules for ${harlowe ? "Harlowe's elements (tw-story, tw-passage, tw-link and so on)" : "SugarCube's elements (#story, .passage, #ui-bar and so on)"} won't apply to Squiffy's, so check how it looks.`,
480
+ });
481
+ }
482
+ if (twine.script) {
483
+ files[`${name}.js`] = twine.script + "\n";
484
+ problems.push({
485
+ text: `${name}.js`,
486
+ 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 add @ui ${name}.js at the top of ${name}.squiffy.`,
487
+ });
488
+ }
489
+ const masterPassageText = masterPassages.length ? "\n\n" + masterPassages.join("\n\n") : "";
490
+ const script = [
491
+ header.join("\n"),
492
+ `[[]]:\n${block(master)}${masterPassageText}`,
493
+ ...sections,
494
+ ...story.extraSections,
495
+ ].filter(s => s.length).join("\n\n") + "\n";
496
+ files[`${name}.squiffy`] = script;
497
+ const map = mapPositions(sectionPassages, story);
498
+ files["squiffy.json"] = formatProjectFile({ main: `${name}.squiffy`, ...(map ? { map } : {}) });
499
+ return {
500
+ title: twine.title,
501
+ format: `${twine.formatName} ${twine.formatVersion}`.trim(),
502
+ files,
503
+ main: `${name}.squiffy`,
504
+ passages: sectionPassages.length,
505
+ problems: [...problems, ...story.noteProblems(), ...story.problems],
506
+ };
507
+ }
508
+ // Where the sections go on the editor's story map, so it looks like the story's map in Twine.
509
+ // Twine's boxes are 100 by 100, on a grid of 25, and usually 125 apart; the map's are short and
510
+ // wide, up to 190 across, so the map is stretched sideways to keep them from overlapping (which
511
+ // leaves only a handful overlapping in real games). Undefined if the story's passages have no
512
+ // places on the map, or have never been arranged.
513
+ const MAP_STRETCH = 1.6;
514
+ function mapPositions(passages, story) {
515
+ const placed = passages.filter(p => p.position);
516
+ if (!placed.length || unarranged(story.twine.passages))
517
+ return undefined;
518
+ const centres = placed.map(p => {
519
+ const [w, h] = p.size ?? [100, 100];
520
+ return { name: story.sectionFor(p.name), x: p.position[0] + w / 2, y: p.position[1] + h / 2 };
521
+ });
522
+ const left = Math.min(...centres.map(c => c.x));
523
+ const top = Math.min(...centres.map(c => c.y));
524
+ const sections = {};
525
+ for (const c of centres)
526
+ sections[c.name] = [Math.round((c.x - left) * MAP_STRETCH), Math.round(c.y - top)];
527
+ return { sections, passages: {} };
528
+ }
529
+ // Whether the passages are where Twine or Tweego put them when the story was made from Twee
530
+ // without positions: in rows of ten, 125 apart. A map like that says nothing about the story, and
531
+ // the editor's own layout is better. It still counts if the author's moved one or two.
532
+ function unarranged(passages) {
533
+ const positions = passages.flatMap(p => p.position ? [p.position] : []);
534
+ if (positions.length < 10)
535
+ return false;
536
+ const left = Math.min(...positions.map(p => p[0]));
537
+ const top = Math.min(...positions.map(p => p[1]));
538
+ const onGrid = positions.filter(([x, y]) => (x - left) % 125 == 0 && (y - top) % 125 == 0 && x - left < 1250);
539
+ const columns = new Set(onGrid.map(([x]) => x));
540
+ return columns.size == 10 && onGrid.length >= positions.length * 0.9;
541
+ }
542
+ // The text of a section or passage: its directives, then its text
543
+ function block(content) {
544
+ const c = typeof content == "string" ? { directives: [], body: content } : content;
545
+ return [...c.directives, finishText(c.body)].filter(l => l.length).join("\n");
546
+ }
547
+ // A name for a generated passage, from a link's text, which can have markup in it
548
+ function sanitisePassageName(name) {
549
+ const plain = name
550
+ .replace(/\{\{[\s\S]*?\}\}/g, "")
551
+ .replace(/\([\w-]+:[^()]*(\([^()]*\)[^()]*)*\)/g, "")
552
+ .replace(/<[^>]*>|&#?\w+;|''|\/\/|[*_~^]/g, "")
553
+ .replace(/[$_]\w+/g, "")
554
+ .replace(/[[\]]/g, " ");
555
+ let result = sanitiseName(plain).replace(/:/g, "").trim();
556
+ if (result.length > 40)
557
+ result = result.substring(0, 40).replace(/\s+\S*$/, "");
558
+ return result.trim();
559
+ }
560
+ function oneLine(text) {
561
+ const line = text.replace(/\s+/g, " ").trim();
562
+ return line.length > 120 ? line.substring(0, 117) + "..." : line;
563
+ }
564
+ // Directives the compiler would read at the start of a line
565
+ const directiveLine = /^@(title|import|start|set|unset|inc|dec|ui|clear|end)\b/;
566
+ // Lines that only hold helpers that write nothing
567
+ const silentHelper = /\{\{(?:!--[\s\S]*?--|![^}]*|~?\s*(?:#if|#unless|else|\/if|\/unless|set|unset|inc|dec|goto|append|prepend|remove|#label|\/label|#replace|\/replace|#animate|\/animate)\b(?:[^{}]|\{\{[^{}]*\}\})*)\}\}/g;
568
+ function isSilent(line) {
569
+ return line.replace(silentHelper, "").trim() == "";
570
+ }
571
+ // Markdown that starts a block, which can't be joined to the line before with <br>
572
+ function isBlockLine(line) {
573
+ 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)
574
+ || /<\/(div|p|ul|ol|table|h\d|blockquote|pre|center|section|article)>\s*$/i.test(line);
575
+ }
576
+ // Tidies converted passage text into lines the compiler reads as text. In Twine, each line
577
+ // break in a passage is a line break in the story, but in Markdown a single line break is just a
578
+ // space, so lines that follow each other get a <br>.
579
+ export function finishText(text) {
580
+ const lines = text.replace(/\r/g, "").split("\n").map(line => {
581
+ let l = line.trim();
582
+ if (/^-{3,}$/.test(l))
583
+ return "<hr>";
584
+ if (directiveLine.test(l))
585
+ l = "&#64;" + l.substring(1);
586
+ if (l.startsWith("+++"))
587
+ l = "&#43;" + l.substring(1);
588
+ if (l.startsWith(">"))
589
+ l = "&gt;" + l.substring(1);
590
+ // A link on its own followed by a colon would be read as a section or passage header
591
+ if (/^\[.*\]:$/.test(l))
592
+ l = l.substring(0, l.length - 1) + "&#58;";
593
+ return l;
594
+ });
595
+ // Collapse runs of blank lines
596
+ const collapsed = [];
597
+ for (const line of lines) {
598
+ if (line == "" && (collapsed.length == 0 || collapsed[collapsed.length - 1] == ""))
599
+ continue;
600
+ collapsed.push(line);
601
+ }
602
+ while (collapsed.length && collapsed[collapsed.length - 1] == "")
603
+ collapsed.pop();
604
+ for (let i = 0; i < collapsed.length - 1; i++) {
605
+ const line = collapsed[i];
606
+ if (line == "" || isSilent(line) || isBlockLine(line) || line.endsWith("<br>"))
607
+ continue;
608
+ // The next line that writes something, if it's straight after this one
609
+ let j = i + 1;
610
+ while (j < collapsed.length && collapsed[j] != "" && isSilent(collapsed[j]))
611
+ j++;
612
+ if (j >= collapsed.length || collapsed[j] == "" || isBlockLine(collapsed[j]))
613
+ continue;
614
+ collapsed[i] = line + "<br>";
615
+ }
616
+ // A backslash before {{ would stop Handlebars reading it as a helper
617
+ return tidyMarkup(collapsed.join("\n")).replace(/\\(?=\{\{)/g, "&#92;");
618
+ }
619
+ // Turns simple HTML emphasis into Markdown, which is easier to read and edit
620
+ function tidyMarkup(text) {
621
+ return text
622
+ .replace(/<b>([^<>*\n\s](?:[^<>*\n]*[^<>*\n\s])?)<\/b>/g, "**$1**")
623
+ .replace(/<strong>([^<>*\n\s](?:[^<>*\n]*[^<>*\n\s])?)<\/strong>/g, "**$1**")
624
+ .replace(/<i>([^<>*_\n\s](?:[^<>*_\n]*[^<>*_\n\s])?)<\/i>/g, "_$1_")
625
+ .replace(/<em>([^<>*_\n\s](?:[^<>*_\n]*[^<>*_\n\s])?)<\/em>/g, "_$1_");
626
+ }
@@ -0,0 +1,62 @@
1
+ export type BinaryOp = "or" | "and" | "=" | "!=" | ">" | ">=" | "<" | "<=" | "+" | "-" | "*" | "/" | "%";
2
+ export type Expr = {
3
+ k: "num";
4
+ v: number;
5
+ } | {
6
+ k: "str";
7
+ v: string;
8
+ } | {
9
+ k: "bool";
10
+ v: boolean;
11
+ } | {
12
+ k: "null";
13
+ } | {
14
+ k: "var";
15
+ name: string;
16
+ } | {
17
+ k: "bin";
18
+ op: BinaryOp;
19
+ l: Expr;
20
+ r: Expr;
21
+ } | {
22
+ k: "not";
23
+ e: Expr;
24
+ } | {
25
+ k: "neg";
26
+ e: Expr;
27
+ } | {
28
+ k: "call";
29
+ fn: string;
30
+ args: Expr[];
31
+ } | {
32
+ k: "array";
33
+ items: Expr[];
34
+ };
35
+ export declare class Unconvertible extends Error {
36
+ }
37
+ export interface PrintOptions {
38
+ preferSingle?: boolean;
39
+ }
40
+ export declare function quote(text: string, options?: PrintOptions): string;
41
+ export declare function attributeRef(name: string): string;
42
+ export declare function print(e: Expr, options?: PrintOptions): string;
43
+ export declare function isBoolean(e: Expr): boolean;
44
+ export declare function randomInteger(min: Expr, max: Expr): Expr;
45
+ export declare function display(e: Expr): string;
46
+ export declare class Tokens<T extends {
47
+ type: string;
48
+ text: string;
49
+ }> {
50
+ readonly items: T[];
51
+ pos: number;
52
+ constructor(items: T[]);
53
+ peek(offset?: number): T | undefined;
54
+ next(): T;
55
+ is(text: string, offset?: number): boolean;
56
+ accept(text: string): boolean;
57
+ expect(text: string): void;
58
+ get done(): boolean;
59
+ }
60
+ export declare function skipBalanced(s: string, start: number, open: string, close: string, quotes?: string): number;
61
+ export declare function skipString(s: string, start: number): number;
62
+ export declare function unescapeString(literal: string): string;