结论:浏览器 Worker 已支持可插拔 Python runtime provider 的 line I/O,缺真实 Python/WASM runtime 时仍保持阻塞不解锁。
68 lines
2.0 KiB
JavaScript
68 lines
2.0 KiB
JavaScript
function postReply(id, type, payload) {
|
|
self.postMessage({ id, type, ok: true, ...payload });
|
|
}
|
|
|
|
function postError(id, type, error) {
|
|
self.postMessage({
|
|
id,
|
|
type,
|
|
ok: false,
|
|
error: error?.message ?? String(error),
|
|
});
|
|
}
|
|
|
|
function pythonRuntimeAvailable() {
|
|
return typeof self.loadPyodide === "function" || Boolean(self.pyodide?.runPythonAsync);
|
|
}
|
|
|
|
function getRuntimeProvider() {
|
|
return self.linuxCncToolDbPythonRuntimeProvider ?? null;
|
|
}
|
|
|
|
self.addEventListener("message", async (event) => {
|
|
const message = event.data ?? {};
|
|
const { id, type, line } = message;
|
|
try {
|
|
if (type === "start") {
|
|
const provider = getRuntimeProvider();
|
|
const providerReady = Boolean(provider?.start && provider?.writeLine && provider?.readLine);
|
|
const ready = providerReady || pythonRuntimeAvailable();
|
|
if (providerReady) {
|
|
await provider.start(message);
|
|
}
|
|
postReply(id, type, {
|
|
runtimeMode: "browser-python-wasm-worker",
|
|
runtimeExecutionReady: ready,
|
|
status: ready
|
|
? "browser_python_wasm_runtime_ready"
|
|
: "blocked_browser_python_wasm_runtime_missing",
|
|
executionEnabled: false,
|
|
promotionAllowed: false,
|
|
});
|
|
return;
|
|
}
|
|
const provider = getRuntimeProvider();
|
|
if (type === "writeLine" && provider?.writeLine) {
|
|
await provider.writeLine(line);
|
|
postReply(id, type, { executionEnabled: false, promotionAllowed: false });
|
|
return;
|
|
}
|
|
if (type === "readLine" && provider?.readLine) {
|
|
postReply(id, type, {
|
|
line: await provider.readLine(),
|
|
executionEnabled: false,
|
|
promotionAllowed: false,
|
|
});
|
|
return;
|
|
}
|
|
if (type === "close" && provider?.close) {
|
|
await provider.close();
|
|
postReply(id, type, { executionEnabled: false, promotionAllowed: false });
|
|
return;
|
|
}
|
|
throw new Error("blocked_browser_python_wasm_runtime_missing");
|
|
} catch (error) {
|
|
postError(id, type, error);
|
|
}
|
|
});
|