Files
pyscript/pyscript.core/esm/worker/_template.js
Andrea Giammarchi 339e40063a WIP: Bringing PyScript.next PoC to the main project (#1507)
* kill unwrapped_remote (#1490)

* kill unwrapped_remote

* linting

* don't use callKwargs for python plugins

* fix tests and improve types

* Bringing PyScript.next PoC to the main project

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Madhur Tandon <20173739+madhur-tandon@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-06-05 21:52:28 +02:00

54 lines
1.8 KiB
JavaScript

// ⚠️ This file is used to generate xworker.js
// That means if any import is circular or brings in too much
// that would be a higher payload for every worker.
// Please check via `npm run size` that worker code is not much
// bigger than it used to be before any changes is applied to this file.
import { registry } from "../runtimes.js";
import { getRuntime, getRuntimeID } from "../loader.js";
let engine, run, runtimeEvent;
const add = (type, fn) => {
addEventListener(
type,
fn ||
(async (event) => {
const runtime = await engine;
runtimeEvent = event;
run(runtime, `xworker.on${type}(xworker.event);`, xworker);
}),
!!fn && { once: true },
);
};
const xworker = {
onerror() {},
onmessage() {},
onmessageerror() {},
postMessage: postMessage.bind(self),
// this getter exists so that arbitrarily access to xworker.event
// would always fail once an event has been dispatched, as that's not
// meant to be accessed in the wild, respecting the one-off event nature of JS.
get event() {
const event = runtimeEvent;
if (!event) throw new Error("Unauthorized event access");
runtimeEvent = void 0;
return event;
},
};
add("message", ({ data: { options, code } }) => {
engine = (async () => {
const { type, version, config, async: isAsync } = options;
const engine = await getRuntime(getRuntimeID(type, version), config);
const details = registry.get(type);
(run = details[`runWorker${isAsync ? "Async" : ""}`].bind(details))(
engine,
code,
(globalThis.xworker = xworker),
);
return engine;
})();
add("error");
add("message");
add("messageerror");
});