@rohal12/spindle 0.60.3 → 0.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +1 -1
  2. package/dist/pkg/format.js +1 -1
  3. package/dist/pkg/headless.js +18671 -18510
  4. package/dist/pkg/play-worker.js +181 -0
  5. package/dist/pkg/play.js +398 -0
  6. package/dist/pkg/story-variables.js +11016 -153
  7. package/package.json +19 -1
  8. package/src/action-registry.ts +43 -3
  9. package/src/components/PassageDialog.tsx +29 -27
  10. package/src/components/dialog-close-context.ts +5 -1
  11. package/src/components/macros/Button.tsx +3 -3
  12. package/src/components/macros/Checkbox.tsx +3 -2
  13. package/src/components/macros/Cycle.tsx +3 -4
  14. package/src/components/macros/Dialog.tsx +3 -3
  15. package/src/components/macros/Listbox.tsx +3 -4
  16. package/src/components/macros/MacroLink.tsx +3 -3
  17. package/src/components/macros/MenubarButtons.tsx +3 -3
  18. package/src/components/macros/PassageDisplay.tsx +14 -9
  19. package/src/components/macros/Radiobutton.tsx +3 -2
  20. package/src/components/macros/detached-body.tsx +1 -4
  21. package/src/components/macros/input-macro.ts +10 -8
  22. package/src/define-macro.ts +0 -4
  23. package/src/execute-mutation.ts +10 -6
  24. package/src/format/fenced-code.ts +59 -0
  25. package/src/format/format-passage.ts +100 -11
  26. package/src/headless.ts +25 -1
  27. package/src/hooks/use-action.ts +44 -4
  28. package/src/hooks/use-modal-focus.ts +1 -30
  29. package/src/markup/ast.ts +4 -3
  30. package/src/markup/pair.ts +22 -9
  31. package/src/markup/parse.ts +2 -0
  32. package/src/markup/validate.ts +5 -3
  33. package/src/observe/observable-text.ts +6 -24
  34. package/src/observe/observe.ts +4 -1
  35. package/src/play/index.ts +15 -0
  36. package/src/play/optional.ts +41 -0
  37. package/src/play/protocol.ts +35 -0
  38. package/src/play/resolve-story.ts +265 -0
  39. package/src/play/session.ts +253 -0
  40. package/src/play/worker.ts +169 -0
  41. package/src/registry.ts +36 -1
  42. package/src/runtime-errors.ts +5 -0
  43. package/src/saves/save-manager.ts +48 -7
  44. package/src/saves/storage.ts +3 -1
  45. package/src/saves/types.ts +1 -0
  46. package/src/store.ts +13 -6
  47. package/src/story-init.ts +6 -1
  48. package/src/structural.ts +126 -66
  49. package/src/tooling.ts +2 -0
  50. package/src/types-drift-check.ts +55 -0
  51. package/src/utils/element-visibility.ts +61 -0
  52. package/types/headless.d.ts +14 -0
  53. package/types/index.d.ts +2 -0
  54. package/types/play.d.ts +83 -0
  55. package/types/tooling.d.ts +2 -0
@@ -0,0 +1,265 @@
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 type * as TweeTs from '@rohal12/twee-ts';
5
+ import { errorMessage } from '../utils/error-message';
6
+ import { loadOptional, type Importer } from './optional';
7
+
8
+ /** A story to play: compiled HTML, or a path to HTML, Twee or a project. */
9
+ export type StoryInput = { html: string } | { path: string };
10
+
11
+ export interface ResolvedStory {
12
+ html: string;
13
+ /** Things worth telling the caller; never errors. */
14
+ notes: string[];
15
+ }
16
+
17
+ interface ResolveEnv {
18
+ /** Where twee-ts looks for the Spindle format (its subfolders). */
19
+ formatSearchDir: string;
20
+ /** The installed Spindle version. */
21
+ version: string;
22
+ importer?: Importer;
23
+ }
24
+
25
+ type TweeTsModule = typeof TweeTs;
26
+
27
+ /**
28
+ * twee-ts takes a format ID to be the name of the folder holding format.js,
29
+ * not the name inside it. The package keeps its format in `dist/pkg/`, and
30
+ * `formatSearchDir` is `dist/`.
31
+ */
32
+ const FORMAT_FOLDER = 'pkg';
33
+ const HTML_PATH = /\.html?$/i;
34
+ const GLOB_CHARS = /[*?[\]{}]/;
35
+
36
+ /** `file:line: message` per error; just the message without a location. */
37
+ function formatDiagnostic(d: {
38
+ message: string;
39
+ file?: string;
40
+ line?: number;
41
+ }): string {
42
+ return d.file !== undefined && d.line !== undefined
43
+ ? `${d.file}:${d.line}: ${d.message}`
44
+ : d.message;
45
+ }
46
+
47
+ function diagnosticsError(
48
+ diagnostics: readonly TweeTs.Diagnostic[],
49
+ fallback: string,
50
+ ): Error {
51
+ const errors = diagnostics.filter((d) => d.level === 'error');
52
+ return new Error(
53
+ errors.length > 0 ? errors.map(formatDiagnostic).join('\n') : fallback,
54
+ );
55
+ }
56
+
57
+ /** The files a glob pattern matches, sorted. */
58
+ async function expandGlob(pattern: string): Promise<string[]> {
59
+ const matches: string[] = [];
60
+ for await (const file of glob(pattern)) matches.push(file);
61
+ return matches.sort();
62
+ }
63
+
64
+ /** A path segment with glob syntax in it (as `path.matchesGlob` reads it). */
65
+ const GLOB_SEGMENT = /[*?[\]{}()!+@]/;
66
+
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: string, pattern: string): string {
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(
84
+ relative(process.cwd(), base).split(sep).join('/'),
85
+ );
86
+ if (fromCwd === '') return rest;
87
+ return rest === '' ? fromCwd : `${fromCwd}/${rest}`;
88
+ }
89
+
90
+ /**
91
+ * The project config with its paths made independent of the working
92
+ * directory. twee-ts reads `sources`, `modules` and `headFile` relative to
93
+ * the working directory, and matches `exclude` globs against paths relative
94
+ * to it, so each is rebased from the project directory.
95
+ */
96
+ function rebaseConfig(
97
+ dir: string,
98
+ config: TweeTs.TweeTsConfig,
99
+ ): TweeTs.TweeTsConfig {
100
+ const rebased: TweeTs.TweeTsConfig = {
101
+ ...config,
102
+ sources: (config.sources ?? ['.']).map((s) => resolve(dir, s)),
103
+ };
104
+ if (config.modules)
105
+ rebased.modules = config.modules.map((m) => resolve(dir, m));
106
+ if (config.headFile !== undefined) {
107
+ rebased.headFile = resolve(dir, config.headFile);
108
+ }
109
+ if (config.exclude) {
110
+ rebased.exclude = config.exclude.map((e) => rebaseExclude(dir, e));
111
+ }
112
+ return rebased;
113
+ }
114
+
115
+ /**
116
+ * The project config less its output and format options. Those are ours: the
117
+ * project's own would write a file, compile for another format, or fetch one.
118
+ */
119
+ function withoutFormatOptions(
120
+ config: TweeTs.TweeTsConfig,
121
+ ): Partial<TweeTs.CompileOptions> {
122
+ return Object.fromEntries(
123
+ Object.entries(config).filter(
124
+ ([key]) =>
125
+ !key.startsWith('format') &&
126
+ !key.startsWith('output') &&
127
+ key !== 'useTweegoPath' &&
128
+ key !== 'noRemote',
129
+ ),
130
+ );
131
+ }
132
+
133
+ /**
134
+ * `text` as a glob matching only itself, for Node's `path.matchesGlob` (which
135
+ * twee-ts uses): a metacharacter goes in brackets. Braces and `!` cannot be
136
+ * bracketed there, so each becomes `?` (any one character).
137
+ */
138
+ function globLiteral(text: string): string {
139
+ return text.replace(/[*?[\]()+@]/g, (c) => `[${c}]`).replace(/[{}!]/g, '?');
140
+ }
141
+
142
+ /** The compile sources and project config for a path (or glob). */
143
+ async function sourcesFor(
144
+ tweeTs: TweeTsModule,
145
+ path: string,
146
+ ): Promise<{ sources: string[]; config: TweeTs.TweeTsConfig }> {
147
+ let isDirectory = false;
148
+ try {
149
+ isDirectory = (await stat(path)).isDirectory();
150
+ } catch (err) {
151
+ if (!GLOB_CHARS.test(path)) {
152
+ throw new Error(
153
+ `spindle: cannot read story ${path}: ${errorMessage(err)}`,
154
+ );
155
+ }
156
+ // twee-ts does not expand globs.
157
+ const sources = await expandGlob(path);
158
+ if (sources.length === 0) {
159
+ throw new Error(`spindle: no story files match ${path}`);
160
+ }
161
+ return { sources, config: {} };
162
+ }
163
+ if (!isDirectory) return { sources: [path], config: {} };
164
+ const found = tweeTs.loadConfig(path);
165
+ if (!found) return { sources: [path], config: {} };
166
+ const config = rebaseConfig(resolve(path), found);
167
+ if (config.sources?.length === 0) {
168
+ throw new Error(`spindle: ${path} has a twee-ts config with no sources`);
169
+ }
170
+ return { sources: config.sources ?? [], config };
171
+ }
172
+
173
+ /** The diagnostics a thrown twee-ts error carries, when it has any. */
174
+ function thrownDiagnostics(err: unknown): TweeTs.Diagnostic[] {
175
+ const diagnostics = (err as { diagnostics?: unknown } | null)?.diagnostics;
176
+ return Array.isArray(diagnostics) ? diagnostics : [];
177
+ }
178
+
179
+ async function compileTwee(path: string, env: ResolveEnv): Promise<string> {
180
+ const tweeTs = await loadOptional<TweeTsModule>(
181
+ '@rohal12/twee-ts',
182
+ 'compiling Twee',
183
+ env.importer,
184
+ );
185
+ const { sources, config } = await sourcesFor(tweeTs, path);
186
+ let result: TweeTs.CompileResult;
187
+ try {
188
+ result = await tweeTs.compile({
189
+ ...withoutFormatOptions(config),
190
+ sources,
191
+ outputMode: 'html',
192
+ formatPaths: [env.formatSearchDir],
193
+ formatId: FORMAT_FOLDER,
194
+ noRemote: true,
195
+ });
196
+ } catch (err) {
197
+ // A fatal compile error is thrown with its diagnostics.
198
+ const diagnostics = thrownDiagnostics(err);
199
+ throw diagnostics.length > 0
200
+ ? diagnosticsError(diagnostics, errorMessage(err))
201
+ : err;
202
+ }
203
+ if (result.diagnostics.some((d) => d.level === 'error')) {
204
+ throw diagnosticsError(result.diagnostics, 'spindle: Twee did not compile');
205
+ }
206
+ return result.output;
207
+ }
208
+
209
+ /** The `format-version` of the story's `<tw-storydata>`, if it has one. */
210
+ function storyFormatVersion(html: string): string | undefined {
211
+ return /<tw-storydata\b[^>]*?\sformat-version="([^"]*)"/.exec(html)?.[1];
212
+ }
213
+
214
+ /** `resolveStoryHtml` with its environment passed in, for tests. */
215
+ export async function resolveStoryHtmlWith(
216
+ input: StoryInput,
217
+ env: ResolveEnv,
218
+ ): Promise<ResolvedStory> {
219
+ let html: string;
220
+ if ('html' in input) {
221
+ html = input.html;
222
+ } else if (HTML_PATH.test(input.path)) {
223
+ try {
224
+ html = await readFile(input.path, 'utf8');
225
+ } catch (err) {
226
+ throw new Error(
227
+ `spindle: cannot read story ${input.path}: ${errorMessage(err)}`,
228
+ );
229
+ }
230
+ } else {
231
+ html = await compileTwee(input.path, env);
232
+ }
233
+ const notes: string[] = [];
234
+ const compiledWith = storyFormatVersion(html);
235
+ if (compiledWith !== undefined && compiledWith !== env.version) {
236
+ notes.push(
237
+ `The story was compiled with Spindle ${compiledWith}; it runs on the installed Spindle ${env.version}.`,
238
+ );
239
+ }
240
+ return { html, notes };
241
+ }
242
+
243
+ /**
244
+ * Turn a story into HTML: inline HTML as given, an `.html` path read, and
245
+ * anything else (a `.twee` file, a glob or a project directory) compiled with
246
+ * the installed Spindle format.
247
+ */
248
+ export async function resolveStoryHtml(
249
+ input: StoryInput,
250
+ ): Promise<ResolvedStory> {
251
+ // Relative to dist/pkg/play.js at runtime; @vite-ignore keeps the build
252
+ // from inlining the files these URLs name.
253
+ const { version } = JSON.parse(
254
+ await readFile(
255
+ new URL(/* @vite-ignore */ '../../package.json', import.meta.url),
256
+ 'utf8',
257
+ ),
258
+ ) as { version: string };
259
+ return resolveStoryHtmlWith(input, {
260
+ formatSearchDir: fileURLToPath(
261
+ new URL(/* @vite-ignore */ '..', import.meta.url),
262
+ ),
263
+ version,
264
+ });
265
+ }
@@ -0,0 +1,253 @@
1
+ /**
2
+ * The main-thread handle of a play session. The story runs in its own worker
3
+ * thread (see `protocol.ts`); this file queues calls so they run one at a
4
+ * time, times them out, and closes the session when the worker dies.
5
+ */
6
+ import { Worker } from 'node:worker_threads';
7
+ import type { TranscriptEntry, TranscriptOptions } from '../headless';
8
+ import type { Observation } from '../observe/observe';
9
+ import { errorMessage } from '../utils/error-message';
10
+ import type { Op, Request, WorkerData, WorkerMessage } from './protocol';
11
+
12
+ export interface PlaySessionOptions {
13
+ html: string;
14
+ /** Per call. Default 10_000. */
15
+ stepTimeoutMs?: number;
16
+ /** Passed to createTranscript() inside the worker. Default { limit: 10 }. */
17
+ transcript?: TranscriptOptions;
18
+ /** Keep passage transitions (bootStory's option). Default false. */
19
+ transitions?: boolean;
20
+ }
21
+
22
+ export interface PlaySession {
23
+ observe(): Promise<Observation>;
24
+ /** Goes through the transcript, so the step is recorded. */
25
+ step(id: string, value?: unknown): Promise<Observation>;
26
+ /**
27
+ * Story.goto(), then waitForActions(), then observe(). Not recorded in the
28
+ * transcript. Rejects for a passage the story does not have, or a special
29
+ * passage (StoryInit, ...).
30
+ */
31
+ goto(passage: string): Promise<Observation>;
32
+ /**
33
+ * Story variables, by name with or without `$`. All of them when `names` is
34
+ * left out. Values are structured clones; one that cannot be cloned is
35
+ * `"[unserializable: <reason>]"`.
36
+ */
37
+ get(names?: string[]): Promise<Record<string, unknown>>;
38
+ /** Story.set(), then waitForActions(). */
39
+ set(values: Record<string, unknown>): Promise<void>;
40
+ transcript(): Promise<TranscriptEntry[]>;
41
+ close(): Promise<void>;
42
+ readonly closed: boolean;
43
+ }
44
+
45
+ const DEFAULT_STEP_TIMEOUT_MS = 10_000;
46
+ /** The largest delay setTimeout accepts. */
47
+ const MAX_TIMEOUT_MS = 2_147_483_647;
48
+ const CLOSED_MESSAGE = 'spindle: play session is closed';
49
+
50
+ interface Job {
51
+ op: Op;
52
+ args: unknown[];
53
+ resolve(result: unknown): void;
54
+ reject(error: Error): void;
55
+ }
56
+
57
+ /**
58
+ * The host's Node flags for the worker, less `--input-type` (as
59
+ * `--input-type=<type>` or `--input-type <type>`): it only applies to `-e`
60
+ * and stdin, and a worker started with it fails.
61
+ */
62
+ export function workerExecArgv(execArgv: readonly string[]): string[] {
63
+ const kept: string[] = [];
64
+ for (let i = 0; i < execArgv.length; i++) {
65
+ const arg = execArgv[i]!;
66
+ if (arg === '--input-type') i++;
67
+ else if (!arg.startsWith('--input-type=')) kept.push(arg);
68
+ }
69
+ return kept;
70
+ }
71
+
72
+ /**
73
+ * Opens a session that runs the story in a worker. There `window` is
74
+ * happy-dom's window, not `globalThis`: story code sees `Story` and the DOM
75
+ * globals, but `window.foo = 1` does not make a bare global `foo`.
76
+ */
77
+ export function openPlaySession(
78
+ options: PlaySessionOptions,
79
+ ): Promise<PlaySession> {
80
+ // Resolved at runtime next to dist/pkg/play.js; @vite-ignore keeps the
81
+ // build from inlining or rewriting them.
82
+ return openPlaySessionWith(options, {
83
+ workerUrl: new URL(/* @vite-ignore */ './play-worker.js', import.meta.url),
84
+ headlessUrl: new URL(/* @vite-ignore */ './headless.js', import.meta.url),
85
+ });
86
+ }
87
+
88
+ /** Internal: `openPlaySession` with the worker and headless URLs given (for tests). */
89
+ export function openPlaySessionWith(
90
+ options: PlaySessionOptions,
91
+ urls: { workerUrl: URL; headlessUrl: URL },
92
+ ): Promise<PlaySession> {
93
+ const stepTimeoutMs = options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS;
94
+ if (
95
+ typeof stepTimeoutMs !== 'number' ||
96
+ !Number.isFinite(stepTimeoutMs) ||
97
+ stepTimeoutMs <= 0 ||
98
+ stepTimeoutMs > MAX_TIMEOUT_MS
99
+ ) {
100
+ return Promise.reject(
101
+ new Error(
102
+ `spindle: openPlaySession(): "stepTimeoutMs" must be a positive number of milliseconds, got ${String(stepTimeoutMs)}`,
103
+ ),
104
+ );
105
+ }
106
+ const timeoutMessage = `spindle: play session timed out after ${stepTimeoutMs} ms (the story may be stuck in a loop)`;
107
+ const workerData: WorkerData = {
108
+ html: options.html,
109
+ headlessUrl: urls.headlessUrl.href,
110
+ transcript: options.transcript ?? { limit: 10 },
111
+ transitions: options.transitions ?? false,
112
+ };
113
+
114
+ return new Promise<PlaySession>((resolveOpen, rejectOpen) => {
115
+ const worker = new Worker(urls.workerUrl, {
116
+ workerData,
117
+ execArgv: workerExecArgv(process.execArgv),
118
+ });
119
+ let booted = false;
120
+ let closed = false;
121
+ let nextId = 1;
122
+ let active: { id: number; job: Job; timer: NodeJS.Timeout } | null = null;
123
+ const queue: Job[] = [];
124
+ let terminated: Promise<void> | null = null;
125
+
126
+ const terminate = (): Promise<void> => {
127
+ terminated ??= worker.terminate().then(
128
+ () => undefined,
129
+ () => undefined,
130
+ );
131
+ return terminated;
132
+ };
133
+
134
+ // Booting is bounded by the same timeout (a StoryInit can loop forever).
135
+ const bootTimer = setTimeout(() => {
136
+ rejectOpen(new Error(timeoutMessage));
137
+ void terminate();
138
+ }, stepTimeoutMs);
139
+
140
+ /** Marks the session closed and settles everything still pending. */
141
+ const shutdown = (runningError: Error, queuedError: Error): void => {
142
+ if (closed) return;
143
+ closed = true;
144
+ const running = active;
145
+ active = null;
146
+ if (running) {
147
+ clearTimeout(running.timer);
148
+ running.job.reject(runningError);
149
+ }
150
+ for (const job of queue.splice(0)) job.reject(queuedError);
151
+ };
152
+
153
+ const pump = (): void => {
154
+ if (closed || active) return;
155
+ const job = queue.shift();
156
+ if (!job) return;
157
+ const id = nextId++;
158
+ const request: Request = { id, op: job.op, args: job.args };
159
+ try {
160
+ worker.postMessage(request);
161
+ } catch (err) {
162
+ // The arguments could not be cloned: only this call fails.
163
+ job.reject(new Error(errorMessage(err)));
164
+ pump();
165
+ return;
166
+ }
167
+ const timer = setTimeout(() => {
168
+ const timeout = new Error(timeoutMessage);
169
+ shutdown(timeout, new Error(CLOSED_MESSAGE));
170
+ void terminate();
171
+ }, stepTimeoutMs);
172
+ active = { id, job, timer };
173
+ };
174
+
175
+ const call = <T>(op: Op, args: unknown[]): Promise<T> =>
176
+ new Promise<T>((resolve, reject) => {
177
+ if (closed) {
178
+ reject(new Error(CLOSED_MESSAGE));
179
+ return;
180
+ }
181
+ queue.push({ op, args, resolve: resolve as Job['resolve'], reject });
182
+ pump();
183
+ });
184
+
185
+ const session: PlaySession = {
186
+ observe: () => call<Observation>('observe', []),
187
+ step: (id, value) =>
188
+ call<Observation>('step', value === undefined ? [id] : [id, value]),
189
+ goto: (passage) => call<Observation>('goto', [passage]),
190
+ get: (names) =>
191
+ call<Record<string, unknown>>(
192
+ 'get',
193
+ names === undefined ? [] : [names],
194
+ ),
195
+ set: (values) => call<void>('set', [values]),
196
+ transcript: () => call<TranscriptEntry[]>('transcript', []),
197
+ async close() {
198
+ const closedError = new Error(CLOSED_MESSAGE);
199
+ shutdown(closedError, closedError);
200
+ await terminate();
201
+ },
202
+ get closed() {
203
+ return closed;
204
+ },
205
+ };
206
+
207
+ const failWorker = (message: string): void => {
208
+ if (!booted) {
209
+ clearTimeout(bootTimer);
210
+ rejectOpen(new Error(message));
211
+ void terminate();
212
+ return;
213
+ }
214
+ const error = new Error(message);
215
+ shutdown(error, error);
216
+ void terminate();
217
+ };
218
+
219
+ worker.on('message', (message: WorkerMessage) => {
220
+ if ('ready' in message) {
221
+ if (booted) return;
222
+ clearTimeout(bootTimer);
223
+ if (message.ready) {
224
+ booted = true;
225
+ resolveOpen(session);
226
+ } else {
227
+ rejectOpen(new Error(message.error.message));
228
+ void terminate();
229
+ }
230
+ return;
231
+ }
232
+ if (!active || active.id !== message.id) return;
233
+ const { job, timer } = active;
234
+ active = null;
235
+ clearTimeout(timer);
236
+ if (message.ok) job.resolve(message.result);
237
+ else job.reject(new Error(message.error.message));
238
+ pump();
239
+ });
240
+ worker.on('error', (err) => failWorker(errorMessage(err)));
241
+ worker.on('exit', (code) => {
242
+ // After a close or a timeout the exit is expected.
243
+ if (closed) return;
244
+ failWorker(`spindle: play session worker exited with code ${code}`);
245
+ });
246
+ // A session that is never closed does not keep Node running on its own
247
+ // (a call in progress still does, through its timer). After the
248
+ // listeners: adding a 'message' listener refs the worker again. The
249
+ // worker sends its stdout to stderr itself, because reading
250
+ // `worker.stdout` here would also keep Node running.
251
+ worker.unref();
252
+ });
253
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * The worker thread of a play session: boots the story on happy-dom and
3
+ * answers the session handle's calls (see `protocol.ts`). Built to
4
+ * `dist/pkg/play-worker.js`.
5
+ */
6
+ import { parentPort, workerData } from 'node:worker_threads';
7
+ import type * as HappyDom from 'happy-dom';
8
+ import type * as Headless from '../headless';
9
+ import { errorMessage } from '../utils/error-message';
10
+ import { loadOptional } from './optional';
11
+ import type { Op, Ready, Reply, Request, WorkerData } from './protocol';
12
+
13
+ type HeadlessModule = typeof Headless;
14
+
15
+ // Story output (`console.log` in a {do}) goes to stderr: a host speaking a
16
+ // protocol on stdout (an MCP server over stdio) must not receive it.
17
+ const stderr = process.stderr;
18
+ Object.defineProperty(process, 'stdout', {
19
+ configurable: true,
20
+ get: () => stderr,
21
+ });
22
+
23
+ const port = parentPort!;
24
+ const data = workerData as WorkerData;
25
+
26
+ /** Make happy-dom's window the global environment Spindle runs in. */
27
+ async function installDom(): Promise<void> {
28
+ const { Window } = await loadOptional<typeof HappyDom>(
29
+ 'happy-dom',
30
+ 'play sessions',
31
+ );
32
+ const window = new Window({ url: 'http://localhost/' });
33
+ const global = globalThis as Record<string, unknown>;
34
+ const source = window as unknown as Record<string, unknown>;
35
+ global.window = window;
36
+ global.document = window.document;
37
+ // Node's own globals (fetch, URL, ...) stay as they are,
38
+ for (const name of Object.getOwnPropertyNames(window)) {
39
+ if (!(name in globalThis)) global[name] = source[name];
40
+ }
41
+ // except those the story must get from happy-dom.
42
+ for (const name of HAPPY_DOM_GLOBALS) {
43
+ Object.defineProperty(globalThis, name, {
44
+ configurable: true,
45
+ writable: true,
46
+ value: source[name],
47
+ });
48
+ }
49
+ // Node's BroadcastChannel reaches every worker thread in the process, so
50
+ // sessions would hear each other's save-slot notices. Spindle works without
51
+ // one (it falls back when the constructor is missing).
52
+ Object.defineProperty(globalThis, 'BroadcastChannel', {
53
+ configurable: true,
54
+ writable: true,
55
+ value: undefined,
56
+ });
57
+ // Spindle installs `window.Story`; story code ({do}, Story JavaScript)
58
+ // names it as a global, as it can in a browser.
59
+ Object.defineProperty(globalThis, 'Story', {
60
+ configurable: true,
61
+ get: () => source.Story,
62
+ });
63
+ }
64
+
65
+ /**
66
+ * Globals happy-dom's window replaces even where Node has its own:
67
+ * - the event classes: happy-dom's dispatchEvent() refuses events made with
68
+ * Node's (`new CustomEvent(':storyready')` at boot);
69
+ * - the storages: Node 25+ has a `localStorage` that is undefined without
70
+ * `--localstorage-file`, and Node's would be shared by every session;
71
+ * - `navigator`: Node's `navigator.locks` is shared by every worker in the
72
+ * process.
73
+ */
74
+ const HAPPY_DOM_GLOBALS = [
75
+ 'Event',
76
+ 'CustomEvent',
77
+ 'EventTarget',
78
+ 'localStorage',
79
+ 'sessionStorage',
80
+ 'navigator',
81
+ ] as const;
82
+
83
+ /**
84
+ * A value as the reply will carry it (structured clone keeps Map, Set, Date
85
+ * and cycles), or a marker when it cannot be cloned (a function, a Map
86
+ * holding one).
87
+ */
88
+ function encode(value: unknown): unknown {
89
+ try {
90
+ return structuredClone(value);
91
+ } catch (err) {
92
+ return `[unserializable: ${errorMessage(err)}]`;
93
+ }
94
+ }
95
+
96
+ function encodeAll(values: Record<string, unknown>): Record<string, unknown> {
97
+ const out: Record<string, unknown> = {};
98
+ for (const [name, value] of Object.entries(values)) out[name] = encode(value);
99
+ return out;
100
+ }
101
+
102
+ async function start(): Promise<void> {
103
+ await installDom();
104
+ const headless = (await import(
105
+ /* @vite-ignore */ data.headlessUrl
106
+ )) as HeadlessModule;
107
+ const story = await headless.bootStory({
108
+ html: data.html,
109
+ transitions: data.transitions,
110
+ });
111
+ const transcript = headless.createTranscript(story, data.transcript);
112
+
113
+ const ops: Record<Op, (args: unknown[]) => unknown> = {
114
+ observe: () => story.observe(),
115
+ step: ([id, value]) => transcript.step(id as string, value),
116
+ goto: async ([passage]) => {
117
+ const name = passage as string;
118
+ // Story.goto() reports a passage it won't go to and returns.
119
+ const refused = headless.gotoError(name);
120
+ if (refused !== null) throw new Error(`spindle: ${refused}`);
121
+ story.goto(name);
122
+ await story.waitForActions();
123
+ return story.observe();
124
+ },
125
+ get: ([names]) => {
126
+ if (names === undefined) return encodeAll(headless.storyVariables());
127
+ const values: Record<string, unknown> = {};
128
+ for (const name of names as string[]) {
129
+ const key = name.replace(/^\$/, '');
130
+ values[key] = story.get(key);
131
+ }
132
+ return encodeAll(values);
133
+ },
134
+ set: async ([values]) => {
135
+ // Story.set() takes names with or without the `$`.
136
+ story.set(values as Record<string, unknown>);
137
+ await story.waitForActions();
138
+ },
139
+ transcript: () => [...transcript.entries],
140
+ };
141
+
142
+ port.on('message', async ({ id, op, args }: Request) => {
143
+ let reply: Reply;
144
+ try {
145
+ reply = { id, ok: true, result: await ops[op](args) };
146
+ } catch (err) {
147
+ reply = { id, ok: false, error: { message: errorMessage(err) } };
148
+ }
149
+ try {
150
+ port.postMessage(reply);
151
+ } catch (err) {
152
+ // The result could not be cloned: report why instead of no reply.
153
+ port.postMessage({
154
+ id,
155
+ ok: false,
156
+ error: { message: errorMessage(err) },
157
+ } satisfies Reply);
158
+ }
159
+ });
160
+ port.postMessage({ ready: true } satisfies Ready);
161
+ }
162
+
163
+ start().catch((err: unknown) => {
164
+ port.postMessage({
165
+ ready: false,
166
+ error: { message: errorMessage(err) },
167
+ } satisfies Ready);
168
+ process.exit(1);
169
+ });