@pyscript/core 0.3.20 → 0.3.21

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{b as PyWorker,T as TYPES,c as config,e as hooks,f as whenDefined}from"./core-_MDTi7dy.js";
1
+ export{b as PyWorker,T as TYPES,c as config,e as hooks,f as whenDefined}from"./core-kKH572HC.js";
2
2
  //# sourceMappingURL=core.js.map
@@ -1,2 +1,2 @@
1
- import{e}from"./core-_MDTi7dy.js";import{notify as o}from"./error-yavCjy9g.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-xSJEJMfx.js.map
1
+ import{e}from"./core-kKH572HC.js";import{notify as o}from"./error-fa3ea4ix.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-m-ZMcfz-.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"deprecations-manager-xSJEJMfx.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-m-ZMcfz-.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-_MDTi7dy.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-yavCjy9g.js.map
1
+ import{e}from"./core-kKH572HC.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-fa3ea4ix.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-yavCjy9g.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-fa3ea4ix.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{T as e,d as t,X as r,H as n}from"./core-_MDTi7dy.js";let o=0;const i=e=>`${e}-editor-${o++}`,s=new Map,a={worker:{onReady:({runAsync:e,io:t},{sync:r})=>{t.stdout=e=>r.write(e),t.stderr=e=>r.writeErr(e),r.revoke(),r.runAsync=e}}};async function c({currentTarget:e}){const{env:t,pySrc:o,outDiv:i}=this;if(e.disabled=!0,i.innerHTML="",!s.has(t)){const e=URL.createObjectURL(new Blob([""])),o=r.call(new n(null,a),e,{type:this.interpreter}),{sync:i}=o,{promise:c,resolve:l}=Promise.withResolvers();s.set(t,c),i.revoke=()=>{URL.revokeObjectURL(e),l(o)}}s.get(t).then((t=>{t.onerror=({error:e})=>{i.innerHTML+=`<span style='color:red'>${e.message||e}</span>\n`,console.error(e)};const r=()=>{e.disabled=!1},{sync:n}=t;n.write=e=>{i.innerText+=`${e}\n`},n.writeErr=e=>{i.innerHTML+=`<span style='color:red'>${e}</span>\n`},n.runAsync(o).then(r,r)}))}const l=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-input`,r.setAttribute("aria-label","Python Script Area");const n=((e,t)=>{const r=document.createElement("button");return r.className=`absolute ${t}-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",e),r})(e,t),o=document.createElement("div");return o.addEventListener("keydown",(e=>{e.stopPropagation()})),r.append(n,o),r},d=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-box`;const n=l(e,t),o=(e=>{const t=document.createElement("div");return t.className=`${e}-editor-output`,t.id=`${i(e)}-output`,t})(t);return r.append(n,o),[r,o]},u=async(e,r,n)=>{const[{basicSetup:o,EditorView:s},{Compartment:a},{python:l},{indentUnit:u},{keymap:m},{defaultKeymap:p}]=await Promise.all([import("./codemirror-Maf5R0Dz.js"),import("./codemirror_state-W084kUeH.js"),import("./codemirror_lang-python-FADyYnPB.js"),import("./codemirror_language-xy4t5bF6.js").then((function(e){return e.x})),import("./codemirror_view-8wK3J563.js").then((function(e){return e.q})),import("./codemirror_commands-bA0DvCyD.js")]),y=e.getAttribute("target");let v;if(y){if(v=document.getElementById(y)||document.querySelector(y),!v)throw new Error(`Unknown target ${y}`)}else v=document.createElement(`${r}-editor`),v.style.display="block",e.after(v);v.id||(v.id=i(r)),v.hasAttribute("exec-id")||v.setAttribute("exec-id",0),v.hasAttribute("root")||v.setAttribute("root",v.id);const f=`${n}-${e.getAttribute("env")||i(r)}`,g={interpreter:n,env:f,get pySrc(){return L.state.doc.toString()},get outDiv(){return w}},h=c.bind(g),[b,w]=d(h,r);b.dataset.env=e.hasAttribute("env")?f:n;const E=b.querySelector(`.${r}-editor-input > div`).attachShadow({mode:"open"});E.innerHTML="<style> :host { all: initial; }</style>",v.appendChild(b);const $=t(e.textContent).trim(),A=/^(\s+)/m.test($)?RegExp.$1:" ",L=new s({extensions:[u.of(A),(new a).of(l()),m.of([...p,{key:"Ctrl-Enter",run:h,preventDefault:!0},{key:"Cmd-Enter",run:h,preventDefault:!0},{key:"Shift-Enter",run:h,preventDefault:!0}]),o],parent:E,doc:$});L.focus()};let m=0;const p=()=>{m=0,y()},y=async()=>{if(!m){m=setTimeout(p,250);for(const[t,r]of e){const e=`script[type="${t}-editor"]`;for(const n of document.querySelectorAll(e))n.type+="-active",await u(n,t,r)}}};new MutationObserver(y).observe(document,{childList:!0,subtree:!0});var v=y();export{v as default};
2
- //# sourceMappingURL=py-editor-9M31cFPh.js.map
1
+ import{T as e,d as t,X as r,H as n}from"./core-kKH572HC.js";let o=0;const s=e=>`${e}-editor-${o++}`,i=new Map,a={worker:{onReady:({runAsync:e,io:t},{sync:r})=>{t.stdout=e=>r.write(e),t.stderr=e=>r.writeErr(e),r.revoke(),r.runAsync=e}}};async function c({currentTarget:e}){const{env:t,pySrc:o,outDiv:s}=this;if(e.disabled=!0,s.innerHTML="",!i.has(t)){const e=URL.createObjectURL(new Blob([""])),o=r.call(new n(null,a),e,{type:this.interpreter}),{sync:s}=o,{promise:c,resolve:l}=Promise.withResolvers();i.set(t,c),s.revoke=()=>{URL.revokeObjectURL(e),l(o)}}i.get(t).then((t=>{t.onerror=({error:e})=>{s.innerHTML+=`<span style='color:red'>${e.message||e}</span>\n`,console.error(e)};const r=()=>{e.disabled=!1},{sync:n}=t;n.write=e=>{s.innerText+=`${e}\n`},n.writeErr=e=>{s.innerHTML+=`<span style='color:red'>${e}</span>\n`},n.runAsync(o).then(r,r)}))}const l=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-input`,r.setAttribute("aria-label","Python Script Area");const n=((e,t)=>{const r=document.createElement("button");return r.className=`absolute ${t}-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",e),r})(e,t),o=document.createElement("div");return o.addEventListener("keydown",(e=>{e.stopPropagation()})),r.append(n,o),r},d=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-box`;const n=l(e,t),o=(e=>{const t=document.createElement("div");return t.className=`${e}-editor-output`,t.id=`${s(e)}-output`,t})(t);return r.append(n,o),[r,o]},u=async(e,r,n)=>{const[{basicSetup:o,EditorView:i},{Compartment:a},{python:l},{indentUnit:u},{keymap:m},{defaultKeymap:p}]=await Promise.all([import("./codemirror-Maf5R0Dz.js"),import("./codemirror_state-W084kUeH.js"),import("./codemirror_lang-python-FADyYnPB.js"),import("./codemirror_language-xy4t5bF6.js").then((function(e){return e.x})),import("./codemirror_view-8wK3J563.js").then((function(e){return e.q})),import("./codemirror_commands-bA0DvCyD.js")]),y=e.getAttribute("target");let v;if(y){if(v=document.getElementById(y)||document.querySelector(y),!v)throw new Error(`Unknown target ${y}`)}else v=document.createElement(`${r}-editor`),v.style.display="block",e.after(v);v.id||(v.id=s(r)),v.hasAttribute("exec-id")||v.setAttribute("exec-id",0),v.hasAttribute("root")||v.setAttribute("root",v.id);const f=`${n}-${e.getAttribute("env")||s(r)}`,g={interpreter:n,env:f,get pySrc(){return L.state.doc.toString()},get outDiv(){return w}},h=c.bind(g),[b,w]=d(h,r);b.dataset.env=e.hasAttribute("env")?f:n;const E=b.querySelector(`.${r}-editor-input > div`).attachShadow({mode:"open"});E.innerHTML="<style> :host { all: initial; }</style>",v.appendChild(b);const $=t(e.textContent).trim(),A=/^(\s+)/m.test($)?RegExp.$1:" ",L=new i({extensions:[u.of(A),(new a).of(l()),m.of([...p,{key:"Ctrl-Enter",run:h,preventDefault:!0},{key:"Cmd-Enter",run:h,preventDefault:!0},{key:"Shift-Enter",run:h,preventDefault:!0}]),o],parent:E,doc:$});L.focus()};let m=0,p=Promise.resolve();const y=()=>{m=0,v()},v=async()=>{if(!m){m=setTimeout(y,250);for(const[t,r]of e){const e=`script[type="${t}-editor"]`;for(const n of document.querySelectorAll(e))n.type+="-active",p=p.then((()=>u(n,t,r)))}return p}};new MutationObserver(v).observe(document,{childList:!0,subtree:!0});var f=v();export{f as default};
2
+ //# sourceMappingURL=py-editor-PPTbETVX.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-editor-9M31cFPh.js","sources":["../src/plugins/py-editor.js"],"sourcesContent":["// PyScript py-editor plugin\nimport { Hook, XWorker, dedent } from \"polyscript/exports\";\nimport { TYPES } 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();\n\nconst hooks = {\n worker: {\n // works on both Pyodide and MicroPython\n onReady: ({ runAsync, io }, { sync }) => {\n io.stdout = (line) => sync.write(line);\n io.stderr = (line) => sync.writeErr(line);\n sync.revoke();\n sync.runAsync = runAsync;\n },\n },\n};\n\nasync function execute({ currentTarget }) {\n const { env, pySrc, outDiv } = this;\n\n currentTarget.disabled = true;\n outDiv.innerHTML = \"\";\n\n if (!envs.has(env)) {\n const srcLink = URL.createObjectURL(new Blob([\"\"]));\n const xworker = XWorker.call(new Hook(null, hooks), srcLink, {\n type: this.interpreter,\n });\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 envs.get(env).then((xworker) => {\n xworker.onerror = ({ error }) => {\n outDiv.innerHTML += `<span style='color:red'>${\n error.message || error\n }</span>\\n`;\n console.error(error);\n };\n\n const enable = () => {\n currentTarget.disabled = false;\n };\n const { sync } = xworker;\n sync.write = (str) => {\n outDiv.innerText += `${str}\\n`;\n };\n sync.writeErr = (str) => {\n outDiv.innerHTML += `<span style='color:red'>${str}</span>\\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 // TODO: find a way to actually produce these bundles locally\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 const selector = script.getAttribute(\"target\");\n\n let 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(`${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 const env = `${interpreter}-${script.getAttribute(\"env\") || getID(type)}`;\n const context = {\n interpreter,\n env,\n get pySrc() {\n return editor.state.doc.toString();\n },\n get outDiv() {\n return outDiv;\n },\n };\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};\n\n// avoid too greedy MutationObserver operations at distance\nlet timeout = 0;\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 = async () => {\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\n script.type += \"-active\";\n await init(script, type, interpreter);\n }\n }\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","hooks","worker","onReady","runAsync","io","sync","stdout","line","write","stderr","writeErr","revoke","async","execute","currentTarget","env","pySrc","outDiv","this","disabled","innerHTML","has","srcLink","URL","createObjectURL","Blob","xworker","XWorker","call","Hook","interpreter","promise","resolve","Promise","withResolvers","set","revokeObjectURL","get","then","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","import","n","x","q","selector","getAttribute","target","getElementById","querySelector","Error","style","display","after","hasAttribute","context","editor","state","doc","toString","bind","dataset","parent","attachShadow","mode","appendChild","dedent","textContent","trim","indentation","test","RegExp","$1","extensions","of","key","run","preventDefault","focus","timeout","resetTimeout","pyEditor","setTimeout","TYPES","querySelectorAll","MutationObserver","observe","childList","subtree","pyEditor$1"],"mappings":"4DAMA,IAAIA,EAAK,EACT,MAAMC,EAASC,GAAS,GAAGA,YAAeF,MAEpCG,EAAO,IAAIC,IAEXC,EAAQ,CACVC,OAAQ,CAEJC,QAAS,EAAGC,WAAUC,OAAQC,WAC1BD,EAAGE,OAAUC,GAASF,EAAKG,MAAMD,GACjCH,EAAGK,OAAUF,GAASF,EAAKK,SAASH,GACpCF,EAAKM,SACLN,EAAKF,SAAWA,CAAQ,IAKpCS,eAAeC,GAAQC,cAAEA,IACrB,MAAMC,IAAEA,EAAGC,MAAEA,EAAKC,OAAEA,GAAWC,KAK/B,GAHAJ,EAAcK,UAAW,EACzBF,EAAOG,UAAY,IAEdtB,EAAKuB,IAAIN,GAAM,CAChB,MAAMO,EAAUC,IAAIC,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OA,CACV,GAIC8B,EAAWlC,EAAQ+E,KAAKL,IACvB1B,EAAQ5C,GAAU2C,EAAWb,EAAUlD,GAC9CgE,EAAOgC,QAAQ9E,IAAMiD,EAAOsB,aAAa,OAASvE,EAAMe,EAExD,MACMgE,EADajC,EAAOoB,cAAc,IAAIpF,wBAClBkG,aAAa,CAAEC,KAAM,SAE/CF,EAAO1E,UAAY,0CAEnB2D,EAAOkB,YAAYpC,GAEnB,MAAM6B,EAAMQ,EAAOlC,EAAOmC,aAAaC,OAGjCC,EAAc,UAAUC,KAAKZ,GAAOa,OAAOC,GAAK,OAEhDhB,EAAS,IAAItB,EAAW,CAC1BuC,WAAY,CACRpC,EAAWqC,GAAGL,IACd,IAAIlC,GAAcuC,GAAGtC,KACrBE,EAAOoC,GAAG,IACHnC,EACH,CAAEoC,IAAK,aAAcC,IAAK7D,EAAU8D,gBAAgB,GACpD,CAAEF,IAAK,YAAaC,IAAK7D,EAAU8D,gBAAgB,GACnD,CAAEF,IAAK,cAAeC,IAAK7D,EAAU8D,gBAAgB,KAEzD5C,GAEJ6B,SACAJ,QAGJF,EAAOsB,OAAO,EAIlB,IAAIC,EAAU,EAGd,MAAMC,EAAe,KACjBD,EAAU,EACVE,GAAU,EAIRA,EAAWrG,UACb,IAAImG,EAAJ,CACAA,EAAUG,WAAWF,EAAc,KACnC,IAAK,MAAOnH,EAAMiC,KAAgBqF,EAAO,CACrC,MAAMtC,EAAW,gBAAgBhF,aACjC,IAAK,MAAMmE,KAAUf,SAASmE,iBAAiBvC,GAE3Cb,EAAOnE,MAAQ,gBACTkE,EAAKC,EAAQnE,EAAMiC,EAEhC,CATmB,CASnB,EAGL,IAAIuF,iBAAiBJ,GAAUK,QAAQrE,SAAU,CAC7CsE,WAAW,EACXC,SAAS,IAIb,IAAAC,EAAeR"}
1
+ {"version":3,"file":"py-editor-PPTbETVX.js","sources":["../src/plugins/py-editor.js"],"sourcesContent":["// PyScript py-editor plugin\nimport { Hook, XWorker, dedent } from \"polyscript/exports\";\nimport { TYPES } 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();\n\nconst hooks = {\n worker: {\n // works on both Pyodide and MicroPython\n onReady: ({ runAsync, io }, { sync }) => {\n io.stdout = (line) => sync.write(line);\n io.stderr = (line) => sync.writeErr(line);\n sync.revoke();\n sync.runAsync = runAsync;\n },\n },\n};\n\nasync function execute({ currentTarget }) {\n const { env, pySrc, outDiv } = this;\n\n currentTarget.disabled = true;\n outDiv.innerHTML = \"\";\n\n if (!envs.has(env)) {\n const srcLink = URL.createObjectURL(new Blob([\"\"]));\n const xworker = XWorker.call(new Hook(null, hooks), srcLink, {\n type: this.interpreter,\n });\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 envs.get(env).then((xworker) => {\n xworker.onerror = ({ error }) => {\n outDiv.innerHTML += `<span style='color:red'>${\n error.message || error\n }</span>\\n`;\n console.error(error);\n };\n\n const enable = () => {\n currentTarget.disabled = false;\n };\n const { sync } = xworker;\n sync.write = (str) => {\n outDiv.innerText += `${str}\\n`;\n };\n sync.writeErr = (str) => {\n outDiv.innerHTML += `<span style='color:red'>${str}</span>\\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 // TODO: find a way to actually produce these bundles locally\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 const selector = script.getAttribute(\"target\");\n\n let 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(`${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 const env = `${interpreter}-${script.getAttribute(\"env\") || getID(type)}`;\n const context = {\n interpreter,\n env,\n get pySrc() {\n return editor.state.doc.toString();\n },\n get outDiv() {\n return outDiv;\n },\n };\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};\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 = async () => {\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","hooks","worker","onReady","runAsync","io","sync","stdout","line","write","stderr","writeErr","revoke","async","execute","currentTarget","env","pySrc","outDiv","this","disabled","innerHTML","has","srcLink","URL","createObjectURL","Blob","xworker","XWorker","call","Hook","interpreter","promise","resolve","Promise","withResolvers","set","revokeObjectURL","get","then","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","import","n","x","q","selector","getAttribute","target","getElementById","querySelector","Error","style","display","after","hasAttribute","context","editor","state","doc","toString","bind","dataset","parent","attachShadow","mode","appendChild","dedent","textContent","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":"4DAMA,IAAIA,EAAK,EACT,MAAMC,EAASC,GAAS,GAAGA,YAAeF,MAEpCG,EAAO,IAAIC,IAEXC,EAAQ,CACVC,OAAQ,CAEJC,QAAS,EAAGC,WAAUC,OAAQC,WAC1BD,EAAGE,OAAUC,GAASF,EAAKG,MAAMD,GACjCH,EAAGK,OAAUF,GAASF,EAAKK,SAASH,GACpCF,EA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,EAAQA,EAAM1E,MAAK,IAAMyB,EAAKC,EAAQnE,EAAMiC,IAEnD,CACD,OAAOkF,CAZa,CAYR,EAGhB,IAAIM,iBAAiBJ,GAAUK,QAAQtE,SAAU,CAC7CuE,WAAW,EACXC,SAAS,IAIb,IAAAC,EAAeR"}
@@ -1,2 +1,2 @@
1
- import{T as e,e as t,a as r}from"./core-_MDTi7dy.js";import{notify as n}from"./error-yavCjy9g.js";const i=[...e.keys()].map((e=>`script[type="${e}"][terminal],${e}-script[terminal]`)).join(","),a=e=>{throw n(e),new Error(e)},o=e=>!l.has(e),s=({attributes:{worker:e}})=>!e,l=new WeakSet;let d=!0;const m=({interpreter:e,io:t,run:r},{sync:n})=>{if(!n.is_pyterminal())return;r("from polyscript.currentScript import terminal as __terminal__");const i=new TextDecoder;let a="";const o={isatty:!0,write:e=>(a=i.decode(e),n.pyterminal_write(a),e.length)};e.setStdout(o),e.setStderr(o),e.setStdin({isatty:!0,stdin:()=>n.pyterminal_read(a)}),t.stderr=e=>{n.pyterminal_write(`${e.message||e}\n`)}},c=async()=>{const e=document.querySelectorAll(i),n=[].filter.call(e,o);if(!n.length)return;n.forEach(l.add,l),[].filter.call(e,s).length>1&&a("You can use at most 1 main terminal"),d&&(d=!1,document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:new URL("./xterm.css",import.meta.url)})));const[{Terminal:c},{Readline:p},{FitAddon:y}]=await Promise.all([import("./xterm-f2QfYNGL.js"),import("./xterm-readline-ONk85xtH.js"),import("./xterm_addon-fit-E4yMPZTX.js")]);for(const e of n){e.matches('script[type="mpy"],mpy-script')&&a("Unsupported terminal.");const n=new p,i=t=>{let i=e;const a=e.getAttribute("target");if(a){if(i=document.getElementById(a)||document.querySelector(a),!i)throw new Error(`Unknown target ${a}`)}else i=document.createElement("py-terminal"),i.style.display="block",e.after(i);const o=new c({theme:{background:"#191A19",foreground:"#F5F2E7"},...t}),s=new y;return o.loadAddon(s),o.loadAddon(n),o.open(i),s.fit(),o.focus(),r(e,"terminal",{value:o}),o};e.hasAttribute("worker")?(t.main.onWorker.add((function e(r,a){l.has(a)||(l.add(a),t.main.onWorker.delete(e),i({disableStdin:!1,cursorBlink:!0,cursorStyle:"block"}),a.sync.is_pyterminal=()=>!0,a.sync.pyterminal_read=n.read.bind(n),a.sync.pyterminal_write=n.write.bind(n))})),t.worker.onReady.add(m)):t.main.onReady.add((function e({interpreter:r,io:a,run:o}){console.warn("py-terminal is read only on main thread"),t.main.onReady.delete(e),globalThis.__py_terminal__=i({disableStdin:!0,cursorBlink:!1,cursorStyle:"underline"}),o("from js import __py_terminal__ as __terminal__"),delete globalThis.__py_terminal__;const s=new TextDecoder;let l="";const d={isatty:!0,write:e=>(l=s.decode(e),n.write(l),e.length)};r.setStdout(d),r.setStderr(d),r.setStdin({isatty:!0,stdin:()=>n.read(l)}),a.stderr=e=>{n.write(`${e.message||e}\n`)}}))}};new MutationObserver(c).observe(document,{childList:!0,subtree:!0});var p=c();export{p as default};
2
- //# sourceMappingURL=py-terminal-oMtvSdlI.js.map
1
+ import{T as e,e as t,a as r}from"./core-kKH572HC.js";import{notify as n}from"./error-fa3ea4ix.js";const i=[...e.keys()].map((e=>`script[type="${e}"][terminal],${e}-script[terminal]`)).join(","),a=e=>{throw n(e),new Error(e)},o=e=>!l.has(e),s=({attributes:{worker:e}})=>!e,l=new WeakSet;let d=!0;const m=({interpreter:e,io:t,run:r},{sync:n})=>{if(!n.is_pyterminal())return;r("from polyscript.currentScript import terminal as __terminal__");const i=new TextDecoder;let a="";const o={isatty:!0,write:e=>(a=i.decode(e),n.pyterminal_write(a),e.length)};e.setStdout(o),e.setStderr(o),e.setStdin({isatty:!0,stdin:()=>n.pyterminal_read(a)}),t.stderr=e=>{n.pyterminal_write(`${e.message||e}\n`)}},c=async()=>{const e=document.querySelectorAll(i),n=[].filter.call(e,o);if(!n.length)return;n.forEach(l.add,l),[].filter.call(e,s).length>1&&a("You can use at most 1 main terminal"),d&&(d=!1,document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:new URL("./xterm.css",import.meta.url)})));const[{Terminal:c},{Readline:p},{FitAddon:y}]=await Promise.all([import("./xterm-f2QfYNGL.js"),import("./xterm-readline-ONk85xtH.js"),import("./xterm_addon-fit-E4yMPZTX.js")]);for(const e of n){e.matches('script[type="mpy"],mpy-script')&&a("Unsupported terminal.");const n=new p,i=t=>{let i=e;const a=e.getAttribute("target");if(a){if(i=document.getElementById(a)||document.querySelector(a),!i)throw new Error(`Unknown target ${a}`)}else i=document.createElement("py-terminal"),i.style.display="block",e.after(i);const o=new c({theme:{background:"#191A19",foreground:"#F5F2E7"},...t}),s=new y;return o.loadAddon(s),o.loadAddon(n),o.open(i),s.fit(),o.focus(),r(e,"terminal",{value:o}),o};e.hasAttribute("worker")?(t.main.onWorker.add((function e(r,a){l.has(a)||(l.add(a),t.main.onWorker.delete(e),i({disableStdin:!1,cursorBlink:!0,cursorStyle:"block"}),a.sync.is_pyterminal=()=>!0,a.sync.pyterminal_read=n.read.bind(n),a.sync.pyterminal_write=n.write.bind(n))})),t.worker.onReady.add(m)):t.main.onReady.add((function e({interpreter:r,io:a,run:o}){console.warn("py-terminal is read only on main thread"),t.main.onReady.delete(e),globalThis.__py_terminal__=i({disableStdin:!0,cursorBlink:!1,cursorStyle:"underline"}),o("from js import __py_terminal__ as __terminal__"),delete globalThis.__py_terminal__;const s=new TextDecoder;let l="";const d={isatty:!0,write:e=>(l=s.decode(e),n.write(l),e.length)};r.setStdout(d),r.setStderr(d),r.setStdin({isatty:!0,stdin:()=>n.read(l)}),a.stderr=e=>{n.write(`${e.message||e}\n`)}}))}};new MutationObserver(c).observe(document,{childList:!0,subtree:!0});var p=c();export{p as default};
2
+ //# sourceMappingURL=py-terminal-YYAkEGug.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-terminal-oMtvSdlI.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES, hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\nimport { defineProperty } from \"polyscript/exports\";\n\nconst SELECTOR = [...TYPES.keys()]\n .map((type) => `script[type=\"${type}\"][terminal],${type}-script[terminal]`)\n .join(\",\");\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 notParsedYet = (script) => !bootstrapped.has(script);\n\nconst onceOnMain = ({ attributes: { worker } }) => !worker;\n\nconst bootstrapped = new WeakSet();\n\nlet addStyle = true;\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 }, { sync }) => {\n if (!sync.is_pyterminal()) return;\n\n // in workers it's always safe to grab the polyscript currentScript\n run(\"from polyscript.currentScript import terminal as __terminal__\");\n\n // This part is inevitably duplicated as external scope\n // can't be reached by workers out of the box.\n // The detail is that here we use sync though, not readline.\n const decoder = new TextDecoder();\n let data = \"\";\n const generic = {\n isatty: true,\n write(buffer) {\n data = decoder.decode(buffer);\n sync.pyterminal_write(data);\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: true,\n stdin: () => sync.pyterminal_read(data),\n });\n\n io.stderr = (error) => {\n sync.pyterminal_write(`${error.message || error}\\n`);\n };\n};\n\nconst pyTerminal = async () => {\n const terminals = document.querySelectorAll(SELECTOR);\n\n const unknown = [].filter.call(terminals, notParsedYet);\n\n // no results will look further for runtime nodes\n if (!unknown.length) return;\n // early flag elements as known to avoid concurrent\n // MutationObserver invokes of this async handler\n else unknown.forEach(bootstrapped.add, bootstrapped);\n\n // we currently support only one terminal as in \"classic\"\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 // lazy load these only when a valid terminal is found\n const [{ Terminal }, { Readline }, { FitAddon }] = await Promise.all([\n import(/* webpackIgnore: true */ \"../3rd-party/xterm.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm-readline.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm_addon-fit.js\"),\n ]);\n\n for (const element of unknown) {\n // hopefully to be removed in the near future!\n if (element.matches('script[type=\"mpy\"],mpy-script'))\n notifyAndThrow(\"Unsupported terminal.\");\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.open(target);\n fitAddon.fit();\n terminal.focus();\n defineProperty(element, \"terminal\", { value: terminal });\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 }) {\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 // This part is inevitably duplicated as external scope\n // can't be reached by workers out of the box.\n // The detail is that here we use readline here, not sync.\n const decoder = new TextDecoder();\n let data = \"\";\n const generic = {\n isatty: true,\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: true,\n stdin: () => readline.read(data),\n });\n\n io.stderr = (error) => {\n readline.write(`${error.message || error}\\n`);\n };\n });\n }\n }\n};\n\nconst mo = new MutationObserver(pyTerminal);\nmo.observe(document, { childList: true, subtree: true });\n\n// try to check the current document ASAP\nexport default pyTerminal();\n"],"names":["SELECTOR","TYPES","keys","map","type","join","notifyAndThrow","message","notify","Error","notParsedYet","script","bootstrapped","has","onceOnMain","attributes","worker","WeakSet","addStyle","workerReady","interpreter","io","run","sync","is_pyterminal","decoder","TextDecoder","data","generic","isatty","write","buffer","decode","pyterminal_write","length","setStdout","setStderr","setStdin","stdin","pyterminal_read","stderr","error","pyTerminal","async","terminals","document","querySelectorAll","unknown","filter","call","forEach","add","head","append","Object","assign","createElement","rel","href","URL","url","Terminal","Readline","FitAddon","Promise","all","import","element","matches","readline","init","options","target","selector","getAttribute","getElementById","querySelector","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperty","value","hasAttribute","hooks","main","onWorker","_","xworker","delete","disableStdin","cursorBlink","cursorStyle","read","bind","onReady","console","warn","globalThis","__py_terminal__","MutationObserver","observe","childList","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CAC9B4B,cAAc,EACdC,aAAa,EACbC,YAAa,cAEjB9E,EAAI,yDACGoF,WAAWC,gBAKlB,MAAMlF,EAAU,IAAIC,YACpB,IAAIC,EAAO,GACX,MAAMC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFJ,EAAOF,EAAQO,OAAOD,GACtBsC,EAASvC,MAAMH,GACRI,EAAOG,SAGtBd,EAAYe,UAAUP,GACtBR,EAAYgB,UAAUR,GACtBR,EAAYiB,SAAS,CACjBR,QAAQ,EACRS,MAAO,IAAM+B,EAASgC,KAAK1E,KAG/BN,EAAGmB,OAAUC,IACT4B,EAASvC,MAAM,GAAGW,EAAMlC,SAAWkC,MAAU,CAEjE,GAEK,GAGM,IAAImE,iBAAiBlE,GAC7BmE,QAAQhE,SAAU,CAAEiE,WAAW,EAAMC,SAAS,IAGjD,IAAAC,EAAetE"}
1
+ {"version":3,"file":"py-terminal-YYAkEGug.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES, hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\nimport { defineProperty } from \"polyscript/exports\";\n\nconst SELECTOR = [...TYPES.keys()]\n .map((type) => `script[type=\"${type}\"][terminal],${type}-script[terminal]`)\n .join(\",\");\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 notParsedYet = (script) => !bootstrapped.has(script);\n\nconst onceOnMain = ({ attributes: { worker } }) => !worker;\n\nconst bootstrapped = new WeakSet();\n\nlet addStyle = true;\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 }, { sync }) => {\n if (!sync.is_pyterminal()) return;\n\n // in workers it's always safe to grab the polyscript currentScript\n run(\"from polyscript.currentScript import terminal as __terminal__\");\n\n // This part is inevitably duplicated as external scope\n // can't be reached by workers out of the box.\n // The detail is that here we use sync though, not readline.\n const decoder = new TextDecoder();\n let data = \"\";\n const generic = {\n isatty: true,\n write(buffer) {\n data = decoder.decode(buffer);\n sync.pyterminal_write(data);\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: true,\n stdin: () => sync.pyterminal_read(data),\n });\n\n io.stderr = (error) => {\n sync.pyterminal_write(`${error.message || error}\\n`);\n };\n};\n\nconst pyTerminal = async () => {\n const terminals = document.querySelectorAll(SELECTOR);\n\n const unknown = [].filter.call(terminals, notParsedYet);\n\n // no results will look further for runtime nodes\n if (!unknown.length) return;\n // early flag elements as known to avoid concurrent\n // MutationObserver invokes of this async handler\n else unknown.forEach(bootstrapped.add, bootstrapped);\n\n // we currently support only one terminal as in \"classic\"\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 // lazy load these only when a valid terminal is found\n const [{ Terminal }, { Readline }, { FitAddon }] = await Promise.all([\n import(/* webpackIgnore: true */ \"../3rd-party/xterm.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm-readline.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm_addon-fit.js\"),\n ]);\n\n for (const element of unknown) {\n // hopefully to be removed in the near future!\n if (element.matches('script[type=\"mpy\"],mpy-script'))\n notifyAndThrow(\"Unsupported terminal.\");\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.open(target);\n fitAddon.fit();\n terminal.focus();\n defineProperty(element, \"terminal\", { value: terminal });\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 }) {\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 // This part is inevitably duplicated as external scope\n // can't be reached by workers out of the box.\n // The detail is that here we use readline here, not sync.\n const decoder = new TextDecoder();\n let data = \"\";\n const generic = {\n isatty: true,\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: true,\n stdin: () => readline.read(data),\n });\n\n io.stderr = (error) => {\n readline.write(`${error.message || error}\\n`);\n };\n });\n }\n }\n};\n\nconst mo = new MutationObserver(pyTerminal);\nmo.observe(document, { childList: true, subtree: true });\n\n// try to check the current document ASAP\nexport default pyTerminal();\n"],"names":["SELECTOR","TYPES","keys","map","type","join","notifyAndThrow","message","notify","Error","notParsedYet","script","bootstrapped","has","onceOnMain","attributes","worker","WeakSet","addStyle","workerReady","interpreter","io","run","sync","is_pyterminal","decoder","TextDecoder","data","generic","isatty","write","buffer","decode","pyterminal_write","length","setStdout","setStderr","setStdin","stdin","pyterminal_read","stderr","error","pyTerminal","async","terminals","document","querySelectorAll","unknown","filter","call","forEach","add","head","append","Object","assign","createElement","rel","href","URL","url","Terminal","Readline","FitAddon","Promise","all","import","element","matches","readline","init","options","target","selector","getAttribute","getElementById","querySelector","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperty","value","hasAttribute","hooks","main","onWorker","_","xworker","delete","disableStdin","cursorBlink","cursorStyle","read","bind","onReady","console","warn","globalThis","__py_terminal__","MutationObserver","observe","childList","subtree","pyTerminal$1"],"mappings":"kGAKA,MAAMA,EAAW,IAAIC,EAAMC,QACtBC,KAAKC,GAAS,gBAAgBA,iBAAoBA,uBAClDC,KAAK,KAIJC,EAAkBC,IAEpB,MADAC,EAAOD,GACD,IAAIE,MAAMF,EAAQ,EAGtBG,EAAgBC,IAAYC,EAAaC,IAAIF,GAE7CG,EAAa,EAAGC,YAAcC,cAAgBA,EAE9CJ,EAAe,IAAIK,QAEzB,IAAIC,GAAW,EAKf,MAAMC,EAAc,EAAGC,cAAaC,KAAIC,QAASC,WAC7C,IAAKA,EAAKC,gBAAiB,OAG3BF,EAAI,iEAKJ,MAAMG,EAAU,IAAIC,YACpB,IAAIC,EAAO,GACX,MAAMC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFJ,EAAOF,EAAQO,OAAOD,GACtBR,EAAKU,iBAAiBN,GACfI,EAAOG,SAGtBd,EAAYe,UAAUP,GACtBR,E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2
2
  "name": "@pyscript/core",
3
- "version": "0.3.20",
3
+ "version": "0.3.21",
4
4
  "type": "module",
5
5
  "description": "PyScript",
6
6
  "module": "./index.js",
@@ -200,6 +200,9 @@ const init = async (script, type, interpreter) => {
200
200
  // avoid too greedy MutationObserver operations at distance
201
201
  let timeout = 0;
202
202
 
203
+ // avoid delayed initialization
204
+ let queue = Promise.resolve();
205
+
203
206
  // reset interval value then check for new scripts
204
207
  const resetTimeout = () => {
205
208
  timeout = 0;
@@ -213,11 +216,14 @@ const pyEditor = async () => {
213
216
  for (const [type, interpreter] of TYPES) {
214
217
  const selector = `script[type="${type}-editor"]`;
215
218
  for (const script of document.querySelectorAll(selector)) {
216
- // avoid any further bootstrap
219
+ // avoid any further bootstrap by changing the type as active
217
220
  script.type += "-active";
218
- await init(script, type, interpreter);
221
+ // don't await in here or multiple calls might happen
222
+ // while the first script is being initialized
223
+ queue = queue.then(() => init(script, type, interpreter));
219
224
  }
220
225
  }
226
+ return queue;
221
227
  };
222
228
 
223
229
  new MutationObserver(pyEditor).observe(document, {