diff --git a/src/renderer/src/worker/eval.ts b/src/renderer/src/worker/eval.ts index a14bd0ed..abbf2635 100644 --- a/src/renderer/src/worker/eval.ts +++ b/src/renderer/src/worker/eval.ts @@ -1,8 +1,28 @@ -const workerUrl = new URL('evalWorker.js', import.meta.url); +import invariant from 'tiny-invariant'; + +// https://github.com/vitejs/vite/issues/11823#issuecomment-1407277242 +// https://github.com/mifi/lossless-cut/issues/2059 +import Worker from './evalWorker?worker'; + + +export interface RequestMessageData { + code: string, + id: number, + context: string // json +} + +export type ResponseMessageData = { id: number } & ({ + error: string, +} | { + data: unknown, +}) // https://v3.vitejs.dev/guide/features.html#web-workers // todo terminate() and recreate in case of error? -const worker = new Worker(workerUrl); +const worker = new Worker(); +worker.addEventListener('error', (err) => { + console.error('evalWorker error', err); +}); let lastRequestId = 0; @@ -22,13 +42,17 @@ export default async function safeishEval(code: string, context: Record { + onmessage = (event: MessageEvent) => { // eslint-disable-next-line strict, lines-around-directive 'use strict'; @@ -130,9 +135,9 @@ myGlobal.fetch = undefined; // https://stackoverflow.com/questions/8403108/calling-eval-in-particular-context // eslint-disable-next-line unicorn/new-for-builtins, no-new-func const result = Function(`\nwith (this) { return (${code}); }`).call(context); - postMessage({ id, data: result }); + postMessage({ id, data: result } satisfies ResponseMessageData); } catch (e) { - postMessage({ id, error: `${e}` }); + postMessage({ id, error: `${e}` } satisfies ResponseMessageData); } }; })(); diff --git a/tsconfig.web.json b/tsconfig.web.json index 56a2e8c4..3eb0d857 100644 --- a/tsconfig.web.json +++ b/tsconfig.web.json @@ -5,6 +5,8 @@ "noEmit": true, "noImplicitAny": false, // todo + + "types": ["vite/client"], }, "references": [ { "path": "./tsconfig.main.json" },