| 1 |
import EmscriptenModule from "./python.mjs"; |
| 2 |
import fs from "node:fs"; |
| 3 |
import { initializeStreams } from "./streams.mjs"; |
| 4 |
|
| 5 |
if (process?.versions?.node) { |
| 6 |
const nodeVersion = Number(process.versions.node.split(".", 1)[0]); |
| 7 |
if (nodeVersion < 18) { |
| 8 |
process.stderr.write( |
| 9 |
`Node version must be >= 18, got version ${process.version}\n`, |
| 10 |
); |
| 11 |
process.exit(1); |
| 12 |
} |
| 13 |
} |
| 14 |
|
| 15 |
function rootDirsToMount(Module) { |
| 16 |
return fs |
| 17 |
.readdirSync("/") |
| 18 |
.filter((dir) => !["dev", "lib", "proc"].includes(dir)) |
| 19 |
.map((dir) => "/" + dir); |
| 20 |
} |
| 21 |
|
| 22 |
function mountDirectories(Module) { |
| 23 |
for (const dir of rootDirsToMount(Module)) { |
| 24 |
Module.FS.mkdirTree(dir); |
| 25 |
Module.FS.mount(Module.FS.filesystems.NODEFS, { root: dir }, dir); |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
const thisProgram = "--this-program="; |
| 30 |
const thisProgramIndex = process.argv.findIndex((x) => |
| 31 |
x.startsWith(thisProgram), |
| 32 |
); |
| 33 |
|
| 34 |
const settings = { |
| 35 |
preRun(Module) { |
| 36 |
// Globally expose API object so we can access it if we raise on startup. |
| 37 |
globalThis.Module = Module; |
| 38 |
mountDirectories(Module); |
| 39 |
Module.FS.chdir(process.cwd()); |
| 40 |
Object.assign(Module.ENV, process.env); |
| 41 |
delete Module.ENV.PATH; |
| 42 |
}, |
| 43 |
onRuntimeInitialized() { |
| 44 |
initializeStreams(Module.FS); |
| 45 |
}, |
| 46 |
// Ensure that sys.executable, sys._base_executable, etc point to python.sh |
| 47 |
// not to this file. To properly handle symlinks, python.sh needs to compute |
| 48 |
// its own path. |
| 49 |
thisProgram: process.argv[thisProgramIndex].slice(thisProgram.length), |
| 50 |
// After python.sh come the arguments thatthe user passed to python.sh. |
| 51 |
arguments: process.argv.slice(thisProgramIndex + 1), |
| 52 |
}; |
| 53 |
|
| 54 |
try { |
| 55 |
await EmscriptenModule(settings); |
| 56 |
} catch (e) { |
| 57 |
// Show JavaScript exception and traceback |
| 58 |
console.warn(e); |
| 59 |
// Show Python exception and traceback |
| 60 |
Module.__Py_DumpTraceback(2, Module._PyGILState_GetThisThreadState()); |
| 61 |
process.exit(1); |
| 62 |
} |