@rohal12/twee-ts 1.16.0 → 1.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/twee-ts.js +1184 -546
- package/dist/bin/twee-ts.js.map +1 -1
- package/dist/{compiler-BiDNwR9q.js → compiler-Bmpbelqj.js} +596 -270
- package/dist/compiler-Bmpbelqj.js.map +1 -0
- package/dist/index.cjs +1686 -1061
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +28 -7
- package/dist/index.d.ts +28 -7
- package/dist/index.js +1688 -1063
- package/dist/index.js.map +1 -1
- package/dist/plugins/rollup.d.ts +6 -0
- package/dist/plugins/rollup.js +16 -1
- package/dist/plugins/rollup.js.map +1 -1
- package/dist/plugins/vite.js +46 -6
- package/dist/plugins/vite.js.map +1 -1
- package/package.json +1 -1
- package/dist/compiler-BiDNwR9q.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch as watch$1, writeFileSync } from "node:fs";
|
|
1
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch as watch$1, writeFileSync } from "node:fs";
|
|
2
2
|
import * as nodePath from "node:path";
|
|
3
|
-
import { basename, dirname, extname, join, parse, relative, resolve, sep } from "node:path";
|
|
3
|
+
import { basename, dirname, extname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
import { homedir } from "node:os";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
@@ -110,6 +110,61 @@ function commentSanitize(s) {
|
|
|
110
110
|
function htmlCommentSanitize(s) {
|
|
111
111
|
return s.replace(/-->/g, "-- >");
|
|
112
112
|
}
|
|
113
|
+
/**
|
|
114
|
+
* Escape JavaScript for the content of an HTML `<script>` element, so that the HTML parser reads all of it as
|
|
115
|
+
* the element's text and ends the element at the end tag written after it.
|
|
116
|
+
*
|
|
117
|
+
* - Every `<\/script` (in any letter case) becomes `<\/script`. HTML ends a script element at the first
|
|
118
|
+
* `<\/script` followed by whitespace, `/` or `>`, wherever it is in the JavaScript, even inside a string.
|
|
119
|
+
* - Every `<!--` becomes `<\!--`, but only if the text would otherwise end in the HTML tokenizer's "script
|
|
120
|
+
* data double escaped" state: after a `<!--` and then a `<script` start tag with no `-->` between them, the
|
|
121
|
+
* end tag after the text would not end the element.
|
|
122
|
+
*
|
|
123
|
+
* Inserting a backslash after `<` keeps the value of every string, template, and regular expression literal
|
|
124
|
+
* and every comment where these sequences can be written (`\/` and `\!` are identity escapes; a backslash
|
|
125
|
+
* already before the `<` escapes the `<`, as it did before); `<\/script` is also how minifiers such as Terser
|
|
126
|
+
* write inline scripts. It only changes code that uses them outside literals (`a <\/script/ b`, an HTML-like `<!--`
|
|
127
|
+
* comment that is escaped because of a later `<script`), the raw text of a tagged template, and a `<!--` in a
|
|
128
|
+
* regular expression with the `u` or `v` flag. The result is unchanged by escaping it again.
|
|
129
|
+
*/
|
|
130
|
+
function scriptContentEscape(s) {
|
|
131
|
+
const escaped = s.replace(/<(?=\/script)/gi, "<\\");
|
|
132
|
+
return endsDoubleEscaped(escaped) ? escaped.replace(/<(?=!--)/g, "<\\") : escaped;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Whether the HTML tokenizer, reading `s` as script element content with no `<\/script` in it, ends in the
|
|
136
|
+
* "script data double escaped" state, where an end tag after `s` would not end the element.
|
|
137
|
+
* See https://html.spec.whatwg.org/multipage/parsing.html#script-data-escaped-state.
|
|
138
|
+
*/
|
|
139
|
+
function endsDoubleEscaped(s) {
|
|
140
|
+
const scriptStartTag = /<script[\t\n\f\r />]/gi;
|
|
141
|
+
let pos = 0;
|
|
142
|
+
for (;;) {
|
|
143
|
+
const open = s.indexOf("<!--", pos);
|
|
144
|
+
if (open === -1) return false;
|
|
145
|
+
const escapedFrom = open + 2;
|
|
146
|
+
const close = s.indexOf("-->", escapedFrom);
|
|
147
|
+
scriptStartTag.lastIndex = escapedFrom;
|
|
148
|
+
const start = scriptStartTag.exec(s);
|
|
149
|
+
if (start === null || close !== -1 && close < start.index) {
|
|
150
|
+
if (close === -1) return false;
|
|
151
|
+
pos = close + 3;
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
const end = s.indexOf("-->", start.index + start[0].length);
|
|
155
|
+
if (end === -1) return true;
|
|
156
|
+
pos = end + 3;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Escape CSS for the content of an HTML `<style>` element: every `</style` (in any letter case) becomes
|
|
161
|
+
* `<\/style`, since HTML ends a style element at the first `</style` followed by whitespace, `/` or `>`.
|
|
162
|
+
* `\/` stands for `/` in CSS strings and URLs, and comments don't matter; `</style` anywhere else isn't valid
|
|
163
|
+
* CSS anyway.
|
|
164
|
+
*/
|
|
165
|
+
function styleContentEscape(s) {
|
|
166
|
+
return s.replace(/<(?=\/style)/gi, "<\\");
|
|
167
|
+
}
|
|
113
168
|
/** Apply ROT13 encoding to a string (only affects [A-Za-z]). */
|
|
114
169
|
function rot13(s) {
|
|
115
170
|
if (s.length === 0) return s;
|
|
@@ -691,10 +746,35 @@ function getFilenames(pathnames, outFilename, exclude = []) {
|
|
|
691
746
|
diagnostics
|
|
692
747
|
};
|
|
693
748
|
}
|
|
749
|
+
/** Whether the absolute path `file` is the absolute path `dir` or inside it. */
|
|
750
|
+
function isInsideDir(file, dir) {
|
|
751
|
+
return file === dir || file.startsWith(dir.endsWith(sep) ? dir : dir + sep);
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* The watched paths split into folders (as given) and files (absolute). A path
|
|
755
|
+
* that cannot be read counts as a folder, which fs.watch then fails to watch.
|
|
756
|
+
*/
|
|
757
|
+
function splitWatchRoots(pathnames) {
|
|
758
|
+
const dirs = [];
|
|
759
|
+
const files = /* @__PURE__ */ new Set();
|
|
760
|
+
for (const pathname of pathnames) {
|
|
761
|
+
let isFile = false;
|
|
762
|
+
try {
|
|
763
|
+
isFile = statSync(pathname).isFile();
|
|
764
|
+
} catch {}
|
|
765
|
+
if (isFile) files.add(resolve(pathname));
|
|
766
|
+
else dirs.push(pathname);
|
|
767
|
+
}
|
|
768
|
+
return {
|
|
769
|
+
dirs,
|
|
770
|
+
files
|
|
771
|
+
};
|
|
772
|
+
}
|
|
694
773
|
/**
|
|
695
774
|
* Watch paths for changes, calling the build callback on known file type changes.
|
|
696
|
-
* A
|
|
697
|
-
*
|
|
775
|
+
* A folder is watched recursively; a file is watched on its own and counts
|
|
776
|
+
* whatever its type (a head file, say). A change to a file `ignore` returns true
|
|
777
|
+
* for (given the path relative to the working directory) schedules no build.
|
|
698
778
|
* Uses debouncing to avoid rapid rebuilds.
|
|
699
779
|
*/
|
|
700
780
|
function watchFilesystem(pathnames, outFilename, callback, ignore = () => false) {
|
|
@@ -713,18 +793,30 @@ function watchFilesystem(pathnames, outFilename, callback, ignore = () => false)
|
|
|
713
793
|
callback(files);
|
|
714
794
|
}, BUILD_DEBOUNCE);
|
|
715
795
|
}
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
796
|
+
function fileChanged(abs, named) {
|
|
797
|
+
if (abs === absOutFile) return;
|
|
798
|
+
if (!named && !isKnownFileType(abs)) return;
|
|
799
|
+
const rel = relative(process.cwd(), abs);
|
|
800
|
+
if (!ignore(rel || abs)) scheduleBuild(rel || abs);
|
|
801
|
+
}
|
|
802
|
+
function watchPath(pathname, recursive, listener) {
|
|
803
|
+
try {
|
|
804
|
+
watchers.push(watch$1(pathname, { recursive }, (_event, filename) => {
|
|
805
|
+
if (filename) listener(filename);
|
|
806
|
+
}));
|
|
807
|
+
} catch {}
|
|
808
|
+
}
|
|
809
|
+
const { dirs, files } = splitWatchRoots(pathnames);
|
|
810
|
+
const absDirs = dirs.map((dir) => resolve(dir));
|
|
811
|
+
for (const dir of dirs) watchPath(dir, true, (filename) => {
|
|
812
|
+
const abs = resolve(dir, filename);
|
|
813
|
+
fileChanged(abs, files.has(abs));
|
|
814
|
+
});
|
|
815
|
+
const fileDirs = new Set([...files].filter((file) => !absDirs.some((dir) => isInsideDir(file, dir))).map((file) => dirname(file)));
|
|
816
|
+
for (const dir of fileDirs) watchPath(dir, false, (filename) => {
|
|
817
|
+
const abs = resolve(dir, filename);
|
|
818
|
+
if (files.has(abs)) fileChanged(abs, true);
|
|
819
|
+
});
|
|
728
820
|
callback();
|
|
729
821
|
return { close() {
|
|
730
822
|
if (buildTimer) clearTimeout(buildTimer);
|
|
@@ -732,16 +824,25 @@ function watchFilesystem(pathnames, outFilename, callback, ignore = () => false)
|
|
|
732
824
|
} };
|
|
733
825
|
}
|
|
734
826
|
//#endregion
|
|
827
|
+
//#region src/source-text.ts
|
|
828
|
+
/**
|
|
829
|
+
* Source text normalization shared by every input path (files, in-memory sources, `parseTwee`).
|
|
830
|
+
*/
|
|
831
|
+
/**
|
|
832
|
+
* Strip a leading UTF-8 byte order mark and convert CRLF and bare CR line endings to LF.
|
|
833
|
+
* Idempotent, so text that is already normalized passes through unchanged.
|
|
834
|
+
*/
|
|
835
|
+
function normalizeSourceText(text) {
|
|
836
|
+
return (text.charCodeAt(0) === 65279 ? text.slice(1) : text).replace(/\r\n?/g, "\n");
|
|
837
|
+
}
|
|
838
|
+
//#endregion
|
|
735
839
|
//#region src/util.ts
|
|
736
840
|
/**
|
|
737
841
|
* Shared file I/O utilities.
|
|
738
842
|
*/
|
|
739
843
|
/** Read a file as UTF-8 with BOM stripping and line ending normalization. */
|
|
740
844
|
function readUTF8(filename) {
|
|
741
|
-
|
|
742
|
-
if (content.charCodeAt(0) === 65279) content = content.slice(1);
|
|
743
|
-
content = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
744
|
-
return content;
|
|
845
|
+
return normalizeSourceText(readFileSync(filename, "utf-8"));
|
|
745
846
|
}
|
|
746
847
|
/** Read a file as base64. */
|
|
747
848
|
function readBase64(filename) {
|
|
@@ -771,16 +872,28 @@ function relaxedJSONParse(json) {
|
|
|
771
872
|
fixed = fixed.replace(/,\s*([}\]])/g, "$1");
|
|
772
873
|
return JSON.parse(fixed);
|
|
773
874
|
}
|
|
875
|
+
/** A `"setup": function` property, which Harlowe appends to its otherwise-JSON format object. */
|
|
876
|
+
const SETUP_FUNCTION_PROPERTY = /,\s*"setup"\s*:\s*function\b/g;
|
|
877
|
+
/** Drop a trailing `"setup": function(){…}` property from a format object, if it has one. */
|
|
878
|
+
function stripSetupFunction(chunk) {
|
|
879
|
+
let lastIndex = -1;
|
|
880
|
+
for (const match of chunk.matchAll(SETUP_FUNCTION_PROPERTY)) lastIndex = match.index;
|
|
881
|
+
return lastIndex === -1 ? void 0 : chunk.slice(0, lastIndex) + "}";
|
|
882
|
+
}
|
|
774
883
|
/**
|
|
775
884
|
* Parse the Twine 2 format.js JSON chunk.
|
|
776
|
-
* Handles Harlowe's malformed JSON by stripping the "setup" function property.
|
|
885
|
+
* Handles Harlowe's malformed JSON by stripping the "setup" function property. The workaround
|
|
886
|
+
* keys on the property itself, so the same bytes parse whether they come from a `harlowe-3`
|
|
887
|
+
* directory or a direct download.
|
|
777
888
|
* Per spec, the name key is Optional.
|
|
889
|
+
*
|
|
890
|
+
* @param _formatId No longer used; kept so existing callers keep compiling.
|
|
778
891
|
*/
|
|
779
|
-
function parseFormatJSON(source,
|
|
892
|
+
function parseFormatJSON(source, _formatId) {
|
|
780
893
|
const first = source.indexOf("{");
|
|
781
894
|
const last = source.lastIndexOf("}");
|
|
782
895
|
if (first === -1 || last === -1) return null;
|
|
783
|
-
|
|
896
|
+
const chunk = source.slice(first, last + 1);
|
|
784
897
|
const parse = (json) => {
|
|
785
898
|
const raw = relaxedJSONParse(json);
|
|
786
899
|
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
|
|
@@ -803,16 +916,13 @@ function parseFormatJSON(source, formatId) {
|
|
|
803
916
|
try {
|
|
804
917
|
return parse(chunk);
|
|
805
918
|
} catch {
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
} catch {}
|
|
813
|
-
}
|
|
919
|
+
const stripped = stripSetupFunction(chunk);
|
|
920
|
+
if (stripped === void 0) return null;
|
|
921
|
+
try {
|
|
922
|
+
return parse(stripped);
|
|
923
|
+
} catch {
|
|
924
|
+
return null;
|
|
814
925
|
}
|
|
815
|
-
return null;
|
|
816
926
|
}
|
|
817
927
|
}
|
|
818
928
|
/**
|
|
@@ -962,6 +1072,54 @@ function semverCompare(a, b) {
|
|
|
962
1072
|
if (aPatch !== bPatch) return aPatch - bPatch;
|
|
963
1073
|
return 0;
|
|
964
1074
|
}
|
|
1075
|
+
/** Build a directory-style format ID from a name and version, e.g. ('SugarCube', '2.37.3') → 'sugarcube-2'. */
|
|
1076
|
+
function makeFormatId(name, version) {
|
|
1077
|
+
const major = parseSemver(version)?.[0] ?? 0;
|
|
1078
|
+
return `${name.toLowerCase().replace(/\s+/g, "-")}-${major}`;
|
|
1079
|
+
}
|
|
1080
|
+
/** Describe a format request for diagnostics. */
|
|
1081
|
+
function describeFormatRequest(request) {
|
|
1082
|
+
switch (request.kind) {
|
|
1083
|
+
case "id": return `"${request.id}"`;
|
|
1084
|
+
case "name": return request.version ? `"${request.name}" at version "${request.version}"` : `"${request.name}"`;
|
|
1085
|
+
default: throw new Error(`unhandled format request: ${JSON.stringify(request)}`);
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
/**
|
|
1089
|
+
* Pick the candidate that best answers a format request.
|
|
1090
|
+
*
|
|
1091
|
+
* - An ID request ('sugarcube-2') matches a candidate whose name and major version build that ID,
|
|
1092
|
+
* and takes the greatest such version.
|
|
1093
|
+
* - A name request matches the name case-insensitively. An exact version wins outright; otherwise
|
|
1094
|
+
* the greatest version with the same major that is not older than the one asked for (or, with
|
|
1095
|
+
* `allowOlder`, the greatest same-major version). An unparseable requested version takes the
|
|
1096
|
+
* greatest version of any major.
|
|
1097
|
+
*/
|
|
1098
|
+
function selectFormatCandidate(request, candidates, describe, options = {}) {
|
|
1099
|
+
const allowOlder = options.allowOlder ?? false;
|
|
1100
|
+
const wanted = request.kind === "name" ? parseSemver(request.version) : null;
|
|
1101
|
+
let best;
|
|
1102
|
+
for (const candidate of candidates) {
|
|
1103
|
+
const { name, version } = describe(candidate);
|
|
1104
|
+
const have = parseSemver(version);
|
|
1105
|
+
if (!have) continue;
|
|
1106
|
+
if (request.kind === "id") {
|
|
1107
|
+
if (makeFormatId(name, version) !== request.id.toLowerCase()) continue;
|
|
1108
|
+
} else {
|
|
1109
|
+
if (name.toLowerCase() !== request.name.toLowerCase()) continue;
|
|
1110
|
+
if (wanted) {
|
|
1111
|
+
if (semverCompare(have, wanted) === 0) return candidate;
|
|
1112
|
+
if (have[0] !== wanted[0]) continue;
|
|
1113
|
+
if (!allowOlder && semverCompare(have, wanted) < 0) continue;
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
if (!best || semverCompare(have, best.version) > 0) best = {
|
|
1117
|
+
candidate,
|
|
1118
|
+
version: have
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
return best?.candidate;
|
|
1122
|
+
}
|
|
965
1123
|
/** Get format ID from Twine 2 name and version, using SemVer major matching. */
|
|
966
1124
|
function getFormatIdByNameAndVersion(formats, name, version) {
|
|
967
1125
|
const wanted = parseSemver(version);
|
|
@@ -991,171 +1149,586 @@ function readFormatSource(format) {
|
|
|
991
1149
|
return source;
|
|
992
1150
|
}
|
|
993
1151
|
//#endregion
|
|
994
|
-
//#region src/
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
//#endregion
|
|
1005
|
-
//#region src/lexer.ts
|
|
1006
|
-
const EOF = -1;
|
|
1007
|
-
const HEADER_DELIM = "::";
|
|
1008
|
-
const NEWLINE_HEADER_DELIM = "\n::";
|
|
1009
|
-
var LexerContext = class {
|
|
1010
|
-
input;
|
|
1011
|
-
line = 1;
|
|
1012
|
-
start = 0;
|
|
1013
|
-
pos = 0;
|
|
1014
|
-
items = [];
|
|
1015
|
-
constructor(input) {
|
|
1016
|
-
this.input = input;
|
|
1017
|
-
}
|
|
1018
|
-
next() {
|
|
1019
|
-
if (this.pos >= this.input.length) return EOF;
|
|
1020
|
-
const ch = this.input.charCodeAt(this.pos);
|
|
1021
|
-
this.pos++;
|
|
1022
|
-
if (ch === 10) this.line++;
|
|
1023
|
-
return ch;
|
|
1024
|
-
}
|
|
1025
|
-
peek() {
|
|
1026
|
-
if (this.pos >= this.input.length) return EOF;
|
|
1027
|
-
return this.input.charCodeAt(this.pos);
|
|
1028
|
-
}
|
|
1029
|
-
backup() {
|
|
1030
|
-
if (this.pos > this.start) {
|
|
1031
|
-
this.pos--;
|
|
1032
|
-
if (this.input.charCodeAt(this.pos) === 10) this.line--;
|
|
1033
|
-
} else throw new Error("backup would leave pos < start");
|
|
1034
|
-
}
|
|
1035
|
-
emit(type) {
|
|
1036
|
-
const val = this.input.slice(this.start, this.pos);
|
|
1037
|
-
this.items.push({
|
|
1038
|
-
type,
|
|
1039
|
-
line: this.line,
|
|
1040
|
-
pos: this.start,
|
|
1041
|
-
val
|
|
1042
|
-
});
|
|
1043
|
-
if (type === ItemType.Content) {
|
|
1044
|
-
for (let i = this.start; i < this.pos; i++) if (this.input.charCodeAt(i) === 10) this.line++;
|
|
1045
|
-
}
|
|
1046
|
-
this.start = this.pos;
|
|
1047
|
-
}
|
|
1048
|
-
ignore() {
|
|
1049
|
-
for (let i = this.start; i < this.pos; i++) if (this.input.charCodeAt(i) === 10) this.line++;
|
|
1050
|
-
this.start = this.pos;
|
|
1051
|
-
}
|
|
1052
|
-
acceptRun(valid) {
|
|
1053
|
-
let ch;
|
|
1054
|
-
for (ch = this.next(); ch !== EOF && valid.includes(String.fromCharCode(ch)); ch = this.next());
|
|
1055
|
-
if (ch !== EOF) this.backup();
|
|
1056
|
-
}
|
|
1057
|
-
errorf(message) {
|
|
1058
|
-
this.items.push({
|
|
1059
|
-
type: ItemType.Error,
|
|
1060
|
-
line: this.line,
|
|
1061
|
-
pos: this.start,
|
|
1062
|
-
val: message
|
|
1063
|
-
});
|
|
1064
|
-
return null;
|
|
1065
|
-
}
|
|
1066
|
-
/** Drain all pending items and return them. */
|
|
1067
|
-
drainItems() {
|
|
1068
|
-
const result = this.items;
|
|
1069
|
-
this.items = [];
|
|
1070
|
-
return result;
|
|
1071
|
-
}
|
|
1072
|
-
};
|
|
1073
|
-
function acceptQuoted(ctx, quote) {
|
|
1074
|
-
for (;;) {
|
|
1075
|
-
const ch = ctx.next();
|
|
1076
|
-
switch (ch) {
|
|
1077
|
-
case 92: {
|
|
1078
|
-
const r = ctx.next();
|
|
1079
|
-
if (r !== 10 && r !== EOF) break;
|
|
1080
|
-
}
|
|
1081
|
-
case 10:
|
|
1082
|
-
case EOF: return "unterminated quoted string";
|
|
1083
|
-
default: if (ch === quote) return null;
|
|
1084
|
-
}
|
|
1085
|
-
}
|
|
1152
|
+
//#region src/remote-formats.ts
|
|
1153
|
+
/**
|
|
1154
|
+
* Remote story format fetching, caching, and checksum verification.
|
|
1155
|
+
* Uses the Story Formats Archive (SFA) as the default source.
|
|
1156
|
+
*/
|
|
1157
|
+
const DEFAULT_SFA_INDICES = ["https://videlais.github.io/story-formats-archive/official/index.json", "https://videlais.github.io/story-formats-archive/unofficial/index.json"];
|
|
1158
|
+
/** Get the cache directory for downloaded story formats. */
|
|
1159
|
+
function getCacheDir() {
|
|
1160
|
+
const base = process.env["XDG_CACHE_HOME"] || join(homedir(), ".cache");
|
|
1161
|
+
return join(base, "twee-ts", "storyformats");
|
|
1086
1162
|
}
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1163
|
+
/**
|
|
1164
|
+
* Whether a string can serve as one directory name inside the cache: not empty, not `.` or `..`,
|
|
1165
|
+
* and free of path separators. Format names and versions come from downloaded metadata, so they
|
|
1166
|
+
* are untrusted path input.
|
|
1167
|
+
*/
|
|
1168
|
+
function isSafeSegment(segment) {
|
|
1169
|
+
return segment !== "" && segment !== "." && segment !== ".." && !/[/\\\0]/.test(segment);
|
|
1170
|
+
}
|
|
1171
|
+
/** Whether absolute path `target` lies strictly inside absolute path `root`. */
|
|
1172
|
+
function isInside(root, target) {
|
|
1173
|
+
const rel = relative(root, target);
|
|
1174
|
+
return rel !== "" && !isAbsolute(rel) && rel.split(sep)[0] !== "..";
|
|
1175
|
+
}
|
|
1176
|
+
/** The cache directory for one format version. Throws when the name or version could leave the cache. */
|
|
1177
|
+
function cachedFormatDir(name, version) {
|
|
1178
|
+
if (!isSafeSegment(name)) throw new Error(`Refusing to cache a story format with an unsafe name: ${JSON.stringify(name)}`);
|
|
1179
|
+
if (!isSafeSegment(version) || !parseSemver(version)) throw new Error(`Refusing to cache story format "${name}" with an unsafe version: ${JSON.stringify(version)}`);
|
|
1180
|
+
const root = resolve(getCacheDir());
|
|
1181
|
+
const dir = resolve(root, name, version);
|
|
1182
|
+
if (!isInside(root, dir)) throw new Error(`Refusing to cache a story format outside the cache directory ${root}: ${dir}`);
|
|
1183
|
+
return dir;
|
|
1184
|
+
}
|
|
1185
|
+
/** Create `dir` as a plain directory, or check that it already is one (a symlink could lead out of the cache). */
|
|
1186
|
+
function ensurePlainDirectory(dir) {
|
|
1187
|
+
const stat = lstatSync(dir, { throwIfNoEntry: false });
|
|
1188
|
+
if (stat === void 0) {
|
|
1189
|
+
mkdirSync(dir);
|
|
1190
|
+
return;
|
|
1094
1191
|
}
|
|
1095
|
-
|
|
1096
|
-
|
|
1192
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`Refusing to write a story format outside the cache directory: ${dir} is not a plain directory`);
|
|
1193
|
+
}
|
|
1194
|
+
/** Write a downloaded format.js to `<cache>/<name>/<version>/format.js` and return its path. */
|
|
1195
|
+
function writeCachedFormat(name, version, text) {
|
|
1196
|
+
const dir = cachedFormatDir(name, version);
|
|
1197
|
+
const root = resolve(getCacheDir());
|
|
1198
|
+
mkdirSync(root, { recursive: true });
|
|
1199
|
+
ensurePlainDirectory(join(root, name));
|
|
1200
|
+
ensurePlainDirectory(dir);
|
|
1201
|
+
const formatPath = join(dir, "format.js");
|
|
1202
|
+
if (lstatSync(formatPath, { throwIfNoEntry: false })?.isSymbolicLink()) throw new Error(`Refusing to write a story format outside the cache directory: ${formatPath} is a symlink`);
|
|
1203
|
+
writeFileSync(formatPath, text, "utf-8");
|
|
1204
|
+
return formatPath;
|
|
1097
1205
|
}
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
ctx.emit(ItemType.Content);
|
|
1104
|
-
return lexHeaderDelim;
|
|
1105
|
-
}
|
|
1106
|
-
ctx.pos = ctx.input.length;
|
|
1107
|
-
if (ctx.pos > ctx.start) ctx.emit(ItemType.Content);
|
|
1108
|
-
ctx.emit(ItemType.EOF);
|
|
1109
|
-
return null;
|
|
1206
|
+
/** In-memory index cache, keyed by URL. Cleared each compile. */
|
|
1207
|
+
const indexCache = /* @__PURE__ */ new Map();
|
|
1208
|
+
/** Clear the in-memory index cache. */
|
|
1209
|
+
function clearIndexCache() {
|
|
1210
|
+
indexCache.clear();
|
|
1110
1211
|
}
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1212
|
+
/** Validate that a JSON value is a valid SFAIndexEntry. */
|
|
1213
|
+
function isValidEntry(val) {
|
|
1214
|
+
if (typeof val !== "object" || val === null || Array.isArray(val)) return false;
|
|
1215
|
+
const obj = val;
|
|
1216
|
+
return typeof obj.name === "string" && typeof obj.version === "string" && typeof obj.checksums === "object" && obj.checksums !== null && !Array.isArray(obj.checksums);
|
|
1115
1217
|
}
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
r = next;
|
|
1125
|
-
}
|
|
1126
|
-
case 91:
|
|
1127
|
-
case 93:
|
|
1128
|
-
case 123:
|
|
1129
|
-
case 125:
|
|
1130
|
-
case 10:
|
|
1131
|
-
case EOF:
|
|
1132
|
-
if (r !== EOF) ctx.backup();
|
|
1133
|
-
break outer;
|
|
1134
|
-
}
|
|
1135
|
-
}
|
|
1136
|
-
ctx.emit(ItemType.Name);
|
|
1137
|
-
switch (r) {
|
|
1138
|
-
case 91: return lexTags;
|
|
1139
|
-
case 93: return ctx.errorf(`unexpected right square bracket ']'`);
|
|
1140
|
-
case 123: return lexMetadata;
|
|
1141
|
-
case 125: return ctx.errorf(`unexpected right curly brace '}'`);
|
|
1142
|
-
case 10:
|
|
1143
|
-
ctx.pos++;
|
|
1144
|
-
ctx.ignore();
|
|
1145
|
-
return lexContent;
|
|
1146
|
-
}
|
|
1147
|
-
ctx.emit(ItemType.EOF);
|
|
1148
|
-
return null;
|
|
1218
|
+
/** Validate that a JSON value conforms to the SFAIndex shape. */
|
|
1219
|
+
function validateSFAIndex(json) {
|
|
1220
|
+
if (typeof json !== "object" || json === null) throw new Error("SFA index is not an object");
|
|
1221
|
+
const obj = json;
|
|
1222
|
+
return {
|
|
1223
|
+
twine1: Array.isArray(obj["twine1"]) ? obj["twine1"].filter(isValidEntry) : [],
|
|
1224
|
+
twine2: Array.isArray(obj["twine2"]) ? obj["twine2"].filter(isValidEntry) : []
|
|
1225
|
+
};
|
|
1149
1226
|
}
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1227
|
+
/** Fetch and parse an SFA index.json, with in-memory caching. */
|
|
1228
|
+
async function fetchIndex(url) {
|
|
1229
|
+
const cached = indexCache.get(url);
|
|
1230
|
+
if (cached) return cached;
|
|
1231
|
+
const res = await fetch(url);
|
|
1232
|
+
if (!res.ok) throw new Error(`Failed to fetch format index from ${url}: ${res.status} ${res.statusText}`);
|
|
1233
|
+
const data = validateSFAIndex(await res.json());
|
|
1234
|
+
indexCache.set(url, data);
|
|
1235
|
+
return data;
|
|
1236
|
+
}
|
|
1237
|
+
/** Find the best matching entry in an SFA index for a name or ID request (twine2 entries first). */
|
|
1238
|
+
function findEntryForRequest(index, request) {
|
|
1239
|
+
return selectFormatCandidate(request, [...(index.twine2 ?? []).map((entry) => ({
|
|
1240
|
+
entry,
|
|
1241
|
+
formatType: "twine2"
|
|
1242
|
+
})), ...(index.twine1 ?? []).map((entry) => ({
|
|
1243
|
+
entry,
|
|
1244
|
+
formatType: "twine1"
|
|
1245
|
+
}))], (c) => c.entry);
|
|
1246
|
+
}
|
|
1247
|
+
/** Verify SHA-256 checksum using Web Crypto API (Node 22 built-in). */
|
|
1248
|
+
async function verifySHA256(content, expectedHex) {
|
|
1249
|
+
const digest = await crypto.subtle.digest("SHA-256", content);
|
|
1250
|
+
return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("") === expectedHex.toLowerCase();
|
|
1251
|
+
}
|
|
1252
|
+
/** Derive the download URL for a format.js from the index URL and entry. */
|
|
1253
|
+
function getDownloadUrl(indexUrl, entry, formatType) {
|
|
1254
|
+
return `${indexUrl.replace(/\/index\.json$/, "")}/${formatType}/${entry.name}/${entry.version}/format.js`;
|
|
1255
|
+
}
|
|
1256
|
+
/** Download a format, verify its checksum, write to cache, and return StoryFormatInfo. */
|
|
1257
|
+
async function fetchAndCacheFormat(entry, downloadUrl) {
|
|
1258
|
+
cachedFormatDir(entry.name, entry.version);
|
|
1259
|
+
const res = await fetch(downloadUrl);
|
|
1260
|
+
if (!res.ok) throw new Error(`Failed to download format from ${downloadUrl}: ${res.status} ${res.statusText}`);
|
|
1261
|
+
const text = await res.text();
|
|
1262
|
+
const checksumKey = Object.keys(entry.checksums ?? {}).find((k) => k.endsWith("format.js"));
|
|
1263
|
+
if (checksumKey) {
|
|
1264
|
+
const expected = entry.checksums[checksumKey];
|
|
1265
|
+
if (!expected) throw new Error(`Missing checksum value for key "${checksumKey}"`);
|
|
1266
|
+
if (!await verifySHA256(new TextEncoder().encode(text), expected)) throw new Error(`Checksum verification failed for ${entry.name} ${entry.version}`);
|
|
1267
|
+
}
|
|
1268
|
+
const id = makeFormatId(entry.name, entry.version);
|
|
1269
|
+
const data = parseFormatJSON(text, id);
|
|
1270
|
+
if (!data) throw new Error(`Failed to parse format JSON from ${downloadUrl}`);
|
|
1271
|
+
return {
|
|
1272
|
+
id,
|
|
1273
|
+
filename: writeCachedFormat(entry.name, entry.version, text),
|
|
1274
|
+
isTwine2: true,
|
|
1275
|
+
name: data.name,
|
|
1276
|
+
version: data.version,
|
|
1277
|
+
proofing: data.proofing ?? false
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
/** Download a direct format.js URL, parse its JSON, cache it, and return StoryFormatInfo. */
|
|
1281
|
+
async function fetchDirectFormat(url) {
|
|
1282
|
+
const res = await fetch(url);
|
|
1283
|
+
if (!res.ok) throw new Error(`Failed to download format from ${url}: ${res.status} ${res.statusText}`);
|
|
1284
|
+
const text = await res.text();
|
|
1285
|
+
const data = parseFormatJSON(text);
|
|
1286
|
+
if (!data) throw new Error(`Failed to parse format JSON from ${url}`);
|
|
1287
|
+
return {
|
|
1288
|
+
id: makeFormatId(data.name, data.version),
|
|
1289
|
+
filename: writeCachedFormat(data.name, data.version, text),
|
|
1290
|
+
isTwine2: true,
|
|
1291
|
+
name: data.name,
|
|
1292
|
+
version: data.version,
|
|
1293
|
+
proofing: data.proofing ?? false
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
/**
|
|
1297
|
+
* Try to resolve a remote story format by name and version.
|
|
1298
|
+
* 0. Use an exactly matching cached download, without touching the network
|
|
1299
|
+
* 1. Try direct format URLs
|
|
1300
|
+
* 2. Try custom index URLs
|
|
1301
|
+
* 3. Try default SFA indices
|
|
1302
|
+
* 4. Fall back to a compatible cached download (e.g. when offline)
|
|
1303
|
+
*/
|
|
1304
|
+
async function resolveRemoteFormat(name, version, indices, urls) {
|
|
1305
|
+
return resolveRemoteFormatRequest({
|
|
1306
|
+
kind: "name",
|
|
1307
|
+
name,
|
|
1308
|
+
version
|
|
1309
|
+
}, indices, urls);
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* Resolve a story format request remotely, in the same order as {@link resolveRemoteFormat}.
|
|
1313
|
+
* An ID request such as 'sugarcube-2' matches the format whose name and major version build that ID
|
|
1314
|
+
* (SugarCube 2.x), taking the greatest version available.
|
|
1315
|
+
*/
|
|
1316
|
+
async function resolveRemoteFormatRequest(request, indices, urls) {
|
|
1317
|
+
let lastError;
|
|
1318
|
+
const cached = findCachedFormat(request);
|
|
1319
|
+
if (cached && request.kind === "name" && isExactVersion(cached.version, request.version)) return cached;
|
|
1320
|
+
for (const url of urls ?? []) try {
|
|
1321
|
+
const info = await fetchDirectFormat(url);
|
|
1322
|
+
if (selectFormatCandidate(request, [info], (f) => f)) return info;
|
|
1323
|
+
} catch (e) {
|
|
1324
|
+
lastError = e instanceof Error ? e : new Error(String(e));
|
|
1325
|
+
}
|
|
1326
|
+
const allIndices = [...indices ?? [], ...DEFAULT_SFA_INDICES];
|
|
1327
|
+
for (const indexUrl of allIndices) try {
|
|
1328
|
+
const result = findEntryForRequest(await fetchIndex(indexUrl), request);
|
|
1329
|
+
if (result) {
|
|
1330
|
+
const hit = getCachedFormat(result.entry.name, result.entry.version);
|
|
1331
|
+
if (hit) return hit;
|
|
1332
|
+
const downloadUrl = getDownloadUrl(indexUrl, result.entry, result.formatType);
|
|
1333
|
+
return await fetchAndCacheFormat(result.entry, downloadUrl);
|
|
1334
|
+
}
|
|
1335
|
+
} catch (e) {
|
|
1336
|
+
lastError = e instanceof Error ? e : new Error(String(e));
|
|
1337
|
+
}
|
|
1338
|
+
if (cached) return cached;
|
|
1339
|
+
if (lastError) throw lastError;
|
|
1340
|
+
}
|
|
1341
|
+
/** Whether two version strings name the same SemVer version. */
|
|
1342
|
+
function isExactVersion(have, wanted) {
|
|
1343
|
+
const a = parseSemver(have);
|
|
1344
|
+
const b = parseSemver(wanted);
|
|
1345
|
+
return a !== null && b !== null && a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
|
|
1346
|
+
}
|
|
1347
|
+
/**
|
|
1348
|
+
* Find the cached download that best answers a format request, without network access.
|
|
1349
|
+
* Matching follows {@link selectFormatCandidate}.
|
|
1350
|
+
*/
|
|
1351
|
+
function findCachedFormat(request, options = {}) {
|
|
1352
|
+
return selectFormatCandidate(request, [...discoverCachedFormats().values()], (f) => f, options);
|
|
1353
|
+
}
|
|
1354
|
+
/** Check if a format is already in the local cache. */
|
|
1355
|
+
function getCachedFormat(name, version) {
|
|
1356
|
+
if (!isSafeSegment(name) || !isSafeSegment(version)) return void 0;
|
|
1357
|
+
const formatPath = join(getCacheDir(), name, version, "format.js");
|
|
1358
|
+
try {
|
|
1359
|
+
if (!existsSync(formatPath)) return void 0;
|
|
1360
|
+
const source = readFileSync(formatPath, "utf-8");
|
|
1361
|
+
const id = makeFormatId(name, version);
|
|
1362
|
+
const data = parseFormatJSON(source, id);
|
|
1363
|
+
if (!data) return void 0;
|
|
1364
|
+
return {
|
|
1365
|
+
id,
|
|
1366
|
+
filename: formatPath,
|
|
1367
|
+
isTwine2: true,
|
|
1368
|
+
name: data.name,
|
|
1369
|
+
version: data.version,
|
|
1370
|
+
proofing: data.proofing ?? false
|
|
1371
|
+
};
|
|
1372
|
+
} catch {
|
|
1373
|
+
return;
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
/** Discover all cached remote formats. Returns a Map like discoverFormats(). */
|
|
1377
|
+
function discoverCachedFormats() {
|
|
1378
|
+
const formats = /* @__PURE__ */ new Map();
|
|
1379
|
+
const cacheDir = getCacheDir();
|
|
1380
|
+
try {
|
|
1381
|
+
if (!existsSync(cacheDir)) return formats;
|
|
1382
|
+
} catch {
|
|
1383
|
+
return formats;
|
|
1384
|
+
}
|
|
1385
|
+
let names;
|
|
1386
|
+
try {
|
|
1387
|
+
names = readdirSync(cacheDir);
|
|
1388
|
+
} catch {
|
|
1389
|
+
return formats;
|
|
1390
|
+
}
|
|
1391
|
+
for (const name of names) {
|
|
1392
|
+
const nameDir = join(cacheDir, name);
|
|
1393
|
+
try {
|
|
1394
|
+
if (!statSync(nameDir).isDirectory()) continue;
|
|
1395
|
+
} catch {
|
|
1396
|
+
continue;
|
|
1397
|
+
}
|
|
1398
|
+
let versions;
|
|
1399
|
+
try {
|
|
1400
|
+
versions = readdirSync(nameDir);
|
|
1401
|
+
} catch {
|
|
1402
|
+
continue;
|
|
1403
|
+
}
|
|
1404
|
+
for (const version of versions) {
|
|
1405
|
+
const info = getCachedFormat(name, version);
|
|
1406
|
+
if (info) formats.set(`${info.id}-${version}`, info);
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
return formats;
|
|
1410
|
+
}
|
|
1411
|
+
/** List all cached formats with size and modification date. */
|
|
1412
|
+
function listCachedFormats() {
|
|
1413
|
+
const cacheDir = getCacheDir();
|
|
1414
|
+
const entries = [];
|
|
1415
|
+
try {
|
|
1416
|
+
if (!existsSync(cacheDir)) return entries;
|
|
1417
|
+
} catch {
|
|
1418
|
+
return entries;
|
|
1419
|
+
}
|
|
1420
|
+
let names;
|
|
1421
|
+
try {
|
|
1422
|
+
names = readdirSync(cacheDir);
|
|
1423
|
+
} catch {
|
|
1424
|
+
return entries;
|
|
1425
|
+
}
|
|
1426
|
+
for (const name of names) {
|
|
1427
|
+
const nameDir = join(cacheDir, name);
|
|
1428
|
+
try {
|
|
1429
|
+
if (!statSync(nameDir).isDirectory()) continue;
|
|
1430
|
+
} catch {
|
|
1431
|
+
continue;
|
|
1432
|
+
}
|
|
1433
|
+
let versions;
|
|
1434
|
+
try {
|
|
1435
|
+
versions = readdirSync(nameDir);
|
|
1436
|
+
} catch {
|
|
1437
|
+
continue;
|
|
1438
|
+
}
|
|
1439
|
+
for (const version of versions) {
|
|
1440
|
+
const formatPath = join(nameDir, version, "format.js");
|
|
1441
|
+
try {
|
|
1442
|
+
const stat = statSync(formatPath);
|
|
1443
|
+
entries.push({
|
|
1444
|
+
name,
|
|
1445
|
+
version,
|
|
1446
|
+
sizeBytes: stat.size,
|
|
1447
|
+
modifiedAt: stat.mtime
|
|
1448
|
+
});
|
|
1449
|
+
} catch {}
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
return entries;
|
|
1453
|
+
}
|
|
1454
|
+
/**
|
|
1455
|
+
* Clear all cached formats, or only those matching a given name. Returns the number of entries removed.
|
|
1456
|
+
* A name must be a single cache entry name (as `listCachedFormats()` reports it); anything with a
|
|
1457
|
+
* path separator or `.`/`..` throws instead of deleting outside the format's own directory.
|
|
1458
|
+
*/
|
|
1459
|
+
function clearCachedFormats(name) {
|
|
1460
|
+
if (name && !isSafeSegment(name)) throw new Error(`Refusing to clear ${JSON.stringify(name)}: it is not a cached format name. Use a name as "cache list" shows it.`);
|
|
1461
|
+
const cacheDir = getCacheDir();
|
|
1462
|
+
if (!existsSync(cacheDir)) return 0;
|
|
1463
|
+
if (!name) {
|
|
1464
|
+
const count = listCachedFormats().length;
|
|
1465
|
+
rmSync(cacheDir, {
|
|
1466
|
+
recursive: true,
|
|
1467
|
+
force: true
|
|
1468
|
+
});
|
|
1469
|
+
return count;
|
|
1470
|
+
}
|
|
1471
|
+
const root = resolve(cacheDir);
|
|
1472
|
+
const nameDir = resolve(root, name);
|
|
1473
|
+
if (!isInside(root, nameDir)) throw new Error(`Refusing to clear ${JSON.stringify(name)}: it is not a cached format name.`);
|
|
1474
|
+
if (!lstatSync(nameDir, { throwIfNoEntry: false })?.isDirectory()) return 0;
|
|
1475
|
+
let versions;
|
|
1476
|
+
try {
|
|
1477
|
+
versions = readdirSync(nameDir);
|
|
1478
|
+
} catch {
|
|
1479
|
+
return 0;
|
|
1480
|
+
}
|
|
1481
|
+
const count = versions.length;
|
|
1482
|
+
rmSync(nameDir, {
|
|
1483
|
+
recursive: true,
|
|
1484
|
+
force: true
|
|
1485
|
+
});
|
|
1486
|
+
return count;
|
|
1487
|
+
}
|
|
1488
|
+
/** Get total cache size in bytes and format count. */
|
|
1489
|
+
function getCacheSize() {
|
|
1490
|
+
const entries = listCachedFormats();
|
|
1491
|
+
return {
|
|
1492
|
+
totalBytes: entries.reduce((sum, e) => sum + e.sizeBytes, 0),
|
|
1493
|
+
count: entries.length
|
|
1494
|
+
};
|
|
1495
|
+
}
|
|
1496
|
+
//#endregion
|
|
1497
|
+
//#region src/format-resolution.ts
|
|
1498
|
+
/** Choose the format request: explicit format ID > StoryData format > default ID. */
|
|
1499
|
+
function formatRequestFor(formatId, storyFormat, storyFormatVersion, defaultId) {
|
|
1500
|
+
if (formatId) return {
|
|
1501
|
+
kind: "id",
|
|
1502
|
+
id: formatId
|
|
1503
|
+
};
|
|
1504
|
+
if (storyFormat) return {
|
|
1505
|
+
kind: "name",
|
|
1506
|
+
name: storyFormat,
|
|
1507
|
+
version: storyFormatVersion
|
|
1508
|
+
};
|
|
1509
|
+
return {
|
|
1510
|
+
kind: "id",
|
|
1511
|
+
id: defaultId
|
|
1512
|
+
};
|
|
1513
|
+
}
|
|
1514
|
+
/** Look a request up among the formats found in local format directories. */
|
|
1515
|
+
function findLocalFormat(formats, request) {
|
|
1516
|
+
switch (request.kind) {
|
|
1517
|
+
case "id": return formats.get(request.id);
|
|
1518
|
+
case "name": {
|
|
1519
|
+
const id = getFormatIdByNameAndVersion(formats, request.name, request.version);
|
|
1520
|
+
return id === void 0 ? void 0 : formats.get(id);
|
|
1521
|
+
}
|
|
1522
|
+
default: throw new Error(`unhandled format request: ${JSON.stringify(request)}`);
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
/**
|
|
1526
|
+
* Resolve a format request to a story format.
|
|
1527
|
+
*
|
|
1528
|
+
* Order: local format directories, then the download cache, then remote sources (unless
|
|
1529
|
+
* `noRemote`). When a StoryData request names a version that none of them has, an older version of
|
|
1530
|
+
* the same format and major version is used with a warning. Anything else is an error diagnostic,
|
|
1531
|
+
* and the result is `undefined`.
|
|
1532
|
+
*/
|
|
1533
|
+
async function resolveStoryFormat(request, options, diagnostics) {
|
|
1534
|
+
const noRemote = options.noRemote ?? false;
|
|
1535
|
+
const formats = discoverFormats(getFormatSearchDirs(options.formatPaths, options.useTweegoPath ?? true));
|
|
1536
|
+
const wanted = describeFormatRequest(request);
|
|
1537
|
+
const local = findLocalFormat(formats, request);
|
|
1538
|
+
if (local) return local;
|
|
1539
|
+
const cached = findCachedFormat(request);
|
|
1540
|
+
if (cached) return cached;
|
|
1541
|
+
if (!noRemote) try {
|
|
1542
|
+
const remote = await resolveRemoteFormatRequest(request, options.formatIndices, options.formatUrls);
|
|
1543
|
+
if (remote) return remote;
|
|
1544
|
+
} catch (e) {
|
|
1545
|
+
diagnostics.push({
|
|
1546
|
+
level: "warning",
|
|
1547
|
+
message: `Remote format fetch failed for ${wanted}: ${e instanceof Error ? e.message : String(e)}`
|
|
1548
|
+
});
|
|
1549
|
+
}
|
|
1550
|
+
if (request.kind === "name") {
|
|
1551
|
+
const older = selectFormatCandidate(request, [...formats.values()].filter((f) => f.isTwine2), (f) => f, { allowOlder: true }) ?? findCachedFormat(request, { allowOlder: true });
|
|
1552
|
+
if (older) {
|
|
1553
|
+
diagnostics.push({
|
|
1554
|
+
level: "warning",
|
|
1555
|
+
message: `Story format ${wanted} is not available; using ${older.name} ${older.version} instead.`
|
|
1556
|
+
});
|
|
1557
|
+
return older;
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
const reason = noRemote ? " (remote fetching disabled)" : "";
|
|
1561
|
+
diagnostics.push({
|
|
1562
|
+
level: "error",
|
|
1563
|
+
message: `Story format ${wanted} is not available${reason}. Found: ${[...formats.keys()].join(", ") || "none"}`
|
|
1564
|
+
});
|
|
1565
|
+
}
|
|
1566
|
+
//#endregion
|
|
1567
|
+
//#region src/types.ts
|
|
1568
|
+
const ItemType = {
|
|
1569
|
+
Error: 0,
|
|
1570
|
+
EOF: 1,
|
|
1571
|
+
Header: 2,
|
|
1572
|
+
Name: 3,
|
|
1573
|
+
Tags: 4,
|
|
1574
|
+
Metadata: 5,
|
|
1575
|
+
Content: 6
|
|
1576
|
+
};
|
|
1577
|
+
//#endregion
|
|
1578
|
+
//#region src/lexer.ts
|
|
1579
|
+
const EOF = -1;
|
|
1580
|
+
const HEADER_DELIM = "::";
|
|
1581
|
+
const NEWLINE_HEADER_DELIM = "\n::";
|
|
1582
|
+
var LexerContext = class {
|
|
1583
|
+
input;
|
|
1584
|
+
line = 1;
|
|
1585
|
+
start = 0;
|
|
1586
|
+
pos = 0;
|
|
1587
|
+
items = [];
|
|
1588
|
+
constructor(input) {
|
|
1589
|
+
this.input = input;
|
|
1590
|
+
}
|
|
1591
|
+
next() {
|
|
1592
|
+
if (this.pos >= this.input.length) return EOF;
|
|
1593
|
+
const ch = this.input.charCodeAt(this.pos);
|
|
1594
|
+
this.pos++;
|
|
1595
|
+
if (ch === 10) this.line++;
|
|
1596
|
+
return ch;
|
|
1597
|
+
}
|
|
1598
|
+
peek() {
|
|
1599
|
+
if (this.pos >= this.input.length) return EOF;
|
|
1600
|
+
return this.input.charCodeAt(this.pos);
|
|
1601
|
+
}
|
|
1602
|
+
backup() {
|
|
1603
|
+
if (this.pos > this.start) {
|
|
1604
|
+
this.pos--;
|
|
1605
|
+
if (this.input.charCodeAt(this.pos) === 10) this.line--;
|
|
1606
|
+
} else throw new Error("backup would leave pos < start");
|
|
1607
|
+
}
|
|
1608
|
+
emit(type) {
|
|
1609
|
+
const val = this.input.slice(this.start, this.pos);
|
|
1610
|
+
this.items.push({
|
|
1611
|
+
type,
|
|
1612
|
+
line: this.line,
|
|
1613
|
+
pos: this.start,
|
|
1614
|
+
val
|
|
1615
|
+
});
|
|
1616
|
+
if (type === ItemType.Content) {
|
|
1617
|
+
for (let i = this.start; i < this.pos; i++) if (this.input.charCodeAt(i) === 10) this.line++;
|
|
1618
|
+
}
|
|
1619
|
+
this.start = this.pos;
|
|
1620
|
+
}
|
|
1621
|
+
ignore() {
|
|
1622
|
+
for (let i = this.start; i < this.pos; i++) if (this.input.charCodeAt(i) === 10) this.line++;
|
|
1623
|
+
this.start = this.pos;
|
|
1624
|
+
}
|
|
1625
|
+
acceptRun(valid) {
|
|
1626
|
+
let ch;
|
|
1627
|
+
for (ch = this.next(); ch !== EOF && valid.includes(String.fromCharCode(ch)); ch = this.next());
|
|
1628
|
+
if (ch !== EOF) this.backup();
|
|
1629
|
+
}
|
|
1630
|
+
errorf(message) {
|
|
1631
|
+
this.items.push({
|
|
1632
|
+
type: ItemType.Error,
|
|
1633
|
+
line: this.line,
|
|
1634
|
+
pos: this.start,
|
|
1635
|
+
val: message
|
|
1636
|
+
});
|
|
1637
|
+
return null;
|
|
1638
|
+
}
|
|
1639
|
+
/** Drain all pending items and return them. */
|
|
1640
|
+
drainItems() {
|
|
1641
|
+
const result = this.items;
|
|
1642
|
+
this.items = [];
|
|
1643
|
+
return result;
|
|
1644
|
+
}
|
|
1645
|
+
};
|
|
1646
|
+
function acceptQuoted(ctx, quote) {
|
|
1647
|
+
for (;;) {
|
|
1648
|
+
const ch = ctx.next();
|
|
1649
|
+
switch (ch) {
|
|
1650
|
+
case 92: {
|
|
1651
|
+
const r = ctx.next();
|
|
1652
|
+
if (r !== 10 && r !== EOF) break;
|
|
1653
|
+
}
|
|
1654
|
+
case 10:
|
|
1655
|
+
case EOF: return "unterminated quoted string";
|
|
1656
|
+
default: if (ch === quote) return null;
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
function lexProlog(ctx) {
|
|
1661
|
+
if (ctx.input.startsWith(HEADER_DELIM, ctx.pos)) return lexHeaderDelim;
|
|
1662
|
+
const i = ctx.input.indexOf(NEWLINE_HEADER_DELIM, ctx.pos);
|
|
1663
|
+
if (i > -1) {
|
|
1664
|
+
ctx.pos = i + 1;
|
|
1665
|
+
ctx.ignore();
|
|
1666
|
+
return lexHeaderDelim;
|
|
1667
|
+
}
|
|
1668
|
+
ctx.emit(ItemType.EOF);
|
|
1669
|
+
return null;
|
|
1670
|
+
}
|
|
1671
|
+
function lexContent(ctx) {
|
|
1672
|
+
if (ctx.input.startsWith(HEADER_DELIM, ctx.pos)) return lexHeaderDelim;
|
|
1673
|
+
const i = ctx.input.indexOf(NEWLINE_HEADER_DELIM, ctx.pos);
|
|
1674
|
+
if (i > -1) {
|
|
1675
|
+
ctx.pos = i + 1;
|
|
1676
|
+
ctx.emit(ItemType.Content);
|
|
1677
|
+
return lexHeaderDelim;
|
|
1678
|
+
}
|
|
1679
|
+
ctx.pos = ctx.input.length;
|
|
1680
|
+
if (ctx.pos > ctx.start) ctx.emit(ItemType.Content);
|
|
1681
|
+
ctx.emit(ItemType.EOF);
|
|
1682
|
+
return null;
|
|
1683
|
+
}
|
|
1684
|
+
function lexHeaderDelim(ctx) {
|
|
1685
|
+
ctx.pos += 2;
|
|
1686
|
+
ctx.emit(ItemType.Header);
|
|
1687
|
+
return lexName;
|
|
1688
|
+
}
|
|
1689
|
+
function lexName(ctx) {
|
|
1690
|
+
let r;
|
|
1691
|
+
outer: for (;;) {
|
|
1692
|
+
r = ctx.next();
|
|
1693
|
+
switch (r) {
|
|
1694
|
+
case 92: {
|
|
1695
|
+
const next = ctx.next();
|
|
1696
|
+
if (next !== 10 && next !== EOF) break;
|
|
1697
|
+
r = next;
|
|
1698
|
+
}
|
|
1699
|
+
case 91:
|
|
1700
|
+
case 93:
|
|
1701
|
+
case 123:
|
|
1702
|
+
case 125:
|
|
1703
|
+
case 10:
|
|
1704
|
+
case EOF:
|
|
1705
|
+
if (r !== EOF) ctx.backup();
|
|
1706
|
+
break outer;
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
ctx.emit(ItemType.Name);
|
|
1710
|
+
switch (r) {
|
|
1711
|
+
case 91: return lexTags;
|
|
1712
|
+
case 93: return ctx.errorf(`unexpected right square bracket ']'`);
|
|
1713
|
+
case 123: return lexMetadata;
|
|
1714
|
+
case 125: return ctx.errorf(`unexpected right curly brace '}'`);
|
|
1715
|
+
case 10:
|
|
1716
|
+
ctx.pos++;
|
|
1717
|
+
ctx.ignore();
|
|
1718
|
+
return lexContent;
|
|
1719
|
+
}
|
|
1720
|
+
ctx.emit(ItemType.EOF);
|
|
1721
|
+
return null;
|
|
1722
|
+
}
|
|
1723
|
+
function lexNextOptionalBlock(ctx) {
|
|
1724
|
+
ctx.acceptRun(" ");
|
|
1725
|
+
ctx.ignore();
|
|
1726
|
+
const r = ctx.peek();
|
|
1727
|
+
switch (r) {
|
|
1728
|
+
case 91: return lexTags;
|
|
1729
|
+
case 93: return ctx.errorf(`unexpected right square bracket ']'`);
|
|
1730
|
+
case 123: return lexMetadata;
|
|
1731
|
+
case 125: return ctx.errorf(`unexpected right curly brace '}'`);
|
|
1159
1732
|
case 10:
|
|
1160
1733
|
ctx.pos++;
|
|
1161
1734
|
ctx.ignore();
|
|
@@ -1280,16 +1853,20 @@ function twee2ToV3(s) {
|
|
|
1280
1853
|
//#region src/parser.ts
|
|
1281
1854
|
/**
|
|
1282
1855
|
* Parse Twee source text into passages.
|
|
1856
|
+
*
|
|
1857
|
+
* The source is normalized first, as files are when they are read: a leading UTF-8 BOM is
|
|
1858
|
+
* removed and CRLF and bare CR line endings become LF.
|
|
1283
1859
|
*/
|
|
1284
1860
|
function parseTwee(source, options = {}) {
|
|
1285
1861
|
const { filename = "<inline>", trim = true, twee2Compat = false } = options;
|
|
1286
1862
|
const diagnostics = [];
|
|
1287
|
-
|
|
1863
|
+
const normalized = normalizeSourceText(source);
|
|
1864
|
+
const tweeSource = twee2Compat ? twee2ToV3(normalized) : normalized;
|
|
1288
1865
|
const passages = [];
|
|
1289
1866
|
let current = null;
|
|
1290
1867
|
let pCount = 0;
|
|
1291
1868
|
let lastType = ItemType.EOF;
|
|
1292
|
-
for (const item of tweeLexer(
|
|
1869
|
+
for (const item of tweeLexer(tweeSource)) {
|
|
1293
1870
|
switch (item.type) {
|
|
1294
1871
|
case ItemType.Error:
|
|
1295
1872
|
diagnostics.push({
|
|
@@ -4170,6 +4747,7 @@ function decompileTwine2(storyData, story, diagnostics) {
|
|
|
4170
4747
|
});
|
|
4171
4748
|
else story.twine2.zoom = parsed;
|
|
4172
4749
|
}
|
|
4750
|
+
if (attrs["tags"]) story.twine2.tags = attrs["tags"];
|
|
4173
4751
|
if (attrs["format"]) story.twine2.format = attrs["format"];
|
|
4174
4752
|
if (attrs["format-version"]) story.twine2.formatVersion = attrs["format-version"];
|
|
4175
4753
|
if (attrs["options"]) for (const opt of attrs["options"].split(/\s+/).filter((s) => s.length > 0)) story.twine2.options.set(opt, true);
|
|
@@ -4229,22 +4807,32 @@ function decompileTwine2(storyData, story, diagnostics) {
|
|
|
4229
4807
|
}, diagnostics);
|
|
4230
4808
|
}
|
|
4231
4809
|
function decompileTwine1(storeArea, story, diagnostics) {
|
|
4232
|
-
|
|
4233
|
-
|
|
4234
|
-
|
|
4235
|
-
|
|
4236
|
-
|
|
4237
|
-
|
|
4238
|
-
|
|
4239
|
-
|
|
4240
|
-
|
|
4241
|
-
|
|
4242
|
-
|
|
4243
|
-
|
|
4244
|
-
|
|
4245
|
-
|
|
4246
|
-
|
|
4247
|
-
|
|
4810
|
+
const passages = (storeArea.children ?? []).filter(isTiddler).map(tiddlerToPassage);
|
|
4811
|
+
const obfuscated = isRot13Obfuscated(passages);
|
|
4812
|
+
for (const p of passages) storyAdd(story, obfuscated && p.name !== "StorySettings" ? {
|
|
4813
|
+
...p,
|
|
4814
|
+
text: rot13(p.text)
|
|
4815
|
+
} : p, diagnostics);
|
|
4816
|
+
}
|
|
4817
|
+
function isTiddler(node) {
|
|
4818
|
+
return node.type === "tag" && node.name === "div" && node.attribs !== void 0 && "tiddler" in node.attribs;
|
|
4819
|
+
}
|
|
4820
|
+
function tiddlerToPassage(node) {
|
|
4821
|
+
const nodeAttrs = node.attribs ?? {};
|
|
4822
|
+
const passage = {
|
|
4823
|
+
name: nodeAttrs["tiddler"] ?? "",
|
|
4824
|
+
tags: nodeAttrs["tags"] ? nodeAttrs["tags"].split(/\s+/).filter((s) => s.length > 0) : [],
|
|
4825
|
+
text: tiddlerUnescape(getTextContent(node)).trim()
|
|
4826
|
+
};
|
|
4827
|
+
const position = nodeAttrs["twine-position"];
|
|
4828
|
+
if (position) passage.metadata = { position };
|
|
4829
|
+
return passage;
|
|
4830
|
+
}
|
|
4831
|
+
/** Whether the StorySettings tiddlers turn on ROT13 obfuscation, read the way the writer reads them. */
|
|
4832
|
+
function isRot13Obfuscated(passages) {
|
|
4833
|
+
const settings = createStory();
|
|
4834
|
+
for (const p of passages) if (p.name === "StorySettings") unmarshalStorySettings(settings, p.text, []);
|
|
4835
|
+
return settings.twine1.settings.get("obfuscate") === "rot13";
|
|
4248
4836
|
}
|
|
4249
4837
|
function findElement(node, tagName) {
|
|
4250
4838
|
if (node.type === "tag" && node.name === tagName) return node;
|
|
@@ -4330,244 +4918,21 @@ function loadSources(story, filenames, opts, diagnostics, processedFiles) {
|
|
|
4330
4918
|
case "oga":
|
|
4331
4919
|
case "ogg":
|
|
4332
4920
|
case "opus":
|
|
4333
|
-
case "wav":
|
|
4334
|
-
case "wave":
|
|
4335
|
-
case "weba":
|
|
4336
|
-
loadMedia(story, "Twine.audio", filename, diagnostics);
|
|
4337
|
-
break;
|
|
4338
|
-
case "mp4":
|
|
4339
|
-
case "ogv":
|
|
4340
|
-
case "webm":
|
|
4341
|
-
loadMedia(story, "Twine.video", filename, diagnostics);
|
|
4342
|
-
break;
|
|
4343
|
-
case "vtt":
|
|
4344
|
-
loadMedia(story, "Twine.vtt", filename, diagnostics);
|
|
4345
|
-
break;
|
|
4346
|
-
default: continue;
|
|
4347
|
-
}
|
|
4348
|
-
} catch (e) {
|
|
4349
|
-
diagnostics.push({
|
|
4350
|
-
level: "error",
|
|
4351
|
-
message: `load ${filename}: ${e instanceof Error ? e.message : String(e)}`,
|
|
4352
|
-
file: filename
|
|
4353
|
-
});
|
|
4354
|
-
continue;
|
|
4355
|
-
}
|
|
4356
|
-
processedFiles.add(filename);
|
|
4357
|
-
}
|
|
4358
|
-
if (story.name !== "" && !story.passages.some((p) => p.name === "StoryTitle")) storyPrepend(story, {
|
|
4359
|
-
name: "StoryTitle",
|
|
4360
|
-
tags: [],
|
|
4361
|
-
text: story.name
|
|
4362
|
-
}, diagnostics);
|
|
4363
|
-
}
|
|
4364
|
-
/**
|
|
4365
|
-
* Load inline sources (string content or InlineSource objects).
|
|
4366
|
-
*/
|
|
4367
|
-
function loadInlineSources(story, sources, opts, diagnostics) {
|
|
4368
|
-
for (const source of sources) {
|
|
4369
|
-
if (typeof source === "string") continue;
|
|
4370
|
-
const content = typeof source.content === "string" ? source.content : source.content.toString("utf-8");
|
|
4371
|
-
const ext = normalizedFileExt(source.filename);
|
|
4372
|
-
switch (ext) {
|
|
4373
|
-
case "":
|
|
4374
|
-
case "tw":
|
|
4375
|
-
case "twee":
|
|
4376
|
-
case "tw2":
|
|
4377
|
-
case "twee2": {
|
|
4378
|
-
const twee2 = ext === "tw2" || ext === "twee2" || opts.twee2Compat;
|
|
4379
|
-
const result = parseTwee(content, {
|
|
4380
|
-
filename: source.filename,
|
|
4381
|
-
trim: opts.trim ?? true,
|
|
4382
|
-
twee2Compat: twee2
|
|
4383
|
-
});
|
|
4384
|
-
diagnostics.push(...result.diagnostics);
|
|
4385
|
-
for (const p of result.passages) storyAdd(story, p, diagnostics);
|
|
4386
|
-
break;
|
|
4387
|
-
}
|
|
4388
|
-
case "css":
|
|
4389
|
-
storyAdd(story, {
|
|
4390
|
-
name: basename(source.filename),
|
|
4391
|
-
tags: ["stylesheet"],
|
|
4392
|
-
text: content
|
|
4393
|
-
}, diagnostics);
|
|
4394
|
-
break;
|
|
4395
|
-
case "js":
|
|
4396
|
-
storyAdd(story, {
|
|
4397
|
-
name: basename(source.filename),
|
|
4398
|
-
tags: ["script"],
|
|
4399
|
-
text: content
|
|
4400
|
-
}, diagnostics);
|
|
4401
|
-
break;
|
|
4402
|
-
default: diagnostics.push({
|
|
4403
|
-
level: "warning",
|
|
4404
|
-
message: `load ${source.filename}: in-memory sources of type .${ext} are not supported; skipped.`
|
|
4405
|
-
});
|
|
4406
|
-
}
|
|
4407
|
-
}
|
|
4408
|
-
}
|
|
4409
|
-
function parseTweeFile(filename, opts) {
|
|
4410
|
-
const result = parseTwee(readUTF8(filename), {
|
|
4411
|
-
filename,
|
|
4412
|
-
trim: opts.trim ?? true,
|
|
4413
|
-
twee2Compat: opts.twee2Compat ?? false
|
|
4414
|
-
});
|
|
4415
|
-
return {
|
|
4416
|
-
passages: result.passages,
|
|
4417
|
-
diagnostics: [...result.diagnostics]
|
|
4418
|
-
};
|
|
4419
|
-
}
|
|
4420
|
-
function parseTaggedFile(tag, filename) {
|
|
4421
|
-
const source = readUTF8(filename);
|
|
4422
|
-
return {
|
|
4423
|
-
passages: [{
|
|
4424
|
-
name: basename(filename),
|
|
4425
|
-
tags: [tag],
|
|
4426
|
-
text: source
|
|
4427
|
-
}],
|
|
4428
|
-
diagnostics: []
|
|
4429
|
-
};
|
|
4430
|
-
}
|
|
4431
|
-
function parseMediaFile(tag, filename) {
|
|
4432
|
-
const source = readBase64(filename);
|
|
4433
|
-
return {
|
|
4434
|
-
passages: [{
|
|
4435
|
-
name: baseNameWithoutExt(filename),
|
|
4436
|
-
tags: [tag],
|
|
4437
|
-
text: `data:${mediaTypeFromFilename(filename)};base64,${source}`
|
|
4438
|
-
}],
|
|
4439
|
-
diagnostics: []
|
|
4440
|
-
};
|
|
4441
|
-
}
|
|
4442
|
-
function parseFontFile(filename) {
|
|
4443
|
-
const source = readBase64(filename);
|
|
4444
|
-
const name = basename(filename);
|
|
4445
|
-
const family = baseNameWithoutExt(filename);
|
|
4446
|
-
const ext = normalizedFileExt(filename);
|
|
4447
|
-
return {
|
|
4448
|
-
passages: [{
|
|
4449
|
-
name,
|
|
4450
|
-
tags: ["stylesheet"],
|
|
4451
|
-
text: `@font-face {\n\tfont-family: "${family}";\n\tsrc: url("data:${mediaTypeFromExt(ext)};base64,${source}") format("${fontFormatHint(ext)}");\n}`
|
|
4452
|
-
}],
|
|
4453
|
-
diagnostics: []
|
|
4454
|
-
};
|
|
4455
|
-
}
|
|
4456
|
-
function parseHTMLFile(filename) {
|
|
4457
|
-
const result = decompileHTML(readUTF8(filename));
|
|
4458
|
-
return {
|
|
4459
|
-
passages: result.story.passages,
|
|
4460
|
-
diagnostics: [...result.diagnostics]
|
|
4461
|
-
};
|
|
4462
|
-
}
|
|
4463
|
-
function parseFile(filename, opts) {
|
|
4464
|
-
switch (normalizedFileExt(filename)) {
|
|
4465
|
-
case "tw":
|
|
4466
|
-
case "twee": return parseTweeFile(filename, opts);
|
|
4467
|
-
case "tw2":
|
|
4468
|
-
case "twee2": return parseTweeFile(filename, {
|
|
4469
|
-
...opts,
|
|
4470
|
-
twee2Compat: true
|
|
4471
|
-
});
|
|
4472
|
-
case "htm":
|
|
4473
|
-
case "html": return parseHTMLFile(filename);
|
|
4474
|
-
case "css": return parseTaggedFile("stylesheet", filename);
|
|
4475
|
-
case "js": return parseTaggedFile("script", filename);
|
|
4476
|
-
case "otf":
|
|
4477
|
-
case "ttf":
|
|
4478
|
-
case "woff":
|
|
4479
|
-
case "woff2": return parseFontFile(filename);
|
|
4480
|
-
case "gif":
|
|
4481
|
-
case "jpeg":
|
|
4482
|
-
case "jpg":
|
|
4483
|
-
case "png":
|
|
4484
|
-
case "svg":
|
|
4485
|
-
case "tif":
|
|
4486
|
-
case "tiff":
|
|
4487
|
-
case "webp": return parseMediaFile("Twine.image", filename);
|
|
4488
|
-
case "aac":
|
|
4489
|
-
case "flac":
|
|
4490
|
-
case "m4a":
|
|
4491
|
-
case "mp3":
|
|
4492
|
-
case "oga":
|
|
4493
|
-
case "ogg":
|
|
4494
|
-
case "opus":
|
|
4495
|
-
case "wav":
|
|
4496
|
-
case "wave":
|
|
4497
|
-
case "weba": return parseMediaFile("Twine.audio", filename);
|
|
4498
|
-
case "mp4":
|
|
4499
|
-
case "ogv":
|
|
4500
|
-
case "webm": return parseMediaFile("Twine.video", filename);
|
|
4501
|
-
case "vtt": return parseMediaFile("Twine.vtt", filename);
|
|
4502
|
-
default: return;
|
|
4503
|
-
}
|
|
4504
|
-
}
|
|
4505
|
-
function loadHTML(story, filename, diagnostics) {
|
|
4506
|
-
const result = parseHTMLFile(filename);
|
|
4507
|
-
diagnostics.push(...result.diagnostics);
|
|
4508
|
-
for (const p of result.passages) storyAdd(story, p, diagnostics);
|
|
4509
|
-
}
|
|
4510
|
-
function loadTwee(story, filename, opts, diagnostics) {
|
|
4511
|
-
const result = parseTweeFile(filename, opts);
|
|
4512
|
-
diagnostics.push(...result.diagnostics);
|
|
4513
|
-
for (const p of result.passages) storyAdd(story, p, diagnostics);
|
|
4514
|
-
}
|
|
4515
|
-
function loadTagged(story, tag, filename, diagnostics) {
|
|
4516
|
-
const result = parseTaggedFile(tag, filename);
|
|
4517
|
-
for (const p of result.passages) storyAdd(story, p, diagnostics);
|
|
4518
|
-
}
|
|
4519
|
-
function loadMedia(story, tag, filename, diagnostics) {
|
|
4520
|
-
const result = parseMediaFile(tag, filename);
|
|
4521
|
-
for (const p of result.passages) storyAdd(story, p, diagnostics);
|
|
4522
|
-
}
|
|
4523
|
-
function loadFont(story, filename, diagnostics) {
|
|
4524
|
-
const result = parseFontFile(filename);
|
|
4525
|
-
for (const p of result.passages) storyAdd(story, p, diagnostics);
|
|
4526
|
-
}
|
|
4527
|
-
/**
|
|
4528
|
-
* Load sources with mtime-based caching for incremental rebuilds.
|
|
4529
|
-
* Always creates a fresh Story; cached passages are replayed via storyAdd().
|
|
4530
|
-
*/
|
|
4531
|
-
function loadSourcesCached(story, filenames, opts, diagnostics, processedFiles, cache, changedFiles) {
|
|
4532
|
-
const currentFiles = /* @__PURE__ */ new Set();
|
|
4533
|
-
for (const filename of filenames) {
|
|
4534
|
-
if (processedFiles.has(filename)) {
|
|
4535
|
-
diagnostics.push({
|
|
4536
|
-
level: "warning",
|
|
4537
|
-
message: `load ${filename}: Skipping duplicate.`
|
|
4538
|
-
});
|
|
4539
|
-
continue;
|
|
4540
|
-
}
|
|
4541
|
-
currentFiles.add(filename);
|
|
4542
|
-
const cached = cache.get(filename);
|
|
4543
|
-
if (changedFiles && cached && !changedFiles.has(filename)) {
|
|
4544
|
-
diagnostics.push(...cached.diagnostics);
|
|
4545
|
-
for (const p of cached.passages) storyAdd(story, p, diagnostics);
|
|
4546
|
-
processedFiles.add(filename);
|
|
4547
|
-
continue;
|
|
4548
|
-
}
|
|
4549
|
-
let mtimeMs;
|
|
4550
|
-
try {
|
|
4551
|
-
mtimeMs = statSync(filename).mtimeMs;
|
|
4552
|
-
} catch {
|
|
4553
|
-
continue;
|
|
4554
|
-
}
|
|
4555
|
-
if (cached && cached.mtimeMs === mtimeMs) {
|
|
4556
|
-
diagnostics.push(...cached.diagnostics);
|
|
4557
|
-
for (const p of cached.passages) storyAdd(story, p, diagnostics);
|
|
4558
|
-
processedFiles.add(filename);
|
|
4559
|
-
continue;
|
|
4560
|
-
}
|
|
4561
|
-
try {
|
|
4562
|
-
const result = parseFile(filename, opts);
|
|
4563
|
-
if (!result) continue;
|
|
4564
|
-
cache.set(filename, {
|
|
4565
|
-
mtimeMs,
|
|
4566
|
-
passages: result.passages,
|
|
4567
|
-
diagnostics: result.diagnostics
|
|
4568
|
-
});
|
|
4569
|
-
diagnostics.push(...result.diagnostics);
|
|
4570
|
-
for (const p of result.passages) storyAdd(story, p, diagnostics);
|
|
4921
|
+
case "wav":
|
|
4922
|
+
case "wave":
|
|
4923
|
+
case "weba":
|
|
4924
|
+
loadMedia(story, "Twine.audio", filename, diagnostics);
|
|
4925
|
+
break;
|
|
4926
|
+
case "mp4":
|
|
4927
|
+
case "ogv":
|
|
4928
|
+
case "webm":
|
|
4929
|
+
loadMedia(story, "Twine.video", filename, diagnostics);
|
|
4930
|
+
break;
|
|
4931
|
+
case "vtt":
|
|
4932
|
+
loadMedia(story, "Twine.vtt", filename, diagnostics);
|
|
4933
|
+
break;
|
|
4934
|
+
default: continue;
|
|
4935
|
+
}
|
|
4571
4936
|
} catch (e) {
|
|
4572
4937
|
diagnostics.push({
|
|
4573
4938
|
level: "error",
|
|
@@ -4578,572 +4943,577 @@ function loadSourcesCached(story, filenames, opts, diagnostics, processedFiles,
|
|
|
4578
4943
|
}
|
|
4579
4944
|
processedFiles.add(filename);
|
|
4580
4945
|
}
|
|
4581
|
-
for (const key of cache.keys()) if (!currentFiles.has(key)) cache.delete(key);
|
|
4582
4946
|
if (story.name !== "" && !story.passages.some((p) => p.name === "StoryTitle")) storyPrepend(story, {
|
|
4583
4947
|
name: "StoryTitle",
|
|
4584
4948
|
tags: [],
|
|
4585
4949
|
text: story.name
|
|
4586
4950
|
}, diagnostics);
|
|
4587
4951
|
}
|
|
4588
|
-
//#endregion
|
|
4589
|
-
//#region src/version.ts
|
|
4590
|
-
/**
|
|
4591
|
-
* The twee-ts version, read at runtime from the package's own package.json.
|
|
4592
|
-
*
|
|
4593
|
-
* The release workflow (semantic-release) writes the new version into the
|
|
4594
|
-
* published package.json only; git keeps the old one. Reading it at runtime
|
|
4595
|
-
* is the only way the CLI and `creator-version` report the published version.
|
|
4596
|
-
*/
|
|
4597
|
-
const PACKAGE_NAME = "@rohal12/twee-ts";
|
|
4598
|
-
/** Walks up from `startDir` to the nearest package.json named @rohal12/twee-ts and returns its version. */
|
|
4599
|
-
function findPackageVersion(startDir) {
|
|
4600
|
-
let dir = startDir;
|
|
4601
|
-
for (;;) {
|
|
4602
|
-
try {
|
|
4603
|
-
const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
|
|
4604
|
-
if (pkg.name === PACKAGE_NAME && typeof pkg.version === "string") return pkg.version;
|
|
4605
|
-
} catch {}
|
|
4606
|
-
const parent = dirname(dir);
|
|
4607
|
-
if (parent === dir) return void 0;
|
|
4608
|
-
dir = parent;
|
|
4609
|
-
}
|
|
4610
|
-
}
|
|
4611
|
-
/** This module's directory: `__dirname` in the CJS build, `import.meta.url` in ESM and in source. */
|
|
4612
|
-
function moduleDir() {
|
|
4613
|
-
return typeof __dirname === "string" ? __dirname : dirname(fileURLToPath(import.meta.url));
|
|
4614
|
-
}
|
|
4615
|
-
const VERSION = findPackageVersion(moduleDir()) ?? "0.0.0";
|
|
4616
|
-
//#endregion
|
|
4617
|
-
//#region src/output-twine2.ts
|
|
4618
|
-
const CREATOR_NAME$2 = "Twee-ts";
|
|
4619
|
-
function toTwine2Archive(story, startName, options) {
|
|
4620
|
-
return getTwine2DataChunk(story, startName, options) + "\n";
|
|
4621
|
-
}
|
|
4622
|
-
function toTwine2HTML(story, format, startName, options) {
|
|
4623
|
-
let template = readFormatSource(format);
|
|
4624
|
-
if (template.includes("{{STORY_NAME}}")) {
|
|
4625
|
-
const name = htmlEscape(story.name);
|
|
4626
|
-
template = template.replaceAll("{{STORY_NAME}}", () => name);
|
|
4627
|
-
}
|
|
4628
|
-
if (template.includes("{{STORY_DATA}}")) {
|
|
4629
|
-
const data = getTwine2DataChunk(story, startName, options);
|
|
4630
|
-
template = template.replace("{{STORY_DATA}}", () => data);
|
|
4631
|
-
}
|
|
4632
|
-
return template;
|
|
4633
|
-
}
|
|
4634
|
-
function getTwine2DataChunk(story, startName, options) {
|
|
4635
|
-
const parts = [];
|
|
4636
|
-
let startID = "";
|
|
4637
|
-
let pid = 0;
|
|
4638
|
-
const scripts = [];
|
|
4639
|
-
const stylesheets = [];
|
|
4640
|
-
for (const p of story.passages) {
|
|
4641
|
-
if (hasTag(p, "Twine.private")) continue;
|
|
4642
|
-
if (hasTag(p, "script")) scripts.push(p);
|
|
4643
|
-
else if (hasTag(p, "stylesheet")) stylesheets.push(p);
|
|
4644
|
-
}
|
|
4645
|
-
let styleContent = "";
|
|
4646
|
-
if (stylesheets.length === 1) styleContent = stylesheets[0]?.text ?? "";
|
|
4647
|
-
else if (stylesheets.length > 1) {
|
|
4648
|
-
let pidS = 1;
|
|
4649
|
-
for (const p of stylesheets) {
|
|
4650
|
-
if (pidS > 1 && !styleContent.endsWith("\n")) styleContent += "\n";
|
|
4651
|
-
styleContent += `/* twine-user-stylesheet #${pidS}: "${commentSanitize(p.name)}" */\n`;
|
|
4652
|
-
styleContent += p.text;
|
|
4653
|
-
pidS++;
|
|
4654
|
-
}
|
|
4655
|
-
}
|
|
4656
|
-
parts.push(`<style role="stylesheet" id="twine-user-stylesheet" type="text/twine-css">${styleContent}</style>`);
|
|
4657
|
-
let scriptContent = "";
|
|
4658
|
-
if (scripts.length === 1) scriptContent = scripts[0]?.text ?? "";
|
|
4659
|
-
else if (scripts.length > 1) {
|
|
4660
|
-
let pidS = 1;
|
|
4661
|
-
for (const p of scripts) {
|
|
4662
|
-
if (pidS > 1 && !scriptContent.endsWith("\n")) scriptContent += "\n";
|
|
4663
|
-
scriptContent += `/* twine-user-script #${pidS}: "${commentSanitize(p.name)}" */\n`;
|
|
4664
|
-
scriptContent += p.text;
|
|
4665
|
-
pidS++;
|
|
4666
|
-
}
|
|
4667
|
-
}
|
|
4668
|
-
parts.push(`<script role="script" id="twine-user-script" type="text/twine-javascript">${scriptContent}<\/script>`);
|
|
4669
|
-
const validTagColors = /* @__PURE__ */ new Set([
|
|
4670
|
-
"gray",
|
|
4671
|
-
"red",
|
|
4672
|
-
"orange",
|
|
4673
|
-
"yellow",
|
|
4674
|
-
"green",
|
|
4675
|
-
"blue",
|
|
4676
|
-
"purple"
|
|
4677
|
-
]);
|
|
4678
|
-
const hexColorPattern = /^#[0-9a-fA-F]{3,8}$/;
|
|
4679
|
-
for (const [tag, color] of story.twine2.tagColors) if (validTagColors.has(color) || hexColorPattern.test(color)) parts.push(`<tw-tag name="${attrEscape(tag)}" color="${attrEscape(color)}"></tw-tag>`);
|
|
4680
|
-
pid = 1;
|
|
4681
|
-
for (const p of story.passages) {
|
|
4682
|
-
if (p.name === "StoryTitle" || p.name === "StoryData" || hasAnyTag(p, "script", "stylesheet", "Twine.private")) continue;
|
|
4683
|
-
if (p.name === "StorySettings" && story.twine1.settings.size === 0) continue;
|
|
4684
|
-
parts.push(passageToPassagedata(p, pid, options));
|
|
4685
|
-
if (startName === p.name) startID = String(pid);
|
|
4686
|
-
pid++;
|
|
4687
|
-
}
|
|
4688
|
-
const opts = [];
|
|
4689
|
-
for (const [opt, val] of story.twine2.options) if (val) opts.push(opt);
|
|
4690
|
-
const optionsStr = opts.join(" ");
|
|
4691
|
-
const zoom = String(story.twine2.zoom);
|
|
4692
|
-
return `<!-- UUID://${htmlCommentSanitize(story.ifid)}// --><tw-storydata name="${attrEscape(story.name)}" startnode="${attrEscape(startID)}" creator="${attrEscape(CREATOR_NAME$2)}" creator-version="${attrEscape(VERSION)}" ifid="${attrEscape(story.ifid)}" zoom="${attrEscape(zoom)}" format="${attrEscape(story.twine2.format)}" format-version="${attrEscape(story.twine2.formatVersion)}" options="${attrEscape(optionsStr)}" tags="${attrEscape(story.twine2.tags)}" hidden>` + parts.join("") + "</tw-storydata>";
|
|
4693
|
-
}
|
|
4694
|
-
//#endregion
|
|
4695
|
-
//#region src/output-twine1.ts
|
|
4696
|
-
/**
|
|
4697
|
-
* Twine 1 HTML and archive output.
|
|
4698
|
-
* Ported from storyout.go.
|
|
4699
|
-
*/
|
|
4700
|
-
const CREATOR_NAME$1 = "twee-ts";
|
|
4701
|
-
function toTwine1Archive(story, _startName) {
|
|
4702
|
-
const { data, count } = getTwine1PassageChunk(story);
|
|
4703
|
-
return `<div id="storeArea" data-size="${count}">${data}</div>\n`;
|
|
4704
|
-
}
|
|
4705
|
-
function toTwine1HTML(story, format, startName) {
|
|
4706
|
-
const formatDir = dirname(format.filename);
|
|
4707
|
-
const parentDir = dirname(formatDir);
|
|
4708
|
-
let template = readFormatSource(format);
|
|
4709
|
-
const { data, count } = getTwine1PassageChunk(story);
|
|
4710
|
-
template = tryReplaceComponent(template, "\"USER_LIB\"", join(formatDir, "userlib.js"), false);
|
|
4711
|
-
template = tryReplaceComponent(template, "\"ENGINE\"", join(parentDir, "engine.js"), true);
|
|
4712
|
-
template = tryReplaceComponent(template, "\"SUGARCANE\"", join(formatDir, "code.js"), true);
|
|
4713
|
-
template = tryReplaceComponent(template, "\"JONAH\"", join(formatDir, "code.js"), true);
|
|
4714
|
-
if (story.twine1.settings.get("jquery") === "on") template = tryReplaceComponent(template, "\"JQUERY\"", join(parentDir, "jquery.js"), true);
|
|
4715
|
-
if (story.twine1.settings.get("modernizr") === "on") template = tryReplaceComponent(template, "\"MODERNIZR\"", join(parentDir, "modernizr.js"), true);
|
|
4716
|
-
const displayStart = startName === "Start" ? "" : startName;
|
|
4717
|
-
template = template.replace("\"VERSION\"", `Compiled with ${CREATOR_NAME$1}, ${VERSION}`);
|
|
4718
|
-
template = template.replace("\"TIME\"", `Built on ${(/* @__PURE__ */ new Date()).toUTCString()}`);
|
|
4719
|
-
const startAtValue = `"${jsStringEscape(displayStart)}"`;
|
|
4720
|
-
template = template.replace("\"START_AT\"", () => startAtValue);
|
|
4721
|
-
template = template.replace("\"STORY_SIZE\"", `"${count}"`);
|
|
4722
|
-
if (template.includes("\"STORY\"")) template = template.replace("\"STORY\"", () => data);
|
|
4723
|
-
else {
|
|
4724
|
-
let footer;
|
|
4725
|
-
try {
|
|
4726
|
-
footer = readFileSync(join(formatDir, "footer.html"), "utf-8");
|
|
4727
|
-
} catch {
|
|
4728
|
-
footer = "</div>\n</body>\n</html>\n";
|
|
4729
|
-
}
|
|
4730
|
-
template += data + footer;
|
|
4731
|
-
}
|
|
4732
|
-
if (story.ifid) {
|
|
4733
|
-
const safeIfid = htmlCommentSanitize(story.ifid);
|
|
4734
|
-
if (template.includes("<div id=\"store-area\"")) template = template.replace("<div id=\"store-area\"", `<!-- UUID://${safeIfid}// --><div id="store-area"`);
|
|
4735
|
-
else template = template.replace("<div id=\"storeArea\"", `<!-- UUID://${safeIfid}// --><div id="storeArea"`);
|
|
4736
|
-
}
|
|
4737
|
-
return template;
|
|
4738
|
-
}
|
|
4739
|
-
function getTwine1PassageChunk(story) {
|
|
4740
|
-
const obfuscateRot13 = story.twine1.settings.get("obfuscate") === "rot13";
|
|
4741
|
-
let data = "";
|
|
4742
|
-
let count = 0;
|
|
4743
|
-
for (const p of story.passages) {
|
|
4744
|
-
if (hasTag(p, "Twine.private")) continue;
|
|
4745
|
-
count++;
|
|
4746
|
-
data += passageToTiddler(p, count, obfuscateRot13);
|
|
4747
|
-
}
|
|
4748
|
-
return {
|
|
4749
|
-
data,
|
|
4750
|
-
count
|
|
4751
|
-
};
|
|
4752
|
-
}
|
|
4753
|
-
function tryReplaceComponent(template, placeholder, componentPath, required) {
|
|
4754
|
-
if (!template.includes(placeholder)) return template;
|
|
4755
|
-
try {
|
|
4756
|
-
let content = readFileSync(componentPath, "utf-8");
|
|
4757
|
-
if (content.charCodeAt(0) === 65279) content = content.slice(1);
|
|
4758
|
-
return template.replace(placeholder, () => content);
|
|
4759
|
-
} catch (e) {
|
|
4760
|
-
if (required) throw new Error(`Required format component not found: ${componentPath}: ${e instanceof Error ? e.message : String(e)}`);
|
|
4761
|
-
return template;
|
|
4762
|
-
}
|
|
4763
|
-
}
|
|
4764
|
-
//#endregion
|
|
4765
|
-
//#region src/output-twee.ts
|
|
4766
|
-
function toTwee(story, outMode) {
|
|
4767
|
-
let data = "";
|
|
4768
|
-
for (const p of story.passages) data += passageToTwee(p, outMode);
|
|
4769
|
-
return data;
|
|
4770
|
-
}
|
|
4771
|
-
//#endregion
|
|
4772
|
-
//#region src/modules.ts
|
|
4773
4952
|
/**
|
|
4774
|
-
* Load
|
|
4953
|
+
* Load inline sources (string content or InlineSource objects).
|
|
4775
4954
|
*/
|
|
4776
|
-
function
|
|
4777
|
-
const
|
|
4778
|
-
|
|
4779
|
-
|
|
4780
|
-
|
|
4781
|
-
const ext = normalizedFileExt(filename);
|
|
4782
|
-
let tag = null;
|
|
4955
|
+
function loadInlineSources(story, sources, opts, diagnostics) {
|
|
4956
|
+
for (const source of sources) {
|
|
4957
|
+
if (typeof source === "string") continue;
|
|
4958
|
+
const content = normalizeSourceText(typeof source.content === "string" ? source.content : source.content.toString("utf-8"));
|
|
4959
|
+
const ext = normalizedFileExt(source.filename);
|
|
4783
4960
|
switch (ext) {
|
|
4961
|
+
case "":
|
|
4962
|
+
case "tw":
|
|
4963
|
+
case "twee":
|
|
4964
|
+
case "tw2":
|
|
4965
|
+
case "twee2": {
|
|
4966
|
+
const twee2 = ext === "tw2" || ext === "twee2" || opts.twee2Compat;
|
|
4967
|
+
const result = parseTwee(content, {
|
|
4968
|
+
filename: source.filename,
|
|
4969
|
+
trim: opts.trim ?? true,
|
|
4970
|
+
twee2Compat: twee2
|
|
4971
|
+
});
|
|
4972
|
+
diagnostics.push(...result.diagnostics);
|
|
4973
|
+
for (const p of result.passages) storyAdd(story, p, diagnostics);
|
|
4974
|
+
break;
|
|
4975
|
+
}
|
|
4784
4976
|
case "css":
|
|
4785
|
-
|
|
4977
|
+
storyAdd(story, {
|
|
4978
|
+
name: basename(source.filename),
|
|
4979
|
+
tags: ["stylesheet"],
|
|
4980
|
+
text: content
|
|
4981
|
+
}, diagnostics);
|
|
4786
4982
|
break;
|
|
4787
4983
|
case "js":
|
|
4788
|
-
|
|
4789
|
-
|
|
4790
|
-
|
|
4791
|
-
|
|
4792
|
-
|
|
4793
|
-
case "woff2":
|
|
4794
|
-
tag = loadModuleFont(filename);
|
|
4984
|
+
storyAdd(story, {
|
|
4985
|
+
name: basename(source.filename),
|
|
4986
|
+
tags: ["script"],
|
|
4987
|
+
text: content
|
|
4988
|
+
}, diagnostics);
|
|
4795
4989
|
break;
|
|
4796
|
-
default:
|
|
4990
|
+
default: diagnostics.push({
|
|
4991
|
+
level: "warning",
|
|
4992
|
+
message: `load ${source.filename}: in-memory sources of type .${ext} are not supported; skipped.`
|
|
4993
|
+
});
|
|
4797
4994
|
}
|
|
4798
|
-
if (tag) headTags.push(tag);
|
|
4799
|
-
processed.add(filename);
|
|
4800
4995
|
}
|
|
4801
|
-
return headTags.join("\n");
|
|
4802
4996
|
}
|
|
4803
|
-
function
|
|
4804
|
-
const
|
|
4805
|
-
|
|
4806
|
-
|
|
4997
|
+
function parseTweeFile(filename, opts) {
|
|
4998
|
+
const result = parseTwee(readUTF8(filename), {
|
|
4999
|
+
filename,
|
|
5000
|
+
trim: opts.trim ?? true,
|
|
5001
|
+
twee2Compat: opts.twee2Compat ?? false
|
|
5002
|
+
});
|
|
5003
|
+
return {
|
|
5004
|
+
passages: result.passages,
|
|
5005
|
+
diagnostics: [...result.diagnostics]
|
|
5006
|
+
};
|
|
5007
|
+
}
|
|
5008
|
+
function parseTaggedFile(tag, filename) {
|
|
5009
|
+
const source = readUTF8(filename);
|
|
5010
|
+
return {
|
|
5011
|
+
passages: [{
|
|
5012
|
+
name: basename(filename),
|
|
5013
|
+
tags: [tag],
|
|
5014
|
+
text: source
|
|
5015
|
+
}],
|
|
5016
|
+
diagnostics: []
|
|
5017
|
+
};
|
|
4807
5018
|
}
|
|
4808
|
-
function
|
|
5019
|
+
function parseMediaFile(tag, filename) {
|
|
5020
|
+
const source = readBase64(filename);
|
|
5021
|
+
return {
|
|
5022
|
+
passages: [{
|
|
5023
|
+
name: baseNameWithoutExt(filename),
|
|
5024
|
+
tags: [tag],
|
|
5025
|
+
text: `data:${mediaTypeFromFilename(filename)};base64,${source}`
|
|
5026
|
+
}],
|
|
5027
|
+
diagnostics: []
|
|
5028
|
+
};
|
|
5029
|
+
}
|
|
5030
|
+
function parseFontFile(filename) {
|
|
4809
5031
|
const source = readBase64(filename);
|
|
5032
|
+
const name = basename(filename);
|
|
4810
5033
|
const family = baseNameWithoutExt(filename);
|
|
4811
|
-
const idSlug = `style-module-${slugify(family)}`;
|
|
4812
5034
|
const ext = normalizedFileExt(filename);
|
|
4813
|
-
return
|
|
5035
|
+
return {
|
|
5036
|
+
passages: [{
|
|
5037
|
+
name,
|
|
5038
|
+
tags: ["stylesheet"],
|
|
5039
|
+
text: `@font-face {\n\tfont-family: "${family}";\n\tsrc: url("data:${mediaTypeFromExt(ext)};base64,${source}") format("${fontFormatHint(ext)}");\n}`
|
|
5040
|
+
}],
|
|
5041
|
+
diagnostics: []
|
|
5042
|
+
};
|
|
5043
|
+
}
|
|
5044
|
+
function parseHTMLFile(filename) {
|
|
5045
|
+
const { story, diagnostics } = decompileHTML(readUTF8(filename));
|
|
5046
|
+
return {
|
|
5047
|
+
passages: story.name !== "" && !storyHas(story, "StoryTitle") ? [{
|
|
5048
|
+
name: "StoryTitle",
|
|
5049
|
+
tags: [],
|
|
5050
|
+
text: story.name
|
|
5051
|
+
}, ...story.passages] : story.passages,
|
|
5052
|
+
diagnostics: [...diagnostics]
|
|
5053
|
+
};
|
|
4814
5054
|
}
|
|
4815
5055
|
/**
|
|
4816
|
-
*
|
|
5056
|
+
* Identity of the options that affect how a file parses, stored on its cache entry.
|
|
5057
|
+
* Only Twee files depend on them; every other file type yields the same key for all options.
|
|
4817
5058
|
*/
|
|
4818
|
-
function
|
|
4819
|
-
const
|
|
4820
|
-
|
|
4821
|
-
|
|
4822
|
-
|
|
4823
|
-
|
|
4824
|
-
|
|
4825
|
-
|
|
4826
|
-
|
|
4827
|
-
|
|
4828
|
-
|
|
4829
|
-
|
|
4830
|
-
|
|
5059
|
+
function parseOptionsKey(filename, opts) {
|
|
5060
|
+
const ext = normalizedFileExt(filename);
|
|
5061
|
+
const twee2File = ext === "tw2" || ext === "twee2";
|
|
5062
|
+
if (!twee2File && ext !== "tw" && ext !== "twee") return "";
|
|
5063
|
+
return JSON.stringify({
|
|
5064
|
+
trim: opts.trim ?? true,
|
|
5065
|
+
twee2Compat: twee2File || (opts.twee2Compat ?? false)
|
|
5066
|
+
});
|
|
5067
|
+
}
|
|
5068
|
+
function parseFile(filename, opts) {
|
|
5069
|
+
switch (normalizedFileExt(filename)) {
|
|
5070
|
+
case "tw":
|
|
5071
|
+
case "twee": return parseTweeFile(filename, opts);
|
|
5072
|
+
case "tw2":
|
|
5073
|
+
case "twee2": return parseTweeFile(filename, {
|
|
5074
|
+
...opts,
|
|
5075
|
+
twee2Compat: true
|
|
4831
5076
|
});
|
|
5077
|
+
case "htm":
|
|
5078
|
+
case "html": return parseHTMLFile(filename);
|
|
5079
|
+
case "css": return parseTaggedFile("stylesheet", filename);
|
|
5080
|
+
case "js": return parseTaggedFile("script", filename);
|
|
5081
|
+
case "otf":
|
|
5082
|
+
case "ttf":
|
|
5083
|
+
case "woff":
|
|
5084
|
+
case "woff2": return parseFontFile(filename);
|
|
5085
|
+
case "gif":
|
|
5086
|
+
case "jpeg":
|
|
5087
|
+
case "jpg":
|
|
5088
|
+
case "png":
|
|
5089
|
+
case "svg":
|
|
5090
|
+
case "tif":
|
|
5091
|
+
case "tiff":
|
|
5092
|
+
case "webp": return parseMediaFile("Twine.image", filename);
|
|
5093
|
+
case "aac":
|
|
5094
|
+
case "flac":
|
|
5095
|
+
case "m4a":
|
|
5096
|
+
case "mp3":
|
|
5097
|
+
case "oga":
|
|
5098
|
+
case "ogg":
|
|
5099
|
+
case "opus":
|
|
5100
|
+
case "wav":
|
|
5101
|
+
case "wave":
|
|
5102
|
+
case "weba": return parseMediaFile("Twine.audio", filename);
|
|
5103
|
+
case "mp4":
|
|
5104
|
+
case "ogv":
|
|
5105
|
+
case "webm": return parseMediaFile("Twine.video", filename);
|
|
5106
|
+
case "vtt": return parseMediaFile("Twine.vtt", filename);
|
|
5107
|
+
default: return;
|
|
4832
5108
|
}
|
|
4833
|
-
if (parts.length > 0) {
|
|
4834
|
-
parts.push("</head>");
|
|
4835
|
-
const replacement = parts.join("\n");
|
|
4836
|
-
return html.replace("</head>", () => replacement);
|
|
4837
|
-
}
|
|
4838
|
-
return html;
|
|
4839
|
-
}
|
|
4840
|
-
//#endregion
|
|
4841
|
-
//#region src/remote-formats.ts
|
|
4842
|
-
/**
|
|
4843
|
-
* Remote story format fetching, caching, and checksum verification.
|
|
4844
|
-
* Uses the Story Formats Archive (SFA) as the default source.
|
|
4845
|
-
*/
|
|
4846
|
-
const DEFAULT_SFA_INDICES = ["https://videlais.github.io/story-formats-archive/official/index.json", "https://videlais.github.io/story-formats-archive/unofficial/index.json"];
|
|
4847
|
-
/** Get the cache directory for downloaded story formats. */
|
|
4848
|
-
function getCacheDir() {
|
|
4849
|
-
const base = process.env["XDG_CACHE_HOME"] || join(homedir(), ".cache");
|
|
4850
|
-
return join(base, "twee-ts", "storyformats");
|
|
4851
5109
|
}
|
|
4852
|
-
|
|
4853
|
-
const
|
|
4854
|
-
|
|
4855
|
-
|
|
4856
|
-
indexCache.clear();
|
|
5110
|
+
function loadHTML(story, filename, diagnostics) {
|
|
5111
|
+
const result = parseHTMLFile(filename);
|
|
5112
|
+
diagnostics.push(...result.diagnostics);
|
|
5113
|
+
for (const p of result.passages) storyAdd(story, p, diagnostics);
|
|
4857
5114
|
}
|
|
4858
|
-
|
|
4859
|
-
|
|
4860
|
-
|
|
4861
|
-
const
|
|
4862
|
-
return typeof obj.name === "string" && typeof obj.version === "string" && typeof obj.checksums === "object" && obj.checksums !== null && !Array.isArray(obj.checksums);
|
|
5115
|
+
function loadTwee(story, filename, opts, diagnostics) {
|
|
5116
|
+
const result = parseTweeFile(filename, opts);
|
|
5117
|
+
diagnostics.push(...result.diagnostics);
|
|
5118
|
+
for (const p of result.passages) storyAdd(story, p, diagnostics);
|
|
4863
5119
|
}
|
|
4864
|
-
|
|
4865
|
-
|
|
4866
|
-
|
|
4867
|
-
const obj = json;
|
|
4868
|
-
return {
|
|
4869
|
-
twine1: Array.isArray(obj["twine1"]) ? obj["twine1"].filter(isValidEntry) : [],
|
|
4870
|
-
twine2: Array.isArray(obj["twine2"]) ? obj["twine2"].filter(isValidEntry) : []
|
|
4871
|
-
};
|
|
5120
|
+
function loadTagged(story, tag, filename, diagnostics) {
|
|
5121
|
+
const result = parseTaggedFile(tag, filename);
|
|
5122
|
+
for (const p of result.passages) storyAdd(story, p, diagnostics);
|
|
4872
5123
|
}
|
|
4873
|
-
|
|
4874
|
-
|
|
4875
|
-
const
|
|
4876
|
-
return `${name.toLowerCase().replace(/\s+/g, "-")}-${major}`;
|
|
5124
|
+
function loadMedia(story, tag, filename, diagnostics) {
|
|
5125
|
+
const result = parseMediaFile(tag, filename);
|
|
5126
|
+
for (const p of result.passages) storyAdd(story, p, diagnostics);
|
|
4877
5127
|
}
|
|
4878
|
-
|
|
4879
|
-
|
|
4880
|
-
const
|
|
4881
|
-
if (cached) return cached;
|
|
4882
|
-
const res = await fetch(url);
|
|
4883
|
-
if (!res.ok) throw new Error(`Failed to fetch format index from ${url}: ${res.status} ${res.statusText}`);
|
|
4884
|
-
const data = validateSFAIndex(await res.json());
|
|
4885
|
-
indexCache.set(url, data);
|
|
4886
|
-
return data;
|
|
5128
|
+
function loadFont(story, filename, diagnostics) {
|
|
5129
|
+
const result = parseFontFile(filename);
|
|
5130
|
+
for (const p of result.passages) storyAdd(story, p, diagnostics);
|
|
4887
5131
|
}
|
|
4888
5132
|
/**
|
|
4889
|
-
*
|
|
4890
|
-
*
|
|
5133
|
+
* Load sources with mtime-based caching for incremental rebuilds.
|
|
5134
|
+
* Always creates a fresh Story; cached passages are replayed via storyAdd().
|
|
4891
5135
|
*/
|
|
4892
|
-
function
|
|
4893
|
-
const
|
|
4894
|
-
const
|
|
4895
|
-
|
|
4896
|
-
|
|
4897
|
-
|
|
4898
|
-
|
|
4899
|
-
|
|
4900
|
-
|
|
4901
|
-
|
|
4902
|
-
|
|
4903
|
-
|
|
4904
|
-
|
|
4905
|
-
const
|
|
4906
|
-
if (!
|
|
4907
|
-
|
|
4908
|
-
|
|
4909
|
-
|
|
4910
|
-
|
|
4911
|
-
|
|
4912
|
-
|
|
4913
|
-
|
|
4914
|
-
|
|
4915
|
-
|
|
4916
|
-
|
|
4917
|
-
|
|
4918
|
-
|
|
5136
|
+
function loadSourcesCached(story, filenames, opts, diagnostics, processedFiles, cache, changedFiles) {
|
|
5137
|
+
const currentFiles = /* @__PURE__ */ new Set();
|
|
5138
|
+
for (const filename of filenames) {
|
|
5139
|
+
if (processedFiles.has(filename)) {
|
|
5140
|
+
diagnostics.push({
|
|
5141
|
+
level: "warning",
|
|
5142
|
+
message: `load ${filename}: Skipping duplicate.`
|
|
5143
|
+
});
|
|
5144
|
+
continue;
|
|
5145
|
+
}
|
|
5146
|
+
currentFiles.add(filename);
|
|
5147
|
+
const optionsKey = parseOptionsKey(filename, opts);
|
|
5148
|
+
const entry = cache.get(filename);
|
|
5149
|
+
const cached = entry?.parseOptionsKey === optionsKey ? entry : void 0;
|
|
5150
|
+
if (changedFiles && cached && !changedFiles.has(filename)) {
|
|
5151
|
+
diagnostics.push(...cached.diagnostics);
|
|
5152
|
+
for (const p of cached.passages) storyAdd(story, p, diagnostics);
|
|
5153
|
+
processedFiles.add(filename);
|
|
5154
|
+
continue;
|
|
5155
|
+
}
|
|
5156
|
+
let mtimeMs;
|
|
5157
|
+
try {
|
|
5158
|
+
mtimeMs = statSync(filename).mtimeMs;
|
|
5159
|
+
} catch {
|
|
5160
|
+
continue;
|
|
5161
|
+
}
|
|
5162
|
+
if (cached && cached.mtimeMs === mtimeMs) {
|
|
5163
|
+
diagnostics.push(...cached.diagnostics);
|
|
5164
|
+
for (const p of cached.passages) storyAdd(story, p, diagnostics);
|
|
5165
|
+
processedFiles.add(filename);
|
|
5166
|
+
continue;
|
|
5167
|
+
}
|
|
5168
|
+
try {
|
|
5169
|
+
const result = parseFile(filename, opts);
|
|
5170
|
+
if (!result) continue;
|
|
5171
|
+
cache.set(filename, {
|
|
5172
|
+
mtimeMs,
|
|
5173
|
+
parseOptionsKey: optionsKey,
|
|
5174
|
+
passages: result.passages,
|
|
5175
|
+
diagnostics: result.diagnostics
|
|
5176
|
+
});
|
|
5177
|
+
diagnostics.push(...result.diagnostics);
|
|
5178
|
+
for (const p of result.passages) storyAdd(story, p, diagnostics);
|
|
5179
|
+
} catch (e) {
|
|
5180
|
+
diagnostics.push({
|
|
5181
|
+
level: "error",
|
|
5182
|
+
message: `load ${filename}: ${e instanceof Error ? e.message : String(e)}`,
|
|
5183
|
+
file: filename
|
|
5184
|
+
});
|
|
5185
|
+
continue;
|
|
4919
5186
|
}
|
|
5187
|
+
processedFiles.add(filename);
|
|
5188
|
+
}
|
|
5189
|
+
for (const key of cache.keys()) if (!currentFiles.has(key)) cache.delete(key);
|
|
5190
|
+
if (story.name !== "" && !story.passages.some((p) => p.name === "StoryTitle")) storyPrepend(story, {
|
|
5191
|
+
name: "StoryTitle",
|
|
5192
|
+
tags: [],
|
|
5193
|
+
text: story.name
|
|
5194
|
+
}, diagnostics);
|
|
5195
|
+
}
|
|
5196
|
+
//#endregion
|
|
5197
|
+
//#region src/version.ts
|
|
5198
|
+
/**
|
|
5199
|
+
* The twee-ts version, read at runtime from the package's own package.json.
|
|
5200
|
+
*
|
|
5201
|
+
* The release workflow (semantic-release) writes the new version into the
|
|
5202
|
+
* published package.json only; git keeps the old one. Reading it at runtime
|
|
5203
|
+
* is the only way the CLI and `creator-version` report the published version.
|
|
5204
|
+
*/
|
|
5205
|
+
const PACKAGE_NAME = "@rohal12/twee-ts";
|
|
5206
|
+
/** Walks up from `startDir` to the nearest package.json named @rohal12/twee-ts and returns its version. */
|
|
5207
|
+
function findPackageVersion(startDir) {
|
|
5208
|
+
let dir = startDir;
|
|
5209
|
+
for (;;) {
|
|
5210
|
+
try {
|
|
5211
|
+
const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
|
|
5212
|
+
if (pkg.name === PACKAGE_NAME && typeof pkg.version === "string") return pkg.version;
|
|
5213
|
+
} catch {}
|
|
5214
|
+
const parent = dirname(dir);
|
|
5215
|
+
if (parent === dir) return void 0;
|
|
5216
|
+
dir = parent;
|
|
4920
5217
|
}
|
|
4921
|
-
return bestResult;
|
|
4922
5218
|
}
|
|
4923
|
-
/**
|
|
4924
|
-
|
|
4925
|
-
|
|
4926
|
-
return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("") === expectedHex.toLowerCase();
|
|
5219
|
+
/** This module's directory: `__dirname` in the CJS build, `import.meta.url` in ESM and in source. */
|
|
5220
|
+
function moduleDir() {
|
|
5221
|
+
return typeof __dirname === "string" ? __dirname : dirname(fileURLToPath(import.meta.url));
|
|
4927
5222
|
}
|
|
4928
|
-
|
|
4929
|
-
|
|
4930
|
-
|
|
5223
|
+
const VERSION = findPackageVersion(moduleDir()) ?? "0.0.0";
|
|
5224
|
+
//#endregion
|
|
5225
|
+
//#region src/output-twine2.ts
|
|
5226
|
+
const CREATOR_NAME$2 = "Twee-ts";
|
|
5227
|
+
function toTwine2Archive(story, startName, options) {
|
|
5228
|
+
return getTwine2DataChunk(story, startName, options) + "\n";
|
|
4931
5229
|
}
|
|
4932
|
-
|
|
4933
|
-
|
|
4934
|
-
|
|
4935
|
-
|
|
4936
|
-
|
|
4937
|
-
const checksumKey = Object.keys(entry.checksums ?? {}).find((k) => k.endsWith("format.js"));
|
|
4938
|
-
if (checksumKey) {
|
|
4939
|
-
const expected = entry.checksums[checksumKey];
|
|
4940
|
-
if (!expected) throw new Error(`Missing checksum value for key "${checksumKey}"`);
|
|
4941
|
-
if (!await verifySHA256(new TextEncoder().encode(text), expected)) throw new Error(`Checksum verification failed for ${entry.name} ${entry.version}`);
|
|
5230
|
+
function toTwine2HTML(story, format, startName, options) {
|
|
5231
|
+
let template = readFormatSource(format);
|
|
5232
|
+
if (template.includes("{{STORY_NAME}}")) {
|
|
5233
|
+
const name = htmlEscape(story.name);
|
|
5234
|
+
template = template.replaceAll("{{STORY_NAME}}", () => name);
|
|
4942
5235
|
}
|
|
4943
|
-
|
|
4944
|
-
|
|
4945
|
-
|
|
4946
|
-
|
|
4947
|
-
|
|
4948
|
-
|
|
4949
|
-
|
|
4950
|
-
|
|
4951
|
-
|
|
4952
|
-
|
|
4953
|
-
|
|
4954
|
-
|
|
4955
|
-
name: data.name,
|
|
4956
|
-
version: data.version,
|
|
4957
|
-
proofing: data.proofing ?? false
|
|
4958
|
-
};
|
|
4959
|
-
}
|
|
4960
|
-
/** Download a direct format.js URL, parse its JSON, cache it, and return StoryFormatInfo. */
|
|
4961
|
-
async function fetchDirectFormat(url) {
|
|
4962
|
-
const res = await fetch(url);
|
|
4963
|
-
if (!res.ok) throw new Error(`Failed to download format from ${url}: ${res.status} ${res.statusText}`);
|
|
4964
|
-
const text = await res.text();
|
|
4965
|
-
const data = parseFormatJSON(text, "direct-url");
|
|
4966
|
-
if (!data) throw new Error(`Failed to parse format JSON from ${url}`);
|
|
4967
|
-
const id = makeFormatId(data.name, data.version);
|
|
4968
|
-
const cacheDir = getCacheDir();
|
|
4969
|
-
const formatDir = join(cacheDir, data.name, data.version);
|
|
4970
|
-
mkdirSync(formatDir, { recursive: true });
|
|
4971
|
-
const formatPath = join(formatDir, "format.js");
|
|
4972
|
-
writeFileSync(formatPath, text, "utf-8");
|
|
4973
|
-
return {
|
|
4974
|
-
id,
|
|
4975
|
-
filename: formatPath,
|
|
4976
|
-
isTwine2: true,
|
|
4977
|
-
name: data.name,
|
|
4978
|
-
version: data.version,
|
|
4979
|
-
proofing: data.proofing ?? false
|
|
4980
|
-
};
|
|
5236
|
+
if (template.includes("{{STORY_DATA}}")) {
|
|
5237
|
+
const data = getTwine2DataChunk({
|
|
5238
|
+
...story,
|
|
5239
|
+
twine2: {
|
|
5240
|
+
...story.twine2,
|
|
5241
|
+
format: format.name,
|
|
5242
|
+
formatVersion: format.version
|
|
5243
|
+
}
|
|
5244
|
+
}, startName, options);
|
|
5245
|
+
template = template.replace("{{STORY_DATA}}", () => data);
|
|
5246
|
+
}
|
|
5247
|
+
return template;
|
|
4981
5248
|
}
|
|
5249
|
+
const OMITTING_TAGS = [
|
|
5250
|
+
"Twine.private",
|
|
5251
|
+
"script",
|
|
5252
|
+
"stylesheet"
|
|
5253
|
+
];
|
|
4982
5254
|
/**
|
|
4983
|
-
*
|
|
4984
|
-
*
|
|
4985
|
-
* 2. Try custom index URLs
|
|
4986
|
-
* 3. Try default SFA indices
|
|
5255
|
+
* Why Twine 2 output leaves a passage out of its `<tw-passagedata>` elements,
|
|
5256
|
+
* or `undefined` when the passage is emitted (and so can be the starting passage).
|
|
4987
5257
|
*/
|
|
4988
|
-
|
|
4989
|
-
|
|
4990
|
-
|
|
4991
|
-
|
|
4992
|
-
|
|
4993
|
-
|
|
4994
|
-
|
|
4995
|
-
|
|
5258
|
+
function twine2PassageOmission(story, p) {
|
|
5259
|
+
if (p.name === "StoryTitle" || p.name === "StoryData") return {
|
|
5260
|
+
kind: "special-name",
|
|
5261
|
+
name: p.name
|
|
5262
|
+
};
|
|
5263
|
+
const tag = OMITTING_TAGS.find((t) => hasTag(p, t));
|
|
5264
|
+
if (tag !== void 0) return {
|
|
5265
|
+
kind: "tag",
|
|
5266
|
+
tag
|
|
5267
|
+
};
|
|
5268
|
+
if (p.name === "StorySettings" && story.twine1.settings.size === 0) return { kind: "empty-story-settings" };
|
|
5269
|
+
}
|
|
5270
|
+
function getTwine2DataChunk(story, startName, options) {
|
|
5271
|
+
const parts = [];
|
|
5272
|
+
let startID = "";
|
|
5273
|
+
let pid = 0;
|
|
5274
|
+
const scripts = [];
|
|
5275
|
+
const stylesheets = [];
|
|
5276
|
+
for (const p of story.passages) {
|
|
5277
|
+
if (hasTag(p, "Twine.private")) continue;
|
|
5278
|
+
if (hasTag(p, "script")) scripts.push(p);
|
|
5279
|
+
else if (hasTag(p, "stylesheet")) stylesheets.push(p);
|
|
5280
|
+
}
|
|
5281
|
+
let styleContent = "";
|
|
5282
|
+
if (stylesheets.length === 1) styleContent = stylesheets[0]?.text ?? "";
|
|
5283
|
+
else if (stylesheets.length > 1) {
|
|
5284
|
+
let pidS = 1;
|
|
5285
|
+
for (const p of stylesheets) {
|
|
5286
|
+
if (pidS > 1 && !styleContent.endsWith("\n")) styleContent += "\n";
|
|
5287
|
+
styleContent += `/* twine-user-stylesheet #${pidS}: "${commentSanitize(p.name)}" */\n`;
|
|
5288
|
+
styleContent += p.text;
|
|
5289
|
+
pidS++;
|
|
4996
5290
|
}
|
|
4997
|
-
} catch (e) {
|
|
4998
|
-
lastError = e instanceof Error ? e : new Error(String(e));
|
|
4999
5291
|
}
|
|
5000
|
-
|
|
5001
|
-
|
|
5002
|
-
|
|
5003
|
-
|
|
5004
|
-
|
|
5005
|
-
|
|
5006
|
-
|
|
5007
|
-
|
|
5292
|
+
parts.push(`<style role="stylesheet" id="twine-user-stylesheet" type="text/twine-css">${styleContentEscape(styleContent)}</style>`);
|
|
5293
|
+
let scriptContent = "";
|
|
5294
|
+
if (scripts.length === 1) scriptContent = scripts[0]?.text ?? "";
|
|
5295
|
+
else if (scripts.length > 1) {
|
|
5296
|
+
let pidS = 1;
|
|
5297
|
+
for (const p of scripts) {
|
|
5298
|
+
if (pidS > 1 && !scriptContent.endsWith("\n")) scriptContent += "\n";
|
|
5299
|
+
scriptContent += `/* twine-user-script #${pidS}: "${commentSanitize(p.name)}" */\n`;
|
|
5300
|
+
scriptContent += p.text;
|
|
5301
|
+
pidS++;
|
|
5008
5302
|
}
|
|
5009
|
-
} catch (e) {
|
|
5010
|
-
lastError = e instanceof Error ? e : new Error(String(e));
|
|
5011
5303
|
}
|
|
5012
|
-
|
|
5304
|
+
parts.push(`<script role="script" id="twine-user-script" type="text/twine-javascript">${scriptContentEscape(scriptContent)}<\/script>`);
|
|
5305
|
+
const validTagColors = /* @__PURE__ */ new Set([
|
|
5306
|
+
"gray",
|
|
5307
|
+
"red",
|
|
5308
|
+
"orange",
|
|
5309
|
+
"yellow",
|
|
5310
|
+
"green",
|
|
5311
|
+
"blue",
|
|
5312
|
+
"purple"
|
|
5313
|
+
]);
|
|
5314
|
+
const hexColorPattern = /^#[0-9a-fA-F]{3,8}$/;
|
|
5315
|
+
for (const [tag, color] of story.twine2.tagColors) if (validTagColors.has(color) || hexColorPattern.test(color)) parts.push(`<tw-tag name="${attrEscape(tag)}" color="${attrEscape(color)}"></tw-tag>`);
|
|
5316
|
+
pid = 1;
|
|
5317
|
+
for (const p of story.passages) {
|
|
5318
|
+
if (twine2PassageOmission(story, p) !== void 0) continue;
|
|
5319
|
+
parts.push(passageToPassagedata(p, pid, options));
|
|
5320
|
+
if (startName === p.name) startID = String(pid);
|
|
5321
|
+
pid++;
|
|
5322
|
+
}
|
|
5323
|
+
const opts = [];
|
|
5324
|
+
for (const [opt, val] of story.twine2.options) if (val) opts.push(opt);
|
|
5325
|
+
const optionsStr = opts.join(" ");
|
|
5326
|
+
const zoom = String(story.twine2.zoom);
|
|
5327
|
+
return `<!-- UUID://${htmlCommentSanitize(story.ifid)}// --><tw-storydata name="${attrEscape(story.name)}" startnode="${attrEscape(startID)}" creator="${attrEscape(CREATOR_NAME$2)}" creator-version="${attrEscape(VERSION)}" ifid="${attrEscape(story.ifid)}" zoom="${attrEscape(zoom)}" format="${attrEscape(story.twine2.format)}" format-version="${attrEscape(story.twine2.formatVersion)}" options="${attrEscape(optionsStr)}" tags="${attrEscape(story.twine2.tags)}" hidden>` + parts.join("") + "</tw-storydata>";
|
|
5013
5328
|
}
|
|
5014
|
-
|
|
5015
|
-
|
|
5016
|
-
|
|
5017
|
-
|
|
5018
|
-
|
|
5019
|
-
|
|
5020
|
-
|
|
5021
|
-
|
|
5022
|
-
|
|
5023
|
-
|
|
5024
|
-
|
|
5025
|
-
|
|
5026
|
-
|
|
5027
|
-
|
|
5028
|
-
|
|
5029
|
-
|
|
5030
|
-
|
|
5031
|
-
|
|
5032
|
-
|
|
5329
|
+
//#endregion
|
|
5330
|
+
//#region src/output-twine1.ts
|
|
5331
|
+
/**
|
|
5332
|
+
* Twine 1 HTML and archive output.
|
|
5333
|
+
* Ported from storyout.go.
|
|
5334
|
+
*/
|
|
5335
|
+
const CREATOR_NAME$1 = "twee-ts";
|
|
5336
|
+
function toTwine1Archive(story, _startName) {
|
|
5337
|
+
const { data, count } = getTwine1PassageChunk(story);
|
|
5338
|
+
return `<div id="storeArea" data-size="${count}">${data}</div>\n`;
|
|
5339
|
+
}
|
|
5340
|
+
function toTwine1HTML(story, format, startName) {
|
|
5341
|
+
const formatDir = dirname(format.filename);
|
|
5342
|
+
const parentDir = dirname(formatDir);
|
|
5343
|
+
let template = readFormatSource(format);
|
|
5344
|
+
const { data, count } = getTwine1PassageChunk(story);
|
|
5345
|
+
template = tryReplaceComponent(template, "\"USER_LIB\"", join(formatDir, "userlib.js"), false);
|
|
5346
|
+
template = tryReplaceComponent(template, "\"ENGINE\"", join(parentDir, "engine.js"), true);
|
|
5347
|
+
template = tryReplaceComponent(template, "\"SUGARCANE\"", join(formatDir, "code.js"), true);
|
|
5348
|
+
template = tryReplaceComponent(template, "\"JONAH\"", join(formatDir, "code.js"), true);
|
|
5349
|
+
if (story.twine1.settings.get("jquery") === "on") template = tryReplaceComponent(template, "\"JQUERY\"", join(parentDir, "jquery.js"), true);
|
|
5350
|
+
if (story.twine1.settings.get("modernizr") === "on") template = tryReplaceComponent(template, "\"MODERNIZR\"", join(parentDir, "modernizr.js"), true);
|
|
5351
|
+
const displayStart = startName === "Start" ? "" : startName;
|
|
5352
|
+
template = template.replace("\"VERSION\"", `Compiled with ${CREATOR_NAME$1}, ${VERSION}`);
|
|
5353
|
+
template = template.replace("\"TIME\"", `Built on ${(/* @__PURE__ */ new Date()).toUTCString()}`);
|
|
5354
|
+
const startAtValue = `"${jsStringEscape(displayStart)}"`;
|
|
5355
|
+
template = template.replace("\"START_AT\"", () => startAtValue);
|
|
5356
|
+
template = template.replace("\"STORY_SIZE\"", `"${count}"`);
|
|
5357
|
+
if (template.includes("\"STORY\"")) template = template.replace("\"STORY\"", () => data);
|
|
5358
|
+
else {
|
|
5359
|
+
let footer;
|
|
5360
|
+
try {
|
|
5361
|
+
footer = readFileSync(join(formatDir, "footer.html"), "utf-8");
|
|
5362
|
+
} catch {
|
|
5363
|
+
footer = "</div>\n</body>\n</html>\n";
|
|
5364
|
+
}
|
|
5365
|
+
template += data + footer;
|
|
5366
|
+
}
|
|
5367
|
+
if (story.ifid) {
|
|
5368
|
+
const safeIfid = htmlCommentSanitize(story.ifid);
|
|
5369
|
+
if (template.includes("<div id=\"store-area\"")) template = template.replace("<div id=\"store-area\"", `<!-- UUID://${safeIfid}// --><div id="store-area"`);
|
|
5370
|
+
else template = template.replace("<div id=\"storeArea\"", `<!-- UUID://${safeIfid}// --><div id="storeArea"`);
|
|
5033
5371
|
}
|
|
5372
|
+
return template;
|
|
5034
5373
|
}
|
|
5035
|
-
/**
|
|
5036
|
-
|
|
5037
|
-
|
|
5038
|
-
|
|
5039
|
-
|
|
5040
|
-
|
|
5041
|
-
|
|
5042
|
-
|
|
5374
|
+
/**
|
|
5375
|
+
* Why Twine 1 output leaves a passage out of its tiddlers, or `undefined` when the passage is emitted.
|
|
5376
|
+
*/
|
|
5377
|
+
function twine1PassageOmission(p) {
|
|
5378
|
+
return hasTag(p, "Twine.private") ? {
|
|
5379
|
+
kind: "tag",
|
|
5380
|
+
tag: "Twine.private"
|
|
5381
|
+
} : void 0;
|
|
5382
|
+
}
|
|
5383
|
+
function getTwine1PassageChunk(story) {
|
|
5384
|
+
const obfuscateRot13 = story.twine1.settings.get("obfuscate") === "rot13";
|
|
5385
|
+
let data = "";
|
|
5386
|
+
let count = 0;
|
|
5387
|
+
for (const p of story.passages) {
|
|
5388
|
+
if (twine1PassageOmission(p) !== void 0) continue;
|
|
5389
|
+
count++;
|
|
5390
|
+
data += passageToTiddler(p, count, obfuscateRot13);
|
|
5043
5391
|
}
|
|
5044
|
-
|
|
5392
|
+
return {
|
|
5393
|
+
data,
|
|
5394
|
+
count
|
|
5395
|
+
};
|
|
5396
|
+
}
|
|
5397
|
+
function tryReplaceComponent(template, placeholder, componentPath, required) {
|
|
5398
|
+
if (!template.includes(placeholder)) return template;
|
|
5045
5399
|
try {
|
|
5046
|
-
|
|
5047
|
-
|
|
5048
|
-
return
|
|
5400
|
+
let content = readFileSync(componentPath, "utf-8");
|
|
5401
|
+
if (content.charCodeAt(0) === 65279) content = content.slice(1);
|
|
5402
|
+
return template.replace(placeholder, () => content);
|
|
5403
|
+
} catch (e) {
|
|
5404
|
+
if (required) throw new Error(`Required format component not found: ${componentPath}: ${e instanceof Error ? e.message : String(e)}`);
|
|
5405
|
+
return template;
|
|
5049
5406
|
}
|
|
5050
|
-
|
|
5051
|
-
|
|
5052
|
-
|
|
5053
|
-
|
|
5054
|
-
|
|
5055
|
-
|
|
5056
|
-
|
|
5057
|
-
|
|
5058
|
-
|
|
5059
|
-
|
|
5060
|
-
|
|
5061
|
-
|
|
5062
|
-
|
|
5063
|
-
|
|
5064
|
-
|
|
5065
|
-
|
|
5407
|
+
}
|
|
5408
|
+
//#endregion
|
|
5409
|
+
//#region src/output-twee.ts
|
|
5410
|
+
function toTwee(story, outMode) {
|
|
5411
|
+
let data = "";
|
|
5412
|
+
for (const p of story.passages) data += passageToTwee(p, outMode);
|
|
5413
|
+
return data;
|
|
5414
|
+
}
|
|
5415
|
+
//#endregion
|
|
5416
|
+
//#region src/modules.ts
|
|
5417
|
+
/**
|
|
5418
|
+
* Load modules and return HTML tags to inject before </head>.
|
|
5419
|
+
*/
|
|
5420
|
+
function loadModules(filenames) {
|
|
5421
|
+
const processed = /* @__PURE__ */ new Set();
|
|
5422
|
+
const headTags = [];
|
|
5423
|
+
for (const filename of filenames) {
|
|
5424
|
+
if (processed.has(filename)) continue;
|
|
5425
|
+
const ext = normalizedFileExt(filename);
|
|
5426
|
+
let tag = null;
|
|
5427
|
+
switch (ext) {
|
|
5428
|
+
case "css":
|
|
5429
|
+
tag = loadModuleTagged("style", filename);
|
|
5430
|
+
break;
|
|
5431
|
+
case "js":
|
|
5432
|
+
tag = loadModuleTagged("script", filename);
|
|
5433
|
+
break;
|
|
5434
|
+
case "otf":
|
|
5435
|
+
case "ttf":
|
|
5436
|
+
case "woff":
|
|
5437
|
+
case "woff2":
|
|
5438
|
+
tag = loadModuleFont(filename);
|
|
5439
|
+
break;
|
|
5440
|
+
default: continue;
|
|
5066
5441
|
}
|
|
5442
|
+
if (tag) headTags.push(tag);
|
|
5443
|
+
processed.add(filename);
|
|
5067
5444
|
}
|
|
5068
|
-
return
|
|
5445
|
+
return headTags.join("\n");
|
|
5069
5446
|
}
|
|
5070
|
-
|
|
5071
|
-
|
|
5072
|
-
|
|
5073
|
-
|
|
5074
|
-
|
|
5075
|
-
|
|
5076
|
-
|
|
5077
|
-
|
|
5447
|
+
function loadModuleTagged(tag, filename) {
|
|
5448
|
+
const source = readUTF8(filename).trim();
|
|
5449
|
+
if (source.length === 0) return null;
|
|
5450
|
+
return `<${tag} id="${`${tag}-module-${slugify(baseNameWithoutExt(filename))}`}" type="${tag === "script" ? "text/javascript" : "text/css"}">${tag === "script" ? scriptContentEscape(source) : styleContentEscape(source)}</${tag}>`;
|
|
5451
|
+
}
|
|
5452
|
+
function loadModuleFont(filename) {
|
|
5453
|
+
const source = readBase64(filename);
|
|
5454
|
+
const family = baseNameWithoutExt(filename);
|
|
5455
|
+
const idSlug = `style-module-${slugify(family)}`;
|
|
5456
|
+
const ext = normalizedFileExt(filename);
|
|
5457
|
+
return `<style id="${idSlug}" type="text/css">@font-face {\n\tfont-family: "${family}";\n\tsrc: url("data:${mediaTypeFromExt(ext)};base64,${source}") format("${fontFormatHint(ext)}");\n}</style>`;
|
|
5458
|
+
}
|
|
5459
|
+
/**
|
|
5460
|
+
* Inject modules and head file content before </head>.
|
|
5461
|
+
*/
|
|
5462
|
+
function modifyHead(html, modulePaths, headFile, diagnostics) {
|
|
5463
|
+
const parts = [];
|
|
5464
|
+
if (modulePaths.length > 0) {
|
|
5465
|
+
const modules = loadModules(modulePaths).trim();
|
|
5466
|
+
if (modules.length > 0) parts.push(modules);
|
|
5078
5467
|
}
|
|
5079
|
-
|
|
5080
|
-
|
|
5081
|
-
|
|
5082
|
-
} catch {
|
|
5083
|
-
|
|
5468
|
+
if (headFile) try {
|
|
5469
|
+
const source = readUTF8(headFile).trim();
|
|
5470
|
+
if (source.length > 0) parts.push(source);
|
|
5471
|
+
} catch (e) {
|
|
5472
|
+
diagnostics?.push({
|
|
5473
|
+
level: "warning",
|
|
5474
|
+
message: `Failed to read head file "${headFile}": ${e instanceof Error ? e.message : String(e)}`
|
|
5475
|
+
});
|
|
5084
5476
|
}
|
|
5085
|
-
|
|
5086
|
-
|
|
5087
|
-
|
|
5088
|
-
|
|
5089
|
-
} catch {
|
|
5090
|
-
continue;
|
|
5091
|
-
}
|
|
5092
|
-
let versions;
|
|
5093
|
-
try {
|
|
5094
|
-
versions = readdirSync(nameDir);
|
|
5095
|
-
} catch {
|
|
5096
|
-
continue;
|
|
5097
|
-
}
|
|
5098
|
-
for (const version of versions) {
|
|
5099
|
-
const formatPath = join(nameDir, version, "format.js");
|
|
5100
|
-
try {
|
|
5101
|
-
const stat = statSync(formatPath);
|
|
5102
|
-
entries.push({
|
|
5103
|
-
name,
|
|
5104
|
-
version,
|
|
5105
|
-
sizeBytes: stat.size,
|
|
5106
|
-
modifiedAt: stat.mtime
|
|
5107
|
-
});
|
|
5108
|
-
} catch {}
|
|
5109
|
-
}
|
|
5477
|
+
if (parts.length > 0) {
|
|
5478
|
+
parts.push("</head>");
|
|
5479
|
+
const replacement = parts.join("\n");
|
|
5480
|
+
return html.replace("</head>", () => replacement);
|
|
5110
5481
|
}
|
|
5111
|
-
return
|
|
5482
|
+
return html;
|
|
5112
5483
|
}
|
|
5113
|
-
|
|
5114
|
-
|
|
5115
|
-
|
|
5116
|
-
|
|
5117
|
-
|
|
5118
|
-
|
|
5119
|
-
|
|
5120
|
-
|
|
5121
|
-
force: true
|
|
5122
|
-
});
|
|
5123
|
-
return count;
|
|
5484
|
+
//#endregion
|
|
5485
|
+
//#region src/start-passage.ts
|
|
5486
|
+
function describeOmission(omission) {
|
|
5487
|
+
switch (omission.kind) {
|
|
5488
|
+
case "special-name": return `is the special "${omission.name}" passage`;
|
|
5489
|
+
case "tag": return `is tagged "${omission.tag}"`;
|
|
5490
|
+
case "empty-story-settings": return "is an empty \"StorySettings\" passage";
|
|
5491
|
+
default: throw new Error(`unhandled passage omission: ${JSON.stringify(omission)}`);
|
|
5124
5492
|
}
|
|
5125
|
-
|
|
5126
|
-
|
|
5127
|
-
|
|
5128
|
-
|
|
5129
|
-
|
|
5130
|
-
|
|
5131
|
-
return 0;
|
|
5493
|
+
}
|
|
5494
|
+
function omissionFor(story, passage, target) {
|
|
5495
|
+
switch (target) {
|
|
5496
|
+
case "twine2": return twine2PassageOmission(story, passage);
|
|
5497
|
+
case "twine1": return twine1PassageOmission(passage);
|
|
5498
|
+
default: throw new Error(`unhandled start passage target: ${String(target)}`);
|
|
5132
5499
|
}
|
|
5133
|
-
const count = versions.length;
|
|
5134
|
-
rmSync(nameDir, {
|
|
5135
|
-
recursive: true,
|
|
5136
|
-
force: true
|
|
5137
|
-
});
|
|
5138
|
-
return count;
|
|
5139
5500
|
}
|
|
5140
|
-
/**
|
|
5141
|
-
|
|
5142
|
-
|
|
5143
|
-
|
|
5144
|
-
|
|
5145
|
-
|
|
5146
|
-
|
|
5501
|
+
/**
|
|
5502
|
+
* Check that `startName` names a passage the `target` output emits.
|
|
5503
|
+
* Returns the error diagnostics to report (empty when the start is usable).
|
|
5504
|
+
*/
|
|
5505
|
+
function startPassageDiagnostics(story, startName, target) {
|
|
5506
|
+
const passage = story.passages.find((p) => p.name === startName);
|
|
5507
|
+
if (passage === void 0) return [{
|
|
5508
|
+
level: "error",
|
|
5509
|
+
message: `Starting passage "${startName}" not found.`
|
|
5510
|
+
}];
|
|
5511
|
+
const omission = omissionFor(story, passage, target);
|
|
5512
|
+
if (omission === void 0) return [];
|
|
5513
|
+
return [{
|
|
5514
|
+
level: "error",
|
|
5515
|
+
message: `Starting passage "${startName}" ${describeOmission(omission)}, so it is left out of the story data. Choose a story passage.`
|
|
5516
|
+
}];
|
|
5147
5517
|
}
|
|
5148
5518
|
//#endregion
|
|
5149
5519
|
//#region src/compiler.ts
|
|
@@ -5173,7 +5543,7 @@ async function compile(options) {
|
|
|
5173
5543
|
* Compile and write to a file.
|
|
5174
5544
|
*/
|
|
5175
5545
|
async function compileToFile(options) {
|
|
5176
|
-
const result = await
|
|
5546
|
+
const result = await buildOutput(options, void 0, void 0, options.outFile);
|
|
5177
5547
|
writeFileSync(options.outFile, result.output, "utf-8");
|
|
5178
5548
|
return result;
|
|
5179
5549
|
}
|
|
@@ -5192,16 +5562,21 @@ async function watch(options) {
|
|
|
5192
5562
|
const cache = /* @__PURE__ */ new Map();
|
|
5193
5563
|
const filePaths = options.sources.filter((s) => typeof s === "string");
|
|
5194
5564
|
const modulePaths = options.modules ?? [];
|
|
5195
|
-
const
|
|
5565
|
+
const headPaths = options.headFile ? [options.headFile] : [];
|
|
5566
|
+
const allPaths = [
|
|
5567
|
+
...filePaths,
|
|
5568
|
+
...modulePaths,
|
|
5569
|
+
...headPaths
|
|
5570
|
+
];
|
|
5196
5571
|
const exclude = options.exclude ?? [];
|
|
5197
|
-
const
|
|
5572
|
+
const notExcludable = [...modulePaths, ...headPaths].map((p) => resolve(p));
|
|
5198
5573
|
const ignore = (filename) => {
|
|
5199
5574
|
if (!isExcluded(filename, exclude)) return false;
|
|
5200
5575
|
const abs = resolve(filename);
|
|
5201
|
-
return !
|
|
5576
|
+
return !notExcludable.some((root) => abs === root || abs.startsWith(root + sep));
|
|
5202
5577
|
};
|
|
5203
5578
|
const handle = watchFilesystem(allPaths, options.outFile, (changedFiles) => {
|
|
5204
|
-
buildOutput(options, cache, changedFiles).then((result) => {
|
|
5579
|
+
buildOutput(options, cache, changedFiles, options.outFile).then((result) => {
|
|
5205
5580
|
writeFileSync(options.outFile, result.output, "utf-8");
|
|
5206
5581
|
options.onBuild?.(result);
|
|
5207
5582
|
}).catch((e) => {
|
|
@@ -5211,7 +5586,11 @@ async function watch(options) {
|
|
|
5211
5586
|
controller.signal.addEventListener("abort", () => handle.close());
|
|
5212
5587
|
return controller;
|
|
5213
5588
|
}
|
|
5214
|
-
|
|
5589
|
+
/**
|
|
5590
|
+
* `outFile`: the file the build is written to, which source and module discovery
|
|
5591
|
+
* skip (as Tweego does), so an output inside a source folder is never loaded back.
|
|
5592
|
+
*/
|
|
5593
|
+
async function buildOutput(options, cache, changedFiles, outFile) {
|
|
5215
5594
|
const diagnostics = [];
|
|
5216
5595
|
const outputMode = options.outputMode ?? "html";
|
|
5217
5596
|
const trim = options.trim ?? true;
|
|
@@ -5224,7 +5603,7 @@ async function buildOutput(options, cache, changedFiles) {
|
|
|
5224
5603
|
const inlineSources = [];
|
|
5225
5604
|
for (const source of options.sources) if (typeof source === "string") filePaths.push(source);
|
|
5226
5605
|
else inlineSources.push(source);
|
|
5227
|
-
const { filenames: sourceFilenames, diagnostics: sourcePathDiagnostics } = getFilenames(filePaths,
|
|
5606
|
+
const { filenames: sourceFilenames, diagnostics: sourcePathDiagnostics } = getFilenames(filePaths, outFile, options.exclude);
|
|
5228
5607
|
diagnostics.push(...sourcePathDiagnostics);
|
|
5229
5608
|
const story = createStory();
|
|
5230
5609
|
const processedFiles = /* @__PURE__ */ new Set();
|
|
@@ -5242,33 +5621,12 @@ async function buildOutput(options, cache, changedFiles) {
|
|
|
5242
5621
|
}, diagnostics);
|
|
5243
5622
|
if (options.tagAliases) story.passages = applyTagAliases(story.passages, options.tagAliases);
|
|
5244
5623
|
let format;
|
|
5245
|
-
|
|
5246
|
-
|
|
5247
|
-
|
|
5248
|
-
|
|
5249
|
-
|
|
5250
|
-
|
|
5251
|
-
if (!format && !noRemote) {
|
|
5252
|
-
const remoteName = story.twine2.format || formatId;
|
|
5253
|
-
const remoteVersion = story.twine2.formatVersion || "";
|
|
5254
|
-
try {
|
|
5255
|
-
format = await resolveRemoteFormat(remoteName, remoteVersion, options.formatIndices, options.formatUrls);
|
|
5256
|
-
} catch (e) {
|
|
5257
|
-
diagnostics.push({
|
|
5258
|
-
level: "warning",
|
|
5259
|
-
message: `Remote format fetch failed for "${remoteName}": ${e instanceof Error ? e.message : String(e)}`
|
|
5260
|
-
});
|
|
5261
|
-
}
|
|
5262
|
-
}
|
|
5263
|
-
if (!format) {
|
|
5264
|
-
const reason = noRemote ? " (remote fetching disabled)" : "";
|
|
5265
|
-
diagnostics.push({
|
|
5266
|
-
level: "error",
|
|
5267
|
-
message: `Story format "${formatId}" is not available${reason}. Found: ${[...formats.keys()].join(", ") || "none"}`
|
|
5268
|
-
});
|
|
5269
|
-
}
|
|
5270
|
-
}
|
|
5271
|
-
const startName = options.startPassage || story.twine2.start || DEFAULT_START_NAME;
|
|
5624
|
+
if (outputMode === "html") format = await resolveStoryFormat(formatRequestFor(options.formatId, story.twine2.format, story.twine2.formatVersion, DEFAULT_FORMAT_ID), {
|
|
5625
|
+
...options,
|
|
5626
|
+
noRemote
|
|
5627
|
+
}, diagnostics);
|
|
5628
|
+
if (options.startPassage) story.twine2.start = options.startPassage;
|
|
5629
|
+
const startName = story.twine2.start || DEFAULT_START_NAME;
|
|
5272
5630
|
if (testMode) story.twine2.options.set("debug", true);
|
|
5273
5631
|
ensureIFID(story, diagnostics);
|
|
5274
5632
|
let output;
|
|
@@ -5287,10 +5645,7 @@ async function buildOutput(options, cache, changedFiles) {
|
|
|
5287
5645
|
output = storyToJSON(story);
|
|
5288
5646
|
break;
|
|
5289
5647
|
case "html": {
|
|
5290
|
-
|
|
5291
|
-
level: "error",
|
|
5292
|
-
message: `Starting passage "${startName}" not found.`
|
|
5293
|
-
});
|
|
5648
|
+
diagnostics.push(...startPassageDiagnostics(story, startName, format?.isTwine2 === false ? "twine1" : "twine2"));
|
|
5294
5649
|
if (!format) throw new TweeTsError("No story format available for HTML output.", diagnostics);
|
|
5295
5650
|
if (format.isTwine2) output = toTwine2HTML(story, format, startName, { sourceInfo });
|
|
5296
5651
|
else {
|
|
@@ -5300,7 +5655,7 @@ async function buildOutput(options, cache, changedFiles) {
|
|
|
5300
5655
|
});
|
|
5301
5656
|
output = toTwine1HTML(story, format, startName);
|
|
5302
5657
|
}
|
|
5303
|
-
const modules = getFilenames(options.modules ?? []);
|
|
5658
|
+
const modules = getFilenames(options.modules ?? [], outFile);
|
|
5304
5659
|
diagnostics.push(...modules.diagnostics);
|
|
5305
5660
|
output = modifyHead(output, modules.filenames, options.headFile, diagnostics);
|
|
5306
5661
|
break;
|
|
@@ -5720,19 +6075,227 @@ function endOfRegularExpression(source, pos) {
|
|
|
5720
6075
|
};
|
|
5721
6076
|
}
|
|
5722
6077
|
//#endregion
|
|
6078
|
+
//#region src/link-markup.ts
|
|
6079
|
+
/**
|
|
6080
|
+
* Reads link or image markup that starts at `start` in `text`, or returns `undefined` where
|
|
6081
|
+
* SugarCube rejects it (and so prints the text instead).
|
|
6082
|
+
*
|
|
6083
|
+
* `budget.left`, if given, is how many characters the reading may look at; it is reduced by as
|
|
6084
|
+
* many as were read, and once it runs out, every reading fails. Unclosed markup is read to the end
|
|
6085
|
+
* of its line, so reading every `[[` of a long line that never closes one would otherwise take
|
|
6086
|
+
* quadratic time.
|
|
6087
|
+
*/
|
|
6088
|
+
function readSquareBracketedMarkup(text, start, budget = { left: Infinity }) {
|
|
6089
|
+
const reader = {
|
|
6090
|
+
text,
|
|
6091
|
+
limit: Math.min(text.length, start + Math.max(budget.left, 0))
|
|
6092
|
+
};
|
|
6093
|
+
const markup = readMarkup(reader, start);
|
|
6094
|
+
budget.left -= (markup?.end ?? reader.limit) - start;
|
|
6095
|
+
return markup;
|
|
6096
|
+
}
|
|
6097
|
+
function readMarkup(reader, start) {
|
|
6098
|
+
const { text } = reader;
|
|
6099
|
+
if (text[start] !== "[") return;
|
|
6100
|
+
let pos = start + 1;
|
|
6101
|
+
let type;
|
|
6102
|
+
if (text[pos] === "[") {
|
|
6103
|
+
type = "link";
|
|
6104
|
+
pos += 1;
|
|
6105
|
+
} else {
|
|
6106
|
+
if (text[pos] === "<" || text[pos] === ">") pos += 1;
|
|
6107
|
+
if (!/^[Ii][Mm][Gg]\[/.test(text.slice(pos, pos + 4))) return;
|
|
6108
|
+
type = "image";
|
|
6109
|
+
pos += 4;
|
|
6110
|
+
}
|
|
6111
|
+
const core = readCoreComponents(reader, pos);
|
|
6112
|
+
if (core === void 0) return;
|
|
6113
|
+
if (type === "link") {
|
|
6114
|
+
if (!core.end.last) {
|
|
6115
|
+
const setterEnd = readSetter(reader, core.end.next);
|
|
6116
|
+
if (setterEnd === void 0) return;
|
|
6117
|
+
return {
|
|
6118
|
+
type,
|
|
6119
|
+
link: linkName(core.link),
|
|
6120
|
+
end: setterEnd
|
|
6121
|
+
};
|
|
6122
|
+
}
|
|
6123
|
+
return {
|
|
6124
|
+
type,
|
|
6125
|
+
link: linkName(core.link),
|
|
6126
|
+
end: core.end.next
|
|
6127
|
+
};
|
|
6128
|
+
}
|
|
6129
|
+
if (core.end.last) return {
|
|
6130
|
+
type,
|
|
6131
|
+
link: void 0,
|
|
6132
|
+
end: core.end.next
|
|
6133
|
+
};
|
|
6134
|
+
const linkEnd = readComponent(reader, core.end.next, false);
|
|
6135
|
+
if (linkEnd === void 0) return;
|
|
6136
|
+
const link = linkName(text.slice(core.end.next, linkEnd.textEnd));
|
|
6137
|
+
if (linkEnd.last) return {
|
|
6138
|
+
type,
|
|
6139
|
+
link,
|
|
6140
|
+
end: linkEnd.next
|
|
6141
|
+
};
|
|
6142
|
+
const setterEnd = readSetter(reader, linkEnd.next);
|
|
6143
|
+
return setterEnd === void 0 ? void 0 : {
|
|
6144
|
+
type,
|
|
6145
|
+
link,
|
|
6146
|
+
end: setterEnd
|
|
6147
|
+
};
|
|
6148
|
+
}
|
|
6149
|
+
/** The link component as SugarCube keeps it: trimmed, and without a leading `~`. */
|
|
6150
|
+
function linkName(component) {
|
|
6151
|
+
const trimmed = component.trim();
|
|
6152
|
+
return trimmed.startsWith("~") ? trimmed.slice(1) : trimmed;
|
|
6153
|
+
}
|
|
6154
|
+
/**
|
|
6155
|
+
* Reads the first components: the text and the link of link markup, or the title and the source
|
|
6156
|
+
* of image markup, divided by the first delimiter. `link` is the text of the link (or source)
|
|
6157
|
+
* component, untrimmed.
|
|
6158
|
+
*/
|
|
6159
|
+
function readCoreComponents(reader, from) {
|
|
6160
|
+
const { text } = reader;
|
|
6161
|
+
let delimiter = "none";
|
|
6162
|
+
let componentStart = from;
|
|
6163
|
+
let link;
|
|
6164
|
+
let depth = 2;
|
|
6165
|
+
let pos = from;
|
|
6166
|
+
while (pos < reader.limit) {
|
|
6167
|
+
const ch = text[pos];
|
|
6168
|
+
pos += 1;
|
|
6169
|
+
switch (ch) {
|
|
6170
|
+
case "\n": return;
|
|
6171
|
+
case "\"": {
|
|
6172
|
+
const end = readQuoted(reader, pos, "\"");
|
|
6173
|
+
if (end === void 0) return;
|
|
6174
|
+
pos = end;
|
|
6175
|
+
break;
|
|
6176
|
+
}
|
|
6177
|
+
case "|":
|
|
6178
|
+
if (delimiter === "none") {
|
|
6179
|
+
delimiter = "ltr";
|
|
6180
|
+
componentStart = pos;
|
|
6181
|
+
}
|
|
6182
|
+
break;
|
|
6183
|
+
case "-":
|
|
6184
|
+
if (delimiter === "none" && text[pos] === ">") {
|
|
6185
|
+
delimiter = "ltr";
|
|
6186
|
+
pos += 1;
|
|
6187
|
+
componentStart = pos;
|
|
6188
|
+
}
|
|
6189
|
+
break;
|
|
6190
|
+
case "<":
|
|
6191
|
+
if (delimiter === "none" && text[pos] === "-") {
|
|
6192
|
+
delimiter = "rtl";
|
|
6193
|
+
link = text.slice(componentStart, pos - 1);
|
|
6194
|
+
pos += 1;
|
|
6195
|
+
componentStart = pos;
|
|
6196
|
+
}
|
|
6197
|
+
break;
|
|
6198
|
+
case "[":
|
|
6199
|
+
depth += 1;
|
|
6200
|
+
break;
|
|
6201
|
+
case "]":
|
|
6202
|
+
depth -= 1;
|
|
6203
|
+
if (depth === 1) {
|
|
6204
|
+
const end = componentEnd(text, pos);
|
|
6205
|
+
if (end === void 0) return;
|
|
6206
|
+
return {
|
|
6207
|
+
link: link ?? text.slice(componentStart, end.textEnd),
|
|
6208
|
+
end
|
|
6209
|
+
};
|
|
6210
|
+
}
|
|
6211
|
+
}
|
|
6212
|
+
}
|
|
6213
|
+
}
|
|
6214
|
+
/**
|
|
6215
|
+
* Reads a component after `][` that holds no delimiter: an image's link (`setter` false) or a
|
|
6216
|
+
* setter, in which single quotes also quote.
|
|
6217
|
+
*/
|
|
6218
|
+
function readComponent(reader, from, setter) {
|
|
6219
|
+
const { text } = reader;
|
|
6220
|
+
let depth = 2;
|
|
6221
|
+
let pos = from;
|
|
6222
|
+
while (pos < reader.limit) {
|
|
6223
|
+
const ch = text[pos];
|
|
6224
|
+
pos += 1;
|
|
6225
|
+
switch (ch) {
|
|
6226
|
+
case "\n": return;
|
|
6227
|
+
case "\"":
|
|
6228
|
+
case "'": {
|
|
6229
|
+
if (ch === "'" && !setter) break;
|
|
6230
|
+
const end = readQuoted(reader, pos, ch);
|
|
6231
|
+
if (end === void 0) return;
|
|
6232
|
+
pos = end;
|
|
6233
|
+
break;
|
|
6234
|
+
}
|
|
6235
|
+
case "[":
|
|
6236
|
+
depth += 1;
|
|
6237
|
+
break;
|
|
6238
|
+
case "]":
|
|
6239
|
+
depth -= 1;
|
|
6240
|
+
if (depth === 1) return componentEnd(text, pos);
|
|
6241
|
+
}
|
|
6242
|
+
}
|
|
6243
|
+
}
|
|
6244
|
+
/** Reads a setter, the last component; returns the index after its closing `]]`. */
|
|
6245
|
+
function readSetter(reader, from) {
|
|
6246
|
+
const end = readComponent(reader, from, true);
|
|
6247
|
+
return end?.last === true ? end.next : void 0;
|
|
6248
|
+
}
|
|
6249
|
+
/** What the `]` just before `pos`, which brings the depth back to one, ends; `undefined` if malformed. */
|
|
6250
|
+
function componentEnd(text, pos) {
|
|
6251
|
+
switch (text[pos]) {
|
|
6252
|
+
case "[": return {
|
|
6253
|
+
textEnd: pos - 1,
|
|
6254
|
+
next: pos + 1,
|
|
6255
|
+
last: false
|
|
6256
|
+
};
|
|
6257
|
+
case "]": return {
|
|
6258
|
+
textEnd: pos - 1,
|
|
6259
|
+
next: pos + 1,
|
|
6260
|
+
last: true
|
|
6261
|
+
};
|
|
6262
|
+
default: return;
|
|
6263
|
+
}
|
|
6264
|
+
}
|
|
6265
|
+
/**
|
|
6266
|
+
* Reads a quoted string from just after its opening quote; a backslash escapes the character
|
|
6267
|
+
* after it. A line feed, or the end of the text, ends it unterminated. Returns the index after the
|
|
6268
|
+
* closing quote.
|
|
6269
|
+
*/
|
|
6270
|
+
function readQuoted(reader, from, quote) {
|
|
6271
|
+
const { text } = reader;
|
|
6272
|
+
let pos = from;
|
|
6273
|
+
while (pos < reader.limit) {
|
|
6274
|
+
const ch = text[pos];
|
|
6275
|
+
pos += 1;
|
|
6276
|
+
if (ch === quote) return pos;
|
|
6277
|
+
if (ch === "\n") return;
|
|
6278
|
+
if (ch === "\\") {
|
|
6279
|
+
if (pos >= reader.limit || text[pos] === "\n") return;
|
|
6280
|
+
pos += 1;
|
|
6281
|
+
}
|
|
6282
|
+
}
|
|
6283
|
+
}
|
|
6284
|
+
//#endregion
|
|
5723
6285
|
//#region src/sugarcube-macros.ts
|
|
5724
6286
|
/**
|
|
5725
|
-
* Reads SugarCube 2 macro calls the way SugarCube 2.37.3 does, so the link check
|
|
5726
|
-
* passage names that `<<link>>` and `<<goto>>` use when the story
|
|
6287
|
+
* Reads SugarCube 2 macro calls and link markup the way SugarCube 2.37.3 does, so the link check
|
|
6288
|
+
* sees the same passage names that `[[…]]` links, `<<link>>` and `<<goto>>` use when the story
|
|
6289
|
+
* plays.
|
|
5727
6290
|
*
|
|
5728
6291
|
* Each step follows a part of SugarCube's macro parser:
|
|
5729
6292
|
* - `findMacroTags` finds where a tag starts and ends (the parser's `lookahead` pattern);
|
|
5730
6293
|
* - `parseMacroArgs` splits the text after the macro name into arguments (`parseArgs`);
|
|
5731
6294
|
* - quoted arguments are evaluated as strict-mode JavaScript strings (`evalStringLiteral`).
|
|
5732
6295
|
*
|
|
6296
|
+
* Link and image markup is read as `parseSquareBracketedMarkup` reads it (see `link-markup.ts`).
|
|
5733
6297
|
* Of the rest of the wikifier, only comments, `<script>` elements and `<<script>>` bodies are
|
|
5734
|
-
* told apart; other markup, such as verbatim text, is read as markup (see
|
|
5735
|
-
* `findMacroPassageLinks`).
|
|
6298
|
+
* told apart; other markup, such as verbatim text, is read as markup (see `findPassageLinks`).
|
|
5736
6299
|
*/
|
|
5737
6300
|
const NAME_RE = /\/?[A-Za-z][\w-]*|[=-]/y;
|
|
5738
6301
|
const SPACES_RE = /\s*/y;
|
|
@@ -5777,17 +6340,22 @@ const RAW_ARGUMENT_MACROS = /* @__PURE__ */ new Set([
|
|
|
5777
6340
|
* levels; the limit keeps the work linear in the size of the text on any input.
|
|
5778
6341
|
*/
|
|
5779
6342
|
const MAX_STRING_DEPTH = 10;
|
|
5780
|
-
/**
|
|
6343
|
+
/**
|
|
6344
|
+
* A context for reading `text`: the closer search, and the markup reading, may each read four
|
|
6345
|
+
* times it, plus an allowance.
|
|
6346
|
+
*/
|
|
5781
6347
|
function readContext(text) {
|
|
6348
|
+
const allowance = () => ({ left: 4 * text.length + 1e5 });
|
|
5782
6349
|
return {
|
|
5783
6350
|
depth: 0,
|
|
5784
|
-
budget:
|
|
6351
|
+
budget: allowance(),
|
|
6352
|
+
markupBudget: allowance()
|
|
5785
6353
|
};
|
|
5786
6354
|
}
|
|
5787
6355
|
function deeper(context) {
|
|
5788
6356
|
return {
|
|
5789
|
-
|
|
5790
|
-
|
|
6357
|
+
...context,
|
|
6358
|
+
depth: context.depth + 1
|
|
5791
6359
|
};
|
|
5792
6360
|
}
|
|
5793
6361
|
/** Index of the first match of a global `re` at or after `from`, or -1. */
|
|
@@ -6017,7 +6585,10 @@ function lexArgument(raw, pos) {
|
|
|
6017
6585
|
case "[": {
|
|
6018
6586
|
const end = lexSquareBracketed(raw, pos + 1);
|
|
6019
6587
|
return end === void 0 ? void 0 : {
|
|
6020
|
-
arg: {
|
|
6588
|
+
arg: {
|
|
6589
|
+
kind: "markup",
|
|
6590
|
+
text: raw.slice(pos, end)
|
|
6591
|
+
},
|
|
6021
6592
|
end
|
|
6022
6593
|
};
|
|
6023
6594
|
}
|
|
@@ -6161,13 +6732,44 @@ function ownPassageLink(tag, lexed) {
|
|
|
6161
6732
|
const arg = passageArgument(tag.name, lexed);
|
|
6162
6733
|
const passage = arg === void 0 ? void 0 : passageName(arg);
|
|
6163
6734
|
return passage === void 0 ? void 0 : {
|
|
6164
|
-
|
|
6735
|
+
via: tag.name,
|
|
6165
6736
|
passage
|
|
6166
6737
|
};
|
|
6167
6738
|
}
|
|
6168
6739
|
/**
|
|
6169
|
-
* The
|
|
6170
|
-
*
|
|
6740
|
+
* The passage a link's destination names. SugarCube evaluates a destination that no passage is
|
|
6741
|
+
* named by, and a quoted string gives its value (`[[Go|"Room"]]`), unless that is blank.
|
|
6742
|
+
*/
|
|
6743
|
+
function linkDestination(link) {
|
|
6744
|
+
const value = evalStringLiteral(link);
|
|
6745
|
+
return value === void 0 || value.trim() === "" ? link : value;
|
|
6746
|
+
}
|
|
6747
|
+
/**
|
|
6748
|
+
* The passage that link markup from `start` in `text` names, and where the markup ends, or
|
|
6749
|
+
* `undefined` where SugarCube rejects the markup. Image markup names none here, nor does markup
|
|
6750
|
+
* with a template literal's `${…}` in it, whose passage is known only in play.
|
|
6751
|
+
*/
|
|
6752
|
+
function linkMarkupAt(text, start, budget) {
|
|
6753
|
+
const markup = readSquareBracketedMarkup(text, start, budget);
|
|
6754
|
+
if (markup === void 0) return;
|
|
6755
|
+
const passage = markup.type === "link" && !text.slice(start, markup.end).includes("") ? markup.link : void 0;
|
|
6756
|
+
return {
|
|
6757
|
+
link: passage === void 0 ? void 0 : {
|
|
6758
|
+
via: "markup",
|
|
6759
|
+
passage: linkDestination(passage)
|
|
6760
|
+
},
|
|
6761
|
+
end: markup.end
|
|
6762
|
+
};
|
|
6763
|
+
}
|
|
6764
|
+
/** The passage that a link markup argument names, if SugarCube reads the whole argument as markup. */
|
|
6765
|
+
function markupArgumentLinks(raw) {
|
|
6766
|
+
const markup = linkMarkupAt(raw, 0);
|
|
6767
|
+
return markup?.link === void 0 || markup.end !== raw.length ? [] : [markup.link];
|
|
6768
|
+
}
|
|
6769
|
+
/**
|
|
6770
|
+
* The passages a tag names: its own, if it is a `<<link>>` or `<<goto>>` call, then those of its
|
|
6771
|
+
* link markup arguments (`<<button [[Go|Room]]>>`), and those of the links and calls inside the
|
|
6772
|
+
* strings of its arguments, which the macro may print or pass on
|
|
6171
6773
|
* (`<<set _out to '<<link "Go" "Room">><</link>>'>>`). The arguments of the macros SugarCube
|
|
6172
6774
|
* doesn't split are read as JavaScript; in others, a backquoted expression is.
|
|
6173
6775
|
*/
|
|
@@ -6180,7 +6782,7 @@ function tagPassageLinks(tag, context) {
|
|
|
6180
6782
|
switch (arg.kind) {
|
|
6181
6783
|
case "string": return markupPassageLinks(arg.value, deeper(context));
|
|
6182
6784
|
case "expression": return javaScriptPassageLinks(arg.code, context);
|
|
6183
|
-
case "markup":
|
|
6785
|
+
case "markup": return markupArgumentLinks(arg.text);
|
|
6184
6786
|
case "word": return [];
|
|
6185
6787
|
default: throw new Error(`unhandled macro argument: ${JSON.stringify(arg)}`);
|
|
6186
6788
|
}
|
|
@@ -6190,16 +6792,26 @@ function tagPassageLinks(tag, context) {
|
|
|
6190
6792
|
/**
|
|
6191
6793
|
* The passage named by a `<<link>>` or `<<goto>>` that appears unquoted inside another tag's
|
|
6192
6794
|
* arguments, at `start`. SugarCube never sees such an outer "tag" when its `<<` lies in text it
|
|
6193
|
-
* reads as something else, such as
|
|
6194
|
-
*
|
|
6795
|
+
* reads as something else, such as verbatim text (`{{{<<if}}}`); the call inside it then runs.
|
|
6796
|
+
* The call ends where the outer tag ends.
|
|
6195
6797
|
*/
|
|
6196
6798
|
function innerPassageLink(matchTagAt, start) {
|
|
6197
6799
|
const inner = matchTagAt(start)?.tag;
|
|
6198
6800
|
const lexed = inner === void 0 ? void 0 : lexMacroArgs(inner.args);
|
|
6199
6801
|
return inner === void 0 || lexed === void 0 ? void 0 : ownPassageLink(inner, lexed);
|
|
6200
6802
|
}
|
|
6201
|
-
const REGION_OPEN_RE =
|
|
6803
|
+
const REGION_OPEN_RE = /\[\[[^[]|\[[<>]?[Ii][Mm][Gg]\[|\/\/|\/\*|\/%|<!--|<[Ss][Cc][Rr][Ii][Pp][Tt]/g;
|
|
6202
6804
|
const HAS_SCRIPT_OPEN_RE = /<[Ss][Cc][Rr][Ii][Pp][Tt]/;
|
|
6805
|
+
function regionKind(opener) {
|
|
6806
|
+
if (opener.startsWith("[")) return "markup";
|
|
6807
|
+
switch (opener) {
|
|
6808
|
+
case "//":
|
|
6809
|
+
case "/*":
|
|
6810
|
+
case "/%":
|
|
6811
|
+
case "<!--": return opener;
|
|
6812
|
+
default: return "script";
|
|
6813
|
+
}
|
|
6814
|
+
}
|
|
6203
6815
|
const SCRIPT_CLOSE_RE = /<\/[Ss][Cc][Rr][Ii][Pp][Tt]>|[\r\u2028\u2029]/g;
|
|
6204
6816
|
const COMMENT_CLOSE_RES = {
|
|
6205
6817
|
"/*": /\*\/|[\r\u2028\u2029]/g,
|
|
@@ -6353,22 +6965,31 @@ function append(links, more) {
|
|
|
6353
6965
|
for (const link of more) links.push(link);
|
|
6354
6966
|
}
|
|
6355
6967
|
/**
|
|
6356
|
-
* The passages that `<<link>>` and `<<goto>>` calls in passage markup
|
|
6357
|
-
* is known only in play (a variable or an
|
|
6358
|
-
*
|
|
6968
|
+
* The passages that link markup (`[[…]]`) and `<<link>>` and `<<goto>>` calls in passage markup
|
|
6969
|
+
* name, in the order they come. Calls whose passage is known only in play (a variable or an
|
|
6970
|
+
* expression) are left out. A tag's own passage comes before those that its arguments name, as
|
|
6971
|
+
* link markup or inside strings.
|
|
6359
6972
|
*
|
|
6360
6973
|
* The markup is walked in order, as SugarCube's wikifier walks it, with a tag tried at each
|
|
6361
|
-
* `<<` the walk reaches
|
|
6362
|
-
*
|
|
6363
|
-
*
|
|
6364
|
-
*
|
|
6365
|
-
*
|
|
6974
|
+
* `<<` the walk reaches, and link or image markup read at each `[[` or `[img[`; markup SugarCube
|
|
6975
|
+
* rejects is read on from just after its opener, and so is markup after a limit on how much
|
|
6976
|
+
* markup a reading may scan, which only input built to take quadratic time reaches (see
|
|
6977
|
+
* `readSquareBracketedMarkup`). Image markup names no passage here. Of the wikifier's other
|
|
6978
|
+
* parsers, only those whose text holds no link or call are told apart: comments (`/* … *` + `/`,
|
|
6979
|
+
* `/% … %/`, `<!-- … -->`), whose links and calls never run, and `<script>` elements and
|
|
6980
|
+
* `<<script>>` bodies, which are JavaScript: only the links and calls in their strings are read
|
|
6981
|
+
* (see `findJavaScriptPassageLinks`). Everything else, verbatim text included, is read as markup.
|
|
6366
6982
|
*
|
|
6367
6983
|
* Where this differs from SugarCube:
|
|
6984
|
+
* - a link whose passage SugarCube evaluates, because no passage has its name, is taken by its
|
|
6985
|
+
* name, `[[Go|$next]]` naming the passage `$next`, unless it is a quoted string, which is taken
|
|
6986
|
+
* by its value even when a passage has the name with the quotes;
|
|
6987
|
+
* - a link SugarCube takes for a URL, because no passage has its name and it looks like one or
|
|
6988
|
+
* holds a `/`, `.`, `?` or `#`, is still read as naming a passage;
|
|
6368
6989
|
* - a comment or a `<<script>>` body is skipped whole, even where `parseBody` ends a container
|
|
6369
6990
|
* such as `<<if>>` at a closing tag inside it and the rest then runs;
|
|
6370
|
-
* - a `/*`, `<!--` or `<script` inside other markup that holds no call, such as
|
|
6371
|
-
* `<style>` element, still starts a comment or an element;
|
|
6991
|
+
* - a `[[`, `/*`, `<!--` or `<script` inside other markup that holds no call, such as verbatim
|
|
6992
|
+
* text or a `<style>` element, still starts link markup, a comment or an element;
|
|
6372
6993
|
* - a `<<` in such other markup still starts a tag. When that tag runs over a `<<link` or
|
|
6373
6994
|
* `<<goto` outside the parts of its arguments that the tag pattern reads as units, that call
|
|
6374
6995
|
* is still read (see `innerPassageLink`), even where the tag's arguments would be JavaScript,
|
|
@@ -6383,33 +7004,43 @@ function append(links, more) {
|
|
|
6383
7004
|
* `Config.passages.nobr`, are not joined before they are read (see `storyInspect` for passages
|
|
6384
7005
|
* tagged `nobr`).
|
|
6385
7006
|
*/
|
|
6386
|
-
function
|
|
7007
|
+
function findPassageLinks(text) {
|
|
6387
7008
|
return markupPassageLinks(text, readContext(text));
|
|
6388
7009
|
}
|
|
6389
7010
|
function markupPassageLinks(text, context) {
|
|
6390
|
-
if (context.depth > MAX_STRING_DEPTH || !text.includes("<<") && !HAS_SCRIPT_OPEN_RE.test(text)) return [];
|
|
7011
|
+
if (context.depth > MAX_STRING_DEPTH || !text.includes("<<") && !text.includes("[[") && !HAS_SCRIPT_OPEN_RE.test(text)) return [];
|
|
6391
7012
|
const matchTagAt = tagMatcher(text);
|
|
6392
7013
|
const matchInnerTagAt = tagMatcher(text);
|
|
6393
7014
|
const readComment = commentReader(text);
|
|
6394
7015
|
const readScriptElement = scriptElementReader(text);
|
|
6395
7016
|
let findScriptCloser;
|
|
6396
7017
|
const links = [];
|
|
6397
|
-
/**
|
|
7018
|
+
/**
|
|
7019
|
+
* Reads the region `opener` opens, adding the passage that link markup names and the links and
|
|
7020
|
+
* calls in a `<script>` element; returns where the walk goes on.
|
|
7021
|
+
*/
|
|
6398
7022
|
const regionEnd = (opener) => {
|
|
6399
7023
|
const start = opener.index;
|
|
6400
|
-
const kind = opener[0];
|
|
7024
|
+
const kind = regionKind(opener[0]);
|
|
6401
7025
|
switch (kind) {
|
|
7026
|
+
case "markup": {
|
|
7027
|
+
const markup = linkMarkupAt(text, start, context.markupBudget);
|
|
7028
|
+
if (markup === void 0) return start + opener[0].length;
|
|
7029
|
+
if (markup.link !== void 0) links.push(markup.link);
|
|
7030
|
+
return markup.end;
|
|
7031
|
+
}
|
|
6402
7032
|
case "//": return start + 2;
|
|
6403
7033
|
case "/*":
|
|
6404
7034
|
case "/%":
|
|
6405
7035
|
case "<!--": return readComment(kind, start) ?? start + kind.length;
|
|
6406
|
-
|
|
7036
|
+
case "script": {
|
|
6407
7037
|
const element = readScriptElement(start);
|
|
6408
7038
|
if (element.openerEnd === void 0) return start + 1;
|
|
6409
7039
|
if (element.close === void 0) return element.openerEnd;
|
|
6410
7040
|
append(links, javaScriptPassageLinks(text.slice(element.openerEnd, element.close), context));
|
|
6411
7041
|
return element.close + 9;
|
|
6412
7042
|
}
|
|
7043
|
+
default: throw new Error(`unhandled region: ${String(kind)}`);
|
|
6413
7044
|
}
|
|
6414
7045
|
};
|
|
6415
7046
|
let macro = -2;
|
|
@@ -6449,24 +7080,26 @@ function markupPassageLinks(text, context) {
|
|
|
6449
7080
|
}
|
|
6450
7081
|
}
|
|
6451
7082
|
/**
|
|
6452
|
-
* The passages that `<<link>>` and `<<goto>>` calls in the strings of JavaScript
|
|
6453
|
-
* such as a script passage or a `<<script>>` body: `$.wiki('<<goto "Room">>')`.
|
|
6454
|
-
* the strings isn't markup, so a call put together while the story plays, such as
|
|
6455
|
-
* `'<<goto "' + target + '">>'`, names no passage here.
|
|
7083
|
+
* The passages that link markup and `<<link>>` and `<<goto>>` calls in the strings of JavaScript
|
|
7084
|
+
* source name, such as a script passage or a `<<script>>` body: `$.wiki('<<goto "Room">>')`.
|
|
7085
|
+
* Code outside the strings isn't markup, so a call put together while the story plays, such as
|
|
7086
|
+
* `'<<goto "' + target + '">>'`, names no passage here, nor does an array of arrays (`[[0, 1]]`).
|
|
6456
7087
|
*/
|
|
6457
7088
|
function findJavaScriptPassageLinks(source) {
|
|
6458
7089
|
return javaScriptPassageLinks(source, readContext(source));
|
|
6459
7090
|
}
|
|
6460
7091
|
/**
|
|
6461
7092
|
* What JavaScript source must contain for one of its string or template literals to hold a call
|
|
6462
|
-
* that is read. A value holding `<<`: each `<` in it is written as `<`, `\<`,
|
|
6463
|
-
* `\u{…}`, two can be next to each other with only line continuations
|
|
6464
|
-
* is `<` or `\<` (then the source holds `<<` or `<\`) or one of the others.
|
|
6465
|
-
*
|
|
7093
|
+
* or link markup that is read. A value holding `<<`: each `<` in it is written as `<`, `\<`,
|
|
7094
|
+
* `\x3c`, `\u003c` or `\u{…}`, two can be next to each other with only line continuations
|
|
7095
|
+
* between, and the first is `<` or `\<` (then the source holds `<<` or `<\`) or one of the others.
|
|
7096
|
+
* A value holding `[[`, likewise: the source holds `[[`, a `[` before `\[` or a line continuation,
|
|
7097
|
+
* `\x5b`, `\u005b` or `\u{`. Or a value holding a `<script>` element, whose own strings can make
|
|
7098
|
+
* `<<` or `[[` from escapes the outer string encodes.
|
|
6466
7099
|
*/
|
|
6467
|
-
const
|
|
7100
|
+
const MAY_HOLD_LINK_RE = /<<|<\\|\\x3c|\\u003c|\\u\{|<script|\[\[|\[\\[[\n\r\u2028\u2029]|\\x5b|\\u005b/i;
|
|
6468
7101
|
function javaScriptPassageLinks(source, context) {
|
|
6469
|
-
if (context.depth >= MAX_STRING_DEPTH || !
|
|
7102
|
+
if (context.depth >= MAX_STRING_DEPTH || !MAY_HOLD_LINK_RE.test(source)) return [];
|
|
6470
7103
|
const inner = deeper(context);
|
|
6471
7104
|
const links = [];
|
|
6472
7105
|
for (const value of javaScriptStrings(source)) append(links, markupPassageLinks(value, inner));
|
|
@@ -6475,43 +7108,34 @@ function javaScriptPassageLinks(source, context) {
|
|
|
6475
7108
|
//#endregion
|
|
6476
7109
|
//#region src/inspect.ts
|
|
6477
7110
|
/**
|
|
6478
|
-
* Extract
|
|
7111
|
+
* Extract the passages that passage text links to, read as SugarCube 2 reads them.
|
|
6479
7112
|
*
|
|
6480
7113
|
* Supported syntaxes:
|
|
6481
7114
|
* - `[[PassageName]]`
|
|
6482
|
-
* - `[[Display Text
|
|
6483
|
-
* - `[[Display Text
|
|
6484
|
-
* -
|
|
7115
|
+
* - `[[Display Text|PassageName]]`
|
|
7116
|
+
* - `[[Display Text->PassageName]]`
|
|
7117
|
+
* - `[[PassageName<-Display Text]]`
|
|
7118
|
+
* - any of those with a setter: `[[Display Text|PassageName][$x to 1]]`
|
|
7119
|
+
* - `<<goto "PassageName">>` (SugarCube macro)
|
|
6485
7120
|
* - `<<link "Display" "PassageName">>` (SugarCube macro)
|
|
6486
7121
|
*
|
|
6487
|
-
*
|
|
6488
|
-
*
|
|
6489
|
-
*
|
|
6490
|
-
*
|
|
6491
|
-
*
|
|
6492
|
-
*
|
|
7122
|
+
* In link markup, the first `|`, `->` or `<-` divides the text from the passage name; image
|
|
7123
|
+
* markup (`[img[…][PassageName]]`) is not read. SugarCube macro arguments may be double- or
|
|
7124
|
+
* single-quoted, with backslash escapes, or bare words; a passage named by a variable or an
|
|
7125
|
+
* expression is known only in play and is skipped. Links and macro calls are also read inside the
|
|
7126
|
+
* quoted strings of macros' arguments, and inside the strings of `<<script>>` bodies and
|
|
7127
|
+
* `<script>` elements; links and calls in comments are not read. A script passage (`isScript`) is
|
|
7128
|
+
* JavaScript, so its links and calls are read only inside its strings. See `sugarcube-macros.ts`
|
|
7129
|
+
* for the details and the known differences from SugarCube.
|
|
6493
7130
|
*/
|
|
6494
7131
|
function extractLinksFromText(text, isScript) {
|
|
6495
|
-
const
|
|
6496
|
-
const
|
|
6497
|
-
|
|
6498
|
-
|
|
6499
|
-
|
|
6500
|
-
|
|
6501
|
-
|
|
6502
|
-
targets.add(content.slice(arrowIdx + 2).trim());
|
|
6503
|
-
continue;
|
|
6504
|
-
}
|
|
6505
|
-
const pipeIdx = content.indexOf("|");
|
|
6506
|
-
if (pipeIdx !== -1) {
|
|
6507
|
-
targets.add(content.slice(pipeIdx + 1).trim());
|
|
6508
|
-
continue;
|
|
6509
|
-
}
|
|
6510
|
-
targets.add(content.trim());
|
|
6511
|
-
}
|
|
6512
|
-
const macroLinks = isScript ? findJavaScriptPassageLinks(text) : findMacroPassageLinks(text);
|
|
6513
|
-
for (const macro of ["goto", "link"]) for (const link of macroLinks) if (link.macro === macro) targets.add(link.passage);
|
|
6514
|
-
return [...targets];
|
|
7132
|
+
const found = isScript ? findJavaScriptPassageLinks(text) : findPassageLinks(text);
|
|
7133
|
+
const ordered = [
|
|
7134
|
+
"markup",
|
|
7135
|
+
"goto",
|
|
7136
|
+
"link"
|
|
7137
|
+
].flatMap((via) => found.filter((link) => link.via === via).map((link) => link.passage));
|
|
7138
|
+
return [...new Set(ordered)];
|
|
6515
7139
|
}
|
|
6516
7140
|
/** Passages SugarCube runs from their raw text, never joining their lines. */
|
|
6517
7141
|
const RAW_TEXT_PASSAGES = /* @__PURE__ */ new Set([
|
|
@@ -6614,7 +7238,8 @@ function storyInspect(story) {
|
|
|
6614
7238
|
//#region src/lint.ts
|
|
6615
7239
|
/**
|
|
6616
7240
|
* Lint a story: compile without output rendering, then inspect structure.
|
|
6617
|
-
* Uses JSON output mode internally to avoid format resolution
|
|
7241
|
+
* Uses JSON output mode internally to avoid format resolution, so it checks
|
|
7242
|
+
* the starting passage itself, against the Twine 2 passage rules.
|
|
6618
7243
|
*/
|
|
6619
7244
|
async function lint(options) {
|
|
6620
7245
|
const result = await compile({
|
|
@@ -6623,7 +7248,7 @@ async function lint(options) {
|
|
|
6623
7248
|
});
|
|
6624
7249
|
const map = storyInspect(result.story);
|
|
6625
7250
|
return {
|
|
6626
|
-
diagnostics: result.diagnostics,
|
|
7251
|
+
diagnostics: [...result.diagnostics, ...startPassageDiagnostics(result.story, map.start, "twine2")],
|
|
6627
7252
|
stats: result.stats,
|
|
6628
7253
|
formatName: result.story.twine2.format,
|
|
6629
7254
|
formatVersion: result.story.twine2.formatVersion,
|