@rohal12/spindle 0.62.3 → 0.62.5

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,63 @@
1
+ import type { Window } from 'happy-dom';
2
+
3
+ /** Expose the story's global window at the DOM event boundary. */
4
+ export function installWindowEvents(window: Window): void {
5
+ const storyWindow = globalThis as unknown as Window;
6
+ type Listener = Parameters<Window['addEventListener']>[1];
7
+ const wrapped = new WeakMap<object, Listener>();
8
+ const originals = new WeakMap<object, Listener>();
9
+ const wrap = (listener: Listener): Listener => {
10
+ // EventListener objects keep their own handleEvent receiver.
11
+ if (typeof listener !== 'function') return listener;
12
+ let callback = wrapped.get(listener);
13
+ if (!callback) {
14
+ callback = listener.bind(storyWindow);
15
+ wrapped.set(listener, callback);
16
+ originals.set(callback, listener);
17
+ }
18
+ return callback;
19
+ };
20
+
21
+ const { addEventListener, removeEventListener } = window;
22
+ window.addEventListener = (type, listener, options) =>
23
+ addEventListener(type, wrap(listener), options);
24
+ // happy-dom also removes already-wrapped listeners for once and abort.
25
+ window.removeEventListener = (type, listener) =>
26
+ removeEventListener(type, wrapped.get(listener) ?? listener);
27
+
28
+ for (const name of Object.getOwnPropertyNames(window)) {
29
+ const descriptor = Object.getOwnPropertyDescriptor(window, name)!;
30
+ if (!name.startsWith('on') || !descriptor.get || !descriptor.set) continue;
31
+ Object.defineProperty(window, name, {
32
+ ...descriptor,
33
+ get() {
34
+ const listener = descriptor.get!.call(window);
35
+ return originals.get(listener) ?? listener;
36
+ },
37
+ set(listener: Listener) {
38
+ descriptor.set!.call(window, wrap(listener));
39
+ },
40
+ });
41
+ }
42
+
43
+ // Translate references on the real event, retaining its identity, methods,
44
+ // cancellation and element targets. Subclasses share this Event prototype.
45
+ const exposeWindow = (target: unknown) =>
46
+ target === window ? storyWindow : target;
47
+ const prototype = window.Event.prototype;
48
+ for (const name of ['target', 'currentTarget']) {
49
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, name)!;
50
+ Object.defineProperty(prototype, name, {
51
+ ...descriptor,
52
+ get() {
53
+ return exposeWindow(descriptor.get!.call(this));
54
+ },
55
+ });
56
+ }
57
+ const { composedPath } = prototype;
58
+ prototype.composedPath = function () {
59
+ return composedPath
60
+ .call(this)
61
+ .map((target) => (target === window ? storyWindow : target));
62
+ };
63
+ }
@@ -8,6 +8,7 @@ import type * as HappyDom from 'happy-dom';
8
8
  import type * as Headless from '../headless';
9
9
  import { errorMessage } from '../utils/error-message';
10
10
  import { loadOptional } from './optional';
11
+ import { installWindowEvents } from './window-events';
11
12
  import type { Op, Ready, Reply, Request, WorkerData } from './protocol';
12
13
 
13
14
  type HeadlessModule = typeof Headless;
@@ -23,20 +24,28 @@ Object.defineProperty(process, 'stdout', {
23
24
  const port = parentPort!;
24
25
  const data = workerData as WorkerData;
25
26
 
26
- /** Make happy-dom's window the global environment Spindle runs in. */
27
+ /** Install happy-dom's DOM in the global environment Spindle runs in. */
27
28
  async function installDom(): Promise<void> {
28
29
  const { Window } = await loadOptional<typeof HappyDom>(
29
30
  'happy-dom',
30
31
  'play sessions',
31
32
  );
32
33
  const window = new Window({ url: 'http://localhost/' });
34
+ installWindowEvents(window);
33
35
  const global = globalThis as Record<string, unknown>;
34
36
  const source = window as unknown as Record<string, unknown>;
35
- global.window = window;
36
37
  global.document = window.document;
37
38
  // Node's own globals (fetch, URL, ...) stay as they are,
38
39
  for (const name of Object.getOwnPropertyNames(window)) {
39
- if (!(name in globalThis)) global[name] = source[name];
40
+ if (!(name in globalThis)) {
41
+ // happy-dom binds its accessors to the DOM window. Keep them live:
42
+ // copying values disconnects onresize setters and snapshots dimensions.
43
+ Object.defineProperty(
44
+ globalThis,
45
+ name,
46
+ Object.getOwnPropertyDescriptor(window, name)!,
47
+ );
48
+ }
40
49
  }
41
50
  // except those the story must get from happy-dom.
42
51
  for (const name of HAPPY_DOM_GLOBALS) {
@@ -46,6 +55,26 @@ async function installDom(): Promise<void> {
46
55
  value: source[name],
47
56
  });
48
57
  }
58
+ // Story JavaScript and expressions run through Function in this realm.
59
+ // Use that realm's global object for browser aliases too, so assignments,
60
+ // property descriptors and deletions on window have browser semantics.
61
+ for (const name of ['window', 'self', 'parent', 'top', 'frames']) {
62
+ Object.defineProperty(globalThis, name, {
63
+ configurable: true,
64
+ writable: true,
65
+ value: globalThis,
66
+ });
67
+ }
68
+ // DOM event callbacks and document.defaultView still use the backing
69
+ // window. Preserve their access to the API now installed on globalThis.
70
+ Object.defineProperty(window, 'Story', {
71
+ configurable: true,
72
+ get: () => global.Story,
73
+ set: (value: unknown) => {
74
+ global.Story = value;
75
+ },
76
+ });
77
+ installIdleCallbacks();
49
78
  // Node's BroadcastChannel reaches every worker thread in the process, so
50
79
  // sessions would hear each other's save-slot notices. Spindle works without
51
80
  // one (it falls back when the constructor is missing).
@@ -54,12 +83,36 @@ async function installDom(): Promise<void> {
54
83
  writable: true,
55
84
  value: undefined,
56
85
  });
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
- });
86
+ }
87
+
88
+ /** happy-dom has no idle scheduler; yield to a timer with a 50 ms budget. */
89
+ function installIdleCallbacks(): void {
90
+ const timers = new Map<number, ReturnType<typeof setTimeout>>();
91
+ let nextHandle = 0;
92
+ globalThis.requestIdleCallback = (callback, options) => {
93
+ const handle = ++nextHandle;
94
+ const requested = performance.now();
95
+ timers.set(
96
+ handle,
97
+ setTimeout(() => {
98
+ timers.delete(handle);
99
+ const started = performance.now();
100
+ const didTimeout =
101
+ options?.timeout !== undefined &&
102
+ started - requested >= options.timeout;
103
+ callback({
104
+ didTimeout,
105
+ timeRemaining: () =>
106
+ didTimeout ? 0 : Math.max(0, 50 - (performance.now() - started)),
107
+ });
108
+ }, 1),
109
+ );
110
+ return handle;
111
+ };
112
+ globalThis.cancelIdleCallback = (handle) => {
113
+ clearTimeout(timers.get(handle));
114
+ timers.delete(handle);
115
+ };
63
116
  }
64
117
 
65
118
  /**
package/src/registry.ts CHANGED
@@ -276,6 +276,9 @@ export function getMacroParameters(
276
276
  return metadataRegistry.get(name)?.parameters;
277
277
  }
278
278
 
279
+ getMacroParameters.source = (name: string) =>
280
+ metadataRegistry.get(name)?.source;
281
+
279
282
  export function getMacroRegistry(): MacroMetadata[] {
280
283
  return Array.from(metadataRegistry.values());
281
284
  }
@@ -318,6 +318,12 @@ export function establishPlaythrough(
318
318
 
319
319
  // --- Save Hooks ---
320
320
 
321
+ /** A synchronous hook capture; dispose also runs when a hook throws. */
322
+ export interface SaveCapture {
323
+ (): SavePayload;
324
+ dispose(): void;
325
+ }
326
+
321
327
  /**
322
328
  * Run a save through the `beforesave` / `aftersave` hooks. `beforesave` fires
323
329
  * before the payload is captured, so data a hook sets is part of the save;
@@ -339,13 +345,18 @@ export function establishPlaythrough(
339
345
  export function saveWithHooks<T>(
340
346
  slot: string | undefined,
341
347
  custom: Record<string, unknown> | undefined,
342
- beginCapture: () => () => SavePayload,
348
+ beginCapture: () => SaveCapture,
343
349
  write: (payload: SavePayload) => Promise<T>,
344
350
  ): Promise<T> {
345
351
  try {
346
352
  const capture = beginCapture();
347
- withoutDraws(() => emit('beforesave', slot, custom));
348
- const payload = capture();
353
+ let payload: SavePayload;
354
+ try {
355
+ withoutDraws(() => emit('beforesave', slot, custom));
356
+ payload = capture();
357
+ } finally {
358
+ capture.dispose();
359
+ }
349
360
  return write(payload).then((result) => {
350
361
  withoutDraws(() => emit('aftersave', slot));
351
362
  return result;
package/src/store.ts CHANGED
@@ -35,6 +35,7 @@ import {
35
35
  startNewPlaythrough,
36
36
  quickSave,
37
37
  saveWithHooks,
38
+ type SaveCapture,
38
39
  loadSlotSave,
39
40
  adoptPlaythrough,
40
41
  populateKnownSaves,
@@ -493,6 +494,7 @@ function enterStart(
493
494
  ): void {
494
495
  state.currentPassage = passage;
495
496
  state.navigationId++;
497
+ state.replacementNavigationId = state.navigationId;
496
498
  state.variables = variables;
497
499
  state.transient = freshTransients(transientDefaults);
498
500
  state.temporary = createNamespace();
@@ -841,11 +843,11 @@ function loadedEntryMoment(
841
843
  }
842
844
 
843
845
  /** The variable paths `Story.set` writes while a save's hooks run. */
844
- let hookWrites: Map<string, string[]> | null = null;
846
+ const hookWrites = new Set<Map<string, string[]>>();
845
847
 
846
848
  /** Note that `path` of the variables was written (see keepHookWrites). */
847
849
  export function recordHookWrite(path: string[]): void {
848
- hookWrites?.set(pathKey(path), path);
850
+ for (const writes of hookWrites) writes.set(pathKey(path), path);
849
851
  }
850
852
 
851
853
  /**
@@ -997,6 +999,8 @@ export interface StoryState {
997
999
  * so the passage display can remount even when the passage name is unchanged.
998
1000
  */
999
1001
  navigationId: number;
1002
+ /** Navigation that most recently initialized, restarted or loaded the game. */
1003
+ replacementNavigationId: number;
1000
1004
  variables: Record<string, unknown>;
1001
1005
  variableDefaults: Record<string, unknown>;
1002
1006
  transient: Record<string, unknown>;
@@ -1080,7 +1084,7 @@ export interface StoryState {
1080
1084
  * function builds the payload after them, and keeps the variables the
1081
1085
  * hooks changed in the saved moment's snapshot, so a load restores them.
1082
1086
  */
1083
- beginSave: () => () => SavePayload;
1087
+ beginSave: () => SaveCapture;
1084
1088
  /**
1085
1089
  * Replace the game state with a live (deserialized) payload. `slot` is
1086
1090
  * passed to the `beforeload`/`afterload` events. Pass the save's
@@ -1303,6 +1307,7 @@ export const useStoryStore = create<StoryState>()(
1303
1307
  storyData: null,
1304
1308
  currentPassage: '',
1305
1309
  navigationId: 0,
1310
+ replacementNavigationId: 0,
1306
1311
  variables: createNamespace(),
1307
1312
  variableDefaults: {},
1308
1313
  transient: createNamespace(),
@@ -1834,20 +1839,28 @@ export const useStoryStore = create<StoryState>()(
1834
1839
  const before = get().variables;
1835
1840
  const replaced = latestStateApplied;
1836
1841
  const writes = new Map<string, string[]>();
1837
- hookWrites = writes;
1838
- return () => {
1839
- if (hookWrites === writes) hookWrites = null;
1840
- // A restart or load in a hook left the game the save was issued
1841
- // for (its playthrough) for another: no save describes both
1842
- if (latestStateApplied !== replaced) {
1843
- throw new Error(
1844
- 'spindle: a beforesave handler restarted or loaded the game, so the save was not made',
1845
- );
1846
- }
1847
- const payload = get().getSavePayload();
1848
- keepHookWrites(payload, before, get().variables, [...writes.values()]);
1849
- return payload;
1842
+ hookWrites.add(writes);
1843
+ const dispose = () => {
1844
+ hookWrites.delete(writes);
1850
1845
  };
1846
+ return Object.assign(
1847
+ () => {
1848
+ dispose();
1849
+ // A restart or load in a hook left the game the save was issued
1850
+ // for (its playthrough) for another: no save describes both
1851
+ if (latestStateApplied !== replaced) {
1852
+ throw new Error(
1853
+ 'spindle: a beforesave handler restarted or loaded the game, so the save was not made',
1854
+ );
1855
+ }
1856
+ const payload = get().getSavePayload();
1857
+ keepHookWrites(payload, before, get().variables, [
1858
+ ...writes.values(),
1859
+ ]);
1860
+ return payload;
1861
+ },
1862
+ { dispose },
1863
+ );
1851
1864
  },
1852
1865
 
1853
1866
  loadFromPayload: (
@@ -1937,6 +1950,7 @@ export const useStoryStore = create<StoryState>()(
1937
1950
  set((state) => {
1938
1951
  state.currentPassage = payload.passage;
1939
1952
  state.navigationId++;
1953
+ state.replacementNavigationId = state.navigationId;
1940
1954
  state.variables = createNamespace(
1941
1955
  deepClone(entry?.variables ?? payload.variables),
1942
1956
  );
@@ -22,6 +22,7 @@ import {
22
22
  pieceOffset,
23
23
  widgetPieces,
24
24
  withParseCache,
25
+ executesRawBody,
25
26
  type ParametersOf,
26
27
  type Piece,
27
28
  } from './code-check';
@@ -832,10 +833,7 @@ function collectTokenRefs(
832
833
  }
833
834
  }
834
835
 
835
- if (
836
- token.name.toLowerCase() === 'do' &&
837
- !parametersOf.widget?.(token.name)
838
- ) {
836
+ if (executesRawBody(token.name, parametersOf)) {
839
837
  // A {do} body is JavaScript: scan its source text as code, however
840
838
  // the markup tokens split it up.
841
839
  let close = t + 1;
package/src/tooling.ts CHANGED
@@ -177,6 +177,8 @@ export interface ValidateMarkupOptions {
177
177
 
178
178
  export interface ToolingMacro {
179
179
  name: string;
180
+ /** Preserve builtin provenance; an explicit macro without it is a replacement. */
181
+ source?: 'builtin' | 'user';
180
182
  block: boolean;
181
183
  subMacros: string[];
182
184
  /**
@@ -2,11 +2,12 @@ import type { ASTNode } from '../markup/ast';
2
2
  import type { Token } from '../markup/tokens';
3
3
  import { codeAndText, parameterLookup, type ParametersOf } from '../code-check';
4
4
  import { parseMarkup, type MarkupHooks } from '../markup/parse';
5
- import { getMacroRegistry } from '../registry';
5
+ import { getMacroRegistry, getMacroParameters } from '../registry';
6
6
 
7
7
  /** The declared parameters of the macros registered so far. */
8
8
  export const registeredParameters: ParametersOf = (name) =>
9
9
  parameterLookup(getMacroRegistry())(name);
10
+ registeredParameters.source = getMacroParameters.source;
10
11
 
11
12
  /**
12
13
  * Whether the text of an attribute value or macro label renders a
package/types/play.d.ts CHANGED
@@ -73,11 +73,12 @@ export interface PlaySession {
73
73
  * Node APIs, files and environment. Worker threads and happy-dom are not a
74
74
  * security sandbox. Only run code you trust.
75
75
  *
76
- * In the worker, `window` is happy-dom's window, not `globalThis`. Story code
77
- * sees `Story` and the DOM globals as in a browser, but a property set on
78
- * `window` (`window.foo = 1`) does not become a bare global `foo`. Sessions do
79
- * not share a `BroadcastChannel`, `localStorage` or `navigator`, so they never
80
- * hear each other. The story's `console.log` goes to stderr, not stdout.
76
+ * In the worker, `window` is `globalThis`, with happy-dom's DOM globals.
77
+ * Properties set on `window` are also bare globals, as in a browser.
78
+ * `requestIdleCallback` and `cancelIdleCallback` use a timer-backed scheduler.
79
+ * Sessions do not share a `BroadcastChannel`, `localStorage` or `navigator`,
80
+ * so they never hear each other. The story's `console.log` goes to stderr,
81
+ * not stdout.
81
82
  *
82
83
  * A session left open does not keep Node running (a call in progress does).
83
84
  */
@@ -653,6 +653,8 @@ export declare function collectPassageReferences(
653
653
  /** What tooling knows about a macro (a `MacroMetadata` has all of it). */
654
654
  export interface ToolingMacro {
655
655
  name: string;
656
+ /** Preserve builtin provenance; an explicit macro without it is a replacement. */
657
+ source?: 'builtin' | 'user';
656
658
  block: boolean;
657
659
  subMacros: string[];
658
660
  /** A widget's parameters and their argument contracts. */