-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsandboxRunner.ts
More file actions
33 lines (30 loc) · 1.02 KB
/
Copy pathsandboxRunner.ts
File metadata and controls
33 lines (30 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import type { SandboxWorkerRequest, SandboxWorkerResponse } from "@/types/sandbox";
let worker: Worker | null = null;
let nextId = 1;
function getWorker(): Worker {
if (!worker) {
worker = new Worker(new URL("../workers/sandbox.worker.ts", import.meta.url), {
type: "module",
});
}
return worker;
}
/**
* Evaluates a numeric expression off the main thread (module worker).
* The worker only runs {@link evaluateSafeNumericExpression}; no general JS execution.
*/
export function evaluateInSandbox(expr: string): Promise<number> {
const id = nextId++;
const w = getWorker();
return new Promise((resolve, reject) => {
const handler = (ev: MessageEvent<SandboxWorkerResponse>) => {
if (ev.data.id !== id) return;
w.removeEventListener("message", handler);
if (ev.data.ok) resolve(ev.data.value);
else reject(new Error(ev.data.error));
};
w.addEventListener("message", handler);
const req: SandboxWorkerRequest = { id, type: "eval", expr };
w.postMessage(req);
});
}