@pyscript/core 0.5.15 → 0.5.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE DELETED
@@ -1,203 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright (c) 2022-present, PyScript Development Team
190
-
191
- Originated at Anaconda, Inc. in 2022
192
-
193
- Licensed under the Apache License, Version 2.0 (the "License");
194
- you may not use this file except in compliance with the License.
195
- You may obtain a copy of the License at
196
-
197
- http://www.apache.org/licenses/LICENSE-2.0
198
-
199
- Unless required by applicable law or agreed to in writing, software
200
- distributed under the License is distributed on an "AS IS" BASIS,
201
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
- See the License for the specific language governing permissions and
203
- limitations under the License.
@@ -1,2 +0,0 @@
1
- const e=(e,t,n=globalThis)=>{const r=Symbol.for(e),s=r in n;return[s?n[r]:Object.defineProperty(n,r,{value:t})[r],s]};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 t=(e,t=document)=>[...t.querySelectorAll(e)],n=(e,t=document)=>{const n=(new XPathEvaluator).createExpression(e).evaluate(t,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE),r=[];for(let e=0,{snapshotLength:t}=n;e<t;e++)r.push(n.snapshotItem(e));return r},r=Object.getOwnPropertyDescriptors(Response.prototype),s=e=>"function"==typeof e,o={get:(e,t)=>r.hasOwnProperty(t)?((e,t,{get:n,value:r})=>n||!s(r)?e.then((e=>e[t])):(...n)=>e.then((e=>e[t](...n))))(e,t,r[t]):((e,t)=>s(t)?t.bind(e):t)(e,e[t])};var a=(e,...t)=>new Proxy(fetch(e,...t),o);const i=new Proxy(new Map,{get:(e,t)=>(e.has(t)||e.set(t,Promise.withResolvers()),e.get(t))}),l=new Set(["__dict__","constructor","get","has","includes","next","set","then"]),c=new Proxy(Object.freeze({}),{get:(e,t)=>"string"!=typeof t||l.has(t)?void 0:i[t].promise.then((e=>e.sync))}),p="object"==typeof self?self:globalThis,u=e=>((e,t)=>{const n=(t,n)=>(e.set(n,t),t),r=s=>{if(e.has(s))return e.get(s);const[o,a]=t[s];switch(o){case 0:case-1:return n(a,s);case 1:{const e=n([],s);for(const t of a)e.push(r(t));return e}case 2:{const e=n({},s);for(const[t,n]of a)e[r(t)]=r(n);return e}case 3:return n(new Date(a),s);case 4:{const{source:e,flags:t}=a;return n(new RegExp(e,t),s)}case 5:{const e=n(new Map,s);for(const[t,n]of a)e.set(r(t),r(n));return e}case 6:{const e=n(new Set,s);for(const t of a)e.add(r(t));return e}case 7:{const{name:e,message:t}=a;return n(new p[e](t),s)}case 8:return n(BigInt(a),s);case"BigInt":return n(Object(BigInt(a)),s)}return n(new p[o](a),s)};return r})(new Map,e)(0),d="",{toString:f}={},{keys:_}=Object,m=e=>{const t=typeof e;if("object"!==t||!e)return[0,t];const n=f.call(e).slice(8,-1);switch(n){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 n.includes("Array")?[1,n]:n.includes("Error")?[7,n]:[2,n]},y=([e,t])=>0===e&&("function"===t||"symbol"===t),h=(e,{json:t,lossy:n}={})=>{const r=[];return((e,t,n,r)=>{const s=(e,t)=>{const s=r.push(e)-1;return n.set(t,s),s},o=r=>{if(n.has(r))return n.get(r);let[a,i]=m(r);switch(a){case 0:{let t=r;switch(i){case"bigint":a=8,t=r.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+i);t=null;break;case"undefined":return s([-1],r)}return s([a,t],r)}case 1:{if(i)return s([i,[...r]],r);const e=[],t=s([a,e],r);for(const t of r)e.push(o(t));return t}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(t&&"toJSON"in r)return o(r.toJSON());const n=[],l=s([a,n],r);for(const t of _(r))!e&&y(m(r[t]))||n.push([o(t),o(r[t])]);return l}case 3:return s([a,r.toISOString()],r);case 4:{const{source:e,flags:t}=r;return s([a,{source:e,flags:t}],r)}case 5:{const t=[],n=s([a,t],r);for(const[n,s]of r)(e||!y(m(n))&&!y(m(s)))&&t.push([o(n),o(s)]);return n}case 6:{const t=[],n=s([a,t],r);for(const n of r)!e&&y(m(n))||t.push(o(n));return n}}const{message:l}=r;return s([a,{name:i,message:l}],r)};return o})(!(t||n),!!t,new Map,r)(e),r},{parse:A,stringify:g}=JSON,w={json:!0,lossy:!0};var E=Object.freeze({__proto__:null,parse:e=>u(A(e)),stringify:e=>g(h(e,w))});const b="ownKeys",v="destruct",B="f9d26a47-9015-443e-bfa3-307ca8b90cc8",C="="+B,k="-"+B,{ArrayBuffer:j,Atomics:x,Promise:R}=globalThis,{isArray:S}=Array,{create:$,getPrototypeOf:P,values:T}=Object,D=P(Int32Array),O=$(x),M=()=>R.withResolvers();let F=0;const I=new Map,N=(e,t)=>class extends e{constructor(e,...n){super(e,...n),e instanceof t&&I.set(this,[F++,0,M()])}},L=new WeakSet,W=e=>(L.add(e),e),H=(e,t)=>{const{data:n}=e,r=S(n)&&(n.at(0)===t||0===n.at(1)&&!t);return r&&(e.stopImmediatePropagation(),e.preventDefault()),r},U=e=>null!==e&&"object"==typeof e&&!L.has(e),J=new WeakMap,q=(e,t,n)=>{if(I.has(e))t.set(e,I.get(e)[0]);else if(!(e instanceof D||e instanceof j))for(const r of T(e))U(r)&&!n.has(r)&&(n.add(r),q(r,t,n))},z=(...e)=>({value:new R((t=>{let n=new Worker("data:application/javascript,onmessage%3De%3D%3EpostMessage(!Atomics.wait(...e.data))");n.onmessage=()=>t("ok"),n.postMessage(e)}))}),G=(e,t,n)=>{for(const[n,r]of t)J.set(n,[r,e.currentTarget]);(({currentTarget:e,type:t,origin:n,lastEventId:r,source:s,ports:o},a)=>{e.dispatchEvent(new MessageEvent(t,{data:a,origin:n,lastEventId:r,source:s,ports:o}))})(e,n)};let{BigInt64Array:K,Int32Array:Y,SharedArrayBuffer:X,Worker:V}=globalThis,Z=e=>e,Q=!1;const ee=e=>({...e,type:"module"});try{new X(4),V=class extends V{constructor(e,t){super(e,ee(t))}},O.waitAsync||(O.waitAsync=z)}catch(e){const t=crypto.randomUUID(),n=new Map,r=(e,t,n,...r)=>{e.addEventListener(t,n,...r)},s=({serviceWorker:e},s,o)=>{let a,i=!0;r(e,"message",(e=>{if(H(e,t)){const[r,s,o]=e.data,i=[s,o].join(","),l=e=>{n.delete(i),a.postMessage([t,s,o,e])},c=n.get(i);if(c)l(c);else{const{promise:e,resolve:t}=M();n.set(i,t),e.then(l)}}})),e.getRegistration(s).then((t=>t??e.register(s))).then((function t(n){i=i&&!!e.controller,a=n.installing||n.waiting||n.active,"activated"===a.state?i?o():location.reload():r(a,"statechange",(()=>t(n)),{once:!0})}))};Z=W,Q=!0,O.notify=(e,r)=>{const[s,o]=(e=>J.get(e))(e),a=[s,r].join(","),i=n.get(a);return i?i(e):n.set(a,e),o.postMessage([t,1,e,s,r]),0},O.waitAsync=(e,...t)=>{const[n,r]=((e,t)=>{const n=I.get(e),[r,s,{promise:o}]=n;return n[1]=t,[r,o]})(e,...t);return{value:r}},X=class extends j{},K=N(K,X),Y=N(Y,X);let o=null;V=class extends V{constructor(e,n){let a=n?.serviceWorker||"";if(a){if(a=new URL(a,location.href).href,n={...n,serviceWorker:a},!o){const{promise:e,resolve:t}=M();s(navigator,a,t),o=e}o.then((()=>super.postMessage([t,3])))}super(e,ee(n)),super.postMessage([t,0,n]),r(this,"message",(e=>{if(H(e,t)){const[t,n,...r]=e.data;switch(n){case 1:((e,t,n)=>{for(const[r,[s,o,{resolve:a}]]of I)if(t===s&&n===o){for(let t=0;t<e.length;t++)r[t]=e[t];I.delete(r),a("ok");break}})(...r);break;case 2:G(e,...r)}}}))}postMessage(e,...n){return super.postMessage(((e,t)=>{const n=new Map;return U(t)&&q(t,n,new Set),n.size?[e,2,n,t]:t})(t,e),...n)}}}const{BYTES_PER_ELEMENT:te}=Int32Array,{BYTES_PER_ELEMENT:ne}=Uint16Array,{notify:re}=O,se=new TextDecoder("utf-16"),oe=new WeakSet,ae=(...e)=>(oe.add(e),e);let ie="";let le=0;const ce=([e,t,n,r,s,o,a,i,l],c)=>(...p)=>{let u=""!==ie,d=0;u&&"="!==ie[0]&&"-"!==ie[0]&&(d=((e,t)=>setTimeout(console.warn,3e3,`💀🔒 - proxy.${e}() in proxy.${t}()`))(c,ie));const f=le++,_=[];oe.has(p.at(-1)||_)&&oe.delete(_=p.pop());const m=n(i?p.map(i):p);let y=t(2*te);return a([e,2,c,f,y,m,r],{transfer:_}),l(y,0).value.then((()=>{u&&clearTimeout(d);const n=y[1];if(!n)return;const r=ne*n;return y=t(r+r%te),a([e,1,f,y]),l(y,0).value.then((()=>{const e=new Uint16Array(y.buffer),t=o?e.subarray(0,n):e.slice(0,n);return s(se.decode(t))}))}))};var pe=({parse:e,stringify:t,transform:n}=JSON)=>{const r=((e,t)=>async(n,r,[s,o,a,i,l])=>{l&&(ie=s);try{const s=await n(...i);if(void 0!==s){const n=e(t?t(s):s);r.set(o,n),a[1]=n.length}}finally{l&&(ie=""),a[0]=1,re(a,0)}})(t,n),s=crypto.randomUUID();return{Worker:class extends V{constructor(t,o){const a=new Map,i=new Map;super(t,o),this.proxy=((e,t)=>new Proxy(t,{get:(t,n)=>{let r;return"then"!==n&&(r=t.get(n),r||(r=ce(e,n),t.set(n,r))),r},set:(e,t,n)=>"then"!==t&&!!e.set(t,n)}))([s,e=>new Y(new X(e)),Z,!1,e,Q,(...e)=>this.postMessage(...e),n,O.waitAsync],a),this.postMessage(Z([s,0,o])),this.addEventListener("message",(e=>{if(H(e,s)){const[t,n,...s]=e.data;switch(n){case 2:((e,t,n,r)=>{const[s]=r,o=n.get(s);if(!o)throw new Error(`Unknown proxy.${s}()`);e(o,t,r)})(r,i,a,s);break;case 1:((e,[t,n])=>{const r=e.get(t);e.delete(t);for(let e=new Uint16Array(n.buffer),t=0,{length:s}=r;t<s;t++)e[t]=r.charCodeAt(t);re(n,0)})(i,s)}}}))}},polyfill:Q,transfer:ae}};const ue="array",de="function",fe="null",_e="number",me="object",ye="string",he="symbol",Ae="undefined";var ge=Object.fromEntries([ue,"bigint","boolean",de,fe,_e,me,ye,he,Ae].map(((e,t)=>[e,t])));const{[b]:we}=Reflect,Ee=new Map(we(Symbol).filter((e=>typeof Symbol[e]===he)).map((e=>[Symbol[e],e]))),be=e=>Ee.get(e)||`.${Symbol.keyFor(e)||""}`,ve=new FinalizationRegistry((([e,t,n])=>{n&&console.debug(`%c${String(t)}`,"font-weight:bold","collected"),e(t)})),Be=Object.create(null),Ce=(e,t,{debug:n,handler:r,return:s,token:o=e}=Be)=>{const a=s||new Proxy(e,r||Be),i=[a,[t,e,!!n]];return!1!==o&&i.push(o),ve.register(...i),a},{addEventListener:ke}=EventTarget.prototype,je=new WeakMap;Reflect.defineProperty(EventTarget.prototype,"addEventListener",{value(e,t,...n){const r=n.at(0)?.invoke;if(r){let t=je.get(this);t||(t=new Map,je.set(this,t)),t.set(e,[].concat(r)),delete n[0].invoke}return ke.call(this,e,t,...n)}});const{isArray:xe}=Array;var Re=(e,t)=>{const{drop:n,get:r,hold:s}=(()=>{const e=new Map,t=new Map;let n=0;return{drop:n=>{const[r,s]=typeof n===_e?[t,e]:[e,t],o=r.has(n);return o&&(s.delete(r.get(n)),r.delete(n)),o},get:e=>t.get(e),hold:r=>{if(!e.has(r)){let s;for(;t.has(s=n++););e.set(r,s),t.set(s,r)}return e.get(r)}}})(),o=new Map,a=e=>{o.delete(e),t(v,e)},i=e=>{const t=typeof e;switch(t){case me:return null===e?[ge[fe],e]:e===globalThis?[ge[me],null]:xe(e)?[ge[ue],s(e)]:[ge[me],e instanceof D?e:s(e)];case de:return[ge[de],s(e)];case he:return[ge[he],be(e)];default:return[ge[t],e]}},l=([e,n])=>{switch(e){case ge[me]:if(null===n)return globalThis;if(typeof n===_e)return r(n);if(!(n instanceof D))for(const e in n)n[e]=l(n[e]);return n;case ge[ue]:return typeof n===_e?r(n):n.map(l);case ge[de]:switch(typeof n){case _e:return r(n);case ye:{let e=o.get(n)?.deref();return e||(e=Ce(n,a,{token:!1,return:function(...e){return e.length&&e[0]instanceof Event&&(e=>{const{currentTarget:t,target:n,type:r}=e,s=je.get(t||n)?.get(r);if(s)for(const t of s)e[t]()})(e[0]),t("apply",n,i(this),e.map(i)).then(l)}}),o.set(n,new WeakRef(e))),e}}case ge[he]:return(e=>{if(e.startsWith("."))return Symbol.for(e.slice(1));for(const[t,n]of Ee)if(n===e)return t})(n);default:return n}},c=t=>import(e(t));return(e,t,...s)=>{if(e===v)n(t);else{const n=Reflect[e],o=null==t?globalThis:r(t);switch(e){case"defineProperty":{const[e,t]=s.map(l);return i(n(o,e,t))}case"getOwnPropertyDescriptor":{const e=n(o,...s.map(l));if(e){const{get:t,set:n,value:r}=e;t&&(e.get=i(t)),n&&(e.set=i(n)),r&&(e.value=i(r))}return[ge[e?me:Ae],e]}case b:return[ge[ue],n(o).map(i)];case"get":if(null==t&&"import"===s[0][1])return i(c);default:return((e,t,n)=>i(e(t,...n.map(l))))(n,o,s)}}}};const{url:Se}=import.meta,$e=/import\((['"])([^)]+?\.js)\1\)/g,Pe=(e,t,n)=>`import(${t}${new URL(n,Se).href}${t})`,{Worker:Te}=(e=>{const t=e?.import,n=pe(e);class r extends n.Worker{constructor(e,n){const{proxy:r}=super(e,n);r[C]=Re(n?.import||t||(e=>new URL(e,location.href)),r[k])}}return{...n,Worker:r}})(E);const De=new WeakMap,Oe=e=>{const t=e||console,n={buffered:Fe,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 De.set(t,n),t}}},Me=new TextDecoder,Fe=(e,t=10)=>{const n=[];return r=>{if(r instanceof Uint8Array)for(const s of r)s===t?e(Me.decode(new Uint8Array(n.splice(0)))):n.push(s);else e(r)}},Ie=new Map,Ne=e=>Ie.get(e),Le=(e,t)=>{try{return Function("require",t)(Ne)}catch(t){De.get(e).stderr(t)}};var We={type:"dummy",module:()=>"data:application/javascript,",engine:e=>Oe().get(e),registerJSModule(e,t,n){Ie.set(t,n)},run:Le,runAsync:Le,runEvent:async(e,t,n)=>{try{await Function("require","e",`return ${t}(e)`)(Ne,n)}catch(t){De.get(e).stderr(t)}},transform:(e,t)=>t,writeFile(){}};const{assign:He}=Object,Ue="entries",Je="readonly",qe="readwrite",ze={durability:"default",prefix:"IDBMap"},Ge=({target:{result:e}})=>e;class Ke extends EventTarget{#e;#t;#n;async#r(e,t){const n=(await this.#e).transaction(Ue,t,this.#t);return new Promise(((t,r)=>He(e(n.objectStore(Ue)),{onsuccess:t,onerror:r})))}constructor(e,{durability:t=ze.durability,prefix:n=ze.prefix}=ze){super(),this.#n=n,this.#t={durability:t},this.#e=new Promise(((t,n)=>{He(indexedDB.open(`${this.#n}/${e}`),{onupgradeneeded({target:{result:e,transaction:n}}){e.objectStoreNames.length||e.createObjectStore(Ue),n.oncomplete=()=>t(e)},onsuccess(e){t(Ge(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?He(new Event(t),{message:n}):e)}async close(){(await this.#e).close()}get size(){return this.#r((e=>e.count()),Je).then(Ge)}async clear(){await this.#r((e=>e.clear()),qe)}async delete(e){await this.#r((t=>t.delete(e)),qe)}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)),Je).then(Ge)}async has(e){return void 0!==await this.#r((t=>t.getKey(e)),Je).then(Ge)}async keys(){return await this.#r((e=>e.getAllKeys()),Je).then(Ge)}async set(e,t){return await this.#r((n=>n.put(t,e)),qe),this}async values(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e))))}get[Symbol.toStringTag](){return this.#n}}class Ye extends Map{#s;#o;constructor(...e){super(),this.#s=new Ke(...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 Xe={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}},{replace:Ve}="",Ze=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g,Qe={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"'},et=e=>Qe[e],tt=(e,...t)=>Xe[typeof e](e,...t),nt=e=>Ve.call(e,Ze,et),{isArray:rt}=Array,{assign:st,create:ot,defineProperties:at,defineProperty:it,entries:lt}=Object,{all:ct,resolve:pt}=new Proxy(Promise,{get:(e,t)=>e[t].bind(e)}),ut=(e,t=location.href)=>new URL(e,t.replace(/^blob:/,"")).href;let dt=0;const ft=(e,t)=>({id:e.id||(e.id=`${t}-w${dt++}`),tag:e.tagName}),_t=(e,t,n,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${t}:${n}`,{bubbles:!0,detail:{worker:r}}))},mt=(e,t,n,r)=>({type:t,config:n,interpreter:r,io:De.get(r),run:(t,...n)=>e.run(r,t,...n),runAsync:(t,...n)=>e.runAsync(r,t,...n),runEvent:(...t)=>e.runEvent(r,...t)}),yt=e=>e.replace(/^(?:\n|\r\n)/,""),ht=(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,yt(t),...o);return r&&s(e,r,...o),a}:async(e,t,...o)=>{n&&await s(e,n,...o);const a=await s(e,yt(t),...o);return r&&await s(e,r,...o),a}},At=Symbol.for("polyscript.js_modules"),gt=new Map;it(globalThis,At,{value:gt});const wt=new Proxy(gt,{get:(e,t)=>e.get(t),has:(e,t)=>e.has(t),ownKeys:e=>[...e.keys()]}),Et=(e,t)=>!t.startsWith("_"),bt=(e,t)=>new Proxy(e,{has:Et,get:(e,n)=>e[t][n]}),vt=(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}`,bt(r,e));t.registerJSModule(n,s,r)},Bt=(e,t)=>import(e).then((e=>{gt.set(t,{...e})})),Ct=e=>new Promise(((t,n)=>{document.querySelector(`link[rel="stylesheet"][href="${e}"]`)?t():document.head.append(st(document.createElement("link"),{rel:"stylesheet",href:e,onload:t,onerror:n}))})),kt=e=>/\.css$/i.test(new URL(e).pathname),jt=e=>/^(?:false|0|no)$/i.test(e.getAttribute("async")),xt=!globalThis.window,Rt=({FS:e,PATH:t,PATH_FS:n},r,s)=>{const o=n.resolve(r),a=t.dirname(o);return e.mkdirTree?e.mkdirTree(a):$t(e,a),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},St=e=>{const t=e.split("/");return t.pop(),t.join("/")},$t=(e,t)=>{const n=[];for(const r of t.split("/"))"."!==r&&".."!==r&&(n.push(r),r&&e.mkdir(n.join("/")))},Pt=(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(/^\/+/,"/")},Tt=e=>{const t=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,""))).filter((e=>""!==e&&"."!==e)).join("/");return e[0].startsWith("/")?`/${t}`:t},Dt=(e,t)=>a(ut(e,t)).arrayBuffer(),Ot=(e,t,n,r)=>ct((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(rt(r))return r.map((n=>({url:Tt([e,n]),path:Tt([t,n])})));const s=n||e.slice(1+e.lastIndexOf("/"));return[{url:e,path:Tt([t,s])}]}))})(n).map((({url:n,path:s})=>Dt(n,r).then((n=>e.writeFile(t,s,n)))))),Mt=(e,t)=>t.endsWith("/")?`${t}${e.split("/").pop()}`:t,Ft=(e,t)=>e.replace(/\{.+?\}/g,(e=>{if(!t.has(e))throw new SyntaxError(`Invalid template: ${e}`);return t.get(e)})),It=(e,t,n,r)=>ct((e=>{const t=new Map,n=new Set,r=[];for(const[s,o]of lt(e))if(/^\{.+\}$/.test(s)){if(t.has(s))throw new SyntaxError(`Duplicated template: ${s}`);t.set(s,Ft(o,t))}else{const e=Ft(s,t),a=Mt(e,Ft(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})=>Dt(n,r).then((r=>e.writeFile(t,s,r,n)))))),Nt=({main:e,worker:t},n)=>{const r=[];if(t&&xt)for(let[e,s]of lt(t))e=ut(e,n),r.push(Bt(e,s));if(e&&!xt)for(let[t,s]of lt(e))t=ut(t,n),kt(t)?Ct(t):r.push(Bt(t,s));return ct(r)},Lt=e=>t=>{dispatchEvent(new CustomEvent(`${e}:progress`,{detail:t}))},Wt=new WeakMap,Ht=async(e,t,n,r,s)=>{r.files&&(t("Loading files"),await It(e,n,r.files,s),t("Loaded files")),r.fetch&&(t("Loading fetch"),await Ot(e,n,r.fetch,s),t("Loaded fetch")),r.js_modules&&(t("Loading JS modules"),await Nt(r.js_modules,s),t("Loaded JS modules"))},Ut=(e,t,n)=>{"polyscript"===t&&(n.lazy_py_modules=async(...t)=>(await Wt.get(e)(t),t.map((t=>e.pyimport(t)))),n.storage=async e=>{const t=new Ye(e);return await t.sync(),t},n.JSON=E),e.registerJsModule(t,n)},Jt=(e,t)=>{if(e.endsWith("/*")){if(/\.(zip|whl|tgz|tar(?:\.gz)?)$/.test(t))return RegExp.$1;throw new Error(`Unsupported archive ${t}`)}return""},qt=(e,t,...n)=>{try{return e.runPython(tt(t),...n)}catch(t){De.get(e).stderr(t)}},zt=async(e,t,...n)=>{try{return await e.runPythonAsync(tt(t),...n)}catch(t){De.get(e).stderr(t)}},Gt=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){De.get(e).stderr(t)}};var Kt=(new TextEncoder).encode("_F='github:'\n_E='user-agent'\n_D=True\n_C=False\n_B='/'\n_A=None\nfrom uio import StringIO\nimport sys\nclass Response:\n\tdef __init__(A,f):A.raw=f;A.encoding='utf-8';A._cached=_A\n\tdef close(A):\n\t\tif A.raw:A.raw.close();A.raw=_A\n\t\tA._cached=_A\n\t@property\n\tdef content(self):\n\t\tA=self\n\t\tif A._cached is _A:\n\t\t\ttry:A._cached=A.raw.read()\n\t\t\tfinally:A.raw.close();A.raw=_A\n\t\treturn A._cached\n\t@property\n\tdef text(self):return str(self.content,self.encoding)\n\tdef json(A):import ujson;return ujson.loads(A.content)\nHEADERS_TO_IGNORE=_E,\ntry:import js\nexcept Exception as err:raise OSError('This version of urequests can only be used in the browser')\nHEADERS_TO_IGNORE=_E,\ndef request(method,url,data=_A,json=_A,headers={},stream=_A,auth=_A,timeout=_A,parse_headers=_D):\n\tE=timeout;D=method;C=data;from js import XMLHttpRequest as G;A=G.new();A.withCredentials=_C\n\tif auth is not _A:import ubinascii;H,I=auth;A.open(D,url,_C,H,I)\n\telse:A.open(D,url,_C)\n\tfor(F,J)in headers.items():\n\t\tif F.lower()not in HEADERS_TO_IGNORE:A.setRequestHeader(F,J)\n\tif E:A.timeout=int(E*1000)\n\tif json is not _A:assert C is _A;import ujson;C=ujson.dumps(json);A.setRequestHeader('Content-Type','application/json')\n\tA.send(C);B=Response(StringIO(A.responseText));B.status_code=A.status;B.reason=A.statusText;B.headers=A.getAllResponseHeaders();return B\ndef get(url,**A):return request('GET',url,**A)\n_PACKAGE_INDEX=const('https://micropython.org/pi/v2')\n_CHUNK_SIZE=128\ndef _ensure_path_exists(path):\n\timport os;A=path.split(_B)\n\tif not A[0]:A.pop(0);A[0]=_B+A[0]\n\tB=''\n\tfor C in range(len(A)-1):\n\t\tB+=A[C]\n\t\ttry:os.stat(B)\n\t\texcept:os.mkdir(B)\n\t\tB+=_B\ndef _chunk(src,dest):\n\tA=memoryview(bytearray(_CHUNK_SIZE))\n\twhile _D:\n\t\tB=src.readinto(A)\n\t\tif B==0:break\n\t\tdest(A if B==_CHUNK_SIZE else A[:B])\ndef _check_exists(path,short_hash):\n\tA=short_hash;import os\n\ttry:\n\t\timport binascii as C,hashlib as D\n\t\twith open(path,'rb')as E:B=D.sha256();_chunk(E,B.update);F=str(C.hexlify(B.digest())[:len(A)],'utf-8');return F==A\n\texcept:return _C\ndef _rewrite_url(url,branch=_A):\n\tB=branch;A=url\n\tif not B:B='HEAD'\n\tif A.startswith(_F):A=A[7:].split(_B);A='https://raw.githubusercontent.com/'+A[0]+_B+A[1]+_B+B+_B+_B.join(A[2:])\n\treturn A\ndef _download_file(url,dest):\n\tB=dest;A=get(url)\n\ttry:\n\t\tif A.status_code!=200:print('Error',A.status_code,'requesting',url);return _C\n\t\tprint('Copying:',B);_ensure_path_exists(B)\n\t\twith open(B,'wb')as C:_chunk(A.raw,C.write)\n\t\treturn _D\n\tfinally:A.close()\ndef _install_json(package_json_url,index,target,version,mpy):\n\tK='File not found: {} {}';I=version;H=index;G=package_json_url;D=target;E=get(_rewrite_url(G,I))\n\ttry:\n\t\tif E.status_code!=200:print('Package not found:',G);return _C\n\t\tF=E.json()\n\tfinally:E.close()\n\tfor(A,C)in F.get('hashes',()):\n\t\tB=D+_B+A\n\t\tif _check_exists(B,C):print('Exists:',B)\n\t\telse:\n\t\t\tL='{}/file/{}/{}'.format(H,C[:2],C)\n\t\t\tif not _download_file(L,B):print(K.format(A,C));return _C\n\tfor(A,J)in F.get('urls',()):\n\t\tB=D+_B+A\n\t\tif not _download_file(_rewrite_url(J,I),B):print(K.format(A,J));return _C\n\tfor(M,N)in F.get('deps',()):\n\t\tif not _install_package(M,H,D,N,mpy):return _C\n\treturn _D\ndef _install_package(package,index,target,version,mpy):\n\tD=index;C=target;B=version;A=package\n\tif A.startswith('http://')or A.startswith('https://')or A.startswith(_F):\n\t\tif A.endswith('.py')or A.endswith('.mpy'):print('Downloading {} to {}'.format(A,C));return _download_file(_rewrite_url(A,B),C+_B+A.rsplit(_B)[-1])\n\t\telse:\n\t\t\tif not A.endswith('.json'):\n\t\t\t\tif not A.endswith(_B):A+=_B\n\t\t\t\tA+='package.json'\n\t\t\tprint('Installing {} to {}'.format(A,C))\n\telse:\n\t\tif not B:B='latest'\n\t\tprint('Installing {} ({}) from {} to {}'.format(A,B,D,C));E=sys.implementation._mpy&255 if mpy and hasattr(sys.implementation,'_mpy')else'py';A='{}/package/{}/{}/{}.json'.format(D,'py',A,B)\n\treturn _install_json(A,D,C,B,mpy)\ndef install(package,index=_A,target=_A,version=_A,mpy=_D):\n\tB=target;A=index\n\tif not B:\n\t\tfor C in sys.path:\n\t\t\tif C.endswith('/lib'):B=C;break\n\t\telse:print('Unable to find lib dir in sys.path');return\n\tif not A:A=_PACKAGE_INDEX\n\tif _install_package(package,A.rstrip(_B),B,version,mpy):print('Done')\n\telse:print('Package may be partially installed')");const Yt=async e=>(await import("./toml-DiUM0_qs.js")).parse(e),Xt=(e,t)=>{try{e.mkdir(t)}catch(e){}},Vt=Lt("mpy");var Zt={type:"micropython",module:(e="1.24.0-preview-114")=>`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}=Oe({stderr:Fe(console.error),stdout:Fe(console.log)});n=n.replace(/\.m?js$/,".wasm"),Vt("Loading MicroPython");const i=await a(e({linebuffer:!1,stderr:s,stdout:o,url:n})),l=Qt.bind(this,i,r);return Wt.set(i,l),await Ht(this,Vt,i,t,r),this.writeFile(i,"./mip.py",Kt),t.packages&&(Vt("Loading packages"),await l(t.packages),Vt("Loaded packages")),Vt("Loaded MicroPython"),i},registerJSModule:Ut,run:qt,runAsync:zt,runEvent:Gt,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},l=Jt(t,r);if(l){const r=t.slice(0,-1);switch("./"!==r&&s.mkdir(r),l){case"whl":case"zip":{const e=new Blob([n],{type:"application/zip"});return import("./zip-DrwYHuF9.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)Xt(s,i);else{Xt(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 Rt(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 Rt(i,t,n)}};async function Qt(e,t,n){let r;for(const s of n)if(s.endsWith(".whl")){const n=ut(s,t),r=await a(n).arrayBuffer();await this.writeFile(e,"./*",r,n)}else r||(r=e.pyimport("mip")),r.install(s)}const en={dict_converter:Object.fromEntries};let tn=!1;const nn=e=>(...t)=>{try{return tn=!0,e(...t)}finally{tn=!1}};let rn=!1;const sn=()=>{if(rn)return;rn=!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){tn=!1;let o=e.get(s)?.deref();if(!o)try{o=Ce(s.copy(),t),e.set(s,new WeakRef(o))}catch(e){console.error(e)}o&&(n[r]=o),tn=!0}}},{call:r}=Function,s=r.bind(r,r.apply);Object.defineProperties(Function.prototype,{apply:{value(e,t){return tn&&n(t),s(this,e,t)}},call:{value(e,...t){return tn&&n(t),s(this,e,t)}}})},on=Lt("py");var an={type:"pyodide",module:(e="0.26.2")=>`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},t,n,r){xt||"auto"!==t.experimental_create_proxy||sn(),on("Loading Pyodide");const{stderr:s,stdout:o,get:a}=Oe(),i=n.slice(0,n.lastIndexOf("/")),l=await a(e({stderr:s,stdout:o,indexURL:i})),c=cn.bind(l);return Wt.set(l,c),await Ht(this,on,l,t,r),t.packages&&await c(t.packages),on("Loaded Pyodide"),l},registerJSModule:Ut,run:nn(qt),runAsync:nn(zt),runEvent:nn(Gt),transform:(e,t)=>ln.call(e,t),writeFile:(e,t,n,r)=>{const s=Jt(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 Rt({FS:o,PATH:a,PATH_FS:i},t,n)}};function ln(e){const{ffi:{PyProxy:t}}=this;if(e&&"object"==typeof e){if(e instanceof t)return e.toJs(en);if(e instanceof Map)return new Map([...e.entries()]);if(rt(e))return e.map(ln,this)}return e}async function cn(e){const{log:t}=console,n=(e,...r)=>{t(e,...r),console.log=t,on(e),console.log=n};console.log=n,await this.loadPackage("micropip");const r=this.pyimport("micropip");await r.install(e,{keep_going:!0}),console.log=t,r.destroy()}const pn="ruby-wasm-wasi",un=pn.replace(/\W+/g,"_");var dn={type:pn,experimental:!0,module:(e="2.6.2")=>`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 a(n).arrayBuffer(),o=await WebAssembly.compile(s),{vm:i}=await e(o);return t.files&&await It(this,i,t.files,r),t.fetch&&await Ot(this,i,t.fetch,r),t.js_modules&&await Nt(t.js_modules,r),i},registerJSModule(e,t,n){t=t.replace(/\W+/g,"__");const r=`__module_${un}_${t}`;globalThis[r]=n,this.run(e,`require "js";$${t}=JS.global[:${r}]`),delete globalThis[r]},run:(e,t,...n)=>e.eval(tt(t),...n),runAsync:(e,t,...n)=>e.evalAsync(tt(t),...n),async runEvent(e,t,n){if(/^xworker\.(on\w+)$/.test(t)){const{$1:t}=RegExp,r=`__module_${un}_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 ${pn}`)}};var fn={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}=Oe(),l=await i((new e).createEngine());return l.global.getTable(t.Base,(e=>{l.global.setField(e,"print",a),l.global.setField(e,"printErr",o)})),n.files&&await It(this,l,n.files,s),n.fetch&&await Ot(this,l,n.fetch,s),n.js_modules&&await Nt(n.js_modules,s),l},registerJSModule:(e,t,n)=>{e.global.set(t,n)},run:(e,t,...n)=>{try{return e.doStringSync(tt(t),...n)}catch(t){De.get(e).stderr(t)}},runAsync:async(e,t,...n)=>{try{return await e.doString(tt(t),...n)}catch(t){De.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){De.get(e).stderr(t)}},transform:(e,t)=>t,writeFile:({cmodule:{module:{FS:e}}},t,n)=>((e,t,n)=>($t(e,St(t)),t=Pt(e,t),e.writeFile(t,new Uint8Array(n),{canOwn:!0})))(e,t,n)};const _n=new WeakMap,mn=async(e,t)=>{const{shelter:n,destroy:r,io:s}=_n.get(e),{output:o,result:a}=await n.captureR(tt(t));for(const{type:e,data:t}of o)s[e](t);return Ce(a,r,{token:!1})};var yn={type:"webr",experimental:!0,module:(e="0.4.2")=>`https://cdn.jsdelivr.net/npm/webr@${e}/dist/webr.mjs`,async engine(e,t,n,r){const{get:s}=Oe(),o=new e.WebR;await s(o.init().then((()=>o)));const a=await new o.Shelter;return _n.set(o,{module:e,shelter:a,destroy:a.destroy.bind(a),io:De.get(o)}),t.files&&await It(this,o,t.files,r),t.fetch&&await Ot(this,o,t.fetch,r),t.js_modules&&await Nt(t.js_modules,r),o},registerJSModule(e,t){console.warn(`Experimental interpreter: module ${t} is not supported (yet)`)},run:mn,runAsync:mn,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 hn=new Map,An=new Map,gn=[],wn=[],En=new Proxy(new Map,{get(e,t){if(!e.has(t)){const[n,...r]=t.split("@"),s=hn.get(n),o=/^(?:\.?\.?\/|[a-z0-9-]+:\/\/)/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=>(An.set(t,e),s(r,e,n,o))))}}),bn=e=>{for(const t of[].concat(e.type))hn.set(t,e),gn.push(`script[type="${t}"]`),wn.push(`${t}-`)};for(const e of[We,Zt,an,dn,fn,yn])bn(e);const{parse:vn}=JSON,Bn=(e,t="./config.txt")=>{let n=typeof e;return"string"===n&&/\.(json|toml|txt)$/.test(e)?n=RegExp.$1:e=t,[ut(e),n]},Cn=(e,t,n={})=>{const[r,s]=Bn(e,t);return"json"===s?n=a(r).json():"toml"===s?n=a(r).text().then(Yt):"string"===s?n=kn(e):"object"===s&&e?n=e:"txt"===s&&"string"==typeof n&&(n=kn(n)),[n,e=r]},kn=e=>{try{return vn(e)}catch(t){return Yt(e)}},jn=(e,t,n,r={})=>(t&&([r,t]=Cn(t,n,r)),pt(r).then((n=>En[e](n,t)))),xn=(e,t="")=>`${e}@${t}`.replace(/@$/,"");function Rn(e=this){return String(e).replace(/^(async\s*)?(\bfunction\b)?(.*?)\(/,((e,t,n,r)=>r&&!n?`${t||""}function ${r}(`:e))}const Sn="BeforeRun",$n="AfterRun",Pn=[`code${Sn}`,`code${Sn}Async`,`code${$n}`,`code${$n}Async`],Tn=["onWorker","onReady",`on${Sn}`,`on${Sn}Async`,`on${$n}`,`on${$n}Async`];function Dn(e,t){const{run:n,runAsync:r}=hn.get(this.type);return{...e,run:n.bind(this,t),runAsync:r.bind(this,t)}}const On=(e,t,n,r,s,o)=>{if(s||o){const a=Dn.bind(e,t),i=r?"runAsync":"run",l=e[i];e[i]=r?async function(e,t,...r){s&&await s.call(this,a(e),n);const i=await l.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=l.call(this,e,t,...r);return o&&o.call(this,a(e),n),i}}};let Mn=class{constructor(e,t={}){const{main:n,worker:r}=t;this.interpreter=e,this.onWorker=n?.onWorker;for(const e of Tn.slice(1))this[e]=r?.[e];for(const e of Pn)this[e]=r?.[e]}toJSON(){const e={};for(const t of Tn.slice(1))this[t]&&(e[t]=Rn(this[t]));for(const t of Pn)this[t]&&(e[t]=tt(this[t]()));return e}};var Fn=(...e)=>function(t,n){if(e.length){const[t,r]=e;(n=st({},n||{type:t,version:r})).type||(n.type=t)}const[r]=Bn(n.config,n.configURL),s=((...e)=>new Te(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,u]=o(r);switch(l){case 0:{let t=r;switch(u){case"bigint":l=8,t=r.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);t=null;break;case"undefined":return i([-1],r)}return i([l,t],r)}case 1:{if(u)return i([u,[...r]],r);const e=[],t=i([l,e],r);for(const t of r)e.push(c(t));return t}case 2:{if(u)switch(u){case"BigInt":return i([u,r.toString()],r);case"Boolean":case"Number":case"String":return i([u,r.valueOf()],r)}if(t&&"toJSON"in r)return c(r.toJSON());const n=[],p=i([l,n],r);for(const t of s(r))!e&&a(o(r[t]))||n.push([c(t),c(r[t])]);return p}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:p}=r;return i([l,{name:u,message:p}],r)};return c})(!(t||n),!!t,new Map,r)(e),r},{parse:c,stringify:l}=JSON,u={json:!0,lossy:!0};var p=Object.freeze({__proto__:null,parse:e=>t(c(e)),stringify:e=>l(i(e,u))});const f="apply",d="construct",y="defineProperty",h="deleteProperty",g="get",w="getOwnPropertyDescriptor",m="getPrototypeOf",_="has",A="isExtensible",b="ownKeys",E="preventExtensions",v="set",x="setPrototypeOf";var k=Object.freeze({__proto__:null,APPLY:f,CONSTRUCT:d,DEFINE_PROPERTY:y,DELETE_PROPERTY:h,GET:g,GET_OWN_PROPERTY_DESCRIPTOR:w,GET_PROTOTYPE_OF:m,HAS:_,IS_EXTENSIBLE:A,OWN_KEYS:b,PREVENT_EXTENSION:E,SET:v,SET_PROTOTYPE_OF:x});const j="destruct",S="f9d26a47-9015-443e-bfa3-307ca8b90cc8",$="="+S,P="-"+S,{ArrayBuffer:B,Atomics:T,Promise:O}=globalThis,{isArray:R}=Array,{create:M,getPrototypeOf:C,values:F}=Object,D=C(Int32Array),I=M(T),W=({currentTarget:e,type:t,origin:n,lastEventId:r,source:s,ports:o},a)=>e.dispatchEvent(new MessageEvent(t,{data:a,origin:n,lastEventId:r,source:s,ports:o})),L=()=>O.withResolvers();let H=0;const N=new Map,J=(e,t)=>class extends e{constructor(e,...n){super(e,...n),e instanceof t&&N.set(this,[H++,0,L()])}},q=new WeakSet,z=e=>(q.add(e),e),U=(e,t)=>{const{data:n}=e,r=R(n)&&(n.at(0)===t||0===n.at(1)&&!t);return r&&(e.stopImmediatePropagation(),e.preventDefault()),r},K=e=>null!==e&&"object"==typeof e&&!q.has(e),G=new WeakMap,Y=(e,t,n)=>{if(N.has(e))t.set(e,N.get(e)[0]);else if(!(e instanceof D||e instanceof B))for(const r of F(e))K(r)&&!n.has(r)&&(n.add(r),Y(r,t,n))},X=(...e)=>({value:new O((t=>{let n=new Worker("data:application/javascript,onmessage%3De%3D%3EpostMessage(!Atomics.wait(...e.data))");n.onmessage=()=>t("ok"),n.postMessage(e)}))}),Z=(e,t)=>{const n=N.get(e),[r,s,{promise:o}]=n;return n[1]=t,[r,o]};let{BigInt64Array:V,Int32Array:Q,SharedArrayBuffer:ee,addEventListener:te,postMessage:ne}=globalThis,re=!0,se=e=>e,oe=!1;const ae=L();try{new ee(4),I.waitAsync||(I.waitAsync=X),ae.resolve()}catch(e){const t=ne,n=te,r=[];let s="",o="";ee=class extends B{},V=J(V,ee),Q=J(Q,ee),se=z,oe=!0,I.notify=(e,n)=>{const[r]=(e=>G.get(e))(e);return t([s,1,e,r,n]),0},I.waitAsync=(...e)=>{const[t,n]=Z(...e);return{value:n}},I.wait=(e,t,...n)=>{const[r]=Z(e,t,...n),a=new XMLHttpRequest;a.responseType="json",a.open("POST",`${o}?sabayon`,!1),a.setRequestHeader("Content-Type","application/json"),a.send(`["${s}",${r},${t}]`);const{response:i}=a;N.delete(e);for(let t=0;t<i.length;t++)e[t]=i[t];return"ok"},n("message",(e=>{if(U(e,s)){const[t,n,...r]=e.data;switch(n){case 0:s=t,o=r.at(0)?.serviceWorker||"",o||(I.wait=null,ae.resolve());break;case 1:((e,t,n)=>{for(const[r,[s,o,{resolve:a}]]of N)if(t===s&&n===o){for(let t=0;t<e.length;t++)r[t]=e[t];N.delete(r),a("ok");break}})(...r);break;case 2:((e,t,n)=>{for(const[n,r]of t)G.set(n,[r,e.currentTarget]);W(e,n)})(e,...r);break;case 3:ae.resolve()}}else if(re){const{currentTarget:t,type:n,origin:s,lastEventId:o,source:a,ports:i}=e;r.push([{currentTarget:t,type:n,origin:s,lastEventId:o,source:a,ports:i},e.data])}})),te=(e,...t)=>{if(n(e,...t),r.length)for(const e of r.splice(0))W(...e)},ne=(e,...n)=>t(((e,t)=>{const n=new Map;return K(t)&&Y(t,n,new Set),n.size?[e,2,n,t]:t})(s,e),...n)}await ae.promise,re=!1;const{BYTES_PER_ELEMENT:ie}=Int32Array,{BYTES_PER_ELEMENT:ce}=Uint16Array,{notify:le}=I,ue=new TextDecoder("utf-16"),pe=new WeakSet,fe=(...e)=>(pe.add(e),e);let de="";const ye=(e,t,n,r)=>{const[s]=r,o=n.get(s);if(!o)throw new Error(`Unknown proxy.${s}()`);e(o,t,r)};let he=0;const ge=([e,t,n,r,s,o,a,i,c],l)=>(...u)=>{let p=""!==de,f=0;p&&"="!==de[0]&&"-"!==de[0]&&(f=((e,t)=>setTimeout(console.warn,3e3,`💀🔒 - proxy.${e}() in proxy.${t}()`))(l,de));const d=he++,y=[];pe.has(u.at(-1)||y)&&pe.delete(y=u.pop());const h=n(i?u.map(i):u);let g=t(2*ie);return a([e,2,l,d,g,h,r],{transfer:y}),c(g,0).value.then((()=>{p&&clearTimeout(f);const n=g[1];if(!n)return;const r=ce*n;return g=t(r+r%ie),a([e,1,d,g]),c(g,0).value.then((()=>{const e=new Uint16Array(g.buffer),t=o?e.subarray(0,n):e.slice(0,n);return s(ue.decode(t))}))}))},we=(e,t)=>new Proxy(t,{get:(t,n)=>{let r;return"then"!==n&&(r=t.get(n),r||(r=ge(e,n),t.set(n,r))),r},set:(e,t,n)=>"then"!==t&&!!e.set(t,n)}),{wait:me,waitAsync:_e}=I;var Ae=({parse:e,stringify:t,transform:n,interrupt:r}=JSON)=>{const s=((e,t)=>async(n,r,[s,o,a,i,c])=>{c&&(de=s);try{const s=await n(...i);if(void 0!==s){const n=e(t?t(s):s);r.set(o,n),a[1]=n.length}}finally{c&&(de=""),a[0]=1,le(a,0)}})(t,n),o=L(),a=new Map,i=new Map;let c="",l=me;if(me&&r){const{handler:e,timeout:t=42}=r;l=(n,r,s)=>{for(;"timed-out"===(s=me(n,r,0,t));)e();return s}}return te("message",(t=>{if(U(t,c)){const[r,u,...p]=t.data;switch(u){case 0:{const t=!!me;c=r,o.resolve({polyfill:oe,sync:t,transfer:fe,proxy:we([c,e=>new Q(new ee(e)),se,t,e,oe,ne,n,t?(...e)=>({value:{then:t=>t(l(...e))}}):_e],a)});break}case 2:a.size?ye(s,i,a,p):setTimeout(ye,0,s,i,a,p);break;case 1:((e,[t,n])=>{const r=e.get(t);e.delete(t);for(let e=new Uint16Array(n.buffer),t=0,{length:s}=r;t<s;t++)e[t]=r.charCodeAt(t);le(n,0)})(i,p)}}})),o.promise};const be="array",Ee="function",ve="null",xe="number",ke="object",je="symbol",Se="undefined";function $e(){return this}const Pe=new FinalizationRegistry((([e,t,n])=>{n&&console.debug(`Held value ${String(t)} not relevant anymore`),e(t)})),Be=Object.create(null),{Object:Te,Proxy:Oe,Reflect:Re}=globalThis,{isArray:Me}=Array,{ownKeys:Ce}=Re,{create:Fe,hasOwn:De,values:Ie}=Te,We=(e,t)=>t===be?e[0]:t===Ee?e():t===ke?e.$:e,Le=(e,t,n,r)=>{const s={type:{value:t}},o=De(e,"valueOf");for(const a of Ie(k)){let i=r(e[a]||Re[a]);if(o&&a===g){const{valueOf:r}=e,{value:s}=i;i={value(e,o,...a){return o===n?r.call(this,We(e,t)):s.call(this,e,o,...a)}}}s[a]=i}return Fe(e,s)},He=(e,t,n,r=e)=>{if(r===e)switch(typeof e){case ke:case Se:r||(r=!1);case Ee:break;default:r=!1,t===e&&(t=Te(e))}const s=new Oe(t,n),{destruct:o}=n;return o?((e,t,{debug:n,handler:r,return:s,token:o=e}=Be)=>{const a=s||new Proxy(e,r||Be),i=[a,[t,e,!!n]];return!1!==o&&i.push(o),Pe.register(...i),a})(e,o,{token:r,return:s}):s},Ne=e=>t=>{const n=typeof t;return n===ke?t?e.get(t)?.[0]??(e=>Me(e)?be:ke)(t):ve:n},Je=e=>t=>{let n=typeof t;switch(n){case ke:if(!t){n=ve;break}case Ee:const r=e.get(t);r&&([n,t]=r)}return[n,t]},qe=e=>((e=>{Pe.unregister(e)})(e),e);var ze=e=>{const t=new WeakMap,n=Symbol(),r={},s=(e,n,r)=>(t.set(e,[n,r]),e),o={proxy:r,release:qe,pair:Je(t),typeOf:Ne(t),isProxy:e=>t.has(e),valueOf:e=>e[n]??e.valueOf()};for(const t of Ce(e)){if(De(o,t))continue;const a=e[t];switch(t){case be:{const e=Le(a,t,n,(e=>({value([t],...n){return e.call(this,t,...n)}})));r[t]=(t,...n)=>s(He(t,[t],e,...n),be,t);break}case Ee:{const e=Le(a,t,n,(e=>({value(t,...n){return e.call(this,t(),...n)}})));r[t]=(t,...n)=>{return s(He(t,(r=t,$e.bind(r)),e,...n),Ee,t);var r};break}case ke:{const e=Le(a,t,n,(e=>({value({$:t},...n){return e.call(this,t,...n)}})));r[t]=(t,...n)=>s(He(t,{$:t},e,...n),ke,t);break}default:{const e=Le(a,t,n,(e=>({value:e})));r[t]=(n,...r)=>s(He(n,n,e,...r),t,n);break}}}return o};const{drop:Ue,get:Ke,hold:Ge}=(()=>{const e=new Map,t=new Map;let n=0;return{drop:n=>{const[r,s]=typeof n===xe?[t,e]:[e,t],o=r.has(n);return o&&(s.delete(r.get(n)),r.delete(n)),o},get:e=>t.get(e),hold:r=>{if(!e.has(r)){let s;for(;t.has(s=n++););e.set(r,s),t.set(s,r)}return e.get(r)}}})();var Ye=Object.fromEntries([be,"bigint","boolean",Ee,ve,xe,ke,"string",je,Se].map(((e,t)=>[e,t])));const{[b]:Xe}=Reflect,Ze=new Map(Xe(Symbol).filter((e=>typeof Symbol[e]===je)).map((e=>[Symbol[e],e]))),Ve=e=>Ze.get(e)||`.${Symbol.keyFor(e)||""}`,{isArray:Qe}=Array,{[f]:et}=Reflect;var tt=(e,t)=>{const n=new Map,r=(e,t)=>{let r=n.get(e)?.deref();return r||n.set(e,new WeakRef(r=t(e))),r},s=([e,t])=>{switch(e){case Ye[ke]:return null==t?globalThis:typeof t===xe?r(t,l.object):t;case Ye[be]:return typeof t===xe?r(t,l.array):t;case Ye[Ee]:return typeof t===xe?r(t,l.function):Ke(parseInt(t));case Ye[je]:return(e=>{if(e.startsWith("."))return Symbol.for(e.slice(1));for(const[t,n]of Ze)if(n===e)return t})(t);default:return t}},o=e=>{let[n,r]=p(e);switch(n){case ke:if(r==globalThis||null==r)r=null;else if(typeof r===ke&&!(r instanceof D))if(r=t(r),Qe(r))r=r.map(o);else for(const e in r)r[e]=o(r[e]);return[Ye[ke],r];case be:return[Ye[be],typeof r===xe?r:t(r).map(o)];case Ee:return[Ye[Ee],typeof r===Ee?String(Ge(t(r))):r];case je:return[Ye[je],Ve(e)];default:return[Ye[n],r]}},a=(...t)=>s(e(...t)),i={[y]:(e,t,n)=>a(y,e,o(t),o(n)),[h]:(e,t)=>a(h,e,o(t)),[g]:(e,t)=>a(g,e,o(t)),[m]:e=>a(m,e),[w]:(e,t)=>{const n=a(w,e,o(t));if(n){const{get:e,set:t,value:r}=n;e&&(n.get=s(e)),t&&(n.set=s(t)),r&&(n.value=s(r))}return n},[_]:(e,t)=>a(_,e,o(t)),[A]:e=>a(A,e),[b]:e=>a(b,e).map(s),[E]:e=>a(E,e),[v]:(e,t,n)=>a(v,e,o(t),o(n)),[x]:(e,t)=>a(x,e,o(t)),[j](t){n.delete(t),e(j,t)}},c={[ke]:i,[be]:i,[Ee]:{...i,[f]:(e,...t)=>a(f,e,...t.map(o)),[d]:(e,...t)=>a(d,e,...t.map(o))}},{proxy:l,isProxy:u,pair:p}=ze(c);return{isProxy:u,global:l.object(null),method:async(e,t,...n)=>{const r=parseInt(t);switch(e){case f:{const[e,t]=n;return o(await et(Ke(r),s(e),t.map(s)))}case j:Ue(r)}}}};const{assign:nt}=Object,rt="entries",st="readonly",ot="readwrite",at={durability:"default",prefix:"IDBMap"},it=({target:{result:e}})=>e;class ct extends EventTarget{#e;#t;#n;async#r(e,t){const n=(await this.#e).transaction(rt,t,this.#t);return new Promise(((t,r)=>nt(e(n.objectStore(rt)),{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)=>{nt(indexedDB.open(`${this.#n}/${e}`),{onupgradeneeded({target:{result:e,transaction:n}}){e.objectStoreNames.length||e.createObjectStore(rt),n.oncomplete=()=>t(e)},onsuccess(e){t(it(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?nt(new Event(t),{message:n}):e)}async close(){(await this.#e).close()}get size(){return this.#r((e=>e.count()),st).then(it)}async clear(){await this.#r((e=>e.clear()),ot)}async delete(e){await this.#r((t=>t.delete(e)),ot)}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)),st).then(it)}async has(e){return void 0!==await this.#r((t=>t.getKey(e)),st).then(it)}async keys(){return await this.#r((e=>e.getAllKeys()),st).then(it)}async set(e,t){return await this.#r((n=>n.put(t,e)),ot),this}async values(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e))))}get[Symbol.toStringTag](){return this.#n}}class lt extends Map{#s;#o;constructor(...e){super(),this.#s=new ct(...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 ut={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}},pt=new WeakMap,ft=e=>{const t=e||console,n={buffered:yt,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 pt.set(t,n),t}}},dt=new TextDecoder,yt=(e,t=10)=>{const n=[];return r=>{if(r instanceof Uint8Array)for(const s of r)s===t?e(dt.decode(new Uint8Array(n.splice(0)))):n.push(s);else e(r)}},ht=(e,...t)=>ut[typeof e](e,...t),{isArray:gt}=Array,{assign:wt,create:mt,defineProperties:_t,defineProperty:At,entries:bt}=Object,{all:Et,resolve:vt}=new Proxy(Promise,{get:(e,t)=>e[t].bind(e)}),xt=(e,t=location.href)=>new URL(e,t.replace(/^blob:/,"")).href,kt=(e,t,n,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${t}:${n}`,{bubbles:!0,detail:{worker:r}}))},jt=e=>Function(`\'use strict\';return (${e})`)(),St=e=>e.replace(/^(?:\\n|\\r\\n)/,""),$t=Symbol.for("polyscript.js_modules"),Pt=new Map;At(globalThis,$t,{value:Pt}),new Proxy(Pt,{get:(e,t)=>e.get(t),has:(e,t)=>e.has(t),ownKeys:e=>[...e.keys()]});const Bt=(e,t)=>!t.startsWith("_"),Tt=(e,t)=>new Proxy(e,{has:Bt,get:(e,n)=>e[t][n]}),Ot=(e,t)=>import(e).then((e=>{Pt.set(t,{...e})})),Rt=e=>new Promise(((t,n)=>{document.querySelector(`link[rel="stylesheet"][href="${e}"]`)?t():document.head.append(wt(document.createElement("link"),{rel:"stylesheet",href:e,onload:t,onerror:n}))})),Mt=e=>/\\.css$/i.test(new URL(e).pathname),Ct=(e,t)=>e.has(t),Ft=e=>[...e.keys()];var Dt=(e,t,n,r)=>{const s=globalThis[$t];if(n)for(let[e,t]of bt(n)){let n=s.get(t);n&&!gt(n)||(s.set(t,n||(n=[])),n.push(e))}return((e,t,n,r)=>new Proxy(e,{has:Ct,ownKeys:Ft,get:(e,s)=>{let o=e.get(s);if(gt(o)){let a=o;o=null;for(let e of a)e=xt(e,r),Mt(e)?n.importCSS(e):(n.importJS(e,s),o=t[$t].get(s));e.set(s,o)}return o}}))(s,e,t,r)};const It=new Map,Wt=e=>It.get(e),Lt=(e,t)=>{try{return Function("require",t)(Wt)}catch(t){pt.get(e).stderr(t)}};var Ht={type:"dummy",module:()=>"data:application/javascript,",engine:e=>ft().get(e),registerJSModule(e,t,n){It.set(t,n)},run:Lt,runAsync:Lt,runEvent:async(e,t,n)=>{try{await Function("require","e",`return ${t}(e)`)(Wt,n)}catch(t){pt.get(e).stderr(t)}},transform:(e,t)=>t,writeFile(){}};const Nt=Object.getOwnPropertyDescriptors(Response.prototype),Jt=e=>"function"==typeof e,qt={get:(e,t)=>Nt.hasOwnProperty(t)?((e,t,{get:n,value:r})=>n||!Jt(r)?e.then((e=>e[t])):(...n)=>e.then((e=>e[t](...n))))(e,t,Nt[t]):((e,t)=>Jt(t)?t.bind(e):t)(e,e[t])};var zt=(e,...t)=>new Proxy(fetch(e,...t),qt);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,Kt=({FS:e,PATH:t,PATH_FS:n},r,s)=>{const o=n.resolve(r),a=t.dirname(o);return e.mkdirTree?e.mkdirTree(a):Yt(e,a),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},Gt=e=>{const t=e.split("/");return t.pop(),t.join("/")},Yt=(e,t)=>{const n=[];for(const r of t.split("/"))"."!==r&&".."!==r&&(n.push(r),r&&e.mkdir(n.join("/")))},Xt=(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(/^\\/+/,"/")},Zt=e=>{const t=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,""))).filter((e=>""!==e&&"."!==e)).join("/");return e[0].startsWith("/")?`/${t}`:t},Vt=(e,t)=>zt(xt(e,t)).arrayBuffer(),Qt=(e,t,n,r)=>Et((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(gt(r))return r.map((n=>({url:Zt([e,n]),path:Zt([t,n])})));const s=n||e.slice(1+e.lastIndexOf("/"));return[{url:e,path:Zt([t,s])}]}))})(n).map((({url:n,path:s})=>Vt(n,r).then((n=>e.writeFile(t,s,n)))))),en=(e,t)=>t.endsWith("/")?`${t}${e.split("/").pop()}`:t,tn=(e,t)=>e.replace(/\\{.+?\\}/g,(e=>{if(!t.has(e))throw new SyntaxError(`Invalid template: ${e}`);return t.get(e)})),nn=(e,t,n,r)=>Et((e=>{const t=new Map,n=new Set,r=[];for(const[s,o]of bt(e))if(/^\\{.+\\}$/.test(s)){if(t.has(s))throw new SyntaxError(`Duplicated template: ${s}`);t.set(s,tn(o,t))}else{const e=tn(s,t),a=en(e,tn(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})=>Vt(n,r).then((r=>e.writeFile(t,s,r,n)))))),rn=({main:e,worker:t},n)=>{const r=[];if(t&&Ut)for(let[e,s]of bt(t))e=xt(e,n),r.push(Ot(e,s));if(e&&!Ut)for(let[t,s]of bt(e))t=xt(t,n),Mt(t)?Rt(t):r.push(Ot(t,s));return Et(r)},sn=e=>t=>{dispatchEvent(new CustomEvent(`${e}:progress`,{detail:t}))},on=new WeakMap,an=async(e,t,n,r,s)=>{r.files&&(t("Loading files"),await nn(e,n,r.files,s),t("Loaded files")),r.fetch&&(t("Loading fetch"),await Qt(e,n,r.fetch,s),t("Loaded fetch")),r.js_modules&&(t("Loading JS modules"),await rn(r.js_modules,s),t("Loaded JS modules"))},cn=(e,t,n)=>{"polyscript"===t&&(n.lazy_py_modules=async(...t)=>(await on.get(e)(t),t.map((t=>e.pyimport(t)))),n.storage=async e=>{const t=new lt(e);return await t.sync(),t},n.JSON=p),e.registerJsModule(t,n)},ln=(e,t)=>{if(e.endsWith("/*")){if(/\\.(zip|whl|tgz|tar(?:\\.gz)?)$/.test(t))return RegExp.$1;throw new Error(`Unsupported archive ${t}`)}return""},un=(e,t,...n)=>{try{return e.runPython(ht(t),...n)}catch(t){pt.get(e).stderr(t)}},pn=async(e,t,...n)=>{try{return await e.runPythonAsync(ht(t),...n)}catch(t){pt.get(e).stderr(t)}},fn=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){pt.get(e).stderr(t)}};var dn=(new TextEncoder).encode("_F=\'github:\'\\n_E=\'user-agent\'\\n_D=True\\n_C=False\\n_B=\'/\'\\n_A=None\\nfrom uio import StringIO\\nimport sys\\nclass Response:\\n\\tdef __init__(A,f):A.raw=f;A.encoding=\'utf-8\';A._cached=_A\\n\\tdef close(A):\\n\\t\\tif A.raw:A.raw.close();A.raw=_A\\n\\t\\tA._cached=_A\\n\\t@property\\n\\tdef content(self):\\n\\t\\tA=self\\n\\t\\tif A._cached is _A:\\n\\t\\t\\ttry:A._cached=A.raw.read()\\n\\t\\t\\tfinally:A.raw.close();A.raw=_A\\n\\t\\treturn A._cached\\n\\t@property\\n\\tdef text(self):return str(self.content,self.encoding)\\n\\tdef json(A):import ujson;return ujson.loads(A.content)\\nHEADERS_TO_IGNORE=_E,\\ntry:import js\\nexcept Exception as err:raise OSError(\'This version of urequests can only be used in the browser\')\\nHEADERS_TO_IGNORE=_E,\\ndef request(method,url,data=_A,json=_A,headers={},stream=_A,auth=_A,timeout=_A,parse_headers=_D):\\n\\tE=timeout;D=method;C=data;from js import XMLHttpRequest as G;A=G.new();A.withCredentials=_C\\n\\tif auth is not _A:import ubinascii;H,I=auth;A.open(D,url,_C,H,I)\\n\\telse:A.open(D,url,_C)\\n\\tfor(F,J)in headers.items():\\n\\t\\tif F.lower()not in HEADERS_TO_IGNORE:A.setRequestHeader(F,J)\\n\\tif E:A.timeout=int(E*1000)\\n\\tif json is not _A:assert C is _A;import ujson;C=ujson.dumps(json);A.setRequestHeader(\'Content-Type\',\'application/json\')\\n\\tA.send(C);B=Response(StringIO(A.responseText));B.status_code=A.status;B.reason=A.statusText;B.headers=A.getAllResponseHeaders();return B\\ndef get(url,**A):return request(\'GET\',url,**A)\\n_PACKAGE_INDEX=const(\'https://micropython.org/pi/v2\')\\n_CHUNK_SIZE=128\\ndef _ensure_path_exists(path):\\n\\timport os;A=path.split(_B)\\n\\tif not A[0]:A.pop(0);A[0]=_B+A[0]\\n\\tB=\'\'\\n\\tfor C in range(len(A)-1):\\n\\t\\tB+=A[C]\\n\\t\\ttry:os.stat(B)\\n\\t\\texcept:os.mkdir(B)\\n\\t\\tB+=_B\\ndef _chunk(src,dest):\\n\\tA=memoryview(bytearray(_CHUNK_SIZE))\\n\\twhile _D:\\n\\t\\tB=src.readinto(A)\\n\\t\\tif B==0:break\\n\\t\\tdest(A if B==_CHUNK_SIZE else A[:B])\\ndef _check_exists(path,short_hash):\\n\\tA=short_hash;import os\\n\\ttry:\\n\\t\\timport binascii as C,hashlib as D\\n\\t\\twith open(path,\'rb\')as E:B=D.sha256();_chunk(E,B.update);F=str(C.hexlify(B.digest())[:len(A)],\'utf-8\');return F==A\\n\\texcept:return _C\\ndef _rewrite_url(url,branch=_A):\\n\\tB=branch;A=url\\n\\tif not B:B=\'HEAD\'\\n\\tif A.startswith(_F):A=A[7:].split(_B);A=\'https://raw.githubusercontent.com/\'+A[0]+_B+A[1]+_B+B+_B+_B.join(A[2:])\\n\\treturn A\\ndef _download_file(url,dest):\\n\\tB=dest;A=get(url)\\n\\ttry:\\n\\t\\tif A.status_code!=200:print(\'Error\',A.status_code,\'requesting\',url);return _C\\n\\t\\tprint(\'Copying:\',B);_ensure_path_exists(B)\\n\\t\\twith open(B,\'wb\')as C:_chunk(A.raw,C.write)\\n\\t\\treturn _D\\n\\tfinally:A.close()\\ndef _install_json(package_json_url,index,target,version,mpy):\\n\\tK=\'File not found: {} {}\';I=version;H=index;G=package_json_url;D=target;E=get(_rewrite_url(G,I))\\n\\ttry:\\n\\t\\tif E.status_code!=200:print(\'Package not found:\',G);return _C\\n\\t\\tF=E.json()\\n\\tfinally:E.close()\\n\\tfor(A,C)in F.get(\'hashes\',()):\\n\\t\\tB=D+_B+A\\n\\t\\tif _check_exists(B,C):print(\'Exists:\',B)\\n\\t\\telse:\\n\\t\\t\\tL=\'{}/file/{}/{}\'.format(H,C[:2],C)\\n\\t\\t\\tif not _download_file(L,B):print(K.format(A,C));return _C\\n\\tfor(A,J)in F.get(\'urls\',()):\\n\\t\\tB=D+_B+A\\n\\t\\tif not _download_file(_rewrite_url(J,I),B):print(K.format(A,J));return _C\\n\\tfor(M,N)in F.get(\'deps\',()):\\n\\t\\tif not _install_package(M,H,D,N,mpy):return _C\\n\\treturn _D\\ndef _install_package(package,index,target,version,mpy):\\n\\tD=index;C=target;B=version;A=package\\n\\tif A.startswith(\'http://\')or A.startswith(\'https://\')or A.startswith(_F):\\n\\t\\tif A.endswith(\'.py\')or A.endswith(\'.mpy\'):print(\'Downloading {} to {}\'.format(A,C));return _download_file(_rewrite_url(A,B),C+_B+A.rsplit(_B)[-1])\\n\\t\\telse:\\n\\t\\t\\tif not A.endswith(\'.json\'):\\n\\t\\t\\t\\tif not A.endswith(_B):A+=_B\\n\\t\\t\\t\\tA+=\'package.json\'\\n\\t\\t\\tprint(\'Installing {} to {}\'.format(A,C))\\n\\telse:\\n\\t\\tif not B:B=\'latest\'\\n\\t\\tprint(\'Installing {} ({}) from {} to {}\'.format(A,B,D,C));E=sys.implementation._mpy&255 if mpy and hasattr(sys.implementation,\'_mpy\')else\'py\';A=\'{}/package/{}/{}/{}.json\'.format(D,\'py\',A,B)\\n\\treturn _install_json(A,D,C,B,mpy)\\ndef install(package,index=_A,target=_A,version=_A,mpy=_D):\\n\\tB=target;A=index\\n\\tif not B:\\n\\t\\tfor C in sys.path:\\n\\t\\t\\tif C.endswith(\'/lib\'):B=C;break\\n\\t\\telse:print(\'Unable to find lib dir in sys.path\');return\\n\\tif not A:A=_PACKAGE_INDEX\\n\\tif _install_package(package,A.rstrip(_B),B,version,mpy):print(\'Done\')\\n\\telse:print(\'Package may be partially installed\')");const yn=async e=>(await import("./toml-DiUM0_qs.js")).parse(e),hn=(e,t)=>{try{e.mkdir(t)}catch(e){}},gn=sn("mpy");var wn={type:"micropython",module:(e="1.24.0-preview-114")=>`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}=ft({stderr:yt(console.error),stdout:yt(console.log)});n=n.replace(/\\.m?js$/,".wasm"),gn("Loading MicroPython");const i=await a(e({linebuffer:!1,stderr:s,stdout:o,url:n})),c=mn.bind(this,i,r);return on.set(i,c),await an(this,gn,i,t,r),this.writeFile(i,"./mip.py",dn),t.packages&&(gn("Loading packages"),await c(t.packages),gn("Loaded packages")),gn("Loaded MicroPython"),i},registerJSModule:cn,run:un,runAsync:pn,runEvent:fn,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=ln(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-DrwYHuF9.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)hn(s,i);else{hn(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 Kt(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 Kt(i,t,n)}};async function mn(e,t,n){let r;for(const s of n)if(s.endsWith(".whl")){const n=xt(s,t),r=await zt(n).arrayBuffer();await this.writeFile(e,"./*",r,n)}else r||(r=e.pyimport("mip")),r.install(s)}const _n=new FinalizationRegistry((([e,t,n])=>{n&&console.debug(`%c${String(t)}`,"font-weight:bold","collected"),e(t)})),An=Object.create(null),bn=(e,t,{debug:n,handler:r,return:s,token:o=e}=An)=>{const a=s||new Proxy(e,r||An),i=[a,[t,e,!!n]];return!1!==o&&i.push(o),_n.register(...i),a},En={dict_converter:Object.fromEntries};let vn=!1;const xn=e=>(...t)=>{try{return vn=!0,e(...t)}finally{vn=!1}};let kn=!1;const jn=()=>{if(kn)return;kn=!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){vn=!1;let o=e.get(s)?.deref();if(!o)try{o=bn(s.copy(),t),e.set(s,new WeakRef(o))}catch(e){console.error(e)}o&&(n[r]=o),vn=!0}}},{call:r}=Function,s=r.bind(r,r.apply);Object.defineProperties(Function.prototype,{apply:{value(e,t){return vn&&n(t),s(this,e,t)}},call:{value(e,...t){return vn&&n(t),s(this,e,t)}}})},Sn=sn("py");var $n={type:"pyodide",module:(e="0.26.2")=>`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},t,n,r){Ut||"auto"!==t.experimental_create_proxy||jn(),Sn("Loading Pyodide");const{stderr:s,stdout:o,get:a}=ft(),i=n.slice(0,n.lastIndexOf("/")),c=await a(e({stderr:s,stdout:o,indexURL:i})),l=Bn.bind(c);return on.set(c,l),await an(this,Sn,c,t,r),t.packages&&await l(t.packages),Sn("Loaded Pyodide"),c},registerJSModule:cn,run:xn(un),runAsync:xn(pn),runEvent:xn(fn),transform:(e,t)=>Pn.call(e,t),writeFile:(e,t,n,r)=>{const s=ln(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 Kt({FS:o,PATH:a,PATH_FS:i},t,n)}};function Pn(e){const{ffi:{PyProxy:t}}=this;if(e&&"object"==typeof e){if(e instanceof t)return e.toJs(En);if(e instanceof Map)return new Map([...e.entries()]);if(gt(e))return e.map(Pn,this)}return e}async function Bn(e){const{log:t}=console,n=(e,...r)=>{t(e,...r),console.log=t,Sn(e),console.log=n};console.log=n,await this.loadPackage("micropip");const r=this.pyimport("micropip");await r.install(e,{keep_going:!0}),console.log=t,r.destroy()}const Tn="ruby-wasm-wasi",On=Tn.replace(/\\W+/g,"_");var Rn={type:Tn,experimental:!0,module:(e="2.6.2")=>`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 zt(n).arrayBuffer(),o=await WebAssembly.compile(s),{vm:a}=await e(o);return t.files&&await nn(this,a,t.files,r),t.fetch&&await Qt(this,a,t.fetch,r),t.js_modules&&await rn(t.js_modules,r),a},registerJSModule(e,t,n){t=t.replace(/\\W+/g,"__");const r=`__module_${On}_${t}`;globalThis[r]=n,this.run(e,`require "js";$${t}=JS.global[:${r}]`),delete globalThis[r]},run:(e,t,...n)=>e.eval(ht(t),...n),runAsync:(e,t,...n)=>e.evalAsync(ht(t),...n),async runEvent(e,t,n){if(/^xworker\\.(on\\w+)$/.test(t)){const{$1:t}=RegExp,r=`__module_${On}_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 ${Tn}`)}};var Mn={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}=ft(),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 nn(this,c,n.files,s),n.fetch&&await Qt(this,c,n.fetch,s),n.js_modules&&await rn(n.js_modules,s),c},registerJSModule:(e,t,n)=>{e.global.set(t,n)},run:(e,t,...n)=>{try{return e.doStringSync(ht(t),...n)}catch(t){pt.get(e).stderr(t)}},runAsync:async(e,t,...n)=>{try{return await e.doString(ht(t),...n)}catch(t){pt.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){pt.get(e).stderr(t)}},transform:(e,t)=>t,writeFile:({cmodule:{module:{FS:e}}},t,n)=>((e,t,n)=>(Yt(e,Gt(t)),t=Xt(e,t),e.writeFile(t,new Uint8Array(n),{canOwn:!0})))(e,t,n)};const Cn=new WeakMap,Fn=async(e,t)=>{const{shelter:n,destroy:r,io:s}=Cn.get(e),{output:o,result:a}=await n.captureR(ht(t));for(const{type:e,data:t}of o)s[e](t);return bn(a,r,{token:!1})};var Dn={type:"webr",experimental:!0,module:(e="0.4.2")=>`https://cdn.jsdelivr.net/npm/webr@${e}/dist/webr.mjs`,async engine(e,t,n,r){const{get:s}=ft(),o=new e.WebR;await s(o.init().then((()=>o)));const a=await new o.Shelter;return Cn.set(o,{module:e,shelter:a,destroy:a.destroy.bind(a),io:pt.get(o)}),t.files&&await nn(this,o,t.files,r),t.fetch&&await Qt(this,o,t.fetch,r),t.js_modules&&await rn(t.js_modules,r),o},registerJSModule(e,t){console.warn(`Experimental interpreter: module ${t} is not supported (yet)`)},run:Fn,runAsync:Fn,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 In=new Map,Wn=new Map,Ln=new Proxy(new Map,{get(e,t){if(!e.has(t)){const[n,...r]=t.split("@"),s=In.get(n),o=/^(?:\\.?\\.?\\/|[a-z0-9-]+:\\/\\/)/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=>(Wn.set(t,e),s(r,e,n,o))))}}),Hn=e=>{for(const t of[].concat(e.type))In.set(t,e)};for(const e of[Ht,wn,$n,Rn,Mn,Dn])Hn(e);const{parse:Nn}=JSON,Jn=(e,t,n={})=>{const[r,s]=((e,t="./config.txt")=>{let n=typeof e;return"string"===n&&/\\.(json|toml|txt)$/.test(e)?n=RegExp.$1:e=t,[xt(e),n]})(e,t);return"json"===s?n=zt(r).json():"toml"===s?n=zt(r).text().then(yn):"string"===s?n=qn(e):"object"===s&&e?n=e:"txt"===s&&"string"==typeof n&&(n=qn(n)),[n,e=r]},qn=e=>{try{return Nn(e)}catch(t){return yn(e)}},zn="BeforeRun",Un="AfterRun",Kn=[`code${zn}`,`code${zn}Async`,`code${Un}`,`code${Un}Async`],Gn=["onWorker","onReady",`on${zn}`,`on${zn}Async`,`on${Un}`,`on${Un}Async`];function Yn(e,t){const{run:n,runAsync:r}=In.get(this.type);return{...e,run:n.bind(this,t),runAsync:r.bind(this,t)}}const Xn=(e,t,n,r,s,o)=>{if(s||o){const a=Yn.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 Zn,Vn,Qn;const er=(e,t)=>{addEventListener(e,t||(async t=>{try{await Zn,Vn(`xworker.on${e}`,t)}catch(e){postMessage(e)}}),!!t&&{once:!0})},{parse:tr,stringify:nr}=p,{proxy:rr,sync:sr,polyfill:or,window:ar,isWindowProxy:ir}=await(async e=>{const t=await Ae(e),{isProxy:n,global:r,method:s}=tt(t.proxy[$],e?.transform||(e=>e));return t.proxy[P]=s,{...t,window:r,isWindowProxy:n}})({parse:tr,stringify:nr,transform:e=>Qn?Qn(e):e}),cr={polyfill:or,sync:rr,window:sr?ar:null,isWindowProxy:ir,onmessage:console.info,onerror:console.error,onmessageerror:console.warn,postMessage:postMessage.bind(self)};er("message",(({data:{options:e,config:t,configURL:n,code:r,hooks:s}})=>{Zn=(async()=>{try{const{id:o,tag:a,type:i,custom:c,version:l,config:u,async:p}=e,f=((e,t="")=>`${e}@${t}`.replace(/@$/,""))(i,l),d=await((e,t,n,r={})=>(t&&([r,t]=Jn(t,n,r)),vt(r).then((n=>Ln[e](n,t)))))(f,t,n,u),{js_modules:y}=Wn.get(f),h=y?.main,g=mt(In.get(i)),w=((e,t,n,r)=>({type:t,config:n,interpreter:r,io:pt.get(r),run:(t,...n)=>e.run(r,t,...n),runAsync:(t,...n)=>e.runAsync(r,t,...n),runEvent:(...t)=>e.runEvent(r,...t)}))(g,c||i,u||{},d);let m="run";if(p&&(m+="Async"),s){let e,t,n="",r="";for(const e of Kn){const t=s[e];if(t){const s=e.endsWith("Async");(s&&p||!s&&!p)&&(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,St(t),...o);return r&&s(e,r,...o),a}:async(e,t,...o)=>{n&&await s(e,n,...o);const a=await s(e,St(t),...o);return r&&await s(e,r,...o),a}})(g,m,n,r);for(const n of Gn.slice(2)){const r=s[n];if(r){const s=n.endsWith("Async");if(s&&p||!s&&!p){const s=jt(r);n.startsWith("onBefore")?e=s:t=s}}}Xn(g,w,cr,p,e,t)}let _,A,b,E=null,v="";sr&&(({CustomEvent:_,document:A}=ar),E=o&&A.getElementById(o)||null,b=e=>kt(E,c||i,e,!0,_));const x=Dt(ar,rr,h,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}`,Tt(r,e));t.registerJSModule(n,s,r)})(i,g,d,x),g.registerJSModule(d,"polyscript",{xworker:cr,currentScript:E,config:w.config,js_modules:x,get target(){return!v&&E&&("SCRIPT"===a?E.after(wt(ar.document.createElement(`script-${c||i}`),{id:v=`${o}-target`})):(v=o,E.replaceChildren(),E.style.display="block")),v}}),Vn=g.runEvent.bind(g,d),Qn=g.transform.bind(g,d),E&&b("ready"),s?.onReady&&jt(s?.onReady).call(g,Yn.call(g,w,d),cr),await g[m](d,r),["micropython","pyodide"].includes(g.type)){const e="polyscript",t=`__${e}_workers__`,n="__export__";d.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&&d.runPython([`from ${e} import xworker as ${t}`,...r.map((e=>`${t}.sync.${e} = ${e}`)),`del ${t}`].join("\\n"))}return E&&b("done"),postMessage("polyscript:done"),d}catch(e){postMessage(e)}})(),er("error"),er("message"),er("messageerror"),sr&&addEventListener("py:progress",(({type:e,detail:t})=>{ar.dispatchEvent(new ar.CustomEvent(e,{detail:t}))}))}));\n'.replace($e,Pe)],{type:"application/javascript"})),...e))({serviceWorker:n?.serviceWorker||n?.service_worker}),{postMessage:o}=s,i=this instanceof Mn,l=st(s.proxy,{importJS:Bt,importCSS:Ct}),c=Promise.withResolvers();let p=a(t).text().then((e=>{const t=i?this.toJSON():void 0;o.call(s,{options:n,config:r,code:e,hooks:t})})).then((()=>{p={then:e=>e()}}));return at(s,{sync:{value:l},ready:{value:c.promise},postMessage:{value:(e,...t)=>p.then((()=>o.call(s,e,...t)))},onerror:{writable:!0,configurable:!0,value:console.error}}),s.addEventListener("message",(e=>{const{data:t}=e,n=t instanceof Error;(n||"polyscript:done"===t)&&(e.stopImmediatePropagation(),n?(c.reject(t),s.onerror(ot(e,{type:{value:"error"},error:{value:t}}))):c.resolve(s))})),i&&this.onWorker?.(this.interpreter,s),s};const In="Invalid content";var Nn=e=>{const{src:t,worker:n}=e.attributes;if(n){let{value:r}=n;if(r)throw new SyntaxError("Invalid worker attribute");if(r=t?.value,!r){if(t)throw new SyntaxError("Invalid worker attribute");if(e.childElementCount){const{innerHTML:t,localName:n,type:s}=e,o=s||n.replace(/-script$/,"");r=nt(t),console.warn(`Deprecated: use <script type="${o}"> for an always safe content parsing:\n`,r)}else r=e.textContent;return URL.createObjectURL(new Blob([tt(r)],{type:"text/plain"}))}return r}if(t&&e.textContent.replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*(?:\/\/|#).*/gm,"").trim())throw new SyntaxError(In)};const Ln=(e,t)=>{const n=(e=>{let t=e;for(;t.parentNode;)t=t.parentNode;return t})(e);return n.getElementById(t)||((e,t=document)=>t.querySelector(e))(t,n)},Wn=new WeakMap,Hn={get(){let e=Wn.get(this);return e||(e=document.createElement(`${this.type}-script`),Wn.set(this,e),Gn(this)),e},set(e){"string"==typeof e?Wn.set(this,Ln(this,e)):(Wn.set(this,e),Gn(this))}},Un=new WeakMap,Jn=new Map,qn=(e,t)=>{const n=e?.value;return n?t+n:""},zn=(e,t,n,r,s,o,a=e)=>{if(!Jn.has(t)){const i={interpreter:jn(n,s,o),queue:pt(),XWorker:Fn(e,r)};Jn.set(t,i),Jn.has(e)||Jn.set(e,i),Jn.has(a)||Jn.set(a,i)}return Jn.get(t)},Gn=async e=>{if(Un.has(e)){const{target:t}=e;t&&(e.closest("head")?document.body.append(t):e.after(t))}else{const{attributes:{config:t,env:n,name:r,target:s,version:o,"service-worker":l},src:p,type:u}=e,d=!jt(e),f=o?.value,_=xn(u,f);let m=qn(t,"|");const y=qn(n,"")||`${_}${m}`;m=m.slice(1);const h=Nn(e);if(h){const t=new(Fn(u,f))(h,{...ft(e,u),version:f,async:d,config:m,serviceWorker:l?.value});Un.set(it(e,"xworker",{value:t}),{xworker:t});const n=r?.value;return void(n&&i[n].resolve(t.ready))}const A=qn(s,""),g=zn(u,y,_,f,m);Un.set(it(e,"target",Hn),g),A&&Wn.set(e,Ln(e,A));const w=p?a(p).text():e.textContent;g.queue=g.queue.then((()=>(async(e,t,n,r)=>{const{type:s}=e,o=hn.get(s);o.experimental&&console.warn(`The ${s} interpreter is experimental`);const[a,i]=await ct([Un.get(e).interpreter,t]);try{vt(s,o,a,wt),o.registerJSModule(a,"polyscript",{XWorker:n,currentScript:e,js_modules:wt,workers:c}),_t(e,s,"ready"),it(document,"currentScript",{configurable:!0,get:()=>e});const t=_t.bind(null,e,s,"done");let l=o[r?"runAsync":"run"](a,i);return r&&(l=await l),t(),l}finally{delete document.currentScript}})(e,w,g.XWorker,d)))}},Kn=new Proxy(ot(null),{get:(e,t)=>new Promise(queueMicrotask).then((()=>Yn(t)))}),Yn=async e=>{if(Jn.has(e)){const{interpreter:t,queue:n}=Jn.get(e);return(await ct([t,n]))[0]}const t=Jn.size?`Available interpreters are: ${[...Jn.keys()].map((e=>`"${e}"`)).join(", ")}.`:"There are no interpreters in this page.";throw new Error(`The interpreter "${e}" was not found. ${t}`)},Xn=async e=>{const{type:t,currentTarget:r}=e;if(wn.length)for(let{name:s,value:o,ownerElement:a}of n(`./@*[${wn.map((e=>`name()="${e}${t}"`)).join(" or ")}]`,r)){s=s.slice(0,-(t.length+1));const n=await Yn(a.getAttribute(`${s}-env`)||s);hn.get(s).runEvent(n,o,e)}},Vn=e=>{if(wn.length)for(let{name:t,ownerElement:r}of n(`.//@*[${wn.map((e=>`starts-with(name(),"${e}")`)).join(" or ")}]`,e)){const e=t.lastIndexOf("-"),n=t.slice(e+1);"env"!==n&&(r.addEventListener(n,Xn),"disabled"in r&&!r.disabled&&(r.disabled=!0,Kn[t.slice(0,e)].then((()=>{r.disabled=!1}))))}},Zn=Fn(),Qn=[],er=new Map,tr=new Map,nr=new Map,rr=async e=>{for(const t of Qn)if(e.matches(t)){const n=tr.get(t),r=sr.get(n),{resolve:s}=nr.get(n),{options:o,known:a}=r;if(a.has(e))return;a.add(e);for(const[t,n]of er)e.matches(t)&&await n(e);const{interpreter:l,configURL:p,config:u,version:d,env:f,onerror:_,hooks:m}=o;let y;try{const t=Nn(e);if(t){let r=d,o=p,a=e.getAttribute("config")||u||{};if(!r||!a){const[e,t]=Cn(a,p);a=await e,o=t,r=a.version||a.interpreter}const c=Zn.call(new Mn(null,m),t,{...ft(e,n),configURL:o,version:r,type:l,custom:n,config:a,async:!jt(e),serviceWorker:e.getAttribute("service-worker")});it(e,"xworker",{value:c}),s({type:n,xworker:c});const f=e.getAttribute("name");return void(f&&i[f].resolve(c.ready))}}catch(e){y=e}const h=xn(l,d),A=f||`${h}${u?`|${u}`:""}`,{interpreter:g,XWorker:w}=zn(n,A,h,d,u,p,l),E=await g,b=ot(hn.get(l)),v=new Mn(E,m),B=function(...e){return w.apply(v,e)},C={...mt(b,n,structuredClone(An.get(h)),E),XWorker:B};vt(l,b,E,wt),b.registerJSModule(E,"polyscript",{XWorker:B,config:C.config,currentScript:n.startsWith("_")?null:e,js_modules:wt,workers:c});for(const t of["Run","RunAsync"]){let n,r,s="",o="";for(const e of Pn){const n=m?.main?.[e];n&&e.endsWith(t)&&(e.startsWith("codeBefore")?s=tt(n()):o=tt(n()))}(s||o)&&ht(b,`r${t.slice(1)}`,s,o);for(let e=2;e<Tn.length;e++){const s=Tn[e],o=m?.main?.[s];o&&s.endsWith(t)&&(s.startsWith("onBefore")?n=o:r=o)}On(b,C,e,t.endsWith("Async"),n,r)}r.queue=r.queue.then((()=>(s(C),y&&_?.(y,e),m?.main?.onReady?.(C,e))))}},sr=new Map;let or=0;const ar=e=>(nr.has(e)||nr.set(e,Promise.withResolvers()),nr.get(e).promise),[{customObserver:ir,define:lr,whenDefined:cr,env:pr,Hook:ur,XWorker:dr},fr]=e("polyscript",{customObserver:er,define:(e,n)=>{let r=null==e;if(r)e="_ps"+or++;else if(hn.has(e)||sr.has(e))throw new Error(`<script type="${e}"> already registered`);if(!hn.has(n?.interpreter))throw new Error("Unspecified interpreter");hn.set(e,hn.get(n.interpreter));const s=[`script[type="${e}"]`];if(ar(e),r){const{hooks:t}=n,r=t?.main?.onReady;n={...n,hooks:{...t,main:{...t?.main,onReady(t,n){Qn.splice(Qn.indexOf(e),1),hn.delete(e),sr.delete(e),nr.delete(e),n.remove(),r?.(t)}}}},document.head.append(st(document.createElement("script"),{type:e}))}else s.push(`${e}-script`),wn.push(`${e}-`);for(const t of s)tr.set(t,e);Qn.push(...s),sr.set(e,{options:st({env:e},n),known:new WeakSet,queue:Promise.resolve()}),r||Vn(document),t(s.join(",")).forEach(rr)},whenDefined:ar,env:Kn,Hook:Mn,XWorker:Zn});if(!fr){const e=new MutationObserver((e=>{const t=gn.join(",");for(const{type:r,target:s,attributeName:o,addedNodes:a}of e)if("attributes"!==r)for(const e of a)1===e.nodeType&&(Vn(e),t&&e.matches(t)?Gn(e):n(t,e,!0));else{const e=o.lastIndexOf("-")+1;if(e){const t=o.slice(0,e);for(const n of wn)if(t===n){const t=o.slice(e);if("env"!==t){const e=s.hasAttribute(o)?"add":"remove";s[`${e}EventListener`](t,Xn)}break}}}})),n=(e,n,r)=>{e&&t(e,n).forEach(Gn),(e=Qn.join(","))&&(r&&rr(n),t(e,n).forEach(rr))},r=t=>(e.observe(t,{childList:!0,subtree:!0,attributes:!0}),t),{attachShadow:s}=Element.prototype;st(Element.prototype,{attachShadow(e){return r(s.call(this,e))}}),queueMicrotask((()=>{Vn(r(document)),n(gn.join(","),document,!1)}))}var _r=new Map([["py","pyodide"],["mpy","micropython"]]);const mr=[];for(const[e]of _r){const t=[`script[type="${e}"]`,`${e}-script`];for(const n of document.querySelectorAll(t.join(","))){const{promise:t,resolve:r}=Promise.withResolvers();mr.push(t),n.addEventListener(`${e}:done`,r,{once:!0})}}Promise.all(mr).then((()=>{dispatchEvent(new Event("py:all-done"))}));var yr={"deprecations-manager":()=>import("./deprecations-manager-B8Tn4H-t.js"),error:()=>import("./error-Dmba-E9f.js"),"py-editor":()=>import("./py-editor-Czy2e-Jt.js"),"py-terminal":()=>import("./py-terminal-w87wZryi.js")};const hr={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 Ar extends Error{constructor(e,t="",n="text"){super(`(${e}): ${t}`),this.errorCode=e,this.messageType=n,this.name="UserError"}}class gr extends Ar{constructor(e,t){super(e,t),this.name="FetchError"}}const wr=e=>e.text();async function Er(e,t){let n;try{n=await fetch(e,t)}catch(t){const n=t;let r;throw r=e.startsWith("http")?`Fetching from URL ${e} failed with error '${n.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 gr(hr.FETCH_ERROR,r)}if(!n.ok){const t=`Fetching from URL ${e} failed with error ${n.status} (${n.statusText}). Are your filename and path correct?`;switch(n.status){case 404:throw new gr(hr.FETCH_NOT_FOUND_ERROR,t);case 401:throw new gr(hr.FETCH_UNAUTHORIZED_ERROR,t);case 403:throw new gr(hr.FETCH_FORBIDDEN_ERROR,t);case 500:throw new gr(hr.FETCH_SERVER_ERROR,t);case 503:throw new gr(hr.FETCH_UNAVAILABLE_ERROR,t);default:throw new gr(hr.FETCH_ERROR,t)}}return n}const{BAD_CONFIG:br,CONFLICTING_CODE:vr}=hr,Br=async(e,t)=>{let n=e?.trim(),r="",s=!1,o=/^{/.test(n)&&/}$/.test(n);if(!o&&/\.(\w+)(?:\?\S*)?$/.test(n)){const e=RegExp.$1;"json"===e&&"toml"!==t?o=!0:"toml"===e&&"json"!==t?s=!0:((e,t="")=>{let n=`(${br}): Invalid URL: ${e}`;throw t&&(n+=`\nexpected ${t} content`),new Error(n)})(n,t),r=n,n=(await Er(r).then(wr)).trim()}return{json:o,toml:s||!o&&!!n,text:n,url:r}},Cr=e=>new Error(`(${vr}): ${e}`),kr=(e,t=location.href)=>new URL(e,t).href,jr=(e,t,{message:n})=>{let r=`(${br}): Invalid ${e}`;return t&&(r+=` @ ${t}`),new SyntaxError(`${r}\n${n}`)},xr=new Map;for(const[e]of _r){let n,r,s,o,a,i,l,c=t(`${e}-config`),p=t([`script[type="${e}"][config]:not([worker])`,`${e}-script[config]:not([worker])`].join(","));if(c.length>1?s=Cr(`Too many ${e}-config`):c.length&&p.length?s=Cr(`Ambiguous ${e}-config VS config attribute`):c.length?([l]=c,a=l.getAttribute("src")||l.textContent,i=l.getAttribute("type")):p.length&&([l,...p]=p,a=l.getAttribute("config"),p.some((e=>e.getAttribute("config")!==a))&&(s=Cr("Unable to use different configs on main"))),!s&&a)try{const{json:e,toml:t,text:n,url:l}=await Br(a,i);if(l&&(o=kr(l)),a=n,e||"json"===i)try{r=JSON.parse(n)}catch(e){s=jr("JSON",l,e)}else if(t||"toml"===i)try{const{parse:e}=await import("./toml-CvAfdf9_.js");r=e(n)}catch(e){s=jr("TOML",l,e)}}catch(e){s=e}const u=[];for(const[e,t]of Object.entries(yr))s?"error"===e&&t().then((({notify:e})=>e(s.message))):r?.plugins?.includes(`!${e}`)||u.push(t().then((({default:e})=>e)));n=Promise.all(u),xr.set(e,{config:r,configURL:o,plugins:n,error:s})}var Rr={is_pyterminal:()=>!1,sleep:e=>new Promise((t=>setTimeout(t,1e3*e)))};const Sr=e=>{it(document,"currentScript",{configurable:!0,get:()=>e})},$r=()=>{delete document.currentScript};var Pr=async(e,t,n,r)=>{const s=r.endsWith("Async");(r.startsWith("onBefore")?Sr:$r)(n);for(const o of e(r))s?await o(t,n):o(t,n)};const Tr=()=>!0,Dr=e=>{throw new TypeError(e)},Or=(e,t)=>{const n=[];if(e)for(const t of e.split(/\s*\|\s*/))"object"===t?n.push((e=>null!==e&&typeof e===t)):"null"===t?n.push((e=>null===e)):n.push((e=>typeof e===t));if(t)for(const e of[].concat(t))n.push((t=>t instanceof e));switch(n.length){case 0:return Tr;case 1:return n[0];default:return e=>n.some((t=>t(e)))}},Mr=(e,t,n,r=Dr)=>s=>{const o=[`Invalid ${typeof s} ${n}: expected `];e&&(o.push(e),t&&o.push(" or ")),t&&(o.push("an instanceof "),o.push([].concat(t).map((({name:e})=>e)).join(" | "))),r(o.join(""),s)},Fr=(e=>t=>{const[n,r]=((e,t="value")=>{const n=e?.typeof,r=e?.instanceof;return[Or(n,r),Mr(n,r,t,e?.onerror)]})(t);return class extends e{add(e){return n(e)?super.add(e):r(e)}}})(Set);const{entries:Ir}=Object,Nr=["import os as _os","from pathlib import Path as _Path","_path = None"],Lr=new class extends Array{#a=!1;#i;#l;constructor(e,...t){super(),this.#l=e,this.#i=t}push(...e){return this.#a&&super.push(...e),this.#l.push(...e)}path(e){for(const t of this.#i)if(this.#a=e.startsWith(t))break}}(Nr,"-"),Wr=(e,t)=>{for(const[n,r]of Ir(t))if(Lr.path(`${e}/${n}`),Lr.push(`_path = _Path("${e}/${n}")`),"string"==typeof r){const e=JSON.stringify(r);Lr.push(`_path.write_text(${e},encoding="utf-8")`)}else Lr.push(`if not _os.path.exists("${e}/${n}"):`),Lr.push(" _path.mkdir(parents=True, exist_ok=True)"),Wr(`${e}/${n}`,r)};Wr(".",{pyscript:{"__init__.py":"from polyscript import lazy_py_modules as py_import\nfrom pyscript.display import HTML,display\nfrom pyscript.fetch import fetch\nfrom pyscript.magic_js import RUNNING_IN_WORKER,PyWorker,config,current_target,document,js_import,js_modules,sync,window\nfrom pyscript.storage import Storage,storage\nfrom pyscript.websocket import WebSocket\nif not RUNNING_IN_WORKER:from pyscript.workers import create_named_worker,workers\ntry:from pyscript.event_handling import when\nexcept:from pyscript.util import NotSupported;when=NotSupported('pyscript.when','pyscript.when currently not available with this interpreter')","display.py":"_L='_repr_mimebundle_'\n_K='image/svg+xml'\n_J='application/json'\n_I='__repr__'\n_H='savefig'\n_G='text/html'\n_F='image/jpeg'\n_E='application/javascript'\n_D='utf-8'\n_C='text/plain'\n_B='image/png'\n_A=None\nimport base64,html,io,re\nfrom pyscript.magic_js import current_target,document,window\n_MIME_METHODS={_H:_B,'_repr_javascript_':_E,'_repr_json_':_J,'_repr_latex':'text/latex','_repr_png_':_B,'_repr_jpeg_':_F,'_repr_pdf_':'application/pdf','_repr_svg_':_K,'_repr_markdown_':'text/markdown','_repr_html_':_G,_I:_C}\ndef _render_image(mime,value,meta):\n\tA=value\n\tif isinstance(A,bytes):A=base64.b64encode(A).decode(_D)\n\tB=re.compile('^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$')\n\tif len(A)>0 and not B.match(A):A=base64.b64encode(A.encode(_D)).decode(_D)\n\tC=f\"data:{mime};charset=utf-8;base64,{A}\";D=' '.join(['{k}=\"{v}\"'for(A,B)in meta.items()]);return f'<img src=\"{C}\" {D}></img>'\ndef _identity(value,meta):return value\n_MIME_RENDERERS={_C:html.escape,_G:_identity,_B:lambda value,meta:_render_image(_B,value,meta),_F:lambda value,meta:_render_image(_F,value,meta),_K:_identity,_J:_identity,_E:lambda value,meta:f\"<script>{value}<\\\\/script>\"}\nclass HTML:\n\tdef __init__(A,html):A._html=html\n\tdef _repr_html_(A):return A._html\ndef _eval_formatter(obj,print_method):\n\tB=obj;A=print_method\n\tif A==_I:return repr(B)\n\telif hasattr(B,A):\n\t\tif A==_H:C=io.BytesIO();B.savefig(C,format='png');C.seek(0);return base64.b64encode(C.read()).decode(_D)\n\t\treturn getattr(B,A)()\n\telif A==_L:return{},{}\ndef _format_mime(obj):\n\tC=obj\n\tif isinstance(C,str):return html.escape(C),_C\n\tD=_eval_formatter(C,_L)\n\tif isinstance(D,tuple):E,I=D\n\telse:E=D\n\tA,F=_A,[]\n\tfor(H,B)in _MIME_METHODS.items():\n\t\tif B in E:A=E[B]\n\t\telse:A=_eval_formatter(C,H)\n\t\tif A is _A:continue\n\t\telif B not in _MIME_RENDERERS:F.append(B);continue\n\t\tbreak\n\tif A is _A:\n\t\tif F:window.console.warn(f\"Rendered object requested unavailable MIME renderers: {F}\")\n\t\tA=repr(A);B=_C\n\telif isinstance(A,tuple):A,G=A\n\telse:G={}\n\treturn _MIME_RENDERERS[B](A,G),B\ndef _write(element,value,append=False):\n\tB=element;C,D=_format_mime(value)\n\tif C=='\\\\n':return\n\tif append:A=document.createElement('div');B.append(A)\n\telse:\n\t\tA=B.lastElementChild\n\t\tif A is _A:A=B\n\tif D in(_E,_G):E=document.createRange().createContextualFragment(C);A.append(E)\n\telse:A.innerHTML=C\ndef display(*D,target=_A,append=True):\n\tC=append;A=target\n\tif A is _A:A=current_target()\n\telif not isinstance(A,str):raise TypeError(f\"target must be str or None, not {A.__class__.__name__}\")\n\telif A=='':raise ValueError('Cannot have an empty target')\n\telif A.startswith('#'):A=A[1:]\n\tB=document.getElementById(A)\n\tif B is _A:raise ValueError(f\"Invalid selector with id={A}. Cannot be found in the page.\")\n\tif B.tagName=='SCRIPT'and hasattr(B,'target'):B=B.target\n\tfor E in D:\n\t\tif not C:B.replaceChildren()\n\t\t_write(B,E,append=C)","event_handling.py":"import inspect\ntry:from pyodide.ffi.wrappers import add_event_listener\nexcept ImportError:\n\tdef add_event_listener(el,event_type,func):el.addEventListener(event_type,func)\nfrom pyscript.magic_js import document\ndef when(event_type=None,selector=None):\n\tA=selector\n\tdef B(func):\n\t\tB=func;from pyscript.web import Element as E,ElementCollection as F\n\t\tif isinstance(A,str):C=document.querySelectorAll(A)\n\t\telif isinstance(A,E):C=[A._dom_element]\n\t\telif isinstance(A,F):C=[A._dom_element for A in A]\n\t\telif isinstance(A,list):C=A\n\t\telse:C=[A]\n\t\ttry:\n\t\t\tG=inspect.signature(B)\n\t\t\tif not G.parameters:\n\t\t\t\tif inspect.iscoroutinefunction(B):\n\t\t\t\t\tasync def D(*A,**C):await B()\n\t\t\t\telse:\n\t\t\t\t\tdef D(*A,**C):B()\n\t\t\telse:D=B\n\t\texcept AttributeError:\n\t\t\tdef D(*C,**D):\n\t\t\t\ttry:return B(*C,**D)\n\t\t\t\texcept TypeError as A:\n\t\t\t\t\tif'takes'in str(A)and'positional arguments'in str(A):return B()\n\t\t\t\t\traise\n\t\tfor H in C:add_event_listener(H,event_type,D)\n\t\treturn B\n\treturn B","fetch.py":"import json,js\nfrom pyscript.util import as_bytearray\nclass _Response:\n\tdef __init__(A,response):A._response=response\n\tdef __getattr__(A,attr):return getattr(A._response,attr)\n\tasync def arrayBuffer(B):\n\t\tA=await B._response.arrayBuffer()\n\t\tif hasattr(A,'to_py'):return A.to_py()\n\t\treturn memoryview(as_bytearray(A))\n\tasync def blob(A):return await A._response.blob()\n\tasync def bytearray(A):B=await A._response.arrayBuffer();return as_bytearray(B)\n\tasync def json(A):return json.loads(await A.text())\n\tasync def text(A):return await A._response.text()\nclass _DirectResponse:\n\t@staticmethod\n\tdef setup(promise,response):A=promise;A._response=_Response(response);return A._response\n\tdef __init__(B,promise):A=promise;B._promise=A;A._response=None;A.arrayBuffer=B.arrayBuffer;A.blob=B.blob;A.bytearray=B.bytearray;A.json=B.json;A.text=B.text\n\tasync def _response(A):\n\t\tif not A._promise._response:await A._promise\n\t\treturn A._promise._response\n\tasync def arrayBuffer(A):B=await A._response();return await B.arrayBuffer()\n\tasync def blob(A):B=await A._response();return await B.blob()\n\tasync def bytearray(A):B=await A._response();return await B.bytearray()\n\tasync def json(A):B=await A._response();return await B.json()\n\tasync def text(A):B=await A._response();return await B.text()\ndef fetch(url,**B):C=js.JSON.parse(json.dumps(B));D=lambda response,*B:_DirectResponse.setup(A,response);A=js.fetch(url,C).then(D);_DirectResponse(A);return A","ffi.py":"try:\n\timport js;from pyodide.ffi import create_proxy as _cp,to_js as _py_tjs;from_entries=js.Object.fromEntries\n\tdef _tjs(value,**A):\n\t\tB='dict_converter'\n\t\tif not hasattr(A,B):A[B]=from_entries\n\t\treturn _py_tjs(value,**A)\nexcept:from jsffi import create_proxy as _cp;from jsffi import to_js as _tjs\ncreate_proxy=_cp\nto_js=_tjs","flatted.py":"import json as _json\nclass _Known:\n\tdef __init__(A):A.key=[];A.value=[]\nclass _String:\n\tdef __init__(A,value):A.value=value\ndef _array_keys(value):\n\tA=[];B=0\n\tfor C in value:A.append(B);B+=1\n\treturn A\ndef _object_keys(value):\n\tA=[]\n\tfor B in value:A.append(B)\n\treturn A\ndef _is_array(value):A=value;return isinstance(A,list)or isinstance(A,tuple)\ndef _is_object(value):return isinstance(value,dict)\ndef _is_string(value):return isinstance(value,str)\ndef _index(known,input,value):B=value;A=known;input.append(B);C=str(len(input)-1);A.key.append(B);A.value.append(C);return C\ndef _loop(keys,input,known,output):\n\tA=output\n\tfor B in keys:\n\t\tC=A[B]\n\t\tif isinstance(C,_String):_ref(B,input[int(C.value)],input,known,A)\n\treturn A\ndef _ref(key,value,input,known,output):\n\tB=known;A=value\n\tif _is_array(A)and not A in B:B.append(A);A=_loop(_array_keys(A),input,B,A)\n\telif _is_object(A)and not A in B:B.append(A);A=_loop(_object_keys(A),input,B,A)\n\toutput[key]=A\ndef _relate(known,input,value):\n\tB=known;A=value\n\tif _is_string(A)or _is_array(A)or _is_object(A):\n\t\ttry:return B.value[B.key.index(A)]\n\t\texcept:return _index(B,input,A)\n\treturn A\ndef _transform(known,input,value):\n\tB=known;A=value\n\tif _is_array(A):\n\t\tC=[]\n\t\tfor F in A:C.append(_relate(B,input,F))\n\t\treturn C\n\tif _is_object(A):\n\t\tD={}\n\t\tfor E in A:D[E]=_relate(B,input,A[E])\n\t\treturn D\n\treturn A\ndef _wrap(value):\n\tA=value\n\tif _is_string(A):return _String(A)\n\tif _is_array(A):\n\t\tB=0\n\t\tfor D in A:A[B]=_wrap(D);B+=1\n\telif _is_object(A):\n\t\tfor C in A:A[C]=_wrap(A[C])\n\treturn A\ndef parse(value,*C,**D):\n\tA=value;E=_json.loads(A,*C,**D);B=[]\n\tfor A in E:B.append(_wrap(A))\n\tinput=[]\n\tfor A in B:\n\t\tif isinstance(A,_String):input.append(A.value)\n\t\telse:input.append(A)\n\tA=input[0]\n\tif _is_array(A):return _loop(_array_keys(A),input,[A],A)\n\tif _is_object(A):return _loop(_object_keys(A),input,[A],A)\n\treturn A\ndef stringify(value,*D,**E):\n\tB=_Known();input=[];C=[];A=int(_index(B,input,value))\n\twhile A<len(input):C.append(_transform(B,input,input[A]));A+=1\n\treturn _json.dumps(C,*D,**E)","magic_js.py":"import json,sys,js as globalThis\nfrom polyscript import config as _config,js_modules\nfrom pyscript.util import NotSupported\nRUNNING_IN_WORKER=not hasattr(globalThis,'document')\nconfig=json.loads(globalThis.JSON.stringify(_config))\nif'MicroPython'in sys.version:config['type']='mpy'\nelse:config['type']='py'\nclass JSModule:\n\tdef __init__(A,name):A.name=name\n\tdef __getattr__(B,field):\n\t\tA=field\n\t\tif not A.startswith('_'):return getattr(getattr(js_modules,B.name),A)\nfor name in globalThis.Reflect.ownKeys(js_modules):sys.modules[f\"pyscript.js_modules.{name}\"]=JSModule(name)\nsys.modules['pyscript.js_modules']=js_modules\nif RUNNING_IN_WORKER:\n\timport polyscript;PyWorker=NotSupported('pyscript.PyWorker','pyscript.PyWorker works only when running in the main thread')\n\ttry:import js;window=polyscript.xworker.window;document=window.document;js.document=document;js_import=window.Function('return (...urls) => Promise.all(urls.map((url) => import(url)))')()\n\texcept:message='Unable to use `window` or `document` -> https://docs.pyscript.net/latest/faq/#sharedarraybuffer';globalThis.console.warn(message);window=NotSupported('pyscript.window',message);document=NotSupported('pyscript.document',message);js_import=None\n\tsync=polyscript.xworker.sync\n\tdef current_target():return polyscript.target\nelse:\n\timport _pyscript;from _pyscript import PyWorker,js_import;window=globalThis;document=globalThis.document;sync=NotSupported('pyscript.sync','pyscript.sync works only when running in a worker')\n\tdef current_target():return _pyscript.target","storage.py":"_C='memoryview'\n_B='bytearray'\n_A='generic'\nfrom polyscript import storage as _storage\nfrom pyscript.flatted import parse as _parse\nfrom pyscript.flatted import stringify as _stringify\ndef _to_idb(value):\n\tA=value\n\tif A is None:return _stringify(['null',0])\n\tif isinstance(A,(bool,float,int,str,list,dict,tuple)):return _stringify([_A,A])\n\tif isinstance(A,bytearray):return _stringify([_B,[A for A in A]])\n\tif isinstance(A,memoryview):return _stringify([_C,[A for A in A]])\n\traise TypeError(f\"Unexpected value: {A}\")\ndef _from_idb(value):\n\tC=value;A,B=_parse(C)\n\tif A=='null':return\n\tif A==_A:return B\n\tif A==_B:return bytearray(B)\n\tif A==_C:return memoryview(bytearray(B))\n\treturn C\nclass Storage(dict):\n\tdef __init__(B,store):A=store;super().__init__({A:_from_idb(B)for(A,B)in A.entries()});B.__store__=A\n\tdef __delitem__(A,attr):A.__store__.delete(attr);super().__delitem__(attr)\n\tdef __setitem__(B,attr,value):A=value;B.__store__.set(attr,_to_idb(A));super().__setitem__(attr,A)\n\tdef clear(A):A.__store__.clear();super().clear()\n\tasync def sync(A):await A.__store__.sync()\nasync def storage(name='',storage_class=Storage):\n\tif not name:raise ValueError('The storage name must be defined')\n\treturn storage_class(await _storage(f\"@pyscript/{name}\"))","util.py":"import js\ndef as_bytearray(buffer):\n\tA=js.Uint8Array.new(buffer);B=A.length;C=bytearray(B)\n\tfor D in range(0,B):C[D]=A[D]\n\treturn C\nclass NotSupported:\n\tdef __init__(A,name,error):object.__setattr__(A,'name',name);object.__setattr__(A,'error',error)\n\tdef __repr__(A):return f\"<NotSupported {A.name} [{A.error}]>\"\n\tdef __getattr__(A,attr):raise AttributeError(A.error)\n\tdef __setattr__(A,attr,value):raise AttributeError(A.error)\n\tdef __call__(A,*B):raise TypeError(A.error)","web.py":"_A=None\nfrom pyscript import document,when\ndef wrap_dom_element(dom_element):return Element.wrap_dom_element(dom_element)\nclass Element:\n\telement_classes_by_tag_name={}\n\t@classmethod\n\tdef get_tag_name(A):return A.__name__.replace('_','')\n\t@classmethod\n\tdef register_element_classes(B,element_classes):\n\t\tfor A in element_classes:C=A.get_tag_name();B.element_classes_by_tag_name[C]=A\n\t@classmethod\n\tdef unregister_element_classes(A,element_classes):\n\t\tfor B in element_classes:C=B.get_tag_name();A.element_classes_by_tag_name.pop(C,_A)\n\t@classmethod\n\tdef wrap_dom_element(A,dom_element):B=dom_element;C=A.element_classes_by_tag_name.get(B.tagName.lower(),A);return C(dom_element=B)\n\tdef __init__(A,dom_element=_A,classes=_A,style=_A,**B):A._dom_element=dom_element or document.createElement(type(A).get_tag_name());A._classes=Classes(A);A._style=Style(A);A.update(classes=classes,style=style,**B)\n\tdef __eq__(A,obj):return isinstance(obj,Element)and obj._dom_element==A._dom_element\n\tdef __getitem__(B,key):\n\t\tA=key\n\t\tif isinstance(A,int)or isinstance(A,slice):return B.children[A]\n\t\treturn B.find(A)\n\tdef __getattr__(B,name):\n\t\tA=name\n\t\tif A.endswith('_'):A=A[:-1]\n\t\treturn getattr(B._dom_element,A)\n\tdef __setattr__(C,name,value):\n\t\tB=value;A=name\n\t\tif A.startswith('_'):super().__setattr__(A,B)\n\t\telse:\n\t\t\tif A.endswith('_'):A=A[:-1]\n\t\t\tsetattr(C._dom_element,A,B)\n\t@property\n\tdef children(self):return ElementCollection.wrap_dom_elements(self._dom_element.children)\n\t@property\n\tdef classes(self):return self._classes\n\t@property\n\tdef parent(self):\n\t\tif self._dom_element.parentElement is _A:return\n\t\treturn Element.wrap_dom_element(self._dom_element.parentElement)\n\t@property\n\tdef style(self):return self._style\n\tdef append(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,Element):B._dom_element.appendChild(A._dom_element)\n\t\t\telif isinstance(A,ElementCollection):\n\t\t\t\tfor D in A:B._dom_element.appendChild(D._dom_element)\n\t\t\telif isinstance(A,list)or isinstance(A,tuple):\n\t\t\t\tfor E in A:B.append(E)\n\t\t\telse:\n\t\t\t\ttry:A.tagName;B._dom_element.appendChild(A)\n\t\t\t\texcept AttributeError:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tA.length\n\t\t\t\t\t\tfor F in A:B._dom_element.appendChild(F)\n\t\t\t\t\texcept AttributeError:raise TypeError(f'Element \"{A}\" is a proxy object, \"but not a valid element or a NodeList.')\n\tdef clone(B,clone_id=_A):A=Element.wrap_dom_element(B._dom_element.cloneNode(True));A.id=clone_id;return A\n\tdef find(A,selector):return ElementCollection.wrap_dom_elements(A._dom_element.querySelectorAll(selector))\n\tdef show_me(A):A._dom_element.scrollIntoView()\n\tdef update(A,classes=_A,style=_A,**D):\n\t\tC=style;B=classes\n\t\tif B:A.classes.add(B)\n\t\tif C:A.style.set(**C)\n\t\tfor(E,F)in D.items():setattr(A,E,F)\nclass Classes:\n\tdef __init__(A,element):A._element=element;A._class_list=A._element._dom_element.classList\n\tdef __contains__(A,item):return item in A._class_list\n\tdef __eq__(C,other):\n\t\tA=other\n\t\tif isinstance(A,Classes):B=list(A._class_list)\n\t\telse:\n\t\t\ttry:B=iter(A)\n\t\t\texcept TypeError:return False\n\t\treturn set(C._class_list)==set(B)\n\tdef __iter__(A):return iter(A._class_list)\n\tdef __len__(A):return A._class_list.length\n\tdef __repr__(A):return f\"Classes({', '.join(A._class_list)})\"\n\tdef __str__(A):return' '.join(A._class_list)\n\tdef add(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,list):\n\t\t\t\tfor D in A:B.add(D)\n\t\t\telse:B._class_list.add(A)\n\tdef contains(A,class_name):return class_name in A\n\tdef remove(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,list):\n\t\t\t\tfor D in A:B.remove(D)\n\t\t\telse:B._class_list.remove(A)\n\tdef replace(A,old_class,new_class):A.remove(old_class);A.add(new_class)\n\tdef toggle(A,*C):\n\t\tfor B in C:\n\t\t\tif B in A:A.remove(B)\n\t\t\telse:A.add(B)\nclass HasOptions:\n\t@property\n\tdef options(self):\n\t\tA=self\n\t\tif not hasattr(A,'_options'):A._options=Options(A)\n\t\treturn A._options\nclass Options:\n\tdef __init__(A,element):A._element=element\n\tdef __getitem__(A,key):return A.options[key]\n\tdef __iter__(A):yield from A.options\n\tdef __len__(A):return len(A.options)\n\tdef __repr__(A):return f\"{A.__class__.__name__} (length: {len(A)}) {A.options}\"\n\t@property\n\tdef options(self):return[Element.wrap_dom_element(A)for A in self._element._dom_element.options]\n\t@property\n\tdef selected(self):return self.options[self._element._dom_element.selectedIndex]\n\tdef add(D,value=_A,html=_A,text=_A,before=_A,**B):\n\t\tC=value;A=before\n\t\tif C is not _A:B['value']=C\n\t\tif html is not _A:B['innerHTML']=html\n\t\tif text is not _A:B['text']=text\n\t\tE=option(**B)\n\t\tif A:\n\t\t\tif isinstance(A,Element):A=A._dom_element\n\t\tD._element._dom_element.add(E._dom_element,A)\n\tdef clear(A):\n\t\twhile len(A)>0:A.remove(0)\n\tdef remove(A,index):A._element._dom_element.remove(index)\nclass Style:\n\tdef __init__(A,element):A._element=element;A._style=A._element._dom_element.style\n\tdef __getitem__(A,key):return A._style.getPropertyValue(key)\n\tdef __setitem__(A,key,value):A._style.setProperty(key,value)\n\tdef remove(A,key):A._style.removeProperty(key)\n\tdef set(A,**B):\n\t\tfor(C,D)in B.items():A._element._dom_element.style.setProperty(C,D)\n\t@property\n\tdef visible(self):return self._element._dom_element.style.visibility\n\t@visible.setter\n\tdef visible(self,value):self._element._dom_element.style.visibility=value\nclass ContainerElement(Element):\n\tdef __init__(B,*C,children=_A,dom_element=_A,style=_A,classes=_A,**D):\n\t\tsuper().__init__(dom_element=dom_element,style=style,classes=classes,**D)\n\t\tfor A in list(C)+(children or[]):\n\t\t\tif isinstance(A,Element)or isinstance(A,ElementCollection):B.append(A)\n\t\t\telse:B._dom_element.insertAdjacentHTML('beforeend',A)\n\tdef __iter__(A):yield from A.children\nclass ClassesCollection:\n\tdef __init__(A,collection):A._collection=collection\n\tdef __contains__(A,class_name):\n\t\tfor B in A._collection:\n\t\t\tif class_name in B.classes:return True\n\t\treturn False\n\tdef __eq__(B,other):A=other;return isinstance(A,ClassesCollection)and B._collection==A._collection\n\tdef __iter__(A):\n\t\tfor B in A._all_class_names():yield B\n\tdef __len__(A):return len(A._all_class_names())\n\tdef __repr__(A):return f\"ClassesCollection({repr(A._collection)})\"\n\tdef __str__(A):return' '.join(A._all_class_names())\n\tdef add(A,*B):\n\t\tfor C in A._collection:C.classes.add(*B)\n\tdef contains(A,class_name):return class_name in A\n\tdef remove(A,*B):\n\t\tfor C in A._collection:C.classes.remove(*B)\n\tdef replace(A,old_class,new_class):\n\t\tfor B in A._collection:B.classes.replace(old_class,new_class)\n\tdef toggle(A,*B):\n\t\tfor C in A._collection:C.classes.toggle(*B)\n\tdef _all_class_names(B):\n\t\tA=set()\n\t\tfor C in B._collection:\n\t\t\tfor D in C.classes:A.add(D)\n\t\treturn A\nclass StyleCollection:\n\tdef __init__(A,collection):A._collection=collection\n\tdef __getitem__(A,key):return[A.style[key]for A in A._collection._elements]\n\tdef __setitem__(A,key,value):\n\t\tfor B in A._collection._elements:B.style[key]=value\n\tdef __repr__(A):return f\"StyleCollection({repr(A._collection)})\"\n\tdef remove(A,key):\n\t\tfor B in A._collection._elements:B.style.remove(key)\nclass ElementCollection:\n\t@classmethod\n\tdef wrap_dom_elements(A,dom_elements):return A([Element.wrap_dom_element(A)for A in dom_elements])\n\tdef __init__(A,elements):A._elements=elements;A._classes=ClassesCollection(A);A._style=StyleCollection(A)\n\tdef __eq__(A,obj):return isinstance(obj,ElementCollection)and obj._elements==A._elements\n\tdef __getitem__(B,key):\n\t\tA=key\n\t\tif isinstance(A,int):return B._elements[A]\n\t\telif isinstance(A,slice):return ElementCollection(B._elements[A])\n\t\treturn B.find(A)\n\tdef __iter__(A):yield from A._elements\n\tdef __len__(A):return len(A._elements)\n\tdef __repr__(A):return f\"{A.__class__.__name__} (length: {len(A._elements)}) {A._elements}\"\n\tdef __getattr__(A,name):return[getattr(A,name)for A in A._elements]\n\tdef __setattr__(C,name,value):\n\t\tB=value;A=name\n\t\tif A.startswith('_'):super().__setattr__(A,B)\n\t\telse:\n\t\t\tfor D in C._elements:setattr(D,A,B)\n\t@property\n\tdef classes(self):return self._classes\n\t@property\n\tdef elements(self):return self._elements\n\t@property\n\tdef style(self):return self._style\n\tdef find(B,selector):\n\t\tA=[]\n\t\tfor C in B._elements:A.extend(C.find(selector))\n\t\treturn ElementCollection(A)\nclass a(ContainerElement):0\nclass abbr(ContainerElement):0\nclass address(ContainerElement):0\nclass area(Element):0\nclass article(ContainerElement):0\nclass aside(ContainerElement):0\nclass audio(ContainerElement):0\nclass b(ContainerElement):0\nclass base(Element):0\nclass blockquote(ContainerElement):0\nclass body(ContainerElement):0\nclass br(Element):0\nclass button(ContainerElement):0\nclass canvas(ContainerElement):\n\tdef download(A,filename='snapped.png'):B=a(download=filename,href=A._dom_element.toDataURL());A.append(B);B._dom_element.click()\n\tdef draw(E,what,width=_A,height=_A):\n\t\tC=height;B=width;A=what\n\t\tif isinstance(A,Element):A=A._dom_element\n\t\tD=E._dom_element.getContext('2d')\n\t\tif B or C:D.drawImage(A,0,0,B,C)\n\t\telse:D.drawImage(A,0,0)\nclass caption(ContainerElement):0\nclass cite(ContainerElement):0\nclass code(ContainerElement):0\nclass col(Element):0\nclass colgroup(ContainerElement):0\nclass data(ContainerElement):0\nclass datalist(ContainerElement,HasOptions):0\nclass dd(ContainerElement):0\nclass del_(ContainerElement):0\nclass details(ContainerElement):0\nclass dialog(ContainerElement):0\nclass div(ContainerElement):0\nclass dl(ContainerElement):0\nclass dt(ContainerElement):0\nclass em(ContainerElement):0\nclass embed(Element):0\nclass fieldset(ContainerElement):0\nclass figcaption(ContainerElement):0\nclass figure(ContainerElement):0\nclass footer(ContainerElement):0\nclass form(ContainerElement):0\nclass h1(ContainerElement):0\nclass h2(ContainerElement):0\nclass h3(ContainerElement):0\nclass h4(ContainerElement):0\nclass h5(ContainerElement):0\nclass h6(ContainerElement):0\nclass head(ContainerElement):0\nclass header(ContainerElement):0\nclass hgroup(ContainerElement):0\nclass hr(Element):0\nclass html(ContainerElement):0\nclass i(ContainerElement):0\nclass iframe(ContainerElement):0\nclass img(Element):0\nclass input_(Element):0\nclass ins(ContainerElement):0\nclass kbd(ContainerElement):0\nclass label(ContainerElement):0\nclass legend(ContainerElement):0\nclass li(ContainerElement):0\nclass link(Element):0\nclass main(ContainerElement):0\nclass map_(ContainerElement):0\nclass mark(ContainerElement):0\nclass menu(ContainerElement):0\nclass meta(ContainerElement):0\nclass meter(ContainerElement):0\nclass nav(ContainerElement):0\nclass object_(ContainerElement):0\nclass ol(ContainerElement):0\nclass optgroup(ContainerElement,HasOptions):0\nclass option(ContainerElement):0\nclass output(ContainerElement):0\nclass p(ContainerElement):0\nclass param(ContainerElement):0\nclass picture(ContainerElement):0\nclass pre(ContainerElement):0\nclass progress(ContainerElement):0\nclass q(ContainerElement):0\nclass s(ContainerElement):0\nclass script(ContainerElement):0\nclass section(ContainerElement):0\nclass select(ContainerElement,HasOptions):0\nclass small(ContainerElement):0\nclass source(Element):0\nclass span(ContainerElement):0\nclass strong(ContainerElement):0\nclass style(ContainerElement):0\nclass sub(ContainerElement):0\nclass summary(ContainerElement):0\nclass sup(ContainerElement):0\nclass table(ContainerElement):0\nclass tbody(ContainerElement):0\nclass td(ContainerElement):0\nclass template(ContainerElement):0\nclass textarea(ContainerElement):0\nclass tfoot(ContainerElement):0\nclass th(ContainerElement):0\nclass thead(ContainerElement):0\nclass time(ContainerElement):0\nclass title(ContainerElement):0\nclass tr(ContainerElement):0\nclass track(Element):0\nclass u(ContainerElement):0\nclass ul(ContainerElement):0\nclass var(ContainerElement):0\nclass video(ContainerElement):\n\tdef snap(D,to=_A,width=_A,height=_A):\n\t\tG='CANVAS';F='Element to snap to must be a canvas.';C=height;B=width;A=to;B=B if B is not _A else D.videoWidth;C=C if C is not _A else D.videoHeight\n\t\tif A is _A:A=canvas(width=B,height=C)\n\t\telif isinstance(A,Element):\n\t\t\tif A.tag!='canvas':raise TypeError(F)\n\t\telif getattr(A,'tagName','')==G:A=canvas(dom_element=A)\n\t\telif isinstance(A,str):\n\t\t\tE=document.querySelectorAll(A)\n\t\t\tif E.length==0:raise TypeError('No element with selector {to} to snap to.')\n\t\t\tif E[0].tagName!=G:raise TypeError(F)\n\t\t\tA=canvas(dom_element=E[0])\n\t\tA.draw(D,B,C);return A\nclass wbr(Element):0\nELEMENT_CLASSES=[a,abbr,address,area,article,aside,audio,b,base,blockquote,body,br,button,canvas,caption,cite,code,col,colgroup,data,datalist,dd,del_,details,dialog,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,i,iframe,img,input_,ins,kbd,label,legend,li,link,main,map_,mark,menu,meta,meter,nav,object_,ol,optgroup,option,output,p,param,picture,pre,progress,q,s,script,section,select,small,source,span,strong,style,sub,summary,sup,table,tbody,td,template,textarea,tfoot,th,thead,time,title,tr,track,u,ul,var,video,wbr]\nElement.register_element_classes(ELEMENT_CLASSES)\nclass Page:\n\tdef __init__(A):A.html=Element.wrap_dom_element(document.documentElement);A.body=Element.wrap_dom_element(document.body);A.head=Element.wrap_dom_element(document.head)\n\tdef __getitem__(A,selector):return A.find(selector)\n\t@property\n\tdef title(self):return document.title\n\t@title.setter\n\tdef title(self,value):document.title=value\n\tdef append(A,*B):A.body.append(*B)\n\tdef find(A,selector):return ElementCollection.wrap_dom_elements(document.querySelectorAll(selector))\npage=Page()","websocket.py":"import js\nfrom pyscript.ffi import create_proxy\nfrom pyscript.util import as_bytearray\ncode='code'\nprotocols='protocols'\nreason='reason'\nmethods=['onclose','onerror','onmessage','onopen']\nclass EventMessage:\n\tdef __init__(A,event):A._event=event\n\tdef __getattr__(B,attr):\n\t\tA=getattr(B._event,attr)\n\t\tif attr=='data'and not isinstance(A,str):\n\t\t\tif hasattr(A,'to_py'):return A.to_py()\n\t\t\treturn memoryview(as_bytearray(A))\n\t\treturn A\nclass WebSocket:\n\tCONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3\n\tdef __init__(E,**A):\n\t\tD=A['url']\n\t\tif protocols in A:B=js.WebSocket.new(D,A[protocols])\n\t\telse:B=js.WebSocket.new(D)\n\t\tobject.__setattr__(E,'_ws',B)\n\t\tfor C in methods:\n\t\t\tif C in A:setattr(B,C,create_proxy(A[C]))\n\tdef __getattr__(A,attr):return getattr(A._ws,attr)\n\tdef __setattr__(B,attr,value):\n\t\tC=value;A=attr\n\t\tif A in methods:D=lambda e:C(EventMessage(e));setattr(B._ws,A,create_proxy(D))\n\t\telse:setattr(B._ws,A,C)\n\tdef close(B,**A):\n\t\tif code in A and reason in A:B._ws.close(A[code],A[reason])\n\t\telif code in A:B._ws.close(A[code])\n\t\telse:B._ws.close()\n\tdef send(B,data):\n\t\tA=data\n\t\tif isinstance(A,str):B._ws.send(A)\n\t\telse:\n\t\t\tC=js.Uint8Array.new(len(A))\n\t\t\tfor(D,E)in enumerate(A):C[D]=E\n\t\t\tB._ws.send(C)","workers.py":"import js as _js\nfrom polyscript import workers as _workers\n_get=_js.Reflect.get\ndef _set(script,name,value=''):script.setAttribute(name,value)\nclass _ReadOnlyProxy:\n\tdef __getitem__(A,name):return _get(_workers,name)\n\tdef __getattr__(A,name):return _get(_workers,name)\nworkers=_ReadOnlyProxy()\nasync def create_named_worker(src='',name='',config=None,type='py'):\n\tC=name;B=config;from json import dumps\n\tif not src:raise ValueError('Named workers require src')\n\tif not C:raise ValueError('Named workers require a name')\n\tA=_js.document.createElement('script');A.type=type;A.src=src;_set(A,'worker');_set(A,'name',C)\n\tif B:_set(A,'config',isinstance(B,str)and B or dumps(B))\n\t_js.document.body.append(A);return await workers[C]"}}),Nr.push("import pyscript as _pyscript"),Nr.push(...["_Path","_path","_os","_pyscript"].map((e=>`del ${e}`))),Nr.push("\n");const Hr=Nr.join("\n"),Ur=Lr.join("\n"),Jr=e=>Zr.main[e],qr=e=>Zr.worker[e],zr=(e,t,n,r)=>{e[n]=()=>{const e=r?[r]:[];return e.push(...t(n)),e.map(tt).join("\n")}},Gr=(e,t)=>{const n="mpy"===t?Hr.replace(Ur,""):Hr,r={};return zr(r,e,"codeBeforeRun",n),zr(r,e,"codeBeforeRunAsync",n),zr(r,e,"codeAfterRun"),zr(r,e,"codeAfterRunAsync"),r},Kr=(e,t)=>{const n=[...qr(t)];if(n.length){const r=Rn(e[`_${t}`]||(t.endsWith("Async")?async(e,t,...n)=>{for(const r of n)await r(e,t)}:(e,t,...n)=>{for(const r of n)r(e,t)})),s=n.map(Rn).join(", ");return Function(`return(w,x)=>(${r})(w,x,...[${s}])`)()}},Yr=Fr({typeof:"function"}),Xr=Fr({typeof:"string"}),Vr='\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',Zr={main:{onWorker:new Yr,onReady:new Yr,onBeforeRun:new Yr,onBeforeRunAsync:new Yr,onAfterRun:new Yr,onAfterRunAsync:new Yr,codeBeforeRun:new Xr([Vr]),codeBeforeRunAsync:new Xr,codeAfterRun:new Xr,codeAfterRunAsync:new Xr},worker:{onReady:new Yr,onBeforeRun:new Yr,onBeforeRunAsync:new Yr,onAfterRun:new Yr,onAfterRunAsync:new Yr,codeBeforeRun:new Xr,codeBeforeRunAsync:new Xr,codeAfterRun:new Xr,codeAfterRunAsync:new Xr}},Qr=({tagName:e})=>"SCRIPT"===e,[es,ts]=[..._r.entries()].map((([e,t])=>async function(n,r){await xr.get(e).plugins;const s=dr.call(new ur(null,cs.get(e)),n,{...r,type:t});return st(s.sync,Rr),s.ready})),[{PyWorker:ns,MPWorker:rs,hooks:ss,config:os,whenDefined:as},is]=e("@pyscript/core",{PyWorker:es,MPWorker:ts,hooks:Zr,config:{},whenDefined:cr}),ls=e=>e?.interpreter&&kr(e.interpreter),cs=new Map;for(const[e,t]of _r){if(is)break;const n=(t,n,r)=>{n?r.then((()=>_t(t,e,"done"))):_t(t,e,"done")},{config:r,configURL:s,plugins:o,error:a}=xr.get(e);let i=0;const l=(t=e)=>`${t}-${i++}`,c=async(t,n,r)=>{if(t.hasAttribute("src"))try{return await Er(t.getAttribute("src")).then(wr)}catch(e){n.stderr(e)}if(r)return tt(t.textContent);const s=tt(nt(t.innerHTML));return console.warn(`Deprecated: use <script type="${e}"> for an always safe content parsing:\n`,s),s};let p,u=!1;const d=({XWorker:e,interpreter:t,io:n})=>{u||(u=!0,t.registerJsModule("_pyscript",{PyWorker:function(...t){const r=e(...t);return r.onerror=({error:e})=>n.stderr(e),r},js_import:(...e)=>Promise.all(e.map((e=>import(e)))),get target(){return Qr(p)?p.target.id:p.id}}))};a||o.then((()=>{const o=new Map,a={main:{...Gr(Jr,e),async onReady(t,r){d(t);for(const e of Jr("onReady"))await e(t,r);if(o.has(r)){let{message:e}=o.get(r);o.delete(r);const n=e===In;return e=`(${hr.CONFLICTING_CODE}) ${e} for `,e+=r.cloneNode(n).outerHTML,void t.io.stderr(e)}if(Qr(r)){const s=!jt(r),o=r.getAttribute("target"),a=o?Ln(r,o):document.createElement("script-py");if(!o){const{head:e,body:t}=document;e.contains(r)?t.append(a):r.after(a)}a.id||(a.id=l()),it(r,"target",{value:a}),_t(r,e,"ready"),n(r,s,t["run"+(s?"Async":"")](await c(r,t.io,!0)))}else r._wrap.resolve(t);console.debug("[pyscript/main] PyScript Ready")},onWorker(e,t){st(t.sync,Rr);for(const n of Jr("onWorker"))n(e,t)},onBeforeRun(e,t){p=t,Pr(Jr,e,t,"onBeforeRun")},onBeforeRunAsync:(e,t)=>(p=t,Pr(Jr,e,t,"onBeforeRunAsync")),onAfterRun(e,t){Pr(Jr,e,t,"onAfterRun")},onAfterRunAsync:(e,t)=>Pr(Jr,e,t,"onAfterRunAsync")},worker:{...Gr(qr,e),get onReady(){return Kr(this,"onReady")},get onBeforeRun(){return Kr(this,"onBeforeRun")},get onBeforeRunAsync(){return Kr(this,"onBeforeRunAsync")},get onAfterRun(){return Kr(this,"onAfterRun")},get onAfterRunAsync(){return Kr(this,"onAfterRunAsync")}}};cs.set(e,a),lr(e,{config:r,configURL:s,interpreter:t,hooks:a,env:`${e}-script`,version:ls(r),onerror(e,t){o.set(t,e)}}),customElements.define(`${e}-script`,class extends HTMLElement{constructor(){st(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 t=!jt(this),{io:r,run:s,runAsync:o}=await this._wrap.promise;this.srcCode=await c(this,r,!this.childElementCount),this.replaceChildren(),this.style.display="block",_t(this,e,"ready"),n(this,t,(t?o:s)(this.srcCode))}}})})),os[e]=structuredClone(r)}export{ur as H,_r as T,dr as X,tt as a,Ur as b,ir as c,at as d,ss as e,ns as f,rs as g,os as h,Vr as i,as as j,ls as o,kr as r,Hr as s};
2
- //# sourceMappingURL=core-CZGzC87D.js.map