pngine 2.0.0 → 3.0.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.
package/src/init-core.js CHANGED
@@ -22,6 +22,15 @@ import { workerErrorFromMessage } from "./worker-errors.js";
22
22
  //
23
23
  // Errors arriving before the handshake settles (a shader that fails to compile
24
24
  // during init) still reach options.onError; they are not init failures.
25
+ //
26
+ // Routing is handed over AT THE RESOLVE, not by the caller afterwards, and that
27
+ // is load-bearing rather than tidy. `ready` resolves this promise but both
28
+ // profiles then await the audio phase — extractAudio, then createAudioPlayer,
29
+ // where a sointu module renders the entire song during instantiation. Leaving
30
+ // these handlers installed across that window meant a worker error in it hit
31
+ // fail(): terminate the worker, then reject a promise that has already settled,
32
+ // which is a silent no-op. The host got a "ready" instance with a dead worker,
33
+ // no error delivered, and a 250ms ack timeout on every later destroy().
25
34
  export function awaitWorkerReady(worker, initMessage, transfer, options) {
26
35
  return new Promise((resolve, reject) => {
27
36
  let timeout = null;
@@ -35,6 +44,7 @@ export function awaitWorkerReady(worker, initMessage, transfer, options) {
35
44
  worker.onmessage = (e) => {
36
45
  if (e.data.type === "ready") {
37
46
  clearTimeout(timeout);
47
+ routeWorkerMessages(worker, options);
38
48
  resolve(e.data);
39
49
  } else if (e.data.type === "error") {
40
50
  fail(new Error(e.data.message));
@@ -50,7 +60,9 @@ export function awaitWorkerReady(worker, initMessage, transfer, options) {
50
60
  }
51
61
 
52
62
  // Install the post-init routing: worker messages → options.onError /
53
- // options.onQueryResult.
63
+ // options.onQueryResult. Called by awaitWorkerReady the instant `ready`
64
+ // arrives, so there is no window in which neither this nor the init handshake
65
+ // owns the worker's messages.
54
66
  //
55
67
  // Repointing `onerror` is the load-bearing part. awaitWorkerReady aimed it at
56
68
  // the init promise's reject; leaving it there means every worker exception
@@ -71,11 +83,22 @@ export function routeWorkerMessages(worker, options) {
71
83
 
72
84
  // Attach pointer / keyboard / wheel tracking to `canvas`, filling a
73
85
  // Float32Array(12) the worker reads as pointer-inputs. Must be called before
74
- // canvas.transferControlToOffscreen(). Returns the buffer plus the document key
75
- // listeners so destroy() can detach them.
86
+ // canvas.transferControlToOffscreen(). Returns the buffer plus a `detach()`
87
+ // that removes every listener installed here.
88
+ //
89
+ // All seven listeners register through ONE AbortController, and that is
90
+ // structural rather than tidy. Five of them (the canvas pointer/wheel handlers)
91
+ // are anonymous: no reference is kept, so removeEventListener has nothing to be
92
+ // passed and they were simply unremovable. Each closes over `ptr` and `canvas`,
93
+ // so a host that retains the element — an SPA that pools canvases, a framework
94
+ // that keeps a ref — kept the whole instance's pointer state alive with it. A
95
+ // signal detaches them without giving every closure a name.
96
+ //
76
97
  // Layout: x, y, clickX, clickY, dx, dy, buttons, pressure, modifiers, scrollX, scrollY, _pad
77
98
  export function attachPointerTracking(canvas) {
78
99
  const ptr = new Float32Array(12);
100
+ const ac = new AbortController();
101
+ const signal = ac.signal;
79
102
  let lastPX = 0, lastPY = 0;
80
103
  // Modifier bitmask: 1=Shift, 2=Ctrl, 4=Alt, 8=Meta, 16=Space
81
104
  let mods = 0;
@@ -83,10 +106,8 @@ export function attachPointerTracking(canvas) {
83
106
  mods = (e.shiftKey ? 1 : 0) | (e.ctrlKey ? 2 : 0) | (e.altKey ? 4 : 0) | (e.metaKey ? 8 : 0) | (mods & 16);
84
107
  ptr[8] = mods;
85
108
  };
86
- const onKeyDown = (e) => { if (e.code === "Space") { mods |= 16; ptr[8] = mods; } };
87
- const onKeyUp = (e) => { if (e.code === "Space") { mods &= ~16; ptr[8] = mods; } };
88
- document.addEventListener("keydown", onKeyDown);
89
- document.addEventListener("keyup", onKeyUp);
109
+ document.addEventListener("keydown", (e) => { if (e.code === "Space") { mods |= 16; ptr[8] = mods; } }, { signal });
110
+ document.addEventListener("keyup", (e) => { if (e.code === "Space") { mods &= ~16; ptr[8] = mods; } }, { signal });
90
111
  canvas.addEventListener("pointerdown", (e) => {
91
112
  const r = canvas.getBoundingClientRect();
92
113
  const nx = (e.clientX - r.left) / r.width;
@@ -95,8 +116,11 @@ export function attachPointerTracking(canvas) {
95
116
  ptr[6] = e.buttons; ptr[7] = e.pressure || 0.5;
96
117
  updateMods(e);
97
118
  lastPX = nx; lastPY = ny;
119
+ // Not released explicitly: the spec auto-releases capture on pointerup and
120
+ // pointercancel, so there is nothing left to hold after the gesture ends
121
+ // (leak register C6 — verified, non-issue).
98
122
  canvas.setPointerCapture(e.pointerId);
99
- });
123
+ }, { signal });
100
124
  canvas.addEventListener("pointermove", (e) => {
101
125
  const r = canvas.getBoundingClientRect();
102
126
  const nx = Math.max(0, Math.min(1, (e.clientX - r.left) / r.width));
@@ -106,23 +130,23 @@ export function attachPointerTracking(canvas) {
106
130
  ptr[6] = e.buttons; ptr[7] = e.pressure || (e.buttons ? 0.5 : 0);
107
131
  updateMods(e);
108
132
  lastPX = nx; lastPY = ny;
109
- }, { passive: true });
133
+ }, { passive: true, signal });
110
134
  canvas.addEventListener("pointerup", () => {
111
135
  ptr[2] = -Math.abs(ptr[2]); ptr[3] = -Math.abs(ptr[3]);
112
136
  ptr[6] = 0; ptr[7] = 0;
113
- });
137
+ }, { signal });
114
138
  canvas.addEventListener("pointercancel", () => {
115
139
  ptr[2] = -Math.abs(ptr[2]); ptr[3] = -Math.abs(ptr[3]);
116
140
  ptr[6] = 0; ptr[7] = 0;
117
- });
141
+ }, { signal });
118
142
  canvas.addEventListener("wheel", (e) => {
119
143
  e.preventDefault();
120
144
  ptr[9] += Math.sign(e.deltaX);
121
145
  ptr[10] += Math.sign(e.deltaY);
122
146
  mods = (e.shiftKey ? 1 : 0) | (e.ctrlKey ? 2 : 0) | (e.altKey ? 4 : 0) | (e.metaKey ? 8 : 0) | (mods & 16);
123
147
  ptr[8] = mods;
124
- }, { passive: false });
125
- return { pointer: ptr, onKeyDown, onKeyUp };
148
+ }, { passive: false, signal });
149
+ return { pointer: ptr, detach: () => ac.abort() };
126
150
  }
127
151
 
128
152
  // Size the canvas backing store for HiDPI, before transferControlToOffscreen.
@@ -221,31 +245,41 @@ export function attachAutoResize(canvas, worker, seedW, seedH, onSize) {
221
245
  */
222
246
 
223
247
  // Create the Pngine POJO with read-only getters over `internal`.
248
+ //
249
+ // Every getter reads through `internal`, which destroy() empties in place. That
250
+ // is the only thing that actually releases the instance: `p._ = null` does not,
251
+ // because these closures capture the `internal` PARAMETER, not the `_` property
252
+ // — so a host holding a destroyed handle used to keep the terminated Worker,
253
+ // the canvas, the audio player and the pointer buffer reachable through it.
254
+ //
255
+ // Post-destroy reads answer null/0 rather than throwing (Decision #3): it
256
+ // matches the POJO feel of the rest of the surface, and a teardown path that
257
+ // reads `p.time` one last time should not explode.
224
258
  export function createPngine(internal) {
225
259
  return {
226
260
  get width() {
227
- return internal.width;
261
+ return internal.width ?? 0;
228
262
  },
229
263
  get height() {
230
- return internal.height;
264
+ return internal.height ?? 0;
231
265
  },
232
266
  get isPlaying() {
233
- return internal.pb.playing;
267
+ return internal.pb?.playing ?? false;
234
268
  },
235
269
  get time() {
236
- return internal.pb.time;
270
+ return internal.pb?.time ?? 0;
237
271
  },
238
272
  get frameCount() {
239
- return internal.frameCount;
273
+ return internal.frameCount ?? 0;
240
274
  },
241
275
  get animation() {
242
276
  return internal.animation;
243
277
  },
244
278
  get currentScene() {
245
- return internal.pb.scene;
279
+ return internal.pb?.scene ?? null;
246
280
  },
247
281
  get currentFrame() {
248
- return internal.pb.frame;
282
+ return internal.pb?.frame ?? null;
249
283
  },
250
284
  get duration() {
251
285
  // Animation duration in seconds, or 0 if no animation
@@ -260,8 +294,23 @@ export function createPngine(internal) {
260
294
  };
261
295
  }
262
296
 
263
- // Destroy a pngine instance: stop the RAF loop, tear down audio, detach the
264
- // document key listeners, and terminate the worker.
297
+ // How long destroy() waits for the worker to acknowledge before terminating it
298
+ // anyway. A wedged or already-dead agent must never strand the thread.
299
+ const DESTROY_ACK_TIMEOUT_MS = 250;
300
+
301
+ // Destroy a pngine instance: stop the RAF loop, tear down audio, detach every
302
+ // listener, let the worker release its GPU device, and terminate it.
303
+ //
304
+ // The worker teardown is ACKNOWLEDGED, not fire-and-forget. This used to post
305
+ // `destroy` and call terminate() on the very next line — and terminate()
306
+ // discards messages that have not been delivered yet, so worker-core's
307
+ // handleDestroy (gpu.destroy() + device.destroy()) was dead code on the normal
308
+ // path. Every GPU resource an instance owned was left for the browser to
309
+ // reclaim whenever it got round to collecting the worker agent, which in a
310
+ // churning SPA means many devices' worth of GPU memory outliving their players.
311
+ //
312
+ // destroy() stays synchronous — the terminate just happens on the ack, or on a
313
+ // timer if none arrives.
265
314
  export function destroy(p) {
266
315
  const i = p._;
267
316
  if (!i) return p;
@@ -269,10 +318,53 @@ export function destroy(p) {
269
318
  if (i.animationId) cancelAnimationFrame(i.animationId);
270
319
  if (i.disconnectResize) i.disconnectResize();
271
320
  if (i.audio) i.audio.destroy();
272
- if (i.onKeyDown) document.removeEventListener("keydown", i.onKeyDown);
273
- if (i.onKeyUp) document.removeEventListener("keyup", i.onKeyUp);
274
- i.worker.postMessage({ type: "destroy" });
275
- i.worker.terminate();
321
+ if (i.detachListeners) i.detachListeners();
322
+ // Settle every in-flight worker request (anim.js workerRequest) with its
323
+ // fallback: no reply can arrive once we terminate, and an unsettled promise
324
+ // retains the awaiting caller's whole continuation.
325
+ if (i.pendingRequests) {
326
+ for (const abandon of [...i.pendingRequests]) abandon();
327
+ i.pendingRequests = null;
328
+ }
329
+
330
+ const worker = i.worker;
331
+ if (worker) {
332
+ let done = false;
333
+ const finish = () => {
334
+ if (done) return;
335
+ done = true;
336
+ clearTimeout(timer);
337
+ worker.terminate();
338
+ };
339
+ const timer = setTimeout(finish, DESTROY_ACK_TIMEOUT_MS);
340
+ // Replaces routeWorkerMessages' handler: nothing else this instance could
341
+ // report still has anywhere to go.
342
+ worker.onmessage = (e) => { if (e.data?.type === "destroyed") finish(); };
343
+ worker.onerror = finish;
344
+ worker.postMessage({ type: "destroy" });
345
+ }
346
+
347
+ // A placeholder canvas initFromImage created is removed from the DOM, not
348
+ // merely forgotten: each `pngine("#img")`/destroy cycle used to stack one
349
+ // more absolutely-positioned canvas over the image, holding its last frame.
350
+ if (i.createdCanvas) i.canvas?.remove?.();
351
+ i.createdCanvas = false;
352
+
353
+ // Empty the bag the getters read through — this is what actually releases the
354
+ // instance, however long the host holds `p`.
355
+ i.worker = null;
356
+ i.canvas = null;
357
+ i.audio = null;
358
+ i.pointer = null;
359
+ i.animation = null;
360
+ i.pb = null;
361
+ i.detachListeners = null;
362
+ i.disconnectResize = null;
363
+ i.animationId = null;
364
+ i.ready = false;
365
+ i.width = 0;
366
+ i.height = 0;
367
+ i.frameCount = 0;
276
368
 
277
369
  p._ = null;
278
370
  return p;
package/src/init.js CHANGED
@@ -3,7 +3,10 @@
3
3
 
4
4
  import { extractBytecode, extractAudio } from "./extract.js";
5
5
  import { createAudioPlayer } from "./audio.js";
6
- import { attachPointerTracking, attachAutoResize, awaitWorkerReady, createPngine, destroy, routeWorkerMessages, sizeCanvasForInit } from "./init-core.js";
6
+ // routeWorkerMessages is NOT called here: awaitWorkerReady installs it at the
7
+ // instant `ready` arrives, so no window exists in which neither owns the
8
+ // worker's messages (the audio phase below used to be exactly that window).
9
+ import { attachPointerTracking, attachAutoResize, awaitWorkerReady, createPngine, destroy, sizeCanvasForInit } from "./init-core.js";
7
10
  import { initialPlayback } from "./playback-state.js";
8
11
 
9
12
  /** @typedef {import("./init-core.js").Pngine} Pngine */
@@ -30,6 +33,9 @@ let workerUrl = null;
30
33
  export async function pngine(source, options = {}) {
31
34
  // Resolve source to canvas + bytecode + raw PNG data
32
35
  let canvas, bytecode, rawData;
36
+ // True when initFromImage created the placeholder canvas itself — then it is
37
+ // ours to remove on destroy (a host-supplied canvas is the host's).
38
+ let createdCanvas = false;
33
39
 
34
40
  if (typeof source === "string") {
35
41
  // Check for CSS selector (# or . but not relative paths like ./ or ../)
@@ -39,7 +45,7 @@ export async function pngine(source, options = {}) {
39
45
  if (!el) throw new Error(`Element not found: ${source}`);
40
46
 
41
47
  if (el instanceof HTMLImageElement) {
42
- ({ canvas, bytecode, rawData } = await initFromImage(el, options));
48
+ ({ canvas, bytecode, rawData, createdCanvas } = await initFromImage(el, options));
43
49
  } else if (el instanceof HTMLCanvasElement) {
44
50
  canvas = el;
45
51
  throw new Error("Canvas source requires URL or data");
@@ -55,7 +61,7 @@ export async function pngine(source, options = {}) {
55
61
  bytecode = await extractBytecode(rawData);
56
62
  }
57
63
  } else if (source instanceof HTMLImageElement) {
58
- ({ canvas, bytecode, rawData } = await initFromImage(source, options));
64
+ ({ canvas, bytecode, rawData, createdCanvas } = await initFromImage(source, options));
59
65
  } else if (
60
66
  source instanceof ArrayBuffer ||
61
67
  source instanceof Uint8Array ||
@@ -73,57 +79,65 @@ export async function pngine(source, options = {}) {
73
79
  const { logicalW, logicalH, deviceW, deviceH } = sizeCanvasForInit(canvas, options);
74
80
 
75
81
  // Pointer/keyboard tracking — must attach before transferControlToOffscreen.
76
- const { pointer: ptr, onKeyDown, onKeyUp } = attachPointerTracking(canvas);
77
-
78
- // Get OffscreenCanvas
79
- const offscreen = canvas.transferControlToOffscreen();
80
-
81
- // Spawn worker
82
- const worker = new Worker(getWorkerUrl(), { type: "module" });
83
-
84
- // Compute WASM URL - must be absolute for worker blob context.
85
- // ../wasm/ resolves from both src/ (repo dev) and dist/ (published bundle)
86
- // to the package's wasm/pngine.wasm fallback.
87
- const wasmUrl = options.wasmUrl
88
- ? new URL(options.wasmUrl, window.location.href).href
89
- : new URL("../wasm/pngine.wasm", import.meta.url).href;
90
-
91
- // Wait for ready — slice bytecode so the original buffer stays alive for
92
- // extractAudio below.
93
- const bc = bytecode.slice();
94
- const result = await awaitWorkerReady(
95
- worker,
96
- {
97
- type: "init",
98
- canvas: offscreen,
99
- bytecode: bc,
100
- wasmUrl,
101
- debug: options.debug || false,
102
- },
103
- [offscreen, bc.buffer],
104
- options
105
- );
106
-
107
- // Extract and initialize audio from PNG (pNGa chunk) on main thread
108
- let audio = null;
109
- if (rawData) {
110
- const audioWasm = await extractAudio(rawData);
111
- if (audioWasm) {
112
- audio = await createAudioPlayer(audioWasm);
113
- }
82
+ const { pointer: ptr, detach: detachListeners } = attachPointerTracking(canvas);
83
+
84
+ // From here until the handle exists, the listeners are ours to release: a
85
+ // worker that fails to come up (WebGPU unsupported, a refused payload, the
86
+ // 15 s timeout, `new Worker` throwing under CSP) rejects from inside this
87
+ // block, and the seven listeners — two of them on `document` — used to
88
+ // outlive the rejection for the page's life. LEAK-06-C closed the audio
89
+ // phase one await later; this is the await before it.
90
+ let worker, result;
91
+ try {
92
+ // Get OffscreenCanvas
93
+ const offscreen = canvas.transferControlToOffscreen();
94
+
95
+ // Spawn worker
96
+ worker = new Worker(getWorkerUrl(), { type: "module" });
97
+
98
+ // Compute WASM URL - must be absolute for worker blob context.
99
+ // ../wasm/ resolves from both src/ (repo dev) and dist/ (published bundle)
100
+ // to the package's wasm/pngine.wasm fallback.
101
+ const wasmUrl = options.wasmUrl
102
+ ? new URL(options.wasmUrl, window.location.href).href
103
+ : new URL("../wasm/pngine.wasm", import.meta.url).href;
104
+
105
+ // Wait for ready — slice bytecode so the original buffer stays alive for
106
+ // extractAudio below.
107
+ const bc = bytecode.slice();
108
+ result = await awaitWorkerReady(
109
+ worker,
110
+ {
111
+ type: "init",
112
+ canvas: offscreen,
113
+ bytecode: bc,
114
+ wasmUrl,
115
+ debug: options.debug || false,
116
+ },
117
+ [offscreen, bc.buffer],
118
+ options
119
+ );
120
+ } catch (err) {
121
+ detachListeners();
122
+ if (createdCanvas) canvas.remove?.();
123
+ throw err;
114
124
  }
115
125
 
116
- // Route worker, shader-compilation, and WebGPU uncaptured errors (plus query
117
- // results) to options.onError / options.onQueryResult.
118
- routeWorkerMessages(worker, options);
119
-
120
- // Create POJO (report logical/CSS dimensions, not physical)
126
+ // The instance exists BEFORE the audio phase, because the audio phase is the
127
+ // first thing that can fail after the worker reports ready — and by then the
128
+ // GPUDevice is live, the canvas has been transferred, the bytecode went with
129
+ // it, and seven listeners are attached through an AbortController that only
130
+ // this handle can reach. A truncated pNGa is enough: createAudioPlayer's
131
+ // first act is WebAssembly.instantiate. Rejecting from here without a handle
132
+ // stranded every one of those for the page's life.
133
+ //
134
+ // (Report logical/CSS dimensions, not physical.)
121
135
  const p = createPngine({
122
136
  canvas,
137
+ createdCanvas,
123
138
  worker,
124
139
  pointer: ptr,
125
- onKeyDown,
126
- onKeyUp,
140
+ detachListeners,
127
141
  width: logicalW,
128
142
  height: logicalH,
129
143
  frameCount: result.frameCount,
@@ -131,9 +145,22 @@ export async function pngine(source, options = {}) {
131
145
  ready: true,
132
146
  pb: initialPlayback(),
133
147
  animationId: null,
134
- audio,
148
+ audio: null,
135
149
  });
136
150
 
151
+ // Extract and initialize audio from PNG (pNGa chunk) on main thread. A
152
+ // failed setup and a host teardown are the same release, so they are the
153
+ // same call — destroy() acks the worker's device release before terminating.
154
+ try {
155
+ if (rawData) {
156
+ const audioWasm = await extractAudio(rawData);
157
+ if (audioWasm) p._.audio = await createAudioPlayer(audioWasm);
158
+ }
159
+ } catch (err) {
160
+ destroy(p);
161
+ throw err;
162
+ }
163
+
137
164
  // Keep the backing store synced to the canvas's rendered size / DPR.
138
165
  p._.disconnectResize = attachAutoResize(canvas, worker, deviceW, deviceH, (w, h) => {
139
166
  p._.width = w;
@@ -147,12 +174,19 @@ export async function pngine(source, options = {}) {
147
174
  * Initialize from image element
148
175
  */
149
176
  async function initFromImage(img, options) {
150
- // Wait for image to load if needed
177
+ // Wait for image to load if needed. Both handlers are CLEARED once settled:
178
+ // each closes over the promise's continuation — i.e. the rest of pngine() —
179
+ // and they are pinned to an element the host owns, so leaving them attached
180
+ // keeps the whole init alive for as long as the page keeps the <img>.
151
181
  if (!img.complete) {
152
- await new Promise((resolve, reject) => {
153
- img.onload = resolve;
154
- img.onerror = reject;
155
- });
182
+ try {
183
+ await new Promise((resolve, reject) => {
184
+ img.onload = resolve;
185
+ img.onerror = reject;
186
+ });
187
+ } finally {
188
+ img.onload = img.onerror = null;
189
+ }
156
190
  }
157
191
 
158
192
  const { naturalWidth: w, naturalHeight: h } = img;
@@ -188,7 +222,7 @@ async function initFromImage(img, options) {
188
222
  const rawData = await resp.arrayBuffer();
189
223
  const bytecode = await extractBytecode(rawData);
190
224
 
191
- return { canvas, bytecode, rawData };
225
+ return { canvas, bytecode, rawData, createdCanvas: !options.canvas };
192
226
  }
193
227
 
194
228
  // createPngine + destroy are shared with the viewer profile (init-core.js).