gwchq-textjam 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,776 +1,776 @@
1
- /* eslint-disable @typescript-eslint/no-empty-function */
2
- /* global globalThis, importScripts, loadPyodide, SharedArrayBuffer, Atomics, pygal */
3
-
4
- function toAbsoluteFromOrigin(url) {
5
- if (url.startsWith("http") || url.startsWith("/")) return url;
6
- // eslint-disable-next-line no-restricted-globals
7
- return new URL(url, self.location.origin).href;
8
- }
9
-
10
- // removing submodules (matplotlib.pyplot = matplotlib)
11
- const normalizeImportName = (name) => name.split(".")[0];
12
-
13
- const WORKING_DIR = "/home/pyodide";
14
-
15
- const toStructuredCloneable = (value) => {
16
- if (value == null) return value;
17
-
18
- if (
19
- typeof value === "string" ||
20
- typeof value === "number" ||
21
- typeof value === "boolean"
22
- ) {
23
- return value;
24
- }
25
-
26
- if (value instanceof Uint8Array) {
27
- return value.slice();
28
- }
29
-
30
- if (ArrayBuffer.isView(value)) {
31
- return new Uint8Array(
32
- value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength),
33
- );
34
- }
35
-
36
- if (value instanceof ArrayBuffer) {
37
- return value.slice(0);
38
- }
39
-
40
- if (value instanceof Map) {
41
- return Object.fromEntries(
42
- [...value.entries()].map(([k, v]) => [k, toStructuredCloneable(v)]),
43
- );
44
- }
45
-
46
- if (Array.isArray(value)) {
47
- return value.map(toStructuredCloneable);
48
- }
49
-
50
- if (typeof value?.toJs === "function") {
51
- try {
52
- const converted = value.toJs({ dict_converter: Object.fromEntries });
53
- return toStructuredCloneable(converted);
54
- } catch (_) {
55
- try {
56
- const converted = value.toJs();
57
- return toStructuredCloneable(converted);
58
- } catch (_) {
59
- return String(value);
60
- }
61
- }
62
- }
63
-
64
- if (typeof value === "object") {
65
- const result = {};
66
- for (const [key, val] of Object.entries(value)) {
67
- result[key] = toStructuredCloneable(val);
68
- }
69
- return result;
70
- }
71
-
72
- return String(value);
73
- };
74
-
75
- // Nest the PyodideWorker function inside a globalThis object so we control when its initialised.
76
- const PyodideWorker = () => {
77
- let assets;
78
- let packageApiUrl;
79
-
80
- const handleInit = (data) => {
81
- assets = data.assets;
82
- packageApiUrl = data.packageApiUrl;
83
-
84
- // Import scripts dynamically based on the environment
85
- console.log("PyodideWorker", "importing scripts");
86
- importScripts(toAbsoluteFromOrigin(assets.pygalUrl));
87
-
88
- assets.pyodideBaseUrl = `${packageApiUrl}/pyodide.js`;
89
- importScripts(toAbsoluteFromOrigin(assets.pyodideBaseUrl));
90
-
91
- initialisePyodide();
92
- };
93
-
94
- const supportsAllFeatures = typeof SharedArrayBuffer !== "undefined";
95
-
96
- // eslint-disable-next-line no-restricted-globals
97
- if (!supportsAllFeatures && name !== "incremental-features") {
98
- console.warn(
99
- [
100
- "The code editor will not be able to capture standard input or stop execution because these HTTP headers are not set:",
101
- " - Cross-Origin-Opener-Policy: same-origin",
102
- " - Cross-Origin-Embedder-Policy: require-corp",
103
- "",
104
- "If your app can cope with or without these features, please initialize the web worker with { name: 'incremental-features' } to silence this warning.",
105
- "You can then check for the presence of { stdinBuffer, interruptBuffer } in the handleLoaded message to check whether these features are supported.",
106
- "",
107
- "If you definitely need these features, either configure your server to respond with the HTTP headers above, or register a service worker.",
108
- "Once the HTTP headers are set, the browser will block cross-domain resources so you will need to add 'crossorigin' to <script> and other tags.",
109
- "You may wish to scope the HTTP headers to only those pages that host the code editor to make the browser restriction easier to deal with.",
110
- "",
111
- "Please refer to these code snippets for registering a service worker:",
112
- " - https://github.com/RaspberryPiFoundation/python-execution-prototypes/blob/fd2c50e032cba3bb0e92e19a88eb62e5b120fe7a/pyodide/index.html#L92-L98",
113
- " - https://github.com/RaspberryPiFoundation/python-execution-prototypes/blob/fd2c50e032cba3bb0e92e19a88eb62e5b120fe7a/pyodide/serviceworker.js",
114
- ].join("\n"),
115
- );
116
- }
117
- let pyodide, pyodidePromise, stdinBuffer, interruptBuffer, stopped;
118
- /** When true, input() uses postMessage + run_sync(getInputAsync) instead of setStdin (requires JSPI). */
119
- let useMessageStdin = false;
120
- /** Used when SharedArrayBuffer is unavailable: resolve for the pending input() call. */
121
- let pendingStdinResolve = null;
122
- // Until Pyodide is fully initialised, keep stdout/stderr in the dev console only.
123
- // After initialisation, route them to the UI via postMessage.
124
- let userStdStreamsEnabled = false;
125
- // When true, suppress internal library / package loader logs from the UI console.
126
- let suppressInternalStdStreams = false;
127
-
128
- const onmessage = async ({ data }) => {
129
- if (data.method !== "init") {
130
- pyodide = await pyodidePromise;
131
- }
132
-
133
- switch (data.method) {
134
- case "stdinResponse": {
135
- if (pendingStdinResolve) {
136
- let content = data.ctrlD ? null : data.content ?? "";
137
- if (content && content.endsWith("\n")) {
138
- content = content.slice(0, -1);
139
- }
140
- pendingStdinResolve(content);
141
- pendingStdinResolve = null;
142
- }
143
- break;
144
- }
145
- case "init": {
146
- handleInit(data);
147
- break;
148
- }
149
- case "createDirectories": {
150
- if (Array.isArray(data.dirs)) {
151
- for (const dir of data.dirs) {
152
- try {
153
- pyodide.FS.mkdirTree(`${WORKING_DIR}/${dir}`);
154
- } catch (e) {
155
- console.error(`Failed to create directory ${dir}:`, e);
156
- }
157
- }
158
- }
159
- break;
160
- }
161
- case "writeFile": {
162
- const encoder = new TextEncoder();
163
- pyodide.FS.writeFile(
164
- `${WORKING_DIR}/${data.filename}`,
165
- encoder.encode(data.content),
166
- );
167
- break;
168
- }
169
- case "runPython":
170
- runPython(data.python, data.userModuleNames);
171
- break;
172
- case "stopPython": {
173
- // Mark as stopped so future checks can raise KeyboardInterrupt.
174
- stopped = true;
175
- // If Python is currently blocked in input() via run_sync(getInputAsync),
176
- // resolve the pending stdin promise with EOF so execution can unwind
177
- // and clearPyodideData can run.
178
- if (pendingStdinResolve) {
179
- pendingStdinResolve(null);
180
- pendingStdinResolve = null;
181
- }
182
- break;
183
- }
184
- default: {
185
- throw new Error(`Unsupported method: ${data.method}`);
186
- }
187
- }
188
- };
189
-
190
- // eslint-disable-next-line no-restricted-globals
191
- addEventListener("message", async (event) => {
192
- onmessage(event);
193
- });
194
-
195
- const runPython = async (python, userModuleNames) => {
196
- stopped = false;
197
-
198
- // When stdin uses postMessage (no SharedArrayBuffer), run_sync() in input() requires
199
- // runPythonAsync so that JSPI stack switching can suspend until the main thread sends stdinResponse.
200
- const runUserCode = useMessageStdin
201
- ? () => pyodide.runPythonAsync(python)
202
- : () => pyodide.runPython(python);
203
-
204
- try {
205
- await withSupportForPackages(python, async () => {
206
- await runUserCode();
207
- });
208
- } catch (error) {
209
- if (!(error instanceof pyodide.ffi.PythonError)) {
210
- throw error;
211
- }
212
- const parsed = parsePythonError(error);
213
- // Stop resolves stdin with EOF so input() raises EOFError; show as interrupt, not error.
214
- if (stopped && parsed.type === "EOFError") {
215
- postMessage({
216
- method: "handleError",
217
- ...parsed,
218
- type: "KeyboardInterrupt",
219
- info: "Execution interrupted",
220
- });
221
- } else {
222
- postMessage({ method: "handleError", ...parsed });
223
- }
224
- }
225
-
226
- await clearPyodideData(userModuleNames);
227
- };
228
-
229
- const checkIfStopped = () => {
230
- if (stopped) {
231
- throw new pyodide.ffi.PythonError("KeyboardInterrupt");
232
- }
233
- };
234
-
235
- const withSupportForPackages = async (
236
- python,
237
- runPythonFn = async () => {},
238
- ) => {
239
- // Suppress internal loader output (e.g. "Loading pyodide-http") from the
240
- // user console while resolving imports and loading packages.
241
- suppressInternalStdStreams = true;
242
- const imports = await pyodide._api.pyodide_code.find_imports(python).toJs();
243
-
244
- await pyodide.runPythonAsync(`
245
- import builtins
246
- if hasattr(builtins, "_original_open"):
247
- builtins.open = builtins._original_open
248
- `);
249
-
250
- await Promise.all(imports.map((name) => loadDependency(name)));
251
-
252
- checkIfStopped();
253
- await pyodide.loadPackagesFromImports(python);
254
-
255
- checkIfStopped();
256
- await pyodide.runPythonAsync(
257
- `
258
- import basthon
259
- import builtins
260
- import os
261
-
262
- MAX_FILES = 100
263
- MAX_FILE_SIZE = 8500000
264
- PROJECT_ROOT = os.path.abspath("${WORKING_DIR}")
265
-
266
- if not hasattr(builtins, "_original_open"):
267
- builtins._original_open = builtins.open
268
-
269
- ORIGINAL_OPEN = builtins._original_open
270
-
271
- def _is_project_file(filename):
272
- abs_path = os.path.abspath(filename)
273
- return abs_path == PROJECT_ROOT or abs_path.startswith(PROJECT_ROOT + os.sep)
274
-
275
- def _to_project_relative(filename):
276
- abs_path = os.path.abspath(filename)
277
- return os.path.relpath(abs_path, PROJECT_ROOT)
278
-
279
- def _custom_open(filename, mode="r", *args, **kwargs):
280
- import os
281
- abs_path = os.path.abspath(filename)
282
-
283
- if "x" in mode and os.path.exists(abs_path):
284
- raise FileExistsError(f"File '{filename}' already exists")
285
-
286
- is_text_write = ("w" in mode or "a" in mode or "x" in mode) and "b" not in mode
287
- is_project_file = _is_project_file(abs_path)
288
-
289
- if is_text_write and is_project_file:
290
- if len(os.listdir(PROJECT_ROOT)) > MAX_FILES and not os.path.exists(abs_path):
291
- raise OSError(f"File system limit reached, no more than {MAX_FILES} files allowed")
292
- class CustomFile:
293
- def __init__(self, filename):
294
- self.filename = filename
295
- self.content = ""
296
-
297
- def write(self, content):
298
- self.content += content
299
- if len(self.content) > MAX_FILE_SIZE:
300
- raise OSError(f"File '{self.filename}' exceeds maximum file size of {MAX_FILE_SIZE} bytes")
301
- with ORIGINAL_OPEN(self.filename, mode, *args, **kwargs) as f:
302
- f.write(self.content)
303
- basthon.kernel.write_file({
304
- "filename": _to_project_relative(self.filename),
305
- "content": self.content,
306
- "mode": mode
307
- })
308
-
309
- def close(self):
310
- pass
311
-
312
- def __enter__(self):
313
- return self
314
-
315
- def __exit__(self, exc_type, exc_val, exc_tb):
316
- self.close()
317
-
318
- return CustomFile(abs_path)
319
- else:
320
- return ORIGINAL_OPEN(filename, mode, *args, **kwargs)
321
-
322
- # Override the built-in open function
323
- builtins.open = _custom_open
324
- `,
325
- { filename: "__custom_open__.py" },
326
- );
327
-
328
- // Re-enable user-visible stdout / stderr for the actual user code run.
329
- suppressInternalStdStreams = false;
330
-
331
- await runPythonFn();
332
-
333
- for (let name of imports) {
334
- checkIfStopped();
335
- const pkgName = normalizeImportName(name);
336
- await vendoredPackages[pkgName]?.after();
337
- }
338
- };
339
-
340
- const loadDependency = async (name) => {
341
- checkIfStopped();
342
-
343
- const pkgName = normalizeImportName(name);
344
- // If the import is for another user file then open it and load its dependencies.
345
- if (pyodide.FS.readdir(WORKING_DIR).includes(`${pkgName}.py`)) {
346
- const fileContent = pyodide.FS.readFile(`${WORKING_DIR}/${pkgName}.py`, {
347
- encoding: "utf8",
348
- });
349
- await withSupportForPackages(fileContent);
350
- return;
351
- }
352
-
353
- // If the import is for a vendored package then run its .before() hook.
354
- const vendoredPackage = vendoredPackages[pkgName];
355
- await vendoredPackage?.before();
356
- if (vendoredPackage) {
357
- return;
358
- }
359
-
360
- // If the import is for a module built into Python then do nothing.
361
- try {
362
- const pythonModule = pyodide.pyimport(pkgName);
363
- if (pythonModule) {
364
- return;
365
- }
366
- } catch (_) {}
367
-
368
- // If the import is for a package built into Pyodide then load it.
369
- // Built-ins: https://pyodide.org/en/stable/usage/packages-in-pyodide.html
370
- try {
371
- await pyodide.loadPackage(pkgName);
372
-
373
- const pyodidePackage = pyodide.pyimport(pkgName);
374
- if (pyodidePackage) {
375
- return;
376
- }
377
- } catch (_) {}
378
-
379
- // Ensure micropip is loaded which can fetch packages from PyPi.
380
- // See: https://pyodide.org/en/stable/usage/loading-packages.html
381
- if (!pyodide.micropip) {
382
- await pyodide.loadPackage("micropip");
383
- pyodide.micropip = pyodide.pyimport("micropip");
384
- }
385
-
386
- // If the import is for a PyPi package then load it.
387
- // Otherwise, don't error now so that we get an error later from Python.
388
- await pyodide.micropip.install(pkgName).catch(() => {});
389
- };
390
-
391
- const vendoredPackages = {
392
- // Support for https://pypi.org/project/py-enigma/ due to package not having a whl file on PyPi.
393
- enigma: {
394
- before: async () => {
395
- await pyodide.loadPackage(toAbsoluteFromOrigin(assets.enigmaWhlUrl));
396
- },
397
- after: () => {},
398
- },
399
- turtle: {
400
- before: async () => {
401
- pyodide.registerJsModule("basthon", fakeBasthonPackage);
402
- await pyodide.loadPackage(toAbsoluteFromOrigin(assets.turtleWhlUrl));
403
- },
404
- after: () =>
405
- pyodide.runPython(`
406
- import turtle
407
- import basthon
408
-
409
- svg_dict = turtle.Screen().show_scene()
410
- basthon.kernel.display_event({ "display_type": "turtle", "content": svg_dict })
411
- turtle.restart()
412
- `),
413
- },
414
- p5: {
415
- before: async () => {
416
- pyodide.registerJsModule("basthon", fakeBasthonPackage);
417
- await pyodide.loadPackage([
418
- "setuptools",
419
- toAbsoluteFromOrigin(assets.p5WhlUrl),
420
- ]);
421
- },
422
- after: () => {},
423
- },
424
- pygal: {
425
- before: () => {
426
- pyodide.registerJsModule("pygal", { ...pygal });
427
- pygal.config.renderChart = (content) => {
428
- postMessage({ method: "handleVisual", origin: "pygal", content });
429
- };
430
- },
431
- after: () => {},
432
- },
433
- matplotlib: {
434
- before: async () => {
435
- pyodide.registerJsModule("basthon", fakeBasthonPackage);
436
- // Patch the document object to prevent matplotlib from trying to render. Since we are running in a web worker,
437
- // the document object is not available. We will instead capture the image and send it back to the main thread.
438
- pyodide.runPython(`
439
- import js
440
-
441
- class __DummyDocument__:
442
- def __init__(self, *args, **kwargs) -> None:
443
- return
444
- def __getattr__(self, __name: str):
445
- return __DummyDocument__
446
- js.document = __DummyDocument__()
447
- `);
448
- await pyodide.loadPackage("matplotlib")?.catch(() => {});
449
- let pyodidePackage;
450
- try {
451
- pyodidePackage = pyodide.pyimport("matplotlib");
452
- } catch (_) {}
453
- if (pyodidePackage) {
454
- pyodide.runPython(`
455
- import matplotlib.pyplot as plt
456
- import io
457
- import basthon
458
-
459
- def show_chart():
460
- bytes_io = io.BytesIO()
461
- plt.savefig(bytes_io, format='jpg')
462
- bytes_io.seek(0)
463
- basthon.kernel.display_event({ "display_type": "matplotlib", "content": bytes_io.read() })
464
- plt.show = show_chart
465
- `);
466
- return;
467
- }
468
- },
469
- after: () => {
470
- pyodide.runPython(`
471
- import matplotlib.pyplot as plt
472
- plt.clf()
473
- `);
474
- },
475
- },
476
- seaborn: {
477
- before: async () => {
478
- pyodide.registerJsModule("basthon", fakeBasthonPackage);
479
- // Patch the document object to prevent matplotlib from trying to render. Since we are running in a web worker,
480
- // the document object is not available. We will instead capture the image and send it back to the main thread.
481
- pyodide.runPython(`
482
- import js
483
-
484
- class __DummyDocument__:
485
- def __init__(self, *args, **kwargs) -> None:
486
- return
487
- def __getattr__(self, __name: str):
488
- return __DummyDocument__
489
- js.document = __DummyDocument__()
490
- `);
491
-
492
- // Ensure micropip is loaded which can fetch packages from PyPi.
493
- // See: https://pyodide.org/en/stable/usage/loading-packages.html
494
- if (!pyodide.micropip) {
495
- await pyodide.loadPackage("micropip");
496
- pyodide.micropip = pyodide.pyimport("micropip");
497
- }
498
-
499
- // If the import is for a PyPi package then load it.
500
- // Otherwise, don't error now so that we get an error later from Python.
501
- await pyodide.micropip.install("seaborn").catch(() => {});
502
- },
503
- after: () => {
504
- pyodide.runPython(`
505
- import matplotlib.pyplot as plt
506
- import io
507
- import basthon
508
-
509
- def is_plot_empty():
510
- fig = plt.gcf()
511
- for ax in fig.get_axes():
512
- # Check if the axes contain any lines, patches, collections, etc.
513
- if ax.lines or ax.patches or ax.collections or ax.images or ax.texts:
514
- return False
515
- return True
516
-
517
- if not is_plot_empty():
518
- bytes_io = io.BytesIO()
519
- plt.savefig(bytes_io, format='jpg')
520
- bytes_io.seek(0)
521
- basthon.kernel.display_event({ "display_type": "matplotlib", "content": bytes_io.read() })
522
-
523
- plt.clf()
524
- `);
525
- },
526
- },
527
- plotly: {
528
- before: async () => {
529
- if (!pyodide.micropip) {
530
- await pyodide.loadPackage("micropip");
531
- pyodide.micropip = pyodide.pyimport("micropip");
532
- }
533
-
534
- // If the import is for a PyPi package then load it.
535
- // Otherwise, don't error now so that we get an error later from Python.
536
- await pyodide.micropip.install("plotly").catch(() => {});
537
- await pyodide.micropip.install("pandas").catch(() => {});
538
- pyodide.registerJsModule("basthon", fakeBasthonPackage);
539
- pyodide.runPython(`
540
- import plotly.graph_objs as go
541
-
542
- def _hacked_show(self, *args, **kwargs):
543
- basthon.kernel.display_event({
544
- "display_type": "plotly",
545
- "content": self.to_json()
546
- })
547
-
548
- go.Figure.show = _hacked_show
549
- `);
550
- },
551
- after: () => {},
552
- },
553
- };
554
-
555
- const fakeBasthonPackage = {
556
- kernel: {
557
- display_event: (event) => {
558
- let payload;
559
- try {
560
- payload = event.toJs({ dict_converter: Object.fromEntries });
561
- } catch (_) {
562
- payload = event.toJs();
563
- }
564
-
565
- const origin = String(payload.display_type);
566
- const content = toStructuredCloneable(payload.content);
567
-
568
- postMessage({ method: "handleVisual", origin, content });
569
- },
570
- write_file: (event) => {
571
- let payload;
572
- try {
573
- payload = event.toJs({ dict_converter: Object.fromEntries });
574
- } catch (_) {
575
- payload = event.toJs();
576
- }
577
-
578
- const filename = String(payload.filename);
579
- const content =
580
- typeof payload.content === "string"
581
- ? payload.content
582
- : toStructuredCloneable(payload.content);
583
- const mode = String(payload.mode);
584
-
585
- postMessage({ method: "handleFileWrite", filename, content, mode });
586
- },
587
- locals: () => pyodide.runPython("globals()"),
588
- /**
589
- * Returns a Promise that resolves with the next line of stdin when the main thread
590
- * sends stdinResponse. Resolves with null on EOF (e.g. Ctrl+D).
591
- * Used when SharedArrayBuffer is unavailable (no COOP/COEP) so we cannot block via Atomics.wait.
592
- * Requires JSPI and runPythonAsync() for run_sync() to work.
593
- */
594
- getInputAsync: () => {
595
- const promise = new Promise((resolve) => {
596
- pendingStdinResolve = resolve;
597
- });
598
- postMessage({ method: "handleInput" });
599
- return promise;
600
- },
601
- },
602
- };
603
-
604
- const clearPyodideData = async (userModuleNames) => {
605
- postMessage({ method: "handleLoading" });
606
- try {
607
- await pyodide.runPythonAsync(`
608
- import builtins
609
- import sys
610
-
611
- # Restore the real open before cleaning up
612
- if hasattr(builtins, "_original_open"):
613
- builtins.open = builtins._original_open
614
-
615
- # Remove user modules from sys.modules
616
- user_modules = ${JSON.stringify(userModuleNames)}
617
- for name in user_modules:
618
- if name in sys.modules:
619
- del sys.modules[name]
620
-
621
- # Clear all user-defined variables and modules
622
- for name in list(globals()):
623
- if not name.startswith('_') and name not in ('basthon', 'sys', 'builtins'):
624
- del globals()[name]
625
- `);
626
- } catch (error) {
627
- console.error("Error while clearing Pyodide data:", error);
628
- }
629
- console.log("clearPyodideData done");
630
- postMessage({ method: "handleLoaded", stdinBuffer, interruptBuffer });
631
- };
632
-
633
- const initialisePyodide = async () => {
634
- postMessage({ method: "handleLoading" });
635
-
636
- pyodidePromise = loadPyodide({
637
- stdout: (content) => {
638
- if (stopped) return;
639
- if (userStdStreamsEnabled && !suppressInternalStdStreams) {
640
- postMessage({ method: "handleOutput", stream: "stdout", content });
641
- } else {
642
- console.log(content);
643
- }
644
- },
645
- stderr: (content) => {
646
- if (stopped) return;
647
- if (userStdStreamsEnabled && !suppressInternalStdStreams) {
648
- postMessage({ method: "handleOutput", stream: "stderr", content });
649
- } else {
650
- console.error(content);
651
- }
652
- },
653
- });
654
-
655
- pyodide = await pyodidePromise;
656
-
657
- pyodide.registerJsModule("basthon", fakeBasthonPackage);
658
-
659
- // When SharedArrayBuffer is unavailable, always use the postMessage-based
660
- // stdin path. JSPI / run_sync will raise at runtime if the environment
661
- // cannot stack-switch, but in JSPI-capable browsers this enables
662
- // interactive input() without COOP/COEP.
663
- useMessageStdin = !supportsAllFeatures;
664
- pyodide.globals.set("__stdin_via_message__", useMessageStdin);
665
-
666
- await pyodide.runPythonAsync(`
667
- import builtins
668
- from pyodide.ffi import run_sync as __run_sync__
669
-
670
- __old_input__ = builtins.input
671
- def __patched_input__(prompt=None):
672
- if prompt is not None:
673
- print(prompt)
674
- if __stdin_via_message__:
675
- result = __run_sync__(basthon.kernel.getInputAsync())
676
- if result is None:
677
- raise EOFError("EOF when reading a line")
678
- return result
679
- return __old_input__()
680
- builtins.input = __patched_input__
681
- `);
682
-
683
- await pyodide.runPythonAsync(`
684
- import builtins
685
- # Save the original open function only once
686
- if not hasattr(builtins, "_original_open"):
687
- builtins._original_open = builtins.open
688
- _original_open = builtins._original_open
689
- `);
690
-
691
- await pyodide.loadPackage("pyodide-http");
692
- await pyodide.runPythonAsync(`
693
- import pyodide_http
694
- pyodide_http.patch_all()
695
- `);
696
-
697
- if (supportsAllFeatures) {
698
- stdinBuffer =
699
- stdinBuffer || new Int32Array(new SharedArrayBuffer(1024 * 1024)); // 1 MiB
700
- stdinBuffer[0] = 1; // Store the length of content in the buffer at index 0.
701
- pyodide.setStdin({ isatty: true, read: readFromStdin });
702
-
703
- interruptBuffer =
704
- interruptBuffer || new Uint8Array(new SharedArrayBuffer(1));
705
- pyodide.setInterruptBuffer(interruptBuffer);
706
- }
707
-
708
- // From this point on, anything written to stdout / stderr is considered
709
- // user-visible and will be forwarded to the UI.
710
- userStdStreamsEnabled = true;
711
-
712
- postMessage({ method: "handleLoaded", stdinBuffer, interruptBuffer });
713
- };
714
-
715
- const readFromStdin = (bufferToWrite) => {
716
- const previousLength = stdinBuffer[0];
717
- postMessage({ method: "handleInput" });
718
-
719
- while (true) {
720
- pyodide.checkInterrupt();
721
- const result = Atomics.wait(stdinBuffer, 0, previousLength, 100);
722
- if (result === "not-equal") {
723
- break;
724
- }
725
- }
726
-
727
- const currentLength = stdinBuffer[0];
728
- if (currentLength === -1) {
729
- return 0;
730
- } // Signals that stdin was closed.
731
-
732
- const addedBytes = stdinBuffer.slice(previousLength, currentLength);
733
- bufferToWrite.set(addedBytes);
734
-
735
- return addedBytes.length;
736
- };
737
-
738
- const parsePythonError = (error) => {
739
- const type = error.type;
740
- const [trace, info] = error.message.split(`${type}:`).map((s) => s?.trim());
741
-
742
- const lines = trace.split("\n");
743
-
744
- // if the third from last line matches /File "__custom_open__\.py", line (\d+)/g then strip off the last three lines
745
- if (
746
- lines.length > 3 &&
747
- /File "__custom_open__\.py", line (\d+)/g.test(lines[lines.length - 3])
748
- ) {
749
- lines.splice(-3, 3);
750
- }
751
-
752
- const snippetLine = lines[lines.length - 2]; // print("hi")invalid
753
- const caretLine = lines[lines.length - 1]; // ^^^^^^^
754
-
755
- const showsMistake = caretLine.includes("^");
756
- const mistake = showsMistake
757
- ? [snippetLine.slice(4), caretLine.slice(4)].join("\n")
758
- : "";
759
-
760
- const matches = [
761
- ...trace.matchAll(/File "(?!__custom_open__\.py)(.*)", line (\d+)/g),
762
- ];
763
- const match = matches[matches.length - 1];
764
-
765
- const path = match ? match[1] : "";
766
- const base = path.split("/").reverse()[0];
767
- const file = base === "<exec>" ? "main.py" : base;
768
-
769
- const line = match ? parseInt(match[2], 10) : "";
770
-
771
- return { file, line, mistake, type, info };
772
- };
773
- };
774
-
775
- globalThis.PyodideWorker = PyodideWorker;
776
- PyodideWorker();
1
+ /* eslint-disable @typescript-eslint/no-empty-function */
2
+ /* global globalThis, importScripts, loadPyodide, SharedArrayBuffer, Atomics, pygal */
3
+
4
+ function toAbsoluteFromOrigin(url) {
5
+ if (url.startsWith("http") || url.startsWith("/")) return url;
6
+ // eslint-disable-next-line no-restricted-globals
7
+ return new URL(url, self.location.origin).href;
8
+ }
9
+
10
+ // removing submodules (matplotlib.pyplot = matplotlib)
11
+ const normalizeImportName = (name) => name.split(".")[0];
12
+
13
+ const WORKING_DIR = "/home/pyodide";
14
+
15
+ const toStructuredCloneable = (value) => {
16
+ if (value == null) return value;
17
+
18
+ if (
19
+ typeof value === "string" ||
20
+ typeof value === "number" ||
21
+ typeof value === "boolean"
22
+ ) {
23
+ return value;
24
+ }
25
+
26
+ if (value instanceof Uint8Array) {
27
+ return value.slice();
28
+ }
29
+
30
+ if (ArrayBuffer.isView(value)) {
31
+ return new Uint8Array(
32
+ value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength),
33
+ );
34
+ }
35
+
36
+ if (value instanceof ArrayBuffer) {
37
+ return value.slice(0);
38
+ }
39
+
40
+ if (value instanceof Map) {
41
+ return Object.fromEntries(
42
+ [...value.entries()].map(([k, v]) => [k, toStructuredCloneable(v)]),
43
+ );
44
+ }
45
+
46
+ if (Array.isArray(value)) {
47
+ return value.map(toStructuredCloneable);
48
+ }
49
+
50
+ if (typeof value?.toJs === "function") {
51
+ try {
52
+ const converted = value.toJs({ dict_converter: Object.fromEntries });
53
+ return toStructuredCloneable(converted);
54
+ } catch (_) {
55
+ try {
56
+ const converted = value.toJs();
57
+ return toStructuredCloneable(converted);
58
+ } catch (_) {
59
+ return String(value);
60
+ }
61
+ }
62
+ }
63
+
64
+ if (typeof value === "object") {
65
+ const result = {};
66
+ for (const [key, val] of Object.entries(value)) {
67
+ result[key] = toStructuredCloneable(val);
68
+ }
69
+ return result;
70
+ }
71
+
72
+ return String(value);
73
+ };
74
+
75
+ // Nest the PyodideWorker function inside a globalThis object so we control when its initialised.
76
+ const PyodideWorker = () => {
77
+ let assets;
78
+ let packageApiUrl;
79
+
80
+ const handleInit = (data) => {
81
+ assets = data.assets;
82
+ packageApiUrl = data.packageApiUrl;
83
+
84
+ // Import scripts dynamically based on the environment
85
+ console.log("PyodideWorker", "importing scripts");
86
+ importScripts(toAbsoluteFromOrigin(assets.pygalUrl));
87
+
88
+ assets.pyodideBaseUrl = `${packageApiUrl}/pyodide.js`;
89
+ importScripts(toAbsoluteFromOrigin(assets.pyodideBaseUrl));
90
+
91
+ initialisePyodide();
92
+ };
93
+
94
+ const supportsAllFeatures = typeof SharedArrayBuffer !== "undefined";
95
+
96
+ // eslint-disable-next-line no-restricted-globals
97
+ if (!supportsAllFeatures && name !== "incremental-features") {
98
+ console.warn(
99
+ [
100
+ "The code editor will not be able to capture standard input or stop execution because these HTTP headers are not set:",
101
+ " - Cross-Origin-Opener-Policy: same-origin",
102
+ " - Cross-Origin-Embedder-Policy: require-corp",
103
+ "",
104
+ "If your app can cope with or without these features, please initialize the web worker with { name: 'incremental-features' } to silence this warning.",
105
+ "You can then check for the presence of { stdinBuffer, interruptBuffer } in the handleLoaded message to check whether these features are supported.",
106
+ "",
107
+ "If you definitely need these features, either configure your server to respond with the HTTP headers above, or register a service worker.",
108
+ "Once the HTTP headers are set, the browser will block cross-domain resources so you will need to add 'crossorigin' to <script> and other tags.",
109
+ "You may wish to scope the HTTP headers to only those pages that host the code editor to make the browser restriction easier to deal with.",
110
+ "",
111
+ "Please refer to these code snippets for registering a service worker:",
112
+ " - https://github.com/RaspberryPiFoundation/python-execution-prototypes/blob/fd2c50e032cba3bb0e92e19a88eb62e5b120fe7a/pyodide/index.html#L92-L98",
113
+ " - https://github.com/RaspberryPiFoundation/python-execution-prototypes/blob/fd2c50e032cba3bb0e92e19a88eb62e5b120fe7a/pyodide/serviceworker.js",
114
+ ].join("\n"),
115
+ );
116
+ }
117
+ let pyodide, pyodidePromise, stdinBuffer, interruptBuffer, stopped;
118
+ /** When true, input() uses postMessage + run_sync(getInputAsync) instead of setStdin (requires JSPI). */
119
+ let useMessageStdin = false;
120
+ /** Used when SharedArrayBuffer is unavailable: resolve for the pending input() call. */
121
+ let pendingStdinResolve = null;
122
+ // Until Pyodide is fully initialised, keep stdout/stderr in the dev console only.
123
+ // After initialisation, route them to the UI via postMessage.
124
+ let userStdStreamsEnabled = false;
125
+ // When true, suppress internal library / package loader logs from the UI console.
126
+ let suppressInternalStdStreams = false;
127
+
128
+ const onmessage = async ({ data }) => {
129
+ if (data.method !== "init") {
130
+ pyodide = await pyodidePromise;
131
+ }
132
+
133
+ switch (data.method) {
134
+ case "stdinResponse": {
135
+ if (pendingStdinResolve) {
136
+ let content = data.ctrlD ? null : data.content ?? "";
137
+ if (content && content.endsWith("\n")) {
138
+ content = content.slice(0, -1);
139
+ }
140
+ pendingStdinResolve(content);
141
+ pendingStdinResolve = null;
142
+ }
143
+ break;
144
+ }
145
+ case "init": {
146
+ handleInit(data);
147
+ break;
148
+ }
149
+ case "createDirectories": {
150
+ if (Array.isArray(data.dirs)) {
151
+ for (const dir of data.dirs) {
152
+ try {
153
+ pyodide.FS.mkdirTree(`${WORKING_DIR}/${dir}`);
154
+ } catch (e) {
155
+ console.error(`Failed to create directory ${dir}:`, e);
156
+ }
157
+ }
158
+ }
159
+ break;
160
+ }
161
+ case "writeFile": {
162
+ const encoder = new TextEncoder();
163
+ pyodide.FS.writeFile(
164
+ `${WORKING_DIR}/${data.filename}`,
165
+ encoder.encode(data.content),
166
+ );
167
+ break;
168
+ }
169
+ case "runPython":
170
+ runPython(data.python, data.userModuleNames);
171
+ break;
172
+ case "stopPython": {
173
+ // Mark as stopped so future checks can raise KeyboardInterrupt.
174
+ stopped = true;
175
+ // If Python is currently blocked in input() via run_sync(getInputAsync),
176
+ // resolve the pending stdin promise with EOF so execution can unwind
177
+ // and clearPyodideData can run.
178
+ if (pendingStdinResolve) {
179
+ pendingStdinResolve(null);
180
+ pendingStdinResolve = null;
181
+ }
182
+ break;
183
+ }
184
+ default: {
185
+ throw new Error(`Unsupported method: ${data.method}`);
186
+ }
187
+ }
188
+ };
189
+
190
+ // eslint-disable-next-line no-restricted-globals
191
+ addEventListener("message", async (event) => {
192
+ onmessage(event);
193
+ });
194
+
195
+ const runPython = async (python, userModuleNames) => {
196
+ stopped = false;
197
+
198
+ // When stdin uses postMessage (no SharedArrayBuffer), run_sync() in input() requires
199
+ // runPythonAsync so that JSPI stack switching can suspend until the main thread sends stdinResponse.
200
+ const runUserCode = useMessageStdin
201
+ ? () => pyodide.runPythonAsync(python)
202
+ : () => pyodide.runPython(python);
203
+
204
+ try {
205
+ await withSupportForPackages(python, async () => {
206
+ await runUserCode();
207
+ });
208
+ } catch (error) {
209
+ if (!(error instanceof pyodide.ffi.PythonError)) {
210
+ throw error;
211
+ }
212
+ const parsed = parsePythonError(error);
213
+ // Stop resolves stdin with EOF so input() raises EOFError; show as interrupt, not error.
214
+ if (stopped && parsed.type === "EOFError") {
215
+ postMessage({
216
+ method: "handleError",
217
+ ...parsed,
218
+ type: "KeyboardInterrupt",
219
+ info: "Execution interrupted",
220
+ });
221
+ } else {
222
+ postMessage({ method: "handleError", ...parsed });
223
+ }
224
+ }
225
+
226
+ await clearPyodideData(userModuleNames);
227
+ };
228
+
229
+ const checkIfStopped = () => {
230
+ if (stopped) {
231
+ throw new pyodide.ffi.PythonError("KeyboardInterrupt");
232
+ }
233
+ };
234
+
235
+ const withSupportForPackages = async (
236
+ python,
237
+ runPythonFn = async () => {},
238
+ ) => {
239
+ // Suppress internal loader output (e.g. "Loading pyodide-http") from the
240
+ // user console while resolving imports and loading packages.
241
+ suppressInternalStdStreams = true;
242
+ const imports = await pyodide._api.pyodide_code.find_imports(python).toJs();
243
+
244
+ await pyodide.runPythonAsync(`
245
+ import builtins
246
+ if hasattr(builtins, "_original_open"):
247
+ builtins.open = builtins._original_open
248
+ `);
249
+
250
+ await Promise.all(imports.map((name) => loadDependency(name)));
251
+
252
+ checkIfStopped();
253
+ await pyodide.loadPackagesFromImports(python);
254
+
255
+ checkIfStopped();
256
+ await pyodide.runPythonAsync(
257
+ `
258
+ import basthon
259
+ import builtins
260
+ import os
261
+
262
+ MAX_FILES = 100
263
+ MAX_FILE_SIZE = 8500000
264
+ PROJECT_ROOT = os.path.abspath("${WORKING_DIR}")
265
+
266
+ if not hasattr(builtins, "_original_open"):
267
+ builtins._original_open = builtins.open
268
+
269
+ ORIGINAL_OPEN = builtins._original_open
270
+
271
+ def _is_project_file(filename):
272
+ abs_path = os.path.abspath(filename)
273
+ return abs_path == PROJECT_ROOT or abs_path.startswith(PROJECT_ROOT + os.sep)
274
+
275
+ def _to_project_relative(filename):
276
+ abs_path = os.path.abspath(filename)
277
+ return os.path.relpath(abs_path, PROJECT_ROOT)
278
+
279
+ def _custom_open(filename, mode="r", *args, **kwargs):
280
+ import os
281
+ abs_path = os.path.abspath(filename)
282
+
283
+ if "x" in mode and os.path.exists(abs_path):
284
+ raise FileExistsError(f"File '{filename}' already exists")
285
+
286
+ is_text_write = ("w" in mode or "a" in mode or "x" in mode) and "b" not in mode
287
+ is_project_file = _is_project_file(abs_path)
288
+
289
+ if is_text_write and is_project_file:
290
+ if len(os.listdir(PROJECT_ROOT)) > MAX_FILES and not os.path.exists(abs_path):
291
+ raise OSError(f"File system limit reached, no more than {MAX_FILES} files allowed")
292
+ class CustomFile:
293
+ def __init__(self, filename):
294
+ self.filename = filename
295
+ self.content = ""
296
+
297
+ def write(self, content):
298
+ self.content += content
299
+ if len(self.content) > MAX_FILE_SIZE:
300
+ raise OSError(f"File '{self.filename}' exceeds maximum file size of {MAX_FILE_SIZE} bytes")
301
+ with ORIGINAL_OPEN(self.filename, mode, *args, **kwargs) as f:
302
+ f.write(self.content)
303
+ basthon.kernel.write_file({
304
+ "filename": _to_project_relative(self.filename),
305
+ "content": self.content,
306
+ "mode": mode
307
+ })
308
+
309
+ def close(self):
310
+ pass
311
+
312
+ def __enter__(self):
313
+ return self
314
+
315
+ def __exit__(self, exc_type, exc_val, exc_tb):
316
+ self.close()
317
+
318
+ return CustomFile(abs_path)
319
+ else:
320
+ return ORIGINAL_OPEN(filename, mode, *args, **kwargs)
321
+
322
+ # Override the built-in open function
323
+ builtins.open = _custom_open
324
+ `,
325
+ { filename: "__custom_open__.py" },
326
+ );
327
+
328
+ // Re-enable user-visible stdout / stderr for the actual user code run.
329
+ suppressInternalStdStreams = false;
330
+
331
+ await runPythonFn();
332
+
333
+ for (let name of imports) {
334
+ checkIfStopped();
335
+ const pkgName = normalizeImportName(name);
336
+ await vendoredPackages[pkgName]?.after();
337
+ }
338
+ };
339
+
340
+ const loadDependency = async (name) => {
341
+ checkIfStopped();
342
+
343
+ const pkgName = normalizeImportName(name);
344
+ // If the import is for another user file then open it and load its dependencies.
345
+ if (pyodide.FS.readdir(WORKING_DIR).includes(`${pkgName}.py`)) {
346
+ const fileContent = pyodide.FS.readFile(`${WORKING_DIR}/${pkgName}.py`, {
347
+ encoding: "utf8",
348
+ });
349
+ await withSupportForPackages(fileContent);
350
+ return;
351
+ }
352
+
353
+ // If the import is for a vendored package then run its .before() hook.
354
+ const vendoredPackage = vendoredPackages[pkgName];
355
+ await vendoredPackage?.before();
356
+ if (vendoredPackage) {
357
+ return;
358
+ }
359
+
360
+ // If the import is for a module built into Python then do nothing.
361
+ try {
362
+ const pythonModule = pyodide.pyimport(pkgName);
363
+ if (pythonModule) {
364
+ return;
365
+ }
366
+ } catch (_) {}
367
+
368
+ // If the import is for a package built into Pyodide then load it.
369
+ // Built-ins: https://pyodide.org/en/stable/usage/packages-in-pyodide.html
370
+ try {
371
+ await pyodide.loadPackage(pkgName);
372
+
373
+ const pyodidePackage = pyodide.pyimport(pkgName);
374
+ if (pyodidePackage) {
375
+ return;
376
+ }
377
+ } catch (_) {}
378
+
379
+ // Ensure micropip is loaded which can fetch packages from PyPi.
380
+ // See: https://pyodide.org/en/stable/usage/loading-packages.html
381
+ if (!pyodide.micropip) {
382
+ await pyodide.loadPackage("micropip");
383
+ pyodide.micropip = pyodide.pyimport("micropip");
384
+ }
385
+
386
+ // If the import is for a PyPi package then load it.
387
+ // Otherwise, don't error now so that we get an error later from Python.
388
+ await pyodide.micropip.install(pkgName).catch(() => {});
389
+ };
390
+
391
+ const vendoredPackages = {
392
+ // Support for https://pypi.org/project/py-enigma/ due to package not having a whl file on PyPi.
393
+ enigma: {
394
+ before: async () => {
395
+ await pyodide.loadPackage(toAbsoluteFromOrigin(assets.enigmaWhlUrl));
396
+ },
397
+ after: () => {},
398
+ },
399
+ turtle: {
400
+ before: async () => {
401
+ pyodide.registerJsModule("basthon", fakeBasthonPackage);
402
+ await pyodide.loadPackage(toAbsoluteFromOrigin(assets.turtleWhlUrl));
403
+ },
404
+ after: () =>
405
+ pyodide.runPython(`
406
+ import turtle
407
+ import basthon
408
+
409
+ svg_dict = turtle.Screen().show_scene()
410
+ basthon.kernel.display_event({ "display_type": "turtle", "content": svg_dict })
411
+ turtle.restart()
412
+ `),
413
+ },
414
+ p5: {
415
+ before: async () => {
416
+ pyodide.registerJsModule("basthon", fakeBasthonPackage);
417
+ await pyodide.loadPackage([
418
+ "setuptools",
419
+ toAbsoluteFromOrigin(assets.p5WhlUrl),
420
+ ]);
421
+ },
422
+ after: () => {},
423
+ },
424
+ pygal: {
425
+ before: () => {
426
+ pyodide.registerJsModule("pygal", { ...pygal });
427
+ pygal.config.renderChart = (content) => {
428
+ postMessage({ method: "handleVisual", origin: "pygal", content });
429
+ };
430
+ },
431
+ after: () => {},
432
+ },
433
+ matplotlib: {
434
+ before: async () => {
435
+ pyodide.registerJsModule("basthon", fakeBasthonPackage);
436
+ // Patch the document object to prevent matplotlib from trying to render. Since we are running in a web worker,
437
+ // the document object is not available. We will instead capture the image and send it back to the main thread.
438
+ pyodide.runPython(`
439
+ import js
440
+
441
+ class __DummyDocument__:
442
+ def __init__(self, *args, **kwargs) -> None:
443
+ return
444
+ def __getattr__(self, __name: str):
445
+ return __DummyDocument__
446
+ js.document = __DummyDocument__()
447
+ `);
448
+ await pyodide.loadPackage("matplotlib")?.catch(() => {});
449
+ let pyodidePackage;
450
+ try {
451
+ pyodidePackage = pyodide.pyimport("matplotlib");
452
+ } catch (_) {}
453
+ if (pyodidePackage) {
454
+ pyodide.runPython(`
455
+ import matplotlib.pyplot as plt
456
+ import io
457
+ import basthon
458
+
459
+ def show_chart():
460
+ bytes_io = io.BytesIO()
461
+ plt.savefig(bytes_io, format='jpg')
462
+ bytes_io.seek(0)
463
+ basthon.kernel.display_event({ "display_type": "matplotlib", "content": bytes_io.read() })
464
+ plt.show = show_chart
465
+ `);
466
+ return;
467
+ }
468
+ },
469
+ after: () => {
470
+ pyodide.runPython(`
471
+ import matplotlib.pyplot as plt
472
+ plt.clf()
473
+ `);
474
+ },
475
+ },
476
+ seaborn: {
477
+ before: async () => {
478
+ pyodide.registerJsModule("basthon", fakeBasthonPackage);
479
+ // Patch the document object to prevent matplotlib from trying to render. Since we are running in a web worker,
480
+ // the document object is not available. We will instead capture the image and send it back to the main thread.
481
+ pyodide.runPython(`
482
+ import js
483
+
484
+ class __DummyDocument__:
485
+ def __init__(self, *args, **kwargs) -> None:
486
+ return
487
+ def __getattr__(self, __name: str):
488
+ return __DummyDocument__
489
+ js.document = __DummyDocument__()
490
+ `);
491
+
492
+ // Ensure micropip is loaded which can fetch packages from PyPi.
493
+ // See: https://pyodide.org/en/stable/usage/loading-packages.html
494
+ if (!pyodide.micropip) {
495
+ await pyodide.loadPackage("micropip");
496
+ pyodide.micropip = pyodide.pyimport("micropip");
497
+ }
498
+
499
+ // If the import is for a PyPi package then load it.
500
+ // Otherwise, don't error now so that we get an error later from Python.
501
+ await pyodide.micropip.install("seaborn").catch(() => {});
502
+ },
503
+ after: () => {
504
+ pyodide.runPython(`
505
+ import matplotlib.pyplot as plt
506
+ import io
507
+ import basthon
508
+
509
+ def is_plot_empty():
510
+ fig = plt.gcf()
511
+ for ax in fig.get_axes():
512
+ # Check if the axes contain any lines, patches, collections, etc.
513
+ if ax.lines or ax.patches or ax.collections or ax.images or ax.texts:
514
+ return False
515
+ return True
516
+
517
+ if not is_plot_empty():
518
+ bytes_io = io.BytesIO()
519
+ plt.savefig(bytes_io, format='jpg')
520
+ bytes_io.seek(0)
521
+ basthon.kernel.display_event({ "display_type": "matplotlib", "content": bytes_io.read() })
522
+
523
+ plt.clf()
524
+ `);
525
+ },
526
+ },
527
+ plotly: {
528
+ before: async () => {
529
+ if (!pyodide.micropip) {
530
+ await pyodide.loadPackage("micropip");
531
+ pyodide.micropip = pyodide.pyimport("micropip");
532
+ }
533
+
534
+ // If the import is for a PyPi package then load it.
535
+ // Otherwise, don't error now so that we get an error later from Python.
536
+ await pyodide.micropip.install("plotly").catch(() => {});
537
+ await pyodide.micropip.install("pandas").catch(() => {});
538
+ pyodide.registerJsModule("basthon", fakeBasthonPackage);
539
+ pyodide.runPython(`
540
+ import plotly.graph_objs as go
541
+
542
+ def _hacked_show(self, *args, **kwargs):
543
+ basthon.kernel.display_event({
544
+ "display_type": "plotly",
545
+ "content": self.to_json()
546
+ })
547
+
548
+ go.Figure.show = _hacked_show
549
+ `);
550
+ },
551
+ after: () => {},
552
+ },
553
+ };
554
+
555
+ const fakeBasthonPackage = {
556
+ kernel: {
557
+ display_event: (event) => {
558
+ let payload;
559
+ try {
560
+ payload = event.toJs({ dict_converter: Object.fromEntries });
561
+ } catch (_) {
562
+ payload = event.toJs();
563
+ }
564
+
565
+ const origin = String(payload.display_type);
566
+ const content = toStructuredCloneable(payload.content);
567
+
568
+ postMessage({ method: "handleVisual", origin, content });
569
+ },
570
+ write_file: (event) => {
571
+ let payload;
572
+ try {
573
+ payload = event.toJs({ dict_converter: Object.fromEntries });
574
+ } catch (_) {
575
+ payload = event.toJs();
576
+ }
577
+
578
+ const filename = String(payload.filename);
579
+ const content =
580
+ typeof payload.content === "string"
581
+ ? payload.content
582
+ : toStructuredCloneable(payload.content);
583
+ const mode = String(payload.mode);
584
+
585
+ postMessage({ method: "handleFileWrite", filename, content, mode });
586
+ },
587
+ locals: () => pyodide.runPython("globals()"),
588
+ /**
589
+ * Returns a Promise that resolves with the next line of stdin when the main thread
590
+ * sends stdinResponse. Resolves with null on EOF (e.g. Ctrl+D).
591
+ * Used when SharedArrayBuffer is unavailable (no COOP/COEP) so we cannot block via Atomics.wait.
592
+ * Requires JSPI and runPythonAsync() for run_sync() to work.
593
+ */
594
+ getInputAsync: () => {
595
+ const promise = new Promise((resolve) => {
596
+ pendingStdinResolve = resolve;
597
+ });
598
+ postMessage({ method: "handleInput" });
599
+ return promise;
600
+ },
601
+ },
602
+ };
603
+
604
+ const clearPyodideData = async (userModuleNames) => {
605
+ postMessage({ method: "handleLoading" });
606
+ try {
607
+ await pyodide.runPythonAsync(`
608
+ import builtins
609
+ import sys
610
+
611
+ # Restore the real open before cleaning up
612
+ if hasattr(builtins, "_original_open"):
613
+ builtins.open = builtins._original_open
614
+
615
+ # Remove user modules from sys.modules
616
+ user_modules = ${JSON.stringify(userModuleNames)}
617
+ for name in user_modules:
618
+ if name in sys.modules:
619
+ del sys.modules[name]
620
+
621
+ # Clear all user-defined variables and modules
622
+ for name in list(globals()):
623
+ if not name.startswith('_') and name not in ('basthon', 'sys', 'builtins'):
624
+ del globals()[name]
625
+ `);
626
+ } catch (error) {
627
+ console.error("Error while clearing Pyodide data:", error);
628
+ }
629
+ console.log("clearPyodideData done");
630
+ postMessage({ method: "handleLoaded", stdinBuffer, interruptBuffer });
631
+ };
632
+
633
+ const initialisePyodide = async () => {
634
+ postMessage({ method: "handleLoading" });
635
+
636
+ pyodidePromise = loadPyodide({
637
+ stdout: (content) => {
638
+ if (stopped) return;
639
+ if (userStdStreamsEnabled && !suppressInternalStdStreams) {
640
+ postMessage({ method: "handleOutput", stream: "stdout", content });
641
+ } else {
642
+ console.log(content);
643
+ }
644
+ },
645
+ stderr: (content) => {
646
+ if (stopped) return;
647
+ if (userStdStreamsEnabled && !suppressInternalStdStreams) {
648
+ postMessage({ method: "handleOutput", stream: "stderr", content });
649
+ } else {
650
+ console.error(content);
651
+ }
652
+ },
653
+ });
654
+
655
+ pyodide = await pyodidePromise;
656
+
657
+ pyodide.registerJsModule("basthon", fakeBasthonPackage);
658
+
659
+ // When SharedArrayBuffer is unavailable, always use the postMessage-based
660
+ // stdin path. JSPI / run_sync will raise at runtime if the environment
661
+ // cannot stack-switch, but in JSPI-capable browsers this enables
662
+ // interactive input() without COOP/COEP.
663
+ useMessageStdin = !supportsAllFeatures;
664
+ pyodide.globals.set("__stdin_via_message__", useMessageStdin);
665
+
666
+ await pyodide.runPythonAsync(`
667
+ import builtins
668
+ from pyodide.ffi import run_sync as __run_sync__
669
+
670
+ __old_input__ = builtins.input
671
+ def __patched_input__(prompt=None):
672
+ if prompt is not None:
673
+ print(prompt)
674
+ if __stdin_via_message__:
675
+ result = __run_sync__(basthon.kernel.getInputAsync())
676
+ if result is None:
677
+ raise EOFError("EOF when reading a line")
678
+ return result
679
+ return __old_input__()
680
+ builtins.input = __patched_input__
681
+ `);
682
+
683
+ await pyodide.runPythonAsync(`
684
+ import builtins
685
+ # Save the original open function only once
686
+ if not hasattr(builtins, "_original_open"):
687
+ builtins._original_open = builtins.open
688
+ _original_open = builtins._original_open
689
+ `);
690
+
691
+ await pyodide.loadPackage("pyodide-http");
692
+ await pyodide.runPythonAsync(`
693
+ import pyodide_http
694
+ pyodide_http.patch_all()
695
+ `);
696
+
697
+ if (supportsAllFeatures) {
698
+ stdinBuffer =
699
+ stdinBuffer || new Int32Array(new SharedArrayBuffer(1024 * 1024)); // 1 MiB
700
+ stdinBuffer[0] = 1; // Store the length of content in the buffer at index 0.
701
+ pyodide.setStdin({ isatty: true, read: readFromStdin });
702
+
703
+ interruptBuffer =
704
+ interruptBuffer || new Uint8Array(new SharedArrayBuffer(1));
705
+ pyodide.setInterruptBuffer(interruptBuffer);
706
+ }
707
+
708
+ // From this point on, anything written to stdout / stderr is considered
709
+ // user-visible and will be forwarded to the UI.
710
+ userStdStreamsEnabled = true;
711
+
712
+ postMessage({ method: "handleLoaded", stdinBuffer, interruptBuffer });
713
+ };
714
+
715
+ const readFromStdin = (bufferToWrite) => {
716
+ const previousLength = stdinBuffer[0];
717
+ postMessage({ method: "handleInput" });
718
+
719
+ while (true) {
720
+ pyodide.checkInterrupt();
721
+ const result = Atomics.wait(stdinBuffer, 0, previousLength, 100);
722
+ if (result === "not-equal") {
723
+ break;
724
+ }
725
+ }
726
+
727
+ const currentLength = stdinBuffer[0];
728
+ if (currentLength === -1) {
729
+ return 0;
730
+ } // Signals that stdin was closed.
731
+
732
+ const addedBytes = stdinBuffer.slice(previousLength, currentLength);
733
+ bufferToWrite.set(addedBytes);
734
+
735
+ return addedBytes.length;
736
+ };
737
+
738
+ const parsePythonError = (error) => {
739
+ const type = error.type;
740
+ const [trace, info] = error.message.split(`${type}:`).map((s) => s?.trim());
741
+
742
+ const lines = trace.split("\n");
743
+
744
+ // if the third from last line matches /File "__custom_open__\.py", line (\d+)/g then strip off the last three lines
745
+ if (
746
+ lines.length > 3 &&
747
+ /File "__custom_open__\.py", line (\d+)/g.test(lines[lines.length - 3])
748
+ ) {
749
+ lines.splice(-3, 3);
750
+ }
751
+
752
+ const snippetLine = lines[lines.length - 2]; // print("hi")invalid
753
+ const caretLine = lines[lines.length - 1]; // ^^^^^^^
754
+
755
+ const showsMistake = caretLine.includes("^");
756
+ const mistake = showsMistake
757
+ ? [snippetLine.slice(4), caretLine.slice(4)].join("\n")
758
+ : "";
759
+
760
+ const matches = [
761
+ ...trace.matchAll(/File "(?!__custom_open__\.py)(.*)", line (\d+)/g),
762
+ ];
763
+ const match = matches[matches.length - 1];
764
+
765
+ const path = match ? match[1] : "";
766
+ const base = path.split("/").reverse()[0];
767
+ const file = base === "<exec>" ? "main.py" : base;
768
+
769
+ const line = match ? parseInt(match[2], 10) : "";
770
+
771
+ return { file, line, mistake, type, info };
772
+ };
773
+ };
774
+
775
+ globalThis.PyodideWorker = PyodideWorker;
776
+ PyodideWorker();