@rohal12/spindle 0.60.4 → 0.61.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.
@@ -10876,6 +10876,10 @@ function showRuntimeError(context, error) {
10876
10876
  count: 1
10877
10877
  }]);
10878
10878
  }
10879
+ /** The error for navigating to `name`, a special passage (StoryInit, ...). */
10880
+ function specialPassageError(name) {
10881
+ return /* @__PURE__ */ new Error(`Cannot navigate to special passage "${name}".`);
10882
+ }
10879
10883
  /**
10880
10884
  * The error for `name`, a passage name that names no passage, used in the
10881
10885
  * passage `from`.
@@ -18472,6 +18476,10 @@ var SPECIAL_PASSAGES = /* @__PURE__ */ new Set([
18472
18476
  "PassageDone",
18473
18477
  "StoryContext"
18474
18478
  ]);
18479
+ /** Whether `name` is a special passage, which navigation never goes to. */
18480
+ function isSpecialPassage(name) {
18481
+ return SPECIAL_PASSAGES.has(name);
18482
+ }
18475
18483
  /** Full variable snapshot at history index 0. */
18476
18484
  var variableBase = createNamespace();
18477
18485
  /**
@@ -19308,8 +19316,8 @@ var useStoryStore = create()(storyStore((set, get) => ({
19308
19316
  }
19309
19317
  const { storyData } = get();
19310
19318
  if (!storyData) return;
19311
- if (SPECIAL_PASSAGES.has(passageName)) {
19312
- console.error(`spindle: Cannot navigate to special passage "${passageName}".`);
19319
+ if (isSpecialPassage(passageName)) {
19320
+ console.error(`spindle: ${specialPassageError(passageName).message}`);
19313
19321
  return;
19314
19322
  }
19315
19323
  if (!storyData.passages.has(passageName)) {
@@ -25152,6 +25160,25 @@ function bootStory(options) {
25152
25160
  });
25153
25161
  }
25154
25162
  /**
25163
+ * The story's `$` variables: a shallow copy of the current values, keyed by
25164
+ * name without the `$`. Values are the store's own (frozen) objects.
25165
+ */
25166
+ function storyVariables() {
25167
+ return { ...useStoryStore.getState().variables };
25168
+ }
25169
+ /**
25170
+ * Why `Story.goto(name)` would not navigate, or `null` if it would: `name` is
25171
+ * a special passage (StoryInit, ...) or names no passage. The message is the
25172
+ * one Spindle logs (and, for a missing passage, shows on the page), since
25173
+ * `Story.goto()` reports these instead of throwing.
25174
+ */
25175
+ function gotoError(name) {
25176
+ const { storyData, currentPassage } = useStoryStore.getState();
25177
+ if (isSpecialPassage(name)) return specialPassageError(name).message;
25178
+ if (!storyData?.passages.has(name)) return noPassageError(name, currentPassage).message;
25179
+ return null;
25180
+ }
25181
+ /**
25155
25182
  * Record a playthrough for stateless decision models, which need the last few
25156
25183
  * steps sent with every call. A step that rejects records nothing.
25157
25184
  */
@@ -25186,4 +25213,4 @@ function createTranscript(story, options = {}) {
25186
25213
  };
25187
25214
  }
25188
25215
  //#endregion
25189
- export { bootStory, createTranscript };
25216
+ export { bootStory, createTranscript, gotoError, storyVariables };
@@ -0,0 +1,181 @@
1
+ import { parentPort, workerData } from "node:worker_threads";
2
+ //#region src/utils/error-message.ts
3
+ /**
4
+ * The message to show for a caught value. Anything can be thrown, not only
5
+ * Errors: an Error gives its message, a string is its own message, and any
6
+ * other value gives `fallback` when one is passed, else its string form
7
+ * (never `undefined`). An empty message also gives `fallback`, or for an
8
+ * Error its string form (e.g. "Error").
9
+ */
10
+ function errorMessage(err, fallback) {
11
+ try {
12
+ if (err instanceof Error) return err.message || fallback || String(err);
13
+ if (typeof err === "string" && err !== "") return err;
14
+ return fallback ?? String(err);
15
+ } catch {
16
+ return fallback ?? "Unprintable error";
17
+ }
18
+ }
19
+ //#endregion
20
+ //#region src/play/optional.ts
21
+ var defaultImporter = (pkg) => import(pkg);
22
+ function isMissingPackage(err, pkg) {
23
+ return err instanceof Error && err.code === "ERR_MODULE_NOT_FOUND" && err.message.includes(`'${pkg}'`);
24
+ }
25
+ /**
26
+ * Import `pkg`, rejecting with an install hint when it isn't installed. Any
27
+ * other import error (a failure inside the package, a different missing
28
+ * module) is rethrown unchanged.
29
+ */
30
+ async function loadOptional(pkg, feature, importer = defaultImporter) {
31
+ try {
32
+ return await importer(pkg);
33
+ } catch (err) {
34
+ if (isMissingPackage(err, pkg)) throw new Error(`spindle: ${feature} needs ${pkg}; install it with npm i -D ${pkg}`);
35
+ throw err;
36
+ }
37
+ }
38
+ //#endregion
39
+ //#region src/play/worker.ts
40
+ /**
41
+ * The worker thread of a play session: boots the story on happy-dom and
42
+ * answers the session handle's calls (see `protocol.ts`). Built to
43
+ * `dist/pkg/play-worker.js`.
44
+ */
45
+ var stderr = process.stderr;
46
+ Object.defineProperty(process, "stdout", {
47
+ configurable: true,
48
+ get: () => stderr
49
+ });
50
+ var port = parentPort;
51
+ var data = workerData;
52
+ /** Make happy-dom's window the global environment Spindle runs in. */
53
+ async function installDom() {
54
+ const { Window } = await loadOptional("happy-dom", "play sessions");
55
+ const window = new Window({ url: "http://localhost/" });
56
+ const global = globalThis;
57
+ const source = window;
58
+ global.window = window;
59
+ global.document = window.document;
60
+ for (const name of Object.getOwnPropertyNames(window)) if (!(name in globalThis)) global[name] = source[name];
61
+ for (const name of HAPPY_DOM_GLOBALS) Object.defineProperty(globalThis, name, {
62
+ configurable: true,
63
+ writable: true,
64
+ value: source[name]
65
+ });
66
+ Object.defineProperty(globalThis, "BroadcastChannel", {
67
+ configurable: true,
68
+ writable: true,
69
+ value: void 0
70
+ });
71
+ Object.defineProperty(globalThis, "Story", {
72
+ configurable: true,
73
+ get: () => source.Story
74
+ });
75
+ }
76
+ /**
77
+ * Globals happy-dom's window replaces even where Node has its own:
78
+ * - the event classes: happy-dom's dispatchEvent() refuses events made with
79
+ * Node's (`new CustomEvent(':storyready')` at boot);
80
+ * - the storages: Node 25+ has a `localStorage` that is undefined without
81
+ * `--localstorage-file`, and Node's would be shared by every session;
82
+ * - `navigator`: Node's `navigator.locks` is shared by every worker in the
83
+ * process.
84
+ */
85
+ var HAPPY_DOM_GLOBALS = [
86
+ "Event",
87
+ "CustomEvent",
88
+ "EventTarget",
89
+ "localStorage",
90
+ "sessionStorage",
91
+ "navigator"
92
+ ];
93
+ /**
94
+ * A value as the reply will carry it (structured clone keeps Map, Set, Date
95
+ * and cycles), or a marker when it cannot be cloned (a function, a Map
96
+ * holding one).
97
+ */
98
+ function encode(value) {
99
+ try {
100
+ return structuredClone(value);
101
+ } catch (err) {
102
+ return `[unserializable: ${errorMessage(err)}]`;
103
+ }
104
+ }
105
+ function encodeAll(values) {
106
+ const out = {};
107
+ for (const [name, value] of Object.entries(values)) out[name] = encode(value);
108
+ return out;
109
+ }
110
+ async function start() {
111
+ await installDom();
112
+ const headless = await import(
113
+ /* @vite-ignore */
114
+ data.headlessUrl
115
+ );
116
+ const story = await headless.bootStory({
117
+ html: data.html,
118
+ transitions: data.transitions
119
+ });
120
+ const transcript = headless.createTranscript(story, data.transcript);
121
+ const ops = {
122
+ observe: () => story.observe(),
123
+ step: ([id, value]) => transcript.step(id, value),
124
+ goto: async ([passage]) => {
125
+ const name = passage;
126
+ const refused = headless.gotoError(name);
127
+ if (refused !== null) throw new Error(`spindle: ${refused}`);
128
+ story.goto(name);
129
+ await story.waitForActions();
130
+ return story.observe();
131
+ },
132
+ get: ([names]) => {
133
+ if (names === void 0) return encodeAll(headless.storyVariables());
134
+ const values = {};
135
+ for (const name of names) {
136
+ const key = name.replace(/^\$/, "");
137
+ values[key] = story.get(key);
138
+ }
139
+ return encodeAll(values);
140
+ },
141
+ set: async ([values]) => {
142
+ story.set(values);
143
+ await story.waitForActions();
144
+ },
145
+ transcript: () => [...transcript.entries]
146
+ };
147
+ port.on("message", async ({ id, op, args }) => {
148
+ let reply;
149
+ try {
150
+ reply = {
151
+ id,
152
+ ok: true,
153
+ result: await ops[op](args)
154
+ };
155
+ } catch (err) {
156
+ reply = {
157
+ id,
158
+ ok: false,
159
+ error: { message: errorMessage(err) }
160
+ };
161
+ }
162
+ try {
163
+ port.postMessage(reply);
164
+ } catch (err) {
165
+ port.postMessage({
166
+ id,
167
+ ok: false,
168
+ error: { message: errorMessage(err) }
169
+ });
170
+ }
171
+ });
172
+ port.postMessage({ ready: true });
173
+ }
174
+ start().catch((err) => {
175
+ port.postMessage({
176
+ ready: false,
177
+ error: { message: errorMessage(err) }
178
+ });
179
+ process.exit(1);
180
+ });
181
+ //#endregion
@@ -0,0 +1,398 @@
1
+ import { glob, readFile, stat } from "node:fs/promises";
2
+ import { isAbsolute, relative, resolve, sep } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { Worker } from "node:worker_threads";
5
+ //#region src/utils/error-message.ts
6
+ /**
7
+ * The message to show for a caught value. Anything can be thrown, not only
8
+ * Errors: an Error gives its message, a string is its own message, and any
9
+ * other value gives `fallback` when one is passed, else its string form
10
+ * (never `undefined`). An empty message also gives `fallback`, or for an
11
+ * Error its string form (e.g. "Error").
12
+ */
13
+ function errorMessage(err, fallback) {
14
+ try {
15
+ if (err instanceof Error) return err.message || fallback || String(err);
16
+ if (typeof err === "string" && err !== "") return err;
17
+ return fallback ?? String(err);
18
+ } catch {
19
+ return fallback ?? "Unprintable error";
20
+ }
21
+ }
22
+ //#endregion
23
+ //#region src/play/optional.ts
24
+ var defaultImporter = (pkg) => import(pkg);
25
+ function isMissingPackage(err, pkg) {
26
+ return err instanceof Error && err.code === "ERR_MODULE_NOT_FOUND" && err.message.includes(`'${pkg}'`);
27
+ }
28
+ /**
29
+ * Import `pkg`, rejecting with an install hint when it isn't installed. Any
30
+ * other import error (a failure inside the package, a different missing
31
+ * module) is rethrown unchanged.
32
+ */
33
+ async function loadOptional(pkg, feature, importer = defaultImporter) {
34
+ try {
35
+ return await importer(pkg);
36
+ } catch (err) {
37
+ if (isMissingPackage(err, pkg)) throw new Error(`spindle: ${feature} needs ${pkg}; install it with npm i -D ${pkg}`);
38
+ throw err;
39
+ }
40
+ }
41
+ //#endregion
42
+ //#region src/play/resolve-story.ts
43
+ /**
44
+ * twee-ts takes a format ID to be the name of the folder holding format.js,
45
+ * not the name inside it. The package keeps its format in `dist/pkg/`, and
46
+ * `formatSearchDir` is `dist/`.
47
+ */
48
+ var FORMAT_FOLDER = "pkg";
49
+ var HTML_PATH = /\.html?$/i;
50
+ var GLOB_CHARS = /[*?[\]{}]/;
51
+ /** `file:line: message` per error; just the message without a location. */
52
+ function formatDiagnostic(d) {
53
+ return d.file !== void 0 && d.line !== void 0 ? `${d.file}:${d.line}: ${d.message}` : d.message;
54
+ }
55
+ function diagnosticsError(diagnostics, fallback) {
56
+ const errors = diagnostics.filter((d) => d.level === "error");
57
+ return new Error(errors.length > 0 ? errors.map(formatDiagnostic).join("\n") : fallback);
58
+ }
59
+ /** The files a glob pattern matches, sorted. */
60
+ async function expandGlob(pattern) {
61
+ const matches = [];
62
+ for await (const file of glob(pattern)) matches.push(file);
63
+ return matches.sort();
64
+ }
65
+ /** A path segment with glob syntax in it (as `path.matchesGlob` reads it). */
66
+ var GLOB_SEGMENT = /[*?[\]{}()!+@]/;
67
+ /**
68
+ * An `exclude` glob of the project config as twee-ts matches it: against
69
+ * paths relative to the working directory. A relative glob is relative to the
70
+ * project directory; an absolute one has its literal leading folders made
71
+ * relative. Either way the folder part added or rewritten is escaped.
72
+ */
73
+ function rebaseExclude(dir, pattern) {
74
+ let base = dir;
75
+ let rest = pattern.replace(/^\.\//, "");
76
+ if (isAbsolute(pattern)) {
77
+ const parts = pattern.split("/");
78
+ let literal = parts.findIndex((part) => GLOB_SEGMENT.test(part));
79
+ if (literal === -1) literal = parts.length;
80
+ base = parts.slice(0, literal).join("/") || "/";
81
+ rest = parts.slice(literal).join("/");
82
+ }
83
+ const fromCwd = globLiteral(relative(process.cwd(), base).split(sep).join("/"));
84
+ if (fromCwd === "") return rest;
85
+ return rest === "" ? fromCwd : `${fromCwd}/${rest}`;
86
+ }
87
+ /**
88
+ * The project config with its paths made independent of the working
89
+ * directory. twee-ts reads `sources`, `modules` and `headFile` relative to
90
+ * the working directory, and matches `exclude` globs against paths relative
91
+ * to it, so each is rebased from the project directory.
92
+ */
93
+ function rebaseConfig(dir, config) {
94
+ const rebased = {
95
+ ...config,
96
+ sources: (config.sources ?? ["."]).map((s) => resolve(dir, s))
97
+ };
98
+ if (config.modules) rebased.modules = config.modules.map((m) => resolve(dir, m));
99
+ if (config.headFile !== void 0) rebased.headFile = resolve(dir, config.headFile);
100
+ if (config.exclude) rebased.exclude = config.exclude.map((e) => rebaseExclude(dir, e));
101
+ return rebased;
102
+ }
103
+ /**
104
+ * The project config less its output and format options. Those are ours: the
105
+ * project's own would write a file, compile for another format, or fetch one.
106
+ */
107
+ function withoutFormatOptions(config) {
108
+ return Object.fromEntries(Object.entries(config).filter(([key]) => !key.startsWith("format") && !key.startsWith("output") && key !== "useTweegoPath" && key !== "noRemote"));
109
+ }
110
+ /**
111
+ * `text` as a glob matching only itself, for Node's `path.matchesGlob` (which
112
+ * twee-ts uses): a metacharacter goes in brackets. Braces and `!` cannot be
113
+ * bracketed there, so each becomes `?` (any one character).
114
+ */
115
+ function globLiteral(text) {
116
+ return text.replace(/[*?[\]()+@]/g, (c) => `[${c}]`).replace(/[{}!]/g, "?");
117
+ }
118
+ /** The compile sources and project config for a path (or glob). */
119
+ async function sourcesFor(tweeTs, path) {
120
+ let isDirectory = false;
121
+ try {
122
+ isDirectory = (await stat(path)).isDirectory();
123
+ } catch (err) {
124
+ if (!GLOB_CHARS.test(path)) throw new Error(`spindle: cannot read story ${path}: ${errorMessage(err)}`);
125
+ const sources = await expandGlob(path);
126
+ if (sources.length === 0) throw new Error(`spindle: no story files match ${path}`);
127
+ return {
128
+ sources,
129
+ config: {}
130
+ };
131
+ }
132
+ if (!isDirectory) return {
133
+ sources: [path],
134
+ config: {}
135
+ };
136
+ const found = tweeTs.loadConfig(path);
137
+ if (!found) return {
138
+ sources: [path],
139
+ config: {}
140
+ };
141
+ const config = rebaseConfig(resolve(path), found);
142
+ if (config.sources?.length === 0) throw new Error(`spindle: ${path} has a twee-ts config with no sources`);
143
+ return {
144
+ sources: config.sources ?? [],
145
+ config
146
+ };
147
+ }
148
+ /** The diagnostics a thrown twee-ts error carries, when it has any. */
149
+ function thrownDiagnostics(err) {
150
+ const diagnostics = err?.diagnostics;
151
+ return Array.isArray(diagnostics) ? diagnostics : [];
152
+ }
153
+ async function compileTwee(path, env) {
154
+ const tweeTs = await loadOptional("@rohal12/twee-ts", "compiling Twee", env.importer);
155
+ const { sources, config } = await sourcesFor(tweeTs, path);
156
+ let result;
157
+ try {
158
+ result = await tweeTs.compile({
159
+ ...withoutFormatOptions(config),
160
+ sources,
161
+ outputMode: "html",
162
+ formatPaths: [env.formatSearchDir],
163
+ formatId: FORMAT_FOLDER,
164
+ noRemote: true
165
+ });
166
+ } catch (err) {
167
+ const diagnostics = thrownDiagnostics(err);
168
+ throw diagnostics.length > 0 ? diagnosticsError(diagnostics, errorMessage(err)) : err;
169
+ }
170
+ if (result.diagnostics.some((d) => d.level === "error")) throw diagnosticsError(result.diagnostics, "spindle: Twee did not compile");
171
+ return result.output;
172
+ }
173
+ /** The `format-version` of the story's `<tw-storydata>`, if it has one. */
174
+ function storyFormatVersion(html) {
175
+ return /<tw-storydata\b[^>]*?\sformat-version="([^"]*)"/.exec(html)?.[1];
176
+ }
177
+ /** `resolveStoryHtml` with its environment passed in, for tests. */
178
+ async function resolveStoryHtmlWith(input, env) {
179
+ let html;
180
+ if ("html" in input) html = input.html;
181
+ else if (HTML_PATH.test(input.path)) try {
182
+ html = await readFile(input.path, "utf8");
183
+ } catch (err) {
184
+ throw new Error(`spindle: cannot read story ${input.path}: ${errorMessage(err)}`);
185
+ }
186
+ else html = await compileTwee(input.path, env);
187
+ const notes = [];
188
+ const compiledWith = storyFormatVersion(html);
189
+ if (compiledWith !== void 0 && compiledWith !== env.version) notes.push(`The story was compiled with Spindle ${compiledWith}; it runs on the installed Spindle ${env.version}.`);
190
+ return {
191
+ html,
192
+ notes
193
+ };
194
+ }
195
+ /**
196
+ * Turn a story into HTML: inline HTML as given, an `.html` path read, and
197
+ * anything else (a `.twee` file, a glob or a project directory) compiled with
198
+ * the installed Spindle format.
199
+ */
200
+ async function resolveStoryHtml(input) {
201
+ const { version } = JSON.parse(await readFile(new URL(
202
+ /* @vite-ignore */
203
+ "../../package.json",
204
+ import.meta.url
205
+ ), "utf8"));
206
+ return resolveStoryHtmlWith(input, {
207
+ formatSearchDir: fileURLToPath(new URL(
208
+ /* @vite-ignore */
209
+ "..",
210
+ import.meta.url
211
+ )),
212
+ version
213
+ });
214
+ }
215
+ //#endregion
216
+ //#region src/play/session.ts
217
+ /**
218
+ * The main-thread handle of a play session. The story runs in its own worker
219
+ * thread (see `protocol.ts`); this file queues calls so they run one at a
220
+ * time, times them out, and closes the session when the worker dies.
221
+ */
222
+ var DEFAULT_STEP_TIMEOUT_MS = 1e4;
223
+ /** The largest delay setTimeout accepts. */
224
+ var MAX_TIMEOUT_MS = 2147483647;
225
+ var CLOSED_MESSAGE = "spindle: play session is closed";
226
+ /**
227
+ * The host's Node flags for the worker, less `--input-type` (as
228
+ * `--input-type=<type>` or `--input-type <type>`): it only applies to `-e`
229
+ * and stdin, and a worker started with it fails.
230
+ */
231
+ function workerExecArgv(execArgv) {
232
+ const kept = [];
233
+ for (let i = 0; i < execArgv.length; i++) {
234
+ const arg = execArgv[i];
235
+ if (arg === "--input-type") i++;
236
+ else if (!arg.startsWith("--input-type=")) kept.push(arg);
237
+ }
238
+ return kept;
239
+ }
240
+ /**
241
+ * Opens a session that runs the story in a worker. There `window` is
242
+ * happy-dom's window, not `globalThis`: story code sees `Story` and the DOM
243
+ * globals, but `window.foo = 1` does not make a bare global `foo`.
244
+ */
245
+ function openPlaySession(options) {
246
+ return openPlaySessionWith(options, {
247
+ workerUrl: new URL(
248
+ /* @vite-ignore */
249
+ "./play-worker.js",
250
+ import.meta.url
251
+ ),
252
+ headlessUrl: new URL(
253
+ /* @vite-ignore */
254
+ "./headless.js",
255
+ import.meta.url
256
+ )
257
+ });
258
+ }
259
+ /** Internal: `openPlaySession` with the worker and headless URLs given (for tests). */
260
+ function openPlaySessionWith(options, urls) {
261
+ const stepTimeoutMs = options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS;
262
+ if (typeof stepTimeoutMs !== "number" || !Number.isFinite(stepTimeoutMs) || stepTimeoutMs <= 0 || stepTimeoutMs > MAX_TIMEOUT_MS) return Promise.reject(/* @__PURE__ */ new Error(`spindle: openPlaySession(): "stepTimeoutMs" must be a positive number of milliseconds, got ${String(stepTimeoutMs)}`));
263
+ const timeoutMessage = `spindle: play session timed out after ${stepTimeoutMs} ms (the story may be stuck in a loop)`;
264
+ const workerData = {
265
+ html: options.html,
266
+ headlessUrl: urls.headlessUrl.href,
267
+ transcript: options.transcript ?? { limit: 10 },
268
+ transitions: options.transitions ?? false
269
+ };
270
+ return new Promise((resolveOpen, rejectOpen) => {
271
+ const worker = new Worker(urls.workerUrl, {
272
+ workerData,
273
+ execArgv: workerExecArgv(process.execArgv)
274
+ });
275
+ let booted = false;
276
+ let closed = false;
277
+ let nextId = 1;
278
+ let active = null;
279
+ const queue = [];
280
+ let terminated = null;
281
+ const terminate = () => {
282
+ terminated ??= worker.terminate().then(() => void 0, () => void 0);
283
+ return terminated;
284
+ };
285
+ const bootTimer = setTimeout(() => {
286
+ rejectOpen(new Error(timeoutMessage));
287
+ terminate();
288
+ }, stepTimeoutMs);
289
+ /** Marks the session closed and settles everything still pending. */
290
+ const shutdown = (runningError, queuedError) => {
291
+ if (closed) return;
292
+ closed = true;
293
+ const running = active;
294
+ active = null;
295
+ if (running) {
296
+ clearTimeout(running.timer);
297
+ running.job.reject(runningError);
298
+ }
299
+ for (const job of queue.splice(0)) job.reject(queuedError);
300
+ };
301
+ const pump = () => {
302
+ if (closed || active) return;
303
+ const job = queue.shift();
304
+ if (!job) return;
305
+ const id = nextId++;
306
+ const request = {
307
+ id,
308
+ op: job.op,
309
+ args: job.args
310
+ };
311
+ try {
312
+ worker.postMessage(request);
313
+ } catch (err) {
314
+ job.reject(new Error(errorMessage(err)));
315
+ pump();
316
+ return;
317
+ }
318
+ active = {
319
+ id,
320
+ job,
321
+ timer: setTimeout(() => {
322
+ const timeout = new Error(timeoutMessage);
323
+ shutdown(timeout, /* @__PURE__ */ new Error(CLOSED_MESSAGE));
324
+ terminate();
325
+ }, stepTimeoutMs)
326
+ };
327
+ };
328
+ const call = (op, args) => new Promise((resolve, reject) => {
329
+ if (closed) {
330
+ reject(/* @__PURE__ */ new Error(CLOSED_MESSAGE));
331
+ return;
332
+ }
333
+ queue.push({
334
+ op,
335
+ args,
336
+ resolve,
337
+ reject
338
+ });
339
+ pump();
340
+ });
341
+ const session = {
342
+ observe: () => call("observe", []),
343
+ step: (id, value) => call("step", value === void 0 ? [id] : [id, value]),
344
+ goto: (passage) => call("goto", [passage]),
345
+ get: (names) => call("get", names === void 0 ? [] : [names]),
346
+ set: (values) => call("set", [values]),
347
+ transcript: () => call("transcript", []),
348
+ async close() {
349
+ const closedError = /* @__PURE__ */ new Error(CLOSED_MESSAGE);
350
+ shutdown(closedError, closedError);
351
+ await terminate();
352
+ },
353
+ get closed() {
354
+ return closed;
355
+ }
356
+ };
357
+ const failWorker = (message) => {
358
+ if (!booted) {
359
+ clearTimeout(bootTimer);
360
+ rejectOpen(new Error(message));
361
+ terminate();
362
+ return;
363
+ }
364
+ const error = new Error(message);
365
+ shutdown(error, error);
366
+ terminate();
367
+ };
368
+ worker.on("message", (message) => {
369
+ if ("ready" in message) {
370
+ if (booted) return;
371
+ clearTimeout(bootTimer);
372
+ if (message.ready) {
373
+ booted = true;
374
+ resolveOpen(session);
375
+ } else {
376
+ rejectOpen(new Error(message.error.message));
377
+ terminate();
378
+ }
379
+ return;
380
+ }
381
+ if (!active || active.id !== message.id) return;
382
+ const { job, timer } = active;
383
+ active = null;
384
+ clearTimeout(timer);
385
+ if (message.ok) job.resolve(message.result);
386
+ else job.reject(new Error(message.error.message));
387
+ pump();
388
+ });
389
+ worker.on("error", (err) => failWorker(errorMessage(err)));
390
+ worker.on("exit", (code) => {
391
+ if (closed) return;
392
+ failWorker(`spindle: play session worker exited with code ${code}`);
393
+ });
394
+ worker.unref();
395
+ });
396
+ }
397
+ //#endregion
398
+ export { openPlaySession, resolveStoryHtml };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.60.4",
3
+ "version": "0.61.1",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -36,6 +36,10 @@
36
36
  "./headless": {
37
37
  "types": "./types/headless.d.ts",
38
38
  "import": "./dist/pkg/headless.js"
39
+ },
40
+ "./play": {
41
+ "types": "./types/play.d.ts",
42
+ "import": "./dist/pkg/play.js"
39
43
  }
40
44
  },
41
45
  "files": [
@@ -43,6 +47,8 @@
43
47
  "dist/pkg/format.js",
44
48
  "dist/pkg/tooling.js",
45
49
  "dist/pkg/headless.js",
50
+ "dist/pkg/play.js",
51
+ "dist/pkg/play-worker.js",
46
52
  "dist/pkg/story-variables.js",
47
53
  "dist/pkg/macro-registry.json",
48
54
  "dist/pkg/macro-registry.js",
@@ -77,6 +83,18 @@
77
83
  "preact": "^11.0.1",
78
84
  "zustand": "^5.0.15"
79
85
  },
86
+ "peerDependencies": {
87
+ "@rohal12/twee-ts": "^1.18.2",
88
+ "happy-dom": ">=20.14.6"
89
+ },
90
+ "peerDependenciesMeta": {
91
+ "@rohal12/twee-ts": {
92
+ "optional": true
93
+ },
94
+ "happy-dom": {
95
+ "optional": true
96
+ }
97
+ },
80
98
  "lint-staged": {
81
99
  "*": "prettier --write --ignore-unknown"
82
100
  },
@@ -92,7 +110,7 @@
92
110
  "fake-indexeddb": "^6.2.5",
93
111
  "fallow": "3.33.1",
94
112
  "fast-check": "^4.10.2",
95
- "happy-dom": "^20.14.6",
113
+ "happy-dom": "^21.0.3",
96
114
  "husky": "^9.1.7",
97
115
  "js-yaml": "^5.4.3",
98
116
  "jscpd": "5.4.1",