@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.
@@ -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
+ });
@@ -42,6 +42,11 @@ export function showRuntimeError(context: string, error: unknown): void {
42
42
  );
43
43
  }
44
44
 
45
+ /** The error for navigating to `name`, a special passage (StoryInit, ...). */
46
+ export function specialPassageError(name: string): Error {
47
+ return new Error(`Cannot navigate to special passage "${name}".`);
48
+ }
49
+
45
50
  /**
46
51
  * The error for `name`, a passage name that names no passage, used in the
47
52
  * passage `from`.
package/src/store.ts CHANGED
@@ -63,7 +63,11 @@ import {
63
63
  } from './structural';
64
64
  import { getByPath } from './utils/object-path';
65
65
  import { isIndexKey } from './utils/value-kinds';
66
- import { noPassageError, showRuntimeError } from './runtime-errors';
66
+ import {
67
+ noPassageError,
68
+ showRuntimeError,
69
+ specialPassageError,
70
+ } from './runtime-errors';
67
71
  import {
68
72
  snapshotPRNG,
69
73
  restorePRNG,
@@ -108,6 +112,11 @@ const SPECIAL_PASSAGES = new Set([
108
112
  'StoryContext',
109
113
  ]);
110
114
 
115
+ /** Whether `name` is a special passage, which navigation never goes to. */
116
+ export function isSpecialPassage(name: string): boolean {
117
+ return SPECIAL_PASSAGES.has(name);
118
+ }
119
+
111
120
  // ---------------------------------------------------------------------------
112
121
  // Patch-based variable history (module-level, outside Zustand)
113
122
  // ---------------------------------------------------------------------------
@@ -1394,10 +1403,8 @@ export const useStoryStore = create<StoryState>()(
1394
1403
  const { storyData } = get();
1395
1404
  if (!storyData) return;
1396
1405
 
1397
- if (SPECIAL_PASSAGES.has(passageName)) {
1398
- console.error(
1399
- `spindle: Cannot navigate to special passage "${passageName}".`,
1400
- );
1406
+ if (isSpecialPassage(passageName)) {
1407
+ console.error(`spindle: ${specialPassageError(passageName).message}`);
1401
1408
  return;
1402
1409
  }
1403
1410
 
@@ -37,6 +37,10 @@ import type {
37
37
  import type { bootStory as PublishedBootStory } from '../types/headless';
38
38
  import type * as SourceTooling from './tooling';
39
39
  import type * as PublishedTooling from '../types/tooling';
40
+ import type * as SourceHeadless from './headless';
41
+ import type * as PublishedHeadless from '../types/headless';
42
+ import type * as SourcePlay from './play/index';
43
+ import type * as PublishedPlay from '../types/play';
40
44
 
41
45
  /** What the source declares, by published name. */
42
46
  interface Source {
@@ -198,3 +202,54 @@ declare const validateStoryMarkup: typeof SourceValidateStoryMarkup;
198
202
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
199
203
  const _validateMarkup: typeof PublishedValidateMarkup = (passages, options) =>
200
204
  validateStoryMarkup(passages, [], options);
205
+
206
+ // The rest of the headless entry point, and the play entry point
207
+ // (`@rohal12/spindle/play`): each must be the same type in the source and in
208
+ // types/headless.d.ts or types/play.d.ts.
209
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
210
+ const _headlessAndPlayTypes: [
211
+ Same<typeof SourceHeadless.gotoError, typeof PublishedHeadless.gotoError>,
212
+ Same<
213
+ typeof SourceHeadless.storyVariables,
214
+ typeof PublishedHeadless.storyVariables
215
+ >,
216
+ Same<
217
+ typeof SourceHeadless.createTranscript,
218
+ typeof PublishedHeadless.createTranscript
219
+ >,
220
+ Same<SourceHeadless.BootStoryOptions, PublishedHeadless.BootStoryOptions>,
221
+ Same<SourceHeadless.Transcript, PublishedHeadless.Transcript>,
222
+ Same<SourceHeadless.TranscriptEntry, PublishedHeadless.TranscriptEntry>,
223
+ Same<SourceHeadless.TranscriptOptions, PublishedHeadless.TranscriptOptions>,
224
+ Same<typeof SourcePlay.openPlaySession, typeof PublishedPlay.openPlaySession>,
225
+ Same<
226
+ typeof SourcePlay.resolveStoryHtml,
227
+ typeof PublishedPlay.resolveStoryHtml
228
+ >,
229
+ Same<SourcePlay.PlaySession, PublishedPlay.PlaySession>,
230
+ Same<SourcePlay.PlaySessionOptions, PublishedPlay.PlaySessionOptions>,
231
+ Same<SourcePlay.StoryInput, PublishedPlay.StoryInput>,
232
+ Same<SourcePlay.ResolvedStory, PublishedPlay.ResolvedStory>,
233
+ Same<SourcePlay.Observation, PublishedPlay.Observation>,
234
+ Same<SourcePlay.ObservedAction, PublishedPlay.ObservedAction>,
235
+ Same<SourcePlay.TranscriptEntry, PublishedPlay.TranscriptEntry>,
236
+ Same<SourcePlay.TranscriptOptions, PublishedPlay.TranscriptOptions>,
237
+ ] = [
238
+ true,
239
+ true,
240
+ true,
241
+ true,
242
+ true,
243
+ true,
244
+ true,
245
+ true,
246
+ true,
247
+ true,
248
+ true,
249
+ true,
250
+ true,
251
+ true,
252
+ true,
253
+ true,
254
+ true,
255
+ ];
@@ -24,6 +24,20 @@ export interface BootStoryOptions {
24
24
  */
25
25
  export function bootStory(options: BootStoryOptions): Promise<StoryAPI>;
26
26
 
27
+ /**
28
+ * The story's `$` variables: a shallow copy of the current values, keyed by
29
+ * name without the `$`. Values are the store's own (frozen) objects.
30
+ */
31
+ export function storyVariables(): Record<string, unknown>;
32
+
33
+ /**
34
+ * Why `Story.goto(name)` would not navigate, or `null` if it would: `name` is
35
+ * a special passage (StoryInit, ...) or names no passage. The message is the
36
+ * one Spindle logs (and, for a missing passage, shows on the page), since
37
+ * `Story.goto()` reports these instead of throwing.
38
+ */
39
+ export function gotoError(name: string): string | null;
40
+
27
41
  /** One recorded step: what the reader saw, and what they chose. */
28
42
  export interface TranscriptEntry {
29
43
  turn: number;
@@ -0,0 +1,83 @@
1
+ import type {
2
+ Observation,
3
+ TranscriptEntry,
4
+ TranscriptOptions,
5
+ } from './headless';
6
+ import type { ObservedAction } from './index';
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
+ /** The result of {@link resolveStoryHtml}. */
12
+ export interface ResolvedStory {
13
+ html: string;
14
+ /** Things worth telling the caller; never errors. */
15
+ notes: string[];
16
+ }
17
+
18
+ /**
19
+ * Turn a story into HTML: inline HTML as given, an `.html` path read, and
20
+ * anything else (a `.twee` file, a glob or a project directory) compiled with
21
+ * the installed Spindle format. Compiling needs the optional peer dependency
22
+ * `@rohal12/twee-ts`.
23
+ */
24
+ export function resolveStoryHtml(input: StoryInput): Promise<ResolvedStory>;
25
+
26
+ /** Options for {@link openPlaySession}. */
27
+ export interface PlaySessionOptions {
28
+ html: string;
29
+ /** Per call. Default 10_000. */
30
+ stepTimeoutMs?: number;
31
+ /** Passed to createTranscript() inside the worker. Default { limit: 10 }. */
32
+ transcript?: TranscriptOptions;
33
+ /** Keep passage transitions (bootStory's option). Default false. */
34
+ transitions?: boolean;
35
+ }
36
+
37
+ /** A running story, returned by {@link openPlaySession}. */
38
+ export interface PlaySession {
39
+ observe(): Promise<Observation>;
40
+ /** Goes through the transcript, so the step is recorded. */
41
+ step(id: string, value?: unknown): Promise<Observation>;
42
+ /**
43
+ * Story.goto(), then waitForActions(), then observe(). Not recorded in the
44
+ * transcript. Rejects for a passage the story does not have
45
+ * (`spindle: No passage named "<name>" ...`) or a special passage such as
46
+ * StoryInit (`spindle: Cannot navigate to special passage ...`); the session
47
+ * stays open.
48
+ */
49
+ goto(passage: string): Promise<Observation>;
50
+ /**
51
+ * Story variables, by name with or without `$`. All of them when `names`
52
+ * is left out. Each value comes back as a structured clone (Map, Set, Date
53
+ * and cycles survive; class instances arrive as plain objects); one that
54
+ * cannot be cloned (a function, a Map holding one) is the string
55
+ * `"[unserializable: <reason>]"`.
56
+ */
57
+ get(names?: string[]): Promise<Record<string, unknown>>;
58
+ /** Story.set(), then waitForActions(). */
59
+ set(values: Record<string, unknown>): Promise<void>;
60
+ transcript(): Promise<TranscriptEntry[]>;
61
+ close(): Promise<void>;
62
+ readonly closed: boolean;
63
+ }
64
+
65
+ /**
66
+ * Boot a compiled story in its own worker thread on happy-dom (an optional
67
+ * peer dependency) and resolve with a session once the first passage is
68
+ * shown. Calls run one at a time; a call that takes longer than
69
+ * `stepTimeoutMs` closes the session.
70
+ *
71
+ * In the worker, `window` is happy-dom's window, not `globalThis`. Story code
72
+ * sees `Story` and the DOM globals as in a browser, but a property set on
73
+ * `window` (`window.foo = 1`) does not become a bare global `foo`. Sessions do
74
+ * not share a `BroadcastChannel`, `localStorage` or `navigator`, so they never
75
+ * hear each other. The story's `console.log` goes to stderr, not stdout.
76
+ *
77
+ * A session left open does not keep Node running (a call in progress does).
78
+ */
79
+ export function openPlaySession(
80
+ options: PlaySessionOptions,
81
+ ): Promise<PlaySession>;
82
+
83
+ export type { Observation, ObservedAction, TranscriptEntry, TranscriptOptions };