@rohal12/spindle 0.62.3 → 0.62.4

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.
@@ -13476,6 +13476,7 @@ function useRenderOptions() {
13476
13476
  inline: useContext(InlineContext),
13477
13477
  raw: useContext(RawTextContext),
13478
13478
  structural: useContext(StructuralContext),
13479
+ preserveEdges: true,
13479
13480
  locals: useContext(LocalsValuesContext)
13480
13481
  };
13481
13482
  }
@@ -14518,7 +14519,7 @@ function renderNodes(nodes, options) {
14518
14519
  const lead = combined.slice(0, skipChars(combined, 0, 1, EDGE_WS));
14519
14520
  const trail = lead.length === combined.length ? "" : combined.slice(skipChars(combined, combined.length, -1, EDGE_WS));
14520
14521
  const core = combined.slice(lead.length, combined.length - trail.length);
14521
- const edges = (content) => unwrapParagraphs && (lead || trail) ? /* @__PURE__ */ jsxs(Fragment$1, { children: [
14522
+ const edges = (content) => (unwrapParagraphs || options?.preserveEdges) && (lead || trail) ? /* @__PURE__ */ jsxs(Fragment$1, { children: [
14522
14523
  lead,
14523
14524
  content,
14524
14525
  trail
@@ -36,6 +36,56 @@ async function loadOptional(pkg, feature, importer = defaultImporter) {
36
36
  }
37
37
  }
38
38
  //#endregion
39
+ //#region src/play/window-events.ts
40
+ /** Expose the story's global window at the DOM event boundary. */
41
+ function installWindowEvents(window) {
42
+ const storyWindow = globalThis;
43
+ const wrapped = /* @__PURE__ */ new WeakMap();
44
+ const originals = /* @__PURE__ */ new WeakMap();
45
+ const wrap = (listener) => {
46
+ if (typeof listener !== "function") return listener;
47
+ let callback = wrapped.get(listener);
48
+ if (!callback) {
49
+ callback = listener.bind(storyWindow);
50
+ wrapped.set(listener, callback);
51
+ originals.set(callback, listener);
52
+ }
53
+ return callback;
54
+ };
55
+ const { addEventListener, removeEventListener } = window;
56
+ window.addEventListener = (type, listener, options) => addEventListener(type, wrap(listener), options);
57
+ window.removeEventListener = (type, listener) => removeEventListener(type, wrapped.get(listener) ?? listener);
58
+ for (const name of Object.getOwnPropertyNames(window)) {
59
+ const descriptor = Object.getOwnPropertyDescriptor(window, name);
60
+ if (!name.startsWith("on") || !descriptor.get || !descriptor.set) continue;
61
+ Object.defineProperty(window, name, {
62
+ ...descriptor,
63
+ get() {
64
+ const listener = descriptor.get.call(window);
65
+ return originals.get(listener) ?? listener;
66
+ },
67
+ set(listener) {
68
+ descriptor.set.call(window, wrap(listener));
69
+ }
70
+ });
71
+ }
72
+ const exposeWindow = (target) => target === window ? storyWindow : target;
73
+ const prototype = window.Event.prototype;
74
+ for (const name of ["target", "currentTarget"]) {
75
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
76
+ Object.defineProperty(prototype, name, {
77
+ ...descriptor,
78
+ get() {
79
+ return exposeWindow(descriptor.get.call(this));
80
+ }
81
+ });
82
+ }
83
+ const { composedPath } = prototype;
84
+ prototype.composedPath = function() {
85
+ return composedPath.call(this).map((target) => target === window ? storyWindow : target);
86
+ };
87
+ }
88
+ //#endregion
39
89
  //#region src/play/worker.ts
40
90
  /**
41
91
  * The worker thread of a play session: boots the story on happy-dom and
@@ -49,30 +99,68 @@ Object.defineProperty(process, "stdout", {
49
99
  });
50
100
  var port = parentPort;
51
101
  var data = workerData;
52
- /** Make happy-dom's window the global environment Spindle runs in. */
102
+ /** Install happy-dom's DOM in the global environment Spindle runs in. */
53
103
  async function installDom() {
54
104
  const { Window } = await loadOptional("happy-dom", "play sessions");
55
105
  const window = new Window({ url: "http://localhost/" });
106
+ installWindowEvents(window);
56
107
  const global = globalThis;
57
108
  const source = window;
58
- global.window = window;
59
109
  global.document = window.document;
60
- for (const name of Object.getOwnPropertyNames(window)) if (!(name in globalThis)) global[name] = source[name];
110
+ for (const name of Object.getOwnPropertyNames(window)) if (!(name in globalThis)) Object.defineProperty(globalThis, name, Object.getOwnPropertyDescriptor(window, name));
61
111
  for (const name of HAPPY_DOM_GLOBALS) Object.defineProperty(globalThis, name, {
62
112
  configurable: true,
63
113
  writable: true,
64
114
  value: source[name]
65
115
  });
66
- Object.defineProperty(globalThis, "BroadcastChannel", {
116
+ for (const name of [
117
+ "window",
118
+ "self",
119
+ "parent",
120
+ "top",
121
+ "frames"
122
+ ]) Object.defineProperty(globalThis, name, {
67
123
  configurable: true,
68
124
  writable: true,
69
- value: void 0
125
+ value: globalThis
70
126
  });
71
- Object.defineProperty(globalThis, "Story", {
127
+ Object.defineProperty(window, "Story", {
72
128
  configurable: true,
73
- get: () => source.Story
129
+ get: () => global.Story,
130
+ set: (value) => {
131
+ global.Story = value;
132
+ }
133
+ });
134
+ installIdleCallbacks();
135
+ Object.defineProperty(globalThis, "BroadcastChannel", {
136
+ configurable: true,
137
+ writable: true,
138
+ value: void 0
74
139
  });
75
140
  }
141
+ /** happy-dom has no idle scheduler; yield to a timer with a 50 ms budget. */
142
+ function installIdleCallbacks() {
143
+ const timers = /* @__PURE__ */ new Map();
144
+ let nextHandle = 0;
145
+ globalThis.requestIdleCallback = (callback, options) => {
146
+ const handle = ++nextHandle;
147
+ const requested = performance.now();
148
+ timers.set(handle, setTimeout(() => {
149
+ timers.delete(handle);
150
+ const started = performance.now();
151
+ const didTimeout = options?.timeout !== void 0 && started - requested >= options.timeout;
152
+ callback({
153
+ didTimeout,
154
+ timeRemaining: () => didTimeout ? 0 : Math.max(0, 50 - (performance.now() - started))
155
+ });
156
+ }, 1));
157
+ return handle;
158
+ };
159
+ globalThis.cancelIdleCallback = (handle) => {
160
+ clearTimeout(timers.get(handle));
161
+ timers.delete(handle);
162
+ };
163
+ }
76
164
  /**
77
165
  * Globals happy-dom's window replaces even where Node has its own:
78
166
  * - the event classes: happy-dom's dispatchEvent() refuses events made with
package/dist/pkg/play.js CHANGED
@@ -192,9 +192,9 @@ function workerExecArgv(execArgv) {
192
192
  return kept;
193
193
  }
194
194
  /**
195
- * Opens a session that runs the story in a worker. There `window` is
196
- * happy-dom's window, not `globalThis`: story code sees `Story` and the DOM
197
- * globals, but `window.foo = 1` does not make a bare global `foo`.
195
+ * Opens a session that runs the story in a worker with happy-dom's DOM.
196
+ * `window` is `globalThis`: properties authored on it are bare globals too.
197
+ * Idle callbacks use a timer-backed scheduler.
198
198
  * Requires `trusted: true`: story code has unrestricted host Node access.
199
199
  */
200
200
  function openPlaySession(options) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.62.3",
3
+ "version": "0.62.4",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -17,6 +17,7 @@ export function useRenderOptions(): {
17
17
  inline: boolean;
18
18
  raw: boolean;
19
19
  structural: boolean;
20
+ preserveEdges: boolean;
20
21
  locals: Record<string, unknown>;
21
22
  } {
22
23
  return {
@@ -24,6 +25,9 @@ export function useRenderOptions(): {
24
25
  inline: useContext(InlineContext),
25
26
  raw: useContext(RawTextContext),
26
27
  structural: useContext(StructuralContext),
28
+ // These are content fragments (macro/widget bodies and forwarded
29
+ // children), whose edge whitespace separates surrounding prose.
30
+ preserveEdges: true,
27
31
  locals: useContext(LocalsValuesContext),
28
32
  };
29
33
  }
@@ -1075,6 +1075,8 @@ export function renderNodes(
1075
1075
  raw?: boolean;
1076
1076
  /** Content of a structural element (see StructuralContext). */
1077
1077
  structural?: boolean;
1078
+ /** A content fragment: keep whitespace separating it from its neighbours. */
1079
+ preserveEdges?: boolean;
1078
1080
  },
1079
1081
  ): preact.ComponentChildren {
1080
1082
  if (nodes.length === 0) return null;
@@ -1131,9 +1133,9 @@ export function renderNodes(
1131
1133
  // Inline content (inside <span> etc.) never gets <p> wrappers (#220).
1132
1134
  const unwrapParagraphs = !!(options?.nobr || options?.inline);
1133
1135
 
1134
- // Markdown strips whitespace at paragraph edges. Without <p> wrappers that
1135
- // whitespace separates this content from its neighbours (as in
1136
- // `<span>*HP*: </span>{$hp}`), so it is kept around the output there.
1136
+ // Markdown strips whitespace at paragraph edges. In content fragments and
1137
+ // without <p> wrappers it separates content from its neighbours (as in
1138
+ // `A.{if true} B.{/if}` or `<span>*HP*: </span>{$hp}`).
1137
1139
  const lead = combined.slice(0, skipChars(combined, 0, 1, EDGE_WS));
1138
1140
  const trail =
1139
1141
  lead.length === combined.length
@@ -1141,7 +1143,7 @@ export function renderNodes(
1141
1143
  : combined.slice(skipChars(combined, combined.length, -1, EDGE_WS));
1142
1144
  const core = combined.slice(lead.length, combined.length - trail.length);
1143
1145
  const edges = (content: preact.ComponentChildren) =>
1144
- unwrapParagraphs && (lead || trail) ? (
1146
+ (unwrapParagraphs || options?.preserveEdges) && (lead || trail) ? (
1145
1147
  <>
1146
1148
  {lead}
1147
1149
  {content}
@@ -72,9 +72,9 @@ export function workerExecArgv(execArgv: readonly string[]): string[] {
72
72
  }
73
73
 
74
74
  /**
75
- * Opens a session that runs the story in a worker. There `window` is
76
- * happy-dom's window, not `globalThis`: story code sees `Story` and the DOM
77
- * globals, but `window.foo = 1` does not make a bare global `foo`.
75
+ * Opens a session that runs the story in a worker with happy-dom's DOM.
76
+ * `window` is `globalThis`: properties authored on it are bare globals too.
77
+ * Idle callbacks use a timer-backed scheduler.
78
78
  * Requires `trusted: true`: story code has unrestricted host Node access.
79
79
  */
80
80
  export function openPlaySession(
@@ -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/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
  */