@pyscript/core 0.4.38 → 0.4.39

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.
package/dist/core.js CHANGED
@@ -1,2 +1,2 @@
1
- export{g as MPWorker,f as PyWorker,T as TYPES,h as config,e as hooks,i as inputFailure,o as offline_interpreter,b as optional,s as stdlib,j as whenDefined}from"./core-VeaFOAwh.js";
1
+ export{g as MPWorker,f as PyWorker,T as TYPES,h as config,e as hooks,i as inputFailure,o as offline_interpreter,b as optional,s as stdlib,j as whenDefined}from"./core-g43HEaAk.js";
2
2
  //# sourceMappingURL=core.js.map
@@ -1,2 +1,2 @@
1
- import{e}from"./core-VeaFOAwh.js";import{notify as o}from"./error-DUpRPSjM.js";function r(){const e=document.querySelectorAll("script");for(const o of e)s(o.src)}function s(e){/\/pyscript\.net\/latest/.test(e)&&o("Loading scripts from latest is deprecated and will be removed soon. Please use a specific version instead.")}e.main.onReady.add(r),e.main.onWorker.add(r);
2
- //# sourceMappingURL=deprecations-manager-Bkm58cNJ.js.map
1
+ import{e}from"./core-g43HEaAk.js";import{notify as o}from"./error-Cj1uxyP7.js";function r(){const e=document.querySelectorAll("script");for(const o of e)s(o.src)}function s(e){/\/pyscript\.net\/latest/.test(e)&&o("Loading scripts from latest is deprecated and will be removed soon. Please use a specific version instead.")}e.main.onReady.add(r),e.main.onWorker.add(r);
2
+ //# sourceMappingURL=deprecations-manager-mDHaG5A8.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"deprecations-manager-Bkm58cNJ.js","sources":["../src/plugins/deprecations-manager.js"],"sourcesContent":["// PyScript Derepcations Plugin\nimport { hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\n\n// react lazily on PyScript bootstrap\nhooks.main.onReady.add(checkDeprecations);\nhooks.main.onWorker.add(checkDeprecations);\n\n/**\n * Check that there are no scripts loading from pyscript.net/latest\n */\nfunction checkDeprecations() {\n const scripts = document.querySelectorAll(\"script\");\n for (const script of scripts) checkLoadingScriptsFromLatest(script.src);\n}\n\n/**\n * Check if src being loaded from pyscript.net/latest and display a notification if true\n * * @param {string} src\n */\nfunction checkLoadingScriptsFromLatest(src) {\n if (/\\/pyscript\\.net\\/latest/.test(src)) {\n notify(\n \"Loading scripts from latest is deprecated and will be removed soon. Please use a specific version instead.\",\n );\n }\n}\n"],"names":["checkDeprecations","scripts","document","querySelectorAll","script","checkLoadingScriptsFromLatest","src","test","notify","hooks","main","onReady","add","onWorker"],"mappings":"+EAWA,SAASA,IACL,MAAMC,EAAUC,SAASC,iBAAiB,UAC1C,IAAK,MAAMC,KAAUH,EAASI,EAA8BD,EAAOE,IACvE,CAMA,SAASD,EAA8BC,GAC/B,0BAA0BC,KAAKD,IAC/BE,EACI,6GAGZ,CArBAC,EAAMC,KAAKC,QAAQC,IAAIZ,GACvBS,EAAMC,KAAKG,SAASD,IAAIZ"}
1
+ {"version":3,"file":"deprecations-manager-mDHaG5A8.js","sources":["../src/plugins/deprecations-manager.js"],"sourcesContent":["// PyScript Derepcations Plugin\nimport { hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\n\n// react lazily on PyScript bootstrap\nhooks.main.onReady.add(checkDeprecations);\nhooks.main.onWorker.add(checkDeprecations);\n\n/**\n * Check that there are no scripts loading from pyscript.net/latest\n */\nfunction checkDeprecations() {\n const scripts = document.querySelectorAll(\"script\");\n for (const script of scripts) checkLoadingScriptsFromLatest(script.src);\n}\n\n/**\n * Check if src being loaded from pyscript.net/latest and display a notification if true\n * * @param {string} src\n */\nfunction checkLoadingScriptsFromLatest(src) {\n if (/\\/pyscript\\.net\\/latest/.test(src)) {\n notify(\n \"Loading scripts from latest is deprecated and will be removed soon. Please use a specific version instead.\",\n );\n }\n}\n"],"names":["checkDeprecations","scripts","document","querySelectorAll","script","checkLoadingScriptsFromLatest","src","test","notify","hooks","main","onReady","add","onWorker"],"mappings":"+EAWA,SAASA,IACL,MAAMC,EAAUC,SAASC,iBAAiB,UAC1C,IAAK,MAAMC,KAAUH,EAASI,EAA8BD,EAAOE,IACvE,CAMA,SAASD,EAA8BC,GAC/B,0BAA0BC,KAAKD,IAC/BE,EACI,6GAGZ,CArBAC,EAAMC,KAAKC,QAAQC,IAAIZ,GACvBS,EAAMC,KAAKG,SAASD,IAAIZ"}
@@ -1,2 +1,2 @@
1
- import{e}from"./core-VeaFOAwh.js";function n(e){const n=document.createElement("div");n.className="py-error",n.textContent=e,n.style.cssText="\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n ",document.body.append(n)}e.main.onReady.add((function o(r){e.main.onReady.delete(o);const{stderr:t}=r.io;r.io.stderr=(e,...o)=>(n(e.message||e),t(e,...o)),addEventListener("error",(({message:e})=>{e.startsWith("Uncaught PythonError")&&n(e)}))}));export{n as notify};
2
- //# sourceMappingURL=error-DUpRPSjM.js.map
1
+ import{e}from"./core-g43HEaAk.js";function n(e){const n=document.createElement("div");n.className="py-error",n.textContent=e,n.style.cssText="\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n ",document.body.append(n)}e.main.onReady.add((function o(r){e.main.onReady.delete(o);const{stderr:t}=r.io;r.io.stderr=(e,...o)=>(n(e.message||e),t(e,...o)),addEventListener("error",(({message:e})=>{e.startsWith("Uncaught PythonError")&&n(e)}))}));export{n as notify};
2
+ //# sourceMappingURL=error-Cj1uxyP7.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-DUpRPSjM.js","sources":["../src/plugins/error.js"],"sourcesContent":["// PyScript Error Plugin\nimport { hooks } from \"../core.js\";\n\nhooks.main.onReady.add(function override(pyScript) {\n // be sure this override happens only once\n hooks.main.onReady.delete(override);\n\n // trap generic `stderr` to propagate to it regardless\n const { stderr } = pyScript.io;\n\n // override it with our own logic\n pyScript.io.stderr = (error, ...rest) => {\n notify(error.message || error);\n // let other plugins or stderr hook, if any, do the rest\n return stderr(error, ...rest);\n };\n\n // be sure uncaught Python errors are also visible\n addEventListener(\"error\", ({ message }) => {\n if (message.startsWith(\"Uncaught PythonError\")) notify(message);\n });\n});\n\n// Error hook utilities\n\n// Custom function to show notifications\n\n/**\n * Add a banner to the top of the page, notifying the user of an error\n * @param {string} message\n */\nexport function notify(message) {\n const div = document.createElement(\"div\");\n div.className = \"py-error\";\n div.textContent = message;\n div.style.cssText = `\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n `;\n document.body.append(div);\n}\n"],"names":["notify","message","div","document","createElement","className","textContent","style","cssText","body","append","hooks","main","onReady","add","override","pyScript","delete","stderr","io","error","rest","addEventListener","startsWith"],"mappings":"kCA+BO,SAASA,EAAOC,GACnB,MAAMC,EAAMC,SAASC,cAAc,OACnCF,EAAIG,UAAY,WAChBH,EAAII,YAAcL,EAClBC,EAAIK,MAAMC,QAAU,6MAUpBL,SAASM,KAAKC,OAAOR,EACzB,CA3CAS,EAAMC,KAAKC,QAAQC,KAAI,SAASC,EAASC,GAErCL,EAAMC,KAAKC,QAAQI,OAAOF,GAG1B,MAAMG,OAAEA,GAAWF,EAASG,GAG5BH,EAASG,GAAGD,OAAS,CAACE,KAAUC,KAC5BrB,EAAOoB,EAAMnB,SAAWmB,GAEjBF,EAAOE,KAAUC,IAI5BC,iBAAiB,SAAS,EAAGrB,cACrBA,EAAQsB,WAAW,yBAAyBvB,EAAOC,EAAQ,GAEvE"}
1
+ {"version":3,"file":"error-Cj1uxyP7.js","sources":["../src/plugins/error.js"],"sourcesContent":["// PyScript Error Plugin\nimport { hooks } from \"../core.js\";\n\nhooks.main.onReady.add(function override(pyScript) {\n // be sure this override happens only once\n hooks.main.onReady.delete(override);\n\n // trap generic `stderr` to propagate to it regardless\n const { stderr } = pyScript.io;\n\n // override it with our own logic\n pyScript.io.stderr = (error, ...rest) => {\n notify(error.message || error);\n // let other plugins or stderr hook, if any, do the rest\n return stderr(error, ...rest);\n };\n\n // be sure uncaught Python errors are also visible\n addEventListener(\"error\", ({ message }) => {\n if (message.startsWith(\"Uncaught PythonError\")) notify(message);\n });\n});\n\n// Error hook utilities\n\n// Custom function to show notifications\n\n/**\n * Add a banner to the top of the page, notifying the user of an error\n * @param {string} message\n */\nexport function notify(message) {\n const div = document.createElement(\"div\");\n div.className = \"py-error\";\n div.textContent = message;\n div.style.cssText = `\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n `;\n document.body.append(div);\n}\n"],"names":["notify","message","div","document","createElement","className","textContent","style","cssText","body","append","hooks","main","onReady","add","override","pyScript","delete","stderr","io","error","rest","addEventListener","startsWith"],"mappings":"kCA+BO,SAASA,EAAOC,GACnB,MAAMC,EAAMC,SAASC,cAAc,OACnCF,EAAIG,UAAY,WAChBH,EAAII,YAAcL,EAClBC,EAAIK,MAAMC,QAAU,6MAUpBL,SAASM,KAAKC,OAAOR,EACzB,CA3CAS,EAAMC,KAAKC,QAAQC,KAAI,SAASC,EAASC,GAErCL,EAAMC,KAAKC,QAAQI,OAAOF,GAG1B,MAAMG,OAAEA,GAAWF,EAASG,GAG5BH,EAASG,GAAGD,OAAS,CAACE,KAAUC,KAC5BrB,EAAOoB,EAAMnB,SAAWmB,GAEjBF,EAAOE,KAAUC,IAI5BC,iBAAiB,SAAS,EAAGrB,cACrBA,EAAQsB,WAAW,yBAAyBvB,EAAOC,EAAQ,GAEvE"}
@@ -1,2 +1,2 @@
1
- import{e,i as r,d as t}from"./core-VeaFOAwh.js";const n=new WeakSet,i=({interpreter:e,io:r,run:t,type:n},{sync:i})=>{if("mpy"!==n||!i.is_pyterminal())return;const{pyterminal_ready:o,pyterminal_read:a,pyterminal_write:s}=i;e.registerJsModule("_pyscript_input",{input:a}),t(["from _pyscript_input import input","from polyscript import currentScript as _","__terminal__ = _.terminal","del _"].join(";"));const l=new Uint8Array([13]);r.stdout=e=>{10===e[0]&&s(l),s(e)},r.stderr=e=>{s(String(e.message||e))},e.registerJsModule("code",{interact(){const r=new TextEncoderStream;r.readable.pipeTo(new WritableStream({write(r){for(const t of r)e.replProcessChar(t)}}));const t=r.writable.getWriter();i.pyterminal_stream_write=e=>t.write(e),o(),e.replInit()}})};var o=async o=>{const[{Terminal:a},{FitAddon:s},{WebLinksAddon:l}]=await Promise.all([import("./xterm-BY7uk_OU.js"),import("./xterm_addon-fit--gyF3PcZ.js"),import("./xterm_addon-web-links-Cnej-nJ6.js")]),m={disableStdin:!1,cursorBlink:!0,cursorStyle:"block"};let d;const p=()=>{let e=o;const r=o.getAttribute("target");if(r){if(e=document.getElementById(r)||document.querySelector(r),!e)throw new Error(`Unknown target ${r}`)}else e=document.createElement("py-terminal"),e.style.display="block",o.after(e);const n=new a({theme:{background:"#191A19",foreground:"#F5F2E7"},...m}),i=new s;return n.loadAddon(i),n.loadAddon(new l),n.open(e),i.fit(),n.focus(),t(o,{terminal:{value:n},process:{value:async e=>{for(const r of e.split(/(?:\r\n|\r|\n)/))await d.write(`${r}\r`)}}}),n};o.hasAttribute("worker")?(e.main.onWorker.add((function r(t,i){if(n.has(i))return;n.add(i),e.main.onWorker.delete(r);const o=p(),{sync:a}=i;let s=null,l="";a.is_pyterminal=()=>!0,a.pyterminal_read=e=>(o.write(e),s=Promise.withResolvers(),s.promise),a.pyterminal_write=e=>{s||o.write(e)},a.pyterminal_ready=()=>{let e=Promise.resolve();d={write:r=>e=e.then((()=>a.pyterminal_stream_write(r)))},o.onData((e=>{s?(l+=e,o.write(e),l.endsWith("\r")&&(o.write("\n"),s.resolve(l.slice(0,-1)),s=null,l="")):d.write(e)}))}})),e.worker.onReady.add(i)):(e.main.codeBeforeRun.delete(r),e.main.onReady.add((function r({interpreter:t,io:n,run:i,type:o}){if("mpy"!==o)return;e.main.onReady.delete(r);const a=p(),s=new Uint8Array([13]);n.stdout=e=>{10===e[0]&&a.write(s),a.write(e)},globalThis.__py_terminal__=a,i(["from js import prompt as input","from js import __py_terminal__ as __terminal__"].join(";")),delete globalThis.__py_terminal__,t.registerJsModule("code",{interact(){const e=new TextEncoderStream;e.readable.pipeTo(new WritableStream({write(e){for(const r of e)t.replProcessChar(r)}})),d=e.writable.getWriter(),a.onData((e=>d.write(e))),t.replInit()}})})))};export{o as default};
2
- //# sourceMappingURL=mpy-BcmFt5Pp.js.map
1
+ import{e,i as r,d as t}from"./core-g43HEaAk.js";const n=new WeakSet,i=({interpreter:e,io:r,run:t,type:n},{sync:i})=>{if("mpy"!==n||!i.is_pyterminal())return;const{pyterminal_ready:o,pyterminal_read:a,pyterminal_write:s}=i;e.registerJsModule("_pyscript_input",{input:a}),t(["from _pyscript_input import input","from polyscript import currentScript as _","__terminal__ = _.terminal","del _"].join(";"));const l=new Uint8Array([13]);r.stdout=e=>{10===e[0]&&s(l),s(e)},r.stderr=e=>{s(String(e.message||e))},e.registerJsModule("code",{interact(){const r=new TextEncoderStream;r.readable.pipeTo(new WritableStream({write(r){for(const t of r)e.replProcessChar(t)}}));const t=r.writable.getWriter();i.pyterminal_stream_write=e=>t.write(e),o(),e.replInit()}})};var o=async o=>{const[{Terminal:a},{FitAddon:s},{WebLinksAddon:l}]=await Promise.all([import("./xterm-BY7uk_OU.js"),import("./xterm_addon-fit--gyF3PcZ.js"),import("./xterm_addon-web-links-Cnej-nJ6.js")]),m={disableStdin:!1,cursorBlink:!0,cursorStyle:"block"};let d;const p=()=>{let e=o;const r=o.getAttribute("target");if(r){if(e=document.getElementById(r)||document.querySelector(r),!e)throw new Error(`Unknown target ${r}`)}else e=document.createElement("py-terminal"),e.style.display="block",o.after(e);const n=new a({theme:{background:"#191A19",foreground:"#F5F2E7"},...m}),i=new s;return n.loadAddon(i),n.loadAddon(new l),n.open(e),i.fit(),n.focus(),t(o,{terminal:{value:n},process:{value:async e=>{for(const r of e.split(/(?:\r\n|\r|\n)/))await d.write(`${r}\r`)}}}),n};o.hasAttribute("worker")?(e.main.onWorker.add((function r(t,i){if(n.has(i))return;n.add(i),e.main.onWorker.delete(r);const o=p(),{sync:a}=i;let s=null,l="";a.is_pyterminal=()=>!0,a.pyterminal_read=e=>(o.write(e),s=Promise.withResolvers(),s.promise),a.pyterminal_write=e=>{s||o.write(e)},a.pyterminal_ready=()=>{let e=Promise.resolve();d={write:r=>e=e.then((()=>a.pyterminal_stream_write(r)))},o.onData((e=>{s?(l+=e,o.write(e),l.endsWith("\r")&&(o.write("\n"),s.resolve(l.slice(0,-1)),s=null,l="")):d.write(e)}))}})),e.worker.onReady.add(i)):(e.main.codeBeforeRun.delete(r),e.main.onReady.add((function r({interpreter:t,io:n,run:i,type:o}){if("mpy"!==o)return;e.main.onReady.delete(r);const a=p(),s=new Uint8Array([13]);n.stdout=e=>{10===e[0]&&a.write(s),a.write(e)},globalThis.__py_terminal__=a,i(["from js import prompt as input","from js import __py_terminal__ as __terminal__"].join(";")),delete globalThis.__py_terminal__,t.registerJsModule("code",{interact(){const e=new TextEncoderStream;e.readable.pipeTo(new WritableStream({write(e){for(const r of e)t.replProcessChar(r)}})),d=e.writable.getWriter(),a.onData((e=>d.write(e))),t.replInit()}})})))};export{o as default};
2
+ //# sourceMappingURL=mpy-C8sNSuAP.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mpy-BcmFt5Pp.js","sources":["../src/plugins/py-terminal/mpy.js"],"sourcesContent":["// PyScript pyodide terminal plugin\nimport { hooks, inputFailure } from \"../../core.js\";\nimport { defineProperties } from \"polyscript/exports\";\n\nconst bootstrapped = new WeakSet();\n\n// this callback will be serialized as string and it never needs\n// to be invoked multiple times. Each xworker here is bootstrapped\n// only once thanks to the `sync.is_pyterminal()` check.\nconst workerReady = ({ interpreter, io, run, type }, { sync }) => {\n if (type !== \"mpy\" || !sync.is_pyterminal()) return;\n\n const { pyterminal_ready, pyterminal_read, pyterminal_write } = sync;\n\n interpreter.registerJsModule(\"_pyscript_input\", {\n input: pyterminal_read,\n });\n\n run(\n [\n \"from _pyscript_input import input\",\n \"from polyscript import currentScript as _\",\n \"__terminal__ = _.terminal\",\n \"del _\",\n ].join(\";\"),\n );\n\n const missingReturn = new Uint8Array([13]);\n io.stdout = (buffer) => {\n if (buffer[0] === 10) pyterminal_write(missingReturn);\n pyterminal_write(buffer);\n };\n io.stderr = (error) => {\n pyterminal_write(String(error.message || error));\n };\n\n // tiny shim of the code module with only interact\n // to bootstrap a REPL like environment\n interpreter.registerJsModule(\"code\", {\n interact() {\n const encoder = new TextEncoderStream();\n encoder.readable.pipeTo(\n new WritableStream({\n write(buffer) {\n for (const c of buffer) interpreter.replProcessChar(c);\n },\n }),\n );\n\n const writer = encoder.writable.getWriter();\n sync.pyterminal_stream_write = (buffer) => writer.write(buffer);\n pyterminal_ready();\n\n interpreter.replInit();\n },\n });\n};\n\nexport default async (element) => {\n // lazy load these only when a valid terminal is found\n const [{ Terminal }, { FitAddon }, { WebLinksAddon }] = await Promise.all([\n import(/* webpackIgnore: true */ \"../../3rd-party/xterm.js\"),\n import(/* webpackIgnore: true */ \"../../3rd-party/xterm_addon-fit.js\"),\n import(\n /* webpackIgnore: true */ \"../../3rd-party/xterm_addon-web-links.js\"\n ),\n ]);\n\n const terminalOptions = {\n disableStdin: false,\n cursorBlink: true,\n cursorStyle: \"block\",\n };\n\n let stream;\n\n // common main thread initialization for both worker\n // or main case, bootstrapping the terminal on its target\n const init = () => {\n let target = element;\n const selector = element.getAttribute(\"target\");\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(\"py-terminal\");\n target.style.display = \"block\";\n element.after(target);\n }\n const terminal = new Terminal({\n theme: {\n background: \"#191A19\",\n foreground: \"#F5F2E7\",\n },\n ...terminalOptions,\n });\n const fitAddon = new FitAddon();\n terminal.loadAddon(fitAddon);\n terminal.loadAddon(new WebLinksAddon());\n terminal.open(target);\n fitAddon.fit();\n terminal.focus();\n defineProperties(element, {\n terminal: { value: terminal },\n process: {\n value: async (code) => {\n for (const line of code.split(/(?:\\r\\n|\\r|\\n)/)) {\n await stream.write(`${line}\\r`);\n }\n },\n },\n });\n return terminal;\n };\n\n // branch logic for the worker\n if (element.hasAttribute(\"worker\")) {\n // add a hook on the main thread to setup all sync helpers\n // also bootstrapping the XTerm target on main *BUT* ...\n hooks.main.onWorker.add(function worker(_, xworker) {\n // ... as multiple workers will add multiple callbacks\n // be sure no xworker is ever initialized twice!\n if (bootstrapped.has(xworker)) return;\n bootstrapped.add(xworker);\n\n // still cleanup this callback for future scripts/workers\n hooks.main.onWorker.delete(worker);\n\n const terminal = init();\n\n const { sync } = xworker;\n\n // handle the read mode on input\n let promisedChunks = null;\n let readChunks = \"\";\n\n sync.is_pyterminal = () => true;\n\n // put the terminal in a read-only state\n // frees the worker on \\r\n sync.pyterminal_read = (buffer) => {\n terminal.write(buffer);\n promisedChunks = Promise.withResolvers();\n return promisedChunks.promise;\n };\n\n // write if not reading input\n sync.pyterminal_write = (buffer) => {\n if (!promisedChunks) terminal.write(buffer);\n };\n\n // add the onData terminal listener which forwards to the worker\n // everything typed in a queued char-by-char way\n sync.pyterminal_ready = () => {\n let queue = Promise.resolve();\n stream = {\n write: (buffer) =>\n (queue = queue.then(() =>\n sync.pyterminal_stream_write(buffer),\n )),\n };\n terminal.onData((buffer) => {\n if (promisedChunks) {\n readChunks += buffer;\n terminal.write(buffer);\n if (readChunks.endsWith(\"\\r\")) {\n terminal.write(\"\\n\");\n promisedChunks.resolve(readChunks.slice(0, -1));\n promisedChunks = null;\n readChunks = \"\";\n }\n } else {\n stream.write(buffer);\n }\n });\n };\n });\n\n // setup remote thread JS/Python code for whenever the\n // worker is ready to become a terminal\n hooks.worker.onReady.add(workerReady);\n } else {\n // ⚠️ In an ideal world the inputFailure should never be used on main.\n // However, Pyodide still can't compete with MicroPython REPL mode\n // so while it's OK to keep that entry on main as default, we need\n // to remove it ASAP from `mpy` use cases, otherwise MicroPython would\n // also throw whenever an `input(...)` is required / digited.\n hooks.main.codeBeforeRun.delete(inputFailure);\n\n // in the main case, just bootstrap XTerm without\n // allowing any input as that's not possible / awkward\n hooks.main.onReady.add(function main({ interpreter, io, run, type }) {\n if (type !== \"mpy\") return;\n\n hooks.main.onReady.delete(main);\n\n const terminal = init();\n\n const missingReturn = new Uint8Array([13]);\n io.stdout = (buffer) => {\n if (buffer[0] === 10) terminal.write(missingReturn);\n terminal.write(buffer);\n };\n\n // expose the __terminal__ one-off reference\n globalThis.__py_terminal__ = terminal;\n run(\n [\n \"from js import prompt as input\",\n \"from js import __py_terminal__ as __terminal__\",\n ].join(\";\"),\n );\n delete globalThis.__py_terminal__;\n\n // NOTE: this is NOT the same as the one within\n // the onWorkerReady callback!\n interpreter.registerJsModule(\"code\", {\n interact() {\n const encoder = new TextEncoderStream();\n encoder.readable.pipeTo(\n new WritableStream({\n write(buffer) {\n for (const c of buffer)\n interpreter.replProcessChar(c);\n },\n }),\n );\n\n stream = encoder.writable.getWriter();\n terminal.onData((buffer) => stream.write(buffer));\n\n interpreter.replInit();\n },\n });\n });\n }\n};\n"],"names":["bootstrapped","WeakSet","workerReady","interpreter","io","run","type","sync","is_pyterminal","pyterminal_ready","pyterminal_read","pyterminal_write","registerJsModule","input","join","missingReturn","Uint8Array","stdout","buffer","stderr","error","String","message","interact","encoder","TextEncoderStream","readable","pipeTo","WritableStream","write","c","replProcessChar","writer","writable","getWriter","pyterminal_stream_write","replInit","mpy","async","element","Terminal","FitAddon","WebLinksAddon","Promise","all","import","terminalOptions","disableStdin","cursorBlink","cursorStyle","stream","init","target","selector","getAttribute","document","getElementById","querySelector","Error","createElement","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperties","value","process","code","line","split","hasAttribute","hooks","main","onWorker","add","worker","_","xworker","has","delete","promisedChunks","readChunks","withResolvers","promise","queue","resolve","then","onData","endsWith","slice","onReady","codeBeforeRun","inputFailure","globalThis","__py_termin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AAOe,QAAQhB,IAAIhF,KAOzB6E,EAAMC,KAAKmB,cAAcZ,OAAOa,GAIhCrB,EAAMC,KAAKkB,QAAQhB,KAAI,SAASF,GAAK7E,YAAEA,EAAWC,GAAEA,EAAEC,IAAEA,EAAGC,KAAEA,IACzD,GAAa,QAATA,EAAgB,OAEpByE,EAAMC,KAAKkB,QAAQX,OAAOP,GAE1B,MAAMjB,EAAWZ,IAEXpC,EAAgB,IAAIC,WAAW,CAAC,KACtCZ,EAAGa,OAAUC,IACS,KAAdA,EAAO,IAAW6C,EAASlC,MAAMd,GACrCgD,EAASlC,MAAMX,EAAO,EAI1BmF,WAAWC,gBAAkBvC,EAC7B1D,EACI,CACI,iCACA,kDACFS,KAAK,aAEJuF,WAAWC,gBAIlBnG,EAAYS,iBAAiB,OAAQ,CACjC,QAAAW,GACI,MAAMC,EAAU,IAAIC,kBACpBD,EAAQE,SAASC,OACb,IAAIC,eAAe,CACf,KAAAC,CAAMX,GACF,IAAK,MAAMY,KAAKZ,EACZf,EAAY4B,gBAAgBD,EACnC,KAIToB,EAAS1B,EAAQS,SAASC,YAC1B6B,EAASgC,QAAQ7E,GAAWgC,EAAOrB,MAAMX,KAEzCf,EAAYiC,UACf,GAEjB,IACK"}
1
+ {"version":3,"file":"mpy-C8sNSuAP.js","sources":["../src/plugins/py-terminal/mpy.js"],"sourcesContent":["// PyScript pyodide terminal plugin\nimport { hooks, inputFailure } from \"../../core.js\";\nimport { defineProperties } from \"polyscript/exports\";\n\nconst bootstrapped = new WeakSet();\n\n// this callback will be serialized as string and it never needs\n// to be invoked multiple times. Each xworker here is bootstrapped\n// only once thanks to the `sync.is_pyterminal()` check.\nconst workerReady = ({ interpreter, io, run, type }, { sync }) => {\n if (type !== \"mpy\" || !sync.is_pyterminal()) return;\n\n const { pyterminal_ready, pyterminal_read, pyterminal_write } = sync;\n\n interpreter.registerJsModule(\"_pyscript_input\", {\n input: pyterminal_read,\n });\n\n run(\n [\n \"from _pyscript_input import input\",\n \"from polyscript import currentScript as _\",\n \"__terminal__ = _.terminal\",\n \"del _\",\n ].join(\";\"),\n );\n\n const missingReturn = new Uint8Array([13]);\n io.stdout = (buffer) => {\n if (buffer[0] === 10) pyterminal_write(missingReturn);\n pyterminal_write(buffer);\n };\n io.stderr = (error) => {\n pyterminal_write(String(error.message || error));\n };\n\n // tiny shim of the code module with only interact\n // to bootstrap a REPL like environment\n interpreter.registerJsModule(\"code\", {\n interact() {\n const encoder = new TextEncoderStream();\n encoder.readable.pipeTo(\n new WritableStream({\n write(buffer) {\n for (const c of buffer) interpreter.replProcessChar(c);\n },\n }),\n );\n\n const writer = encoder.writable.getWriter();\n sync.pyterminal_stream_write = (buffer) => writer.write(buffer);\n pyterminal_ready();\n\n interpreter.replInit();\n },\n });\n};\n\nexport default async (element) => {\n // lazy load these only when a valid terminal is found\n const [{ Terminal }, { FitAddon }, { WebLinksAddon }] = await Promise.all([\n import(/* webpackIgnore: true */ \"../../3rd-party/xterm.js\"),\n import(/* webpackIgnore: true */ \"../../3rd-party/xterm_addon-fit.js\"),\n import(\n /* webpackIgnore: true */ \"../../3rd-party/xterm_addon-web-links.js\"\n ),\n ]);\n\n const terminalOptions = {\n disableStdin: false,\n cursorBlink: true,\n cursorStyle: \"block\",\n };\n\n let stream;\n\n // common main thread initialization for both worker\n // or main case, bootstrapping the terminal on its target\n const init = () => {\n let target = element;\n const selector = element.getAttribute(\"target\");\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(\"py-terminal\");\n target.style.display = \"block\";\n element.after(target);\n }\n const terminal = new Terminal({\n theme: {\n background: \"#191A19\",\n foreground: \"#F5F2E7\",\n },\n ...terminalOptions,\n });\n const fitAddon = new FitAddon();\n terminal.loadAddon(fitAddon);\n terminal.loadAddon(new WebLinksAddon());\n terminal.open(target);\n fitAddon.fit();\n terminal.focus();\n defineProperties(element, {\n terminal: { value: terminal },\n process: {\n value: async (code) => {\n for (const line of code.split(/(?:\\r\\n|\\r|\\n)/)) {\n await stream.write(`${line}\\r`);\n }\n },\n },\n });\n return terminal;\n };\n\n // branch logic for the worker\n if (element.hasAttribute(\"worker\")) {\n // add a hook on the main thread to setup all sync helpers\n // also bootstrapping the XTerm target on main *BUT* ...\n hooks.main.onWorker.add(function worker(_, xworker) {\n // ... as multiple workers will add multiple callbacks\n // be sure no xworker is ever initialized twice!\n if (bootstrapped.has(xworker)) return;\n bootstrapped.add(xworker);\n\n // still cleanup this callback for future scripts/workers\n hooks.main.onWorker.delete(worker);\n\n const terminal = init();\n\n const { sync } = xworker;\n\n // handle the read mode on input\n let promisedChunks = null;\n let readChunks = \"\";\n\n sync.is_pyterminal = () => true;\n\n // put the terminal in a read-only state\n // frees the worker on \\r\n sync.pyterminal_read = (buffer) => {\n terminal.write(buffer);\n promisedChunks = Promise.withResolvers();\n return promisedChunks.promise;\n };\n\n // write if not reading input\n sync.pyterminal_write = (buffer) => {\n if (!promisedChunks) terminal.write(buffer);\n };\n\n // add the onData terminal listener which forwards to the worker\n // everything typed in a queued char-by-char way\n sync.pyterminal_ready = () => {\n let queue = Promise.resolve();\n stream = {\n write: (buffer) =>\n (queue = queue.then(() =>\n sync.pyterminal_stream_write(buffer),\n )),\n };\n terminal.onData((buffer) => {\n if (promisedChunks) {\n readChunks += buffer;\n terminal.write(buffer);\n if (readChunks.endsWith(\"\\r\")) {\n terminal.write(\"\\n\");\n promisedChunks.resolve(readChunks.slice(0, -1));\n promisedChunks = null;\n readChunks = \"\";\n }\n } else {\n stream.write(buffer);\n }\n });\n };\n });\n\n // setup remote thread JS/Python code for whenever the\n // worker is ready to become a terminal\n hooks.worker.onReady.add(workerReady);\n } else {\n // ⚠️ In an ideal world the inputFailure should never be used on main.\n // However, Pyodide still can't compete with MicroPython REPL mode\n // so while it's OK to keep that entry on main as default, we need\n // to remove it ASAP from `mpy` use cases, otherwise MicroPython would\n // also throw whenever an `input(...)` is required / digited.\n hooks.main.codeBeforeRun.delete(inputFailure);\n\n // in the main case, just bootstrap XTerm without\n // allowing any input as that's not possible / awkward\n hooks.main.onReady.add(function main({ interpreter, io, run, type }) {\n if (type !== \"mpy\") return;\n\n hooks.main.onReady.delete(main);\n\n const terminal = init();\n\n const missingReturn = new Uint8Array([13]);\n io.stdout = (buffer) => {\n if (buffer[0] === 10) terminal.write(missingReturn);\n terminal.write(buffer);\n };\n\n // expose the __terminal__ one-off reference\n globalThis.__py_terminal__ = terminal;\n run(\n [\n \"from js import prompt as input\",\n \"from js import __py_terminal__ as __terminal__\",\n ].join(\";\"),\n );\n delete globalThis.__py_terminal__;\n\n // NOTE: this is NOT the same as the one within\n // the onWorkerReady callback!\n interpreter.registerJsModule(\"code\", {\n interact() {\n const encoder = new TextEncoderStream();\n encoder.readable.pipeTo(\n new WritableStream({\n write(buffer) {\n for (const c of buffer)\n interpreter.replProcessChar(c);\n },\n }),\n );\n\n stream = encoder.writable.getWriter();\n terminal.onData((buffer) => stream.write(buffer));\n\n interpreter.replInit();\n },\n });\n });\n }\n};\n"],"names":["bootstrapped","WeakSet","workerReady","interpreter","io","run","type","sync","is_pyterminal","pyterminal_ready","pyterminal_read","pyterminal_write","registerJsModule","input","join","missingReturn","Uint8Array","stdout","buffer","stderr","error","String","message","interact","encoder","TextEncoderStream","readable","pipeTo","WritableStream","write","c","replProcessChar","writer","writable","getWriter","pyterminal_stream_write","replInit","mpy","async","element","Terminal","FitAddon","WebLinksAddon","Promise","all","import","terminalOptions","disableStdin","cursorBlink","cursorStyle","stream","init","target","selector","getAttribute","document","getElementById","querySelector","Error","createElement","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperties","value","process","code","line","split","hasAttribute","hooks","main","onWorker","add","worker","_","xworker","has","delete","promisedChunks","readChunks","withResolvers","promise","queue","resolve","then","onData","endsWith","slice","onReady","codeBeforeRun","inputFailure","globalThis","__py_terminal__"],"mappings":"gDAIA,MAAMA,EAAe,IAAIC,QAKnBC,EAA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cZ,OAAOa,GAIhCrB,EAAMC,KAAKkB,QAAQhB,KAAI,SAASF,GAAK7E,YAAEA,EAAWC,GAAEA,EAAEC,IAAEA,EAAGC,KAAEA,IACzD,GAAa,QAATA,EAAgB,OAEpByE,EAAMC,KAAKkB,QAAQX,OAAOP,GAE1B,MAAMjB,EAAWZ,IAEXpC,EAAgB,IAAIC,WAAW,CAAC,KACtCZ,EAAGa,OAAUC,IACS,KAAdA,EAAO,IAAW6C,EAASlC,MAAMd,GACrCgD,EAASlC,MAAMX,EAAO,EAI1BmF,WAAWC,gBAAkBvC,EAC7B1D,EACI,CACI,iCACA,kDACFS,KAAK,aAEJuF,WAAWC,gBAIlBnG,EAAYS,iBAAiB,OAAQ,CACjC,QAAAW,GACI,MAAMC,EAAU,IAAIC,kBACpBD,EAAQE,SAASC,OACb,IAAIC,eAAe,CACf,KAAAC,CAAMX,GACF,IAAK,MAAMY,KAAKZ,EACZf,EAAY4B,gBAAgBD,EACnC,KAIToB,EAAS1B,EAAQS,SAASC,YAC1B6B,EAASgC,QAAQ7E,GAAWgC,EAAOrB,MAAMX,KAEzCf,EAAYiC,UACf,GAEjB,IACK"}
@@ -1,2 +1,2 @@
1
- import{e,d as t}from"./core-VeaFOAwh.js";const r=new WeakSet,n=({interpreter:e,io:t,run:r,type:n},{sync:i})=>{if("py"!==n||!i.is_pyterminal())return;r(["from polyscript import currentScript as _","__terminal__ = _.terminal","del _"].join(";"));let o="";const{pyterminal_read:a,pyterminal_write:d}=i,s=new TextDecoder,l={isatty:!1,write:e=>(o=s.decode(e),d(o),e.length)};t.stderr=e=>{d(String(e.message||e))},e.setStdout(l),e.setStderr(l),e.setStdin({isatty:!1,stdin:()=>a(o)})};var i=async i=>{const[{Terminal:o},{Readline:a},{FitAddon:d},{WebLinksAddon:s}]=await Promise.all([import("./xterm-BY7uk_OU.js"),import("./xterm-readline-D247p8vq.js"),import("./xterm_addon-fit--gyF3PcZ.js"),import("./xterm_addon-web-links-Cnej-nJ6.js")]),l=new a,m=e=>{let r=i;const n=i.getAttribute("target");if(n){if(r=document.getElementById(n)||document.querySelector(n),!r)throw new Error(`Unknown target ${n}`)}else r=document.createElement("py-terminal"),r.style.display="block",i.after(r);const a=new o({theme:{background:"#191A19",foreground:"#F5F2E7"},...e}),m=new d;return a.loadAddon(m),a.loadAddon(l),a.loadAddon(new s),a.open(r),m.fit(),a.focus(),t(i,{terminal:{value:a},process:{value:async e=>{for(const t of e.split(/(?:\r\n|\r|\n)/)){a.paste(`${t}`),a.write("\r\n");do{await new Promise((e=>setTimeout(e,0)))}while(!l.activeRead?.resolve);l.activeRead.resolve(t)}}}}),a};i.hasAttribute("worker")?(e.main.onWorker.add((function t(n,i){r.has(i)||(r.add(i),e.main.onWorker.delete(t),m({disableStdin:!1,cursorBlink:!0,cursorStyle:"block"}),i.sync.is_pyterminal=()=>!0,i.sync.pyterminal_read=l.read.bind(l),i.sync.pyterminal_write=l.write.bind(l))})),e.worker.onReady.add(n)):e.main.onReady.add((function t({interpreter:r,io:n,run:i,type:o}){if("py"!==o)return;console.warn("py-terminal is read only on main thread"),e.main.onReady.delete(t),globalThis.__py_terminal__=m({disableStdin:!0,cursorBlink:!1,cursorStyle:"underline"}),i("from js import __py_terminal__ as __terminal__"),delete globalThis.__py_terminal__,n.stderr=e=>{l.write(String(e.message||e))};let a="";const d=new TextDecoder,s={isatty:!1,write:e=>(a=d.decode(e),l.write(a),e.length)};r.setStdout(s),r.setStderr(s),r.setStdin({isatty:!1,stdin:()=>l.read(a)})}))};export{i as default};
2
- //# sourceMappingURL=py-BhqrNMZk.js.map
1
+ import{e,d as t}from"./core-g43HEaAk.js";const r=new WeakSet,n=({interpreter:e,io:t,run:r,type:n},{sync:i})=>{if("py"!==n||!i.is_pyterminal())return;r(["from polyscript import currentScript as _","__terminal__ = _.terminal","del _"].join(";"));let o="";const{pyterminal_read:a,pyterminal_write:d}=i,s=new TextDecoder,l={isatty:!1,write:e=>(o=s.decode(e),d(o),e.length)};t.stderr=e=>{d(String(e.message||e))},e.setStdout(l),e.setStderr(l),e.setStdin({isatty:!1,stdin:()=>a(o)})};var i=async i=>{const[{Terminal:o},{Readline:a},{FitAddon:d},{WebLinksAddon:s}]=await Promise.all([import("./xterm-BY7uk_OU.js"),import("./xterm-readline-D247p8vq.js"),import("./xterm_addon-fit--gyF3PcZ.js"),import("./xterm_addon-web-links-Cnej-nJ6.js")]),l=new a,m=e=>{let r=i;const n=i.getAttribute("target");if(n){if(r=document.getElementById(n)||document.querySelector(n),!r)throw new Error(`Unknown target ${n}`)}else r=document.createElement("py-terminal"),r.style.display="block",i.after(r);const a=new o({theme:{background:"#191A19",foreground:"#F5F2E7"},...e}),m=new d;return a.loadAddon(m),a.loadAddon(l),a.loadAddon(new s),a.open(r),m.fit(),a.focus(),t(i,{terminal:{value:a},process:{value:async e=>{for(const t of e.split(/(?:\r\n|\r|\n)/)){a.paste(`${t}`),a.write("\r\n");do{await new Promise((e=>setTimeout(e,0)))}while(!l.activeRead?.resolve);l.activeRead.resolve(t)}}}}),a};i.hasAttribute("worker")?(e.main.onWorker.add((function t(n,i){r.has(i)||(r.add(i),e.main.onWorker.delete(t),m({disableStdin:!1,cursorBlink:!0,cursorStyle:"block"}),i.sync.is_pyterminal=()=>!0,i.sync.pyterminal_read=l.read.bind(l),i.sync.pyterminal_write=l.write.bind(l))})),e.worker.onReady.add(n)):e.main.onReady.add((function t({interpreter:r,io:n,run:i,type:o}){if("py"!==o)return;console.warn("py-terminal is read only on main thread"),e.main.onReady.delete(t),globalThis.__py_terminal__=m({disableStdin:!0,cursorBlink:!1,cursorStyle:"underline"}),i("from js import __py_terminal__ as __terminal__"),delete globalThis.__py_terminal__,n.stderr=e=>{l.write(String(e.message||e))};let a="";const d=new TextDecoder,s={isatty:!1,write:e=>(a=d.decode(e),l.write(a),e.length)};r.setStdout(s),r.setStderr(s),r.setStdin({isatty:!1,stdin:()=>l.read(a)})}))};export{i as default};
2
+ //# sourceMappingURL=py-BBDA21Aq.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-BhqrNMZk.js","sources":["../src/plugins/py-terminal/py.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { hooks } from \"../../core.js\";\nimport { defineProperties } from \"polyscript/exports\";\n\nconst bootstrapped = new WeakSet();\n\n// this callback will be serialized as string and it never needs\n// to be invoked multiple times. Each xworker here is bootstrapped\n// only once thanks to the `sync.is_pyterminal()` check.\nconst workerReady = ({ interpreter, io, run, type }, { sync }) => {\n if (type !== \"py\" || !sync.is_pyterminal()) return;\n\n run(\n [\n \"from polyscript import currentScript as _\",\n \"__terminal__ = _.terminal\",\n \"del _\",\n ].join(\";\"),\n );\n\n let data = \"\";\n const { pyterminal_read, pyterminal_write } = sync;\n const decoder = new TextDecoder();\n const generic = {\n isatty: false,\n write(buffer) {\n data = decoder.decode(buffer);\n pyterminal_write(data);\n return buffer.length;\n },\n };\n\n io.stderr = (error) => {\n pyterminal_write(String(error.message || error));\n };\n\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: false,\n stdin: () => pyterminal_read(data),\n });\n};\n\nexport default async (element) => {\n // lazy load these only when a valid terminal is found\n const [{ Terminal }, { Readline }, { FitAddon }, { WebLinksAddon }] =\n await Promise.all([\n import(/* webpackIgnore: true */ \"../../3rd-party/xterm.js\"),\n import(\n /* webpackIgnore: true */ \"../../3rd-party/xterm-readline.js\"\n ),\n import(\n /* webpackIgnore: true */ \"../../3rd-party/xterm_addon-fit.js\"\n ),\n import(\n /* webpackIgnore: true */ \"../../3rd-party/xterm_addon-web-links.js\"\n ),\n ]);\n\n const readline = new Readline();\n\n // common main thread initialization for both worker\n // or main case, bootstrapping the terminal on its target\n const init = (options) => {\n let target = element;\n const selector = element.getAttribute(\"target\");\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(\"py-terminal\");\n target.style.display = \"block\";\n element.after(target);\n }\n const terminal = new Terminal({\n theme: {\n background: \"#191A19\",\n foreground: \"#F5F2E7\",\n },\n ...options,\n });\n const fitAddon = new FitAddon();\n terminal.loadAddon(fitAddon);\n terminal.loadAddon(readline);\n terminal.loadAddon(new WebLinksAddon());\n terminal.open(target);\n fitAddon.fit();\n terminal.focus();\n defineProperties(element, {\n terminal: { value: terminal },\n process: {\n value: async (code) => {\n for (const line of code.split(/(?:\\r\\n|\\r|\\n)/)) {\n terminal.paste(`${line}`);\n terminal.write(\"\\r\\n\");\n do {\n await new Promise((resolve) =>\n setTimeout(resolve, 0),\n );\n } while (!readline.activeRead?.resolve);\n readline.activeRead.resolve(line);\n }\n },\n },\n });\n return terminal;\n };\n\n // branch logic for the worker\n if (element.hasAttribute(\"worker\")) {\n // add a hook on the main thread to setup all sync helpers\n // also bootstrapping the XTerm target on main *BUT* ...\n hooks.main.onWorker.add(function worker(_, xworker) {\n // ... as multiple workers will add multiple callbacks\n // be sure no xworker is ever initialized twice!\n if (bootstrapped.has(xworker)) return;\n bootstrapped.add(xworker);\n\n // still cleanup this callback for future scripts/workers\n hooks.main.onWorker.delete(worker);\n\n init({\n disableStdin: false,\n cursorBlink: true,\n cursorStyle: \"block\",\n });\n\n xworker.sync.is_pyterminal = () => true;\n xworker.sync.pyterminal_read = readline.read.bind(readline);\n xworker.sync.pyterminal_write = readline.write.bind(readline);\n });\n\n // setup remote thread JS/Python code for whenever the\n // worker is ready to become a terminal\n hooks.worker.onReady.add(workerReady);\n } else {\n // in the main case, just bootstrap XTerm without\n // allowing any input as that's not possible / awkward\n hooks.main.onReady.add(function main({ interpreter, io, run, type }) {\n if (type !== \"py\") return;\n\n console.warn(\"py-terminal is read only on main thread\");\n hooks.main.onReady.delete(main);\n\n // on main, it's easy to trash and clean the current terminal\n globalThis.__py_terminal__ = init({\n disableStdin: true,\n cursorBlink: false,\n cursorStyle: \"underline\",\n });\n run(\"from js import __py_terminal__ as __terminal__\");\n delete globalThis.__py_terminal__;\n\n io.stderr = (error) => {\n readline.write(String(error.message || error));\n };\n\n let data = \"\";\n const decoder = new TextDecoder();\n const generic = {\n isatty: false,\n write(buffer) {\n data = decoder.decode(buffer);\n readline.write(data);\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: false,\n stdin: () => readline.read(data),\n });\n });\n }\n};\n"],"names":["bootstrapped","WeakSet","workerReady","interpreter","io","run","type","sync","is_pyterminal","join","data","pyterminal_read","pyterminal_write","decoder","TextDecoder","generic","isatty","write","buffer","decode","length","stderr","error","String","message","setStdout","setStderr","setStdin","stdin","py","async","element","Terminal","Readline","FitAddon","WebLinksAddon","Promise","all","import","readline","init","options","target","selector","getAttribute","document","getElementById","querySelector","Error","createElement","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperties","value","process","code","line","split","paste","resolve","setTimeout","activeRead","hasAttribute","hooks","main","onWorker","add","worker","_","xworker","has","delete","disableStdin","cursorBlink","cursorStyle","read","bind","onReady","console","warn","globalThis","__py_terminal__"],"mappings":"yCAIA,MAAMA,EAAe,IAAIC,QAKnBC,EAAc,EAAGC,cAAaC,KAAIC,MAAKC,SAAUC,WACnD,GAAa,OAATD,IAAkBC,EAAKC,gBAAiB,OAE5CH,EACI,CACI,4CACA,4BACA,SACFI,KAAK,MAGX,IAAIC,EAAO,GACX,MAAMC,gBAAEA,EAAeC,iBAAEA,GAAqBL,EACxCM,EAAU,IAAIC,YACdC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFR,EAAOG,EAAQM,OAAOD,GACtBN,EAAiBF,GACVQ,EAAOE,SAItBhB,EAAGiB,OAAUC,IACTV,EAAiBW,OAAOD,EAAME,SAAWF,GAAO,EAGpDnB,EAAYsB,UAAUV,GACtBZ,EAAYuB,UAAUX,GACtBZ,EAAYwB,SAAS,CACjBX,QAAQ,EACRY,MAAO,IAAMjB,EAAgBD,IAC/B,EAGN,IAAemB,EAAAC,MAAOC,IAElB,OAAOC,SAAEA,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KAAKC,KAAK/C,GAClDwC,EAAQxE,KAAKK,iBAAmB2B,EAAStB,MAAMqE,KAAK/C,GAChE,IAIQkC,EAAMI,OAAOU,QAAQX,IAAI1E,IAIzBuE,EAAMC,KAAKa,QAAQX,KAAI,SAASF,GAAKvE,YAAEA,EAAWC,GAAEA,EAAEC,IAAEA,EAAGC,KAAEA,IACzD,GAAa,OAATA,EAAe,OAEnBkF,QAAQC,KAAK,2CACbhB,EAAMC,KAAKa,QAAQN,OAAOP,GAG1BgB,WAAWC,gBAAkBnD,EAAK,CAC9B0C,cAAc,EACdC,aAAa,EACbC,YAAa,cAEjB/E,EAAI,yDACGqF,WAAWC,gBAElBvF,EAAGiB,OAAUC,IACTiB,EAAStB,MAAMM,OAAOD,EAAME,SAAWF,GAAO,EAGlD,IAAIZ,EAAO,GACX,MAAMG,EAAU,IAAIC,YACdC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFR,EAAOG,EAAQM,OAAOD,GACtBqB,EAAStB,MAAMP,GACRQ,EAAOE,SAGtBjB,EAAYsB,UAAUV,GACtBZ,EAAYuB,UAAUX,GACtBZ,EAAYwB,SAAS,CACjBX,QAAQ,EACRY,MAAO,IAAMW,EAAS8C,KAAK3E,IAE3C,GACK"}
1
+ {"version":3,"file":"py-BBDA21Aq.js","sources":["../src/plugins/py-terminal/py.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { hooks } from \"../../core.js\";\nimport { defineProperties } from \"polyscript/exports\";\n\nconst bootstrapped = new WeakSet();\n\n// this callback will be serialized as string and it never needs\n// to be invoked multiple times. Each xworker here is bootstrapped\n// only once thanks to the `sync.is_pyterminal()` check.\nconst workerReady = ({ interpreter, io, run, type }, { sync }) => {\n if (type !== \"py\" || !sync.is_pyterminal()) return;\n\n run(\n [\n \"from polyscript import currentScript as _\",\n \"__terminal__ = _.terminal\",\n \"del _\",\n ].join(\";\"),\n );\n\n let data = \"\";\n const { pyterminal_read, pyterminal_write } = sync;\n const decoder = new TextDecoder();\n const generic = {\n isatty: false,\n write(buffer) {\n data = decoder.decode(buffer);\n pyterminal_write(data);\n return buffer.length;\n },\n };\n\n io.stderr = (error) => {\n pyterminal_write(String(error.message || error));\n };\n\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: false,\n stdin: () => pyterminal_read(data),\n });\n};\n\nexport default async (element) => {\n // lazy load these only when a valid terminal is found\n const [{ Terminal }, { Readline }, { FitAddon }, { WebLinksAddon }] =\n await Promise.all([\n import(/* webpackIgnore: true */ \"../../3rd-party/xterm.js\"),\n import(\n /* webpackIgnore: true */ \"../../3rd-party/xterm-readline.js\"\n ),\n import(\n /* webpackIgnore: true */ \"../../3rd-party/xterm_addon-fit.js\"\n ),\n import(\n /* webpackIgnore: true */ \"../../3rd-party/xterm_addon-web-links.js\"\n ),\n ]);\n\n const readline = new Readline();\n\n // common main thread initialization for both worker\n // or main case, bootstrapping the terminal on its target\n const init = (options) => {\n let target = element;\n const selector = element.getAttribute(\"target\");\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(\"py-terminal\");\n target.style.display = \"block\";\n element.after(target);\n }\n const terminal = new Terminal({\n theme: {\n background: \"#191A19\",\n foreground: \"#F5F2E7\",\n },\n ...options,\n });\n const fitAddon = new FitAddon();\n terminal.loadAddon(fitAddon);\n terminal.loadAddon(readline);\n terminal.loadAddon(new WebLinksAddon());\n terminal.open(target);\n fitAddon.fit();\n terminal.focus();\n defineProperties(element, {\n terminal: { value: terminal },\n process: {\n value: async (code) => {\n for (const line of code.split(/(?:\\r\\n|\\r|\\n)/)) {\n terminal.paste(`${line}`);\n terminal.write(\"\\r\\n\");\n do {\n await new Promise((resolve) =>\n setTimeout(resolve, 0),\n );\n } while (!readline.activeRead?.resolve);\n readline.activeRead.resolve(line);\n }\n },\n },\n });\n return terminal;\n };\n\n // branch logic for the worker\n if (element.hasAttribute(\"worker\")) {\n // add a hook on the main thread to setup all sync helpers\n // also bootstrapping the XTerm target on main *BUT* ...\n hooks.main.onWorker.add(function worker(_, xworker) {\n // ... as multiple workers will add multiple callbacks\n // be sure no xworker is ever initialized twice!\n if (bootstrapped.has(xworker)) return;\n bootstrapped.add(xworker);\n\n // still cleanup this callback for future scripts/workers\n hooks.main.onWorker.delete(worker);\n\n init({\n disableStdin: false,\n cursorBlink: true,\n cursorStyle: \"block\",\n });\n\n xworker.sync.is_pyterminal = () => true;\n xworker.sync.pyterminal_read = readline.read.bind(readline);\n xworker.sync.pyterminal_write = readline.write.bind(readline);\n });\n\n // setup remote thread JS/Python code for whenever the\n // worker is ready to become a terminal\n hooks.worker.onReady.add(workerReady);\n } else {\n // in the main case, just bootstrap XTerm without\n // allowing any input as that's not possible / awkward\n hooks.main.onReady.add(function main({ interpreter, io, run, type }) {\n if (type !== \"py\") return;\n\n console.warn(\"py-terminal is read only on main thread\");\n hooks.main.onReady.delete(main);\n\n // on main, it's easy to trash and clean the current terminal\n globalThis.__py_terminal__ = init({\n disableStdin: true,\n cursorBlink: false,\n cursorStyle: \"underline\",\n });\n run(\"from js import __py_terminal__ as __terminal__\");\n delete globalThis.__py_terminal__;\n\n io.stderr = (error) => {\n readline.write(String(error.message || error));\n };\n\n let data = \"\";\n const decoder = new TextDecoder();\n const generic = {\n isatty: false,\n write(buffer) {\n data = decoder.decode(buffer);\n readline.write(data);\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: false,\n stdin: () => readline.read(data),\n });\n });\n }\n};\n"],"names":["bootstrapped","WeakSet","workerReady","interpreter","io","run","type","sync","is_pyterminal","join","data","pyterminal_read","pyterminal_write","decoder","TextDecoder","generic","isatty","write","buffer","decode","length","stderr","error","String","message","setStdout","setStderr","setStdin","stdin","py","async","element","Terminal","Readline","FitAddon","WebLinksAddon","Promise","all","import","readline","init","options","target","selector","getAttribute","document","getElementById","querySelector","Error","createElement","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperties","value","process","code","line","split","paste","resolve","setTimeout","activeRead","hasAttribute","hooks","main","onWorker","add","worker","_","xworker","has","delete","disableStdin","cursorBlink","cursorStyle","read","bind","onReady","console","warn","globalThis","__py_terminal__"],"mappings":"yCAIA,MAAMA,EAAe,IAAIC,QAKnBC,EAAc,EAAGC,cAAaC,KAAIC,MAAKC,SAAUC,WACnD,GAAa,OAATD,IAAkBC,EAAKC,gBAAiB,OAE5CH,EACI,CACI,4CACA,4BACA,SACFI,KAAK,MAGX,IAAIC,EAAO,GACX,MAAMC,gBAAEA,EAAeC,iBAAEA,GAAqBL,EACxCM,EAAU,IAAIC,YACdC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFR,EAAOG,EAAQM,OAAOD,GACtBN,EAAiBF,GACVQ,EAAOE,SAItBhB,EAAGiB,OAAUC,IACTV,EAAiBW,OAAOD,EAAME,SAAWF,GAAO,EAGpDnB,EAAYsB,UAAUV,GACtBZ,EAAYuB,UAAUX,GACtBZ,EAAYwB,SAAS,CACjBX,QAAQ,EACRY,MAAO,IAAMjB,EAAgBD,IAC/B,EAGN,IAAemB,EAAAC,MAAOC,IAElB,OAAOC,SAAEA,IAAYC,SAAEA,IAAYC,SAAEA,IAAYC,cAAEA,UACzCC,QAAQC,IAAI,CACdC,OAAiC,uBACjCA,OAC8B,gCAE9BA,OAC8B,iCAE9BA,OAC8B,yCAIhCC,EAAW,IAAIN,EAIfO,EAAQC,IACV,IAAIC,EAASX,EACb,MAAMY,EAAWZ,EAAQa,aAAa,UACtC,GAAID,GAIA,GAHAD,EACIG,SAASC,eAAeH,IACxBE,SAASE,cAAcJ,IACtBD,EAAQ,MAAM,IAAIM,MAAM,kBAAkBL,UAE/CD,EAASG,SAASI,cAAc,eAChCP,EAAOQ,MAAMC,QAAU,QACvBpB,EAAQqB,MAAMV,GAElB,MAAMW,EAAW,IAAIrB,EAAS,CAC1BsB,MAAO,CACHC,WAAY,UACZC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SAAWF,GAAO,EAGlD,IAAIZ,EAAO,GACX,MAAMG,EAAU,IAAIC,YACdC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFR,EAAOG,EAAQM,OAAOD,GACtBqB,EAAStB,MAAMP,GACRQ,EAAOE,SAGtBjB,EAAYsB,UAAUV,GACtBZ,EAAYuB,UAAUX,GACtBZ,EAAYwB,SAAS,CACjBX,QAAQ,EACRY,MAAO,IAAMW,EAAS8C,KAAK3E,IAE3C,GACK"}
@@ -1,2 +1,2 @@
1
- import{T as t,d as e,a as r,o as n,X as o,H as s,s as i}from"./core-VeaFOAwh.js";let a=0;const c=t=>`${t}-editor-${a++}`,l=new Map,u=new Map,d={worker:{codeBeforeRun:()=>i,onReady:({runAsync:t,io:e},{sync:r})=>{e.stdout=e.buffered(r.write),e.stderr=e.buffered(r.writeErr),r.revoke(),r.runAsync=t}}};async function m({currentTarget:t}){const{env:e,pySrc:r,outDiv:i}=this,a=!!t;if(a&&(t.disabled=!0,i.innerHTML=""),!l.has(e)){const t=URL.createObjectURL(new Blob([""])),r={type:this.interpreter},{config:i}=this;if(i){r.configURL=i;const{parse:t}=i.endsWith(".toml")?await import("./toml-CvAfdf9_.js"):JSON;r.config=t(await fetch(i).then((t=>t.text()))),r.version=n(r.config)}else r.config={};const a=o.call(new s(null,d),t,r),{sync:c}=a,{promise:u,resolve:m}=Promise.withResolvers();l.set(e,u),c.revoke=()=>{URL.revokeObjectURL(t),m(a)}}return l.get(e).then((e=>{e.onerror=({error:t})=>{a&&(i.innerHTML+=`<span style='color:red'>${t.message||t}</span>\n`),console.error(t)};const n=()=>{a&&(t.disabled=!1)},{sync:o}=e;o.write=t=>{a&&(i.innerText+=`${t}\n`)},o.writeErr=t=>{a&&(i.innerHTML+=`<span style='color:red'>${t}</span>\n`)},o.runAsync(r).then(n,n)}))}const p=(t,e)=>{const r=document.createElement("div");r.className=`${e}-editor-input`,r.setAttribute("aria-label","Python Script Area");const n=((t,e)=>{const r=document.createElement("button");return r.className=`absolute ${e}-editor-run-button`,r.innerHTML='<svg style="height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green" viewBox="0 0 384 512" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg"><g transform="translate(192 256)" transform-origin="96 0"><g transform="translate(0,0) scale(1,1)"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z" fill="currentColor" transform="translate(-192 -256)"></path></g></g></svg>',r.setAttribute("aria-label","Python Script Run Button"),r.addEventListener("click",t),r})(t,e),o=document.createElement("div");return o.addEventListener("keydown",(t=>{t.stopPropagation()})),r.append(n,o),r},f=(t,e)=>{const r=document.createElement("div");r.className=`${e}-editor-box`;const n=p(t,e),o=(t=>{const e=document.createElement("div");return e.className=`${t}-editor-output`,e.id=`${c(t)}-output`,e})(e);return r.append(n,o),[r,o]},g=async(t,n,o)=>{const[{basicSetup:s,EditorView:i},{Compartment:a},{python:l},{indentUnit:d},{keymap:p},{defaultKeymap:g}]=await Promise.all([import("./codemirror-zS6ccqby.js"),import("./codemirror_state-D1qTXrff.js"),import("./codemirror_lang-python-D74-Kgzp.js"),import("./codemirror_language-BheMcNfw.js").then((function(t){return t.x})),import("./codemirror_view-C3_bb6sY.js").then((function(t){return t.q})),import("./codemirror_commands-4671n0xX.js")]);let h=t.hasAttribute("setup");const v=t.hasAttribute("config"),b=`${o}-${t.getAttribute("env")||c(n)}`;if(v&&u.has(b))throw new SyntaxError(u.get(b)?`duplicated config for env: ${b}`:`unable to add a config to the env: ${b}`);u.set(b,v);let w=t.src?await fetch(t.src).then((t=>t.text())):t.textContent;const y={interpreter:o,env:b,config:v&&new URL(t.getAttribute("config"),location.href).href,get pySrc(){return h?w:T.state.doc.toString()},get outDiv(){return h?null:C}};let E;e(t,{target:{get:()=>E},process:{value(t){const e=h,r=w;h=!0,w=t;const n=()=>{h=e,w=r};return m.call(y,{currentTarget:null}).then(n,n)}}});const $=()=>{const e=new Event(`${n}-editor`,{bubbles:!0});t.dispatchEvent(e)};if(h)return await m.call(y,{currentTarget:null}),void $();const x=t.getAttribute("target");if(x){if(E=document.getElementById(x)||document.querySelector(x),!E)throw new Error(`Unknown target ${x}`)}else E=document.createElement(`${n}-editor`),E.style.display="block",t.after(E);E.id||(E.id=c(n)),E.hasAttribute("exec-id")||E.setAttribute("exec-id",0),E.hasAttribute("root")||E.setAttribute("root",E.id);const A=m.bind(y),[L,C]=f(A,n);L.dataset.env=t.hasAttribute("env")?b:o;const S=L.querySelector(`.${n}-editor-input > div`).attachShadow({mode:"open"});S.innerHTML="<style> :host { all: initial; }</style>",E.appendChild(L);const k=r(t.textContent).trim(),R=/^(\s+)/m.test(k)?RegExp.$1:" ",T=new i({extensions:[d.of(R),(new a).of(l()),p.of([...g,{key:"Ctrl-Enter",run:A,preventDefault:!0},{key:"Cmd-Enter",run:A,preventDefault:!0},{key:"Shift-Enter",run:A,preventDefault:!0}]),s],parent:S,doc:k});T.focus(),$()};let h=0,v=Promise.resolve();const b=()=>{h=0,w()},w=()=>{if(!h){h=setTimeout(b,250);for(const[e,r]of t){const t=`script[type="${e}-editor"]`;for(const n of document.querySelectorAll(t))n.type+="-active",v=v.then((()=>g(n,e,r)))}return v}};new MutationObserver(w).observe(document,{childList:!0,subtree:!0});var y=w();export{y as default};
2
- //# sourceMappingURL=py-editor-VcIseMPm.js.map
1
+ import{T as t,d as e,a as r,o as n,X as o,H as s,s as i}from"./core-g43HEaAk.js";let a=0;const c=t=>`${t}-editor-${a++}`,l=new Map,u=new Map,d={worker:{codeBeforeRun:()=>i,onReady:({runAsync:t,io:e},{sync:r})=>{e.stdout=e.buffered(r.write),e.stderr=e.buffered(r.writeErr),r.revoke(),r.runAsync=t}}};async function m({currentTarget:t}){const{env:e,pySrc:r,outDiv:i}=this,a=!!t;if(a&&(t.disabled=!0,i.innerHTML=""),!l.has(e)){const t=URL.createObjectURL(new Blob([""])),r={type:this.interpreter},{config:i}=this;if(i){r.configURL=i;const{parse:t}=i.endsWith(".toml")?await import("./toml-CvAfdf9_.js"):JSON;r.config=t(await fetch(i).then((t=>t.text()))),r.version=n(r.config)}else r.config={};const a=o.call(new s(null,d),t,r),{sync:c}=a,{promise:u,resolve:m}=Promise.withResolvers();l.set(e,u),c.revoke=()=>{URL.revokeObjectURL(t),m(a)}}return l.get(e).then((e=>{e.onerror=({error:t})=>{a&&(i.innerHTML+=`<span style='color:red'>${t.message||t}</span>\n`),console.error(t)};const n=()=>{a&&(t.disabled=!1)},{sync:o}=e;o.write=t=>{a&&(i.innerText+=`${t}\n`)},o.writeErr=t=>{a&&(i.innerHTML+=`<span style='color:red'>${t}</span>\n`)},o.runAsync(r).then(n,n)}))}const p=(t,e)=>{const r=document.createElement("div");r.className=`${e}-editor-input`,r.setAttribute("aria-label","Python Script Area");const n=((t,e)=>{const r=document.createElement("button");return r.className=`absolute ${e}-editor-run-button`,r.innerHTML='<svg style="height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green" viewBox="0 0 384 512" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg"><g transform="translate(192 256)" transform-origin="96 0"><g transform="translate(0,0) scale(1,1)"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z" fill="currentColor" transform="translate(-192 -256)"></path></g></g></svg>',r.setAttribute("aria-label","Python Script Run Button"),r.addEventListener("click",t),r})(t,e),o=document.createElement("div");return o.addEventListener("keydown",(t=>{t.stopPropagation()})),r.append(n,o),r},f=(t,e)=>{const r=document.createElement("div");r.className=`${e}-editor-box`;const n=p(t,e),o=(t=>{const e=document.createElement("div");return e.className=`${t}-editor-output`,e.id=`${c(t)}-output`,e})(e);return r.append(n,o),[r,o]},g=async(t,n,o)=>{const[{basicSetup:s,EditorView:i},{Compartment:a},{python:l},{indentUnit:d},{keymap:p},{defaultKeymap:g}]=await Promise.all([import("./codemirror-zS6ccqby.js"),import("./codemirror_state-D1qTXrff.js"),import("./codemirror_lang-python-D74-Kgzp.js"),import("./codemirror_language-BheMcNfw.js").then((function(t){return t.x})),import("./codemirror_view-C3_bb6sY.js").then((function(t){return t.q})),import("./codemirror_commands-4671n0xX.js")]);let h=t.hasAttribute("setup");const v=t.hasAttribute("config"),b=`${o}-${t.getAttribute("env")||c(n)}`;if(v&&u.has(b))throw new SyntaxError(u.get(b)?`duplicated config for env: ${b}`:`unable to add a config to the env: ${b}`);u.set(b,v);let w=t.src?await fetch(t.src).then((t=>t.text())):t.textContent;const y={interpreter:o,env:b,config:v&&new URL(t.getAttribute("config"),location.href).href,get pySrc(){return h?w:T.state.doc.toString()},get outDiv(){return h?null:C}};let E;e(t,{target:{get:()=>E},process:{value(t){const e=h,r=w;h=!0,w=t;const n=()=>{h=e,w=r};return m.call(y,{currentTarget:null}).then(n,n)}}});const $=()=>{const e=new Event(`${n}-editor`,{bubbles:!0});t.dispatchEvent(e)};if(h)return await m.call(y,{currentTarget:null}),void $();const x=t.getAttribute("target");if(x){if(E=document.getElementById(x)||document.querySelector(x),!E)throw new Error(`Unknown target ${x}`)}else E=document.createElement(`${n}-editor`),E.style.display="block",t.after(E);E.id||(E.id=c(n)),E.hasAttribute("exec-id")||E.setAttribute("exec-id",0),E.hasAttribute("root")||E.setAttribute("root",E.id);const A=m.bind(y),[L,C]=f(A,n);L.dataset.env=t.hasAttribute("env")?b:o;const S=L.querySelector(`.${n}-editor-input > div`).attachShadow({mode:"open"});S.innerHTML="<style> :host { all: initial; }</style>",E.appendChild(L);const k=r(t.textContent).trim(),R=/^(\s+)/m.test(k)?RegExp.$1:" ",T=new i({extensions:[d.of(R),(new a).of(l()),p.of([...g,{key:"Ctrl-Enter",run:A,preventDefault:!0},{key:"Cmd-Enter",run:A,preventDefault:!0},{key:"Shift-Enter",run:A,preventDefault:!0}]),s],parent:S,doc:k});T.focus(),$()};let h=0,v=Promise.resolve();const b=()=>{h=0,w()},w=()=>{if(!h){h=setTimeout(b,250);for(const[e,r]of t){const t=`script[type="${e}-editor"]`;for(const n of document.querySelectorAll(t))n.type+="-active",v=v.then((()=>g(n,e,r)))}return v}};new MutationObserver(w).observe(document,{childList:!0,subtree:!0});var y=w();export{y as default};
2
+ //# sourceMappingURL=py-editor-CgWtLE3U.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-editor-VcIseMPm.js","sources":["../src/plugins/py-editor.js"],"sourcesContent":["// PyScript py-editor plugin\nimport { Hook, XWorker, dedent, defineProperties } from \"polyscript/exports\";\nimport { TYPES, offline_interpreter, stdlib } from \"../core.js\";\n\nconst RUN_BUTTON = `<svg style=\"height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green\" viewBox=\"0 0 384 512\" aria-hidden=\"true\" role=\"img\" xmlns=\"http://www.w3.org/2000/svg\"><g transform=\"translate(192 256)\" transform-origin=\"96 0\"><g transform=\"translate(0,0) scale(1,1)\"><path d=\"M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z\" fill=\"currentColor\" transform=\"translate(-192 -256)\"></path></g></g></svg>`;\n\nlet id = 0;\nconst getID = (type) => `${type}-editor-${id++}`;\n\nconst envs = new Map();\nconst configs = new Map();\n\nconst hooks = {\n worker: {\n codeBeforeRun: () => stdlib,\n // works on both Pyodide and MicroPython\n onReady: ({ runAsync, io }, { sync }) => {\n io.stdout = io.buffered(sync.write);\n io.stderr = io.buffered(sync.writeErr);\n sync.revoke();\n sync.runAsync = runAsync;\n },\n },\n};\n\nasync function execute({ currentTarget }) {\n const { env, pySrc, outDiv } = this;\n const hasRunButton = !!currentTarget;\n\n if (hasRunButton) {\n currentTarget.disabled = true;\n outDiv.innerHTML = \"\";\n }\n\n if (!envs.has(env)) {\n const srcLink = URL.createObjectURL(new Blob([\"\"]));\n const details = { type: this.interpreter };\n const { config } = this;\n if (config) {\n details.configURL = config;\n const { parse } = config.endsWith(\".toml\")\n ? await import(/* webpackIgnore: true */ \"../3rd-party/toml.js\")\n : JSON;\n details.config = parse(await fetch(config).then((r) => r.text()));\n details.version = offline_interpreter(details.config);\n } else {\n details.config = {};\n }\n\n const xworker = XWorker.call(new Hook(null, hooks), srcLink, details);\n\n const { sync } = xworker;\n const { promise, resolve } = Promise.withResolvers();\n envs.set(env, promise);\n sync.revoke = () => {\n URL.revokeObjectURL(srcLink);\n resolve(xworker);\n };\n }\n\n // wait for the env then set the target div\n // before executing the current code\n return envs.get(env).then((xworker) => {\n xworker.onerror = ({ error }) => {\n if (hasRunButton) {\n outDiv.innerHTML += `<span style='color:red'>${\n error.message || error\n }</span>\\n`;\n }\n console.error(error);\n };\n\n const enable = () => {\n if (hasRunButton) currentTarget.disabled = false;\n };\n const { sync } = xworker;\n sync.write = (str) => {\n if (hasRunButton) outDiv.innerText += `${str}\\n`;\n };\n sync.writeErr = (str) => {\n if (hasRunButton) {\n outDiv.innerHTML += `<span style='color:red'>${str}</span>\\n`;\n }\n };\n sync.runAsync(pySrc).then(enable, enable);\n });\n}\n\nconst makeRunButton = (listener, type) => {\n const runButton = document.createElement(\"button\");\n runButton.className = `absolute ${type}-editor-run-button`;\n runButton.innerHTML = RUN_BUTTON;\n runButton.setAttribute(\"aria-label\", \"Python Script Run Button\");\n runButton.addEventListener(\"click\", listener);\n return runButton;\n};\n\nconst makeEditorDiv = (listener, type) => {\n const editorDiv = document.createElement(\"div\");\n editorDiv.className = `${type}-editor-input`;\n editorDiv.setAttribute(\"aria-label\", \"Python Script Area\");\n\n const runButton = makeRunButton(listener, type);\n const editorShadowContainer = document.createElement(\"div\");\n\n // avoid outer elements intercepting key events (reveal as example)\n editorShadowContainer.addEventListener(\"keydown\", (event) => {\n event.stopPropagation();\n });\n\n editorDiv.append(runButton, editorShadowContainer);\n\n return editorDiv;\n};\n\nconst makeOutDiv = (type) => {\n const outDiv = document.createElement(\"div\");\n outDiv.className = `${type}-editor-output`;\n outDiv.id = `${getID(type)}-output`;\n return outDiv;\n};\n\nconst makeBoxDiv = (listener, type) => {\n const boxDiv = document.createElement(\"div\");\n boxDiv.className = `${type}-editor-box`;\n\n const editorDiv = makeEditorDiv(listener, type);\n const outDiv = makeOutDiv(type);\n boxDiv.append(editorDiv, outDiv);\n\n return [boxDiv, outDiv];\n};\n\nconst init = async (script, type, interpreter) => {\n const [\n { basicSetup, EditorView },\n { Compartment },\n { python },\n { indentUnit },\n { keymap },\n { defaultKeymap },\n ] = await Promise.all([\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_state.js\"),\n import(\n /* webpackIgnore: true */ \"../3rd-party/codemirror_lang-python.js\"\n ),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_language.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_view.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_commands.js\"),\n ]);\n\n let isSetup = script.hasAttribute(\"setup\");\n const hasConfig = script.hasAttribute(\"config\");\n const env = `${interpreter}-${script.getAttribute(\"env\") || getID(type)}`;\n\n if (hasConfig && configs.has(env)) {\n throw new SyntaxError(\n configs.get(env)\n ? `duplicated config for env: ${env}`\n : `unable to add a config to the env: ${env}`,\n );\n }\n\n configs.set(env, hasConfig);\n\n let source = script.src\n ? await fetch(script.src).then((b) => b.text())\n : script.textContent;\n const context = {\n interpreter,\n env,\n config:\n hasConfig &&\n new URL(script.getAttribute(\"config\"), location.href).href,\n get pySrc() {\n return isSetup ? source : editor.state.doc.toString();\n },\n get outDiv() {\n return isSetup ? null : outDiv;\n },\n };\n\n let target;\n defineProperties(script, {\n target: { get: () => target },\n process: {\n /**\n * Simulate a setup node overriding the source to evaluate.\n * @param {string} code the Python code to evaluate.\n * @returns {Promise<...>} fulfill once code has been evaluated.\n */\n value(code) {\n const wasSetup = isSetup;\n const wasSource = source;\n isSetup = true;\n source = code;\n const restore = () => {\n isSetup = wasSetup;\n source = wasSource;\n };\n return execute\n .call(context, { currentTarget: null })\n .then(restore, restore);\n },\n },\n });\n\n const notify = () => {\n const event = new Event(`${type}-editor`, { bubbles: true });\n script.dispatchEvent(event);\n };\n\n if (isSetup) {\n await execute.call(context, { currentTarget: null });\n notify();\n return;\n }\n\n const selector = script.getAttribute(\"target\");\n\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(`${type}-editor`);\n target.style.display = \"block\";\n script.after(target);\n }\n\n if (!target.id) target.id = getID(type);\n if (!target.hasAttribute(\"exec-id\")) target.setAttribute(\"exec-id\", 0);\n if (!target.hasAttribute(\"root\")) target.setAttribute(\"root\", target.id);\n\n // @see https://github.com/JeffersGlass/mkdocs-pyscript/blob/main/mkdocs_pyscript/js/makeblocks.js\n const listener = execute.bind(context);\n const [boxDiv, outDiv] = makeBoxDiv(listener, type);\n boxDiv.dataset.env = script.hasAttribute(\"env\") ? env : interpreter;\n\n const inputChild = boxDiv.querySelector(`.${type}-editor-input > div`);\n const parent = inputChild.attachShadow({ mode: \"open\" });\n // avoid inheriting styles from the outer component\n parent.innerHTML = `<style> :host { all: initial; }</style>`;\n\n target.appendChild(boxDiv);\n\n const doc = dedent(script.textContent).trim();\n\n // preserve user indentation, if any\n const indentation = /^(\\s+)/m.test(doc) ? RegExp.$1 : \" \";\n\n const editor = new EditorView({\n extensions: [\n indentUnit.of(indentation),\n new Compartment().of(python()),\n keymap.of([\n ...defaultKeymap,\n { key: \"Ctrl-Enter\", run: listener, preventDefault: true },\n { key: \"Cmd-Enter\", run: listener, preventDefault: true },\n { key: \"Shift-Enter\", run: listener, preventDefault: true },\n ]),\n basicSetup,\n ],\n parent,\n doc,\n });\n\n editor.focus();\n notify();\n};\n\n// avoid too greedy MutationObserver operations at distance\nlet timeout = 0;\n\n// avoid delayed initialization\nlet queue = Promise.resolve();\n\n// reset interval value then check for new scripts\nconst resetTimeout = () => {\n timeout = 0;\n pyEditor();\n};\n\n// triggered both ASAP on the living DOM and via MutationObserver later\nconst pyEditor = () => {\n if (timeout) return;\n timeout = setTimeout(resetTimeout, 250);\n for (const [type, interpreter] of TYPES) {\n const selector = `script[type=\"${type}-editor\"]`;\n for (const script of document.querySelectorAll(selector)) {\n // avoid any further bootstrap by changing the type as active\n script.type += \"-active\";\n // don't await in here or multiple calls might happen\n // while the first script is being initialized\n queue = queue.then(() => init(script, type, interpreter));\n }\n }\n return queue;\n};\n\nnew MutationObserver(pyEditor).observe(document, {\n childList: true,\n subtree: true,\n});\n\n// try to check the current document ASAP\nexport default pyEditor();\n"],"names":["id","getID","type","envs","Map","configs","hooks","worker","codeBeforeRun","stdlib","onReady","runAsync","io","sync","stdout","buffered","write","stderr","writeErr","revoke","async","execute","currentTarget","env","pySrc","outDiv","this","hasRunButton","disabled","innerHTML","has","srcLink","URL","createObjectURL","Blob","details","interpreter","config","configURL","parse","endsWith","import","JSON","fetch","then","r","text","version","offline_interpreter","xworker","XWorker","call","Hook","promise","resolve","Promise","withResolvers","set","revokeObjectURL","get","onerror","error","message","console","enable","str","innerText","makeEditorDiv","listener","editorDiv","document","createElement","className","setAttribute","runButton","addEventListener","makeRunButton","editorShadowContainer","event","stopPropagation","append","makeBoxDiv","boxDiv","makeOutDiv","init","script","basicSetup","EditorView","Compartment","python","indentUnit","keymap","defaultKeymap","all","n","x","q","isSetup","hasAttribute","hasConfig","getAttribute","SyntaxError","source","src","b","textContent","context","location","href","editor","state","doc","toString","target","defineProperties","process","value","code","wasSetup","wasSource","restore","notify","Event","bubbles","dispatchEvent","selector","getElementById","querySelector","Error","style","display","after","bind","dataset","parent","attachShadow","mode","appendChild","dedent","trim","indentation","test","RegExp","$1","extensions","of","key","run","preventDefault","focus","timeout","queue","resetTimeout","pyEditor","setTimeout","TYPES","querySelectorAll","MutationObserver","observe","childList","subtree","pyEditor$1"],"mappings":"iFAMA,IAAIA,EAAK,EACT,MAAMC,EAASC,GAAS,GAAGA,YAAeF,MAEpCG,EAAO,IAAIC,IACXC,EAAU,IAAID,IAEdE,EAAQ,CACVC,OAAQ,CACJC,cAAe,IAAMC,EAErBC,QAAS,EAAGC,WAAUC,OAAQC,WAC1BD,EAAGE,OAASF,EAAGG,SAASF,EAAKG,OAC7BJ,EAAGK,OAASL,EAAGG,SAASF,EAAKK,UAC7BL,EAAKM,SACLN,EAAKF,SAAWA,CAAQ,IAKpCS,eAAeC,GAAQC,cAAEA,IACrB,MAAMC,IAAEA,EAAGC,MAAEA,EAAKC,OAAEA,GAAWC,KACzBC,IAAiBL,EAOvB,GALIK,IACAL,EAAcM,UAAW,EACzBH,EAAOI,UAAY,KAGlB1B,EAAK2B,IAAIP,GAAM,CAChB,MAAMQ,EAAUC,IAAIC,gBAAgB,IAAIC,KAAK,CAAC,MACxCC,EAAU,CAAEjC,KAAMwB,KAAKU,cACvBC,OAAEA,GAAWX,KACnB,GAAIW,EAAQ,CACRF,EAAQG,UAAYD,EACpB,MAAME,MAAEA,GAAUF,EAAOG,SAAS,eACtBC,OAAiC,sBACvCC,KACNP,EAAQE,OAASE,QAAYI,MAAMN,GAAQO,MAAMC,GAAMA,EAAEC,UACzDX,EAAQY,QAAUC,EAAoBb,EAAQE,OAC1D,MACYF,EAAQE,OAAS,GAGrB,MAAMY,EAAUC,EAAQC,KAAK,IAAIC,EAAK,KAAM9C,GAAQyB,EAASI,IAEvDtB,KAAEA,GAASoC,GACXI,QAAEA,EAAOC,QAAEA,GAAYC,QAAQC,gBACrCrD,EAAKsD,IAAIlC,EAAK8B,GACdxC,EAAKM,OAAS,KACVa,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AK,aAAcC,IAAK/E,EAAUgF,gBAAgB,GACpD,CAAEF,IAAK,YAAaC,IAAK/E,EAAUgF,gBAAgB,GACnD,CAAEF,IAAK,cAAeC,IAAK/E,EAAUgF,gBAAgB,KAEzD9D,GAEJgD,SACAvB,QAGJF,EAAOwC,QACP5B,GAAQ,EAIZ,IAAI6B,EAAU,EAGVC,EAAQhG,QAAQD,UAGpB,MAAMkG,EAAe,KACjBF,EAAU,EACVG,GAAU,EAIRA,EAAW,KACb,IAAIH,EAAJ,CACAA,EAAUI,WAAWF,EAAc,KACnC,IAAK,MAAOtJ,EAAMkC,KAAgBuH,EAAO,CACrC,MAAM9B,EAAW,gBAAgB3H,aACjC,IAAK,MAAMmF,KAAUf,SAASsF,iBAAiB/B,GAE3CxC,EAAOnF,MAAQ,UAGfqJ,EAAQA,EAAM3G,MAAK,IAAMwC,EAAKC,EAAQnF,EAAMkC,IAEnD,CACD,OAAOmH,CAZa,CAYR,EAGhB,IAAIM,iBAAiBJ,GAAUK,QAAQxF,SAAU,CAC7CyF,WAAW,EACXC,SAAS,IAIb,IAAAC,EAAeR"}
1
+ {"version":3,"file":"py-editor-CgWtLE3U.js","sources":["../src/plugins/py-editor.js"],"sourcesContent":["// PyScript py-editor plugin\nimport { Hook, XWorker, dedent, defineProperties } from \"polyscript/exports\";\nimport { TYPES, offline_interpreter, stdlib } from \"../core.js\";\n\nconst RUN_BUTTON = `<svg style=\"height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green\" viewBox=\"0 0 384 512\" aria-hidden=\"true\" role=\"img\" xmlns=\"http://www.w3.org/2000/svg\"><g transform=\"translate(192 256)\" transform-origin=\"96 0\"><g transform=\"translate(0,0) scale(1,1)\"><path d=\"M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z\" fill=\"currentColor\" transform=\"translate(-192 -256)\"></path></g></g></svg>`;\n\nlet id = 0;\nconst getID = (type) => `${type}-editor-${id++}`;\n\nconst envs = new Map();\nconst configs = new Map();\n\nconst hooks = {\n worker: {\n codeBeforeRun: () => stdlib,\n // works on both Pyodide and MicroPython\n onReady: ({ runAsync, io }, { sync }) => {\n io.stdout = io.buffered(sync.write);\n io.stderr = io.buffered(sync.writeErr);\n sync.revoke();\n sync.runAsync = runAsync;\n },\n },\n};\n\nasync function execute({ currentTarget }) {\n const { env, pySrc, outDiv } = this;\n const hasRunButton = !!currentTarget;\n\n if (hasRunButton) {\n currentTarget.disabled = true;\n outDiv.innerHTML = \"\";\n }\n\n if (!envs.has(env)) {\n const srcLink = URL.createObjectURL(new Blob([\"\"]));\n const details = { type: this.interpreter };\n const { config } = this;\n if (config) {\n details.configURL = config;\n const { parse } = config.endsWith(\".toml\")\n ? await import(/* webpackIgnore: true */ \"../3rd-party/toml.js\")\n : JSON;\n details.config = parse(await fetch(config).then((r) => r.text()));\n details.version = offline_interpreter(details.config);\n } else {\n details.config = {};\n }\n\n const xworker = XWorker.call(new Hook(null, hooks), srcLink, details);\n\n const { sync } = xworker;\n const { promise, resolve } = Promise.withResolvers();\n envs.set(env, promise);\n sync.revoke = () => {\n URL.revokeObjectURL(srcLink);\n resolve(xworker);\n };\n }\n\n // wait for the env then set the target div\n // before executing the current code\n return envs.get(env).then((xworker) => {\n xworker.onerror = ({ error }) => {\n if (hasRunButton) {\n outDiv.innerHTML += `<span style='color:red'>${\n error.message || error\n }</span>\\n`;\n }\n console.error(error);\n };\n\n const enable = () => {\n if (hasRunButton) currentTarget.disabled = false;\n };\n const { sync } = xworker;\n sync.write = (str) => {\n if (hasRunButton) outDiv.innerText += `${str}\\n`;\n };\n sync.writeErr = (str) => {\n if (hasRunButton) {\n outDiv.innerHTML += `<span style='color:red'>${str}</span>\\n`;\n }\n };\n sync.runAsync(pySrc).then(enable, enable);\n });\n}\n\nconst makeRunButton = (listener, type) => {\n const runButton = document.createElement(\"button\");\n runButton.className = `absolute ${type}-editor-run-button`;\n runButton.innerHTML = RUN_BUTTON;\n runButton.setAttribute(\"aria-label\", \"Python Script Run Button\");\n runButton.addEventListener(\"click\", listener);\n return runButton;\n};\n\nconst makeEditorDiv = (listener, type) => {\n const editorDiv = document.createElement(\"div\");\n editorDiv.className = `${type}-editor-input`;\n editorDiv.setAttribute(\"aria-label\", \"Python Script Area\");\n\n const runButton = makeRunButton(listener, type);\n const editorShadowContainer = document.createElement(\"div\");\n\n // avoid outer elements intercepting key events (reveal as example)\n editorShadowContainer.addEventListener(\"keydown\", (event) => {\n event.stopPropagation();\n });\n\n editorDiv.append(runButton, editorShadowContainer);\n\n return editorDiv;\n};\n\nconst makeOutDiv = (type) => {\n const outDiv = document.createElement(\"div\");\n outDiv.className = `${type}-editor-output`;\n outDiv.id = `${getID(type)}-output`;\n return outDiv;\n};\n\nconst makeBoxDiv = (listener, type) => {\n const boxDiv = document.createElement(\"div\");\n boxDiv.className = `${type}-editor-box`;\n\n const editorDiv = makeEditorDiv(listener, type);\n const outDiv = makeOutDiv(type);\n boxDiv.append(editorDiv, outDiv);\n\n return [boxDiv, outDiv];\n};\n\nconst init = async (script, type, interpreter) => {\n const [\n { basicSetup, EditorView },\n { Compartment },\n { python },\n { indentUnit },\n { keymap },\n { defaultKeymap },\n ] = await Promise.all([\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_state.js\"),\n import(\n /* webpackIgnore: true */ \"../3rd-party/codemirror_lang-python.js\"\n ),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_language.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_view.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_commands.js\"),\n ]);\n\n let isSetup = script.hasAttribute(\"setup\");\n const hasConfig = script.hasAttribute(\"config\");\n const env = `${interpreter}-${script.getAttribute(\"env\") || getID(type)}`;\n\n if (hasConfig && configs.has(env)) {\n throw new SyntaxError(\n configs.get(env)\n ? `duplicated config for env: ${env}`\n : `unable to add a config to the env: ${env}`,\n );\n }\n\n configs.set(env, hasConfig);\n\n let source = script.src\n ? await fetch(script.src).then((b) => b.text())\n : script.textContent;\n const context = {\n interpreter,\n env,\n config:\n hasConfig &&\n new URL(script.getAttribute(\"config\"), location.href).href,\n get pySrc() {\n return isSetup ? source : editor.state.doc.toString();\n },\n get outDiv() {\n return isSetup ? null : outDiv;\n },\n };\n\n let target;\n defineProperties(script, {\n target: { get: () => target },\n process: {\n /**\n * Simulate a setup node overriding the source to evaluate.\n * @param {string} code the Python code to evaluate.\n * @returns {Promise<...>} fulfill once code has been evaluated.\n */\n value(code) {\n const wasSetup = isSetup;\n const wasSource = source;\n isSetup = true;\n source = code;\n const restore = () => {\n isSetup = wasSetup;\n source = wasSource;\n };\n return execute\n .call(context, { currentTarget: null })\n .then(restore, restore);\n },\n },\n });\n\n const notify = () => {\n const event = new Event(`${type}-editor`, { bubbles: true });\n script.dispatchEvent(event);\n };\n\n if (isSetup) {\n await execute.call(context, { currentTarget: null });\n notify();\n return;\n }\n\n const selector = script.getAttribute(\"target\");\n\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(`${type}-editor`);\n target.style.display = \"block\";\n script.after(target);\n }\n\n if (!target.id) target.id = getID(type);\n if (!target.hasAttribute(\"exec-id\")) target.setAttribute(\"exec-id\", 0);\n if (!target.hasAttribute(\"root\")) target.setAttribute(\"root\", target.id);\n\n // @see https://github.com/JeffersGlass/mkdocs-pyscript/blob/main/mkdocs_pyscript/js/makeblocks.js\n const listener = execute.bind(context);\n const [boxDiv, outDiv] = makeBoxDiv(listener, type);\n boxDiv.dataset.env = script.hasAttribute(\"env\") ? env : interpreter;\n\n const inputChild = boxDiv.querySelector(`.${type}-editor-input > div`);\n const parent = inputChild.attachShadow({ mode: \"open\" });\n // avoid inheriting styles from the outer component\n parent.innerHTML = `<style> :host { all: initial; }</style>`;\n\n target.appendChild(boxDiv);\n\n const doc = dedent(script.textContent).trim();\n\n // preserve user indentation, if any\n const indentation = /^(\\s+)/m.test(doc) ? RegExp.$1 : \" \";\n\n const editor = new EditorView({\n extensions: [\n indentUnit.of(indentation),\n new Compartment().of(python()),\n keymap.of([\n ...defaultKeymap,\n { key: \"Ctrl-Enter\", run: listener, preventDefault: true },\n { key: \"Cmd-Enter\", run: listener, preventDefault: true },\n { key: \"Shift-Enter\", run: listener, preventDefault: true },\n ]),\n basicSetup,\n ],\n parent,\n doc,\n });\n\n editor.focus();\n notify();\n};\n\n// avoid too greedy MutationObserver operations at distance\nlet timeout = 0;\n\n// avoid delayed initialization\nlet queue = Promise.resolve();\n\n// reset interval value then check for new scripts\nconst resetTimeout = () => {\n timeout = 0;\n pyEditor();\n};\n\n// triggered both ASAP on the living DOM and via MutationObserver later\nconst pyEditor = () => {\n if (timeout) return;\n timeout = setTimeout(resetTimeout, 250);\n for (const [type, interpreter] of TYPES) {\n const selector = `script[type=\"${type}-editor\"]`;\n for (const script of document.querySelectorAll(selector)) {\n // avoid any further bootstrap by changing the type as active\n script.type += \"-active\";\n // don't await in here or multiple calls might happen\n // while the first script is being initialized\n queue = queue.then(() => init(script, type, interpreter));\n }\n }\n return queue;\n};\n\nnew MutationObserver(pyEditor).observe(document, {\n childList: true,\n subtree: true,\n});\n\n// try to check the current document ASAP\nexport default pyEditor();\n"],"names":["id","getID","type","envs","Map","configs","hooks","worker","codeBeforeRun","stdlib","onReady","runAsync","io","sync","stdout","buffered","write","stderr","writeErr","revoke","async","execute","currentTarget","env","pySrc","outDiv","this","hasRunButton","disabled","innerHTML","has","srcLink","URL","createObjectURL","Blob","details","interpreter","config","configURL","parse","endsWith","import","JSON","fetch","then","r","text","version","offline_interpreter","xworker","XWorker","call","Hook","promise","resolve","Promise","withResolvers","set","revokeObjectURL","get","onerror","error","message","console","enable","str","innerText","makeEditorDiv","listener","editorDiv","document","createElement","className","setAttribute","runButton","addEventListener","makeRunButton","editorShadowContainer","event","stopPropagation","append","makeBoxDiv","boxDiv","makeOutDiv","init","script","basicSetup","EditorView","Compartment","python","indentUnit","keymap","defaultKeymap","all","n","x","q","isSetup","hasAttribute","hasConfig","getAttribute","SyntaxError","source","src","b","textContent","context","location","href","editor","state","doc","toString","target","defineProperties","process","value","code","wasSetup","wasSource","restore","notify","Event","bubbles","dispatchEvent","selector","getElementById","querySelector","Error","style","display","after","bind","dataset","parent","attachShadow","mode","appendChild","dedent","trim","indentation","test","RegExp","$1","extensions","of","key","run","preventDefault","focus","timeout","queue","resetTimeout","pyEditor","setTimeout","TYPES","querySelectorAll","MutationObserver","observe","childList","subtree","pyEditor$1"],"mappings":"iFAMA,IAAIA,EAAK,EACT,MAAMC,EAASC,GAAS,GAAGA,YAAeF,MAEpCG,EAAO,IAAIC,IACXC,EAAU,IAAID,IAEdE,EAAQ,CACVC,OAAQ,CACJC,cAAe,IAAMC,EAErBC,QAAS,EAAGC,WAAUC,OAAQC,WAC1BD,EAAGE,OAASF,EAAGG,SAASF,EAAKG,OAC7BJ,EAAGK,OAASL,EAAGG,SAASF,EAAKK,UAC7BL,EAAKM,SACLN,EAAKF,SAAWA,CAAQ,IAKpCS,eAAeC,GAAQC,cAAEA,IACrB,MAAMC,IAAEA,EAAGC,MAAEA,EAAKC,OAAEA,GAAWC,KACzBC,IAAiBL,EAOvB,GALIK,IACAL,EAAcM,UAAW,EACzBH,EAAOI,UAAY,KAGlB1B,EAAK2B,IAAIP,GAAM,CAChB,MAAMQ,EAAUC,IAAIC,gBAAgB,IAAIC,KAAK,CAAC,MACxCC,EAAU,CAAEjC,KAAMwB,KAAKU,cACvBC,OAAEA,GAAWX,KACnB,GAAIW,EAAQ,CACRF,EAAQG,UAAYD,EACpB,MAAME,MAAEA,GAAUF,EAAOG,SAAS,eACtBC,OAAiC,sBACvCC,KACNP,EAAQE,OAASE,Q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AAEC,KAAM,SAE/CF,EAAOzG,UAAY,0CAEnBoF,EAAOwB,YAAYvD,GAEnB,MAAM6B,EAAM2B,EAAOrD,EAAOoB,aAAakC,OAGjCC,EAAc,UAAUC,KAAK9B,GAAO+B,OAAOC,GAAK,OAEhDlC,EAAS,IAAItB,EAAW,CAC1ByD,WAAY,CACRtD,EAAWuD,GAAGL,IACd,IAAIpD,GAAcyD,GAAGxD,KACrBE,EAAOsD,GAAG,IACHrD,EACH,CAAEsD,IAAK,aAAcC,IAAK/E,EAAUgF,gBAAgB,GACpD,CAAEF,IAAK,YAAaC,IAAK/E,EAAUgF,gBAAgB,GACnD,CAAEF,IAAK,cAAeC,IAAK/E,EAAUgF,gBAAgB,KAEzD9D,GAEJgD,SACAvB,QAGJF,EAAOwC,QACP5B,GAAQ,EAIZ,IAAI6B,EAAU,EAGVC,EAAQhG,QAAQD,UAGpB,MAAMkG,EAAe,KACjBF,EAAU,EACVG,GAAU,EAIRA,EAAW,KACb,IAAIH,EAAJ,CACAA,EAAUI,WAAWF,EAAc,KACnC,IAAK,MAAOtJ,EAAMkC,KAAgBuH,EAAO,CACrC,MAAM9B,EAAW,gBAAgB3H,aACjC,IAAK,MAAMmF,KAAUf,SAASsF,iBAAiB/B,GAE3CxC,EAAOnF,MAAQ,UAGfqJ,EAAQA,EAAM3G,MAAK,IAAMwC,EAAKC,EAAQnF,EAAMkC,IAEnD,CACD,OAAOmH,CAZa,CAYR,EAGhB,IAAIM,iBAAiBJ,GAAUK,QAAQxF,SAAU,CAC7CyF,WAAW,EACXC,SAAS,IAIb,IAAAC,EAAeR"}
@@ -1,2 +1,2 @@
1
- import{T as e,c as t}from"./core-VeaFOAwh.js";import{notify as r}from"./error-DUpRPSjM.js";const s=[],n=new WeakSet,o=e=>{throw r(e),new Error(e)},a=({attributes:{worker:e}})=>!e;let m=!0;for(const r of e.keys()){const e=`script[type="${r}"][terminal],${r}-script[terminal]`;s.push(e),t.set(e,(async e=>{const t=document.querySelectorAll(s.join(","));if([].filter.call(t,a).length>1&&o("You can use at most 1 main terminal"),m&&(m=!1,document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:new URL("./xterm.css",import.meta.url)}))),n.has(e))return;n.add(e);const c=t=>t.default(e);"mpy"===r?await import("./mpy-BcmFt5Pp.js").then(c):await import("./py-BhqrNMZk.js").then(c)}))}
2
- //# sourceMappingURL=py-terminal-ECrKTiw7.js.map
1
+ import{T as e,c as t}from"./core-g43HEaAk.js";import{notify as r}from"./error-Cj1uxyP7.js";const s=[],n=new WeakSet,o=e=>{throw r(e),new Error(e)},a=({attributes:{worker:e}})=>!e;let m=!0;for(const r of e.keys()){const e=`script[type="${r}"][terminal],${r}-script[terminal]`;s.push(e),t.set(e,(async e=>{const t=document.querySelectorAll(s.join(","));if([].filter.call(t,a).length>1&&o("You can use at most 1 main terminal"),m&&(m=!1,document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:new URL("./xterm.css",import.meta.url)}))),n.has(e))return;n.add(e);const c=t=>t.default(e);"mpy"===r?await import("./mpy-C8sNSuAP.js").then(c):await import("./py-BBDA21Aq.js").then(c)}))}
2
+ //# sourceMappingURL=py-terminal-Cs3_SuLo.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-terminal-ECrKTiw7.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES } from \"../core.js\";\nimport { notify } from \"./error.js\";\nimport { customObserver } from \"polyscript/exports\";\n\n// will contain all valid selectors\nconst SELECTORS = [];\n\n// avoid processing same elements twice\nconst processed = new WeakSet();\n\n// show the error on main and\n// stops the module from keep executing\nconst notifyAndThrow = (message) => {\n notify(message);\n throw new Error(message);\n};\n\nconst onceOnMain = ({ attributes: { worker } }) => !worker;\n\nlet addStyle = true;\n\nfor (const type of TYPES.keys()) {\n const selector = `script[type=\"${type}\"][terminal],${type}-script[terminal]`;\n SELECTORS.push(selector);\n customObserver.set(selector, async (element) => {\n // we currently support only one terminal on main as in \"classic\"\n const terminals = document.querySelectorAll(SELECTORS.join(\",\"));\n if ([].filter.call(terminals, onceOnMain).length > 1)\n notifyAndThrow(\"You can use at most 1 main terminal\");\n\n // import styles lazily\n if (addStyle) {\n addStyle = false;\n document.head.append(\n Object.assign(document.createElement(\"link\"), {\n rel: \"stylesheet\",\n href: new URL(\"./xterm.css\", import.meta.url),\n }),\n );\n }\n\n if (processed.has(element)) return;\n processed.add(element);\n\n const bootstrap = (module) => module.default(element);\n\n // we can't be smart with template literals for the dynamic import\n // or bundlers are incapable of producing multiple files around\n if (type === \"mpy\") {\n await import(/* webpackIgnore: true */ \"./py-terminal/mpy.js\").then(\n bootstrap,\n );\n } else {\n await import(/* webpackIgnore: true */ \"./py-terminal/py.js\").then(\n bootstrap,\n );\n }\n });\n}\n"],"names":["SELECTORS","processed","WeakSet","notifyAndThrow","message","notify","Error","onceOnMain","attributes","worker","addStyle","type","TYPES","keys","selector","push","customObserver","set","async","element","terminals","document","querySelectorAll","join","filter","call","length","head","append","Object","assign","createElement","rel","href","URL","url","has","add","bootstrap","module","default","import","then"],"mappings":"2FAMA,MAAMA,EAAY,GAGZC,EAAY,IAAIC,QAIhBC,EAAkBC,IAEpB,MADAC,EAAOD,GACD,IAAIE,MAAMF,EAAQ,EAGtBG,EAAa,EAAGC,YAAcC,cAAgBA,EAEpD,IAAIC,GAAW,EAEf,IAAK,MAAMC,KAAQC,EAAMC,OAAQ,CAC7B,MAAMC,EAAW,gBAAgBH,iBAAoBA,qBACrDX,EAAUe,KAAKD,GACfE,EAAeC,IAAIH,GAAUI,MAAOC,IAEhC,MAAMC,EAAYC,SAASC,iBAAiBtB,EAAUuB,KAAK,MAe3D,GAdI,GAAGC,OAAOC,KAAKL,EAAWb,GAAYmB,OAAS,GAC/CvB,EAAe,uCAGfO,IACAA,GAAW,EACXW,SAASM,KAAKC,OACVC,OAAOC,OAAOT,SAASU,cAAc,QAAS,CAC1CC,IAAK,aACLC,KAAM,IAAIC,IAAI,0BAA2BC,SAKjDlC,EAAUmC,IAAIjB,GAAU,OAC5BlB,EAAUoC,IAAIlB,GAEd,MAAMmB,EAAaC,GAAWA,EAAOC,QAAQrB,GAIhC,QAATR,QACM8B,OAAiC,qBAAwBC,KAC3DJ,SAGEG,OAAiC,oBAAuBC,KAC1DJ,EAEP,GAET"}
1
+ {"version":3,"file":"py-terminal-Cs3_SuLo.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES } from \"../core.js\";\nimport { notify } from \"./error.js\";\nimport { customObserver } from \"polyscript/exports\";\n\n// will contain all valid selectors\nconst SELECTORS = [];\n\n// avoid processing same elements twice\nconst processed = new WeakSet();\n\n// show the error on main and\n// stops the module from keep executing\nconst notifyAndThrow = (message) => {\n notify(message);\n throw new Error(message);\n};\n\nconst onceOnMain = ({ attributes: { worker } }) => !worker;\n\nlet addStyle = true;\n\nfor (const type of TYPES.keys()) {\n const selector = `script[type=\"${type}\"][terminal],${type}-script[terminal]`;\n SELECTORS.push(selector);\n customObserver.set(selector, async (element) => {\n // we currently support only one terminal on main as in \"classic\"\n const terminals = document.querySelectorAll(SELECTORS.join(\",\"));\n if ([].filter.call(terminals, onceOnMain).length > 1)\n notifyAndThrow(\"You can use at most 1 main terminal\");\n\n // import styles lazily\n if (addStyle) {\n addStyle = false;\n document.head.append(\n Object.assign(document.createElement(\"link\"), {\n rel: \"stylesheet\",\n href: new URL(\"./xterm.css\", import.meta.url),\n }),\n );\n }\n\n if (processed.has(element)) return;\n processed.add(element);\n\n const bootstrap = (module) => module.default(element);\n\n // we can't be smart with template literals for the dynamic import\n // or bundlers are incapable of producing multiple files around\n if (type === \"mpy\") {\n await import(/* webpackIgnore: true */ \"./py-terminal/mpy.js\").then(\n bootstrap,\n );\n } else {\n await import(/* webpackIgnore: true */ \"./py-terminal/py.js\").then(\n bootstrap,\n );\n }\n });\n}\n"],"names":["SELECTORS","processed","WeakSet","notifyAndThrow","message","notify","Error","onceOnMain","attributes","worker","addStyle","type","TYPES","keys","selector","push","customObserver","set","async","element","terminals","document","querySelectorAll","join","filter","call","length","head","append","Object","assign","createElement","rel","href","URL","url","has","add","bootstrap","module","default","import","then"],"mappings":"2FAMA,MAAMA,EAAY,GAGZC,EAAY,IAAIC,QAIhBC,EAAkBC,IAEpB,MADAC,EAAOD,GACD,IAAIE,MAAMF,EAAQ,EAGtBG,EAAa,EAAGC,YAAcC,cAAgBA,EAEpD,IAAIC,GAAW,EAEf,IAAK,MAAMC,KAAQC,EAAMC,OAAQ,CAC7B,MAAMC,EAAW,gBAAgBH,iBAAoBA,qBACrDX,EAAUe,KAAKD,GACfE,EAAeC,IAAIH,GAAUI,MAAOC,IAEhC,MAAMC,EAAYC,SAASC,iBAAiBtB,EAAUuB,KAAK,MAe3D,GAdI,GAAGC,OAAOC,KAAKL,EAAWb,GAAYmB,OAAS,GAC/CvB,EAAe,uCAGfO,IACAA,GAAW,EACXW,SAASM,KAAKC,OACVC,OAAOC,OAAOT,SAASU,cAAc,QAAS,CAC1CC,IAAK,aACLC,KAAM,IAAIC,IAAI,0BAA2BC,SAKjDlC,EAAUmC,IAAIjB,GAAU,OAC5BlB,EAAUoC,IAAIlB,GAEd,MAAMmB,EAAaC,GAAWA,EAAOC,QAAQrB,GAIhC,QAATR,QACM8B,OAAiC,qBAAwBC,KAC3DJ,SAGEG,OAAiC,oBAAuBC,KAC1DJ,EAEP,GAET"}
package/dist.zip ADDED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyscript/core",
3
- "version": "0.4.38",
3
+ "version": "0.4.39",
4
4
  "type": "module",
5
5
  "description": "PyScript",
6
6
  "module": "./index.js",
@@ -43,7 +43,7 @@
43
43
  "dependencies": {
44
44
  "@ungap/with-resolvers": "^0.1.0",
45
45
  "basic-devtools": "^0.1.6",
46
- "polyscript": "^0.12.11",
46
+ "polyscript": "^0.12.13",
47
47
  "sticky-module": "^0.1.1",
48
48
  "to-json-callback": "^0.1.1",
49
49
  "type-checked-collections": "^0.1.7"