-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
299 lines (271 loc) · 9.63 KB
/
worker.js
File metadata and controls
299 lines (271 loc) · 9.63 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/**
* Nuilith Worker: Python Engine
* This worker encapsulates the Pyodide WebAssembly runtime.
* It is isolated from the main thread to ensure that long-running
* Python scripts do not lock the user interface.
*/
importScripts("https://cdn.jsdelivr.net/pyodide/v0.27.0/full/pyodide.js");
let pyodide = null;
// Helper to send messages to UI without DataCloneErrors
function postToUI(type, text) {
self.postMessage({ type: type, text: String(text) });
}
/**
* Initializes the Python environment by loading Pyodide and micropip.
* Sends a READY signal to the UI once the runtime is fully initialized.
*/
async function initPython() {
pyodide = await loadPyodide();
await pyodide.loadPackage("micropip");
postToUI("READY", "Python Runtime Ready");
}
/**
* Main message handler for the Web Worker.
* Routes incoming signals from index.js to the appropriate Pyodide actions.
*/
self.onmessage = async (event) => {
const { type, code, id } = event.data;
if (type === "LINT") {
if (!pyodide) return;
try {
self.__lint_code__ = code;
await pyodide.runPythonAsync(`
import json
import micropip
try:
import pyflakes
except ImportError:
micropip.install('pyflakes')
import pyflakes
from pyflakes.api import check
from pyflakes.reporter import Reporter
import io
class LintReporter(Reporter):
def __init__(self):
Reporter.__init__(self, io.StringIO(), io.StringIO())
self.errors = []
def unexpectedError(self, filename, msg):
self.errors.append({"line": 0, "ch": 0, "message": msg, "severity": "error"})
def syntaxError(self, filename, msg, lineno, offset, text):
self.errors.append({
"line": max((lineno or 1) - 1, 0),
"ch": max(offset or 0, 0),
"message": msg,
"severity": "error"
})
def flake(self, message):
self.errors.append({
"line": message.lineno - 1,
"ch": message.col,
"message": str(message).split(": ", 3)[-1] if ":" in str(message) else str(message),
"severity": "warning"
})
r = LintReporter()
from js import __lint_code__
code_str = __lint_code__.to_py()
check(code_str, "main.py", r)
`);
const result = await pyodide.runPythonAsync("json.dumps(r.errors)");
const annotations = JSON.parse(result.toString());
const formatted = annotations.map(a => ({
from: { line: a.line, ch: a.ch },
to: { line: a.line, ch: Math.max(a.ch + 1, 0) },
message: a.message,
severity: a.severity || "warning"
}));
if (!formatted.toString().includes("micropip") && !formatted.toString().includes("pyflakes")) {
self.postMessage({ type: "LINT_RESULT", id, annotations: formatted });
}
} catch (err) {
if (!formatted.toString().includes("micropip") && !formatted.toString().includes("pyflakes")) {
self.postMessage({ type: "LINT_RESULT", id, annotations: [{ from: { line: 0, ch: 0 }, to: { line: 0, ch: 1 }, message: String(err.message), severity: "error" }] });
}
}
return;
}
// --- MICROPIP INSTALL HANDLER ---
if (type === "INSTALL") {
const pkg = event.data.package;
const isSilent = event.data.isSilent || false;
if (!pyodide) {
self.postMessage({ type: "INSTALL_ERROR", package: pkg, error: "Python runtime not ready yet.", isSilent });
return;
}
try {
// Handle both string and array
const packagesToInstall = Array.isArray(pkg) ? pkg : [pkg];
// Skip if empty array
if (packagesToInstall.length === 0) return;
self.__packages_to_install__ = packagesToInstall;
await pyodide.runPythonAsync(`
import micropip
from js import __packages_to_install__
pkgs = __packages_to_install__.to_py()
await micropip.install(pkgs)
`);
// Get updated list of installed packages
const listResult = await pyodide.runPythonAsync(`
import micropip, json
# Filter out internal/helper packages if desired, or just return all
all_pkgs = sorted([str(p) for p in micropip.list()])
json.dumps(all_pkgs)
`);
const packages = JSON.parse(listResult.toString());
self.postMessage({
type: "INSTALL_SUCCESS",
package: Array.isArray(pkg) ? pkg.join(', ') : pkg,
installedPackages: packages,
isSilent
});
} catch (err) {
self.postMessage({
type: "INSTALL_ERROR",
package: Array.isArray(pkg) ? pkg.join(', ') : pkg,
error: String(err.message),
isSilent
});
}
return;
}
// --- LIST PACKAGES HANDLER ---
if (type === "LIST_PACKAGES") {
if (!pyodide) {
self.postMessage({ type: "PACKAGE_LIST", installedPackages: [] });
return;
}
try {
const listResult = await pyodide.runPythonAsync(`
import micropip, json
json.dumps(sorted([str(p) for p in micropip.list()]))
`);
const packages = JSON.parse(listResult.toString());
self.postMessage({ type: "PACKAGE_LIST", installedPackages: packages });
} catch (err) {
self.postMessage({ type: "PACKAGE_LIST", installedPackages: [] });
}
return;
}
if (type === "EVAL_REPL") {
if (!pyodide) return;
const decoder = new TextDecoder("utf-8");
pyodide.setStdout({
write: (buffer) => {
try { postToUI("PRINT", decoder.decode(buffer)); } catch (e) { }
return buffer.length;
}
});
pyodide.setStderr({
write: (buffer) => {
try { postToUI("ERROR", decoder.decode(buffer)); } catch (e) { }
return buffer.length;
}
});
try {
// Spoof isatty AFTER setStdout so the patch applies to the current stdout
await pyodide.runPythonAsync(`
import builtins, os, sys, importlib
from js import postToUI
# Restore __import__ in case a previous run installed a bad hook
builtins.__import__ = importlib.__import__
def _mocked_system(cmd):
if cmd in ('cls', 'clear'):
postToUI("CLEAR", "")
return 0
return -1
os.system = _mocked_system
builtins.clear = lambda: postToUI("CLEAR", "")
sys.stdout.isatty = lambda: True
sys.stderr.isatty = lambda: True
# Patch colorama if already imported
if 'colorama' in sys.modules:
import colorama
colorama.init(strip=False, convert=False)
`);
const result = await pyodide.runPythonAsync(code);
if (result !== undefined) {
postToUI("PRINT", String(result) + "\\n");
}
postToUI("FINISHED", "");
} catch (err) {
postToUI("ERROR", err.message + "\\n");
postToUI("FINISHED", "");
}
return;
}
if (type === "RUN") {
if (!pyodide) return;
// Setup the Sync Input Bridge.
// Standard Python input() is synchronous and blocking.
// This bridge uses a synchronous XMLHttpRequest to a dummy path.
// The Service Worker (sw.js) intercepts this call to await user input.
await pyodide.runPythonAsync(`
import builtins, importlib
from js import XMLHttpRequest, postToUI
# Restore __import__ for reliability
builtins.__import__ = importlib.__import__
def sync_input(prompt=""):
if prompt:
postToUI("PRINT", str(prompt))
# This call blocks the worker thread until the Service Worker responds
request = XMLHttpRequest.new()
request.open("GET", "/get_input?t=" + str(builtins.id(request)), False)
try:
request.send(None)
return str(request.responseText)
except Exception as e:
return ""
import os
def _mocked_system(cmd):
if cmd in ('cls', 'clear'):
postToUI("CLEAR", "")
return 0
return -1
os.system = _mocked_system
builtins.input = sync_input
builtins.clear = lambda: postToUI("CLEAR", "")
`);
// Redirect stdout/stderr using streaming writes with proper byte handling
const decoder = new TextDecoder("utf-8");
pyodide.setStdout({
write: (buffer) => {
try {
const text = decoder.decode(buffer);
postToUI("PRINT", text);
} catch (e) {
postToUI("ERROR", "stdout decode error: " + e.message);
return 0;
}
return buffer.length;
}
});
pyodide.setStderr({
write: (buffer) => {
try {
const text = decoder.decode(buffer);
postToUI("ERROR", text);
} catch (e) {
postToUI("ERROR", "stderr decode error: " + e.message);
return 0;
}
return buffer.length;
}
});
// Spoof isatty AFTER setStdout so the patch applies to the CURRENT stdout
await pyodide.runPythonAsync(`
import sys
sys.stdout.isatty = lambda: True
sys.stderr.isatty = lambda: True
# Patch colorama if already imported (no dangerous import hook needed)
if 'colorama' in sys.modules:
import colorama
colorama.init(strip=False, convert=False)
`);
try {
await pyodide.runPythonAsync(code);
postToUI("FINISHED", "");
} catch (err) {
postToUI("ERROR", err.message);
}
}
};
initPython();