@pyscript/core 0.4.50 → 0.4.51

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.
Files changed (40) hide show
  1. package/dist/{codemirror-CdY86QAP.js → codemirror-kHGMDdMq.js} +2 -2
  2. package/dist/codemirror-kHGMDdMq.js.map +1 -0
  3. package/dist/{codemirror_commands-Cg5rCf1I.js → codemirror_commands-BNzatDRz.js} +2 -2
  4. package/dist/{codemirror_commands-Cg5rCf1I.js.map → codemirror_commands-BNzatDRz.js.map} +1 -1
  5. package/dist/{codemirror_lang-python-BVX9Mc4s.js → codemirror_lang-python-PBvh5MWJ.js} +2 -2
  6. package/dist/{codemirror_lang-python-BVX9Mc4s.js.map → codemirror_lang-python-PBvh5MWJ.js.map} +1 -1
  7. package/dist/{codemirror_language-BFA8854-.js → codemirror_language-C0ccoJVB.js} +2 -2
  8. package/dist/{codemirror_language-BFA8854-.js.map → codemirror_language-C0ccoJVB.js.map} +1 -1
  9. package/dist/codemirror_view-CvBNngGG.js +2 -0
  10. package/dist/codemirror_view-CvBNngGG.js.map +1 -0
  11. package/dist/core-BQAbLvre.js +3 -0
  12. package/dist/core-BQAbLvre.js.map +1 -0
  13. package/dist/core.js +1 -1
  14. package/dist/{deprecations-manager-Bw93NImr.js → deprecations-manager-CQv1VsU_.js} +2 -2
  15. package/dist/{deprecations-manager-Bw93NImr.js.map → deprecations-manager-CQv1VsU_.js.map} +1 -1
  16. package/dist/{error-2kcNIsk_.js → error-DueleOMN.js} +2 -2
  17. package/dist/{error-2kcNIsk_.js.map → error-DueleOMN.js.map} +1 -1
  18. package/dist/index-lTKU5_hG.js +2 -0
  19. package/dist/index-lTKU5_hG.js.map +1 -0
  20. package/dist/{mpy-CD7enyf0.js → mpy-DOTPCj0o.js} +2 -2
  21. package/dist/{mpy-CD7enyf0.js.map → mpy-DOTPCj0o.js.map} +1 -1
  22. package/dist/{py-02uHRCjO.js → py-DoxIVXsQ.js} +2 -2
  23. package/dist/{py-02uHRCjO.js.map → py-DoxIVXsQ.js.map} +1 -1
  24. package/dist/{py-editor-DE9p9BaP.js → py-editor-D3FDoYNU.js} +2 -2
  25. package/dist/{py-editor-DE9p9BaP.js.map → py-editor-D3FDoYNU.js.map} +1 -1
  26. package/dist/{py-terminal-BlDcqGGy.js → py-terminal-DMP3XcAx.js} +2 -2
  27. package/dist/{py-terminal-BlDcqGGy.js.map → py-terminal-DMP3XcAx.js.map} +1 -1
  28. package/package.json +5 -5
  29. package/src/stdlib/pyscript/__init__.py +3 -0
  30. package/src/stdlib/pyscript/workers.py +15 -0
  31. package/src/stdlib/pyscript.js +3 -2
  32. package/types/exceptions.d.ts +1 -16
  33. package/types/stdlib/pyscript.d.ts +1 -0
  34. package/dist/codemirror-CdY86QAP.js.map +0 -1
  35. package/dist/codemirror_view-CH0UDCz6.js +0 -2
  36. package/dist/codemirror_view-CH0UDCz6.js.map +0 -1
  37. package/dist/core-66LzWJRR.js +0 -3
  38. package/dist/core-66LzWJRR.js.map +0 -1
  39. package/dist/index-C02Lyjc0.js +0 -2
  40. package/dist/index-C02Lyjc0.js.map +0 -1
@@ -0,0 +1,3 @@
1
+ const e=(e,n,t=globalThis)=>{const r=Symbol.for(e),s=r in t;return[s?t[r]:Object.defineProperty(t,r,{value:n})[r],s]};Promise.withResolvers||(Promise.withResolvers=function(){var e,n,t=new this((function(t,r){e=t,n=r}));return{resolve:e,reject:n,promise:t}});const n=(e,n=document)=>[...n.querySelectorAll(e)],t=(e,n=document)=>{const t=(new XPathEvaluator).createExpression(e).evaluate(n,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE),r=[];for(let e=0,{snapshotLength:n}=t;e<n;e++)r.push(t.snapshotItem(e));return r},r=Object.getOwnPropertyDescriptors(Response.prototype),s=e=>"function"==typeof e,o={get:(e,n)=>r.hasOwnProperty(n)?((e,n,{get:t,value:r})=>t||!s(r)?e.then((e=>e[n])):(...t)=>e.then((e=>e[n](...t))))(e,n,r[n]):((e,n)=>s(n)?n.bind(e):n)(e,e[n])};var a=(e,...n)=>new Proxy(fetch(e,...n),o);const i=new Proxy(new Map,{get:(e,n)=>(e.has(n)||e.set(n,Promise.withResolvers()),e.get(n))}),l=new Proxy(i,{get:(e,n)=>i[n].promise.then((e=>e.sync))}),p="object"==typeof self?self:globalThis,c=e=>((e,n)=>{const t=(n,t)=>(e.set(t,n),n),r=s=>{if(e.has(s))return e.get(s);const[o,a]=n[s];switch(o){case 0:case-1:return t(a,s);case 1:{const e=t([],s);for(const n of a)e.push(r(n));return e}case 2:{const e=t({},s);for(const[n,t]of a)e[r(n)]=r(t);return e}case 3:return t(new Date(a),s);case 4:{const{source:e,flags:n}=a;return t(new RegExp(e,n),s)}case 5:{const e=t(new Map,s);for(const[n,t]of a)e.set(r(n),r(t));return e}case 6:{const e=t(new Set,s);for(const n of a)e.add(r(n));return e}case 7:{const{name:e,message:n}=a;return t(new p[e](n),s)}case 8:return t(BigInt(a),s);case"BigInt":return t(Object(BigInt(a)),s)}return t(new p[o](a),s)};return r})(new Map,e)(0),d="",{toString:f}={},{keys:m}=Object,u=e=>{const n=typeof e;if("object"!==n||!e)return[0,n];const t=f.call(e).slice(8,-1);switch(t){case"Array":return[1,d];case"Object":return[2,d];case"Date":return[3,d];case"RegExp":return[4,d];case"Map":return[5,d];case"Set":return[6,d]}return t.includes("Array")?[1,t]:t.includes("Error")?[7,t]:[2,t]},h=([e,n])=>0===e&&("function"===n||"symbol"===n),y=(e,{json:n,lossy:t}={})=>{const r=[];return((e,n,t,r)=>{const s=(e,n)=>{const s=r.push(e)-1;return t.set(n,s),s},o=r=>{if(t.has(r))return t.get(r);let[a,i]=u(r);switch(a){case 0:{let n=r;switch(i){case"bigint":a=8,n=r.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+i);n=null;break;case"undefined":return s([-1],r)}return s([a,n],r)}case 1:{if(i)return s([i,[...r]],r);const e=[],n=s([a,e],r);for(const n of r)e.push(o(n));return n}case 2:{if(i)switch(i){case"BigInt":return s([i,r.toString()],r);case"Boolean":case"Number":case"String":return s([i,r.valueOf()],r)}if(n&&"toJSON"in r)return o(r.toJSON());const t=[],l=s([a,t],r);for(const n of m(r))!e&&h(u(r[n]))||t.push([o(n),o(r[n])]);return l}case 3:return s([a,r.toISOString()],r);case 4:{const{source:e,flags:n}=r;return s([a,{source:e,flags:n}],r)}case 5:{const n=[],t=s([a,n],r);for(const[t,s]of r)(e||!h(u(t))&&!h(u(s)))&&n.push([o(t),o(s)]);return t}case 6:{const n=[],t=s([a,n],r);for(const t of r)!e&&h(u(t))||n.push(o(t));return t}}const{message:l}=r;return s([a,{name:i,message:l}],r)};return o})(!(n||t),!!n,new Map,r)(e),r},{parse:g,stringify:_}=JSON,w={json:!0,lossy:!0};var b=Object.freeze({__proto__:null,parse:e=>c(g(e)),stringify:e=>_(y(e,w))});const v="64e10b34-2bf7-4616-9668-f99de5aa046e",S="M"+v,E="T"+v,P="array",T="function",k="null",x="number",J="object",j="string",R="symbol",M="undefined",N="apply",A="construct",L="defineProperty",W="deleteProperty",O="get",H="getOwnPropertyDescriptor",B="getPrototypeOf",U="has",I="isExtensible",z="ownKeys",$="preventExtensions",C="set",D="setPrototypeOf",F="delete",{isArray:q}=Array;let{SharedArrayBuffer:G,window:V}=globalThis,{notify:Y,wait:K,waitAsync:X}=Atomics,Z=null;X||(X=e=>({value:new Promise((n=>{let t=new Worker("data:application/javascript,onmessage%3D(%7Bdata%3Ab%7D)%3D%3E(Atomics.wait(b%2C0)%2CpostMessage(0))");t.onmessage=n,t.postMessage(e)}))}));try{new G(4)}catch(e){G=ArrayBuffer;const n=new WeakMap;if(V){const e=new Map,{prototype:{postMessage:t}}=Worker,r=n=>{const t=n.data?.[v];if(!q(t)){n.stopImmediatePropagation();const{id:r,sb:s}=t;e.get(r)(s)}};Z=function(e,...s){const o=e?.[v];if(q(o)){const[e,t]=o;n.set(t,e),this.addEventListener("message",r)}return t.call(this,e,...s)},X=t=>({value:new Promise((r=>{e.set(n.get(t),r)})).then((r=>{e.delete(n.get(t)),n.delete(t);for(let e=0;e<r.length;e++)t[e]=r[e];return"ok"}))})}else{const e=(e,n)=>({[v]:{id:e,sb:n}});Y=t=>{postMessage(e(n.get(t),t))},addEventListener("message",(e=>{const t=e.data?.[v];if(q(t)){const[e,r]=t;n.set(r,e)}}))}}
2
+ /*! (c) Andrea Giammarchi - ISC */const{Int32Array:Q,Map:ee,Uint16Array:ne}=globalThis,{BYTES_PER_ELEMENT:te}=Q,{BYTES_PER_ELEMENT:re}=ne,se=new WeakSet,oe=new WeakMap,ae={value:{then:e=>e()}};let ie=0;const le=(e,{parse:n=JSON.parse,stringify:t=JSON.stringify,transform:r,interrupt:s}=JSON)=>{if(!oe.has(e)){const o=Z||e.postMessage,a=(n,...t)=>o.call(e,{[v]:t},{transfer:n}),i=typeof s===T?s:s?.handler,l=s?.delay||42,p=new TextDecoder("utf-16"),c=(e,n)=>e?X(n,0):(i?((e,n,t)=>{for(;"timed-out"===K(e,0,0,n);)t()})(n,l,i):K(n,0),ae);let d=!1;oe.set(e,new Proxy(new ee,{[U]:(e,n)=>"string"==typeof n&&!n.startsWith("_"),[O]:(t,s)=>"then"===s?null:(...t)=>{const o=ie++;let i=new Q(new G(2*te)),l=[];se.has(t.at(-1)||l)&&se.delete(l=t.pop()),a(l,o,i,s,r?t.map(r):t);const f=e!==globalThis;let m=0;return d&&f&&(m=setTimeout(console.warn,1e3,`💀🔒 - Possible deadlock if proxy.${s}(...args) is awaited`)),c(f,i).value.then((()=>{clearTimeout(m);const e=i[1];if(!e)return;const t=re*e;return i=new Q(new G(t+t%te)),a([],o,i),c(f,i).value.then((()=>n(p.decode(new ne(i.buffer).slice(0,e)))))}))},[C](n,s,o){const a=typeof o;if(a!==T)throw new Error(`Unable to assign ${s} as ${a}`);if(!n.size){const s=new ee;e.addEventListener("message",(async e=>{const o=e.data?.[v];if(q(o)){e.stopImmediatePropagation();const[a,i,...l]=o;let p;if(l.length){const[e,o]=l;if(n.has(e)){d=!0;try{const l=await n.get(e)(...o);if(void 0!==l){const e=t(r?r(l):l);s.set(a,e),i[1]=e.length}}catch(e){p=e}finally{d=!1}}else p=new Error(`Unsupported action: ${e}`);i[0]=1}else{const e=s.get(a);s.delete(a);for(let n=new ne(i.buffer),t=0;t<e.length;t++)n[t]=e.charCodeAt(t)}if(Y(i,0),p)throw p}}))}return!!n.set(s,o)}}))}return oe.get(e)};le.transfer=(...e)=>(se.add(e),e);const{isArray:pe}=Array,ce=(e,n)=>n,de=e=>typeof e===T?(e=>e())(e):e;function fe(){return this}const me=(e,n)=>e===P?[n]:{t:e,v:n},ue=(e,n=ce)=>{let t=typeof e,r=e;return t===J&&(pe(e)?(t=P,r=e.at(0)):({t:t,v:r}=e)),n(t,r)},he=(e,n)=>e===T?n:me(e,n),ye=(e,n=he)=>{const t=null===e?k:typeof e;return n(t===J&&pe(e)?P:t,e)},ge=new FinalizationRegistry((([e,n,t])=>{t&&console.debug(`Held value ${String(n)} not relevant anymore`),e(n)})),_e=Object.create(null),we=(e,n,{debug:t,handler:r,return:s,token:o=e}=_e)=>{const a=s||new Proxy(e,r||_e),i=[a,[n,e,!!t]];return!1!==o&&i.push(o),ge.register(...i),a},{defineProperty:be,deleteProperty:ve,getOwnPropertyDescriptor:Se,getPrototypeOf:Ee,isExtensible:Pe,ownKeys:Te,preventExtensions:ke,set:xe,setPrototypeOf:Je}=Reflect,{assign:je,create:Re}=Object,Me=Ee(Int8Array),Ne=(e,n)=>{const{get:t,set:r,value:s}=e;return t&&(e.get=n(t)),r&&(e.set=n(r)),s&&(e.value=n(s)),e},Ae=e=>n=>ye(n,((n,t)=>{switch(n){case k:return me(k,t);case J:if(t===globalThis)return me(n,null);case P:case T:return e(n,t);case"boolean":case x:case j:case M:case"bigint":return me(n,t);case R:{if(Le.has(t))return me(n,Le.get(t));let e=Symbol.keyFor(t);if(e)return me(n,`.${e}`)}}throw new TypeError(`Unable to handle this ${n}: ${String(t)}`)})),Le=new Map(Te(Symbol).filter((e=>typeof Symbol[e]===R)).map((e=>[Symbol[e],e]))),We=e=>{if(e.startsWith("."))return Symbol.for(e.slice(1));for(const[n,t]of Le)if(t===e)return n},Oe=e=>e;var He=((e,n)=>{const t=new WeakMap;{const{addEventListener:e}=EventTarget.prototype;be(EventTarget.prototype,"addEventListener",{value(n,r,...s){return s.at(0)?.invoke&&(t.has(this)||t.set(this,new Map),t.get(this).set(n,[].concat(s[0].invoke)),delete s[0].invoke),e.call(this,n,r,...s)}})}return function(n,r,s,...o){let a=0,i=this?.transform||Oe;const l=new Map,p=new Map,{[s]:c}=n,d=o.length?je(Re(globalThis),...o):globalThis,f=Ae(((e,n)=>{if(!l.has(n)){let t;for(;p.has(t=a++););l.set(n,t),p.set(t,e===T?n:i(n))}return me(e,l.get(n))})),m=e=>{c(F,me(j,e))},u=(e,n)=>{switch(e){case J:if(null==n)return d;case P:if(typeof n===x)return p.get(n);if(!(n instanceof Me))for(const e in n)n[e]=h(n[e]);return n;case T:if(typeof n===j){const e=p.get(n)?.deref();if(e)return e;const r=function(...e){return e.at(0)instanceof Event&&(e=>{const{currentTarget:n,target:r,type:s}=e;for(const o of t.get(n||r)?.get(s)||[])e[o]()})(...e),c(N,me(T,n),f(this),e.map(f))};return p.set(n,new WeakRef(r)),we(n,m,{return:r,token:!1})}return p.get(n);case R:return We(n)}return n},h=e=>ue(e,u),y={[N]:(e,n,t)=>f(e.apply(n,t)),[A]:(e,n)=>f(new e(...n)),[L]:(e,n,t)=>f(be(e,n,t)),[W]:(e,n)=>f(ve(e,n)),[B]:e=>f(Ee(e)),[O]:(e,n)=>f(e[n]),[H]:(e,n)=>{const t=Se(e,n);return t?me(J,Ne(t,f)):me(M,t)},[U]:(e,n)=>f(n in e),[I]:e=>f(Pe(e)),[z]:e=>me(P,Te(e).map(f)),[$]:e=>f(ke(e)),[C]:(e,n,t)=>f(xe(e,n,t)),[D]:(e,n)=>f(Je(e,n)),[F](e){l.delete(p.get(e)),p.delete(e)}};return n[r]=(e,n,...t)=>{switch(e){case N:t[0]=h(t[0]),t[1]=t[1].map(h);break;case A:t[0]=t[0].map(h);break;case L:{const[e,n]=t;t[0]=h(e);const{get:r,set:s,value:o}=n;r&&(n.get=h(r)),s&&(n.set=h(s)),o&&(n.value=h(o));break}default:t=t.map(h)}return y[e](h(n),...t)},{proxy:n,[e.toLowerCase()]:d,[`is${e}Proxy`]:()=>!1}}})("Window"),Be=(e=>{let n=0;const t=new Map,r=new Map,s=Symbol();return function(o,a,i){const l=this?.transform||Oe,{[a]:p}=o,c=new Map,d=e=>{c.delete(e),p(F,f(e))},f=Ae(((e,o)=>{if(s in o)return de(o[s]);if(e===T){if(o=l(o),!r.has(o)){let e;for(;r.has(e=String(n++)););t.set(o,e),r.set(e,o)}return me(e,t.get(o))}if(!(o instanceof Me)){o=l(o);for(const e in o)o[e]=f(o[e])}return me(e,o)})),m=(e,n,t)=>{const r=c.get(t)?.deref();if(r)return r;const s=n===T?(e=>fe.bind(e))(e):e,o=new Proxy(s,y);return c.set(t,new WeakRef(o)),we(t,d,{return:o,token:!1})},u=e=>ue(e,((n,t)=>{switch(n){case J:if(null===t)return globalThis;case P:return typeof t===x?m(e,n,t):t;case T:return typeof t===j?r.get(t):m(e,n,t);case R:return We(t)}return t})),h=(e,n,...t)=>u(p(e,de(n),...t)),y={[N]:(e,n,t)=>h(N,e,f(n),t.map(f)),[A]:(e,n)=>h(A,e,n.map(f)),[L]:(e,n,t)=>{const{get:r,set:s,value:o}=t;return typeof r===T&&(t.get=f(r)),typeof s===T&&(t.set=f(s)),typeof o===T&&(t.value=f(o)),h(L,e,f(n),t)},[W]:(e,n)=>h(W,e,f(n)),[B]:e=>h(B,e),[O]:(e,n)=>n===s?e:h(O,e,f(n)),[H]:(e,n)=>{const t=h(H,e,f(n));return t&&Ne(t,u)},[U]:(e,n)=>n===s||h(U,e,f(n)),[I]:e=>h(I,e),[z]:e=>h(z,e).map(u),[$]:e=>h($,e),[C]:(e,n,t)=>h(C,e,f(n),f(t)),[D]:(e,n)=>h(D,e,f(n))};o[i]=(e,n,s,o)=>{switch(e){case N:return u(n).apply(u(s),o.map(u));case F:{const e=u(n);t.delete(r.get(e)),r.delete(e)}}};const g=new Proxy(me(J,null),y);return{[e.toLowerCase()]:g,[`is${e}Proxy`]:e=>typeof e===J&&!!e&&s in e,proxy:o}}})("Window"),Ue=typeof Worker===T?Worker:class{};const Ie=new WeakMap,ze=(e,...n)=>{const t=le(e,...n);if(!Ie.has(t)){const r=e instanceof Ue?He:Be;Ie.set(t,r.call(n.at(0),t,S,E))}return Ie.get(t)};ze.transfer=le.transfer;const{url:$e}=import.meta,Ce=/import\((['"])([^)]+?\.js)\1\)/g,De=(e,n,t)=>`import(${n}${new URL(t,$e).href}${n})`;const Fe={object(...e){return this.string(function(e){for(var n=e[0],t=1,r=arguments.length;t<r;t++)n+=arguments[t]+e[t];return n}(...e))},string(e){for(const n of e.split(/[\r\n]+/))if(n.trim().length){/^(\s+)/.test(n)&&(e=e.replace(new RegExp("^"+RegExp.$1,"gm"),""));break}return e}},{replace:qe}="",Ge=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g,Ve={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"'},Ye=e=>Ve[e],Ke=new WeakMap,Xe=e=>{const n=e||console,t={buffered:Qe,stderr:(n.stderr||console.error).bind(n),stdout:(n.stdout||console.log).bind(n)};return{stderr:(...e)=>t.stderr(...e),stdout:(...e)=>t.stdout(...e),async get(e){const n=await e;return Ke.set(n,t),n}}},Ze=new TextDecoder,Qe=(e,n=10)=>{const t=[];return r=>{if(r instanceof Uint8Array)for(const s of r)s===n?e(Ze.decode(new Uint8Array(t.splice(0)))):t.push(s);else e(r)}},en=(e,...n)=>Fe[typeof e](e,...n),nn=e=>qe.call(e,Ge,Ye),{isArray:tn}=Array,{assign:rn,create:sn,defineProperties:on,defineProperty:an,entries:ln}=Object,{all:pn,resolve:cn}=new Proxy(Promise,{get:(e,n)=>e[n].bind(e)}),dn=(e,n=location.href)=>new URL(e,n.replace(/^blob:/,"")).href;let fn=0;const mn=(e,n)=>({id:e.id||(e.id=`${n}-w${fn++}`),tag:e.tagName}),un=(e,n,t,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${n}:${t}`,{bubbles:!0,detail:{worker:r}}))},hn=(e,n,t,r)=>({type:n,config:t,interpreter:r,io:Ke.get(r),run:(n,...t)=>e.run(r,n,...t),runAsync:(n,...t)=>e.runAsync(r,n,...t),runEvent:(...n)=>e.runEvent(r,...n)}),yn=e=>e.replace(/^(?:\n|\r\n)/,""),gn=(e,n,t,r)=>{const s=e[n].bind(e);e[n]="run"===n?(e,n,...o)=>{t&&s(e,t,...o);const a=s(e,yn(n),...o);return r&&s(e,r,...o),a}:async(e,n,...o)=>{t&&await s(e,t,...o);const a=await s(e,yn(n),...o);return r&&await s(e,r,...o),a}},_n=Symbol.for("polyscript.js_modules"),wn=new Map;an(globalThis,_n,{value:wn});const bn=new Proxy(wn,{get:(e,n)=>e.get(n),has:(e,n)=>e.has(n),ownKeys:e=>[...e.keys()]}),vn=(e,n)=>!n.startsWith("_"),Sn=(e,n)=>new Proxy(e,{has:vn,get:(e,t)=>e[n][t]}),En=(e,n,t,r)=>{if("pyodide"===e)return;const s="polyscript.js_modules";for(const e of Reflect.ownKeys(r))n.registerJSModule(t,`${s}.${e}`,Sn(r,e));n.registerJSModule(t,s,r)},Pn=(e,n)=>import(e).then((e=>{wn.set(n,{...e})})),Tn=e=>new Promise(((n,t)=>{document.querySelector(`link[href="${e}"]`)&&n(),document.head.append(rn(document.createElement("link"),{rel:"stylesheet",href:e,onload:n,onerror:t}))})),kn=e=>/\.css/i.test(new URL(e).pathname),xn=!globalThis.window,Jn=({FS:e,PATH:n,PATH_FS:t},r,s)=>{const o=t.resolve(r),a=n.dirname(o);return e.mkdirTree?e.mkdirTree(a):Rn(e,a),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},jn=e=>{const n=e.split("/");return n.pop(),n.join("/")},Rn=(e,n)=>{const t=[];for(const r of n.split("/"))"."!==r&&".."!==r&&(t.push(r),r&&e.mkdir(t.join("/")))},Mn=(e,n)=>{const t=[];for(const e of n.split("/"))switch(e){case"":case".":break;case"..":t.pop();break;default:t.push(e)}return[e.cwd()].concat(t).join("/").replace(/^\/+/,"/")},Nn=e=>{const n=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,""))).filter((e=>""!==e&&"."!==e)).join("/");return e[0].startsWith("/")?`/${n}`:n},An=(e,n)=>a(dn(e,n)).arrayBuffer(),Ln=(e,n,t,r)=>pn((e=>{for(const{files:n,to_file:t,from:r=""}of e){if(void 0!==n&&void 0!==t)throw new Error("Cannot use 'to_file' and 'files' parameters together!");if(void 0===n&&void 0===t&&r.endsWith("/"))throw new Error(`Couldn't determine the filename from the path ${r}, please supply 'to_file' parameter.`)}return e.flatMap((({from:e="",to_folder:n=".",to_file:t,files:r})=>{if(tn(r))return r.map((t=>({url:Nn([e,t]),path:Nn([n,t])})));const s=t||e.slice(1+e.lastIndexOf("/"));return[{url:e,path:Nn([n,s])}]}))})(t).map((({url:t,path:s})=>An(t,r).then((t=>e.writeFile(n,s,t)))))),Wn=(e,n)=>n.endsWith("/")?`${n}${e.split("/").pop()}`:n,On=(e,n)=>e.replace(/\{.+?\}/g,(e=>{if(!n.has(e))throw new SyntaxError(`Invalid template: ${e}`);return n.get(e)})),Hn=(e,n,t,r)=>pn((e=>{const n=new Map,t=new Set,r=[];for(const[s,o]of ln(e))if(/^\{.+\}$/.test(s)){if(n.has(s))throw new SyntaxError(`Duplicated template: ${s}`);n.set(s,On(o,n))}else{const e=On(s,n),a=Wn(e,On(o||"./",n));if(t.has(a))throw new SyntaxError(`Duplicated destination: ${a}`);t.add(a),r.push({url:e,path:a})}return r})(t).map((({url:t,path:s})=>An(t,r).then((r=>e.writeFile(n,s,r,t)))))),Bn=({main:e,worker:n},t)=>{const r=[];if(n&&xn)for(let[e,s]of ln(n))e=dn(e,t),r.push(Pn(e,s));if(e&&!xn)for(let[n,s]of ln(e))n=dn(n,t),kn(n)?Tn(n):r.push(Pn(n,s));return pn(r)},{assign:Un}=Object,In="entries",zn="readonly",$n="readwrite",Cn={durability:"default",prefix:"IDBMap"},Dn=({target:{result:e}})=>e;class Fn extends EventTarget{#e;#n;#t;async#r(e,n){const t=(await this.#e).transaction(In,n,this.#n);return new Promise(((n,r)=>Un(e(t.objectStore(In)),{onsuccess:n,onerror:r})))}constructor(e,{durability:n=Cn.durability,prefix:t=Cn.prefix}=Cn){super(),this.#t=t,this.#n={durability:n},this.#e=new Promise(((n,t)=>{Un(indexedDB.open(`${this.#t}/${e}`),{onupgradeneeded({target:{result:e,transaction:t}}){e.objectStoreNames.length||e.createObjectStore(In),t.oncomplete=()=>n(e)},onsuccess(e){n(Dn(e))},onerror(e){t(e),this.dispatchEvent(e)}})})).then((e=>{const n=this.dispatchEvent.bind(this);for(const t in e)t.startsWith("on")&&(e[t]=n);return e}))}dispatchEvent(e){const{type:n,message:t,isTrusted:r}=e;return super.dispatchEvent(r?Un(new Event(n),{message:t}):e)}async close(){(await this.#e).close()}get size(){return this.#r((e=>e.count()),zn).then(Dn)}async clear(){await this.#r((e=>e.clear()),$n)}async delete(e){await this.#r((n=>n.delete(e)),$n)}async entries(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e).then((n=>[e,n])))))}async forEach(e,n=this){for(const[t,r]of await this.entries())await e.call(n,r,t,this)}async get(e){return await this.#r((n=>n.get(e)),zn).then(Dn)}async has(e){return void 0!==await this.#r((n=>n.getKey(e)),zn).then(Dn)}async keys(){return await this.#r((e=>e.getAllKeys()),zn).then(Dn)}async set(e,n){return await this.#r((t=>t.put(n,e)),$n),this}async values(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e))))}get[Symbol.toStringTag](){return this.#t}}class qn extends Map{#s;#o;constructor(...e){super(),this.#s=new Fn(...e),this.#o=this.#s.entries().then((e=>{for(const[n,t]of e)super.set(n,t)}))}async sync(){await this.#o}clear(){return this.#o=this.#o.then((()=>this.#s.clear())),super.clear()}delete(e){return this.#o=this.#o.then((()=>this.#s.delete(e))),super.delete(e)}set(e,n){return this.#o=this.#o.then((()=>this.#s.set(e,n))),super.set(e,n)}}const Gn=new WeakMap,Vn=(e,n,t)=>{"polyscript"===n&&(t.lazy_py_modules=async(...n)=>(await Gn.get(e)(n),n.map((n=>e.pyimport(n)))),t.storage=async e=>{const n=new qn(e);return await n.sync(),n},t.JSON=b),e.registerJsModule(n,t)},Yn=(e,n)=>{if(e.endsWith("/*")){if(/\.(zip|whl|tgz|tar(?:\.gz)?)$/.test(n))return RegExp.$1;throw new Error(`Unsupported archive ${n}`)}return""},Kn=(e,n,...t)=>{try{return e.runPython(en(n),...t)}catch(n){Ke.get(e).stderr(n)}},Xn=async(e,n,...t)=>{try{return await e.runPythonAsync(en(n),...t)}catch(n){Ke.get(e).stderr(n)}},Zn=async(e,n,t)=>{const[r,...s]=n.split(".");let o,a=e.globals.get(r);for(const e of s)[o,a]=[a,a[e]];try{await a.call(o,t)}catch(n){Ke.get(e).stderr(n)}};var Qn=(new TextEncoder).encode('from uio import StringIO\nimport sys\n\nclass Response:\n def __init__(self, f):\n self.raw = f\n self.encoding = "utf-8"\n self._cached = None\n\n def close(self):\n if self.raw:\n self.raw.close()\n self.raw = None\n self._cached = None\n\n @property\n def content(self):\n if self._cached is None:\n try:\n self._cached = self.raw.read()\n finally:\n self.raw.close()\n self.raw = None\n return self._cached\n\n @property\n def text(self):\n return str(self.content, self.encoding)\n\n def json(self):\n import ujson\n\n return ujson.loads(self.content)\n\n\n# TODO try to support streaming xhr requests, a-la pyodide-http\nHEADERS_TO_IGNORE = ("user-agent",)\n\n\ntry:\n import js\nexcept Exception as err:\n raise OSError("This version of urequests can only be used in the browser")\n\n# TODO try to support streaming xhr requests, a-la pyodide-http\n\nHEADERS_TO_IGNORE = ("user-agent",)\n\n\ndef request(\n method,\n url,\n data=None,\n json=None,\n headers={},\n stream=None,\n auth=None,\n timeout=None,\n parse_headers=True,\n):\n from js import XMLHttpRequest\n\n xhr = XMLHttpRequest.new()\n xhr.withCredentials = False\n\n if auth is not None:\n import ubinascii\n\n username, password = auth\n xhr.open(method, url, False, username, password)\n else:\n xhr.open(method, url, False)\n\n for name, value in headers.items():\n if name.lower() not in HEADERS_TO_IGNORE:\n xhr.setRequestHeader(name, value)\n\n if timeout:\n xhr.timeout = int(timeout * 1000)\n\n if json is not None:\n assert data is None\n import ujson\n\n data = ujson.dumps(json)\n # s.write(b"Content-Type: application/json\\r\\n")\n xhr.setRequestHeader("Content-Type", "application/json")\n\n xhr.send(data)\n\n # Emulates the construction process in the original urequests\n resp = Response(StringIO(xhr.responseText))\n resp.status_code = xhr.status\n resp.reason = xhr.statusText\n resp.headers = xhr.getAllResponseHeaders()\n\n return resp\n\n\n# Other methods - head, post, put, patch, delete - are not used by\n# mip and therefore not included\n\n\ndef get(url, **kw):\n return request("GET", url, **kw)\n\n\n# Content below this line is from the Micropython MIP package and is covered\n# by the applicable MIT license:\n# \n# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \n# DEALINGS IN THE SOFTWARE.\n\n# MicroPython package installer\n# MIT license; Copyright (c) 2022 Jim Mussared\n\n\n_PACKAGE_INDEX = const("https://micropython.org/pi/v2")\n_CHUNK_SIZE = 128\n\n\n# This implements os.makedirs(os.dirname(path))\ndef _ensure_path_exists(path):\n import os\n\n split = path.split("/")\n\n # Handle paths starting with "/".\n if not split[0]:\n split.pop(0)\n split[0] = "/" + split[0]\n\n prefix = ""\n for i in range(len(split) - 1):\n prefix += split[i]\n try:\n os.stat(prefix)\n except:\n os.mkdir(prefix)\n prefix += "/"\n\n\n# Copy from src (stream) to dest (function-taking-bytes)\ndef _chunk(src, dest):\n buf = memoryview(bytearray(_CHUNK_SIZE))\n while True:\n n = src.readinto(buf)\n if n == 0:\n break\n dest(buf if n == _CHUNK_SIZE else buf[:n])\n\n\n# Check if the specified path exists and matches the hash.\ndef _check_exists(path, short_hash):\n import os\n\n try:\n import binascii\n import hashlib\n\n with open(path, "rb") as f:\n hs256 = hashlib.sha256()\n _chunk(f, hs256.update)\n existing_hash = str(binascii.hexlify(hs256.digest())[: len(short_hash)], "utf-8")\n return existing_hash == short_hash\n except:\n return False\n\n\ndef _rewrite_url(url, branch=None):\n if not branch:\n branch = "HEAD"\n if url.startswith("github:"):\n url = url[7:].split("/")\n url = (\n "https://raw.githubusercontent.com/"\n + url[0]\n + "/"\n + url[1]\n + "/"\n + branch\n + "/"\n + "/".join(url[2:])\n )\n return url\n\n\ndef _download_file(url, dest):\n response = get(url)\n try:\n if response.status_code != 200:\n print("Error", response.status_code, "requesting", url)\n return False\n\n print("Copying:", dest)\n _ensure_path_exists(dest)\n with open(dest, "wb") as f:\n _chunk(response.raw, f.write)\n\n return True\n finally:\n response.close()\n\n\ndef _install_json(package_json_url, index, target, version, mpy):\n response = get(_rewrite_url(package_json_url, version))\n try:\n if response.status_code != 200:\n print("Package not found:", package_json_url)\n return False\n\n package_json = response.json()\n finally:\n response.close()\n for target_path, short_hash in package_json.get("hashes", ()):\n fs_target_path = target + "/" + target_path\n if _check_exists(fs_target_path, short_hash):\n print("Exists:", fs_target_path)\n else:\n file_url = "{}/file/{}/{}".format(index, short_hash[:2], short_hash)\n if not _download_file(file_url, fs_target_path):\n print("File not found: {} {}".format(target_path, short_hash))\n return False\n for target_path, url in package_json.get("urls", ()):\n fs_target_path = target + "/" + target_path\n if not _download_file(_rewrite_url(url, version), fs_target_path):\n print("File not found: {} {}".format(target_path, url))\n return False\n for dep, dep_version in package_json.get("deps", ()):\n if not _install_package(dep, index, target, dep_version, mpy):\n return False\n return True\n\n\ndef _install_package(package, index, target, version, mpy):\n if (\n package.startswith("http://")\n or package.startswith("https://")\n or package.startswith("github:")\n ):\n if package.endswith(".py") or package.endswith(".mpy"):\n print("Downloading {} to {}".format(package, target))\n return _download_file(\n _rewrite_url(package, version), target + "/" + package.rsplit("/")[-1]\n )\n else:\n if not package.endswith(".json"):\n if not package.endswith("/"):\n package += "/"\n package += "package.json"\n print("Installing {} to {}".format(package, target))\n else:\n if not version:\n version = "latest"\n print("Installing {} ({}) from {} to {}".format(package, version, index, target))\n\n mpy_version = (\n sys.implementation._mpy & 0xFF if mpy and hasattr(sys.implementation, "_mpy") else "py"\n )\n\n # WARNING: mpy_version fails miserably with 1.22.0-380\n package = "{}/package/{}/{}/{}.json".format(index, "py", package, version)\n\n return _install_json(package, index, target, version, mpy)\n\n\ndef install(package, index=None, target=None, version=None, mpy=True):\n if not target:\n for p in sys.path:\n if p.endswith("/lib"):\n target = p\n break\n else:\n print("Unable to find lib dir in sys.path")\n return\n\n if not index:\n index = _PACKAGE_INDEX\n\n if _install_package(package, index.rstrip("/"), target, version, mpy):\n print("Done")\n else:\n print("Package may be partially installed")\n');const et=async e=>(await import("./toml-DiUM0_qs.js")).parse(e),nt=(e,n)=>{try{e.mkdir(n)}catch(e){}};var tt={type:"micropython",module:(e="1.24.0-preview-47")=>`https://cdn.jsdelivr.net/npm/@micropython/micropython-webassembly-pyscript@${e}/micropython.mjs`,async engine({loadMicroPython:e},n,t,r){const{stderr:s,stdout:o,get:a}=Xe({stderr:Qe(console.error),stdout:Qe(console.log)});t=t.replace(/\.m?js$/,".wasm");const i=await a(e({linebuffer:!1,stderr:s,stdout:o,url:t})),l=rt.bind(this,i,r);return Gn.set(i,l),n.files&&await Hn(this,i,n.files,r),n.fetch&&await Ln(this,i,n.fetch,r),n.js_modules&&await Bn(n.js_modules,r),this.writeFile(i,"./mip.py",Qn),n.packages&&await l(n.packages),i},registerJSModule:Vn,run:Kn,runAsync:Xn,runEvent:Zn,transform:(e,n)=>e.PyProxy.toJs(n),writeFile:(e,n,t,r)=>{const{FS:s,_module:{PATH:o,PATH_FS:a}}=e,i={FS:s,PATH:o,PATH_FS:a},l=Yn(n,r);if(l){const r=n.slice(0,-1);switch("./"!==r&&s.mkdir(r),l){case"whl":case"zip":{const e=new Blob([t],{type:"application/zip"});return import("./zip-BxogYCy6.js").then((async({BlobReader:n,Uint8ArrayWriter:t,ZipReader:a})=>{const i=new a(new n(e));for(const e of await i.getEntries()){const{directory:n,filename:a}=e,i=r+a;if(n)nt(s,i);else{nt(s,o.dirname(i));const n=await e.getData(new t);s.writeFile(i,n,{canOwn:!0})}}i.close()}))}case"tgz":case"tar.gz":{const n="./_.tar.gz";return Jn(i,n,t),void e.runPython(`\n import os, gzip, tarfile\n tar = tarfile.TarFile(fileobj=gzip.GzipFile(fileobj=open("${n}", "rb")))\n for f in tar:\n name = f"${r}{f.name}"\n if f.type == tarfile.DIRTYPE:\n if f.name != "./":\n os.mkdir(name.strip("/"))\n else:\n dir = os.path.dirname(name)\n if not os.path.exists(dir):\n os.mkdir(dir)\n source = tar.extractfile(f)\n with open(name, "wb") as dest:\n dest.write(source.read())\n dest.close()\n tar.close()\n os.remove("${n}")\n `)}}}return Jn(i,n,t)}};async function rt(e,n,t){let r;for(const s of t)if(s.endsWith(".whl")){const t=dn(s,n),r=await a(t).arrayBuffer();await this.writeFile(e,"./*",r,t)}else r||(r=e.pyimport("mip")),r.install(s)}const st={dict_converter:Object.fromEntries};let ot=!1;const at=e=>(...n)=>{try{return ot=!0,e(...n)}finally{ot=!1}};let it=!1;const lt=()=>{if(it)return;it=!0;const e=new WeakMap,n=e=>e.destroy(),t=t=>{for(let r=0;r<t.length;r++){const s=t[r];if("function"==typeof s&&"copy"in s){ot=!1;let o=e.get(s)?.deref();if(!o)try{o=we(s.copy(),n),e.set(s,new WeakRef(o))}catch(e){console.error(e)}o&&(t[r]=o),ot=!0}}},{call:r}=Function,s=r.bind(r,r.apply);Object.defineProperties(Function.prototype,{apply:{value(e,n){return ot&&t(n),s(this,e,n)}},call:{value(e,...n){return ot&&t(n),s(this,e,n)}}})};var pt={type:"pyodide",module:(e="0.26.1")=>`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},n,t,r){xn||"auto"!==n.experimental_create_proxy||lt();const{stderr:s,stdout:o,get:a}=Xe(),i=t.slice(0,t.lastIndexOf("/")),l=await a(e({stderr:s,stdout:o,indexURL:i})),p=ct.bind(l);return Gn.set(l,p),n.files&&await Hn(this,l,n.files,r),n.fetch&&await Ln(this,l,n.fetch,r),n.js_modules&&await Bn(n.js_modules,r),n.packages&&await p(n.packages),l},registerJSModule:Vn,run:at(Kn),runAsync:at(Xn),runEvent:at(Zn),transform:({ffi:{PyProxy:e}},n)=>n instanceof e?n.toJs(st):n,writeFile:(e,n,t,r)=>{const s=Yn(n,r);if(s)return e.unpackArchive(t,s,{extractDir:n.slice(0,-1)});const{FS:o,PATH:a,_module:{PATH_FS:i}}=e;return Jn({FS:o,PATH:a,PATH_FS:i},n,t)}};async function ct(e){await this.loadPackage("micropip");const n=this.pyimport("micropip");await n.install(e,{keep_going:!0}),n.destroy()}const dt="ruby-wasm-wasi",ft=dt.replace(/\W+/g,"_");var mt={type:dt,experimental:!0,module:(e="2.6.1")=>`https://cdn.jsdelivr.net/npm/@ruby/3.2-wasm-wasi@${e}/dist/browser/+esm`,async engine({DefaultRubyVM:e},n,t,r){t=t.replace(/\/browser\/\+esm$/,"/ruby.wasm");const s=await a(t).arrayBuffer(),o=await WebAssembly.compile(s),{vm:i}=await e(o);return n.files&&await Hn(this,i,n.files,r),n.fetch&&await Ln(this,i,n.fetch,r),n.js_modules&&await Bn(n.js_modules,r),i},registerJSModule(e,n,t){n=n.replace(/\W+/g,"__");const r=`__module_${ft}_${n}`;globalThis[r]=t,this.run(e,`require "js";$${n}=JS.global[:${r}]`),delete globalThis[r]},run:(e,n,...t)=>e.eval(en(n),...t),runAsync:(e,n,...t)=>e.evalAsync(en(n),...t),async runEvent(e,n,t){if(/^xworker\.(on\w+)$/.test(n)){const{$1:n}=RegExp,r=`__module_${ft}_event`;globalThis[r]=t,this.run(e,`require "js";$xworker.call("${n}",JS.global[:${r}])`),delete globalThis[r]}else{const r=this.run(e,`method(:${n})`);await r.call(n,e.wrap(t))}},transform:(e,n)=>n,writeFile:()=>{throw new Error(`writeFile is not supported in ${dt}`)}};var ut={type:"wasmoon",module:(e="1.16.0")=>`https://cdn.jsdelivr.net/npm/wasmoon@${e}/+esm`,async engine({LuaFactory:e,LuaLibraries:n},t,r,s){const{stderr:o,stdout:a,get:i}=Xe(),l=await i((new e).createEngine());return l.global.getTable(n.Base,(e=>{l.global.setField(e,"print",a),l.global.setField(e,"printErr",o)})),t.files&&await Hn(this,l,t.files,s),t.fetch&&await Ln(this,l,t.fetch,s),t.js_modules&&await Bn(t.js_modules,s),l},registerJSModule:(e,n,t)=>{e.global.set(n,t)},run:(e,n,...t)=>{try{return e.doStringSync(en(n),...t)}catch(n){Ke.get(e).stderr(n)}},runAsync:async(e,n,...t)=>{try{return await e.doString(en(n),...t)}catch(n){Ke.get(e).stderr(n)}},runEvent:async(e,n,t)=>{const[r,...s]=n.split(".");let o,a=e.global.get(r);for(const e of s)[o,a]=[a,a[e]];try{await a.call(o,t)}catch(n){Ke.get(e).stderr(n)}},transform:(e,n)=>n,writeFile:({cmodule:{module:{FS:e}}},n,t)=>((e,n,t)=>(Rn(e,jn(n)),n=Mn(e,n),e.writeFile(n,new Uint8Array(t),{canOwn:!0})))(e,n,t)};const ht=new WeakMap,yt=async(e,n)=>{const{shelter:t,destroy:r,io:s}=ht.get(e),{output:o,result:a}=await t.captureR(en(n));for(const{type:e,data:n}of o)s[e](n);return we(a,r,{token:!1})};var gt={type:"webr",experimental:!0,module:(e="0.3.3")=>`https://cdn.jsdelivr.net/npm/webr@${e}/dist/webr.mjs`,async engine(e,n,t,r){const{get:s}=Xe(),o=new e.WebR;await s(o.init().then((()=>o)));const a=await new o.Shelter;return ht.set(o,{module:e,shelter:a,destroy:a.destroy.bind(a),io:Ke.get(o)}),n.files&&await Hn(this,o,n.files,r),n.fetch&&await Ln(this,o,n.fetch,r),n.js_modules&&await Bn(n.js_modules,r),o},registerJSModule(e,n){console.warn(`Experimental interpreter: module ${n} is not supported (yet)`)},run:yt,runAsync:yt,async runEvent(e,n,t){await e.evalRVoid(`${n}(event)`,{env:{event:{type:[t.type]}}})},transform:(e,n)=>(console.log("transforming",n),n),writeFile:()=>{}};const _t=new Map,wt=new Map,bt=[],vt=[],St=new Proxy(new Map,{get(e,n){if(!e.has(n)){const[t,...r]=n.split("@"),s=_t.get(t),o=/^(?:\.?\.?\/|https?:\/\/)/i.test(r)?r.join("@"):s.module(...r);e.set(n,{url:o,module:import(o),engine:s.engine.bind(s)})}const{url:t,module:r,engine:s}=e.get(n);return(e,o)=>r.then((r=>(wt.set(n,e),s(r,e,t,o))))}}),Et=e=>{for(const n of[].concat(e.type))_t.set(n,e),bt.push(`script[type="${n}"]`),vt.push(`${n}-`)};for(const e of[tt,pt,mt,ut,gt])Et(e);const{parse:Pt}=JSON,Tt=(e,n="./config.txt")=>{let t=typeof e;return"string"===t&&/\.(json|toml|txt)$/.test(e)?t=RegExp.$1:e=n,[dn(e),t]},kt=e=>{try{return Pt(e)}catch(n){return et(e)}},xt=(e,n,t,r={})=>{if(n){const[e,s]=Tt(n,t);"json"===s?r=a(e).json():"toml"===s?r=a(e).text().then(et):"string"===s?r=kt(n):"object"===s&&n?r=n:"txt"===s&&"string"==typeof r&&(r=kt(r)),n=e}return cn(r).then((t=>St[e](t,n)))},Jt=(e,n="")=>`${e}@${n}`.replace(/@$/,"");function jt(e=this){return String(e).replace(/^(async\s*)?(\bfunction\b)?(.*?)\(/,((e,n,t,r)=>r&&!t?`${n||""}function ${r}(`:e))}const Rt="BeforeRun",Mt="AfterRun",Nt=[`code${Rt}`,`code${Rt}Async`,`code${Mt}`,`code${Mt}Async`],At=["onWorker","onReady",`on${Rt}`,`on${Rt}Async`,`on${Mt}`,`on${Mt}Async`];function Lt(e,n){const{run:t,runAsync:r}=_t.get(this.type);return{...e,run:t.bind(this,n),runAsync:r.bind(this,n)}}const Wt=(e,n,t,r,s,o)=>{if(s||o){const a=Lt.bind(e,n),i=r?"runAsync":"run",l=e[i];e[i]=r?async function(e,n,...r){s&&await s.call(this,a(e),t);const i=await l.call(this,e,n,...r);return o&&await o.call(this,a(e),t),i}:function(e,n,...r){s&&s.call(this,a(e),t);const i=l.call(this,e,n,...r);return o&&o.call(this,a(e),t),i}}};let Ot=class{constructor(e,n={}){const{main:t,worker:r}=n;this.interpreter=e,this.onWorker=t?.onWorker;for(const e of At.slice(1))this[e]=r?.[e];for(const e of Nt)this[e]=r?.[e]}toJSON(){const e={};for(const n of At.slice(1))this[n]&&(e[n]=jt(this[n]));for(const n of Nt)this[n]&&(e[n]=en(this[n]()));return e}};var Ht=(...e)=>function(n,t){const r=new Worker(URL.createObjectURL(new Blob(['const e="object"==typeof self?self:globalThis,t=t=>((t,n)=>{const r=(e,n)=>(t.set(n,e),e),s=o=>{if(t.has(o))return t.get(o);const[a,i]=n[o];switch(a){case 0:case-1:return r(i,o);case 1:{const e=r([],o);for(const t of i)e.push(s(t));return e}case 2:{const e=r({},o);for(const[t,n]of i)e[s(t)]=s(n);return e}case 3:return r(new Date(i),o);case 4:{const{source:e,flags:t}=i;return r(new RegExp(e,t),o)}case 5:{const e=r(new Map,o);for(const[t,n]of i)e.set(s(t),s(n));return e}case 6:{const e=r(new Set,o);for(const t of i)e.add(s(t));return e}case 7:{const{name:t,message:n}=i;return r(new e[t](n),o)}case 8:return r(BigInt(i),o);case"BigInt":return r(Object(BigInt(i)),o)}return r(new e[a](i),o)};return s})(new Map,t)(0),n="",{toString:r}={},{keys:s}=Object,o=e=>{const t=typeof e;if("object"!==t||!e)return[0,t];const s=r.call(e).slice(8,-1);switch(s){case"Array":return[1,n];case"Object":return[2,n];case"Date":return[3,n];case"RegExp":return[4,n];case"Map":return[5,n];case"Set":return[6,n]}return s.includes("Array")?[1,s]:s.includes("Error")?[7,s]:[2,s]},a=([e,t])=>0===e&&("function"===t||"symbol"===t),i=(e,{json:t,lossy:n}={})=>{const r=[];return((e,t,n,r)=>{const i=(e,t)=>{const s=r.push(e)-1;return n.set(t,s),s},c=r=>{if(n.has(r))return n.get(r);let[l,p]=o(r);switch(l){case 0:{let t=r;switch(p){case"bigint":l=8,t=r.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);t=null;break;case"undefined":return i([-1],r)}return i([l,t],r)}case 1:{if(p)return i([p,[...r]],r);const e=[],t=i([l,e],r);for(const t of r)e.push(c(t));return t}case 2:{if(p)switch(p){case"BigInt":return i([p,r.toString()],r);case"Boolean":case"Number":case"String":return i([p,r.valueOf()],r)}if(t&&"toJSON"in r)return c(r.toJSON());const n=[],u=i([l,n],r);for(const t of s(r))!e&&a(o(r[t]))||n.push([c(t),c(r[t])]);return u}case 3:return i([l,r.toISOString()],r);case 4:{const{source:e,flags:t}=r;return i([l,{source:e,flags:t}],r)}case 5:{const t=[],n=i([l,t],r);for(const[n,s]of r)(e||!a(o(n))&&!a(o(s)))&&t.push([c(n),c(s)]);return n}case 6:{const t=[],n=i([l,t],r);for(const n of r)!e&&a(o(n))||t.push(c(n));return n}}const{message:u}=r;return i([l,{name:p,message:u}],r)};return c})(!(t||n),!!t,new Map,r)(e),r},{parse:c,stringify:l}=JSON,p={json:!0,lossy:!0};var u=Object.freeze({__proto__:null,parse:e=>t(c(e)),stringify:e=>l(i(e,p))});const f="64e10b34-2bf7-4616-9668-f99de5aa046e",h="M"+f,d="T"+f,g="array",y="function",w="null",m="number",_="object",b="string",E="symbol",v="undefined",k="apply",x="construct",T="defineProperty",S="deleteProperty",A="get",j="getOwnPropertyDescriptor",O="getPrototypeOf",$="has",R="isExtensible",P="ownKeys",N="preventExtensions",M="set",I="setPrototypeOf",F="delete",{isArray:W}=Array;let{SharedArrayBuffer:H,window:D}=globalThis,{notify:C,wait:L,waitAsync:B}=Atomics,U=null;B||(B=e=>({value:new Promise((t=>{let n=new Worker("data:application/javascript,onmessage%3D(%7Bdata%3Ab%7D)%3D%3E(Atomics.wait(b%2C0)%2CpostMessage(0))");n.onmessage=t,n.postMessage(e)}))}));try{new H(4)}catch(e){H=ArrayBuffer;const t=new WeakMap;if(D){const e=new Map,{prototype:{postMessage:n}}=Worker,r=t=>{const n=t.data?.[f];if(!W(n)){t.stopImmediatePropagation();const{id:r,sb:s}=n;e.get(r)(s)}};U=function(e,...s){const o=e?.[f];if(W(o)){const[e,n]=o;t.set(n,e),this.addEventListener("message",r)}return n.call(this,e,...s)},B=n=>({value:new Promise((r=>{e.set(t.get(n),r)})).then((r=>{e.delete(t.get(n)),t.delete(n);for(let e=0;e<r.length;e++)n[e]=r[e];return"ok"}))})}else{const e=(e,t)=>({[f]:{id:e,sb:t}});C=n=>{postMessage(e(t.get(n),n))},addEventListener("message",(e=>{const n=e.data?.[f];if(W(n)){const[e,r]=n;t.set(r,e)}}))}}\n/*! (c) Andrea Giammarchi - ISC */const{Int32Array:q,Map:J,Uint16Array:z}=globalThis,{BYTES_PER_ELEMENT:G}=q,{BYTES_PER_ELEMENT:K}=z,Y=new WeakSet,X=new WeakMap,V={value:{then:e=>e()}};let Z=0;const Q=(e,{parse:t=JSON.parse,stringify:n=JSON.stringify,transform:r,interrupt:s}=JSON)=>{if(!X.has(e)){const o=U||e.postMessage,a=(t,...n)=>o.call(e,{[f]:n},{transfer:t}),i=typeof s===y?s:s?.handler,c=s?.delay||42,l=new TextDecoder("utf-16"),p=(e,t)=>e?B(t,0):(i?((e,t,n)=>{for(;"timed-out"===L(e,0,0,t);)n()})(t,c,i):L(t,0),V);let u=!1;X.set(e,new Proxy(new J,{[$]:(e,t)=>"string"==typeof t&&!t.startsWith("_"),[A]:(n,s)=>"then"===s?null:(...n)=>{const o=Z++;let i=new q(new H(2*G)),c=[];Y.has(n.at(-1)||c)&&Y.delete(c=n.pop()),a(c,o,i,s,r?n.map(r):n);const f=e!==globalThis;let h=0;return u&&f&&(h=setTimeout(console.warn,1e3,`💀🔒 - Possible deadlock if proxy.${s}(...args) is awaited`)),p(f,i).value.then((()=>{clearTimeout(h);const e=i[1];if(!e)return;const n=K*e;return i=new q(new H(n+n%G)),a([],o,i),p(f,i).value.then((()=>t(l.decode(new z(i.buffer).slice(0,e)))))}))},[M](t,s,o){const a=typeof o;if(a!==y)throw new Error(`Unable to assign ${s} as ${a}`);if(!t.size){const s=new J;e.addEventListener("message",(async e=>{const o=e.data?.[f];if(W(o)){e.stopImmediatePropagation();const[a,i,...c]=o;let l;if(c.length){const[e,o]=c;if(t.has(e)){u=!0;try{const c=await t.get(e)(...o);if(void 0!==c){const e=n(r?r(c):c);s.set(a,e),i[1]=e.length}}catch(e){l=e}finally{u=!1}}else l=new Error(`Unsupported action: ${e}`);i[0]=1}else{const e=s.get(a);s.delete(a);for(let t=new z(i.buffer),n=0;n<e.length;n++)t[n]=e.charCodeAt(n)}if(C(i,0),l)throw l}}))}return!!t.set(s,o)}}))}return X.get(e)};Q.transfer=(...e)=>(Y.add(e),e);const{isArray:ee}=Array,te=(e,t)=>t,ne=e=>typeof e===y?(e=>e())(e):e;function re(){return this}const se=(e,t)=>e===g?[t]:{t:e,v:t},oe=(e,t=te)=>{let n=typeof e,r=e;return n===_&&(ee(e)?(n=g,r=e.at(0)):({t:n,v:r}=e)),t(n,r)},ae=(e,t)=>e===y?t:se(e,t),ie=(e,t=ae)=>{const n=null===e?w:typeof e;return t(n===_&&ee(e)?g:n,e)},ce=new FinalizationRegistry((([e,t,n])=>{n&&console.debug(`Held value ${String(t)} not relevant anymore`),e(t)})),le=Object.create(null),pe=(e,t,{debug:n,handler:r,return:s,token:o=e}=le)=>{const a=s||new Proxy(e,r||le),i=[a,[t,e,!!n]];return!1!==o&&i.push(o),ce.register(...i),a},{defineProperty:ue,deleteProperty:fe,getOwnPropertyDescriptor:he,getPrototypeOf:de,isExtensible:ge,ownKeys:ye,preventExtensions:we,set:me,setPrototypeOf:_e}=Reflect,{assign:be,create:Ee}=Object,ve=de(Int8Array),ke=(e,t)=>{const{get:n,set:r,value:s}=e;return n&&(e.get=t(n)),r&&(e.set=t(r)),s&&(e.value=t(s)),e},xe=e=>t=>ie(t,((t,n)=>{switch(t){case w:return se(w,n);case _:if(n===globalThis)return se(t,null);case g:case y:return e(t,n);case"boolean":case m:case b:case v:case"bigint":return se(t,n);case E:{if(Te.has(n))return se(t,Te.get(n));let e=Symbol.keyFor(n);if(e)return se(t,`.${e}`)}}throw new TypeError(`Unable to handle this ${t}: ${String(n)}`)})),Te=new Map(ye(Symbol).filter((e=>typeof Symbol[e]===E)).map((e=>[Symbol[e],e]))),Se=e=>{if(e.startsWith("."))return Symbol.for(e.slice(1));for(const[t,n]of Te)if(n===e)return t},Ae=e=>e;var je=((e,t)=>{const n=new WeakMap;{const{addEventListener:e}=EventTarget.prototype;ue(EventTarget.prototype,"addEventListener",{value(t,r,...s){return s.at(0)?.invoke&&(n.has(this)||n.set(this,new Map),n.get(this).set(t,[].concat(s[0].invoke)),delete s[0].invoke),e.call(this,t,r,...s)}})}return function(t,r,s,...o){let a=0,i=this?.transform||Ae;const c=new Map,l=new Map,{[s]:p}=t,u=o.length?be(Ee(globalThis),...o):globalThis,f=xe(((e,t)=>{if(!c.has(t)){let n;for(;l.has(n=a++););c.set(t,n),l.set(n,e===y?t:i(t))}return se(e,c.get(t))})),h=e=>{p(F,se(b,e))},d=(e,t)=>{switch(e){case _:if(null==t)return u;case g:if(typeof t===m)return l.get(t);if(!(t instanceof ve))for(const e in t)t[e]=w(t[e]);return t;case y:if(typeof t===b){const e=l.get(t)?.deref();if(e)return e;const r=function(...e){return e.at(0)instanceof Event&&(e=>{const{currentTarget:t,target:r,type:s}=e;for(const o of n.get(t||r)?.get(s)||[])e[o]()})(...e),p(k,se(y,t),f(this),e.map(f))};return l.set(t,new WeakRef(r)),pe(t,h,{return:r,token:!1})}return l.get(t);case E:return Se(t)}return t},w=e=>oe(e,d),W={[k]:(e,t,n)=>f(e.apply(t,n)),[x]:(e,t)=>f(new e(...t)),[T]:(e,t,n)=>f(ue(e,t,n)),[S]:(e,t)=>f(fe(e,t)),[O]:e=>f(de(e)),[A]:(e,t)=>f(e[t]),[j]:(e,t)=>{const n=he(e,t);return n?se(_,ke(n,f)):se(v,n)},[$]:(e,t)=>f(t in e),[R]:e=>f(ge(e)),[P]:e=>se(g,ye(e).map(f)),[N]:e=>f(we(e)),[M]:(e,t,n)=>f(me(e,t,n)),[I]:(e,t)=>f(_e(e,t)),[F](e){c.delete(l.get(e)),l.delete(e)}};return t[r]=(e,t,...n)=>{switch(e){case k:n[0]=w(n[0]),n[1]=n[1].map(w);break;case x:n[0]=n[0].map(w);break;case T:{const[e,t]=n;n[0]=w(e);const{get:r,set:s,value:o}=t;r&&(t.get=w(r)),s&&(t.set=w(s)),o&&(t.value=w(o));break}default:n=n.map(w)}return W[e](w(t),...n)},{proxy:t,[e.toLowerCase()]:u,[`is${e}Proxy`]:()=>!1}}})("Window"),Oe=(e=>{let t=0;const n=new Map,r=new Map,s=Symbol();return function(o,a,i){const c=this?.transform||Ae,{[a]:l}=o,p=new Map,u=e=>{p.delete(e),l(F,f(e))},f=xe(((e,o)=>{if(s in o)return ne(o[s]);if(e===y){if(o=c(o),!r.has(o)){let e;for(;r.has(e=String(t++)););n.set(o,e),r.set(e,o)}return se(e,n.get(o))}if(!(o instanceof ve)){o=c(o);for(const e in o)o[e]=f(o[e])}return se(e,o)})),h=(e,t,n)=>{const r=p.get(n)?.deref();if(r)return r;const s=t===y?(e=>re.bind(e))(e):e,o=new Proxy(s,v);return p.set(n,new WeakRef(o)),pe(n,u,{return:o,token:!1})},d=e=>oe(e,((t,n)=>{switch(t){case _:if(null===n)return globalThis;case g:return typeof n===m?h(e,t,n):n;case y:return typeof n===b?r.get(n):h(e,t,n);case E:return Se(n)}return n})),w=(e,t,...n)=>d(l(e,ne(t),...n)),v={[k]:(e,t,n)=>w(k,e,f(t),n.map(f)),[x]:(e,t)=>w(x,e,t.map(f)),[T]:(e,t,n)=>{const{get:r,set:s,value:o}=n;return typeof r===y&&(n.get=f(r)),typeof s===y&&(n.set=f(s)),typeof o===y&&(n.value=f(o)),w(T,e,f(t),n)},[S]:(e,t)=>w(S,e,f(t)),[O]:e=>w(O,e),[A]:(e,t)=>t===s?e:w(A,e,f(t)),[j]:(e,t)=>{const n=w(j,e,f(t));return n&&ke(n,d)},[$]:(e,t)=>t===s||w($,e,f(t)),[R]:e=>w(R,e),[P]:e=>w(P,e).map(d),[N]:e=>w(N,e),[M]:(e,t,n)=>w(M,e,f(t),f(n)),[I]:(e,t)=>w(I,e,f(t))};o[i]=(e,t,s,o)=>{switch(e){case k:return d(t).apply(d(s),o.map(d));case F:{const e=d(t);n.delete(r.get(e)),r.delete(e)}}};const W=new Proxy(se(_,null),v);return{[e.toLowerCase()]:W,[`is${e}Proxy`]:e=>typeof e===_&&!!e&&s in e,proxy:o}}})("Window"),$e=typeof Worker===y?Worker:class{};const Re=new WeakMap,Pe=(e,...t)=>{const n=Q(e,...t);if(!Re.has(n)){const r=e instanceof $e?je:Oe;Re.set(n,r.call(t.at(0),n,h,d))}return Re.get(n)};Pe.transfer=Q.transfer;const Ne={object(...e){return this.string(function(e){for(var t=e[0],n=1,r=arguments.length;n<r;n++)t+=arguments[n]+e[n];return t}(...e))},string(e){for(const t of e.split(/[\\r\\n]+/))if(t.trim().length){/^(\\s+)/.test(t)&&(e=e.replace(new RegExp("^"+RegExp.$1,"gm"),""));break}return e}},Me=new WeakMap,Ie=e=>{const t=e||console,n={buffered:We,stderr:(t.stderr||console.error).bind(t),stdout:(t.stdout||console.log).bind(t)};return{stderr:(...e)=>n.stderr(...e),stdout:(...e)=>n.stdout(...e),async get(e){const t=await e;return Me.set(t,n),t}}},Fe=new TextDecoder,We=(e,t=10)=>{const n=[];return r=>{if(r instanceof Uint8Array)for(const s of r)s===t?e(Fe.decode(new Uint8Array(n.splice(0)))):n.push(s);else e(r)}},He=(e,...t)=>Ne[typeof e](e,...t),{isArray:De}=Array,{assign:Ce,create:Le,defineProperties:Be,defineProperty:Ue,entries:qe}=Object,{all:Je,resolve:ze}=new Proxy(Promise,{get:(e,t)=>e[t].bind(e)}),Ge=(e,t=location.href)=>new URL(e,t.replace(/^blob:/,"")).href,Ke=(e,t,n,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${t}:${n}`,{bubbles:!0,detail:{worker:r}}))},Ye=e=>Function(`\'use strict\';return (${e})`)(),Xe=e=>e.replace(/^(?:\\n|\\r\\n)/,""),Ve=Symbol.for("polyscript.js_modules"),Ze=new Map;Ue(globalThis,Ve,{value:Ze}),new Proxy(Ze,{get:(e,t)=>e.get(t),has:(e,t)=>e.has(t),ownKeys:e=>[...e.keys()]});const Qe=(e,t)=>!t.startsWith("_"),et=(e,t)=>new Proxy(e,{has:Qe,get:(e,n)=>e[t][n]}),tt=(e,t)=>import(e).then((e=>{Ze.set(t,{...e})})),nt=e=>new Promise(((t,n)=>{document.querySelector(`link[href="${e}"]`)&&t(),document.head.append(Ce(document.createElement("link"),{rel:"stylesheet",href:e,onload:t,onerror:n}))})),rt=e=>/\\.css/i.test(new URL(e).pathname),st=(e,t)=>e.has(t),ot=e=>[...e.keys()];var at=(e,t,n,r)=>{const s=globalThis[Ve];if(n)for(let[e,t]of qe(n)){let n=s.get(t);n&&!De(n)||(s.set(t,n||(n=[])),n.push(e))}return((e,t,n,r)=>new Proxy(e,{has:st,ownKeys:ot,get:(e,s)=>{let o=e.get(s);if(De(o)){let a=o;o=null;for(let e of a)e=Ge(e,r),rt(e)?n.importCSS(e):(n.importJS(e,s),o=t[Ve].get(s));e.set(s,o)}return o}}))(s,e,t,r)};const it=Object.getOwnPropertyDescriptors(Response.prototype),ct=e=>"function"==typeof e,lt={get:(e,t)=>it.hasOwnProperty(t)?((e,t,{get:n,value:r})=>n||!ct(r)?e.then((e=>e[t])):(...n)=>e.then((e=>e[t](...n))))(e,t,it[t]):((e,t)=>ct(t)?t.bind(e):t)(e,e[t])};var pt=(e,...t)=>new Proxy(fetch(e,...t),lt);Promise.withResolvers||(Promise.withResolvers=function(){var e,t,n=new this((function(n,r){e=n,t=r}));return{resolve:e,reject:t,promise:n}});const ut=!globalThis.window,ft=({FS:e,PATH:t,PATH_FS:n},r,s)=>{const o=n.resolve(r),a=t.dirname(o);return e.mkdirTree?e.mkdirTree(a):dt(e,a),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},ht=e=>{const t=e.split("/");return t.pop(),t.join("/")},dt=(e,t)=>{const n=[];for(const r of t.split("/"))"."!==r&&".."!==r&&(n.push(r),r&&e.mkdir(n.join("/")))},gt=(e,t)=>{const n=[];for(const e of t.split("/"))switch(e){case"":case".":break;case"..":n.pop();break;default:n.push(e)}return[e.cwd()].concat(n).join("/").replace(/^\\/+/,"/")},yt=e=>{const t=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,""))).filter((e=>""!==e&&"."!==e)).join("/");return e[0].startsWith("/")?`/${t}`:t},wt=(e,t)=>pt(Ge(e,t)).arrayBuffer(),mt=(e,t,n,r)=>Je((e=>{for(const{files:t,to_file:n,from:r=""}of e){if(void 0!==t&&void 0!==n)throw new Error("Cannot use \'to_file\' and \'files\' parameters together!");if(void 0===t&&void 0===n&&r.endsWith("/"))throw new Error(`Couldn\'t determine the filename from the path ${r}, please supply \'to_file\' parameter.`)}return e.flatMap((({from:e="",to_folder:t=".",to_file:n,files:r})=>{if(De(r))return r.map((n=>({url:yt([e,n]),path:yt([t,n])})));const s=n||e.slice(1+e.lastIndexOf("/"));return[{url:e,path:yt([t,s])}]}))})(n).map((({url:n,path:s})=>wt(n,r).then((n=>e.writeFile(t,s,n)))))),_t=(e,t)=>t.endsWith("/")?`${t}${e.split("/").pop()}`:t,bt=(e,t)=>e.replace(/\\{.+?\\}/g,(e=>{if(!t.has(e))throw new SyntaxError(`Invalid template: ${e}`);return t.get(e)})),Et=(e,t,n,r)=>Je((e=>{const t=new Map,n=new Set,r=[];for(const[s,o]of qe(e))if(/^\\{.+\\}$/.test(s)){if(t.has(s))throw new SyntaxError(`Duplicated template: ${s}`);t.set(s,bt(o,t))}else{const e=bt(s,t),a=_t(e,bt(o||"./",t));if(n.has(a))throw new SyntaxError(`Duplicated destination: ${a}`);n.add(a),r.push({url:e,path:a})}return r})(n).map((({url:n,path:s})=>wt(n,r).then((r=>e.writeFile(t,s,r,n)))))),vt=({main:e,worker:t},n)=>{const r=[];if(t&&ut)for(let[e,s]of qe(t))e=Ge(e,n),r.push(tt(e,s));if(e&&!ut)for(let[t,s]of qe(e))t=Ge(t,n),rt(t)?nt(t):r.push(tt(t,s));return Je(r)},{assign:kt}=Object,xt="entries",Tt="readonly",St="readwrite",At={durability:"default",prefix:"IDBMap"},jt=({target:{result:e}})=>e;class Ot extends EventTarget{#e;#t;#n;async#r(e,t){const n=(await this.#e).transaction(xt,t,this.#t);return new Promise(((t,r)=>kt(e(n.objectStore(xt)),{onsuccess:t,onerror:r})))}constructor(e,{durability:t=At.durability,prefix:n=At.prefix}=At){super(),this.#n=n,this.#t={durability:t},this.#e=new Promise(((t,n)=>{kt(indexedDB.open(`${this.#n}/${e}`),{onupgradeneeded({target:{result:e,transaction:n}}){e.objectStoreNames.length||e.createObjectStore(xt),n.oncomplete=()=>t(e)},onsuccess(e){t(jt(e))},onerror(e){n(e),this.dispatchEvent(e)}})})).then((e=>{const t=this.dispatchEvent.bind(this);for(const n in e)n.startsWith("on")&&(e[n]=t);return e}))}dispatchEvent(e){const{type:t,message:n,isTrusted:r}=e;return super.dispatchEvent(r?kt(new Event(t),{message:n}):e)}async close(){(await this.#e).close()}get size(){return this.#r((e=>e.count()),Tt).then(jt)}async clear(){await this.#r((e=>e.clear()),St)}async delete(e){await this.#r((t=>t.delete(e)),St)}async entries(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e).then((t=>[e,t])))))}async forEach(e,t=this){for(const[n,r]of await this.entries())await e.call(t,r,n,this)}async get(e){return await this.#r((t=>t.get(e)),Tt).then(jt)}async has(e){return void 0!==await this.#r((t=>t.getKey(e)),Tt).then(jt)}async keys(){return await this.#r((e=>e.getAllKeys()),Tt).then(jt)}async set(e,t){return await this.#r((n=>n.put(t,e)),St),this}async values(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e))))}get[Symbol.toStringTag](){return this.#n}}class $t extends Map{#s;#o;constructor(...e){super(),this.#s=new Ot(...e),this.#o=this.#s.entries().then((e=>{for(const[t,n]of e)super.set(t,n)}))}async sync(){await this.#o}clear(){return this.#o=this.#o.then((()=>this.#s.clear())),super.clear()}delete(e){return this.#o=this.#o.then((()=>this.#s.delete(e))),super.delete(e)}set(e,t){return this.#o=this.#o.then((()=>this.#s.set(e,t))),super.set(e,t)}}const Rt=new WeakMap,Pt=(e,t,n)=>{"polyscript"===t&&(n.lazy_py_modules=async(...t)=>(await Rt.get(e)(t),t.map((t=>e.pyimport(t)))),n.storage=async e=>{const t=new $t(e);return await t.sync(),t},n.JSON=u),e.registerJsModule(t,n)},Nt=(e,t)=>{if(e.endsWith("/*")){if(/\\.(zip|whl|tgz|tar(?:\\.gz)?)$/.test(t))return RegExp.$1;throw new Error(`Unsupported archive ${t}`)}return""},Mt=(e,t,...n)=>{try{return e.runPython(He(t),...n)}catch(t){Me.get(e).stderr(t)}},It=async(e,t,...n)=>{try{return await e.runPythonAsync(He(t),...n)}catch(t){Me.get(e).stderr(t)}},Ft=async(e,t,n)=>{const[r,...s]=t.split(".");let o,a=e.globals.get(r);for(const e of s)[o,a]=[a,a[e]];try{await a.call(o,n)}catch(t){Me.get(e).stderr(t)}};var Wt=(new TextEncoder).encode(\'from uio import StringIO\\nimport sys\\n\\nclass Response:\\n def __init__(self, f):\\n self.raw = f\\n self.encoding = "utf-8"\\n self._cached = None\\n\\n def close(self):\\n if self.raw:\\n self.raw.close()\\n self.raw = None\\n self._cached = None\\n\\n @property\\n def content(self):\\n if self._cached is None:\\n try:\\n self._cached = self.raw.read()\\n finally:\\n self.raw.close()\\n self.raw = None\\n return self._cached\\n\\n @property\\n def text(self):\\n return str(self.content, self.encoding)\\n\\n def json(self):\\n import ujson\\n\\n return ujson.loads(self.content)\\n\\n\\n# TODO try to support streaming xhr requests, a-la pyodide-http\\nHEADERS_TO_IGNORE = ("user-agent",)\\n\\n\\ntry:\\n import js\\nexcept Exception as err:\\n raise OSError("This version of urequests can only be used in the browser")\\n\\n# TODO try to support streaming xhr requests, a-la pyodide-http\\n\\nHEADERS_TO_IGNORE = ("user-agent",)\\n\\n\\ndef request(\\n method,\\n url,\\n data=None,\\n json=None,\\n headers={},\\n stream=None,\\n auth=None,\\n timeout=None,\\n parse_headers=True,\\n):\\n from js import XMLHttpRequest\\n\\n xhr = XMLHttpRequest.new()\\n xhr.withCredentials = False\\n\\n if auth is not None:\\n import ubinascii\\n\\n username, password = auth\\n xhr.open(method, url, False, username, password)\\n else:\\n xhr.open(method, url, False)\\n\\n for name, value in headers.items():\\n if name.lower() not in HEADERS_TO_IGNORE:\\n xhr.setRequestHeader(name, value)\\n\\n if timeout:\\n xhr.timeout = int(timeout * 1000)\\n\\n if json is not None:\\n assert data is None\\n import ujson\\n\\n data = ujson.dumps(json)\\n # s.write(b"Content-Type: application/json\\\\r\\\\n")\\n xhr.setRequestHeader("Content-Type", "application/json")\\n\\n xhr.send(data)\\n\\n # Emulates the construction process in the original urequests\\n resp = Response(StringIO(xhr.responseText))\\n resp.status_code = xhr.status\\n resp.reason = xhr.statusText\\n resp.headers = xhr.getAllResponseHeaders()\\n\\n return resp\\n\\n\\n# Other methods - head, post, put, patch, delete - are not used by\\n# mip and therefore not included\\n\\n\\ndef get(url, **kw):\\n return request("GET", url, **kw)\\n\\n\\n# Content below this line is from the Micropython MIP package and is covered\\n# by the applicable MIT license:\\n# \\n# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \\n# DEALINGS IN THE SOFTWARE.\\n\\n# MicroPython package installer\\n# MIT license; Copyright (c) 2022 Jim Mussared\\n\\n\\n_PACKAGE_INDEX = const("https://micropython.org/pi/v2")\\n_CHUNK_SIZE = 128\\n\\n\\n# This implements os.makedirs(os.dirname(path))\\ndef _ensure_path_exists(path):\\n import os\\n\\n split = path.split("/")\\n\\n # Handle paths starting with "/".\\n if not split[0]:\\n split.pop(0)\\n split[0] = "/" + split[0]\\n\\n prefix = ""\\n for i in range(len(split) - 1):\\n prefix += split[i]\\n try:\\n os.stat(prefix)\\n except:\\n os.mkdir(prefix)\\n prefix += "/"\\n\\n\\n# Copy from src (stream) to dest (function-taking-bytes)\\ndef _chunk(src, dest):\\n buf = memoryview(bytearray(_CHUNK_SIZE))\\n while True:\\n n = src.readinto(buf)\\n if n == 0:\\n break\\n dest(buf if n == _CHUNK_SIZE else buf[:n])\\n\\n\\n# Check if the specified path exists and matches the hash.\\ndef _check_exists(path, short_hash):\\n import os\\n\\n try:\\n import binascii\\n import hashlib\\n\\n with open(path, "rb") as f:\\n hs256 = hashlib.sha256()\\n _chunk(f, hs256.update)\\n existing_hash = str(binascii.hexlify(hs256.digest())[: len(short_hash)], "utf-8")\\n return existing_hash == short_hash\\n except:\\n return False\\n\\n\\ndef _rewrite_url(url, branch=None):\\n if not branch:\\n branch = "HEAD"\\n if url.startswith("github:"):\\n url = url[7:].split("/")\\n url = (\\n "https://raw.githubusercontent.com/"\\n + url[0]\\n + "/"\\n + url[1]\\n + "/"\\n + branch\\n + "/"\\n + "/".join(url[2:])\\n )\\n return url\\n\\n\\ndef _download_file(url, dest):\\n response = get(url)\\n try:\\n if response.status_code != 200:\\n print("Error", response.status_code, "requesting", url)\\n return False\\n\\n print("Copying:", dest)\\n _ensure_path_exists(dest)\\n with open(dest, "wb") as f:\\n _chunk(response.raw, f.write)\\n\\n return True\\n finally:\\n response.close()\\n\\n\\ndef _install_json(package_json_url, index, target, version, mpy):\\n response = get(_rewrite_url(package_json_url, version))\\n try:\\n if response.status_code != 200:\\n print("Package not found:", package_json_url)\\n return False\\n\\n package_json = response.json()\\n finally:\\n response.close()\\n for target_path, short_hash in package_json.get("hashes", ()):\\n fs_target_path = target + "/" + target_path\\n if _check_exists(fs_target_path, short_hash):\\n print("Exists:", fs_target_path)\\n else:\\n file_url = "{}/file/{}/{}".format(index, short_hash[:2], short_hash)\\n if not _download_file(file_url, fs_target_path):\\n print("File not found: {} {}".format(target_path, short_hash))\\n return False\\n for target_path, url in package_json.get("urls", ()):\\n fs_target_path = target + "/" + target_path\\n if not _download_file(_rewrite_url(url, version), fs_target_path):\\n print("File not found: {} {}".format(target_path, url))\\n return False\\n for dep, dep_version in package_json.get("deps", ()):\\n if not _install_package(dep, index, target, dep_version, mpy):\\n return False\\n return True\\n\\n\\ndef _install_package(package, index, target, version, mpy):\\n if (\\n package.startswith("http://")\\n or package.startswith("https://")\\n or package.startswith("github:")\\n ):\\n if package.endswith(".py") or package.endswith(".mpy"):\\n print("Downloading {} to {}".format(package, target))\\n return _download_file(\\n _rewrite_url(package, version), target + "/" + package.rsplit("/")[-1]\\n )\\n else:\\n if not package.endswith(".json"):\\n if not package.endswith("/"):\\n package += "/"\\n package += "package.json"\\n print("Installing {} to {}".format(package, target))\\n else:\\n if not version:\\n version = "latest"\\n print("Installing {} ({}) from {} to {}".format(package, version, index, target))\\n\\n mpy_version = (\\n sys.implementation._mpy & 0xFF if mpy and hasattr(sys.implementation, "_mpy") else "py"\\n )\\n\\n # WARNING: mpy_version fails miserably with 1.22.0-380\\n package = "{}/package/{}/{}/{}.json".format(index, "py", package, version)\\n\\n return _install_json(package, index, target, version, mpy)\\n\\n\\ndef install(package, index=None, target=None, version=None, mpy=True):\\n if not target:\\n for p in sys.path:\\n if p.endswith("/lib"):\\n target = p\\n break\\n else:\\n print("Unable to find lib dir in sys.path")\\n return\\n\\n if not index:\\n index = _PACKAGE_INDEX\\n\\n if _install_package(package, index.rstrip("/"), target, version, mpy):\\n print("Done")\\n else:\\n print("Package may be partially installed")\\n\');const Ht=async e=>(await import("./toml-DiUM0_qs.js")).parse(e),Dt=(e,t)=>{try{e.mkdir(t)}catch(e){}};var Ct={type:"micropython",module:(e="1.24.0-preview-47")=>`https://cdn.jsdelivr.net/npm/@micropython/micropython-webassembly-pyscript@${e}/micropython.mjs`,async engine({loadMicroPython:e},t,n,r){const{stderr:s,stdout:o,get:a}=Ie({stderr:We(console.error),stdout:We(console.log)});n=n.replace(/\\.m?js$/,".wasm");const i=await a(e({linebuffer:!1,stderr:s,stdout:o,url:n})),c=Lt.bind(this,i,r);return Rt.set(i,c),t.files&&await Et(this,i,t.files,r),t.fetch&&await mt(this,i,t.fetch,r),t.js_modules&&await vt(t.js_modules,r),this.writeFile(i,"./mip.py",Wt),t.packages&&await c(t.packages),i},registerJSModule:Pt,run:Mt,runAsync:It,runEvent:Ft,transform:(e,t)=>e.PyProxy.toJs(t),writeFile:(e,t,n,r)=>{const{FS:s,_module:{PATH:o,PATH_FS:a}}=e,i={FS:s,PATH:o,PATH_FS:a},c=Nt(t,r);if(c){const r=t.slice(0,-1);switch("./"!==r&&s.mkdir(r),c){case"whl":case"zip":{const e=new Blob([n],{type:"application/zip"});return import("./zip-BxogYCy6.js").then((async({BlobReader:t,Uint8ArrayWriter:n,ZipReader:a})=>{const i=new a(new t(e));for(const e of await i.getEntries()){const{directory:t,filename:a}=e,i=r+a;if(t)Dt(s,i);else{Dt(s,o.dirname(i));const t=await e.getData(new n);s.writeFile(i,t,{canOwn:!0})}}i.close()}))}case"tgz":case"tar.gz":{const t="./_.tar.gz";return ft(i,t,n),void e.runPython(`\\n import os, gzip, tarfile\\n tar = tarfile.TarFile(fileobj=gzip.GzipFile(fileobj=open("${t}", "rb")))\\n for f in tar:\\n name = f"${r}{f.name}"\\n if f.type == tarfile.DIRTYPE:\\n if f.name != "./":\\n os.mkdir(name.strip("/"))\\n else:\\n dir = os.path.dirname(name)\\n if not os.path.exists(dir):\\n os.mkdir(dir)\\n source = tar.extractfile(f)\\n with open(name, "wb") as dest:\\n dest.write(source.read())\\n dest.close()\\n tar.close()\\n os.remove("${t}")\\n `)}}}return ft(i,t,n)}};async function Lt(e,t,n){let r;for(const s of n)if(s.endsWith(".whl")){const n=Ge(s,t),r=await pt(n).arrayBuffer();await this.writeFile(e,"./*",r,n)}else r||(r=e.pyimport("mip")),r.install(s)}const Bt={dict_converter:Object.fromEntries};let Ut=!1;const qt=e=>(...t)=>{try{return Ut=!0,e(...t)}finally{Ut=!1}};let Jt=!1;const zt=()=>{if(Jt)return;Jt=!0;const e=new WeakMap,t=e=>e.destroy(),n=n=>{for(let r=0;r<n.length;r++){const s=n[r];if("function"==typeof s&&"copy"in s){Ut=!1;let o=e.get(s)?.deref();if(!o)try{o=pe(s.copy(),t),e.set(s,new WeakRef(o))}catch(e){console.error(e)}o&&(n[r]=o),Ut=!0}}},{call:r}=Function,s=r.bind(r,r.apply);Object.defineProperties(Function.prototype,{apply:{value(e,t){return Ut&&n(t),s(this,e,t)}},call:{value(e,...t){return Ut&&n(t),s(this,e,t)}}})};var Gt={type:"pyodide",module:(e="0.26.1")=>`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},t,n,r){ut||"auto"!==t.experimental_create_proxy||zt();const{stderr:s,stdout:o,get:a}=Ie(),i=n.slice(0,n.lastIndexOf("/")),c=await a(e({stderr:s,stdout:o,indexURL:i})),l=Kt.bind(c);return Rt.set(c,l),t.files&&await Et(this,c,t.files,r),t.fetch&&await mt(this,c,t.fetch,r),t.js_modules&&await vt(t.js_modules,r),t.packages&&await l(t.packages),c},registerJSModule:Pt,run:qt(Mt),runAsync:qt(It),runEvent:qt(Ft),transform:({ffi:{PyProxy:e}},t)=>t instanceof e?t.toJs(Bt):t,writeFile:(e,t,n,r)=>{const s=Nt(t,r);if(s)return e.unpackArchive(n,s,{extractDir:t.slice(0,-1)});const{FS:o,PATH:a,_module:{PATH_FS:i}}=e;return ft({FS:o,PATH:a,PATH_FS:i},t,n)}};async function Kt(e){await this.loadPackage("micropip");const t=this.pyimport("micropip");await t.install(e,{keep_going:!0}),t.destroy()}const Yt="ruby-wasm-wasi",Xt=Yt.replace(/\\W+/g,"_");var Vt={type:Yt,experimental:!0,module:(e="2.6.1")=>`https://cdn.jsdelivr.net/npm/@ruby/3.2-wasm-wasi@${e}/dist/browser/+esm`,async engine({DefaultRubyVM:e},t,n,r){n=n.replace(/\\/browser\\/\\+esm$/,"/ruby.wasm");const s=await pt(n).arrayBuffer(),o=await WebAssembly.compile(s),{vm:a}=await e(o);return t.files&&await Et(this,a,t.files,r),t.fetch&&await mt(this,a,t.fetch,r),t.js_modules&&await vt(t.js_modules,r),a},registerJSModule(e,t,n){t=t.replace(/\\W+/g,"__");const r=`__module_${Xt}_${t}`;globalThis[r]=n,this.run(e,`require "js";$${t}=JS.global[:${r}]`),delete globalThis[r]},run:(e,t,...n)=>e.eval(He(t),...n),runAsync:(e,t,...n)=>e.evalAsync(He(t),...n),async runEvent(e,t,n){if(/^xworker\\.(on\\w+)$/.test(t)){const{$1:t}=RegExp,r=`__module_${Xt}_event`;globalThis[r]=n,this.run(e,`require "js";$xworker.call("${t}",JS.global[:${r}])`),delete globalThis[r]}else{const r=this.run(e,`method(:${t})`);await r.call(t,e.wrap(n))}},transform:(e,t)=>t,writeFile:()=>{throw new Error(`writeFile is not supported in ${Yt}`)}};var Zt={type:"wasmoon",module:(e="1.16.0")=>`https://cdn.jsdelivr.net/npm/wasmoon@${e}/+esm`,async engine({LuaFactory:e,LuaLibraries:t},n,r,s){const{stderr:o,stdout:a,get:i}=Ie(),c=await i((new e).createEngine());return c.global.getTable(t.Base,(e=>{c.global.setField(e,"print",a),c.global.setField(e,"printErr",o)})),n.files&&await Et(this,c,n.files,s),n.fetch&&await mt(this,c,n.fetch,s),n.js_modules&&await vt(n.js_modules,s),c},registerJSModule:(e,t,n)=>{e.global.set(t,n)},run:(e,t,...n)=>{try{return e.doStringSync(He(t),...n)}catch(t){Me.get(e).stderr(t)}},runAsync:async(e,t,...n)=>{try{return await e.doString(He(t),...n)}catch(t){Me.get(e).stderr(t)}},runEvent:async(e,t,n)=>{const[r,...s]=t.split(".");let o,a=e.global.get(r);for(const e of s)[o,a]=[a,a[e]];try{await a.call(o,n)}catch(t){Me.get(e).stderr(t)}},transform:(e,t)=>t,writeFile:({cmodule:{module:{FS:e}}},t,n)=>((e,t,n)=>(dt(e,ht(t)),t=gt(e,t),e.writeFile(t,new Uint8Array(n),{canOwn:!0})))(e,t,n)};const Qt=new WeakMap,en=async(e,t)=>{const{shelter:n,destroy:r,io:s}=Qt.get(e),{output:o,result:a}=await n.captureR(He(t));for(const{type:e,data:t}of o)s[e](t);return pe(a,r,{token:!1})};var tn={type:"webr",experimental:!0,module:(e="0.3.3")=>`https://cdn.jsdelivr.net/npm/webr@${e}/dist/webr.mjs`,async engine(e,t,n,r){const{get:s}=Ie(),o=new e.WebR;await s(o.init().then((()=>o)));const a=await new o.Shelter;return Qt.set(o,{module:e,shelter:a,destroy:a.destroy.bind(a),io:Me.get(o)}),t.files&&await Et(this,o,t.files,r),t.fetch&&await mt(this,o,t.fetch,r),t.js_modules&&await vt(t.js_modules,r),o},registerJSModule(e,t){console.warn(`Experimental interpreter: module ${t} is not supported (yet)`)},run:en,runAsync:en,async runEvent(e,t,n){await e.evalRVoid(`${t}(event)`,{env:{event:{type:[n.type]}}})},transform:(e,t)=>(console.log("transforming",t),t),writeFile:()=>{}};const nn=new Map,rn=new Map,sn=new Proxy(new Map,{get(e,t){if(!e.has(t)){const[n,...r]=t.split("@"),s=nn.get(n),o=/^(?:\\.?\\.?\\/|https?:\\/\\/)/i.test(r)?r.join("@"):s.module(...r);e.set(t,{url:o,module:import(o),engine:s.engine.bind(s)})}const{url:n,module:r,engine:s}=e.get(t);return(e,o)=>r.then((r=>(rn.set(t,e),s(r,e,n,o))))}}),on=e=>{for(const t of[].concat(e.type))nn.set(t,e)};for(const e of[Ct,Gt,Vt,Zt,tn])on(e);const{parse:an}=JSON,cn=e=>{try{return an(e)}catch(t){return Ht(e)}},ln=(e,t,n,r={})=>{if(t){const[e,s]=((e,t="./config.txt")=>{let n=typeof e;return"string"===n&&/\\.(json|toml|txt)$/.test(e)?n=RegExp.$1:e=t,[Ge(e),n]})(t,n);"json"===s?r=pt(e).json():"toml"===s?r=pt(e).text().then(Ht):"string"===s?r=cn(t):"object"===s&&t?r=t:"txt"===s&&"string"==typeof r&&(r=cn(r)),t=e}return ze(r).then((n=>sn[e](n,t)))},pn="BeforeRun",un="AfterRun",fn=[`code${pn}`,`code${pn}Async`,`code${un}`,`code${un}Async`],hn=["onWorker","onReady",`on${pn}`,`on${pn}Async`,`on${un}`,`on${un}Async`];function dn(e,t){const{run:n,runAsync:r}=nn.get(this.type);return{...e,run:n.bind(this,t),runAsync:r.bind(this,t)}}const gn=(e,t,n,r,s,o)=>{if(s||o){const a=dn.bind(e,t),i=r?"runAsync":"run",c=e[i];e[i]=r?async function(e,t,...r){s&&await s.call(this,a(e),n);const i=await c.call(this,e,t,...r);return o&&await o.call(this,a(e),n),i}:function(e,t,...r){s&&s.call(this,a(e),n);const i=c.call(this,e,t,...r);return o&&o.call(this,a(e),n),i}}};let yn,wn,mn;const _n=(e,t)=>{addEventListener(e,t||(async t=>{try{await yn,wn(`xworker.on${e}`,t)}catch(e){postMessage(e)}}),!!t&&{once:!0})},{parse:bn,stringify:En}=u,{proxy:vn,window:kn,isWindowProxy:xn}=Pe(self,{parse:bn,stringify:En,transform:e=>mn?mn(e):e}),Tn={sync:vn,window:kn,isWindowProxy:xn,onmessage:console.info,onerror:console.error,onmessageerror:console.warn,postMessage:postMessage.bind(self)};_n("message",(({data:{options:e,config:t,configURL:n,code:r,hooks:s}})=>{yn=(async()=>{try{const{id:o,tag:a,type:i,custom:c,version:l,config:p,async:u}=e,f=((e,t="")=>`${e}@${t}`.replace(/@$/,""))(i,l),h=await ln(f,t,n,p),{js_modules:d,sync_main_only:g}=rn.get(f),y=d?.main;let w=!g;try{new SharedArrayBuffer(4),w=!0}catch(e){if(w)throw new Error(["Unable to use SharedArrayBuffer due insecure environment.","Please read requirements in MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements"].join("\\n"))}const m=Le(nn.get(i)),_=((e,t,n,r)=>({type:t,config:n,interpreter:r,io:Me.get(r),run:(t,...n)=>e.run(r,t,...n),runAsync:(t,...n)=>e.runAsync(r,t,...n),runEvent:(...t)=>e.runEvent(r,...t)}))(m,c||i,p||{},h);let b="run";if(u&&(b+="Async"),s){let e,t,n="",r="";for(const e of fn){const t=s[e];if(t){const s=e.endsWith("Async");(s&&u||!s&&!u)&&(e.startsWith("codeBefore")?n=t:r=t)}}(n||r)&&((e,t,n,r)=>{const s=e[t].bind(e);e[t]="run"===t?(e,t,...o)=>{n&&s(e,n,...o);const a=s(e,Xe(t),...o);return r&&s(e,r,...o),a}:async(e,t,...o)=>{n&&await s(e,n,...o);const a=await s(e,Xe(t),...o);return r&&await s(e,r,...o),a}})(m,b,n,r);for(const n of hn.slice(2)){const r=s[n];if(r){const s=n.endsWith("Async");if(s&&u||!s&&!u){const s=Ye(r);n.startsWith("onBefore")?e=s:t=s}}}gn(m,_,Tn,u,e,t)}let E,v,k,x=null,T="";w&&(({CustomEvent:E,document:v}=kn),x=o&&v.getElementById(o)||null,k=e=>Ke(x,c||i,e,!0,E));const S=at(kn,vn,y,t);if(((e,t,n,r)=>{if("pyodide"===e)return;const s="polyscript.js_modules";for(const e of Reflect.ownKeys(r))t.registerJSModule(n,`${s}.${e}`,et(r,e));t.registerJSModule(n,s,r)})(i,m,h,S),m.registerJSModule(h,"polyscript",{xworker:Tn,currentScript:x,config:_.config,js_modules:S,get target(){return!T&&x&&("SCRIPT"===a?x.after(Ce(v.createElement(`script-${c||i}`),{id:T=`${o}-target`})):(T=o,x.replaceChildren(),x.style.display="block")),T}}),wn=m.runEvent.bind(m,h),mn=m.transform.bind(m,h),x&&k("ready"),s?.onReady&&Ye(s?.onReady).call(m,dn.call(m,_,h),Tn),await m[b](h,r),["micropython","pyodide"].includes(m.type)){const e="polyscript",t=`__${e}_workers__`,n="__export__";h.runPython([`import js as ${t}`,`${t}.${t} = "${n}" in locals() and ${n} or []`,`del ${t}`].join("\\n"));const r=[...globalThis[t]];delete globalThis[t],r.length&&h.runPython([`from ${e} import xworker as ${t}`,...r.map((e=>`${t}.sync.${e} = ${e}`)),`del ${t}`].join("\\n"))}return x&&k("done"),postMessage("polyscript:done"),h}catch(e){postMessage(e)}})(),_n("error"),_n("message"),_n("messageerror")}));\n'.replace(Ce,De)],{type:"application/javascript"})),{type:"module"}),{postMessage:s}=r,o=this instanceof Ot;if(e.length){const[n,r]=e;(t=rn({},t||{type:n,version:r})).type||(t.type=n)}const[i]=Tt(t.config,t.configURL),l=a(n).text().then((e=>{const n=o?this.toJSON():void 0;s.call(r,{options:t,config:i,code:e,hooks:n})})),p=rn(ze(r,b).proxy,{importJS:Pn,importCSS:Tn}),c=Promise.withResolvers();return on(r,{sync:{value:p},ready:{value:c.promise},postMessage:{value:(e,...n)=>l.then((()=>s.call(r,e,...n)))},onerror:{writable:!0,configurable:!0,value:console.error}}),r.addEventListener("message",(e=>{const{data:n}=e,t=n instanceof Error;(t||"polyscript:done"===n)&&(e.stopImmediatePropagation(),t?(c.reject(n),r.onerror(sn(e,{type:{value:"error"},error:{value:n}}))):c.resolve(r))})),o&&this.onWorker?.(this.interpreter,r),r};const Bt="Invalid content";var Ut=e=>{const{src:n,worker:t}=e.attributes;if(t){let{value:r}=t;if(r)throw new SyntaxError("Invalid worker attribute");if(r=n?.value,!r){if(n)throw new SyntaxError("Invalid worker attribute");if(e.childElementCount){const{innerHTML:n,localName:t,type:s}=e,o=s||t.replace(/-script$/,"");r=nn(n),console.warn(`Deprecated: use <script type="${o}"> for an always safe content parsing:\n`,r)}else r=e.textContent;return URL.createObjectURL(new Blob([en(r)],{type:"text/plain"}))}return r}if(n&&e.textContent.replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*(?:\/\/|#).*/gm,"").trim())throw new SyntaxError(Bt)};const It=(e,n)=>{const t=(e=>{let n=e;for(;n.parentNode;)n=n.parentNode;return n})(e);return t.getElementById(n)||((e,n=document)=>n.querySelector(e))(n,t)},zt=new WeakMap,$t={get(){let e=zt.get(this);return e||(e=document.createElement(`${this.type}-script`),zt.set(this,e),Gt(this)),e},set(e){"string"==typeof e?zt.set(this,It(this,e)):(zt.set(this,e),Gt(this))}},Ct=new WeakMap,Dt=new Map,Ft=(e,n)=>{const t=e?.value;return t?n+t:""},qt=(e,n,t,r,s,o,a=e)=>{if(!Dt.has(n)){const i={interpreter:xt(t,s,o),queue:cn(),XWorker:Ht(e,r)};Dt.set(n,i),Dt.has(e)||Dt.set(e,i),Dt.has(a)||Dt.set(a,i)}return Dt.get(n)},Gt=async e=>{if(Ct.has(e)){const{target:n}=e;n&&(e.closest("head")?document.body.append(n):e.after(n))}else{const{attributes:{async:n,config:t,env:r,name:s,target:o,version:p},src:c,type:d}=e,f=p?.value,m=Jt(d,f);let u=Ft(t,"|");const h=Ft(r,"")||`${m}${u}`;u=u.slice(1);const y=Ut(e);if(y){const t=new(Ht(d,f))(y,{...mn(e,d),async:!!n,config:u});Ct.set(an(e,"xworker",{value:t}),{xworker:t});const r=s?.value;return void(r&&i[r].resolve(t.ready))}const g=Ft(o,""),_=qt(d,h,m,f,u);Ct.set(an(e,"target",$t),_),g&&zt.set(e,It(e,g));const w=c?a(c).text():e.textContent;_.queue=_.queue.then((()=>(async(e,n,t,r)=>{const{type:s}=e,o=_t.get(s);o.experimental&&console.warn(`The ${s} interpreter is experimental`);const[a,i]=await pn([Ct.get(e).interpreter,n]);try{an(document,"currentScript",{configurable:!0,get:()=>e}),En(s,o,a,bn),o.registerJSModule(a,"polyscript",{XWorker:t,currentScript:e,js_modules:bn,workers:l}),un(e,s,"ready");const n=o[r?"runAsync":"run"](a,i),p=un.bind(null,e,s,"done");return r?n.then(p):p(),n}finally{delete document.currentScript}})(e,w,_.XWorker,!!n)))}},Vt=new Proxy(sn(null),{get:(e,n)=>new Promise(queueMicrotask).then((()=>Yt(n)))}),Yt=async e=>{if(Dt.has(e)){const{interpreter:n,queue:t}=Dt.get(e);return(await pn([n,t]))[0]}const n=Dt.size?`Available interpreters are: ${[...Dt.keys()].map((e=>`"${e}"`)).join(", ")}.`:"There are no interpreters in this page.";throw new Error(`The interpreter "${e}" was not found. ${n}`)},Kt=async e=>{const{type:n,currentTarget:r}=e;if(vt.length)for(let{name:s,value:o,ownerElement:a}of t(`./@*[${vt.map((e=>`name()="${e}${n}"`)).join(" or ")}]`,r)){s=s.slice(0,-(n.length+1));const t=await Yt(a.getAttribute(`${s}-env`)||s);_t.get(s).runEvent(t,o,e)}},Xt=e=>{if(vt.length)for(let{name:n,ownerElement:r}of t(`.//@*[${vt.map((e=>`starts-with(name(),"${e}")`)).join(" or ")}]`,e)){const e=n.lastIndexOf("-"),t=n.slice(e+1);"env"!==t&&(r.addEventListener(t,Kt),"disabled"in r&&!r.disabled&&(r.disabled=!0,Vt[n.slice(0,e)].then((()=>{r.disabled=!1}))))}},Zt=Ht(),Qt=[],er=new Map,nr=new Map,tr=new Map,rr=async e=>{for(const n of Qt)if(e.matches(n)){const t=nr.get(n),r=sr.get(t),{resolve:s}=tr.get(t),{options:o,known:a}=r;if(a.has(e))return;a.add(e);for(const[n,t]of er)e.matches(n)&&await t(e);const{interpreter:p,configURL:c,config:d,version:f,env:m,onerror:u,hooks:h}=o;let y;try{const n=Ut(e);if(n){const r=Zt.call(new Ot(null,h),n,{...mn(e,t),version:f,configURL:c,type:p,custom:t,config:e.getAttribute("config")||d||{},async:e.hasAttribute("async")});an(e,"xworker",{value:r}),s({type:t,xworker:r});const o=e.getAttribute("name");return void(o&&i[o].resolve(r.ready))}}catch(e){y=e}const g=Jt(p,f),_=m||`${g}${d?`|${d}`:""}`,{interpreter:w,XWorker:b}=qt(t,_,g,f,d,c,p),v=await w,S=sn(_t.get(p)),E=new Ot(v,h),P=function(...e){return b.apply(E,e)},T={...hn(S,t,structuredClone(wt.get(g)),v),XWorker:P};En(p,S,v,bn),S.registerJSModule(v,"polyscript",{XWorker:P,config:T.config,currentScript:t.startsWith("_")?null:e,js_modules:bn,workers:l});for(const n of["Run","RunAsync"]){let t,r,s="",o="";for(const e of Nt){const t=h?.main?.[e];t&&e.endsWith(n)&&(e.startsWith("codeBefore")?s=en(t()):o=en(t()))}(s||o)&&gn(S,`r${n.slice(1)}`,s,o);for(let e=2;e<At.length;e++){const s=At[e],o=h?.main?.[s];o&&s.endsWith(n)&&(s.startsWith("onBefore")?t=o:r=o)}Wt(S,T,e,n.endsWith("Async"),t,r)}r.queue=r.queue.then((()=>(s(T),y&&u?.(y,e),h?.main?.onReady?.(T,e))))}},sr=new Map;let or=0;const ar=e=>(tr.has(e)||tr.set(e,Promise.withResolvers()),tr.get(e).promise),[{customObserver:ir,define:lr,whenDefined:pr,env:cr,Hook:dr,XWorker:fr},mr]=e("polyscript",{customObserver:er,define:(e,t)=>{let r=null==e;if(r)e="_ps"+or++;else if(_t.has(e)||sr.has(e))throw new Error(`<script type="${e}"> already registered`);if(!_t.has(t?.interpreter))throw new Error("Unspecified interpreter");_t.set(e,_t.get(t.interpreter));const s=[`script[type="${e}"]`];if(ar(e),r){const{hooks:n}=t,r=n?.main?.onReady;t={...t,hooks:{...n,main:{...n?.main,onReady(n,t){Qt.splice(Qt.indexOf(e),1),_t.delete(e),sr.delete(e),tr.delete(e),t.remove(),r?.(n)}}}},document.head.append(rn(document.createElement("script"),{type:e}))}else s.push(`${e}-script`),vt.push(`${e}-`);for(const n of s)nr.set(n,e);Qt.push(...s),sr.set(e,{options:rn({env:e},t),known:new WeakSet,queue:Promise.resolve()}),r||Xt(document),n(s.join(",")).forEach(rr)},whenDefined:ar,env:Vt,Hook:Ot,XWorker:Zt});if(!mr){const e=new MutationObserver((e=>{const n=bt.join(",");for(const{type:r,target:s,attributeName:o,addedNodes:a}of e)if("attributes"!==r)for(const e of a)1===e.nodeType&&(Xt(e),n&&e.matches(n)?Gt(e):t(n,e,!0));else{const e=o.lastIndexOf("-")+1;if(e){const n=o.slice(0,e);for(const t of vt)if(n===t){const n=o.slice(e);if("env"!==n){const e=s.hasAttribute(o)?"add":"remove";s[`${e}EventListener`](n,Kt)}break}}}})),t=(e,t,r)=>{e&&n(e,t).forEach(Gt),(e=Qt.join(","))&&(r&&rr(t),n(e,t).forEach(rr))},r=n=>(e.observe(n,{childList:!0,subtree:!0,attributes:!0}),n),{attachShadow:s}=Element.prototype;rn(Element.prototype,{attachShadow(e){return r(s.call(this,e))}}),queueMicrotask((()=>{Xt(r(document)),t(bt.join(","),document,!1)}))}var ur=new Map([["py","pyodide"],["mpy","micropython"]]);const hr=[];for(const[e]of ur){const n=[`script[type="${e}"]`,`${e}-script`];for(const t of document.querySelectorAll(n.join(","))){const{promise:n,resolve:r}=Promise.withResolvers();hr.push(n),t.addEventListener(`${e}:done`,r,{once:!0})}}Promise.all(hr).then((()=>{dispatchEvent(new Event("py:all-done"))}));var yr={"deprecations-manager":()=>import("./deprecations-manager-CQv1VsU_.js"),error:()=>import("./error-DueleOMN.js"),"py-editor":()=>import("./py-editor-D3FDoYNU.js"),"py-terminal":()=>import("./py-terminal-DMP3XcAx.js")};const gr={GENERIC:"PY0000",CONFLICTING_CODE:"PY0409",BAD_CONFIG:"PY1000",MICROPIP_INSTALL_ERROR:"PY1001",BAD_PLUGIN_FILE_EXTENSION:"PY2000",NO_DEFAULT_EXPORT:"PY2001",TOP_LEVEL_AWAIT:"PY9000",FETCH_ERROR:"PY0001",FETCH_NAME_ERROR:"PY0002",FETCH_UNAUTHORIZED_ERROR:"PY0401",FETCH_FORBIDDEN_ERROR:"PY0403",FETCH_NOT_FOUND_ERROR:"PY0404",FETCH_SERVER_ERROR:"PY0500",FETCH_UNAVAILABLE_ERROR:"PY0503"};class _r extends Error{constructor(e,n="",t="text"){super(`(${e}): ${n}`),this.errorCode=e,this.messageType=t,this.name="UserError"}}class wr extends _r{constructor(e,n){super(e,n),this.name="FetchError"}}const br=e=>e.text();async function vr(e,n){let t;try{t=await fetch(e,n)}catch(n){const t=n;let r;throw r=e.startsWith("http")?`Fetching from URL ${e} failed with error '${t.message}'. Are your filename and path correct?`:'Polyscript: Access to local files\n (using [[fetch]] configurations in &lt;py-config&gt;)\n is not available when directly opening a HTML file;\n you must use a webserver to serve the additional files.\n See <a style="text-decoration: underline;" href="https://github.com/pyscript/pyscript/issues/257#issuecomment-1119595062">this reference</a>\n on starting a simple webserver with Python.\n ',new wr(gr.FETCH_ERROR,r)}if(!t.ok){const n=`Fetching from URL ${e} failed with error ${t.status} (${t.statusText}). Are your filename and path correct?`;switch(t.status){case 404:throw new wr(gr.FETCH_NOT_FOUND_ERROR,n);case 401:throw new wr(gr.FETCH_UNAUTHORIZED_ERROR,n);case 403:throw new wr(gr.FETCH_FORBIDDEN_ERROR,n);case 500:throw new wr(gr.FETCH_SERVER_ERROR,n);case 503:throw new wr(gr.FETCH_UNAVAILABLE_ERROR,n);default:throw new wr(gr.FETCH_ERROR,n)}}return t}const{BAD_CONFIG:Sr,CONFLICTING_CODE:Er}=gr,Pr=async(e,n)=>{let t=e?.trim(),r="",s=!1,o=/^{/.test(t)&&/}$/.test(t);if(!o&&/\.(\w+)(?:\?\S*)?$/.test(t)){const e=RegExp.$1;"json"===e&&"toml"!==n?o=!0:"toml"===e&&"json"!==n?s=!0:((e,n="")=>{let t=`(${Sr}): Invalid URL: ${e}`;throw n&&(t+=`\nexpected ${n} content`),new Error(t)})(t,n),r=t,t=(await vr(r).then(br)).trim()}return{json:o,toml:s||!o&&!!t,text:t,url:r}},Tr=e=>new Error(`(${Er}): ${e}`),kr=(e,n,{message:t})=>{let r=`(${Sr}): Invalid ${e}`;return n&&(r+=` @ ${n}`),new SyntaxError(`${r}\n${t}`)},xr=new Map;for(const[e]of ur){let t,r,s,o,a,i,l,p=n(`${e}-config`),c=n([`script[type="${e}"][config]:not([worker])`,`${e}-script[config]:not([worker])`].join(","));if(p.length>1?s=Tr(`Too many ${e}-config`):p.length&&c.length?s=Tr(`Ambiguous ${e}-config VS config attribute`):p.length?([l]=p,a=l.getAttribute("src")||l.textContent,i=l.getAttribute("type")):c.length&&([l,...c]=c,a=l.getAttribute("config"),c.some((e=>e.getAttribute("config")!==a))&&(s=Tr("Unable to use different configs on main"))),!s&&a)try{const{json:e,toml:n,text:t,url:l}=await Pr(a,i);if(l&&(o=new URL(l,location.href).href),a=t,e||"json"===i)try{r=JSON.parse(t)}catch(e){s=kr("JSON",l,e)}else if(n||"toml"===i)try{const{parse:e}=await import("./toml-CvAfdf9_.js");r=e(t)}catch(e){s=kr("TOML",l,e)}}catch(e){s=e}const d=[];for(const[e,n]of Object.entries(yr))s?"error"===e&&n().then((({notify:e})=>e(s.message))):r?.plugins?.includes(`!${e}`)||d.push(n().then((({default:e})=>e)));t=Promise.all(d),xr.set(e,{config:r,configURL:o,plugins:t,error:s})}var Jr={is_pyterminal:()=>!1,sleep:e=>new Promise((n=>setTimeout(n,1e3*e)))};const jr=e=>{an(document,"currentScript",{configurable:!0,get:()=>e})},Rr=()=>{delete document.currentScript};var Mr=async(e,n,t,r)=>{const s=r.endsWith("Async");(r.startsWith("onBefore")?jr:Rr)(t);for(const o of e(r))s?await o(n,t):o(n,t)};const Nr=()=>!0,Ar=e=>{throw new TypeError(e)},Lr=(e,n)=>{const t=[];if(e)for(const n of e.split(/\s*\|\s*/))"object"===n?t.push((e=>null!==e&&typeof e===n)):"null"===n?t.push((e=>null===e)):t.push((e=>typeof e===n));if(n)for(const e of[].concat(n))t.push((n=>n instanceof e));switch(t.length){case 0:return Nr;case 1:return t[0];default:return e=>t.some((n=>n(e)))}},Wr=(e,n,t,r=Ar)=>s=>{const o=[`Invalid ${typeof s} ${t}: expected `];e&&(o.push(e),n&&o.push(" or ")),n&&(o.push("an instanceof "),o.push([].concat(n).map((({name:e})=>e)).join(" | "))),r(o.join(""),s)},Or=(e=>n=>{const[t,r]=((e,n="value")=>{const t=e?.typeof,r=e?.instanceof;return[Lr(t,r),Wr(t,r,n,e?.onerror)]})(n);return class extends e{add(e){return t(e)?super.add(e):r(e)}}})(Set);const{entries:Hr}=Object,Br=["import os as _os","from pathlib import Path as _Path","_path = None"],Ur=new class extends Array{#a=!1;#i;#l;constructor(e,...n){super(),this.#l=e,this.#i=n}push(...e){return this.#a&&super.push(...e),this.#l.push(...e)}path(e){for(const n of this.#i)if(this.#a=e.startsWith(n))break}}(Br,"-"),Ir=(e,n)=>{for(const[t,r]of Hr(n))if(Ur.path(`${e}/${t}`),Ur.push(`_path = _Path("${e}/${t}")`),"string"==typeof r){const e=JSON.stringify(r);Ur.push(`_path.write_text(${e},encoding="utf-8")`)}else Ur.push(`if not _os.path.exists("${e}/${t}"):`),Ur.push(" _path.mkdir(parents=True, exist_ok=True)"),Ir(`${e}/${t}`,r)};Ir(".",{pyscript:{"__init__.py":'# Some notes about the naming conventions and the relationship between various\n# similar-but-different names.\n#\n# import pyscript\n# this package contains the main user-facing API offered by pyscript. All\n# the names which are supposed be used by end users should be made\n# available in pyscript/__init__.py (i.e., this file)\n#\n# import _pyscript\n# this is an internal module implemented in JS. It is used internally by\n# the pyscript package, end users should not use it directly. For its\n# implementation, grep for `interpreter.registerJsModule("_pyscript",\n# ...)` in core.js\n#\n# import js\n# this is the JS globalThis, as exported by pyodide and/or micropython\'s\n# FFIs. As such, it contains different things in the main thread or in a\n# worker.\n#\n# import pyscript.magic_js\n# this submodule abstracts away some of the differences between the main\n# thread and the worker. In particular, it defines `window` and `document`\n# in such a way that these names work in both cases: in the main thread,\n# they are the "real" objects, in the worker they are proxies which work\n# thanks to coincident.\n#\n# from pyscript import window, document\n# these are just the window and document objects as defined by\n# pyscript.magic_js. This is the blessed way to access them from pyscript,\n# as it works transparently in both the main thread and worker cases.\n\nfrom polyscript import lazy_py_modules as py_import\nfrom pyscript.display import HTML, display\nfrom pyscript.fetch import fetch\nfrom pyscript.magic_js import (\n RUNNING_IN_WORKER,\n PyWorker,\n config,\n current_target,\n document,\n js_import,\n js_modules,\n sync,\n window,\n)\nfrom pyscript.storage import Storage, storage\nfrom pyscript.websocket import WebSocket\n\nif not RUNNING_IN_WORKER:\n from pyscript.workers import workers\n\ntry:\n from pyscript.event_handling import when\nexcept:\n # TODO: should we remove this? Or at the very least, we should capture\n # the traceback otherwise it\'s very hard to debug\n from pyscript.util import NotSupported\n\n when = NotSupported(\n "pyscript.when", "pyscript.when currently not available with this interpreter"\n )\n',"display.py":'import base64\nimport html\nimport io\nimport re\n\nfrom pyscript.magic_js import current_target, document, window\n\n_MIME_METHODS = {\n "savefig": "image/png",\n "_repr_javascript_": "application/javascript",\n "_repr_json_": "application/json",\n "_repr_latex": "text/latex",\n "_repr_png_": "image/png",\n "_repr_jpeg_": "image/jpeg",\n "_repr_pdf_": "application/pdf",\n "_repr_svg_": "image/svg+xml",\n "_repr_markdown_": "text/markdown",\n "_repr_html_": "text/html",\n "__repr__": "text/plain",\n}\n\n\ndef _render_image(mime, value, meta):\n # If the image value is using bytes we should convert it to base64\n # otherwise it will return raw bytes and the browser will not be able to\n # render it.\n if isinstance(value, bytes):\n value = base64.b64encode(value).decode("utf-8")\n\n # This is the pattern of base64 strings\n base64_pattern = re.compile(\n r"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$"\n )\n # If value doesn\'t match the base64 pattern we should encode it to base64\n if len(value) > 0 and not base64_pattern.match(value):\n value = base64.b64encode(value.encode("utf-8")).decode("utf-8")\n\n data = f"data:{mime};charset=utf-8;base64,{value}"\n attrs = " ".join([\'{k}="{v}"\' for k, v in meta.items()])\n return f\'<img src="{data}" {attrs}></img>\'\n\n\ndef _identity(value, meta):\n return value\n\n\n_MIME_RENDERERS = {\n "text/plain": html.escape,\n "text/html": _identity,\n "image/png": lambda value, meta: _render_image("image/png", value, meta),\n "image/jpeg": lambda value, meta: _render_image("image/jpeg", value, meta),\n "image/svg+xml": _identity,\n "application/json": _identity,\n "application/javascript": lambda value, meta: f"<script>{value}<\\\\/script>",\n}\n\n\nclass HTML:\n """\n Wrap a string so that display() can render it as plain HTML\n """\n\n def __init__(self, html):\n self._html = html\n\n def _repr_html_(self):\n return self._html\n\n\ndef _eval_formatter(obj, print_method):\n """\n Evaluates a formatter method.\n """\n if print_method == "__repr__":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == "savefig":\n buf = io.BytesIO()\n obj.savefig(buf, format="png")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode("utf-8")\n return getattr(obj, print_method)()\n elif print_method == "_repr_mimebundle_":\n return {}, {}\n return None\n\n\ndef _format_mime(obj):\n """\n Formats object using _repr_x_ methods.\n """\n if isinstance(obj, str):\n return html.escape(obj), "text/plain"\n\n mimebundle = _eval_formatter(obj, "_repr_mimebundle_")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in _MIME_METHODS.items():\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = _eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in _MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n window.console.warn(\n f"Rendered object requested unavailable MIME renderers: {not_available}"\n )\n output = repr(output)\n mime_type = "text/plain"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return _MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\ndef _write(element, value, append=False):\n html, mime_type = _format_mime(value)\n if html == "\\\\n":\n return\n\n if append:\n out_element = document.createElement("div")\n element.append(out_element)\n else:\n out_element = element.lastElementChild\n if out_element is None:\n out_element = element\n\n if mime_type in ("application/javascript", "text/html"):\n script_element = document.createRange().createContextualFragment(html)\n out_element.append(script_element)\n else:\n out_element.innerHTML = html\n\n\ndef display(*values, target=None, append=True):\n if target is None:\n target = current_target()\n elif not isinstance(target, str):\n raise TypeError(f"target must be str or None, not {target.__class__.__name__}")\n elif target == "":\n raise ValueError("Cannot have an empty target")\n elif target.startswith("#"):\n # note: here target is str and not None!\n # align with @when behavior\n target = target[1:]\n\n element = document.getElementById(target)\n\n # If target cannot be found on the page, a ValueError is raised\n if element is None:\n raise ValueError(\n f"Invalid selector with id={target}. Cannot be found in the page."\n )\n\n # if element is a <script type="py">, it has a \'target\' attribute which\n # points to the visual element holding the displayed values. In that case,\n # use that.\n if element.tagName == "SCRIPT" and hasattr(element, "target"):\n element = element.target\n\n for v in values:\n if not append:\n element.replaceChildren()\n _write(element, v, append=append)\n',"event_handling.py":'import inspect\n\ntry:\n from pyodide.ffi.wrappers import add_event_listener\n\nexcept ImportError:\n\n def add_event_listener(el, event_type, func):\n el.addEventListener(event_type, func)\n\n\nfrom pyscript.magic_js import document\n\n\ndef when(event_type=None, selector=None):\n """\n Decorates a function and passes py-* events to the decorated function\n The events might or not be an argument of the decorated function\n """\n\n def decorator(func):\n if isinstance(selector, str):\n elements = document.querySelectorAll(selector)\n else:\n # TODO: This is a hack that will be removed when pyscript becomes a package\n # and we can better manage the imports without circular dependencies\n from pyweb import pydom\n\n if isinstance(selector, pydom.Element):\n elements = [selector._js]\n elif isinstance(selector, pydom.ElementCollection):\n elements = [el._js for el in selector]\n else:\n raise ValueError(\n f"Invalid selector: {selector}. Selector must"\n " be a string, a pydom.Element or a pydom.ElementCollection."\n )\n try:\n sig = inspect.signature(func)\n # Function doesn\'t receive events\n if not sig.parameters:\n\n def wrapper(*args, **kwargs):\n func()\n\n else:\n wrapper = func\n\n except AttributeError:\n # TODO: this is very ugly hack to get micropython working because inspect.signature\n # doesn\'t exist, but we need to actually properly replace inspect.signature.\n # It may be actually better to not try any magic for now and raise the error\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except TypeError as e:\n if "takes" in str(e) and "positional arguments" in str(e):\n return func()\n\n raise\n\n for el in elements:\n add_event_listener(el, event_type, wrapper)\n\n return func\n\n return decorator\n',"fetch.py":'import json\n\nimport js\nfrom pyscript.util import as_bytearray\n\n\n### wrap the response to grant Pythonic results\nclass _Response:\n def __init__(self, response):\n self._response = response\n\n # grant access to response.ok and other fields\n def __getattr__(self, attr):\n return getattr(self._response, attr)\n\n # exposed methods with Pythonic results\n async def arrayBuffer(self):\n buffer = await self._response.arrayBuffer()\n # works in Pyodide\n if hasattr(buffer, "to_py"):\n return buffer.to_py()\n # shims in MicroPython\n return memoryview(as_bytearray(buffer))\n\n async def blob(self):\n return await self._response.blob()\n\n async def bytearray(self):\n buffer = await self._response.arrayBuffer()\n return as_bytearray(buffer)\n\n async def json(self):\n return json.loads(await self.text())\n\n async def text(self):\n return await self._response.text()\n\n\n### allow direct await to _Response methods\nclass _DirectResponse:\n @staticmethod\n def setup(promise, response):\n promise._response = _Response(response)\n return promise._response\n\n def __init__(self, promise):\n self._promise = promise\n promise._response = None\n promise.arrayBuffer = self.arrayBuffer\n promise.blob = self.blob\n promise.bytearray = self.bytearray\n promise.json = self.json\n promise.text = self.text\n\n async def _response(self):\n if not self._promise._response:\n await self._promise\n return self._promise._response\n\n async def arrayBuffer(self):\n response = await self._response()\n return await response.arrayBuffer()\n\n async def blob(self):\n response = await self._response()\n return await response.blob()\n\n async def bytearray(self):\n response = await self._response()\n return await response.bytearray()\n\n async def json(self):\n response = await self._response()\n return await response.json()\n\n async def text(self):\n response = await self._response()\n return await response.text()\n\n\ndef fetch(url, **kw):\n # workaround Pyodide / MicroPython dict <-> js conversion\n options = js.JSON.parse(json.dumps(kw))\n awaited = lambda response, *args: _DirectResponse.setup(promise, response)\n promise = js.fetch(url, options).then(awaited)\n _DirectResponse(promise)\n return promise\n',"ffi.py":'try:\n import js\n from pyodide.ffi import create_proxy as _cp\n from pyodide.ffi import to_js as _py_tjs\n\n from_entries = js.Object.fromEntries\n\n def _tjs(value, **kw):\n if not hasattr(kw, "dict_converter"):\n kw["dict_converter"] = from_entries\n return _py_tjs(value, **kw)\n\nexcept:\n from jsffi import create_proxy as _cp\n from jsffi import to_js as _tjs\n\ncreate_proxy = _cp\nto_js = _tjs\n',"flatted.py":"# https://www.npmjs.com/package/flatted\n\nimport json as _json\n\n\nclass _Known:\n def __init__(self):\n self.key = []\n self.value = []\n\n\nclass _String:\n def __init__(self, value):\n self.value = value\n\n\ndef _array_keys(value):\n keys = []\n i = 0\n for _ in value:\n keys.append(i)\n i += 1\n return keys\n\n\ndef _object_keys(value):\n keys = []\n for key in value:\n keys.append(key)\n return keys\n\n\ndef _is_array(value):\n return isinstance(value, list) or isinstance(value, tuple)\n\n\ndef _is_object(value):\n return isinstance(value, dict)\n\n\ndef _is_string(value):\n return isinstance(value, str)\n\n\ndef _index(known, input, value):\n input.append(value)\n index = str(len(input) - 1)\n known.key.append(value)\n known.value.append(index)\n return index\n\n\ndef _loop(keys, input, known, output):\n for key in keys:\n value = output[key]\n if isinstance(value, _String):\n _ref(key, input[int(value.value)], input, known, output)\n\n return output\n\n\ndef _ref(key, value, input, known, output):\n if _is_array(value) and not value in known:\n known.append(value)\n value = _loop(_array_keys(value), input, known, value)\n elif _is_object(value) and not value in known:\n known.append(value)\n value = _loop(_object_keys(value), input, known, value)\n\n output[key] = value\n\n\ndef _relate(known, input, value):\n if _is_string(value) or _is_array(value) or _is_object(value):\n try:\n return known.value[known.key.index(value)]\n except:\n return _index(known, input, value)\n\n return value\n\n\ndef _transform(known, input, value):\n if _is_array(value):\n output = []\n for val in value:\n output.append(_relate(known, input, val))\n return output\n\n if _is_object(value):\n obj = {}\n for key in value:\n obj[key] = _relate(known, input, value[key])\n return obj\n\n return value\n\n\ndef _wrap(value):\n if _is_string(value):\n return _String(value)\n\n if _is_array(value):\n i = 0\n for val in value:\n value[i] = _wrap(val)\n i += 1\n\n elif _is_object(value):\n for key in value:\n value[key] = _wrap(value[key])\n\n return value\n\n\ndef parse(value, *args, **kwargs):\n json = _json.loads(value, *args, **kwargs)\n wrapped = []\n for value in json:\n wrapped.append(_wrap(value))\n\n input = []\n for value in wrapped:\n if isinstance(value, _String):\n input.append(value.value)\n else:\n input.append(value)\n\n value = input[0]\n\n if _is_array(value):\n return _loop(_array_keys(value), input, [value], value)\n\n if _is_object(value):\n return _loop(_object_keys(value), input, [value], value)\n\n return value\n\n\ndef stringify(value, *args, **kwargs):\n known = _Known()\n input = []\n output = []\n i = int(_index(known, input, value))\n while i < len(input):\n output.append(_transform(known, input, input[i]))\n i += 1\n return _json.dumps(output, *args, **kwargs)\n","magic_js.py":'import json\nimport sys\n\nimport js as globalThis\nfrom polyscript import config as _config\nfrom polyscript import js_modules\nfrom pyscript.util import NotSupported\n\nRUNNING_IN_WORKER = not hasattr(globalThis, "document")\n\nconfig = json.loads(globalThis.JSON.stringify(_config))\n\n\n# allow `from pyscript.js_modules.xxx import yyy`\nclass JSModule:\n def __init__(self, name):\n self.name = name\n\n def __getattr__(self, field):\n # avoid pyodide looking for non existent fields\n if not field.startswith("_"):\n return getattr(getattr(js_modules, self.name), field)\n\n\n# generate N modules in the system that will proxy the real value\nfor name in globalThis.Reflect.ownKeys(js_modules):\n sys.modules[f"pyscript.js_modules.{name}"] = JSModule(name)\nsys.modules["pyscript.js_modules"] = js_modules\n\nif RUNNING_IN_WORKER:\n import polyscript\n\n PyWorker = NotSupported(\n "pyscript.PyWorker",\n "pyscript.PyWorker works only when running in the main thread",\n )\n\n try:\n globalThis.SharedArrayBuffer.new(4)\n import js\n\n window = polyscript.xworker.window\n document = window.document\n js.document = document\n # this is the same as js_import on main and it lands modules on main\n js_import = window.Function(\n "return (...urls) => Promise.all(urls.map((url) => import(url)))"\n )()\n except:\n globalThis.console.debug("SharedArrayBuffer is not available")\n # in this scenario none of the utilities would work\n # as expected so we better export these as NotSupported\n window = NotSupported(\n "pyscript.window",\n "pyscript.window in workers works only via SharedArrayBuffer",\n )\n document = NotSupported(\n "pyscript.document",\n "pyscript.document in workers works only via SharedArrayBuffer",\n )\n\n sync = polyscript.xworker.sync\n\n # in workers the display does not have a default ID\n # but there is a sync utility from xworker\n def current_target():\n return polyscript.target\n\nelse:\n import _pyscript\n from _pyscript import PyWorker, js_import\n\n window = globalThis\n document = globalThis.document\n sync = NotSupported(\n "pyscript.sync", "pyscript.sync works only when running in a worker"\n )\n\n # in MAIN the current element target exist, just use it\n def current_target():\n return _pyscript.target\n',"storage.py":'from polyscript import storage as _storage\nfrom pyscript.flatted import parse as _parse\nfrom pyscript.flatted import stringify as _stringify\n\n\n# convert a Python value into an IndexedDB compatible entry\ndef _to_idb(value):\n if value is None:\n return _stringify(["null", 0])\n if isinstance(value, (bool, float, int, str, list, dict, tuple)):\n return _stringify(["generic", value])\n if isinstance(value, bytearray):\n return _stringify(["bytearray", [v for v in value]])\n if isinstance(value, memoryview):\n return _stringify(["memoryview", [v for v in value]])\n raise TypeError(f"Unexpected value: {value}")\n\n\n# convert an IndexedDB compatible entry into a Python value\ndef _from_idb(value):\n (\n kind,\n result,\n ) = _parse(value)\n if kind == "null":\n return None\n if kind == "generic":\n return result\n if kind == "bytearray":\n return bytearray(result)\n if kind == "memoryview":\n return memoryview(bytearray(result))\n return value\n\n\nclass Storage(dict):\n def __init__(self, store):\n super().__init__({k: _from_idb(v) for k, v in store.entries()})\n self.__store__ = store\n\n def __delitem__(self, attr):\n self.__store__.delete(attr)\n super().__delitem__(attr)\n\n def __setitem__(self, attr, value):\n self.__store__.set(attr, _to_idb(value))\n super().__setitem__(attr, value)\n\n def clear(self):\n self.__store__.clear()\n super().clear()\n\n async def sync(self):\n await self.__store__.sync()\n\n\nasync def storage(name="", storage_class=Storage):\n if not name:\n raise ValueError("The storage name must be defined")\n return storage_class(await _storage(f"@pyscript/{name}"))\n',"util.py":'import js\n\n\ndef as_bytearray(buffer):\n ui8a = js.Uint8Array.new(buffer)\n size = ui8a.length\n ba = bytearray(size)\n for i in range(0, size):\n ba[i] = ui8a[i]\n return ba\n\n\nclass NotSupported:\n """\n Small helper that raises exceptions if you try to get/set any attribute on\n it.\n """\n\n def __init__(self, name, error):\n object.__setattr__(self, "name", name)\n object.__setattr__(self, "error", error)\n\n def __repr__(self):\n return f"<NotSupported {self.name} [{self.error}]>"\n\n def __getattr__(self, attr):\n raise AttributeError(self.error)\n\n def __setattr__(self, attr, value):\n raise AttributeError(self.error)\n\n def __call__(self, *args):\n raise TypeError(self.error)\n',web:{"__init__.py":"from . import elements\n\n# Ugly trick to hide the dom module in the web package since we want the module\n# to allow querying right away.\nfrom .dom import dom\n","dom.py":'from pyscript import document\nfrom pyscript.web.elements import Element, ElementCollection\n\n\nclass PyDom:\n # Add objects we want to expose to the DOM namespace since this class instance is being\n # remapped as "the module" itself\n ElementCollection = ElementCollection\n\n def __init__(self):\n self._js = document\n\n self.body = Element(document.body)\n self.head = Element(document.head)\n\n def __getitem__(self, key):\n elements = self._js.querySelectorAll(key)\n return ElementCollection([Element(el) for el in elements])\n\n\ndom = PyDom()\n',"elements.py":'import inspect\nimport sys\n\ntry:\n from typing import Any\nexcept ImportError:\n Any = "Any"\n\ntry:\n import warnings\nexcept ImportError:\n # TODO: For now it probably means we are in MicroPython. We should figure\n # out the "right" way to handle this. For now we just ignore the warning\n # and logging to console\n class warnings:\n @staticmethod\n def warn(*args, **kwargs):\n print("WARNING: ", *args, **kwargs)\n\n\ntry:\n from functools import cached_property\nexcept ImportError:\n # TODO: same comment about micropython as above\n cached_property = property\n\ntry:\n from pyodide.ffi import JsProxy\nexcept ImportError:\n # TODO: same comment about micropython as above\n def JsProxy(obj):\n return obj\n\n\nfrom pyscript import document, window\n\n# from pyscript.web import dom as pydom\n\n#: A flag to show if MicroPython is the current Python interpreter.\nis_micropython = "MicroPython" in sys.version\n\n\ndef getmembers_static(cls):\n """Cross-interpreter implementation of inspect.getmembers_static."""\n\n if is_micropython: # pragma: no cover\n return [(name, getattr(cls, name)) for name, _ in inspect.getmembers(cls)]\n\n return inspect.getmembers_static(cls)\n\n\nclass JSProperty:\n """JS property descriptor that directly maps to the property with the same\n name in the underlying JS component."""\n\n def __init__(self, name: str, allow_nones: bool = False):\n self.name = name\n self.allow_nones = allow_nones\n\n def __get__(self, obj, objtype=None):\n return getattr(obj._js, self.name)\n\n def __set__(self, obj, value):\n if not self.allow_nones and value is None:\n return\n setattr(obj._js, self.name, value)\n\n\n# ------ TODO: REMOVE!!!! pydom elements\n\n\nclass BaseElement:\n def __init__(self, js_element):\n self._js = js_element\n self._parent = None\n self.style = StyleProxy(self)\n self._proxies = {}\n\n def __eq__(self, obj):\n """Check if the element is the same as the other element by comparing\n the underlying JS element"""\n return isinstance(obj, BaseElement) and obj._js == self._js\n\n @property\n def parent(self):\n if self._parent:\n return self._parent\n\n if self._js.parentElement:\n # TODO: This should actually return the correct class (== to tagName)\n self._parent = Element(self._js.parentElement)\n\n return self._parent\n\n # @property\n # def __class(self):\n # return self.__class__ if self.__class__ != PyDom else Element\n\n def create(self, type_, is_child=True, classes=None, html=None, label=None):\n js_el = document.createElement(type_)\n element = self.__class(js_el)\n\n if classes:\n for class_ in classes:\n element.add_class(class_)\n\n if html is not None:\n element.html = html\n\n if label is not None:\n element.label = label\n\n if is_child:\n self.append(element)\n\n return element\n\n def find(self, selector):\n """Return an ElementCollection representing all the child elements that\n match the specified selector.\n\n Args:\n selector (str): A string containing a selector expression\n\n Returns:\n ElementCollection: A collection of elements matching the selector\n """\n elements = self._js.querySelectorAll(selector)\n if not elements:\n return None\n return ElementCollection([Element(el) for el in elements])\n\n\nclass Element(BaseElement):\n @property\n def children(self):\n return [self.__class__(el) for el in self._js.children]\n\n def append(self, child):\n # TODO: this is Pyodide specific for now!!!!!!\n # if we get passed a JSProxy Element directly we just map it to the\n # higher level Python element\n if inspect.isclass(JsProxy) and isinstance(child, JsProxy):\n return self.append(Element(child))\n\n elif isinstance(child, Element):\n self._js.appendChild(child._js)\n\n return child\n\n elif isinstance(child, ElementCollection):\n for el in child:\n self.append(el)\n\n # -------- Pythonic Interface to Element -------- #\n @property\n def html(self):\n return self._js.innerHTML\n\n @html.setter\n def html(self, value):\n self._js.innerHTML = value\n\n @property\n def text(self):\n return self._js.textContent\n\n @text.setter\n def text(self, value):\n self._js.textContent = value\n\n @property\n def content(self):\n # TODO: This breaks with with standard template elements. Define how to best\n # handle this specifica use case. Just not support for now?\n if self._js.tagName == "TEMPLATE":\n warnings.warn(\n "Content attribute not supported for template elements.", stacklevel=2\n )\n return None\n return self._js.innerHTML\n\n @content.setter\n def content(self, value):\n # TODO: (same comment as above)\n if self._js.tagName == "TEMPLATE":\n warnings.warn(\n "Content attribute not supported for template elements.", stacklevel=2\n )\n return\n\n display(value, target=self.id)\n\n @property\n def id(self):\n return self._js.id\n\n @id.setter\n def id(self, value):\n self._js.id = value\n\n @property\n def options(self):\n if "options" in self._proxies:\n return self._proxies["options"]\n\n if not self._js.tagName.lower() in {"select", "datalist", "optgroup"}:\n raise AttributeError(\n f"Element {self._js.tagName} has no options attribute."\n )\n self._proxies["options"] = OptionsProxy(self)\n return self._proxies["options"]\n\n @property\n def value(self):\n return self._js.value\n\n @value.setter\n def value(self, value):\n # in order to avoid confusion to the user, we don\'t allow setting the\n # value of elements that don\'t have a value attribute\n if not hasattr(self._js, "value"):\n raise AttributeError(\n f"Element {self._js.tagName} has no value attribute. If you want to "\n "force a value attribute, set it directly using the `_js.value = <value>` "\n "javascript API attribute instead."\n )\n self._js.value = value\n\n @property\n def selected(self):\n return self._js.selected\n\n @selected.setter\n def selected(self, value):\n # in order to avoid confusion to the user, we don\'t allow setting the\n # value of elements that don\'t have a value attribute\n if not hasattr(self._js, "selected"):\n raise AttributeError(\n f"Element {self._js.tagName} has no value attribute. If you want to "\n "force a value attribute, set it directly using the `_js.value = <value>` "\n "javascript API attribute instead."\n )\n self._js.selected = value\n\n def clone(self, new_id=None):\n clone = Element(self._js.cloneNode(True))\n clone.id = new_id\n\n return clone\n\n def remove_class(self, classname):\n classList = self._js.classList\n if isinstance(classname, list):\n classList.remove(*classname)\n else:\n classList.remove(classname)\n return self\n\n def add_class(self, classname):\n classList = self._js.classList\n if isinstance(classname, list):\n classList.add(*classname)\n else:\n self._js.classList.add(classname)\n return self\n\n @property\n def classes(self):\n classes = self._js.classList.values()\n return [x for x in classes]\n\n def show_me(self):\n self._js.scrollIntoView()\n\n def snap(\n self,\n to: BaseElement | str = None,\n width: int | None = None,\n height: int | None = None,\n ):\n """\n Captures a snapshot of a video element. (Only available for video elements)\n\n Inputs:\n\n * to: element where to save the snapshot of the video frame to\n * width: width of the image\n * height: height of the image\n\n Output:\n (Element) canvas element where the video frame snapshot was drawn into\n """\n if self._js.tagName != "VIDEO":\n raise AttributeError("Snap method is only available for video Elements")\n\n if to is None:\n canvas = self.create("canvas")\n if width is None:\n width = self._js.width\n if height is None:\n height = self._js.height\n canvas._js.width = width\n canvas._js.height = height\n\n elif isinstance(to, Element):\n if to._js.tagName != "CANVAS":\n raise TypeError("Element to snap to must a canvas.")\n canvas = to\n elif getattr(to, "tagName", "") == "CANVAS":\n canvas = Element(to)\n elif isinstance(to, str):\n # TODO (fpliger): This needs a better fix but doing a local import here for a quick fix\n from pyscript.web import dom\n\n canvas = dom[to][0]\n if canvas._js.tagName != "CANVAS":\n raise TypeError("Element to snap to must a be canvas.")\n\n canvas.draw(self, width, height)\n\n return canvas\n\n def download(self, filename: str = "snapped.png") -> None:\n """Download the current element (only available for canvas elements) with the filename\n provided in input.\n\n Inputs:\n * filename (str): name of the file being downloaded\n\n Output:\n None\n """\n if self._js.tagName != "CANVAS":\n raise AttributeError(\n "The download method is only available for canvas Elements"\n )\n\n link = self.create("a")\n link._js.download = filename\n link._js.href = self._js.toDataURL()\n link._js.click()\n\n def draw(self, what, width, height):\n """Draw `what` on the current element (only available for canvas elements).\n\n Inputs:\n\n * what (canvas image source): An element to draw into the context. The specification permits any canvas\n image source, specifically, an HTMLImageElement, an SVGImageElement, an HTMLVideoElement,\n an HTMLCanvasElement, an ImageBitmap, an OffscreenCanvas, or a VideoFrame.\n """\n if self._js.tagName != "CANVAS":\n raise AttributeError(\n "The draw method is only available for canvas Elements"\n )\n\n if isinstance(what, Element):\n what = what._js\n\n # https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage\n self._js.getContext("2d").drawImage(what, 0, 0, width, height)\n\n\nclass OptionsProxy:\n """This class represents the options of a select element. It\n allows to access to add and remove options by using the `add` and `remove` methods.\n """\n\n def __init__(self, element: Element) -> None:\n self._element = element\n if self._element._js.tagName.lower() != "select":\n raise AttributeError(\n f"Element {self._element._js.tagName} has no options attribute."\n )\n\n def add(\n self,\n value: Any = None,\n html: str = None,\n text: str = None,\n before: Element | int = None,\n **kws,\n ) -> None:\n """Add a new option to the select element"""\n # create the option element and set the attributes\n option = document.createElement("option")\n if value is not None:\n kws["value"] = value\n if html is not None:\n option.innerHTML = html\n if text is not None:\n kws["text"] = text\n\n for key, value in kws.items():\n option.setAttribute(key, value)\n\n if before:\n if isinstance(before, Element):\n before = before._js\n\n self._element._js.add(option, before)\n\n def remove(self, item: int) -> None:\n """Remove the option at the specified index"""\n self._element._js.remove(item)\n\n def clear(self) -> None:\n """Remove all the options"""\n for i in range(len(self)):\n self.remove(0)\n\n @property\n def options(self):\n """Return the list of options"""\n return [Element(opt) for opt in self._element._js.options]\n\n @property\n def selected(self):\n """Return the selected option"""\n return self.options[self._element._js.selectedIndex]\n\n def __iter__(self):\n yield from self.options\n\n def __len__(self):\n return len(self.options)\n\n def __repr__(self):\n return f"{self.__class__.__name__} (length: {len(self)}) {self.options}"\n\n def __getitem__(self, key):\n return self.options[key]\n\n\nclass StyleProxy: # (dict):\n def __init__(self, element: Element) -> None:\n self._element = element\n\n @cached_property\n def _style(self):\n return self._element._js.style\n\n def __getitem__(self, key):\n return self._style.getPropertyValue(key)\n\n def __setitem__(self, key, value):\n self._style.setProperty(key, value)\n\n def remove(self, key):\n self._style.removeProperty(key)\n\n def set(self, **kws):\n for k, v in kws.items():\n self._element._js.style.setProperty(k, v)\n\n # CSS Properties\n # Reference: https://github.com/microsoft/TypeScript/blob/main/src/lib/dom.generated.d.ts#L3799C1-L5005C2\n # Following prperties automatically generated from the above reference using\n # tools/codegen_css_proxy.py\n @property\n def visible(self):\n return self._element._js.style.visibility\n\n @visible.setter\n def visible(self, value):\n self._element._js.style.visibility = value\n\n\n# --------- END OF PYDOM STUFF ------\n\n\nclass ElementBase(Element):\n tag = "div"\n\n # GLOBAL ATTRIBUTES\n # These are attribute that all elements have (this list is a subset of the official one)\n # We are trying to capture the most used ones\n accesskey = JSProperty("accesskey")\n autofocus = JSProperty("autofocus")\n autocapitalize = JSProperty("autocapitalize")\n className = JSProperty("className")\n contenteditable = JSProperty("contenteditable")\n draggable = JSProperty("draggable")\n enterkeyhint = JSProperty("enterkeyhint")\n hidden = JSProperty("hidden")\n id = JSProperty("id")\n lang = JSProperty("lang")\n nonce = JSProperty("nonce")\n part = JSProperty("part")\n popover = JSProperty("popover")\n slot = JSProperty("slot")\n spellcheck = JSProperty("spellcheck")\n tabindex = JSProperty("tabindex")\n title = JSProperty("title")\n translate = JSProperty("translate")\n virtualkeyboardpolicy = JSProperty("virtualkeyboardpolicy")\n\n def __init__(self, style=None, **kwargs):\n super().__init__(document.createElement(self.tag))\n\n # set all the style properties provided in input\n if isinstance(style, dict):\n for key, value in style.items():\n self.style[key] = value\n elif style is None:\n pass\n else:\n raise ValueError(\n f"Style should be a dictionary, received {style} (type {type(style)}) instead."\n )\n\n # IMPORTANT!!! This is used to auto-harvest all input arguments and set them as properties\n self._init_properties(**kwargs)\n\n def _init_properties(self, **kwargs):\n """Set all the properties (of type JSProperties) provided in input as properties\n of the class instance.\n\n Args:\n **kwargs: The properties to set\n """\n # Look at all the properties of the class and see if they were provided in kwargs\n for attr_name, attr in getmembers_static(self.__class__):\n # For each one, actually check if it is a property of the class and set it\n if isinstance(attr, JSProperty) and attr_name in kwargs:\n try:\n setattr(self, attr_name, kwargs[attr_name])\n except Exception as e:\n print(f"Error setting {attr_name} to {kwargs[attr_name]}: {e}")\n raise\n\n\nclass TextElementBase(ElementBase):\n def __init__(self, content=None, style=None, **kwargs):\n super().__init__(style=style, **kwargs)\n\n # If it\'s an element, append the element\n if isinstance(content, Element):\n self.append(content)\n # If it\'s a list of elements\n elif isinstance(content, list):\n for item in content:\n self.append(item)\n # If the content wasn\'t set just ignore\n elif content is None:\n pass\n else:\n # Otherwise, set content as the html of the element\n self.html = content\n\n\n# IMPORTANT: For all HTML components defined below, we are not mapping all\n# available attributes, just the global and the most common ones.\n# If you need to access a specific attribute, you can always use the `_js.<attribute>`\nclass a(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a"""\n\n tag = "a"\n\n download = JSProperty("download")\n href = JSProperty("href")\n referrerpolicy = JSProperty("referrerpolicy")\n rel = JSProperty("rel")\n target = JSProperty("target")\n type = JSProperty("type")\n\n\nclass abbr(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/abbr"""\n\n tag = "abbr"\n\n\nclass address(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/address"""\n\n tag = "address"\n\n\nclass area(ElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area"""\n\n tag = "area"\n\n alt = JSProperty("alt")\n coords = JSProperty("coords")\n download = JSProperty("download")\n href = JSProperty("href")\n ping = JSProperty("ping")\n referrerpolicy = JSProperty("referrerpolicy")\n rel = JSProperty("rel")\n shape = JSProperty("shape")\n target = JSProperty("target")\n\n\nclass article(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/article"""\n\n tag = "article"\n\n\nclass aside(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/aside"""\n\n tag = "aside"\n\n\nclass audio(ElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio"""\n\n tag = "audio"\n\n autoplay = JSProperty("autoplay")\n controls = JSProperty("controls")\n controlslist = JSProperty("controlslist")\n crossorigin = JSProperty("crossorigin")\n disableremoteplayback = JSProperty("disableremoteplayback")\n loop = JSProperty("loop")\n muted = JSProperty("muted")\n preload = JSProperty("preload")\n src = JSProperty("src")\n\n\nclass b(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b"""\n\n tag = "b"\n\n\nclass blockquote(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote"""\n\n tag = "blockquote"\n\n cite = JSProperty("cite")\n\n\nclass br(ElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br"""\n\n tag = "br"\n\n\nclass button(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button"""\n\n tag = "button"\n\n autofocus = JSProperty("autofocus")\n disabled = JSProperty("disabled")\n form = JSProperty("form")\n formaction = JSProperty("formaction")\n formenctype = JSProperty("formenctype")\n formmethod = JSProperty("formmethod")\n formnovalidate = JSProperty("formnovalidate")\n formtarget = JSProperty("formtarget")\n name = JSProperty("name")\n type = JSProperty("type")\n value = JSProperty("value")\n\n\nclass canvas(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas"""\n\n tag = "canvas"\n\n height = JSProperty("height")\n width = JSProperty("width")\n\n\nclass caption(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption"""\n\n tag = "caption"\n\n\nclass cite(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/cite"""\n\n tag = "cite"\n\n\nclass code(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/code"""\n\n tag = "code"\n\n\nclass data(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/data"""\n\n tag = "data"\n\n value = JSProperty("value")\n\n\nclass datalist(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist"""\n\n tag = "datalist"\n\n\nclass dd(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dd"""\n\n tag = "dd"\n\n\nclass del_(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/del"""\n\n tag = "del"\n\n cite = JSProperty("cite")\n datetime = JSProperty("datetime")\n\n\nclass details(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details"""\n\n tag = "details"\n\n open = JSProperty("open")\n\n\nclass dialog(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog"""\n\n tag = "dialog"\n\n open = JSProperty("open")\n\n\nclass div(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div"""\n\n tag = "div"\n\n\nclass dl(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl"""\n\n tag = "dl"\n\n value = JSProperty("value")\n\n\nclass dt(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dt"""\n\n tag = "dt"\n\n\nclass em(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em"""\n\n tag = "em"\n\n\nclass embed(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed"""\n\n tag = "embed"\n\n height = JSProperty("height")\n src = JSProperty("src")\n type = JSProperty("type")\n width = JSProperty("width")\n\n\nclass fieldset(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset"""\n\n tag = "fieldset"\n\n disabled = JSProperty("disabled")\n form = JSProperty("form")\n name = JSProperty("name")\n\n\nclass figcaption(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figcaption"""\n\n tag = "figcaption"\n\n\nclass figure(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figure"""\n\n tag = "figure"\n\n\nclass footer(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/footer"""\n\n tag = "footer"\n\n\nclass form(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form"""\n\n tag = "form"\n\n accept_charset = JSProperty("accept-charset")\n action = JSProperty("action")\n autocapitalize = JSProperty("autocapitalize")\n autocomplete = JSProperty("autocomplete")\n enctype = JSProperty("enctype")\n name = JSProperty("name")\n method = JSProperty("method")\n nonvalidate = JSProperty("nonvalidate")\n rel = JSProperty("rel")\n target = JSProperty("target")\n\n\nclass h1(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h1"""\n\n tag = "h1"\n\n\nclass h2(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h2"""\n\n tag = "h2"\n\n\nclass h3(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h3"""\n\n tag = "h3"\n\n\nclass h4(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h4"""\n\n tag = "h4"\n\n\nclass h5(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h5"""\n\n tag = "h5"\n\n\nclass h6(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h6"""\n\n tag = "h6"\n\n\nclass header(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/header"""\n\n tag = "header"\n\n\nclass hgroup(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hgroup"""\n\n tag = "hgroup"\n\n\nclass hr(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hr"""\n\n tag = "hr"\n\n\nclass i(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i"""\n\n tag = "i"\n\n\nclass iframe(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe"""\n\n tag = "iframe"\n\n allow = JSProperty("allow")\n allowfullscreen = JSProperty("allowfullscreen")\n height = JSProperty("height")\n loading = JSProperty("loading")\n name = JSProperty("name")\n referrerpolicy = JSProperty("referrerpolicy")\n sandbox = JSProperty("sandbox")\n src = JSProperty("src")\n srcdoc = JSProperty("srcdoc")\n width = JSProperty("width")\n\n\nclass img(ElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img"""\n\n tag = "img"\n\n alt = JSProperty("alt")\n crossorigin = JSProperty("crossorigin")\n decoding = JSProperty("decoding")\n fetchpriority = JSProperty("fetchpriority")\n height = JSProperty("height")\n ismap = JSProperty("ismap")\n loading = JSProperty("loading")\n referrerpolicy = JSProperty("referrerpolicy")\n sizes = JSProperty("sizes")\n src = JSProperty("src")\n width = JSProperty("width")\n\n\n# NOTE: Input is a reserved keyword in Python, so we use input_ instead\nclass input_(ElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input"""\n\n tag = "input"\n\n accept = JSProperty("accept")\n alt = JSProperty("alt")\n autofocus = JSProperty("autofocus")\n capture = JSProperty("capture")\n checked = JSProperty("checked")\n dirname = JSProperty("dirname")\n disabled = JSProperty("disabled")\n form = JSProperty("form")\n formaction = JSProperty("formaction")\n formenctype = JSProperty("formenctype")\n formmethod = JSProperty("formmethod")\n formnovalidate = JSProperty("formnovalidate")\n formtarget = JSProperty("formtarget")\n height = JSProperty("height")\n list = JSProperty("list")\n max = JSProperty("max")\n maxlength = JSProperty("maxlength")\n min = JSProperty("min")\n minlength = JSProperty("minlength")\n multiple = JSProperty("multiple")\n name = JSProperty("name")\n pattern = JSProperty("pattern")\n placeholder = JSProperty("placeholder")\n popovertarget = JSProperty("popovertarget")\n popovertargetaction = JSProperty("popovertargetaction")\n readonly = JSProperty("readonly")\n required = JSProperty("required")\n size = JSProperty("size")\n src = JSProperty("src")\n step = JSProperty("step")\n type = JSProperty("type")\n value = JSProperty("value")\n width = JSProperty("width")\n\n\nclass ins(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ins"""\n\n tag = "ins"\n\n cite = JSProperty("cite")\n datetime = JSProperty("datetime")\n\n\nclass kbd(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/kbd"""\n\n tag = "kbd"\n\n\nclass label(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label"""\n\n tag = "label"\n\n for_ = JSProperty("for")\n\n\nclass legend(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/legend"""\n\n tag = "legend"\n\n\nclass li(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li"""\n\n tag = "li"\n\n value = JSProperty("value")\n\n\nclass link(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link"""\n\n tag = "link"\n\n as_ = JSProperty("as")\n crossorigin = JSProperty("crossorigin")\n disabled = JSProperty("disabled")\n fetchpriority = JSProperty("fetchpriority")\n href = JSProperty("href")\n imagesizes = JSProperty("imagesizes")\n imagesrcset = JSProperty("imagesrcset")\n integrity = JSProperty("integrity")\n media = JSProperty("media")\n rel = JSProperty("rel")\n referrerpolicy = JSProperty("referrerpolicy")\n sizes = JSProperty("sizes")\n title = JSProperty("title")\n type = JSProperty("type")\n\n\nclass main(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/main"""\n\n tag = "main"\n\n\nclass map_(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map"""\n\n tag = "map"\n\n name = JSProperty("name")\n\n\nclass mark(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/mark"""\n\n tag = "mark"\n\n\nclass menu(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/menu"""\n\n tag = "menu"\n\n\nclass meter(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter"""\n\n tag = "meter"\n\n form = JSProperty("form")\n high = JSProperty("high")\n low = JSProperty("low")\n max = JSProperty("max")\n min = JSProperty("min")\n optimum = JSProperty("optimum")\n value = JSProperty("value")\n\n\nclass nav(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/nav"""\n\n tag = "nav"\n\n\nclass object_(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object"""\n\n tag = "object"\n\n data = JSProperty("data")\n form = JSProperty("form")\n height = JSProperty("height")\n name = JSProperty("name")\n type = JSProperty("type")\n usemap = JSProperty("usemap")\n width = JSProperty("width")\n\n\nclass ol(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol"""\n\n tag = "ol"\n\n reversed = JSProperty("reversed")\n start = JSProperty("start")\n type = JSProperty("type")\n\n\nclass optgroup(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup"""\n\n tag = "optgroup"\n\n disabled = JSProperty("disabled")\n label = JSProperty("label")\n\n\nclass option(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option"""\n\n tag = "option"\n\n disabled = JSProperty("value")\n label = JSProperty("label")\n selected = JSProperty("selected")\n value = JSProperty("value")\n\n\nclass output(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output"""\n\n tag = "output"\n\n for_ = JSProperty("for")\n form = JSProperty("form")\n name = JSProperty("name")\n\n\nclass p(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p"""\n\n tag = "p"\n\n\nclass picture(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture"""\n\n tag = "picture"\n\n\nclass pre(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre"""\n\n tag = "pre"\n\n\nclass progress(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress"""\n\n tag = "progress"\n\n max = JSProperty("max")\n value = JSProperty("value")\n\n\nclass q(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q"""\n\n tag = "q"\n\n cite = JSProperty("cite")\n\n\nclass s(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/s"""\n\n tag = "s"\n\n\nclass script(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script"""\n\n tag = "script"\n\n # Let\'s add async manually since it\'s a reserved keyword in Python\n async_ = JSProperty("async")\n blocking = JSProperty("blocking")\n crossorigin = JSProperty("crossorigin")\n defer = JSProperty("defer")\n fetchpriority = JSProperty("fetchpriority")\n integrity = JSProperty("integrity")\n nomodule = JSProperty("nomodule")\n nonce = JSProperty("nonce")\n referrerpolicy = JSProperty("referrerpolicy")\n src = JSProperty("src")\n type = JSProperty("type")\n\n\nclass section(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/section"""\n\n tag = "section"\n\n\nclass select(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select"""\n\n tag = "select"\n\n\nclass small(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/small"""\n\n tag = "small"\n\n\nclass source(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source"""\n\n tag = "source"\n\n media = JSProperty("media")\n sizes = JSProperty("sizes")\n src = JSProperty("src")\n srcset = JSProperty("srcset")\n type = JSProperty("type")\n\n\nclass span(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span"""\n\n tag = "span"\n\n\nclass strong(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strong"""\n\n tag = "strong"\n\n\nclass style(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style"""\n\n tag = "style"\n\n blocking = JSProperty("blocking")\n media = JSProperty("media")\n nonce = JSProperty("nonce")\n title = JSProperty("title")\n\n\nclass sub(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sub"""\n\n tag = "sub"\n\n\nclass summary(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/summary"""\n\n tag = "summary"\n\n\nclass sup(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sup"""\n\n tag = "sup"\n\n\nclass table(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table"""\n\n tag = "table"\n\n\nclass tbody(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody"""\n\n tag = "tbody"\n\n\nclass td(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td"""\n\n tag = "td"\n\n colspan = JSProperty("colspan")\n headers = JSProperty("headers")\n rowspan = JSProperty("rowspan")\n\n\nclass template(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template"""\n\n tag = "template"\n\n shadowrootmode = JSProperty("shadowrootmode")\n\n\nclass textarea(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea"""\n\n tag = "textarea"\n\n autocapitalize = JSProperty("autocapitalize")\n autocomplete = JSProperty("autocomplete")\n autofocus = JSProperty("autofocus")\n cols = JSProperty("cols")\n dirname = JSProperty("dirname")\n disabled = JSProperty("disabled")\n form = JSProperty("form")\n maxlength = JSProperty("maxlength")\n minlength = JSProperty("minlength")\n name = JSProperty("name")\n placeholder = JSProperty("placeholder")\n readonly = JSProperty("readonly")\n required = JSProperty("required")\n rows = JSProperty("rows")\n spellcheck = JSProperty("spellcheck")\n wrap = JSProperty("wrap")\n\n\nclass tfoot(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tfoot"""\n\n tag = "tfoot"\n\n\nclass th(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th"""\n\n tag = "th"\n\n\nclass thead(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead"""\n\n tag = "thead"\n\n\nclass time(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/time"""\n\n tag = "time"\n\n datetime = JSProperty("datetime")\n\n\nclass title(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title"""\n\n tag = "title"\n\n\nclass tr(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr"""\n\n tag = "tr"\n\n abbr = JSProperty("abbr")\n colspan = JSProperty("colspan")\n headers = JSProperty("headers")\n rowspan = JSProperty("rowspan")\n scope = JSProperty("scope")\n\n\nclass track(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track"""\n\n tag = "track"\n\n default = JSProperty("default")\n kind = JSProperty("kind")\n label = JSProperty("label")\n src = JSProperty("src")\n srclang = JSProperty("srclang")\n\n\nclass u(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/u"""\n\n tag = "u"\n\n\nclass ul(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul"""\n\n tag = "ul"\n\n\nclass var(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/var"""\n\n tag = "var"\n\n\nclass video(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video"""\n\n tag = "video"\n\n autoplay = JSProperty("autoplay")\n controls = JSProperty("controls")\n crossorigin = JSProperty("crossorigin")\n disablepictureinpicture = JSProperty("disablepictureinpicture")\n disableremoteplayback = JSProperty("disableremoteplayback")\n height = JSProperty("height")\n loop = JSProperty("loop")\n muted = JSProperty("muted")\n playsinline = JSProperty("playsinline")\n poster = JSProperty("poster")\n preload = JSProperty("preload")\n src = JSProperty("src")\n width = JSProperty("width")\n\n\n# Custom Elements\nclass grid(TextElementBase):\n tag = "div"\n\n def __init__(self, layout, content=None, gap=None, **kwargs):\n super().__init__(content, **kwargs)\n self.style["display"] = "grid"\n self.style["grid-template-columns"] = layout\n\n # TODO: This should be a property\n if not gap is None:\n self.style["gap"] = gap\n\n\nclass StyleCollection:\n def __init__(self, collection: "ElementCollection") -> None:\n self._collection = collection\n\n def __get__(self, obj, objtype=None):\n return obj._get_attribute("style")\n\n def __getitem__(self, key):\n return self._collection._get_attribute("style")[key]\n\n def __setitem__(self, key, value):\n for element in self._collection._elements:\n element.style[key] = value\n\n def remove(self, key):\n for element in self._collection._elements:\n element.style.remove(key)\n\n\nclass ElementCollection:\n def __init__(self, elements: [Element]) -> None:\n self._elements = elements\n self.style = StyleCollection(self)\n\n def __getitem__(self, key):\n # If it\'s an integer we use it to access the elements in the collection\n if isinstance(key, int):\n return self._elements[key]\n # If it\'s a slice we use it to support slice operations over the elements\n # in the collection\n elif isinstance(key, slice):\n return ElementCollection(self._elements[key])\n\n # If it\'s anything else (basically a string) we use it as a selector\n # TODO: Write tests!\n elements = self._element.querySelectorAll(key)\n return ElementCollection([Element(el) for el in elements])\n\n def __len__(self):\n return len(self._elements)\n\n def __eq__(self, obj):\n """Check if the element is the same as the other element by comparing\n the underlying JS element"""\n return isinstance(obj, ElementCollection) and obj._elements == self._elements\n\n def _get_attribute(self, attr, index=None):\n if index is None:\n return [getattr(el, attr) for el in self._elements]\n\n # As JQuery, when getting an attr, only return it for the first element\n return getattr(self._elements[index], attr)\n\n def _set_attribute(self, attr, value):\n for el in self._elements:\n setattr(el, attr, value)\n\n @property\n def html(self):\n return self._get_attribute("html")\n\n @html.setter\n def html(self, value):\n self._set_attribute("html", value)\n\n @property\n def value(self):\n return self._get_attribute("value")\n\n @value.setter\n def value(self, value):\n self._set_attribute("value", value)\n\n @property\n def children(self):\n return self._elements\n\n def __iter__(self):\n yield from self._elements\n\n def __repr__(self):\n return f"{self.__class__.__name__} (length: {len(self._elements)}) {self._elements}"\n',"media.py":'from pyodide.ffi import to_js\nfrom pyscript import window\n\n\nclass Device:\n """Device represents a media input or output device, such as a microphone,\n camera, or headset.\n """\n\n def __init__(self, device):\n self._js = device\n\n @property\n def id(self):\n return self._js.deviceId\n\n @property\n def group(self):\n return self._js.groupId\n\n @property\n def kind(self):\n return self._js.kind\n\n @property\n def label(self):\n return self._js.label\n\n def __getitem__(self, key):\n return getattr(self, key)\n\n @classmethod\n async def load(cls, audio=False, video=True):\n """Load the device stream."""\n options = window.Object.new()\n options.audio = audio\n if isinstance(video, bool):\n options.video = video\n else:\n # TODO: Think this can be simplified but need to check it on the pyodide side\n\n # TODO: this is pyodide specific. shouldn\'t be!\n options.video = window.Object.new()\n for k in video:\n setattr(\n options.video,\n k,\n to_js(video[k], dict_converter=window.Object.fromEntries),\n )\n\n stream = await window.navigator.mediaDevices.getUserMedia(options)\n return stream\n\n async def get_stream(self):\n key = self.kind.replace("input", "").replace("output", "")\n options = {key: {"deviceId": {"exact": self.id}}}\n\n return await self.load(**options)\n\n\nasync def list_devices() -> list[dict]:\n """\n Return the list of the currently available media input and output devices,\n such as microphones, cameras, headsets, and so forth.\n\n Output:\n\n list(dict) - list of dictionaries representing the available media devices.\n Each dictionary has the following keys:\n * deviceId: a string that is an identifier for the represented device\n that is persisted across sessions. It is un-guessable by other\n applications and unique to the origin of the calling application.\n It is reset when the user clears cookies (for Private Browsing, a\n different identifier is used that is not persisted across sessions).\n\n * groupId: a string that is a group identifier. Two devices have the same\n group identifier if they belong to the same physical device — for\n example a monitor with both a built-in camera and a microphone.\n\n * kind: an enumerated value that is either "videoinput", "audioinput"\n or "audiooutput".\n\n * label: a string describing this device (for example "External USB\n Webcam").\n\n Note: the returned list will omit any devices that are blocked by the document\n Permission Policy: microphone, camera, speaker-selection (for output devices),\n and so on. Access to particular non-default devices is also gated by the\n Permissions API, and the list will omit devices for which the user has not\n granted explicit permission.\n """\n # https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices\n return [\n Device(obj) for obj in await window.navigator.mediaDevices.enumerateDevices()\n ]\n'},"websocket.py":'import js\nfrom pyscript.util import as_bytearray\n\ncode = "code"\nprotocols = "protocols"\nreason = "reason"\n\n\nclass EventMessage:\n def __init__(self, event):\n self._event = event\n\n def __getattr__(self, attr):\n value = getattr(self._event, attr)\n\n if attr == "data" and not isinstance(value, str):\n if hasattr(value, "to_py"):\n return value.to_py()\n # shims in MicroPython\n return memoryview(as_bytearray(value))\n\n return value\n\n\nclass WebSocket(object):\n CONNECTING = 0\n OPEN = 1\n CLOSING = 2\n CLOSED = 3\n\n def __init__(self, **kw):\n url = kw["url"]\n if protocols in kw:\n socket = js.WebSocket.new(url, kw[protocols])\n else:\n socket = js.WebSocket.new(url)\n object.__setattr__(self, "_ws", socket)\n\n for t in ["onclose", "onerror", "onmessage", "onopen"]:\n if t in kw:\n socket[t] = kw[t]\n\n def __getattr__(self, attr):\n return getattr(self._ws, attr)\n\n def __setattr__(self, attr, value):\n if attr == "onmessage":\n self._ws[attr] = lambda e: value(EventMessage(e))\n else:\n self._ws[attr] = value\n\n def close(self, **kw):\n if code in kw and reason in kw:\n self._ws.close(kw[code], kw[reason])\n elif code in kw:\n self._ws.close(kw[code])\n else:\n self._ws.close()\n\n def send(self, data):\n if isinstance(data, str):\n self._ws.send(data)\n else:\n buffer = js.Uint8Array.new(len(data))\n for pos, b in enumerate(data):\n buffer[pos] = b\n self._ws.send(buffer)\n',"workers.py":"import js as _js\n\nfrom polyscript import workers as _workers\n\n_get = _js.Reflect.get\n\n# this solves an inconsistency between Pyodide and MicroPython\n# @see https://github.com/pyscript/pyscript/issues/2106\nclass _ReadOnlyProxy:\n def __getitem__(self, name):\n return _get(_workers, name)\n def __getattr__(self, name):\n return _get(_workers, name)\n\nworkers = _ReadOnlyProxy()\n"},pyweb:{"__init__.py":"from .pydom import JSProperty\nfrom .pydom import dom as pydom\n","media.py":'from pyodide.ffi import to_js\nfrom pyscript import window\n\n\nclass Device:\n """Device represents a media input or output device, such as a microphone,\n camera, or headset.\n """\n\n def __init__(self, device):\n self._js = device\n\n @property\n def id(self):\n return self._js.deviceId\n\n @property\n def group(self):\n return self._js.groupId\n\n @property\n def kind(self):\n return self._js.kind\n\n @property\n def label(self):\n return self._js.label\n\n def __getitem__(self, key):\n return getattr(self, key)\n\n @classmethod\n async def load(cls, audio=False, video=True):\n """Load the device stream."""\n options = window.Object.new()\n options.audio = audio\n if isinstance(video, bool):\n options.video = video\n else:\n # TODO: Think this can be simplified but need to check it on the pyodide side\n\n # TODO: this is pyodide specific. shouldn\'t be!\n options.video = window.Object.new()\n for k in video:\n setattr(\n options.video,\n k,\n to_js(video[k], dict_converter=window.Object.fromEntries),\n )\n\n stream = await window.navigator.mediaDevices.getUserMedia(options)\n return stream\n\n async def get_stream(self):\n key = self.kind.replace("input", "").replace("output", "")\n options = {key: {"deviceId": {"exact": self.id}}}\n\n return await self.load(**options)\n\n\nasync def list_devices() -> list[dict]:\n """\n Return the list of the currently available media input and output devices,\n such as microphones, cameras, headsets, and so forth.\n\n Output:\n\n list(dict) - list of dictionaries representing the available media devices.\n Each dictionary has the following keys:\n * deviceId: a string that is an identifier for the represented device\n that is persisted across sessions. It is un-guessable by other\n applications and unique to the origin of the calling application.\n It is reset when the user clears cookies (for Private Browsing, a\n different identifier is used that is not persisted across sessions).\n\n * groupId: a string that is a group identifier. Two devices have the same\n group identifier if they belong to the same physical device — for\n example a monitor with both a built-in camera and a microphone.\n\n * kind: an enumerated value that is either "videoinput", "audioinput"\n or "audiooutput".\n\n * label: a string describing this device (for example "External USB\n Webcam").\n\n Note: the returned list will omit any devices that are blocked by the document\n Permission Policy: microphone, camera, speaker-selection (for output devices),\n and so on. Access to particular non-default devices is also gated by the\n Permissions API, and the list will omit devices for which the user has not\n granted explicit permission.\n """\n # https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices\n return [\n Device(obj) for obj in await window.navigator.mediaDevices.enumerateDevices()\n ]\n',"pydom.py":'import inspect\n\ntry:\n from typing import Any\nexcept ImportError:\n Any = "Any"\n\ntry:\n import warnings\nexcept ImportError:\n # TODO: For now it probably means we are in MicroPython. We should figure\n # out the "right" way to handle this. For now we just ignore the warning\n # and logging to console\n class warnings:\n @staticmethod\n def warn(*args, **kwargs):\n print("WARNING: ", *args, **kwargs)\n\n\ntry:\n from functools import cached_property\nexcept ImportError:\n # TODO: same comment about micropython as above\n cached_property = property\n\ntry:\n from pyodide.ffi import JsProxy\nexcept ImportError:\n # TODO: same comment about micropython as above\n def JsProxy(obj):\n return obj\n\n\nfrom pyscript import display, document, window\n\nalert = window.alert\n\n\nclass JSProperty:\n """JS property descriptor that directly maps to the property with the same\n name in the underlying JS component."""\n\n def __init__(self, name: str, allow_nones: bool = False):\n self.name = name\n self.allow_nones = allow_nones\n\n def __get__(self, obj, objtype=None):\n return getattr(obj._js, self.name)\n\n def __set__(self, obj, value):\n if not self.allow_nones and value is None:\n return\n setattr(obj._js, self.name, value)\n\n\nclass BaseElement:\n def __init__(self, js_element):\n self._js = js_element\n self._parent = None\n self.style = StyleProxy(self)\n self._proxies = {}\n\n def __eq__(self, obj):\n """Check if the element is the same as the other element by comparing\n the underlying JS element"""\n return isinstance(obj, BaseElement) and obj._js == self._js\n\n @property\n def parent(self):\n if self._parent:\n return self._parent\n\n if self._js.parentElement:\n self._parent = self.__class__(self._js.parentElement)\n\n return self._parent\n\n @property\n def __class(self):\n return self.__class__ if self.__class__ != PyDom else Element\n\n def create(self, type_, is_child=True, classes=None, html=None, label=None):\n js_el = document.createElement(type_)\n element = self.__class(js_el)\n\n if classes:\n for class_ in classes:\n element.add_class(class_)\n\n if html is not None:\n element.html = html\n\n if label is not None:\n element.label = label\n\n if is_child:\n self.append(element)\n\n return element\n\n def find(self, selector):\n """Return an ElementCollection representing all the child elements that\n match the specified selector.\n\n Args:\n selector (str): A string containing a selector expression\n\n Returns:\n ElementCollection: A collection of elements matching the selector\n """\n elements = self._js.querySelectorAll(selector)\n if not elements:\n return None\n return ElementCollection([Element(el) for el in elements])\n\n\nclass Element(BaseElement):\n @property\n def children(self):\n return [self.__class__(el) for el in self._js.children]\n\n def append(self, child):\n # TODO: this is Pyodide specific for now!!!!!!\n # if we get passed a JSProxy Element directly we just map it to the\n # higher level Python element\n if inspect.isclass(JsProxy) and isinstance(child, JsProxy):\n return self.append(Element(child))\n\n elif isinstance(child, Element):\n self._js.appendChild(child._js)\n\n return child\n\n elif isinstance(child, ElementCollection):\n for el in child:\n self.append(el)\n\n # -------- Pythonic Interface to Element -------- #\n @property\n def html(self):\n return self._js.innerHTML\n\n @html.setter\n def html(self, value):\n self._js.innerHTML = value\n\n @property\n def text(self):\n return self._js.textContent\n\n @text.setter\n def text(self, value):\n self._js.textContent = value\n\n @property\n def content(self):\n # TODO: This breaks with with standard template elements. Define how to best\n # handle this specifica use case. Just not support for now?\n if self._js.tagName == "TEMPLATE":\n warnings.warn(\n "Content attribute not supported for template elements.", stacklevel=2\n )\n return None\n return self._js.innerHTML\n\n @content.setter\n def content(self, value):\n # TODO: (same comment as above)\n if self._js.tagName == "TEMPLATE":\n warnings.warn(\n "Content attribute not supported for template elements.", stacklevel=2\n )\n return\n\n display(value, target=self.id)\n\n @property\n def id(self):\n return self._js.id\n\n @id.setter\n def id(self, value):\n self._js.id = value\n\n @property\n def options(self):\n if "options" in self._proxies:\n return self._proxies["options"]\n\n if not self._js.tagName.lower() in {"select", "datalist", "optgroup"}:\n raise AttributeError(\n f"Element {self._js.tagName} has no options attribute."\n )\n self._proxies["options"] = OptionsProxy(self)\n return self._proxies["options"]\n\n @property\n def value(self):\n return self._js.value\n\n @value.setter\n def value(self, value):\n # in order to avoid confusion to the user, we don\'t allow setting the\n # value of elements that don\'t have a value attribute\n if not hasattr(self._js, "value"):\n raise AttributeError(\n f"Element {self._js.tagName} has no value attribute. If you want to "\n "force a value attribute, set it directly using the `_js.value = <value>` "\n "javascript API attribute instead."\n )\n self._js.value = value\n\n @property\n def selected(self):\n return self._js.selected\n\n @selected.setter\n def selected(self, value):\n # in order to avoid confusion to the user, we don\'t allow setting the\n # value of elements that don\'t have a value attribute\n if not hasattr(self._js, "selected"):\n raise AttributeError(\n f"Element {self._js.tagName} has no value attribute. If you want to "\n "force a value attribute, set it directly using the `_js.value = <value>` "\n "javascript API attribute instead."\n )\n self._js.selected = value\n\n def clone(self, new_id=None):\n clone = Element(self._js.cloneNode(True))\n clone.id = new_id\n\n return clone\n\n def remove_class(self, classname):\n classList = self._js.classList\n if isinstance(classname, list):\n classList.remove(*classname)\n else:\n classList.remove(classname)\n return self\n\n def add_class(self, classname):\n classList = self._js.classList\n if isinstance(classname, list):\n classList.add(*classname)\n else:\n self._js.classList.add(classname)\n return self\n\n @property\n def classes(self):\n classes = self._js.classList.values()\n return [x for x in classes]\n\n def show_me(self):\n self._js.scrollIntoView()\n\n def snap(\n self,\n to: BaseElement | str = None,\n width: int | None = None,\n height: int | None = None,\n ):\n """\n Captures a snapshot of a video element. (Only available for video elements)\n\n Inputs:\n\n * to: element where to save the snapshot of the video frame to\n * width: width of the image\n * height: height of the image\n\n Output:\n (Element) canvas element where the video frame snapshot was drawn into\n """\n if self._js.tagName != "VIDEO":\n raise AttributeError("Snap method is only available for video Elements")\n\n if to is None:\n canvas = self.create("canvas")\n if width is None:\n width = self._js.width\n if height is None:\n height = self._js.height\n canvas._js.width = width\n canvas._js.height = height\n\n elif isinstance(to, Element):\n if to._js.tagName != "CANVAS":\n raise TypeError("Element to snap to must a canvas.")\n canvas = to\n elif getattr(to, "tagName", "") == "CANVAS":\n canvas = Element(to)\n elif isinstance(to, str):\n canvas = pydom[to][0]\n if canvas._js.tagName != "CANVAS":\n raise TypeError("Element to snap to must a be canvas.")\n\n canvas.draw(self, width, height)\n\n return canvas\n\n def download(self, filename: str = "snapped.png") -> None:\n """Download the current element (only available for canvas elements) with the filename\n provided in input.\n\n Inputs:\n * filename (str): name of the file being downloaded\n\n Output:\n None\n """\n if self._js.tagName != "CANVAS":\n raise AttributeError(\n "The download method is only available for canvas Elements"\n )\n\n link = self.create("a")\n link._js.download = filename\n link._js.href = self._js.toDataURL()\n link._js.click()\n\n def draw(self, what, width, height):\n """Draw `what` on the current element (only available for canvas elements).\n\n Inputs:\n\n * what (canvas image source): An element to draw into the context. The specification permits any canvas\n image source, specifically, an HTMLImageElement, an SVGImageElement, an HTMLVideoElement,\n an HTMLCanvasElement, an ImageBitmap, an OffscreenCanvas, or a VideoFrame.\n """\n if self._js.tagName != "CANVAS":\n raise AttributeError(\n "The draw method is only available for canvas Elements"\n )\n\n if isinstance(what, Element):\n what = what._js\n\n # https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage\n self._js.getContext("2d").drawImage(what, 0, 0, width, height)\n\n\nclass OptionsProxy:\n """This class represents the options of a select element. It\n allows to access to add and remove options by using the `add` and `remove` methods.\n """\n\n def __init__(self, element: Element) -> None:\n self._element = element\n if self._element._js.tagName.lower() != "select":\n raise AttributeError(\n f"Element {self._element._js.tagName} has no options attribute."\n )\n\n def add(\n self,\n value: Any = None,\n html: str = None,\n text: str = None,\n before: Element | int = None,\n **kws,\n ) -> None:\n """Add a new option to the select element"""\n # create the option element and set the attributes\n option = document.createElement("option")\n if value is not None:\n kws["value"] = value\n if html is not None:\n option.innerHTML = html\n if text is not None:\n kws["text"] = text\n\n for key, value in kws.items():\n option.setAttribute(key, value)\n\n if before:\n if isinstance(before, Element):\n before = before._js\n\n self._element._js.add(option, before)\n\n def remove(self, item: int) -> None:\n """Remove the option at the specified index"""\n self._element._js.remove(item)\n\n def clear(self) -> None:\n """Remove all the options"""\n for i in range(len(self)):\n self.remove(0)\n\n @property\n def options(self):\n """Return the list of options"""\n return [Element(opt) for opt in self._element._js.options]\n\n @property\n def selected(self):\n """Return the selected option"""\n return self.options[self._element._js.selectedIndex]\n\n def __iter__(self):\n yield from self.options\n\n def __len__(self):\n return len(self.options)\n\n def __repr__(self):\n return f"{self.__class__.__name__} (length: {len(self)}) {self.options}"\n\n def __getitem__(self, key):\n return self.options[key]\n\n\nclass StyleProxy: # (dict):\n def __init__(self, element: Element) -> None:\n self._element = element\n\n @cached_property\n def _style(self):\n return self._element._js.style\n\n def __getitem__(self, key):\n return self._style.getPropertyValue(key)\n\n def __setitem__(self, key, value):\n self._style.setProperty(key, value)\n\n def remove(self, key):\n self._style.removeProperty(key)\n\n def set(self, **kws):\n for k, v in kws.items():\n self._element._js.style.setProperty(k, v)\n\n # CSS Properties\n # Reference: https://github.com/microsoft/TypeScript/blob/main/src/lib/dom.generated.d.ts#L3799C1-L5005C2\n # Following prperties automatically generated from the above reference using\n # tools/codegen_css_proxy.py\n @property\n def visible(self):\n return self._element._js.style.visibility\n\n @visible.setter\n def visible(self, value):\n self._element._js.style.visibility = value\n\n\nclass StyleCollection:\n def __init__(self, collection: "ElementCollection") -> None:\n self._collection = collection\n\n def __get__(self, obj, objtype=None):\n return obj._get_attribute("style")\n\n def __getitem__(self, key):\n return self._collection._get_attribute("style")[key]\n\n def __setitem__(self, key, value):\n for element in self._collection._elements:\n element.style[key] = value\n\n def remove(self, key):\n for element in self._collection._elements:\n element.style.remove(key)\n\n\nclass ElementCollection:\n def __init__(self, elements: [Element]) -> None:\n self._elements = elements\n self.style = StyleCollection(self)\n\n def __getitem__(self, key):\n # If it\'s an integer we use it to access the elements in the collection\n if isinstance(key, int):\n return self._elements[key]\n # If it\'s a slice we use it to support slice operations over the elements\n # in the collection\n elif isinstance(key, slice):\n return ElementCollection(self._elements[key])\n\n # If it\'s anything else (basically a string) we use it as a selector\n # TODO: Write tests!\n elements = self._element.querySelectorAll(key)\n return ElementCollection([Element(el) for el in elements])\n\n def __len__(self):\n return len(self._elements)\n\n def __eq__(self, obj):\n """Check if the element is the same as the other element by comparing\n the underlying JS element"""\n return isinstance(obj, ElementCollection) and obj._elements == self._elements\n\n def _get_attribute(self, attr, index=None):\n if index is None:\n return [getattr(el, attr) for el in self._elements]\n\n # As JQuery, when getting an attr, only return it for the first element\n return getattr(self._elements[index], attr)\n\n def _set_attribute(self, attr, value):\n for el in self._elements:\n setattr(el, attr, value)\n\n @property\n def html(self):\n return self._get_attribute("html")\n\n @html.setter\n def html(self, value):\n self._set_attribute("html", value)\n\n @property\n def value(self):\n return self._get_attribute("value")\n\n @value.setter\n def value(self, value):\n self._set_attribute("value", value)\n\n @property\n def children(self):\n return self._elements\n\n def __iter__(self):\n yield from self._elements\n\n def __repr__(self):\n return f"{self.__class__.__name__} (length: {len(self._elements)}) {self._elements}"\n\n\nclass DomScope:\n def __getattr__(self, __name: str):\n element = document[f"#{__name}"]\n if element:\n return element[0]\n\n\nclass PyDom(BaseElement):\n # Add objects we want to expose to the DOM namespace since this class instance is being\n # remapped as "the module" itself\n BaseElement = BaseElement\n Element = Element\n ElementCollection = ElementCollection\n\n def __init__(self):\n # PyDom is a special case of BaseElement where we don\'t want to create a new JS element\n # and it really doesn\'t have a need for styleproxy or parent to to call to __init__\n # (which actually fails in MP for some reason)\n self._js = document\n self._parent = None\n self._proxies = {}\n self.ids = DomScope()\n self.body = Element(document.body)\n self.head = Element(document.head)\n\n def create(self, type_, classes=None, html=None):\n return super().create(type_, is_child=False, classes=classes, html=html)\n\n def __getitem__(self, key):\n elements = self._js.querySelectorAll(key)\n if not elements:\n return None\n return ElementCollection([Element(el) for el in elements])\n\n\ndom = PyDom()\n',ui:{"__init__.py":"from . import elements\n","elements.py":'import inspect\nimport sys\n\nfrom pyscript import document, when, window\nfrom pyweb import JSProperty, pydom\n\n#: A flag to show if MicroPython is the current Python interpreter.\nis_micropython = "MicroPython" in sys.version\n\n\ndef getmembers_static(cls):\n """Cross-interpreter implementation of inspect.getmembers_static."""\n\n if is_micropython: # pragma: no cover\n return [(name, getattr(cls, name)) for name, _ in inspect.getmembers(cls)]\n\n return inspect.getmembers_static(cls)\n\n\nclass ElementBase(pydom.Element):\n tag = "div"\n\n # GLOBAL ATTRIBUTES\n # These are attribute that all elements have (this list is a subset of the official one)\n # We are trying to capture the most used ones\n accesskey = JSProperty("accesskey")\n autofocus = JSProperty("autofocus")\n autocapitalize = JSProperty("autocapitalize")\n className = JSProperty("className")\n contenteditable = JSProperty("contenteditable")\n draggable = JSProperty("draggable")\n enterkeyhint = JSProperty("enterkeyhint")\n hidden = JSProperty("hidden")\n id = JSProperty("id")\n lang = JSProperty("lang")\n nonce = JSProperty("nonce")\n part = JSProperty("part")\n popover = JSProperty("popover")\n slot = JSProperty("slot")\n spellcheck = JSProperty("spellcheck")\n tabindex = JSProperty("tabindex")\n title = JSProperty("title")\n translate = JSProperty("translate")\n virtualkeyboardpolicy = JSProperty("virtualkeyboardpolicy")\n\n def __init__(self, style=None, **kwargs):\n super().__init__(document.createElement(self.tag))\n\n # set all the style properties provided in input\n if isinstance(style, dict):\n for key, value in style.items():\n self.style[key] = value\n elif style is None:\n pass\n else:\n raise ValueError(\n f"Style should be a dictionary, received {style} (type {type(style)}) instead."\n )\n\n # IMPORTANT!!! This is used to auto-harvest all input arguments and set them as properties\n self._init_properties(**kwargs)\n\n def _init_properties(self, **kwargs):\n """Set all the properties (of type JSProperties) provided in input as properties\n of the class instance.\n\n Args:\n **kwargs: The properties to set\n """\n # Look at all the properties of the class and see if they were provided in kwargs\n for attr_name, attr in getmembers_static(self.__class__):\n # For each one, actually check if it is a property of the class and set it\n if isinstance(attr, JSProperty) and attr_name in kwargs:\n try:\n setattr(self, attr_name, kwargs[attr_name])\n except Exception as e:\n print(f"Error setting {attr_name} to {kwargs[attr_name]}: {e}")\n raise\n\n\nclass TextElementBase(ElementBase):\n def __init__(self, content=None, style=None, **kwargs):\n super().__init__(style=style, **kwargs)\n\n # If it\'s an element, append the element\n if isinstance(content, pydom.Element):\n self.append(content)\n # If it\'s a list of elements\n elif isinstance(content, list):\n for item in content:\n self.append(item)\n # If the content wasn\'t set just ignore\n elif content is None:\n pass\n else:\n # Otherwise, set content as the html of the element\n self.html = content\n\n\n# IMPORTANT: For all HTML components defined below, we are not mapping all\n# available attributes, just the global and the most common ones.\n# If you need to access a specific attribute, you can always use the `_js.<attribute>`\nclass a(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a"""\n\n tag = "a"\n\n download = JSProperty("download")\n href = JSProperty("href")\n referrerpolicy = JSProperty("referrerpolicy")\n rel = JSProperty("rel")\n target = JSProperty("target")\n type = JSProperty("type")\n\n\nclass abbr(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/abbr"""\n\n tag = "abbr"\n\n\nclass address(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/address"""\n\n tag = "address"\n\n\nclass area(ElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area"""\n\n tag = "area"\n\n alt = JSProperty("alt")\n coords = JSProperty("coords")\n download = JSProperty("download")\n href = JSProperty("href")\n ping = JSProperty("ping")\n referrerpolicy = JSProperty("referrerpolicy")\n rel = JSProperty("rel")\n shape = JSProperty("shape")\n target = JSProperty("target")\n\n\nclass article(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/article"""\n\n tag = "article"\n\n\nclass aside(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/aside"""\n\n tag = "aside"\n\n\nclass audio(ElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio"""\n\n tag = "audio"\n\n autoplay = JSProperty("autoplay")\n controls = JSProperty("controls")\n controlslist = JSProperty("controlslist")\n crossorigin = JSProperty("crossorigin")\n disableremoteplayback = JSProperty("disableremoteplayback")\n loop = JSProperty("loop")\n muted = JSProperty("muted")\n preload = JSProperty("preload")\n src = JSProperty("src")\n\n\nclass b(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b"""\n\n tag = "b"\n\n\nclass blockquote(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote"""\n\n tag = "blockquote"\n\n cite = JSProperty("cite")\n\n\nclass br(ElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br"""\n\n tag = "br"\n\n\nclass button(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button"""\n\n tag = "button"\n\n autofocus = JSProperty("autofocus")\n disabled = JSProperty("disabled")\n form = JSProperty("form")\n formaction = JSProperty("formaction")\n formenctype = JSProperty("formenctype")\n formmethod = JSProperty("formmethod")\n formnovalidate = JSProperty("formnovalidate")\n formtarget = JSProperty("formtarget")\n name = JSProperty("name")\n type = JSProperty("type")\n value = JSProperty("value")\n\n\nclass canvas(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas"""\n\n tag = "canvas"\n\n height = JSProperty("height")\n width = JSProperty("width")\n\n\nclass caption(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption"""\n\n tag = "caption"\n\n\nclass cite(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/cite"""\n\n tag = "cite"\n\n\nclass code(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/code"""\n\n tag = "code"\n\n\nclass data(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/data"""\n\n tag = "data"\n\n value = JSProperty("value")\n\n\nclass datalist(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist"""\n\n tag = "datalist"\n\n\nclass dd(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dd"""\n\n tag = "dd"\n\n\nclass del_(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/del"""\n\n tag = "del"\n\n cite = JSProperty("cite")\n datetime = JSProperty("datetime")\n\n\nclass details(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details"""\n\n tag = "details"\n\n open = JSProperty("open")\n\n\nclass dialog(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog"""\n\n tag = "dialog"\n\n open = JSProperty("open")\n\n\nclass div(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div"""\n\n tag = "div"\n\n\nclass dl(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl"""\n\n tag = "dl"\n\n value = JSProperty("value")\n\n\nclass dt(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dt"""\n\n tag = "dt"\n\n\nclass em(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em"""\n\n tag = "em"\n\n\nclass embed(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed"""\n\n tag = "embed"\n\n height = JSProperty("height")\n src = JSProperty("src")\n type = JSProperty("type")\n width = JSProperty("width")\n\n\nclass fieldset(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset"""\n\n tag = "fieldset"\n\n disabled = JSProperty("disabled")\n form = JSProperty("form")\n name = JSProperty("name")\n\n\nclass figcaption(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figcaption"""\n\n tag = "figcaption"\n\n\nclass figure(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figure"""\n\n tag = "figure"\n\n\nclass footer(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/footer"""\n\n tag = "footer"\n\n\nclass form(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form"""\n\n tag = "form"\n\n accept_charset = JSProperty("accept-charset")\n action = JSProperty("action")\n autocapitalize = JSProperty("autocapitalize")\n autocomplete = JSProperty("autocomplete")\n enctype = JSProperty("enctype")\n name = JSProperty("name")\n method = JSProperty("method")\n nonvalidate = JSProperty("nonvalidate")\n rel = JSProperty("rel")\n target = JSProperty("target")\n\n\nclass h1(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h1"""\n\n tag = "h1"\n\n\nclass h2(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h2"""\n\n tag = "h2"\n\n\nclass h3(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h3"""\n\n tag = "h3"\n\n\nclass h4(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h4"""\n\n tag = "h4"\n\n\nclass h5(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h5"""\n\n tag = "h5"\n\n\nclass h6(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h6"""\n\n tag = "h6"\n\n\nclass header(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/header"""\n\n tag = "header"\n\n\nclass hgroup(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hgroup"""\n\n tag = "hgroup"\n\n\nclass hr(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hr"""\n\n tag = "hr"\n\n\nclass i(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i"""\n\n tag = "i"\n\n\nclass iframe(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe"""\n\n tag = "iframe"\n\n allow = JSProperty("allow")\n allowfullscreen = JSProperty("allowfullscreen")\n height = JSProperty("height")\n loading = JSProperty("loading")\n name = JSProperty("name")\n referrerpolicy = JSProperty("referrerpolicy")\n sandbox = JSProperty("sandbox")\n src = JSProperty("src")\n srcdoc = JSProperty("srcdoc")\n width = JSProperty("width")\n\n\nclass img(ElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img"""\n\n tag = "img"\n\n alt = JSProperty("alt")\n crossorigin = JSProperty("crossorigin")\n decoding = JSProperty("decoding")\n fetchpriority = JSProperty("fetchpriority")\n height = JSProperty("height")\n ismap = JSProperty("ismap")\n loading = JSProperty("loading")\n referrerpolicy = JSProperty("referrerpolicy")\n sizes = JSProperty("sizes")\n src = JSProperty("src")\n width = JSProperty("width")\n\n\n# NOTE: Input is a reserved keyword in Python, so we use input_ instead\nclass input_(ElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input"""\n\n tag = "input"\n\n accept = JSProperty("accept")\n alt = JSProperty("alt")\n autofocus = JSProperty("autofocus")\n capture = JSProperty("capture")\n checked = JSProperty("checked")\n dirname = JSProperty("dirname")\n disabled = JSProperty("disabled")\n form = JSProperty("form")\n formaction = JSProperty("formaction")\n formenctype = JSProperty("formenctype")\n formmethod = JSProperty("formmethod")\n formnovalidate = JSProperty("formnovalidate")\n formtarget = JSProperty("formtarget")\n height = JSProperty("height")\n list = JSProperty("list")\n max = JSProperty("max")\n maxlength = JSProperty("maxlength")\n min = JSProperty("min")\n minlength = JSProperty("minlength")\n multiple = JSProperty("multiple")\n name = JSProperty("name")\n pattern = JSProperty("pattern")\n placeholder = JSProperty("placeholder")\n popovertarget = JSProperty("popovertarget")\n popovertargetaction = JSProperty("popovertargetaction")\n readonly = JSProperty("readonly")\n required = JSProperty("required")\n size = JSProperty("size")\n src = JSProperty("src")\n step = JSProperty("step")\n type = JSProperty("type")\n value = JSProperty("value")\n width = JSProperty("width")\n\n\nclass ins(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ins"""\n\n tag = "ins"\n\n cite = JSProperty("cite")\n datetime = JSProperty("datetime")\n\n\nclass kbd(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/kbd"""\n\n tag = "kbd"\n\n\nclass label(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label"""\n\n tag = "label"\n\n for_ = JSProperty("for")\n\n\nclass legend(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/legend"""\n\n tag = "legend"\n\n\nclass li(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li"""\n\n tag = "li"\n\n value = JSProperty("value")\n\n\nclass link(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link"""\n\n tag = "link"\n\n as_ = JSProperty("as")\n crossorigin = JSProperty("crossorigin")\n disabled = JSProperty("disabled")\n fetchpriority = JSProperty("fetchpriority")\n href = JSProperty("href")\n imagesizes = JSProperty("imagesizes")\n imagesrcset = JSProperty("imagesrcset")\n integrity = JSProperty("integrity")\n media = JSProperty("media")\n rel = JSProperty("rel")\n referrerpolicy = JSProperty("referrerpolicy")\n sizes = JSProperty("sizes")\n title = JSProperty("title")\n type = JSProperty("type")\n\n\nclass main(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/main"""\n\n tag = "main"\n\n\nclass map_(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map"""\n\n tag = "map"\n\n name = JSProperty("name")\n\n\nclass mark(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/mark"""\n\n tag = "mark"\n\n\nclass menu(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/menu"""\n\n tag = "menu"\n\n\nclass meter(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter"""\n\n tag = "meter"\n\n form = JSProperty("form")\n high = JSProperty("high")\n low = JSProperty("low")\n max = JSProperty("max")\n min = JSProperty("min")\n optimum = JSProperty("optimum")\n value = JSProperty("value")\n\n\nclass nav(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/nav"""\n\n tag = "nav"\n\n\nclass object_(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object"""\n\n tag = "object"\n\n data = JSProperty("data")\n form = JSProperty("form")\n height = JSProperty("height")\n name = JSProperty("name")\n type = JSProperty("type")\n usemap = JSProperty("usemap")\n width = JSProperty("width")\n\n\nclass ol(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol"""\n\n tag = "ol"\n\n reversed = JSProperty("reversed")\n start = JSProperty("start")\n type = JSProperty("type")\n\n\nclass optgroup(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup"""\n\n tag = "optgroup"\n\n disabled = JSProperty("disabled")\n label = JSProperty("label")\n\n\nclass option(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option"""\n\n tag = "option"\n\n disabled = JSProperty("value")\n label = JSProperty("label")\n selected = JSProperty("selected")\n value = JSProperty("value")\n\n\nclass output(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output"""\n\n tag = "output"\n\n for_ = JSProperty("for")\n form = JSProperty("form")\n name = JSProperty("name")\n\n\nclass p(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p"""\n\n tag = "p"\n\n\nclass picture(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture"""\n\n tag = "picture"\n\n\nclass pre(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre"""\n\n tag = "pre"\n\n\nclass progress(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress"""\n\n tag = "progress"\n\n max = JSProperty("max")\n value = JSProperty("value")\n\n\nclass q(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q"""\n\n tag = "q"\n\n cite = JSProperty("cite")\n\n\nclass s(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/s"""\n\n tag = "s"\n\n\nclass script(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script"""\n\n tag = "script"\n\n # Let\'s add async manually since it\'s a reserved keyword in Python\n async_ = JSProperty("async")\n blocking = JSProperty("blocking")\n crossorigin = JSProperty("crossorigin")\n defer = JSProperty("defer")\n fetchpriority = JSProperty("fetchpriority")\n integrity = JSProperty("integrity")\n nomodule = JSProperty("nomodule")\n nonce = JSProperty("nonce")\n referrerpolicy = JSProperty("referrerpolicy")\n src = JSProperty("src")\n type = JSProperty("type")\n\n\nclass section(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/section"""\n\n tag = "section"\n\n\nclass select(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select"""\n\n tag = "select"\n\n\nclass small(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/small"""\n\n tag = "small"\n\n\nclass source(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source"""\n\n tag = "source"\n\n media = JSProperty("media")\n sizes = JSProperty("sizes")\n src = JSProperty("src")\n srcset = JSProperty("srcset")\n type = JSProperty("type")\n\n\nclass span(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span"""\n\n tag = "span"\n\n\nclass strong(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strong"""\n\n tag = "strong"\n\n\nclass style(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style"""\n\n tag = "style"\n\n blocking = JSProperty("blocking")\n media = JSProperty("media")\n nonce = JSProperty("nonce")\n title = JSProperty("title")\n\n\nclass sub(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sub"""\n\n tag = "sub"\n\n\nclass summary(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/summary"""\n\n tag = "summary"\n\n\nclass sup(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sup"""\n\n tag = "sup"\n\n\nclass table(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table"""\n\n tag = "table"\n\n\nclass tbody(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody"""\n\n tag = "tbody"\n\n\nclass td(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td"""\n\n tag = "td"\n\n colspan = JSProperty("colspan")\n headers = JSProperty("headers")\n rowspan = JSProperty("rowspan")\n\n\nclass template(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template"""\n\n tag = "template"\n\n shadowrootmode = JSProperty("shadowrootmode")\n\n\nclass textarea(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea"""\n\n tag = "textarea"\n\n autocapitalize = JSProperty("autocapitalize")\n autocomplete = JSProperty("autocomplete")\n autofocus = JSProperty("autofocus")\n cols = JSProperty("cols")\n dirname = JSProperty("dirname")\n disabled = JSProperty("disabled")\n form = JSProperty("form")\n maxlength = JSProperty("maxlength")\n minlength = JSProperty("minlength")\n name = JSProperty("name")\n placeholder = JSProperty("placeholder")\n readonly = JSProperty("readonly")\n required = JSProperty("required")\n rows = JSProperty("rows")\n spellcheck = JSProperty("spellcheck")\n wrap = JSProperty("wrap")\n\n\nclass tfoot(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tfoot"""\n\n tag = "tfoot"\n\n\nclass th(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th"""\n\n tag = "th"\n\n\nclass thead(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead"""\n\n tag = "thead"\n\n\nclass time(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/time"""\n\n tag = "time"\n\n datetime = JSProperty("datetime")\n\n\nclass title(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title"""\n\n tag = "title"\n\n\nclass tr(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr"""\n\n tag = "tr"\n\n abbr = JSProperty("abbr")\n colspan = JSProperty("colspan")\n headers = JSProperty("headers")\n rowspan = JSProperty("rowspan")\n scope = JSProperty("scope")\n\n\nclass track(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track"""\n\n tag = "track"\n\n default = JSProperty("default")\n kind = JSProperty("kind")\n label = JSProperty("label")\n src = JSProperty("src")\n srclang = JSProperty("srclang")\n\n\nclass u(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/u"""\n\n tag = "u"\n\n\nclass ul(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul"""\n\n tag = "ul"\n\n\nclass var(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/var"""\n\n tag = "var"\n\n\nclass video(TextElementBase):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video"""\n\n tag = "video"\n\n autoplay = JSProperty("autoplay")\n controls = JSProperty("controls")\n crossorigin = JSProperty("crossorigin")\n disablepictureinpicture = JSProperty("disablepictureinpicture")\n disableremoteplayback = JSProperty("disableremoteplayback")\n height = JSProperty("height")\n loop = JSProperty("loop")\n muted = JSProperty("muted")\n playsinline = JSProperty("playsinline")\n poster = JSProperty("poster")\n preload = JSProperty("preload")\n src = JSProperty("src")\n width = JSProperty("width")\n\n\n# Custom Elements\nclass grid(TextElementBase):\n tag = "div"\n\n def __init__(self, layout, content=None, gap=None, **kwargs):\n super().__init__(content, **kwargs)\n self.style["display"] = "grid"\n self.style["grid-template-columns"] = layout\n\n # TODO: This should be a property\n if not gap is None:\n self.style["gap"] = gap\n'}}}),Br.push("import pyscript as _pyscript"),Br.push(...["_Path","_path","_os","_pyscript"].map((e=>`del ${e}`))),Br.push("\n");const zr=Br.join("\n"),$r=Ur.join("\n"),Cr=e=>Xr.main[e],Dr=e=>Xr.worker[e],Fr=(e,n,t,r)=>{e[t]=()=>{const e=r?[r]:[];return e.push(...n(t)),e.map(en).join("\n")}},qr=(e,n)=>{const t="mpy"===n?zr.replace($r,""):zr,r={};return Fr(r,e,"codeBeforeRun",t),Fr(r,e,"codeBeforeRunAsync",t),Fr(r,e,"codeAfterRun"),Fr(r,e,"codeAfterRunAsync"),r},Gr=(e,n)=>{const t=[...Dr(n)];if(t.length){const r=jt(e[`_${n}`]||(n.endsWith("Async")?async(e,n,...t)=>{for(const r of t)await r(e,n)}:(e,n,...t)=>{for(const r of t)r(e,n)})),s=t.map(jt).join(", ");return Function(`return(w,x)=>(${r})(w,x,...[${s}])`)()}},Vr=Or({typeof:"function"}),Yr=Or({typeof:"string"}),Kr='\n import builtins\n def input(prompt=""):\n raise Exception("\\n ".join([\n "input() doesn\'t work when PyScript runs in the main thread.",\n "Consider using the worker attribute: https://pyscript.github.io/docs/2023.11.2/user-guide/workers/"\n ]))\n\n builtins.input = input\n del builtins\n del input\n',Xr={main:{onWorker:new Vr,onReady:new Vr,onBeforeRun:new Vr,onBeforeRunAsync:new Vr,onAfterRun:new Vr,onAfterRunAsync:new Vr,codeBeforeRun:new Yr([Kr]),codeBeforeRunAsync:new Yr,codeAfterRun:new Yr,codeAfterRunAsync:new Yr},worker:{onReady:new Vr,onBeforeRun:new Vr,onBeforeRunAsync:new Vr,onAfterRun:new Vr,onAfterRunAsync:new Vr,codeBeforeRun:new Yr,codeBeforeRunAsync:new Yr,codeAfterRun:new Yr,codeAfterRunAsync:new Yr}},Zr=({tagName:e})=>"SCRIPT"===e,[Qr,es]=[...ur.entries()].map((([e,n])=>async function(t,r){await xr.get(e).plugins;const s=fr.call(new dr(null,ls.get(e)),t,{...r,type:n});return rn(s.sync,Jr),s.ready})),[{PyWorker:ns,MPWorker:ts,hooks:rs,config:ss,whenDefined:os},as]=e("@pyscript/core",{PyWorker:Qr,MPWorker:es,hooks:Xr,config:{},whenDefined:pr}),is=e=>e?.interpreter&&new URL(e.interpreter,location.href).href,ls=new Map;for(const[e,n]of ur){if(as)break;const t=(n,t,r)=>{t?r.then((()=>un(n,e,"done"))):un(n,e,"done")},{config:r,configURL:s,plugins:o,error:a}=xr.get(e);let i=0;const l=(n=e)=>`${n}-${i++}`,p=async(n,t,r)=>{if(n.hasAttribute("src"))try{return await vr(n.getAttribute("src")).then(br)}catch(e){t.stderr(e)}if(r)return en(n.textContent);const s=en(nn(n.innerHTML));return console.warn(`Deprecated: use <script type="${e}"> for an always safe content parsing:\n`,s),s};let c,d=!1;const f=({XWorker:e,interpreter:n,io:t})=>{d||(d=!0,n.registerJsModule("_pyscript",{PyWorker:function(...n){const r=e(...n);return r.onerror=({error:e})=>t.stderr(e),r},js_import:(...e)=>Promise.all(e.map((e=>import(e)))),get target(){return Zr(c)?c.target.id:c.id}}))};a||o.then((()=>{const o=new Map,a={main:{...qr(Cr,e),async onReady(n,r){f(n);for(const e of Cr("onReady"))await e(n,r);if(o.has(r)){let{message:e}=o.get(r);o.delete(r);const t=e===Bt;return e=`(${gr.CONFLICTING_CODE}) ${e} for `,e+=r.cloneNode(t).outerHTML,void n.io.stderr(e)}if(Zr(r)){const{attributes:{async:s,target:o}}=r,a=!!o?.value,i=a?It(r,o.value):document.createElement("script-py");if(!a){const{head:e,body:n}=document;e.contains(r)?n.append(i):r.after(i)}i.id||(i.id=l()),an(r,"target",{value:i}),un(r,e,"ready"),t(r,s,n["run"+(s?"Async":"")](await p(r,n.io,!0)))}else r._wrap.resolve(n);console.debug("[pyscript/main] PyScript Ready")},onWorker(e,n){rn(n.sync,Jr);for(const t of Cr("onWorker"))t(e,n)},onBeforeRun(e,n){c=n,Mr(Cr,e,n,"onBeforeRun")},onBeforeRunAsync:(e,n)=>(c=n,Mr(Cr,e,n,"onBeforeRunAsync")),onAfterRun(e,n){Mr(Cr,e,n,"onAfterRun")},onAfterRunAsync:(e,n)=>Mr(Cr,e,n,"onAfterRunAsync")},worker:{...qr(Dr,e),get onReady(){return Gr(this,"onReady")},get onBeforeRun(){return Gr(this,"onBeforeRun")},get onBeforeRunAsync(){return Gr(this,"onBeforeRunAsync")},get onAfterRun(){return Gr(this,"onAfterRun")},get onAfterRunAsync(){return Gr(this,"onAfterRunAsync")}}};ls.set(e,a),lr(e,{config:r,configURL:s,interpreter:n,hooks:a,env:`${e}-script`,version:is(r),onerror(e,n){o.set(n,e)}}),customElements.define(`${e}-script`,class extends HTMLElement{constructor(){rn(super(),{_wrap:Promise.withResolvers(),srcCode:"",executed:!1})}get id(){return super.id||(super.id=l())}set id(e){super.id=e}async connectedCallback(){if(!this.executed){this.executed=!0;const n=this.hasAttribute("async"),{io:r,run:s,runAsync:o}=await this._wrap.promise;this.srcCode=await p(this,r,!this.childElementCount),this.replaceChildren(),this.style.display="block",un(this,e,"ready"),t(this,n,(n?o:s)(this.srcCode))}}})})),ss[e]=structuredClone(r)}export{dr as H,ur as T,fr as X,en as a,$r as b,ir as c,on as d,rs as e,ns as f,ts as g,ss as h,Kr as i,os as j,is as o,zr as s};
3
+ //# sourceMappingURL=core-BQAbLvre.js.map