@margoengine/worker 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +84 -3
- package/dist/auto.d.ts +37 -0
- package/dist/auto.js +110 -0
- package/dist/canvas.d.ts +67 -0
- package/dist/canvas.js +157 -0
- package/dist/errors-CDgOgzCd.js +7 -0
- package/dist/index.d.ts +66 -0
- package/dist/index.js +191 -0
- package/dist/rpc.d.ts +101 -0
- package/dist/rpc.js +254 -0
- package/dist/scene-runtime.d.ts +24 -0
- package/dist/scene.worker.d.ts +1 -0
- package/dist/workers/scene.js +1 -0
- package/package.json +61 -6
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
//#region ../shared/errors.js
|
|
2
|
+
var e = (e, t) => Object.assign(Error(t), {
|
|
3
|
+
name: "MargoError",
|
|
4
|
+
code: e
|
|
5
|
+
}), t = (e, t) => `${e}; see https://margoengine.com/errors#${t}`, n = (n, r, i = n) => e(n, t(r, i)), r = (e, n) => TypeError(t(e, n)), i = (e, n) => RangeError(t(e, n));
|
|
6
|
+
//#endregion
|
|
7
|
+
export { i as n, r, n as t };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { WorkerPointerLockOptions } from './canvas.js';
|
|
2
|
+
/** What {@link transferCanvas} needs of a worker: a `Worker`, or anything with the same messages. */
|
|
3
|
+
export type CanvasWorker = Pick<Worker, 'postMessage' | 'addEventListener' | 'removeEventListener'>;
|
|
4
|
+
/** Options of {@link transferCanvas}. */
|
|
5
|
+
export interface TransferCanvasOptions {
|
|
6
|
+
/** Anything structured clone accepts, handed to the worker as `received.data`. Default undefined. */
|
|
7
|
+
data?: unknown;
|
|
8
|
+
/** Objects in `data` to transfer instead of copy. Default none. */
|
|
9
|
+
transfer?: Transferable[];
|
|
10
|
+
/** Aborts the wait for the worker; the canvas stays usable when it had not moved yet. Default none. */
|
|
11
|
+
signal?: AbortSignal;
|
|
12
|
+
/** Milliseconds to wait for the worker to call `receiveCanvas`, above 0. Default 30000. */
|
|
13
|
+
timeout?: number;
|
|
14
|
+
}
|
|
15
|
+
/** True when this page can hand a canvas to a worker. Check it to keep a main-thread path for older browsers. */
|
|
16
|
+
export declare const workerCanvasSupported: () => boolean;
|
|
17
|
+
/**
|
|
18
|
+
* The page's end of a canvas drawn by a worker, from {@link transferCanvas}. It keeps the worker told of the canvas's
|
|
19
|
+
* size, position, pixel ratio and visibility, and forwards the input events the worker listens for.
|
|
20
|
+
*/
|
|
21
|
+
export declare class WorkerCanvas {
|
|
22
|
+
/** The page's canvas. It shows what the worker draws and can no longer be drawn to from here. */
|
|
23
|
+
readonly canvas: HTMLCanvasElement;
|
|
24
|
+
/** The worker drawing it. It stays the caller's: `dispose` does not terminate it. */
|
|
25
|
+
readonly worker: CanvasWorker;
|
|
26
|
+
private readonly port;
|
|
27
|
+
[Symbol.dispose]: () => void;
|
|
28
|
+
/** True after `dispose`. */
|
|
29
|
+
disposed: boolean;
|
|
30
|
+
private readonly listening;
|
|
31
|
+
private readonly resizing;
|
|
32
|
+
private readonly closing;
|
|
33
|
+
private readonly lockRequests;
|
|
34
|
+
private readonly lockChanged;
|
|
35
|
+
private readonly lockError;
|
|
36
|
+
private ratio?;
|
|
37
|
+
/** The size and position the worker holds: the last ones posted, by a size message or an event. */
|
|
38
|
+
private sent;
|
|
39
|
+
/** Posts the size only when it differs from what the worker holds, so the observer's first call (fired on observe, with
|
|
40
|
+
* the size the canvas message already carried) and a pixel ratio change that also resizes cost no message. */
|
|
41
|
+
private readonly send;
|
|
42
|
+
private readonly ratioChanged;
|
|
43
|
+
private readonly visibility;
|
|
44
|
+
/** True while the page has locked the pointer to this canvas. */
|
|
45
|
+
get pointerLocked(): boolean;
|
|
46
|
+
/** Requests lock on the page. Call in a trusted user gesture; browser permission/activation rules still apply. */
|
|
47
|
+
requestPointerLock({ signal, timeout, unadjustedMovement, }?: WorkerPointerLockOptions): Promise<void>;
|
|
48
|
+
/** Releases this canvas's lock. Leaves another element's lock alone. */
|
|
49
|
+
exitPointerLock(): void;
|
|
50
|
+
private post;
|
|
51
|
+
/** A pixel ratio change is no resize (a window moved to another screen): one media query per ratio tells of it. */
|
|
52
|
+
private watchRatio;
|
|
53
|
+
private listen;
|
|
54
|
+
/**
|
|
55
|
+
* Stops forwarding and tells the worker: `received.signal` aborts there, and an engine attached to `received` is disposed.
|
|
56
|
+
* The canvas cannot be taken back, and the worker stays running until you call `worker.terminate()`.
|
|
57
|
+
*/
|
|
58
|
+
dispose(): void;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Moves drawing of `canvas` to `worker`, once the worker calls `receiveCanvas` from `@margoengine/worker/canvas`.
|
|
62
|
+
* Resolves when the worker holds the canvas. Rejects with `unsupported` where a canvas cannot move, `state` when this
|
|
63
|
+
* canvas already moved or has a context, `failed` when the worker fails to start, `timeout` when it never asks, or the
|
|
64
|
+
* signal's reason. Your own `postMessage` traffic with the worker is left alone.
|
|
65
|
+
*/
|
|
66
|
+
export declare function transferCanvas(canvas: HTMLCanvasElement, worker: CanvasWorker, { data, transfer, signal, timeout }?: TransferCanvasOptions): Promise<WorkerCanvas>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { n as e, r as t, t as n } from "./errors-CDgOgzCd.js";
|
|
2
|
+
//#region src/index.ts
|
|
3
|
+
var r = "margo-worker-canvas", i = /* @__PURE__ */ new Set([
|
|
4
|
+
"pointerdown",
|
|
5
|
+
"pointermove",
|
|
6
|
+
"pointerup",
|
|
7
|
+
"pointercancel",
|
|
8
|
+
"pointerenter",
|
|
9
|
+
"pointerleave",
|
|
10
|
+
"pointerover",
|
|
11
|
+
"pointerout",
|
|
12
|
+
"lostpointercapture",
|
|
13
|
+
"gotpointercapture",
|
|
14
|
+
"mousedown",
|
|
15
|
+
"mousemove",
|
|
16
|
+
"mouseup",
|
|
17
|
+
"click",
|
|
18
|
+
"dblclick",
|
|
19
|
+
"contextmenu",
|
|
20
|
+
"wheel",
|
|
21
|
+
"focus",
|
|
22
|
+
"blur"
|
|
23
|
+
]), a = /* @__PURE__ */ new Set(["keydown", "keyup"]), o = /* @__PURE__ */ new Set(["wheel", "contextmenu"]), s = /* @__PURE__ */ "altKey.button.buttons.clientX.clientY.code.ctrlKey.deltaMode.deltaX.deltaY.deltaZ.height.isPrimary.key.location.metaKey.movementX.movementY.offsetX.offsetY.pageX.pageY.pointerId.pointerType.pressure.repeat.screenX.screenY.shiftKey.tangentialPressure.tiltX.tiltY.twist.width.x.y".split("."), c = () => typeof Worker == "function" && typeof HTMLCanvasElement == "function" && "transferControlToOffscreen" in HTMLCanvasElement.prototype, l = class {
|
|
24
|
+
constructor(e, t, n) {
|
|
25
|
+
this.canvas = e, this.worker = t, this.port = n, this.disposed = !1, this.listening = /* @__PURE__ */ new Map(), this.closing = new AbortController(), this.lockRequests = /* @__PURE__ */ new Map(), this.lockChanged = () => this.post({
|
|
26
|
+
type: "pointerlock",
|
|
27
|
+
locked: this.pointerLocked
|
|
28
|
+
}), this.lockError = () => this.post({ type: "pointerlockerror" }), this.send = () => {
|
|
29
|
+
let e = this.size();
|
|
30
|
+
Object.keys(e).every((t) => Object.is(e[t], this.sent[t])) || (this.sent = { ...e }, this.post({
|
|
31
|
+
type: "size",
|
|
32
|
+
...e
|
|
33
|
+
}));
|
|
34
|
+
}, this.ratioChanged = () => {
|
|
35
|
+
this.watchRatio(), this.send();
|
|
36
|
+
}, this.visibility = () => this.post({
|
|
37
|
+
type: "hidden",
|
|
38
|
+
hidden: this.canvas.ownerDocument.visibilityState === "hidden"
|
|
39
|
+
}), n.onmessage = ({ data: e }) => {
|
|
40
|
+
if (e.listen) this.listen(e.listen);
|
|
41
|
+
else if (e.style) this.canvas.style.setProperty(e.style[0], e.style[1]);
|
|
42
|
+
else if (e.closed) this.dispose();
|
|
43
|
+
else if (e.pointerLock === "exit") this.exitPointerLock();
|
|
44
|
+
else if (e.pointerLock === "cancel") this.lockRequests.get(e.id)?.abort();
|
|
45
|
+
else if (e.pointerLock === "request") {
|
|
46
|
+
let t = new AbortController();
|
|
47
|
+
this.lockRequests.set(e.id, t), this.requestPointerLock({
|
|
48
|
+
...e.options,
|
|
49
|
+
signal: t.signal
|
|
50
|
+
}).then(() => this.post({
|
|
51
|
+
type: "lock-result",
|
|
52
|
+
id: e.id
|
|
53
|
+
}), (t) => this.post({
|
|
54
|
+
type: "lock-result",
|
|
55
|
+
id: e.id,
|
|
56
|
+
error: {
|
|
57
|
+
name: t?.name,
|
|
58
|
+
message: String(t?.message ?? t),
|
|
59
|
+
code: t?.code
|
|
60
|
+
}
|
|
61
|
+
})).finally(() => this.lockRequests.delete(e.id));
|
|
62
|
+
}
|
|
63
|
+
}, this.sent = this.size(), this.resizing = new ResizeObserver(this.send), this.resizing.observe(e), this.watchRatio(), e.ownerDocument.addEventListener("visibilitychange", this.visibility), e.ownerDocument.addEventListener("pointerlockchange", this.lockChanged), e.ownerDocument.addEventListener("pointerlockerror", this.lockError), this.lockChanged();
|
|
64
|
+
}
|
|
65
|
+
get pointerLocked() {
|
|
66
|
+
return this.canvas.ownerDocument.pointerLockElement === this.canvas;
|
|
67
|
+
}
|
|
68
|
+
requestPointerLock({ signal: t, timeout: r = 1e4, unadjustedMovement: i = !1 } = {}) {
|
|
69
|
+
return new Promise((a, o) => {
|
|
70
|
+
if (this.disposed) throw n("state", "Worker canvas disposed; transfer a new canvas", "worker");
|
|
71
|
+
if (typeof this.canvas.requestPointerLock != "function") throw n("unsupported", "Pointer lock unavailable in this browser", "worker");
|
|
72
|
+
if (!(r > 0 && Number.isFinite(r))) throw e("Pointer lock timeout must be finite and above zero", "worker");
|
|
73
|
+
let s = AbortSignal.any([this.closing.signal, ...t ? [t] : []]);
|
|
74
|
+
if (s.throwIfAborted(), this.pointerLocked) {
|
|
75
|
+
a();
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
let c = this.canvas.ownerDocument, l = (e) => {
|
|
79
|
+
clearTimeout(p), c.removeEventListener("pointerlockchange", u), c.removeEventListener("pointerlockerror", d), s.removeEventListener("abort", f), e === void 0 ? a() : o(e);
|
|
80
|
+
}, u = () => {
|
|
81
|
+
this.pointerLocked && l();
|
|
82
|
+
}, d = () => l(n("failed", "Pointer lock denied; request it from a trusted page gesture", "worker")), f = () => l(s.reason), p = setTimeout(() => l(n("timeout", "Pointer lock deadline exceeded; request from a trusted gesture", "worker")), r);
|
|
83
|
+
c.addEventListener("pointerlockchange", u), c.addEventListener("pointerlockerror", d), s.addEventListener("abort", f, { once: !0 });
|
|
84
|
+
try {
|
|
85
|
+
this.canvas.requestPointerLock({ unadjustedMovement: i })?.catch((e) => l(e));
|
|
86
|
+
} catch (e) {
|
|
87
|
+
l(e);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
exitPointerLock() {
|
|
92
|
+
this.pointerLocked && this.canvas.ownerDocument.exitPointerLock();
|
|
93
|
+
}
|
|
94
|
+
size() {
|
|
95
|
+
let { left: e, top: t } = this.canvas.getBoundingClientRect(), n = this.canvas.ownerDocument.defaultView;
|
|
96
|
+
return {
|
|
97
|
+
width: this.canvas.clientWidth,
|
|
98
|
+
height: this.canvas.clientHeight,
|
|
99
|
+
left: e,
|
|
100
|
+
top: t,
|
|
101
|
+
ratio: n?.devicePixelRatio,
|
|
102
|
+
low: globalThis.margoLow
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
post(e) {
|
|
106
|
+
this.disposed || this.port.postMessage(e);
|
|
107
|
+
}
|
|
108
|
+
watchRatio() {
|
|
109
|
+
let e = this.canvas.ownerDocument.defaultView;
|
|
110
|
+
this.ratio?.removeEventListener("change", this.ratioChanged), this.ratio = e?.matchMedia?.(`(resolution: ${e.devicePixelRatio}dppx)`), this.ratio?.addEventListener("change", this.ratioChanged);
|
|
111
|
+
}
|
|
112
|
+
listen(e) {
|
|
113
|
+
let t = a.has(e) ? this.canvas.ownerDocument : i.has(e) ? this.canvas : null;
|
|
114
|
+
if (!t) return;
|
|
115
|
+
let n = this.listening.get(t);
|
|
116
|
+
if (n || this.listening.set(t, n = /* @__PURE__ */ new Map()), n.has(e)) return;
|
|
117
|
+
let r = (t) => {
|
|
118
|
+
o.has(e) && t.preventDefault(), e === "pointerdown" && t.isTrusted && this.canvas.setPointerCapture(t.pointerId);
|
|
119
|
+
let n = {}, r = t;
|
|
120
|
+
for (let e of s) e in t && (n[e] = r[e]);
|
|
121
|
+
let { left: i, top: a } = this.canvas.getBoundingClientRect();
|
|
122
|
+
this.sent.left = i, this.sent.top = a, this.post({
|
|
123
|
+
type: "event",
|
|
124
|
+
name: e,
|
|
125
|
+
fields: n,
|
|
126
|
+
left: i,
|
|
127
|
+
top: a
|
|
128
|
+
});
|
|
129
|
+
}, c = e === "mousemove" ? (e) => {
|
|
130
|
+
this.pointerLocked || r(e);
|
|
131
|
+
} : r;
|
|
132
|
+
if (n.set(e, c), t.addEventListener(e, c, { passive: !o.has(e) }), e === "mousemove") {
|
|
133
|
+
let t = this.canvas.ownerDocument, n = this.listening.get(t);
|
|
134
|
+
n || this.listening.set(t, n = /* @__PURE__ */ new Map());
|
|
135
|
+
let i = (e) => {
|
|
136
|
+
this.pointerLocked && r(e);
|
|
137
|
+
};
|
|
138
|
+
n.set(e, i), t.addEventListener(e, i);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
dispose() {
|
|
142
|
+
if (!this.disposed) {
|
|
143
|
+
this.exitPointerLock(), this.closing.abort(), this.post({ type: "close" }), this.disposed = !0;
|
|
144
|
+
for (let [e, t] of this.listening) for (let [n, r] of t) e.removeEventListener(n, r);
|
|
145
|
+
this.listening.clear(), this.resizing.disconnect(), this.ratio?.removeEventListener("change", this.ratioChanged), this.canvas.ownerDocument.removeEventListener("visibilitychange", this.visibility), this.canvas.ownerDocument.removeEventListener("pointerlockchange", this.lockChanged), this.canvas.ownerDocument.removeEventListener("pointerlockerror", this.lockError), this.port.close();
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
[Symbol.dispose ?? Symbol()]() {
|
|
149
|
+
this.dispose();
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
function u(i, a, { data: o, transfer: s = [], signal: c, timeout: u = 3e4 } = {}) {
|
|
153
|
+
return new Promise((d, f) => {
|
|
154
|
+
if (typeof i?.transferControlToOffscreen != "function") throw n("unsupported", "transferCanvas needs a canvas element in a browser with OffscreenCanvas", "worker");
|
|
155
|
+
if (typeof a?.postMessage != "function") throw t("transferCanvas: expected a Worker", "worker");
|
|
156
|
+
if (!(u > 0 && u < Infinity)) throw e("transferCanvas: timeout above 0", "worker");
|
|
157
|
+
c?.throwIfAborted();
|
|
158
|
+
let p, m = () => {
|
|
159
|
+
clearTimeout(b), c?.removeEventListener("abort", g), a.removeEventListener("message", y), a.removeEventListener("error", _), a.removeEventListener("messageerror", _);
|
|
160
|
+
}, h = (e) => {
|
|
161
|
+
m(), f(e);
|
|
162
|
+
}, g = () => h(c.reason), _ = (e) => h(n("failed", `Worker failed before it took the canvas: ${e.message ?? "bad message"}`, "worker")), v = () => {
|
|
163
|
+
if (!p) try {
|
|
164
|
+
let { port1: e, port2: t } = new MessageChannel(), c;
|
|
165
|
+
try {
|
|
166
|
+
c = i.transferControlToOffscreen();
|
|
167
|
+
} catch (e) {
|
|
168
|
+
throw Object.assign(n("state", "This canvas has a context or already moved to a worker", "worker"), { cause: e });
|
|
169
|
+
}
|
|
170
|
+
p = new l(i, a, e), a.postMessage({
|
|
171
|
+
[r]: "canvas",
|
|
172
|
+
canvas: c,
|
|
173
|
+
port: t,
|
|
174
|
+
data: o,
|
|
175
|
+
...p.sent
|
|
176
|
+
}, [
|
|
177
|
+
c,
|
|
178
|
+
t,
|
|
179
|
+
...s
|
|
180
|
+
]);
|
|
181
|
+
} catch (e) {
|
|
182
|
+
p?.dispose(), h(e);
|
|
183
|
+
}
|
|
184
|
+
}, y = (e) => {
|
|
185
|
+
e.data?.[r] === "hello" ? v() : e.data?.[r] === "received" && (m(), d(p));
|
|
186
|
+
}, b = setTimeout(() => h(n("timeout", "The worker never called receiveCanvas", "worker")), u);
|
|
187
|
+
c?.addEventListener("abort", g), a.addEventListener("message", y), a.addEventListener("error", _), a.addEventListener("messageerror", _), a.postMessage({ [r]: "ask" });
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
//#endregion
|
|
191
|
+
export { l as WorkerCanvas, u as transferCanvas, c as workerCanvasSupported };
|
package/dist/rpc.d.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
type Arguments<T> = T extends (...args: infer A) => unknown ? A : never;
|
|
2
|
+
type Result<T> = T extends (...args: never[]) => infer R ? Awaited<R> : never;
|
|
3
|
+
type Method<T> = {
|
|
4
|
+
[K in keyof T]: T[K] extends (...args: never[]) => unknown ? K : never;
|
|
5
|
+
}[keyof T] & string;
|
|
6
|
+
/** A Worker, MessagePort, or worker global scope. Ports are started automatically; ownership stays with the caller. */
|
|
7
|
+
export interface RpcEndpoint {
|
|
8
|
+
/** Sends a structured-clone message, optionally moving ownership of its transferables. */
|
|
9
|
+
postMessage(message: unknown, transfer: Transferable[]): void;
|
|
10
|
+
/** Subscribes to messages and transport failures. */
|
|
11
|
+
addEventListener(type: string, listener: EventListener): void;
|
|
12
|
+
/** Removes a subscription installed by this entry. */
|
|
13
|
+
removeEventListener(type: string, listener: EventListener): void;
|
|
14
|
+
/** Starts a MessagePort; Worker endpoints need no start method. */
|
|
15
|
+
start?(): void;
|
|
16
|
+
}
|
|
17
|
+
/** Per-call cancellation and transport options. */
|
|
18
|
+
export interface RpcCallOptions {
|
|
19
|
+
/** Receives ordered progress messages before settlement. Default none. Exceptions reject and cancel the call. */
|
|
20
|
+
onProgress?: (value: unknown) => void;
|
|
21
|
+
/** Cancels queued or running work. Running handlers receive an aborted context signal. Default none. */
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
/** Input ownership moves only when dispatched. Default none. */
|
|
24
|
+
transfer?: Transferable[];
|
|
25
|
+
/** Hard response deadline in milliseconds, above zero. Default 30000. A timeout closes the client/pool. */
|
|
26
|
+
timeout?: number;
|
|
27
|
+
}
|
|
28
|
+
/** Context appended to each exposed handler's arguments. Cancellation is cooperative. */
|
|
29
|
+
export interface RpcContext {
|
|
30
|
+
/** Sends cloneable progress while the handler is active; optionally transfers owned buffers. */
|
|
31
|
+
progress(value: unknown, transfer?: Transferable[]): void;
|
|
32
|
+
/** Aborted on caller cancellation or server disposal. A synchronous loop must yield to receive cancellation. */
|
|
33
|
+
signal: AbortSignal;
|
|
34
|
+
}
|
|
35
|
+
/** Result plus ownership to move back to the caller. Construct with {@link rpcTransfer}. */
|
|
36
|
+
export interface RpcTransfer<T> {
|
|
37
|
+
/** Returned value, containing the objects in transfer. */
|
|
38
|
+
value: T;
|
|
39
|
+
/** Transferables whose ownership moves to the caller. */
|
|
40
|
+
transfer: Transferable[];
|
|
41
|
+
}
|
|
42
|
+
/** Adds a cancellation context to each typed method. Handlers may return values, promises, or transferred results. */
|
|
43
|
+
export type RpcHandlers<T> = {
|
|
44
|
+
[K in Method<T>]: (...args: [...Arguments<T[K]>, RpcContext]) => Result<T[K]> | RpcTransfer<Result<T[K]>> | PromiseLike<Result<T[K]> | RpcTransfer<Result<T[K]>>>;
|
|
45
|
+
};
|
|
46
|
+
/** Marks a handler's result for transfer rather than copy. Input transfer is specified in call options. */
|
|
47
|
+
export declare function rpcTransfer<T>(value: T, transfer: Transferable[]): RpcTransfer<T>;
|
|
48
|
+
/** Promise RPC over a caller-owned endpoint. Multiple clients can share one endpoint without ID collisions. */
|
|
49
|
+
export declare class RpcClient<T extends object> {
|
|
50
|
+
private readonly endpoint;
|
|
51
|
+
[Symbol.dispose]: () => void;
|
|
52
|
+
private readonly channel;
|
|
53
|
+
private readonly pending;
|
|
54
|
+
private next;
|
|
55
|
+
private closed?;
|
|
56
|
+
private readonly message;
|
|
57
|
+
private readonly failed;
|
|
58
|
+
/** Starts listening, without taking ownership of the worker or port. */
|
|
59
|
+
constructor(endpoint: RpcEndpoint);
|
|
60
|
+
/** True after disposal, timeout, or a transport failure. */
|
|
61
|
+
get disposed(): boolean;
|
|
62
|
+
/** Calls a named method with its typed arguments and promised result. */
|
|
63
|
+
call<K extends Method<T>>(method: K, args: Arguments<T[K]>, options?: RpcCallOptions): Promise<Result<T[K]>>;
|
|
64
|
+
private close;
|
|
65
|
+
/** Rejects pending calls, cancels handlers and removes listeners. Does not terminate the caller's worker. */
|
|
66
|
+
dispose(): void;
|
|
67
|
+
}
|
|
68
|
+
/** Exposes only own, named functions on an endpoint. Returns a disposable server; unrelated messages are untouched. */
|
|
69
|
+
export declare function exposeRpc<T extends object>(handlers: RpcHandlers<T>, endpoint?: RpcEndpoint): {
|
|
70
|
+
dispose(): void;
|
|
71
|
+
[Symbol.dispose](): void;
|
|
72
|
+
};
|
|
73
|
+
/** Sized pool configuration. Workers are created once and owned by the pool. */
|
|
74
|
+
export interface RpcPoolOptions {
|
|
75
|
+
/** Concurrent workers, a positive integer. Default 2. */
|
|
76
|
+
size?: number;
|
|
77
|
+
/** Maximum waiting jobs; running jobs do not count. Default 1024. */
|
|
78
|
+
maxQueue?: number;
|
|
79
|
+
}
|
|
80
|
+
/** FIFO task pool with a fixed worker count, backpressure, input/output transfer and cooperative cancellation. */
|
|
81
|
+
export declare class RpcPool<T extends object> {
|
|
82
|
+
[Symbol.dispose]: () => void;
|
|
83
|
+
private readonly slots;
|
|
84
|
+
private readonly queue;
|
|
85
|
+
private closed;
|
|
86
|
+
private readonly maxQueue;
|
|
87
|
+
/** Creates `size` workers using the factory. A creation failure cleans up all workers already created. */
|
|
88
|
+
constructor(factory: (index: number) => RpcEndpoint & {
|
|
89
|
+
terminate(): unknown;
|
|
90
|
+
}, { size, maxQueue }?: RpcPoolOptions);
|
|
91
|
+
/** Number of workers, fixed at construction. */
|
|
92
|
+
get size(): number;
|
|
93
|
+
/** Number of calls waiting for a worker. */
|
|
94
|
+
get queued(): number;
|
|
95
|
+
/** Schedules one call. Cancellation before dispatch leaves transferables attached to the caller. */
|
|
96
|
+
call<K extends Method<T>>(method: K, args: Arguments<T[K]>, options?: RpcCallOptions): Promise<Result<T[K]>>;
|
|
97
|
+
private drain;
|
|
98
|
+
/** Cancels all queued/running calls and terminates every owned worker, idempotently. */
|
|
99
|
+
dispose(): void;
|
|
100
|
+
}
|
|
101
|
+
export {};
|
package/dist/rpc.js
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { n as e, t } from "./errors-CDgOgzCd.js";
|
|
2
|
+
//#region src/rpc.ts
|
|
3
|
+
var n = "margo-worker-rpc", r = Symbol("rpc-transfer");
|
|
4
|
+
function i(e, t) {
|
|
5
|
+
return {
|
|
6
|
+
[r]: !0,
|
|
7
|
+
value: e,
|
|
8
|
+
transfer: t
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
var a = (t) => {
|
|
12
|
+
if (!(t > 0 && Number.isFinite(t))) throw e("RPC timeout must be finite and above zero", "worker");
|
|
13
|
+
return t;
|
|
14
|
+
}, o = (e) => {
|
|
15
|
+
let t = e;
|
|
16
|
+
return {
|
|
17
|
+
name: typeof t?.name == "string" ? t.name : "Error",
|
|
18
|
+
message: typeof t?.message == "string" ? t.message : String(e),
|
|
19
|
+
...typeof t?.code == "string" ? { code: t.code } : {},
|
|
20
|
+
...typeof t?.stack == "string" ? { stack: t.stack } : {}
|
|
21
|
+
};
|
|
22
|
+
}, s = class {
|
|
23
|
+
constructor(e) {
|
|
24
|
+
this.endpoint = e, this.channel = crypto.randomUUID(), this.pending = /* @__PURE__ */ new Map(), this.next = 0, this.message = ((e) => {
|
|
25
|
+
let t = e.data;
|
|
26
|
+
t?.tag === n && t.channel === this.channel && (t.type === "progress" ? this.pending.get(t.id)?.progress(t.value) : t.type === "result" && this.pending.get(t.id)?.finish(t.value, t.error && Object.assign(Error(t.error.message), t.error)));
|
|
27
|
+
}), this.failed = (() => this.close(t("failed", "RPC transport failed; create a new client", "worker"))), e.addEventListener("message", this.message), e.addEventListener("error", this.failed), e.addEventListener("messageerror", this.failed), e.start?.();
|
|
28
|
+
}
|
|
29
|
+
get disposed() {
|
|
30
|
+
return this.closed !== void 0;
|
|
31
|
+
}
|
|
32
|
+
call(e, t, n = {}) {
|
|
33
|
+
return this.dispatch(e, t, n).result;
|
|
34
|
+
}
|
|
35
|
+
dispatch(e, r, { signal: i, transfer: o = [], timeout: s = 3e4, onProgress: c }) {
|
|
36
|
+
let l, u = new Promise((e) => {
|
|
37
|
+
l = e;
|
|
38
|
+
});
|
|
39
|
+
return {
|
|
40
|
+
result: new Promise((u, d) => {
|
|
41
|
+
if (this.disposed) {
|
|
42
|
+
l(), d(this.closed);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (i?.aborted) {
|
|
46
|
+
l(), d(i.reason);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
let f;
|
|
50
|
+
try {
|
|
51
|
+
f = a(s);
|
|
52
|
+
} catch (e) {
|
|
53
|
+
l(), d(e);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
let p = ++this.next, m = (e) => this.endpoint.postMessage({
|
|
57
|
+
tag: n,
|
|
58
|
+
channel: this.channel,
|
|
59
|
+
type: e,
|
|
60
|
+
id: p
|
|
61
|
+
}, []), h = () => {
|
|
62
|
+
d(i.reason);
|
|
63
|
+
try {
|
|
64
|
+
m("cancel");
|
|
65
|
+
} catch (e) {
|
|
66
|
+
this.close(e);
|
|
67
|
+
}
|
|
68
|
+
}, g = setTimeout(() => this.close(t("timeout", "RPC response deadline exceeded; create a new client", "worker")), f), _ = (e, t) => {
|
|
69
|
+
clearTimeout(g), i?.removeEventListener("abort", h), this.pending.delete(p), l(), t === void 0 ? u(e) : d(t);
|
|
70
|
+
}, v = !1;
|
|
71
|
+
this.pending.set(p, {
|
|
72
|
+
finish: _,
|
|
73
|
+
cancel: () => m("cancel"),
|
|
74
|
+
progress: (e) => {
|
|
75
|
+
if (!(v || i?.aborted)) try {
|
|
76
|
+
c?.(e);
|
|
77
|
+
} catch (e) {
|
|
78
|
+
v = !0, d(e);
|
|
79
|
+
try {
|
|
80
|
+
m("cancel");
|
|
81
|
+
} catch (e) {
|
|
82
|
+
this.close(e);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}), i?.addEventListener("abort", h, { once: !0 });
|
|
87
|
+
try {
|
|
88
|
+
this.endpoint.postMessage({
|
|
89
|
+
tag: n,
|
|
90
|
+
channel: this.channel,
|
|
91
|
+
type: "call",
|
|
92
|
+
id: p,
|
|
93
|
+
method: e,
|
|
94
|
+
args: r
|
|
95
|
+
}, o);
|
|
96
|
+
} catch (e) {
|
|
97
|
+
_(void 0, e);
|
|
98
|
+
}
|
|
99
|
+
}),
|
|
100
|
+
done: u
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
close(e) {
|
|
104
|
+
if (!this.disposed) {
|
|
105
|
+
this.closed = e, this.endpoint.removeEventListener("message", this.message), this.endpoint.removeEventListener("error", this.failed), this.endpoint.removeEventListener("messageerror", this.failed);
|
|
106
|
+
for (let t of this.pending.values()) {
|
|
107
|
+
try {
|
|
108
|
+
t.cancel();
|
|
109
|
+
} catch {}
|
|
110
|
+
t.finish(void 0, e);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
dispose() {
|
|
115
|
+
this.close(t("state", "RPC client disposed; create a new client", "worker"));
|
|
116
|
+
}
|
|
117
|
+
[Symbol.dispose ?? Symbol()]() {
|
|
118
|
+
this.dispose();
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
function c(e, i = globalThis) {
|
|
122
|
+
let a = /* @__PURE__ */ new Map(), s = ((s) => {
|
|
123
|
+
let c = s.data;
|
|
124
|
+
if (c?.tag !== n || typeof c.channel != "string" || !Number.isSafeInteger(c.id)) return;
|
|
125
|
+
let l = `${c.channel}:${c.id}`;
|
|
126
|
+
if (c.type === "cancel") {
|
|
127
|
+
a.get(l)?.controller.abort();
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (c.type !== "call" || a.has(l)) return;
|
|
131
|
+
let u = new AbortController(), d = (e, t) => {
|
|
132
|
+
if (!a.delete(l)) return;
|
|
133
|
+
let s = e && typeof e == "object" && r in e ? e : void 0;
|
|
134
|
+
try {
|
|
135
|
+
i.postMessage({
|
|
136
|
+
tag: n,
|
|
137
|
+
channel: c.channel,
|
|
138
|
+
id: c.id,
|
|
139
|
+
type: "result",
|
|
140
|
+
value: s ? s.value : e,
|
|
141
|
+
...t === void 0 ? {} : { error: o(t) }
|
|
142
|
+
}, s?.transfer ?? []);
|
|
143
|
+
} catch (e) {
|
|
144
|
+
i.postMessage({
|
|
145
|
+
tag: n,
|
|
146
|
+
channel: c.channel,
|
|
147
|
+
id: c.id,
|
|
148
|
+
type: "result",
|
|
149
|
+
error: o(e)
|
|
150
|
+
}, []);
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
a.set(l, {
|
|
154
|
+
controller: u,
|
|
155
|
+
reply: d
|
|
156
|
+
}), (async () => {
|
|
157
|
+
try {
|
|
158
|
+
if (!Object.hasOwn(e, c.method) || typeof e[c.method] != "function") throw t("state", `Unknown RPC method ${c.method}; expose a named handler`, "worker");
|
|
159
|
+
if (!Array.isArray(c.args)) throw t("state", "RPC arguments must be an array", "worker");
|
|
160
|
+
let r = e[c.method], o = (e, t = []) => {
|
|
161
|
+
a.has(l) && !u.signal.aborted && i.postMessage({
|
|
162
|
+
tag: n,
|
|
163
|
+
channel: c.channel,
|
|
164
|
+
id: c.id,
|
|
165
|
+
type: "progress",
|
|
166
|
+
value: e
|
|
167
|
+
}, t);
|
|
168
|
+
}, s = await r.apply(e, [...c.args, {
|
|
169
|
+
signal: u.signal,
|
|
170
|
+
progress: o
|
|
171
|
+
}]);
|
|
172
|
+
d(s);
|
|
173
|
+
} catch (e) {
|
|
174
|
+
d(void 0, o(e));
|
|
175
|
+
}
|
|
176
|
+
})();
|
|
177
|
+
});
|
|
178
|
+
i.addEventListener("message", s), i.start?.();
|
|
179
|
+
let c = () => {
|
|
180
|
+
i.removeEventListener("message", s);
|
|
181
|
+
for (let e of a.values()) e.controller.abort(), e.reply(void 0, t("state", "RPC server disposed; expose a new server", "worker"));
|
|
182
|
+
};
|
|
183
|
+
return {
|
|
184
|
+
dispose: c,
|
|
185
|
+
[Symbol.dispose]: c
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
var l = class {
|
|
189
|
+
constructor(t, { size: n = 2, maxQueue: r = 1024 } = {}) {
|
|
190
|
+
if (this.slots = [], this.queue = [], this.closed = !1, !Number.isSafeInteger(n) || n < 1 || !Number.isSafeInteger(r) || r < 0) throw e("RPC pool needs a positive size and nonnegative maxQueue", "worker");
|
|
191
|
+
this.maxQueue = r;
|
|
192
|
+
try {
|
|
193
|
+
for (let e = 0; e < n; e++) {
|
|
194
|
+
let n = t(e);
|
|
195
|
+
this.slots.push({
|
|
196
|
+
worker: n,
|
|
197
|
+
client: new s(n),
|
|
198
|
+
busy: !1
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
} catch (e) {
|
|
202
|
+
throw this.dispose(), e;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
get size() {
|
|
206
|
+
return this.slots.length;
|
|
207
|
+
}
|
|
208
|
+
get queued() {
|
|
209
|
+
return this.queue.length;
|
|
210
|
+
}
|
|
211
|
+
call(e, n, r = {}) {
|
|
212
|
+
return new Promise((i, o) => {
|
|
213
|
+
if (this.closed) throw t("state", "RPC pool disposed; create a new pool", "worker");
|
|
214
|
+
r.signal?.throwIfAborted();
|
|
215
|
+
let s = a(r.timeout ?? 3e4);
|
|
216
|
+
if (this.slots.every((e) => e.busy) && this.queue.length >= this.maxQueue) throw t("state", "RPC pool queue is full; await a task before submitting more", "worker");
|
|
217
|
+
let c = Date.now(), l = () => {
|
|
218
|
+
clearTimeout(p), r.signal?.removeEventListener("abort", d);
|
|
219
|
+
}, u = (e) => {
|
|
220
|
+
let t = this.queue.indexOf(f);
|
|
221
|
+
t >= 0 && this.queue.splice(t, 1), l(), o(e);
|
|
222
|
+
}, d = () => u(r.signal.reason), f = {
|
|
223
|
+
reject: u,
|
|
224
|
+
run: (t) => {
|
|
225
|
+
l();
|
|
226
|
+
let a = t.dispatch(e, n, {
|
|
227
|
+
...r,
|
|
228
|
+
timeout: Math.max(1, s - (Date.now() - c))
|
|
229
|
+
});
|
|
230
|
+
a.result.then(i, o), a.done.then(() => {
|
|
231
|
+
let e = this.slots.find((e) => e.client === t);
|
|
232
|
+
e.busy = !1, e.client.disposed ? this.dispose() : this.drain();
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
}, p = setTimeout(() => u(t("timeout", "RPC queue deadline exceeded; submit less work", "worker")), s);
|
|
236
|
+
r.signal?.addEventListener("abort", d, { once: !0 }), this.queue.push(f), this.drain();
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
drain() {
|
|
240
|
+
if (!this.closed) for (let e of this.slots) !e.busy && this.queue.length && (e.busy = !0, this.queue.shift().run(e.client));
|
|
241
|
+
}
|
|
242
|
+
dispose() {
|
|
243
|
+
if (!this.closed) {
|
|
244
|
+
this.closed = !0;
|
|
245
|
+
for (let e of [...this.queue]) e.reject(t("state", "RPC pool disposed; create a new pool", "worker"));
|
|
246
|
+
for (let e of this.slots) e.client.dispose(), e.worker.terminate();
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
[Symbol.dispose ?? Symbol()]() {
|
|
250
|
+
this.dispose();
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
//#endregion
|
|
254
|
+
export { s as RpcClient, l as RpcPool, c as exposeRpc, i as rpcTransfer };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
2
|
+
/** A scene's shared environment, identical on page and worker apart from mode. */
|
|
3
|
+
export interface SceneContext {
|
|
4
|
+
/** Page canvas or the worker's forwarded OffscreenCanvas element facade. */
|
|
5
|
+
canvas: HTMLCanvasElement;
|
|
6
|
+
/** User data, structured cloned for the worker and passed directly on the page. */
|
|
7
|
+
data: unknown;
|
|
8
|
+
/** Lifetime cancellation, aborted on startup cancellation and disposal. */
|
|
9
|
+
signal: AbortSignal;
|
|
10
|
+
/** Where this instance is running. */
|
|
11
|
+
mode: 'worker' | 'page';
|
|
12
|
+
/** Ties an engine to canvas visibility and lifetime. */
|
|
13
|
+
attach(engine: EngineKernel): void;
|
|
14
|
+
}
|
|
15
|
+
/** Scene instance cleanup, optionally asynchronous. */
|
|
16
|
+
export interface SceneInstance {
|
|
17
|
+
/** Releases scene resources. Called once by the scene owner. */
|
|
18
|
+
dispose(): void | Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
/** A module URL must export createScene with this shape. The same module is loaded on either thread. */
|
|
21
|
+
export interface SceneModule {
|
|
22
|
+
/** Starts this scene, returning its cleanup owner. */
|
|
23
|
+
createScene(context: SceneContext): SceneInstance | Promise<SceneInstance>;
|
|
24
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(function(){var e=(e,t)=>Object.assign(Error(t),{name:`MargoError`,code:e}),t=(e,t)=>`${e}; see https://margoengine.com/errors#${t}`,n=(n,r,i=n)=>e(n,t(r,i)),r=(e,n)=>RangeError(t(e,n)),i=`margo-worker-canvas`,a=()=>globalThis,o=class{constructor(e,t,n,r){this.canvas=e,this.data=t,this.port=n,this.hidden=!1,this.closing=new AbortController,this.captured=new Set,this.listened=new Set,this.locks=new Map,this.nextLock=0,this.locked=!1,this.resuming=!1,this.rect={width:0,height:0,left:0,top:0},this.resize(r);let i=e.addEventListener.bind(e),a=e=>this.send(e),o=this.captured;Object.defineProperties(e,{clientWidth:{get:()=>this.rect.width},clientHeight:{get:()=>this.rect.height},style:{value:new Proxy({},{get:(e,t)=>e[t]??``,set(e,t,n){return e[t]=n,a({style:[t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`),n]}),!0}})},getBoundingClientRect:{value:()=>{let{left:e,top:t,width:n,height:r}=this.rect;return{left:e,top:t,width:n,height:r,x:e,y:t,right:e+n,bottom:t+r}}},setPointerCapture:{value:e=>o.add(e)},releasePointerCapture:{value:e=>o.delete(e)},hasPointerCapture:{value:e=>o.has(e)},requestPointerLock:{value:e=>this.requestPointerLock(e)},exitPointerLock:{value:()=>this.exitPointerLock()},pointerLockElement:{get:()=>this.locked?e:null},addEventListener:{value:(e,...t)=>{this.listened.has(e)||(this.listened.add(e),a({listen:e})),i(e,...t)}}}),n.onmessage=({data:t})=>{t.type===`event`?this.dispatch(t):t.type===`size`?this.resize(t):t.type===`hidden`?this.setHidden(t.hidden):t.type===`close`?this.close():t.type===`pointerlock`?(this.locked=t.locked,e.dispatchEvent(new Event(`pointerlockchange`))):t.type===`pointerlockerror`?e.dispatchEvent(new Event(`pointerlockerror`)):t.type===`lock-result`&&this.locks.get(t.id)?.finish(t.error&&Object.assign(Error(t.error.message),t.error))}}get signal(){return this.closing.signal}get pointerLocked(){return this.locked}requestPointerLock({signal:e,timeout:t=1e4,unadjustedMovement:i=!1}={}){return new Promise((a,o)=>{let s=AbortSignal.any([this.signal,...e?[e]:[]]);if(s.throwIfAborted(),!(t>0&&Number.isFinite(t)))throw r(`Pointer lock timeout must be finite and above zero`,`worker`);let c=++this.nextLock,l=e=>{clearTimeout(d),s.removeEventListener(`abort`,u),this.locks.delete(c),e===void 0?a():o(e)},u=()=>{this.send({pointerLock:`cancel`,id:c}),l(s.reason)},d=setTimeout(()=>{this.send({pointerLock:`cancel`,id:c}),l(n(`timeout`,`Pointer lock response deadline exceeded; check the page connection`,`worker`))},t);this.locks.set(c,{finish:l}),s.addEventListener(`abort`,u,{once:!0});try{this.send({pointerLock:`request`,id:c,options:{timeout:t,unadjustedMovement:i}})}catch(e){l(e)}})}exitPointerLock(){this.send({pointerLock:`exit`})}send(e){this.closing.signal.aborted||this.port.postMessage(e)}resize({width:e,height:t,left:n,top:r,ratio:i,low:o}){this.rect={width:e,height:t,left:n,top:r};let s=a();i&&(s.devicePixelRatio=i),o!==void 0&&(s.margoLow=o)}dispatch({name:e,fields:t,left:n,top:r}){this.rect.left=n,this.rect.top=r,this.canvas.dispatchEvent(Object.assign(new Event(e,{cancelable:!0}),t))}setHidden(e){let t=this.hidden&&!e,n=this.engine;if(this.hidden=e,!t||!n||this.resuming)return;let r=n.maxDelta;this.resuming=!0,n.maxDelta=0;let i=n.onFrame(()=>{i(),n.maxDelta=r,this.resuming=!1})}close(){let e=this.engine;this.dispose(),e&&!e.disposed&&e.dispose()}attach(e){return e.use({name:`worker-canvas`,setup(){},dispose:()=>this.dispose()}),this.engine=e,this}dispose(){this.closing.signal.aborted||(this.send({closed:!0}),this.closing.abort(),this.locked&&(this.locked=!1,this.canvas.dispatchEvent(new Event(`pointerlockchange`))),this.engine=void 0,this.port.close())}[Symbol.dispose??Symbol()](){this.dispose()}};function s({signal:e,timeout:t=3e4}={}){return new Promise((s,c)=>{if(!(t>0&&t<1/0))throw r(`receiveCanvas: timeout above 0`,`worker`);e?.throwIfAborted();let l=a(),u=()=>{clearTimeout(p),e?.removeEventListener(`abort`,d),l.removeEventListener(`message`,f)},d=()=>{u(),c(e.reason)},f=e=>{let t=e.data;if(t?.[i]===`ask`)l.postMessage({[i]:`hello`});else if(t?.[i]===`canvas`){u();let e=new o(t.canvas,t.data,t.port,t);l.postMessage({[i]:`received`}),s(e)}},p=setTimeout(()=>{u(),c(n(`timeout`,`The page never called transferCanvas`,`worker`))},t);e?.addEventListener(`abort`,d),l.addEventListener(`message`,f),l.postMessage({[i]:`hello`})})}var c=`margo-worker-rpc`,l=Symbol(`rpc-transfer`),u=e=>{let t=e;return{name:typeof t?.name==`string`?t.name:`Error`,message:typeof t?.message==`string`?t.message:String(e),...typeof t?.code==`string`?{code:t.code}:{},...typeof t?.stack==`string`?{stack:t.stack}:{}}};function d(e,t=globalThis){let r=new Map,i=(i=>{let a=i.data;if(a?.tag!==c||typeof a.channel!=`string`||!Number.isSafeInteger(a.id))return;let o=`${a.channel}:${a.id}`;if(a.type===`cancel`){r.get(o)?.controller.abort();return}if(a.type!==`call`||r.has(o))return;let s=new AbortController,d=(e,n)=>{if(!r.delete(o))return;let i=e&&typeof e==`object`&&l in e?e:void 0;try{t.postMessage({tag:c,channel:a.channel,id:a.id,type:`result`,value:i?i.value:e,...n===void 0?{}:{error:u(n)}},i?.transfer??[])}catch(e){t.postMessage({tag:c,channel:a.channel,id:a.id,type:`result`,error:u(e)},[])}};r.set(o,{controller:s,reply:d}),(async()=>{try{if(!Object.hasOwn(e,a.method)||typeof e[a.method]!=`function`)throw n(`state`,`Unknown RPC method ${a.method}; expose a named handler`,`worker`);if(!Array.isArray(a.args))throw n(`state`,`RPC arguments must be an array`,`worker`);let i=e[a.method],l=(e,n=[])=>{r.has(o)&&!s.signal.aborted&&t.postMessage({tag:c,channel:a.channel,id:a.id,type:`progress`,value:e},n)},u=await i.apply(e,[...a.args,{signal:s.signal,progress:l}]);d(u)}catch(e){d(void 0,u(e))}})()});t.addEventListener(`message`,i),t.start?.();let a=()=>{t.removeEventListener(`message`,i);for(let e of r.values())e.controller.abort(),e.reply(void 0,n(`state`,`RPC server disposed; expose a new server`,`worker`))};return{dispose:a,[Symbol.dispose]:a}}var f=e=>import(e),p=(e,t)=>({canvas:e.canvas,data:e.data,signal:t,mode:`worker`,attach:t=>{e.attach(t)}}),m,h,g,_=!1,v=!1,y=new AbortController,b=async e=>{if(typeof OffscreenCanvas!=`function`||typeof requestAnimationFrame!=`function`)return!1;if(e!==`webgl2`&&typeof navigator.gpu?.requestAdapter==`function`&&await navigator.gpu.requestAdapter())return!0;if(e===`webgpu`)return!1;let t=new OffscreenCanvas(1,1).getContext(`webgl2`);return t?.getExtension(`WEBGL_lose_context`)?.loseContext(),!!t};d({async prepare(e,t){if(_)throw n(`state`,`Scene worker already prepared; create a new scene`,`worker`);if(_=!0,!await b(t))return!1;if(m=await f(e),typeof m.createScene!=`function`)throw n(`state`,`Scene module must export createScene`,`worker`);return h=s({signal:y.signal}),h.catch(()=>{}),!0},async start({signal:e}){if(!m||!h||v)throw n(`state`,`Prepare a new worker scene before starting`,`worker`);v=!0;let t=await h,r=AbortSignal.any([e,y.signal,t.signal]);g=await m.createScene(p(t,r)),r.aborted&&(await g.dispose(),g=void 0,r.throwIfAborted())},async dispose(){y.abort();let e=g;g=void 0;try{await e?.dispose()}finally{h&&(await h).dispose()}}})})();
|