| 154 | let currentElement; |
| 155 | |
| 156 | const registerModule = ({ XWorker, interpreter, io }) => { |
| 157 | // avoid multiple registration of the same interpreter |
| 158 | if (alreadyRegistered) return; |
| 159 | alreadyRegistered = true; |
| 160 | |
| 161 | // automatically use the pyscript stderr (when/if defined) |
| 162 | // this defaults to console.error |
| 163 | function PyWorker(...args) { |
| 164 | const worker = XWorker(...args); |
| 165 | worker.onerror = ({ error }) => io.stderr(error); |
| 166 | return worker; |
| 167 | } |
| 168 | |
| 169 | // enrich the Python env with some JS utility for main |
| 170 | interpreter.registerJsModule("_pyscript", { |
| 171 | PyWorker, |
| 172 | fs, |
| 173 | interpreter, |
| 174 | js_import: (...urls) => Promise.all(urls.map((url) => import(url))), |
| 175 | get target() { |
| 176 | return isScript(currentElement) |
| 177 | ? currentElement.target.id |
| 178 | : currentElement.id; |
| 179 | }, |
| 180 | }); |
| 181 | }; |
| 182 | |
| 183 | // ensure plugins are bootstrapped already before custom type definition |
| 184 | // NOTE: we cannot top-level await in here as plugins import other utilities |