@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.
package/src/headless.ts CHANGED
@@ -8,7 +8,8 @@
8
8
  * same boot sequence directly.
9
9
  */
10
10
  import { boot } from './index';
11
- import { useStoryStore } from './store';
11
+ import { isSpecialPassage, useStoryStore } from './store';
12
+ import { noPassageError, specialPassageError } from './runtime-errors';
12
13
  import type { StoryAPI } from './story-api';
13
14
  import type { Observation } from './observe/observe';
14
15
 
@@ -85,6 +86,29 @@ export function bootStory(options: BootStoryOptions): Promise<StoryAPI> {
85
86
  });
86
87
  }
87
88
 
89
+ /**
90
+ * The story's `$` variables: a shallow copy of the current values, keyed by
91
+ * name without the `$`. Values are the store's own (frozen) objects.
92
+ */
93
+ export function storyVariables(): Record<string, unknown> {
94
+ return { ...useStoryStore.getState().variables };
95
+ }
96
+
97
+ /**
98
+ * Why `Story.goto(name)` would not navigate, or `null` if it would: `name` is
99
+ * a special passage (StoryInit, ...) or names no passage. The message is the
100
+ * one Spindle logs (and, for a missing passage, shows on the page), since
101
+ * `Story.goto()` reports these instead of throwing.
102
+ */
103
+ export function gotoError(name: string): string | null {
104
+ const { storyData, currentPassage } = useStoryStore.getState();
105
+ if (isSpecialPassage(name)) return specialPassageError(name).message;
106
+ if (!storyData?.passages.has(name)) {
107
+ return noPassageError(name, currentPassage).message;
108
+ }
109
+ return null;
110
+ }
111
+
88
112
  /** One recorded step: what the reader saw, and what they chose. */
89
113
  export interface TranscriptEntry {
90
114
  turn: number;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Node entry point (`@rohal12/spindle/play`): play a story from a script or a
3
+ * tool. A session runs the story in its own worker thread on happy-dom, so
4
+ * sessions are isolated and a story stuck in a loop can be stopped.
5
+ */
6
+ export { resolveStoryHtml } from './resolve-story';
7
+ export type { ResolvedStory, StoryInput } from './resolve-story';
8
+ export { openPlaySession } from './session';
9
+ export type { PlaySession, PlaySessionOptions } from './session';
10
+ export type {
11
+ Observation,
12
+ TranscriptEntry,
13
+ TranscriptOptions,
14
+ } from '../headless';
15
+ export type { ObservedAction } from '../observe/observe';
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Loading of the optional packages the play entry depends on. `happy-dom` and
3
+ * `@rohal12/twee-ts` are optional peer dependencies: a missing one is reported
4
+ * with the exact command that installs it.
5
+ */
6
+
7
+ export type OptionalPackage = '@rohal12/twee-ts' | 'happy-dom';
8
+
9
+ export type Importer = (pkg: string) => Promise<unknown>;
10
+
11
+ const defaultImporter: Importer = (pkg) => import(pkg);
12
+
13
+ function isMissingPackage(err: unknown, pkg: string): boolean {
14
+ return (
15
+ err instanceof Error &&
16
+ (err as { code?: unknown }).code === 'ERR_MODULE_NOT_FOUND' &&
17
+ err.message.includes(`'${pkg}'`)
18
+ );
19
+ }
20
+
21
+ /**
22
+ * Import `pkg`, rejecting with an install hint when it isn't installed. Any
23
+ * other import error (a failure inside the package, a different missing
24
+ * module) is rethrown unchanged.
25
+ */
26
+ export async function loadOptional<T>(
27
+ pkg: OptionalPackage,
28
+ feature: string,
29
+ importer: Importer = defaultImporter,
30
+ ): Promise<T> {
31
+ try {
32
+ return (await importer(pkg)) as T;
33
+ } catch (err) {
34
+ if (isMissingPackage(err, pkg)) {
35
+ throw new Error(
36
+ `spindle: ${feature} needs ${pkg}; install it with npm i -D ${pkg}`,
37
+ );
38
+ }
39
+ throw err;
40
+ }
41
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The messages between a play session's main-thread handle (`session.ts`) and
3
+ * its worker. This file is the single source of the shapes.
4
+ */
5
+ import type { TranscriptOptions } from '../headless';
6
+
7
+ export type Op = 'observe' | 'step' | 'goto' | 'get' | 'set' | 'transcript';
8
+
9
+ /** Main thread to worker: one call of the session API. */
10
+ export interface Request {
11
+ id: number;
12
+ op: Op;
13
+ args: unknown[];
14
+ }
15
+
16
+ /** Worker to main thread: the outcome of the call with the same `id`. */
17
+ export type Reply =
18
+ | { id: number; ok: true; result: unknown }
19
+ | { id: number; ok: false; error: { message: string } };
20
+
21
+ /** The worker's `workerData`. */
22
+ export interface WorkerData {
23
+ html: string;
24
+ /** The URL (as a string) of the module that exports `bootStory`. */
25
+ headlessUrl: string;
26
+ transcript: TranscriptOptions;
27
+ transitions: boolean;
28
+ }
29
+
30
+ /** Worker to main thread, once: the story booted or it did not. */
31
+ export type Ready =
32
+ { ready: true } | { ready: false; error: { message: string } };
33
+
34
+ /** Anything the worker posts to the main thread. */
35
+ export type WorkerMessage = Ready | Reply;
@@ -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
+ }