Debian Codegraph @

Platforms/emscripten/web_example/python.worker.mjs

raw
1 import createEmscriptenModule from "./python.mjs";
2
3 class StdinBuffer {
4 constructor() {
5 this.sab = new SharedArrayBuffer(128 * Int32Array.BYTES_PER_ELEMENT);
6 this.buffer = new Int32Array(this.sab);
7 this.readIndex = 1;
8 this.numberOfCharacters = 0;
9 this.sentNull = true;
10 }
11
12 prompt() {
13 this.readIndex = 1;
14 Atomics.store(this.buffer, 0, -1);
15 postMessage({
16 type: "stdin",
17 buffer: this.sab,
18 });
19 Atomics.wait(this.buffer, 0, -1);
20 this.numberOfCharacters = this.buffer[0];
21 }
22
23 stdin = () => {
24 while (this.numberOfCharacters + 1 === this.readIndex) {
25 if (!this.sentNull) {
26 // Must return null once to indicate we're done for now.
27 this.sentNull = true;
28 return null;
29 }
30 this.sentNull = false;
31 // Prompt will reset this.readIndex to 1
32 this.prompt();
33 }
34 const char = this.buffer[this.readIndex];
35 this.readIndex += 1;
36 return char;
37 };
38 }
39
40 const stdout = (charCode) => {
41 if (charCode) {
42 postMessage({
43 type: "stdout",
44 stdout: charCode,
45 });
46 } else {
47 console.log(typeof charCode, charCode);
48 }
49 };
50
51 const stderr = (charCode) => {
52 if (charCode) {
53 postMessage({
54 type: "stderr",
55 stderr: charCode,
56 });
57 } else {
58 console.log(typeof charCode, charCode);
59 }
60 };
61
62 const stdinBuffer = new StdinBuffer();
63
64 const emscriptenSettings = {
65 noInitialRun: true,
66 stdin: stdinBuffer.stdin,
67 stdout: stdout,
68 stderr: stderr,
69 onRuntimeInitialized: () => {
70 postMessage({ type: "ready", stdinBuffer: stdinBuffer.sab });
71 },
72 async preRun(Module) {
73 const versionInt = Module.HEAPU32[Module._Py_Version >>> 2];
74 const major = (versionInt >>> 24) & 0xff;
75 const minor = (versionInt >>> 16) & 0xff;
76 // Prevent complaints about not finding exec-prefix by making a lib-dynload directory
77 Module.FS.mkdirTree(`/lib/python${major}.${minor}/lib-dynload/`);
78 Module.addRunDependency("install-stdlib");
79 const resp = await fetch(`python${major}.${minor}.zip`);
80 const stdlibBuffer = await resp.arrayBuffer();
81 Module.FS.writeFile(
82 `/lib/python${major}${minor}.zip`,
83 new Uint8Array(stdlibBuffer),
84 { canOwn: true },
85 );
86 Module.removeRunDependency("install-stdlib");
87 },
88 };
89
90 const modulePromise = createEmscriptenModule(emscriptenSettings);
91
92 onmessage = async (event) => {
93 if (event.data.type === "run") {
94 const Module = await modulePromise;
95 if (event.data.files) {
96 for (const [filename, contents] of Object.entries(event.data.files)) {
97 Module.FS.writeFile(filename, contents);
98 }
99 }
100 const ret = Module.callMain(event.data.args);
101 postMessage({
102 type: "finished",
103 returnCode: ret,
104 });
105 }
106 };