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,1584 @@
1
+ // Converts a SugarCube passage to Squiffy text.
2
+ //
3
+ // The passage is parsed into a tree of text, <<macros>> (with the bodies of container macros
4
+ // such as <<if>>...<</if>>), links and naked variables, which is then written out as Squiffy:
5
+ // <<if>> becomes {{#if}}, <<set>> becomes @set or {{set}}, links with setters become links with
6
+ // setters, and <<link>> and friends become links to generated passages and sections.
7
+ import { display, print, randomInteger, skipString, Tokens, Unconvertible, unescapeString } from "./expression.js";
8
+ import { dynamicSectionLink, escapeText, isUrl, urlLink, passageLink, sectionLink, setter } from "./convert.js";
9
+ const containers = new Set([
10
+ "if", "for", "switch", "link", "button", "linkreplace", "linkappend", "linkprepend", "nobr", "silently", "capture",
11
+ "script", "timed", "repeat", "widget", "cycle", "listbox", "append", "prepend", "replace", "type", "done", "do",
12
+ "click", "createplaylist", "createaudiogroup",
13
+ ]);
14
+ const childMacros = {
15
+ if: ["elseif", "else"],
16
+ switch: ["case", "default"],
17
+ timed: ["next"],
18
+ cycle: ["option", "optionsfrom"],
19
+ listbox: ["option", "optionsfrom"],
20
+ repeat: [],
21
+ };
22
+ class Parser {
23
+ constructor(src) {
24
+ Object.defineProperty(this, "src", {
25
+ enumerable: true,
26
+ configurable: true,
27
+ writable: true,
28
+ value: src
29
+ });
30
+ }
31
+ // Parses until the end, or until the end of the container, or one of its child macros
32
+ parse(start, container) {
33
+ const src = this.src;
34
+ const nodes = [];
35
+ let text = "";
36
+ const flush = () => {
37
+ if (text)
38
+ nodes.push({ t: "text", s: text });
39
+ text = "";
40
+ };
41
+ let i = start;
42
+ while (i < src.length) {
43
+ const rest = src.substring(i, i + 300);
44
+ if (rest.startsWith("<<")) {
45
+ const macro = readMacro(src, i);
46
+ if (macro) {
47
+ const close = /^\/(\w+)$|^end\s*(\w+)$/.exec(macro.name);
48
+ if (close) {
49
+ const closing = close[1] ?? close[2];
50
+ if (container && closing == container) {
51
+ flush();
52
+ return { nodes, end: macro.end, stop: { name: closing, args: "", raw: macro.raw, close: true } };
53
+ }
54
+ // A stray closing tag: left out
55
+ flush();
56
+ i = macro.end;
57
+ continue;
58
+ }
59
+ const name = macro.name == "else" && /^\s*if\b/.test(macro.args) ? "elseif" : macro.name;
60
+ const args = name == "elseif" && macro.name == "else" ? macro.args.replace(/^\s*if\b/, "") : macro.args;
61
+ if (container && childMacros[container]?.includes(name)) {
62
+ flush();
63
+ return { nodes, end: macro.end, stop: { name, args, raw: macro.raw, close: false } };
64
+ }
65
+ flush();
66
+ if (containers.has(name)) {
67
+ const node = { t: "macro", name, args, raw: macro.raw, clauses: [] };
68
+ let clause = { name, args, raw: macro.raw, nodes: [] };
69
+ let j = macro.end;
70
+ for (;;) {
71
+ const body = this.parse(j, name);
72
+ clause.nodes = body.nodes;
73
+ node.clauses.push(clause);
74
+ j = body.end;
75
+ if (!body.stop || body.stop.close) {
76
+ node.raw = src.substring(i, j);
77
+ break;
78
+ }
79
+ clause = { name: body.stop.name, args: body.stop.args, raw: body.stop.raw, nodes: [] };
80
+ }
81
+ nodes.push(node);
82
+ i = j;
83
+ continue;
84
+ }
85
+ nodes.push({ t: "macro", name, args, raw: macro.raw });
86
+ i = macro.end;
87
+ continue;
88
+ }
89
+ }
90
+ if (rest.startsWith("/*") || rest.startsWith("/%")) {
91
+ const closer = rest.startsWith("/*") ? "*/" : "%/";
92
+ const end = src.indexOf(closer, i + 2);
93
+ flush();
94
+ i = end == -1 ? src.length : end + 2;
95
+ continue;
96
+ }
97
+ if (rest.startsWith("<!--")) {
98
+ const end = src.indexOf("-->", i + 4);
99
+ const stop = end == -1 ? src.length : end + 3;
100
+ flush();
101
+ nodes.push({ t: "raw", s: src.substring(i, stop).replace(/\n/g, " ") });
102
+ i = stop;
103
+ continue;
104
+ }
105
+ if (rest.startsWith("\"\"\"")) {
106
+ const end = src.indexOf("\"\"\"", i + 3);
107
+ if (end != -1) {
108
+ flush();
109
+ nodes.push({ t: "raw", s: escapeText(escapeHtml(src.substring(i + 3, end))) });
110
+ i = end + 3;
111
+ continue;
112
+ }
113
+ }
114
+ if (/^<nowiki>/i.test(rest)) {
115
+ const end = src.toLowerCase().indexOf("</nowiki>", i);
116
+ if (end != -1) {
117
+ flush();
118
+ nodes.push({ t: "raw", s: escapeText(src.substring(i + 8, end)) });
119
+ i = end + 9;
120
+ continue;
121
+ }
122
+ }
123
+ if (rest.startsWith("{{{")) {
124
+ const end = src.indexOf("}}}", i + 3);
125
+ if (end != -1) {
126
+ flush();
127
+ nodes.push({ t: "raw", s: `<code>${escapeText(escapeHtml(src.substring(i + 3, end)))}</code>` });
128
+ i = end + 3;
129
+ continue;
130
+ }
131
+ }
132
+ const scriptMatch = /^<(script|style)\b/i.exec(rest);
133
+ if (scriptMatch) {
134
+ const closeTag = `</${scriptMatch[1].toLowerCase()}>`;
135
+ const end = src.toLowerCase().indexOf(closeTag, i);
136
+ const stop = end == -1 ? src.length : end + closeTag.length;
137
+ flush();
138
+ nodes.push({ t: "comment", text: src.substring(i, stop), reason: `A <${scriptMatch[1]}> in a passage isn't run by Squiffy. Move it to the story's JavaScript or CSS file.` });
139
+ i = stop;
140
+ continue;
141
+ }
142
+ const image = /^\[[<>]?img\[(?:([^|\]]*)\|)?([^\]]*)\](?:\[([^\]]*)\])?\]/i.exec(rest);
143
+ if (image) {
144
+ flush();
145
+ nodes.push({ t: "image", raw: image[0], title: image[1], src: image[2], link: image[3] });
146
+ i += image[0].length;
147
+ continue;
148
+ }
149
+ const link = /^\[\[((?:[^\]]|\](?!\]|\[))*)\](?:\[((?:[^\]]|\](?!\]))*)\])?\]/.exec(rest);
150
+ if (link) {
151
+ flush();
152
+ nodes.push(parseLink(link[1], link[0], link[2]));
153
+ i += link[0].length;
154
+ continue;
155
+ }
156
+ const variable = /^(?:\$[A-Za-z_]|_[A-Za-z])\w*(?:\.[A-Za-z_$][\w$]*|\[(?:[^\]\n]+)\])*/.exec(rest);
157
+ if (variable && (rest[0] == "$" || !/\w/.test(src[i - 1] ?? "")) && !/\w/.test(src[i - 1] ?? "")) {
158
+ flush();
159
+ nodes.push({ t: "var", raw: variable[0] });
160
+ i += variable[0].length;
161
+ continue;
162
+ }
163
+ text += src[i];
164
+ i++;
165
+ }
166
+ flush();
167
+ return { nodes, end: i };
168
+ }
169
+ }
170
+ // Reads <<name args>> at start, or null if it isn't a macro
171
+ function readMacro(src, start) {
172
+ const head = /^<<(\/?[A-Za-z][\w-]*|=|-|end\s+\w+)/.exec(src.substring(start, start + 100));
173
+ if (!head)
174
+ return null;
175
+ let i = start + head[0].length;
176
+ while (i < src.length) {
177
+ const c = src[i];
178
+ if (c == "\"" || c == "'" || c == "`") {
179
+ const end = skipString(src, i);
180
+ if (end == -1)
181
+ return null;
182
+ i = end;
183
+ continue;
184
+ }
185
+ if (src.startsWith("[[", i)) {
186
+ const end = src.indexOf("]]", i);
187
+ if (end == -1)
188
+ return null;
189
+ i = end + 2;
190
+ continue;
191
+ }
192
+ if (src.startsWith("/*", i)) {
193
+ const end = src.indexOf("*/", i + 2);
194
+ if (end == -1)
195
+ return null;
196
+ i = end + 2;
197
+ continue;
198
+ }
199
+ if (src.startsWith(">>", i)) {
200
+ const name = head[1] == "=" || head[1] == "-" ? "print" : head[1].replace(/\s+/g, "");
201
+ return { name: name.toLowerCase(), args: src.substring(start + head[0].length, i).trim(), raw: src.substring(start, i + 2), end: i + 2 };
202
+ }
203
+ i++;
204
+ }
205
+ return null;
206
+ }
207
+ function parseLink(inner, raw, setter) {
208
+ let text;
209
+ let target;
210
+ const bar = inner.lastIndexOf("|");
211
+ const arrow = inner.lastIndexOf("->");
212
+ const back = inner.indexOf("<-");
213
+ if (bar != -1) {
214
+ text = inner.substring(0, bar);
215
+ target = inner.substring(bar + 1);
216
+ }
217
+ else if (arrow != -1) {
218
+ text = inner.substring(0, arrow);
219
+ target = inner.substring(arrow + 2);
220
+ }
221
+ else if (back != -1) {
222
+ target = inner.substring(0, back);
223
+ text = inner.substring(back + 2);
224
+ }
225
+ else {
226
+ text = target = inner;
227
+ }
228
+ return { t: "link", raw, text, target: target.trim(), ...(setter === undefined ? {} : { setter }) };
229
+ }
230
+ function escapeHtml(s) {
231
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
232
+ }
233
+ const symbols = [
234
+ "===", "!==", "**", "==", "!=", ">=", "<=", "&&", "||", "+=", "-=", "*=", "/=", "%=", "++", "--", "=>",
235
+ "+", "-", "*", "/", "%", ">", "<", "=", "!", "?", ":", "(", ")", "[", "]", "{", "}", ",", ".", ";", "&", "|",
236
+ ];
237
+ const wordOperators = {
238
+ to: "=", eq: "==", neq: "!=", is: "===", isnot: "!==", gt: ">", gte: ">=", lt: "<", lte: "<=",
239
+ and: "&&", or: "||", not: "!", def: "def", ndef: "ndef", typeof: "typeof", new: "new", instanceof: "instanceof",
240
+ };
241
+ function tokenize(s) {
242
+ const tokens = [];
243
+ let i = 0;
244
+ while (i < s.length) {
245
+ const c = s[i];
246
+ if (/\s/.test(c)) {
247
+ i++;
248
+ continue;
249
+ }
250
+ if (c == "\"" || c == "'") {
251
+ const end = skipString(s, i);
252
+ if (end == -1)
253
+ throw new Unconvertible("an expression with a string that isn't closed");
254
+ tokens.push({ type: "str", text: s.substring(i, end), value: unescapeString(s.substring(i, end)) });
255
+ i = end;
256
+ continue;
257
+ }
258
+ if (s.startsWith("/*", i)) {
259
+ const end = s.indexOf("*/", i + 2);
260
+ i = end == -1 ? s.length : end + 2;
261
+ continue;
262
+ }
263
+ if (c == "`")
264
+ throw new Unconvertible("a JavaScript template literal");
265
+ const num = /^(\d+(?:\.\d+)?|\.\d+)(ms|s)?(?![\w])/i.exec(s.substring(i));
266
+ if (num) {
267
+ let value = parseFloat(num[1]);
268
+ if (num[2]?.toLowerCase() == "s")
269
+ value *= 1000;
270
+ tokens.push({ type: "num", text: num[0], value });
271
+ i += num[0].length;
272
+ continue;
273
+ }
274
+ const variable = /^([$_])([A-Za-z_]\w*)/.exec(s.substring(i));
275
+ if (variable && (variable[1] == "$" || !/\w/.test(s[i - 1] ?? ""))) {
276
+ tokens.push({ type: variable[1] == "$" ? "var" : "temp", text: variable[0], value: variable[2] });
277
+ i += variable[0].length;
278
+ continue;
279
+ }
280
+ const word = /^[A-Za-z_$][\w$]*/.exec(s.substring(i));
281
+ if (word) {
282
+ const op = wordOperators[word[0]];
283
+ tokens.push(op ? { type: "op", text: op } : { type: "ident", text: word[0] });
284
+ i += word[0].length;
285
+ continue;
286
+ }
287
+ const symbol = symbols.find(o => s.startsWith(o, i));
288
+ if (symbol) {
289
+ // & and | on true and false work as && and ||, and are usually a typo for them
290
+ const text = symbol == "&" ? "&&" : symbol == "|" ? "||" : symbol;
291
+ tokens.push({ type: "(),[]{}.;:?".includes(symbol) ? "punct" : "op", text });
292
+ i += symbol.length;
293
+ continue;
294
+ }
295
+ throw new Unconvertible(`an expression Squiffy can't read ("${s.substring(i, i + 10)}")`);
296
+ }
297
+ return tokens;
298
+ }
299
+ export class SugarCubeExpressions {
300
+ constructor(ctx) {
301
+ Object.defineProperty(this, "ctx", {
302
+ enumerable: true,
303
+ configurable: true,
304
+ writable: true,
305
+ value: ctx
306
+ });
307
+ }
308
+ attribute(name, temp) {
309
+ return this.ctx.story.attribute(name, temp);
310
+ }
311
+ parse(source) {
312
+ const tokens = new Tokens(tokenize(source));
313
+ const e = new ExpressionParser(this, tokens).expression();
314
+ if (!tokens.done)
315
+ throw new Unconvertible(`an expression Squiffy can't read (at "${tokens.peek().text}")`);
316
+ return e;
317
+ }
318
+ // Statements, as in <<set>> and <<run>>: assignments and changes to arrays
319
+ statements(source) {
320
+ const tokens = new Tokens(tokenize(source));
321
+ const parser = new ExpressionParser(this, tokens);
322
+ const result = [];
323
+ while (!tokens.done) {
324
+ result.push(...parser.statement());
325
+ if (!tokens.accept(",") && !tokens.accept(";"))
326
+ break;
327
+ }
328
+ if (!tokens.done)
329
+ throw new Unconvertible(`a statement Squiffy can't read (at "${tokens.peek().text}")`);
330
+ return result;
331
+ }
332
+ // A value used as a passage name, for <<goto>>, <<include>> and links
333
+ passageName(source) {
334
+ const link = /^\[\[(.*)\]\]$/.exec(source.trim());
335
+ if (link) {
336
+ const node = parseLink(link[1], source);
337
+ return { name: node.target };
338
+ }
339
+ // A bare word that isn't a variable is a passage name, e.g. <<goto Library>>
340
+ if (/^[^"'`$_[(\s][^\s]*$/.test(source.trim())) {
341
+ try {
342
+ const e = this.parse(source);
343
+ if (e.k == "str")
344
+ return { name: e.v };
345
+ }
346
+ catch {
347
+ // Treated as a name
348
+ }
349
+ return { name: source.trim() };
350
+ }
351
+ const e = this.parse(source);
352
+ if (e.k == "str")
353
+ return { name: e.v };
354
+ return { expr: e };
355
+ }
356
+ }
357
+ class ExpressionParser {
358
+ constructor(s, tokens) {
359
+ Object.defineProperty(this, "s", {
360
+ enumerable: true,
361
+ configurable: true,
362
+ writable: true,
363
+ value: s
364
+ });
365
+ Object.defineProperty(this, "tokens", {
366
+ enumerable: true,
367
+ configurable: true,
368
+ writable: true,
369
+ value: tokens
370
+ });
371
+ }
372
+ expression() {
373
+ const e = this.or();
374
+ if (this.tokens.is("?"))
375
+ throw new Unconvertible("the ? : operator");
376
+ return e;
377
+ }
378
+ // Objects are flattened, so $player to { hp: 10 } sets player_hp
379
+ statement() {
380
+ const target = this.postfixValue();
381
+ const t = this.tokens.peek();
382
+ if (target.v == "expr" && target.e.k == "var" && t?.text == "=") {
383
+ const start = this.tokens.pos;
384
+ this.tokens.next();
385
+ const value = this.postfixOrObject();
386
+ if (value.v == "object")
387
+ return this.flatten(target.e.name, value);
388
+ this.tokens.pos = start;
389
+ }
390
+ return [this.singleStatement(target, t)];
391
+ }
392
+ flatten(name, object) {
393
+ return object.entries.flatMap(([key, value]) => {
394
+ const attribute = `${name}_${key}`;
395
+ if (value.v == "object")
396
+ return this.flatten(attribute, value);
397
+ return [{ kind: "set", name: attribute, value: this.toExpr(value) }];
398
+ });
399
+ }
400
+ // An object literal, or an ordinary expression
401
+ postfixOrObject() {
402
+ if (this.tokens.is("{"))
403
+ return this.primary();
404
+ return { v: "expr", e: this.expression() };
405
+ }
406
+ singleStatement(target, t) {
407
+ if (target.v == "expr" && target.e.k == "var") {
408
+ const name = target.e.name;
409
+ if (t?.text == "++" || t?.text == "--") {
410
+ this.tokens.next();
411
+ return { kind: t.text == "++" ? "inc" : "dec", name, value: { k: "num", v: 1 } };
412
+ }
413
+ if (t && ["=", "+=", "-=", "*=", "/="].includes(t.text)) {
414
+ this.tokens.next();
415
+ const value = this.expression();
416
+ switch (t.text) {
417
+ case "+=":
418
+ if (value.k == "array")
419
+ return this.arrayChange("append", name, value);
420
+ return { kind: "inc", name, value };
421
+ case "-=": return { kind: "dec", name, value };
422
+ case "*=":
423
+ case "/=": return { kind: "set", name, value, op: t.text };
424
+ }
425
+ // $x to $x + 1
426
+ if (value.k == "bin" && (value.op == "+" || value.op == "-") && value.l.k == "var" && value.l.name == name) {
427
+ if (value.r.k == "array")
428
+ return this.arrayChange(value.op == "+" ? "append" : "remove", name, value.r);
429
+ if (value.r.k == "num" || value.op == "-")
430
+ return { kind: value.op == "+" ? "inc" : "dec", name, value: value.r };
431
+ }
432
+ return { kind: "set", name, value };
433
+ }
434
+ throw new Unconvertible("a statement that isn't an assignment");
435
+ }
436
+ if (target.v == "expr" && target.e.k == "call" && target.e.fn == "__statement") {
437
+ const [kind, name, value] = target.e.args;
438
+ return { kind: kind.v, name: name.v, value };
439
+ }
440
+ throw new Unconvertible("a statement Squiffy can't convert");
441
+ }
442
+ arrayChange(kind, name, array) {
443
+ if (array.items.length != 1)
444
+ throw new Unconvertible("adding or removing more than one item at once");
445
+ return { kind, name, value: array.items[0] };
446
+ }
447
+ or() {
448
+ let left = this.and();
449
+ while (this.tokens.is("||")) {
450
+ this.tokens.next();
451
+ left = { k: "bin", op: "or", l: left, r: this.and() };
452
+ }
453
+ return left;
454
+ }
455
+ and() {
456
+ let left = this.equality();
457
+ while (this.tokens.is("&&")) {
458
+ this.tokens.next();
459
+ left = { k: "bin", op: "and", l: left, r: this.equality() };
460
+ }
461
+ return left;
462
+ }
463
+ equality() {
464
+ let left = this.relational();
465
+ for (;;) {
466
+ const t = this.tokens.peek()?.text;
467
+ if (t == "==" || t == "===") {
468
+ this.tokens.next();
469
+ left = { k: "bin", op: "=", l: left, r: this.relational() };
470
+ }
471
+ else if (t == "!=" || t == "!==") {
472
+ this.tokens.next();
473
+ left = { k: "bin", op: "!=", l: left, r: this.relational() };
474
+ }
475
+ else if (t == "=") {
476
+ throw new Unconvertible("an assignment (=) in a condition");
477
+ }
478
+ else {
479
+ return left;
480
+ }
481
+ }
482
+ }
483
+ relational() {
484
+ let left = this.additive();
485
+ for (;;) {
486
+ const t = this.tokens.peek()?.text;
487
+ if (t == ">" || t == "<" || t == ">=" || t == "<=") {
488
+ this.tokens.next();
489
+ left = { k: "bin", op: t, l: left, r: this.additive() };
490
+ }
491
+ else {
492
+ return left;
493
+ }
494
+ }
495
+ }
496
+ additive() {
497
+ let left = this.multiplicative();
498
+ while (this.tokens.is("+") || this.tokens.is("-")) {
499
+ const op = this.tokens.next().text;
500
+ left = { k: "bin", op, l: left, r: this.multiplicative() };
501
+ }
502
+ return left;
503
+ }
504
+ multiplicative() {
505
+ let left = this.unary();
506
+ while (this.tokens.is("*") || this.tokens.is("/") || this.tokens.is("%")) {
507
+ const op = this.tokens.next().text;
508
+ left = { k: "bin", op, l: left, r: this.unary() };
509
+ }
510
+ return left;
511
+ }
512
+ unary() {
513
+ const t = this.tokens.peek()?.text;
514
+ if (t == "!") {
515
+ this.tokens.next();
516
+ return { k: "not", e: this.unary() };
517
+ }
518
+ if (t == "-") {
519
+ this.tokens.next();
520
+ const e = this.unary();
521
+ return e.k == "num" ? { k: "num", v: -e.v } : { k: "neg", e };
522
+ }
523
+ if (t == "+") {
524
+ this.tokens.next();
525
+ return this.unary();
526
+ }
527
+ if (t == "def" || t == "ndef") {
528
+ this.tokens.next();
529
+ const e = this.unary();
530
+ return t == "def" ? { k: "bin", op: "!=", l: e, r: { k: "null" } } : { k: "bin", op: "=", l: e, r: { k: "null" } };
531
+ }
532
+ if (t == "typeof" || t == "new")
533
+ throw new Unconvertible(`"${t}"`);
534
+ return this.postfix();
535
+ }
536
+ postfix() {
537
+ return this.toExpr(this.postfixValue());
538
+ }
539
+ toExpr(v) {
540
+ if (v.v == "expr")
541
+ return v.e;
542
+ if (v.v == "object")
543
+ throw new Unconvertible("a JavaScript object, other than one set to a variable");
544
+ if (v.v == "member") {
545
+ if (v.property == "length")
546
+ return { k: "call", fn: "length", args: [this.collection(v.object)] };
547
+ throw new Unconvertible(`properties of variables (.${v.property})`);
548
+ }
549
+ throw new Unconvertible(`"${v.name}"`);
550
+ }
551
+ // The first argument of contains and length: the attribute's name, or an array
552
+ collection(v) {
553
+ if (v.v == "expr" && v.e.k == "var")
554
+ return { k: "str", v: v.e.name };
555
+ if (v.v == "expr" && v.e.k == "array")
556
+ return v.e;
557
+ throw new Unconvertible("an array method on something other than a variable");
558
+ }
559
+ postfixValue() {
560
+ let value = this.primary();
561
+ for (;;) {
562
+ if (this.tokens.accept(".")) {
563
+ const property = this.tokens.next();
564
+ if (property.type != "ident")
565
+ throw new Unconvertible("an expression Squiffy can't read");
566
+ // An object's property, which is its own attribute: $player.hp is player_hp
567
+ if (value.v == "expr" && value.e.k == "var" && !this.tokens.is("(") && property.text != "length") {
568
+ value = { v: "expr", e: { k: "var", name: `${value.e.name}_${property.text}` } };
569
+ continue;
570
+ }
571
+ value = this.member(value, property.text);
572
+ }
573
+ else if (this.tokens.is("[")) {
574
+ this.tokens.next();
575
+ const index = this.expression();
576
+ this.tokens.expect("]");
577
+ // A widget's arguments, which a call to it puts in args_0, args_1 and so on
578
+ if (value.v == "expr" && value.e.k == "var" && value.e.name == "args" && index.k == "num") {
579
+ value = { v: "expr", e: { k: "var", name: `args_${index.v}` } };
580
+ continue;
581
+ }
582
+ if (value.v == "expr" && value.e.k == "var" && index.k == "str" && /^[A-Za-z_]\w*$/.test(index.v)) {
583
+ value = { v: "expr", e: { k: "var", name: `${value.e.name}_${index.v}` } };
584
+ continue;
585
+ }
586
+ if (value.v == "expr" && (value.e.k == "var" || value.e.k == "array") && index.k == "num") {
587
+ value = { v: "expr", e: { k: "call", fn: "lookup", args: [value.e, index] } };
588
+ continue;
589
+ }
590
+ throw new Unconvertible("array indexes and object properties ([...])");
591
+ }
592
+ else if (this.tokens.is("(")) {
593
+ this.tokens.next();
594
+ const args = [];
595
+ if (!this.tokens.accept(")")) {
596
+ do
597
+ args.push(this.expression());
598
+ while (this.tokens.accept(","));
599
+ this.tokens.expect(")");
600
+ }
601
+ value = { v: "expr", e: this.call(value, args) };
602
+ }
603
+ else {
604
+ return value;
605
+ }
606
+ }
607
+ }
608
+ // State.variables.x is $x, and State.temporary.x is _x
609
+ member(object, property) {
610
+ if (object.v == "global") {
611
+ const path = `${object.name}.${property}`;
612
+ if (path == "State.variables" || path == "State.temporary" || path == "SugarCube.State")
613
+ return { v: "global", name: path };
614
+ if (object.name == "State.variables" || object.name == "variables")
615
+ return { v: "expr", e: { k: "var", name: this.s.attribute(property, false) } };
616
+ if (object.name == "State.temporary" || object.name == "temporary")
617
+ return { v: "expr", e: { k: "var", name: this.s.attribute(property, true) } };
618
+ return { v: "global", name: path };
619
+ }
620
+ return { v: "member", object, property };
621
+ }
622
+ call(callee, args) {
623
+ const str = (e, what) => {
624
+ if (e?.k == "str")
625
+ return e.v;
626
+ throw new Unconvertible(`${what} with something other than a passage name`);
627
+ };
628
+ if (callee.v == "global") {
629
+ switch (callee.name) {
630
+ case "visited":
631
+ case "hasVisited": {
632
+ if (args.length == 0)
633
+ return { k: "call", fn: "visits", args: [{ k: "str", v: this.s.ctx.section }] };
634
+ if (args.length > 1)
635
+ throw new Unconvertible(`${callee.name}() with more than one passage`);
636
+ const section = this.s.ctx.story.sectionForUnknown(str(args[0], `${callee.name}()`));
637
+ return callee.name == "visited" ? { k: "call", fn: "visits", args: [{ k: "str", v: section }] } : { k: "call", fn: "seen", args: [{ k: "str", v: section }] };
638
+ }
639
+ case "turns":
640
+ return { k: "var", name: "turns" };
641
+ case "random":
642
+ if (args.length == 1)
643
+ return randomInteger({ k: "num", v: 0 }, args[0]);
644
+ return randomInteger(args[0], args[1]);
645
+ case "either":
646
+ return { k: "call", fn: "random", args: [{ k: "array", items: args }] };
647
+ case "passage":
648
+ return { k: "str", v: this.s.ctx.passage.name };
649
+ case "tags":
650
+ // Only as tags().includes("tag")
651
+ return { k: "call", fn: "__tags", args: [] };
652
+ case "Number":
653
+ case "String":
654
+ case "parseInt":
655
+ case "parseFloat":
656
+ if (args.length < 1)
657
+ throw new Unconvertible(`${callee.name}()`);
658
+ return args[0];
659
+ }
660
+ throw new Unconvertible(`${callee.name}()`);
661
+ }
662
+ if (callee.v == "member" && callee.object.v == "expr" && callee.object.e.k == "call" && callee.object.e.fn == "__tags") {
663
+ // tags().includes("x"): whether this is one of the passages tagged x
664
+ if ((callee.property == "includes" || callee.property == "contains") && args[0]?.k == "str") {
665
+ const tag = args[0].v;
666
+ const sections = this.s.ctx.story.twine.passages
667
+ .filter(p => p.tags.includes(tag))
668
+ .map(p => this.s.ctx.story.sectionFor(p.name))
669
+ .filter((s) => s !== undefined);
670
+ return { k: "call", fn: "at", args: [{ k: "array", items: sections.map(s => ({ k: "str", v: s })) }] };
671
+ }
672
+ throw new Unconvertible("tags()");
673
+ }
674
+ if (callee.v == "member") {
675
+ const collection = () => this.collection(callee.object);
676
+ switch (callee.property) {
677
+ case "includes":
678
+ case "contains":
679
+ if (args.length != 1)
680
+ throw new Unconvertible(`.${callee.property}() with more than one value`);
681
+ return { k: "call", fn: "contains", args: [collection(), args[0]] };
682
+ case "random":
683
+ if (callee.object.v == "expr")
684
+ return { k: "call", fn: "random", args: [callee.object.e] };
685
+ break;
686
+ case "push":
687
+ case "pushUnique":
688
+ case "delete": {
689
+ const target = collection();
690
+ if (target.k != "str" || args.length != 1)
691
+ throw new Unconvertible(`.${callee.property}() with more than one value`);
692
+ return { k: "call", fn: "__statement", args: [{ k: "str", v: callee.property == "delete" ? "remove" : "append" }, target, args[0]] };
693
+ }
694
+ }
695
+ throw new Unconvertible(`the .${callee.property}() method`);
696
+ }
697
+ throw new Unconvertible("calling something that isn't a function");
698
+ }
699
+ primary() {
700
+ const t = this.tokens.next();
701
+ switch (t.type) {
702
+ case "str": return { v: "expr", e: { k: "str", v: t.value } };
703
+ case "num": return { v: "expr", e: { k: "num", v: t.value } };
704
+ case "var": return { v: "expr", e: { k: "var", name: this.s.attribute(t.value, false) } };
705
+ case "temp": return { v: "expr", e: { k: "var", name: this.s.attribute(t.value, true) } };
706
+ case "ident":
707
+ switch (t.text) {
708
+ case "true": return { v: "expr", e: { k: "bool", v: true } };
709
+ case "false": return { v: "expr", e: { k: "bool", v: false } };
710
+ case "null":
711
+ case "undefined": return { v: "expr", e: { k: "null" } };
712
+ }
713
+ return { v: "global", name: t.text };
714
+ case "punct":
715
+ if (t.text == "(") {
716
+ const e = this.expression();
717
+ this.tokens.expect(")");
718
+ return { v: "expr", e };
719
+ }
720
+ if (t.text == "[") {
721
+ const items = [];
722
+ if (!this.tokens.accept("]")) {
723
+ do
724
+ items.push(this.expression());
725
+ while (this.tokens.accept(","));
726
+ this.tokens.expect("]");
727
+ }
728
+ return { v: "expr", e: { k: "array", items } };
729
+ }
730
+ if (t.text == "{") {
731
+ const entries = [];
732
+ if (!this.tokens.accept("}")) {
733
+ do {
734
+ if (this.tokens.is("}"))
735
+ break;
736
+ const key = this.tokens.next();
737
+ if (key.type != "ident" && key.type != "str" && key.type != "num")
738
+ throw new Unconvertible("a JavaScript object Squiffy can't read");
739
+ if (!/^[A-Za-z_]\w*$/.test(String(key.value ?? key.text)))
740
+ throw new Unconvertible("a JavaScript object with keys that aren't words");
741
+ this.tokens.expect(":");
742
+ entries.push([String(key.value ?? key.text), this.postfixOrObject()]);
743
+ } while (this.tokens.accept(","));
744
+ this.tokens.expect("}");
745
+ }
746
+ return { v: "object", entries };
747
+ }
748
+ break;
749
+ }
750
+ throw new Unconvertible(`an expression Squiffy can't read (at "${t.text}")`);
751
+ }
752
+ }
753
+ // SugarCube macro arguments: separated by spaces, each a string, number, $variable, [[link]],
754
+ // `expression` or bare word
755
+ function splitMacroArgs(args) {
756
+ const result = [];
757
+ let i = 0;
758
+ while (i < args.length) {
759
+ const c = args[i];
760
+ if (/\s/.test(c)) {
761
+ i++;
762
+ continue;
763
+ }
764
+ let end;
765
+ if (c == "\"" || c == "'" || c == "`") {
766
+ end = skipString(args, i);
767
+ if (end == -1)
768
+ end = args.length;
769
+ }
770
+ else if (args.startsWith("[[", i)) {
771
+ end = args.indexOf("]]", i);
772
+ end = end == -1 ? args.length : end + 2;
773
+ }
774
+ else {
775
+ end = i;
776
+ while (end < args.length && !/\s/.test(args[end]))
777
+ end++;
778
+ }
779
+ result.push(args.substring(i, end));
780
+ i = end;
781
+ }
782
+ return result;
783
+ }
784
+ class Writer {
785
+ constructor(ctx) {
786
+ Object.defineProperty(this, "ctx", {
787
+ enumerable: true,
788
+ configurable: true,
789
+ writable: true,
790
+ value: ctx
791
+ });
792
+ Object.defineProperty(this, "expr", {
793
+ enumerable: true,
794
+ configurable: true,
795
+ writable: true,
796
+ value: void 0
797
+ });
798
+ Object.defineProperty(this, "open", {
799
+ enumerable: true,
800
+ configurable: true,
801
+ writable: true,
802
+ value: new Set()
803
+ });
804
+ Object.defineProperty(this, "atLineStart", {
805
+ enumerable: true,
806
+ configurable: true,
807
+ writable: true,
808
+ value: true
809
+ });
810
+ // Widget name -> the section it's converted to
811
+ Object.defineProperty(this, "widgets", {
812
+ enumerable: true,
813
+ configurable: true,
814
+ writable: true,
815
+ value: void 0
816
+ });
817
+ // Element ids targeted by <<replace>> and friends, which become labels
818
+ Object.defineProperty(this, "targets", {
819
+ enumerable: true,
820
+ configurable: true,
821
+ writable: true,
822
+ value: new Map()
823
+ });
824
+ this.expr = new SugarCubeExpressions(ctx);
825
+ this.widgets = sugarCubeWidgets(ctx.story);
826
+ }
827
+ // A widget passage: each <<widget>> in it, converted to a section
828
+ widgetSections(nodes) {
829
+ const result = [];
830
+ for (const n of nodes) {
831
+ if (n.t != "macro" || n.name != "widget")
832
+ continue;
833
+ const name = /^["']?([\w-]+)/.exec(n.args)?.[1]?.toLowerCase();
834
+ const section = name ? this.widgets.get(name) : undefined;
835
+ if (!section)
836
+ continue;
837
+ if (/\bcontainer\b/.test(n.args))
838
+ this.ctx.approximate(n.raw, "Container widgets (whose calls have text in them) can't be converted. Wherever the story uses one, it's been left as a comment.");
839
+ // An embedded section's directives don't run, so everything is a helper
840
+ const state = { leading: false, directives: [], nobr: false };
841
+ this.open.clear();
842
+ this.atLineStart = true;
843
+ let body = this.nodes(n.clauses?.[0]?.nodes ?? [], state);
844
+ for (const tag of [...this.open].reverse())
845
+ body += `</${tag}>`;
846
+ result.push({ section, converted: { directives: [], body } });
847
+ }
848
+ return result;
849
+ }
850
+ // A call to a widget: its arguments go in attributes _args_0, _args_1 and so on, then the
851
+ // widget's section is embedded
852
+ widgetCall(m, section) {
853
+ if (m.clauses)
854
+ throw new Unconvertible(`the <<${m.name}>> container widget`);
855
+ const sets = splitMacroArgs(m.args).map((a, n) => {
856
+ let value;
857
+ try {
858
+ value = /^[^"'`$_[(\-\d\s][^\s]*$/.test(a) && !["true", "false", "null"].includes(a) ? { k: "str", v: a } : this.expr.parse(a);
859
+ }
860
+ catch {
861
+ value = { k: "str", v: a };
862
+ }
863
+ return `{{set "args_${n}" ${print(value)}}}`;
864
+ });
865
+ return sets.join("") + `{{embed ${print({ k: "str", v: section })}}}`;
866
+ }
867
+ // Finds the ids that <<replace "#id">> and friends change, so they can be labels
868
+ findTargets(source) {
869
+ for (const m of source.matchAll(/<<(?:replace|append|prepend|remove)\s+["']#([\w-]+)["']/g)) {
870
+ if (!this.targets.has(m[1]))
871
+ this.targets.set(m[1], this.ctx.newLabel(m[1]));
872
+ }
873
+ let result = source;
874
+ for (const [id, label] of this.targets) {
875
+ const span = new RegExp(`<(span|div)\\b[^>]*\\bid=["']${id}["'][^>]*>([^<]*)</\\1>`, "g");
876
+ result = result.replace(span, (_m, _tag, inner) => `\uE000label ${label}\uE001${inner}\uE000/label\uE001`);
877
+ }
878
+ return result;
879
+ }
880
+ passage(nodes, nobr) {
881
+ const state = { leading: true, directives: [], nobr };
882
+ let body = this.nodes(nodes, state);
883
+ for (const tag of [...this.open].reverse())
884
+ body += `</${tag}>`;
885
+ body = body.replace(/\uE000label ([\w-]+)\uE001/g, "{{#label \"$1\"}}").replace(/\uE000\/label\uE001/g, "{{/label}}");
886
+ return { directives: state.directives, body };
887
+ }
888
+ nodes(nodes, state) {
889
+ let out = "";
890
+ for (const node of nodes) {
891
+ const written = this.node(node, state);
892
+ if (node.t != "text" && written)
893
+ this.atLineStart = false;
894
+ out += written;
895
+ }
896
+ return out;
897
+ }
898
+ node(node, state) {
899
+ switch (node.t) {
900
+ case "text":
901
+ if (node.s.trim())
902
+ state.leading = false;
903
+ return this.text(node.s, state);
904
+ case "raw":
905
+ return node.s;
906
+ case "comment":
907
+ return this.ctx.unconvertible(node.text, node.reason);
908
+ case "var":
909
+ state.leading = false;
910
+ try {
911
+ return display(this.expr.parse(node.raw));
912
+ }
913
+ catch (e) {
914
+ if (!(e instanceof Unconvertible))
915
+ throw e;
916
+ return this.ctx.unconvertible(node.raw, `This couldn't be converted: ${e.message}.`);
917
+ }
918
+ case "link":
919
+ state.leading = false;
920
+ return this.link(node);
921
+ case "image": {
922
+ state.leading = false;
923
+ const alt = node.title ? ` alt="${escapeAttribute(node.title)}"` : "";
924
+ if (/^data:|\.\w{2,4}$|^https?:/i.test(node.src) === false) {
925
+ this.ctx.approximate(node.raw, "Images stored in the story (Twine.image passages) aren't converted. Put the image in a file next to the story.");
926
+ }
927
+ const img = `<img src="${escapeAttribute(node.src)}"${alt}>`;
928
+ if (!node.link)
929
+ return img;
930
+ const target = this.ctx.story.sectionFor(node.link.trim());
931
+ return target === undefined ? img : `{{section ${print({ k: "str", v: target })} text=${print({ k: "str", v: img })}}}`;
932
+ }
933
+ case "macro":
934
+ return this.macro(node, state);
935
+ }
936
+ }
937
+ link(node) {
938
+ const text = this.inlineText(node.text);
939
+ if (isUrl(node.target))
940
+ return urlLink(text, node.target);
941
+ let setters = [];
942
+ if (node.setter !== undefined) {
943
+ try {
944
+ setters = this.setters(node.setter);
945
+ }
946
+ catch (e) {
947
+ if (!(e instanceof Unconvertible))
948
+ throw e;
949
+ return this.ctx.unconvertible(node.raw, `This link's setter couldn't be converted: ${e.message}.`);
950
+ }
951
+ }
952
+ if (/^[$_][A-Za-z]/.test(node.target) || /\(/.test(node.target) && !this.ctx.story.sectionFor(node.target)) {
953
+ try {
954
+ const target = this.expr.parse(node.target);
955
+ return dynamicSectionLink(node.text, target, setters);
956
+ }
957
+ catch {
958
+ // Treated as a passage name
959
+ }
960
+ }
961
+ const target = this.ctx.story.sectionFor(node.target);
962
+ if (target === undefined) {
963
+ this.ctx.approximate(node.raw, `There's no passage called "${node.target}".`);
964
+ return sectionLink(text, this.ctx.story.sectionForUnknown(node.target), setters);
965
+ }
966
+ return sectionLink(text, target, setters);
967
+ }
968
+ // Converts a link's setter ([[text|passage][$x to 1]]) to Squiffy setters
969
+ setters(source, inLink = true) {
970
+ return this.expr.statements(source).map(s => {
971
+ switch (s.kind) {
972
+ case "set": return setter(s.name, s.op ?? "=", s.value, inLink);
973
+ case "inc": return setter(s.name, "+=", s.value, inLink);
974
+ case "dec": return setter(s.name, "-=", s.value, inLink);
975
+ default: throw new Unconvertible("changing an array in a link");
976
+ }
977
+ });
978
+ }
979
+ inlineText(text) {
980
+ const nodes = new Parser(text).parse(0).nodes;
981
+ return this.nodes(nodes, { leading: false, directives: [], nobr: true }).replace(/\n/g, " ");
982
+ }
983
+ text(s, state) {
984
+ let out = "";
985
+ for (let i = 0; i < s.length;) {
986
+ const rest = s.substring(i, i + 200);
987
+ if (this.atLineStart) {
988
+ this.atLineStart = false;
989
+ const lineEnd = rest.indexOf("\n");
990
+ const line = lineEnd == -1 ? rest : rest.substring(0, lineEnd);
991
+ const heading = /^(!{1,6})\s*/.exec(line);
992
+ if (heading) {
993
+ out += "#".repeat(heading[1].length) + " ";
994
+ i += heading[0].length;
995
+ continue;
996
+ }
997
+ const bullet = /^([*#]+)\s+/.exec(line);
998
+ if (bullet) {
999
+ out += " ".repeat(bullet[1].length - 1) + (bullet[1].endsWith("#") ? "1. " : "* ");
1000
+ i += bullet[0].length;
1001
+ continue;
1002
+ }
1003
+ if (/^\s*-{4,}\s*$/.test(line)) {
1004
+ out += "<hr>";
1005
+ i += line.length;
1006
+ continue;
1007
+ }
1008
+ const number = /^(\s*\d+)\.(\s)/.exec(line);
1009
+ if (number) {
1010
+ // Not a Markdown list
1011
+ out += number[1] + "&#46;" + number[2];
1012
+ i += number[0].length;
1013
+ continue;
1014
+ }
1015
+ }
1016
+ const c = s[i];
1017
+ if (c == "\n") {
1018
+ out += state.nobr ? " " : "\n";
1019
+ this.atLineStart = !state.nobr;
1020
+ i++;
1021
+ continue;
1022
+ }
1023
+ if (c == "\\" && s[i + 1] == "\n") {
1024
+ // Joins the line to the next
1025
+ i += 2;
1026
+ continue;
1027
+ }
1028
+ const style = /^@@([^;@]*);/.exec(rest);
1029
+ if (style) {
1030
+ const end = s.indexOf("@@", i + style[0].length);
1031
+ if (end != -1) {
1032
+ out += `<span${cssAttributes(style[1])}>`;
1033
+ // The text in it is converted with the rest, and @@ closes the span
1034
+ this.open.add("span@@");
1035
+ i += style[0].length;
1036
+ continue;
1037
+ }
1038
+ }
1039
+ if (rest.startsWith("@@") && this.open.has("span@@")) {
1040
+ this.open.delete("span@@");
1041
+ out += "</span>";
1042
+ i += 2;
1043
+ continue;
1044
+ }
1045
+ const toggle = this.toggle(s, i);
1046
+ if (toggle) {
1047
+ out += toggle.text;
1048
+ i += toggle.length;
1049
+ continue;
1050
+ }
1051
+ if (c == "<") {
1052
+ const tag = /^<\/?[A-Za-z][^<>]*>/.exec(rest);
1053
+ if (tag) {
1054
+ out += this.htmlTag(tag[0]);
1055
+ i += tag[0].length;
1056
+ continue;
1057
+ }
1058
+ }
1059
+ out += escapeProse(s, i);
1060
+ i++;
1061
+ }
1062
+ return out;
1063
+ }
1064
+ // An HTML tag, with SugarCube's data-passage links turned into Squiffy links
1065
+ htmlTag(tag) {
1066
+ if (/\s@[\w-]+=/.test(tag)) {
1067
+ this.ctx.approximate(tag, "SugarCube's attribute directives (@attribute=\"...\") aren't converted.");
1068
+ }
1069
+ return tag.replace(/\{\{/g, "&#123;{").replace(/\[/g, "&#91;").replace(/\]/g, "&#93;");
1070
+ }
1071
+ toggle(s, i) {
1072
+ const marks = [["''", "b"], ["//", "i"], ["__", "u"], ["==", "s"], ["^^", "sup"], ["~~", "sub"]];
1073
+ for (const [mark, tag] of marks) {
1074
+ if (!s.startsWith(mark, i))
1075
+ continue;
1076
+ if (mark == "//" && s[i - 1] == ":")
1077
+ return null;
1078
+ if (this.open.has(tag)) {
1079
+ this.open.delete(tag);
1080
+ return { text: `</${tag}>`, length: mark.length };
1081
+ }
1082
+ const end = s.indexOf(mark, i + mark.length);
1083
+ if (end == -1)
1084
+ return null;
1085
+ this.open.add(tag);
1086
+ return { text: `<${tag}>`, length: mark.length };
1087
+ }
1088
+ return null;
1089
+ }
1090
+ // ---- Macros ----
1091
+ macro(m, state) {
1092
+ try {
1093
+ return this.macroOrThrow(m, state);
1094
+ }
1095
+ catch (e) {
1096
+ if (!(e instanceof Unconvertible))
1097
+ throw e;
1098
+ state.leading = false;
1099
+ return this.ctx.unconvertible(m.raw, `This couldn't be converted: ${e.message}.`);
1100
+ }
1101
+ }
1102
+ body(m, state, clause = 0) {
1103
+ return this.nodes(m.clauses?.[clause]?.nodes ?? [], { ...state, leading: false });
1104
+ }
1105
+ macroOrThrow(m, state) {
1106
+ const args = splitMacroArgs(m.args);
1107
+ switch (m.name) {
1108
+ case "set":
1109
+ return this.set(this.expr.statements(m.args), state);
1110
+ case "unset": {
1111
+ const statements = m.args.split(",").map(a => {
1112
+ const match = /^\s*([$_])([A-Za-z_]\w*)\s*$/.exec(a);
1113
+ if (!match)
1114
+ throw new Unconvertible("<<unset>> of something other than a variable");
1115
+ return { kind: "unset", name: this.expr.attribute(match[2], match[1] == "_") };
1116
+ });
1117
+ return this.set(statements, state);
1118
+ }
1119
+ case "run": {
1120
+ return this.set(this.expr.statements(m.args), state);
1121
+ }
1122
+ case "print":
1123
+ state.leading = false;
1124
+ return display(this.expr.parse(m.args));
1125
+ case "if": {
1126
+ state.leading = false;
1127
+ const clauses = m.clauses;
1128
+ let out = "";
1129
+ clauses.forEach((c, n) => {
1130
+ const cond = c.name == "else" ? null : this.expr.parse(c.args);
1131
+ out += n == 0 ? `{{#if ${print(cond)}}}` : cond ? `{{else if ${print(cond)}}}` : "{{else}}";
1132
+ out += this.nodes(c.nodes, { ...state, leading: false });
1133
+ });
1134
+ return out + "{{/if}}";
1135
+ }
1136
+ case "switch": {
1137
+ state.leading = false;
1138
+ const subject = this.expr.parse(m.args);
1139
+ let out = "";
1140
+ let first = true;
1141
+ for (const c of m.clauses.slice(1)) {
1142
+ let cond = null;
1143
+ if (c.name == "case") {
1144
+ const values = splitMacroArgs(c.args).map(a => this.expr.parse(a));
1145
+ cond = values.map((v) => ({ k: "bin", op: "=", l: subject, r: v }))
1146
+ .reduce((a, b) => ({ k: "bin", op: "or", l: a, r: b }));
1147
+ }
1148
+ out += first ? (cond ? `{{#if ${print(cond)}}}` : "{{#if true}}") : cond ? `{{else if ${print(cond)}}}` : "{{else}}";
1149
+ first = false;
1150
+ out += this.nodes(c.nodes, { ...state, leading: false });
1151
+ }
1152
+ return first ? "" : out + "{{/if}}";
1153
+ }
1154
+ case "include":
1155
+ case "display": {
1156
+ state.leading = false;
1157
+ const target = this.expr.passageName(args[0] ?? "");
1158
+ if ("name" in target)
1159
+ return `{{embed ${print({ k: "str", v: this.sectionName(target.name, m.raw) })}}}`;
1160
+ return `{{embed ${print(target.expr)}}}`;
1161
+ }
1162
+ case "goto":
1163
+ state.leading = false;
1164
+ return this.goto(args[0] ?? "", m.raw);
1165
+ case "link":
1166
+ case "button":
1167
+ case "click":
1168
+ state.leading = false;
1169
+ return this.linkMacro(m, args);
1170
+ case "linkreplace":
1171
+ case "linkappend":
1172
+ case "linkprepend": {
1173
+ state.leading = false;
1174
+ const text = this.linkText(args[0] ?? "");
1175
+ const content = this.body(m, state);
1176
+ const label = this.ctx.newLabel(text.plain);
1177
+ const replacement = m.name == "linkreplace" ? content : m.name == "linkappend" ? text.squiffy + content : content + text.squiffy;
1178
+ const passage = this.ctx.addPassage(text.plain, `{{#replace "${label}"}}${replacement}{{/replace}}`);
1179
+ return `{{#label "${label}"}}${passageLink(text.squiffy, passage)}{{/label}}`;
1180
+ }
1181
+ case "actions":
1182
+ case "choice": {
1183
+ state.leading = false;
1184
+ const links = args.map(a => {
1185
+ const target = this.expr.passageName(a);
1186
+ if (!("name" in target))
1187
+ throw new Unconvertible(`<<${m.name}>> with a passage that isn't fixed`);
1188
+ return sectionLink(escapeText(target.name), this.sectionName(target.name, m.raw));
1189
+ });
1190
+ return m.name == "actions" ? "\n" + links.map(l => `* ${l}`).join("\n") + "\n" : links.join(" ");
1191
+ }
1192
+ case "nobr":
1193
+ return this.nodes(m.clauses[0].nodes, { ...state, nobr: true });
1194
+ case "silently": {
1195
+ const content = this.nodes(m.clauses[0].nodes, state);
1196
+ // Only the helpers, which write nothing
1197
+ return (content.match(/\{\{(?:[^{}]|\{\{[^{}]*\}\})*\}\}/g) ?? []).join("");
1198
+ }
1199
+ case "capture":
1200
+ case "done":
1201
+ case "do":
1202
+ if (m.name == "done")
1203
+ this.ctx.approximate(m.raw, "<<done>> has been converted to its contents, which are shown straight away.");
1204
+ return this.nodes(m.clauses[0].nodes, state);
1205
+ case "timed": {
1206
+ state.leading = false;
1207
+ let delay = 0;
1208
+ let out = "";
1209
+ for (const c of m.clauses) {
1210
+ const d = splitMacroArgs(c.args)[0];
1211
+ const ms = d ? this.expr.parse(d) : { k: "num", v: 0 };
1212
+ if (ms.k != "num")
1213
+ throw new Unconvertible("<<timed>> with a delay that isn't fixed");
1214
+ delay += ms.v;
1215
+ const goto = this.gotoOnly(c.nodes);
1216
+ if (goto)
1217
+ out += goto.replace(/\}\}$/, ` after=${delay}}}`);
1218
+ else
1219
+ out += `{{#animate "fadeIn" start=${delay}}}${this.nodes(c.nodes, { ...state, leading: false })}{{/animate}}`;
1220
+ }
1221
+ return out;
1222
+ }
1223
+ case "type": {
1224
+ state.leading = false;
1225
+ const speed = this.expr.parse(args[0] ?? "40ms");
1226
+ const interval = speed.k == "num" ? ` interval=${speed.v}` : "";
1227
+ return `{{#animate "typewriter"${interval}}}${this.body(m, state)}{{/animate}}`;
1228
+ }
1229
+ case "textbox":
1230
+ case "textarea":
1231
+ case "numberbox": {
1232
+ state.leading = false;
1233
+ const bound = this.receiver(args[0] ?? "");
1234
+ const defaultValue = args[1] ? this.expr.parse(args[1]) : null;
1235
+ if (args.slice(2).some(a => a != "autofocus")) {
1236
+ this.ctx.approximate(m.raw, "Squiffy's text boxes don't go to a passage when Enter is pressed.");
1237
+ }
1238
+ const value = defaultValue?.k == "str" || defaultValue?.k == "num" ? String(defaultValue.v) : null;
1239
+ const set = defaultValue ? `{{set "${bound}" ${print(defaultValue)}}}` : "";
1240
+ if (m.name == "textarea")
1241
+ return `${set}<textarea data-attribute="${bound}">${escapeText(escapeHtml(value ?? ""))}</textarea>`;
1242
+ const type = m.name == "numberbox" ? "number" : "text";
1243
+ return `${set}<input type="${type}" data-attribute="${bound}"${value === null ? "" : ` value="${escapeAttribute(value)}"`}>`;
1244
+ }
1245
+ case "checkbox": {
1246
+ state.leading = false;
1247
+ const bound = this.receiver(args[0] ?? "");
1248
+ this.ctx.approximate(m.raw, "Check how this checkbox works in Squiffy.");
1249
+ return `<input type="checkbox" data-attribute="${bound}">`;
1250
+ }
1251
+ case "radiobutton": {
1252
+ state.leading = false;
1253
+ const bound = this.receiver(args[0] ?? "");
1254
+ const value = this.expr.parse(args[1] ?? "");
1255
+ if (value.k != "str" && value.k != "num")
1256
+ throw new Unconvertible("<<radiobutton>> with a value that isn't fixed");
1257
+ this.ctx.approximate(m.raw, "Check how this radio button works in Squiffy.");
1258
+ return `<input type="radio" name="${bound}" data-attribute="${bound}" value="${escapeAttribute(String(value.v))}">`;
1259
+ }
1260
+ case "cycle":
1261
+ case "listbox": {
1262
+ state.leading = false;
1263
+ const bound = this.receiver(args[0] ?? "");
1264
+ const options = [];
1265
+ for (const c of m.clauses.slice(1)) {
1266
+ if (c.name == "optionsfrom")
1267
+ throw new Unconvertible("<<optionsfrom>>");
1268
+ const [label, value] = splitMacroArgs(c.args).map(a => this.expr.parse(a));
1269
+ if (label?.k != "str" && label?.k != "num")
1270
+ throw new Unconvertible("an option that isn't fixed text");
1271
+ const v = value ? value : label;
1272
+ if (v.k != "str" && v.k != "num")
1273
+ throw new Unconvertible("an option that isn't fixed text");
1274
+ options.push({ label: String(label.v), value: String(v.v) });
1275
+ }
1276
+ if (m.name == "listbox") {
1277
+ return `<select data-attribute="${bound}">${options.map(o => `<option value="${escapeAttribute(o.value)}">${escapeText(escapeHtml(o.label))}</option>`).join("")}</select>`;
1278
+ }
1279
+ if (options.some(o => o.label != o.value)) {
1280
+ this.ctx.approximate(m.raw, "Squiffy's {{rotate}} sets the attribute to the text shown, not the option's value.");
1281
+ }
1282
+ return `{{rotate ${print({ k: "array", items: options.map(o => ({ k: "str", v: o.label })) })} set="${bound}"}}`;
1283
+ }
1284
+ case "replace":
1285
+ case "append":
1286
+ case "prepend":
1287
+ case "remove": {
1288
+ state.leading = false;
1289
+ const target = /^["']#([\w-]+)["']$/.exec(args[0] ?? "");
1290
+ if (!target)
1291
+ throw new Unconvertible(`<<${m.name}>> on something other than an element with an id ("#id")`);
1292
+ const label = this.targets.get(target[1]);
1293
+ const content = m.name == "remove" ? "" : this.body(m, state);
1294
+ if (m.name == "append" || m.name == "prepend") {
1295
+ this.ctx.approximate(m.raw, `<<${m.name}>> has been converted to {{#replace}}, which replaces the text rather than adding to it.`);
1296
+ }
1297
+ return `{{#replace "${label}"}}${content}{{/replace}}`;
1298
+ }
1299
+ case "script":
1300
+ throw new Unconvertible("<<script>>, which runs SugarCube JavaScript");
1301
+ case "for":
1302
+ throw new Unconvertible("<<for>> loops");
1303
+ case "widget":
1304
+ return "";
1305
+ case "back":
1306
+ case "return":
1307
+ throw new Unconvertible(`<<${m.name}>>. Squiffy has its own Back button`);
1308
+ case "audio":
1309
+ case "cacheaudio":
1310
+ case "playlist":
1311
+ case "masteraudio":
1312
+ case "waitforaudio":
1313
+ case "createplaylist":
1314
+ case "createaudiogroup":
1315
+ case "track":
1316
+ throw new Unconvertible("audio macros");
1317
+ case "addclass":
1318
+ case "removeclass":
1319
+ case "toggleclass":
1320
+ throw new Unconvertible("macros that change elements' classes");
1321
+ case "repeat":
1322
+ throw new Unconvertible("<<repeat>>, which runs again and again");
1323
+ case "stop":
1324
+ case "silent":
1325
+ return "";
1326
+ case "elseif":
1327
+ case "else":
1328
+ case "case":
1329
+ case "default":
1330
+ case "next":
1331
+ case "option":
1332
+ throw new Unconvertible(`<<${m.name}>> outside the macro it belongs to`);
1333
+ default:
1334
+ if (this.widgets.has(m.name)) {
1335
+ state.leading = false;
1336
+ return this.widgetCall(m, this.widgets.get(m.name));
1337
+ }
1338
+ if (!knownMacros.has(m.name))
1339
+ throw new Unconvertible(`the <<${m.name}>> macro, which isn't one of SugarCube's own: it's probably added by the story's JavaScript`);
1340
+ throw new Unconvertible(`the <<${m.name}>> macro, which Squiffy has no equivalent for`);
1341
+ }
1342
+ }
1343
+ // The attribute a form macro like <<textbox "$name">> sets
1344
+ receiver(arg) {
1345
+ const match = /^["']([$_])([A-Za-z_]\w*)["']$/.exec(arg);
1346
+ if (!match)
1347
+ throw new Unconvertible("a form control that doesn't set a plain variable");
1348
+ return this.expr.attribute(match[2], match[1] == "_");
1349
+ }
1350
+ linkText(arg) {
1351
+ if (arg.startsWith("[[")) {
1352
+ const node = parseLink(arg.slice(2, -2), arg);
1353
+ return { plain: node.text, squiffy: this.inlineText(node.text) };
1354
+ }
1355
+ const e = this.expr.parse(arg);
1356
+ if (e.k != "str")
1357
+ throw new Unconvertible("a link whose text isn't fixed");
1358
+ return { plain: e.v, squiffy: this.inlineText(e.v) };
1359
+ }
1360
+ sectionName(passage, raw) {
1361
+ const section = this.ctx.story.sectionFor(passage);
1362
+ if (section === undefined) {
1363
+ this.ctx.approximate(raw, `There's no passage called "${passage}".`);
1364
+ return this.ctx.story.sectionForUnknown(passage);
1365
+ }
1366
+ return section;
1367
+ }
1368
+ goto(arg, raw) {
1369
+ const target = this.expr.passageName(arg);
1370
+ if ("name" in target)
1371
+ return `{{goto ${print({ k: "str", v: this.sectionName(target.name, raw) })}}}`;
1372
+ return `{{goto ${print(target.expr)}}}`;
1373
+ }
1374
+ gotoOnly(nodes) {
1375
+ const significant = nodes.filter(n => !(n.t == "text" && n.s.trim() == ""));
1376
+ if (significant.length != 1)
1377
+ return null;
1378
+ const n = significant[0];
1379
+ if (n.t != "macro" || n.name != "goto")
1380
+ return null;
1381
+ return this.goto(splitMacroArgs(n.args)[0] ?? "", n.raw);
1382
+ }
1383
+ // <<link>>, <<button>>: the body runs when it's clicked, then the story goes to the passage
1384
+ // given, if there is one
1385
+ linkMacro(m, args) {
1386
+ let text;
1387
+ let passage = null;
1388
+ let setters = [];
1389
+ let setterSource = null;
1390
+ let dynamicDestination = null;
1391
+ if (args[0]?.startsWith("[[")) {
1392
+ const link = /^\[\[(.*?)\](?:\[(.*)\])?\]$/.exec(args[0]);
1393
+ if (!link)
1394
+ throw new Unconvertible("a link Squiffy can't read");
1395
+ const node = parseLink(link[1], args[0]);
1396
+ text = { plain: node.text, squiffy: this.inlineText(node.text) };
1397
+ passage = node.target;
1398
+ if (link[2]) {
1399
+ setters = this.setters(link[2]);
1400
+ setterSource = link[2];
1401
+ }
1402
+ }
1403
+ else {
1404
+ text = this.linkText(args[0] ?? "");
1405
+ if (args[1]) {
1406
+ const target = this.expr.passageName(args[1]);
1407
+ if ("name" in target)
1408
+ passage = target.name;
1409
+ else
1410
+ dynamicDestination = target.expr;
1411
+ }
1412
+ }
1413
+ const body = m.clauses?.[0]?.nodes ?? [];
1414
+ const significant = body.filter(n => !(n.t == "text" && n.s.trim() == ""));
1415
+ // A trailing <<goto>> is where the link goes
1416
+ const last = significant[significant.length - 1];
1417
+ let gotoArg = null;
1418
+ if (last?.t == "macro" && last.name == "goto") {
1419
+ gotoArg = splitMacroArgs(last.args)[0] ?? "";
1420
+ significant.pop();
1421
+ }
1422
+ const destination = gotoArg !== null ? this.expr.passageName(gotoArg)
1423
+ : passage !== null ? { name: passage }
1424
+ : dynamicDestination ? { expr: dynamicDestination } : null;
1425
+ // Only <<set>>s: a link with setters
1426
+ const bodySetters = this.bodySetters(significant);
1427
+ if (destination && bodySetters) {
1428
+ const all = [...setters, ...bodySetters];
1429
+ if ("name" in destination)
1430
+ return sectionLink(text.squiffy, this.sectionName(destination.name, m.raw), all);
1431
+ return dynamicSectionLink(text.plain, destination.expr, all);
1432
+ }
1433
+ const state = { leading: true, directives: [], nobr: false };
1434
+ const content = this.nodes(body, state);
1435
+ const directives = [...(setterSource === null ? [] : this.setters(setterSource, false).map(s => `@set ${s}`)), ...state.directives];
1436
+ if (destination) {
1437
+ // Run the body in a section of its own, which then goes on to the passage
1438
+ const goto = gotoArg !== null ? "" : "\n" + ("name" in destination
1439
+ ? `{{goto ${print({ k: "str", v: this.sectionName(destination.name, m.raw) })}}}`
1440
+ : `{{goto ${print(destination.expr)}}}`);
1441
+ const section = this.ctx.addSection(`${this.ctx.section}: ${text.plain}`, { directives, body: content + goto });
1442
+ return sectionLink(text.squiffy, section);
1443
+ }
1444
+ // Stays in this passage: a passage link, whose passage does what the body does
1445
+ const name = this.ctx.addPassage(text.plain, { directives, body: content });
1446
+ return passageLink(text.squiffy, name);
1447
+ }
1448
+ // The setters for nodes that are only <<set>>s, or null
1449
+ bodySetters(nodes) {
1450
+ const result = [];
1451
+ for (const n of nodes) {
1452
+ if (n.t != "macro" || n.name != "set")
1453
+ return null;
1454
+ try {
1455
+ result.push(...this.setters(n.args));
1456
+ }
1457
+ catch (e) {
1458
+ if (e instanceof Unconvertible)
1459
+ return null;
1460
+ throw e;
1461
+ }
1462
+ }
1463
+ return result;
1464
+ }
1465
+ set(statements, state) {
1466
+ let out = "";
1467
+ for (const s of statements) {
1468
+ if (state.leading) {
1469
+ switch (s.kind) {
1470
+ case "set":
1471
+ state.directives.push(`@set ${setter(s.name, s.op ?? "=", s.value, false)}`);
1472
+ continue;
1473
+ case "inc":
1474
+ case "dec": {
1475
+ const amount = s.value.k == "num" && Number.isInteger(s.value.v) && s.value.v >= 0 ? s.value.v : null;
1476
+ state.directives.push(amount === null
1477
+ ? `@set ${setter(s.name, s.kind == "inc" ? "+=" : "-=", s.value, false)}`
1478
+ : `@${s.kind} ${s.name}${amount == 1 ? "" : " " + amount}`);
1479
+ continue;
1480
+ }
1481
+ case "unset":
1482
+ state.directives.push(`@unset ${s.name}`);
1483
+ continue;
1484
+ }
1485
+ }
1486
+ state.leading = false;
1487
+ const name = print({ k: "str", v: s.name });
1488
+ switch (s.kind) {
1489
+ case "set":
1490
+ out += s.op
1491
+ ? `{{set ${name} ${print({ k: "bin", op: s.op == "*=" ? "*" : "/", l: { k: "var", name: s.name }, r: s.value })}}}`
1492
+ : `{{set ${name} ${print(s.value)}}}`;
1493
+ break;
1494
+ case "inc":
1495
+ case "dec":
1496
+ out += s.value.k == "num" && s.value.v == 1 ? `{{${s.kind} ${name}}}` : `{{${s.kind} ${name} ${print(s.value)}}}`;
1497
+ break;
1498
+ case "append":
1499
+ case "remove":
1500
+ out += `{{${s.kind} ${name} ${print(s.value)}}}`;
1501
+ break;
1502
+ case "unset":
1503
+ out += `{{unset ${name}}}`;
1504
+ break;
1505
+ }
1506
+ }
1507
+ return out;
1508
+ }
1509
+ }
1510
+ const knownMacros = new Set([
1511
+ "capture", "set", "unset", "run", "script", "include", "nobr", "print", "silently", "type", "if", "switch", "for",
1512
+ "break", "continue", "back", "return", "actions", "choice", "link", "button", "linkappend", "linkprepend",
1513
+ "linkreplace", "checkbox", "cycle", "listbox", "numberbox", "radiobutton", "textarea", "textbox", "addclass",
1514
+ "append", "copy", "prepend", "remove", "removeclass", "replace", "toggleclass", "audio", "cacheaudio",
1515
+ "createaudiogroup", "createplaylist", "masteraudio", "playlist", "removeaudiogroup", "removeplaylist",
1516
+ "waitforaudio", "done", "goto", "repeat", "stop", "timed", "widget", "display", "click", "do", "redo", "track",
1517
+ ]);
1518
+ // The story's widgets, by name, with the section each is converted to
1519
+ export function sugarCubeWidgets(story) {
1520
+ return story.cached("sugarcube-widgets", () => {
1521
+ const result = new Map();
1522
+ for (const p of story.twine.passages) {
1523
+ if (!p.tags.includes("widget"))
1524
+ continue;
1525
+ for (const m of p.text.matchAll(/<<widget\s+["']?([\w-]+)/g)) {
1526
+ const name = m[1].toLowerCase();
1527
+ if (!result.has(name))
1528
+ result.set(name, story.uniqueSectionName(`widget ${name}`));
1529
+ }
1530
+ }
1531
+ return result;
1532
+ });
1533
+ }
1534
+ export function convertSugarCubeWidgets(text, ctx) {
1535
+ const writer = new Writer(ctx);
1536
+ const nodes = new Parser(writer.findTargets(text.replace(/\\\r?\n/g, ""))).parse(0).nodes;
1537
+ return writer.widgetSections(nodes);
1538
+ }
1539
+ function cssAttributes(spec) {
1540
+ const classes = [];
1541
+ const styles = [];
1542
+ let id = "";
1543
+ for (const part of spec.split(/\s+/).filter(p => p)) {
1544
+ if (part.startsWith("."))
1545
+ classes.push(...part.substring(1).split(".").filter(c => c));
1546
+ else if (part.startsWith("#"))
1547
+ id = part.substring(1);
1548
+ else
1549
+ styles.push(part);
1550
+ }
1551
+ let attrs = "";
1552
+ if (id)
1553
+ attrs += ` id="${escapeAttribute(id)}"`;
1554
+ if (classes.length)
1555
+ attrs += ` class="${escapeAttribute(classes.join(" "))}"`;
1556
+ if (styles.length)
1557
+ attrs += ` style="${escapeAttribute(styles.join(" "))}"`;
1558
+ return attrs;
1559
+ }
1560
+ function escapeAttribute(s) {
1561
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/\[/g, "&#91;").replace(/\]/g, "&#93;").replace(/\{\{/g, "&#123;{");
1562
+ }
1563
+ // A character of SugarCube prose, which isn't Markdown: * and _ would be emphasis
1564
+ function escapeProse(s, i) {
1565
+ const c = s[i];
1566
+ if (c == "*")
1567
+ return "&#42;";
1568
+ if (c == "`")
1569
+ return "&#96;";
1570
+ if (c == "_" && !(/\w/.test(s[i - 1] ?? "") && /\w/.test(s[i + 1] ?? "")))
1571
+ return "&#95;";
1572
+ if (c == "{" && s[i + 1] == "{")
1573
+ return "&#123;";
1574
+ if (c == "}" && s[i + 1] == "}")
1575
+ return "&#125;";
1576
+ return escapeText(c);
1577
+ }
1578
+ export function convertSugarCubePassage(text, ctx) {
1579
+ const writer = new Writer(ctx);
1580
+ // A backslash at the end of a line joins it to the next
1581
+ const source = writer.findTargets(text.replace(/\\\r?\n/g, ""));
1582
+ const nodes = new Parser(source).parse(0).nodes;
1583
+ return writer.passage(nodes, ctx.passage.tags.includes("nobr"));
1584
+ }