gwchq-textjam 0.1.110 → 0.1.111

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