polyscript
Advanced tools
Comparing version 0.6.10 to 0.6.11
@@ -7,5 +7,5 @@ 'use strict'; | ||
// REQUIRES INTEGRATION TEST | ||
/* c8 ignore start */ | ||
const getConfigURLAndType = config => { | ||
// REQUIRES INTEGRATION TEST | ||
/* c8 ignore start */ | ||
let type = typeof config; | ||
@@ -17,6 +17,14 @@ if (type === 'string' && /\.(json|toml|txt)$/.test(config)) | ||
return [absoluteURL(config), type]; | ||
/* c8 ignore stop */ | ||
}; | ||
exports.getConfigURLAndType = getConfigURLAndType; | ||
const parseString = config => { | ||
try { | ||
return JSON.parse(config); | ||
} catch (_) { | ||
return parse(config); | ||
} | ||
}; | ||
/* c8 ignore stop */ | ||
/** | ||
@@ -42,9 +50,7 @@ * Parse a generic config if it came from an attribute either as URL | ||
} else if (type === 'string') { | ||
try { | ||
options = JSON.parse(config); | ||
} catch (_) { | ||
options = parse(config); | ||
} | ||
options = parseString(config); | ||
} else if (type === 'object' && config) { | ||
options = config; | ||
} else if (type === 'txt' && typeof options === 'string') { | ||
options = parseString(options); | ||
} | ||
@@ -51,0 +57,0 @@ config = absolute; |
'use strict'; | ||
/* c8 ignore next */ | ||
module.exports = () => new Worker(URL.createObjectURL(new Blob(["const e=\"object\"==typeof self?self:globalThis,t=t=>((t,n)=>{const r=(e,n)=>(t.set(n,e),e),s=o=>{if(t.has(o))return t.get(o);const[a,i]=n[o];switch(a){case 0:case-1:return r(i,o);case 1:{const e=r([],o);for(const t of i)e.push(s(t));return e}case 2:{const e=r({},o);for(const[t,n]of i)e[s(t)]=s(n);return e}case 3:return r(new Date(i),o);case 4:{const{source:e,flags:t}=i;return r(new RegExp(e,t),o)}case 5:{const e=r(new Map,o);for(const[t,n]of i)e.set(s(t),s(n));return e}case 6:{const e=r(new Set,o);for(const t of i)e.add(s(t));return e}case 7:{const{name:t,message:n}=i;return r(new e[t](n),o)}case 8:return r(BigInt(i),o);case\"BigInt\":return r(Object(BigInt(i)),o)}return r(new e[a](i),o)};return s})(new Map,t)(0),n=\"\",{toString:r}={},{keys:s}=Object,o=e=>{const t=typeof e;if(\"object\"!==t||!e)return[0,t];const s=r.call(e).slice(8,-1);switch(s){case\"Array\":return[1,n];case\"Object\":return[2,n];case\"Date\":return[3,n];case\"RegExp\":return[4,n];case\"Map\":return[5,n];case\"Set\":return[6,n]}return s.includes(\"Array\")?[1,s]:s.includes(\"Error\")?[7,s]:[2,s]},a=([e,t])=>0===e&&(\"function\"===t||\"symbol\"===t),i=(e,{json:t,lossy:n}={})=>{const r=[];return((e,t,n,r)=>{const i=(e,t)=>{const s=r.push(e)-1;return n.set(t,s),s},c=r=>{if(n.has(r))return n.get(r);let[l,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=\"ac6c1995-0675-46af-a99f-7fa298fa4e6d\",h=\"M\"+f,d=\"T\"+f,g=\"array\",y=\"function\",m=\"null\",w=\"number\",_=\"object\",b=\"string\",E=\"symbol\",k=\"undefined\",v=\"apply\",T=\"construct\",S=\"defineProperty\",x=\"deleteProperty\",A=\"get\",O=\"getOwnPropertyDescriptor\",j=\"getPrototypeOf\",R=\"has\",P=\"isExtensible\",N=\"ownKeys\",I=\"preventExtensions\",$=\"set\",M=\"setPrototypeOf\",F=\"delete\";var H=e=>({value:new Promise((t=>{let n=new Worker(\"data:application/javascript,onmessage%3D(%7Bdata%3Ab%7D)%3D%3E(Atomics.wait(b%2C0)%2CpostMessage(0))\");n.onmessage=t,n.postMessage(e)}))})\n/*! (c) Andrea Giammarchi - ISC */;const{Int32Array:W,Map:C,SharedArrayBuffer:D,Uint16Array:L}=globalThis,{BYTES_PER_ELEMENT:B}=W,{BYTES_PER_ELEMENT:U}=L,{isArray:J}=Array,{notify:q,wait:G,waitAsync:K}=Atomics,Y=new WeakSet,z=new WeakMap,X={value:{then:e=>e()}};let V=0;const Z=(e,{parse:t=JSON.parse,stringify:n=JSON.stringify,transform:r,interrupt:s}=JSON)=>{if(!z.has(e)){const o=(t,...n)=>e.postMessage({[f]:n},{transfer:t}),a=typeof s===y?s:s?.handler,i=s?.delay||42,c=new TextDecoder(\"utf-16\"),l=(e,t)=>e?(K||H)(t,0):(a?((e,t,n)=>{for(;\"timed-out\"===G(e,0,0,t);)n()})(t,i,a):G(t,0),X);let u=!1;z.set(e,new Proxy(new C,{[R]:(e,t)=>\"string\"==typeof t&&!t.startsWith(\"_\"),[A]:(n,s)=>\"then\"===s?null:(...n)=>{const a=V++;let i=new W(new D(2*B)),p=[];Y.has(n.at(-1)||p)&&Y.delete(p=n.pop()),o(p,a,i,s,r?n.map(r):n);const f=e!==globalThis;let h=0;return u&&f&&(h=setTimeout(console.warn,1e3,`ππ - Possible deadlock if proxy.${s}(...args) is awaited`)),l(f,i).value.then((()=>{clearTimeout(h);const e=i[1];if(!e)return;const n=U*e;return i=new W(new D(n+n%B)),o([],a,i),l(f,i).value.then((()=>t(c.decode(new L(i.buffer).slice(0,e)))))}))},[$](t,s,o){const a=typeof o;if(a!==y)throw new Error(`Unable to assign ${s} as ${a}`);if(!t.size){const s=new C;e.addEventListener(\"message\",(async e=>{const o=e.data?.[f];if(J(o)){e.stopImmediatePropagation();const[a,i,...c]=o;let l;if(c.length){const[e,o]=c;if(t.has(e)){u=!0;try{const c=await t.get(e)(...o);if(void 0!==c){const e=n(r?r(c):c);s.set(a,e),i[1]=e.length}}catch(e){l=e}finally{u=!1}}else l=new Error(`Unsupported action: ${e}`);i[0]=1}else{const e=s.get(a);s.delete(a);for(let t=new L(i.buffer),n=0;n<e.length;n++)t[n]=e.charCodeAt(n)}if(q(i,0),l)throw l}}))}return!!t.set(s,o)}}))}return z.get(e)};Z.transfer=(...e)=>(Y.add(e),e);const{isArray:Q}=Array,ee=(e,t)=>t,te=e=>typeof e===y?(e=>e())(e):e;function ne(){return this}const re=(e,t)=>e===g?[t]:{t:e,v:t},se=(e,t=ee)=>{let n=typeof e,r=e;return n===_&&(Q(e)?(n=g,r=e.at(0)):({t:n,v:r}=e)),t(n,r)},oe=(e,t)=>e===y?t:re(e,t),ae=(e,t=oe)=>{const n=null===e?m:typeof e;return t(n===_&&Q(e)?g:n,e)},ie=new FinalizationRegistry((([e,t,n])=>{n&&console.debug(`Held value ${String(t)} not relevant anymore`),e(t)})),ce=Object.create(null),le=(e,t,{debug:n,return:r,token:s=e}=ce)=>{const o=r||new Proxy(e,ce),a=[o,[t,e,!!n]];return!1!==s&&a.push(s),ie.register(...a),o},{defineProperty:ue,deleteProperty:pe,getOwnPropertyDescriptor:fe,getPrototypeOf:he,isExtensible:de,ownKeys:ge,preventExtensions:ye,set:me,setPrototypeOf:we}=Reflect,{assign:_e,create:be}=Object,Ee=he(Int8Array),ke=(e,t)=>{const{get:n,set:r,value:s}=e;return n&&(e.get=t(n)),r&&(e.set=t(r)),s&&(e.value=t(s)),e},ve=e=>t=>ae(t,((t,n)=>{switch(t){case m:return re(m,n);case _:if(n===globalThis)return re(t,null);case g:case y:return e(t,n);case\"boolean\":case w:case b:case k:case\"bigint\":return re(t,n);case E:{if(Te.has(n))return re(t,Te.get(n));let e=Symbol.keyFor(n);if(e)return re(t,`.${e}`)}}throw new TypeError(`Unable to handle this ${t}: ${String(n)}`)})),Te=new Map(ge(Symbol).filter((e=>typeof Symbol[e]===E)).map((e=>[Symbol[e],e]))),Se=e=>{if(e.startsWith(\".\"))return Symbol.for(e.slice(1));for(const[t,n]of Te)if(n===e)return t},xe=e=>e;var Ae=((e,t)=>{const n=t&&new WeakMap;if(t){const{addEventListener:e}=EventTarget.prototype;ue(EventTarget.prototype,\"addEventListener\",{value(t,r,...s){return s.at(0)?.invoke&&(n.has(this)||n.set(this,new Map),n.get(this).set(t,[].concat(s[0].invoke)),delete s[0].invoke),e.call(this,t,r,...s)}})}const r=t&&(e=>{const{currentTarget:t,target:r,type:s}=e;for(const o of n.get(t||r)?.get(s)||[])e[o]()});return function(n,s,o,...a){let i=0,c=this?.transform||xe;const l=new Map,u=new Map,{[o]:p}=n,f=a.length?_e(be(globalThis),...a):globalThis,h=ve(((e,t)=>{if(!l.has(t)){let n;for(;u.has(n=i++););l.set(t,n),u.set(n,e===y?t:c(t))}return re(e,l.get(t))})),d=e=>{p(F,re(b,e))},m=(e,n)=>{switch(e){case _:if(null==n)return f;case g:if(typeof n===w)return u.get(n);if(!(n instanceof Ee))for(const e in n)n[e]=H(n[e]);return n;case y:if(typeof n===b){if(!u.has(n)){const e=function(...e){return t&&e.at(0)instanceof Event&&r(...e),p(v,re(y,n),h(this),e.map(h))};return u.set(n,new WeakRef(e)),le(n,d,{return:e,token:!1})}return u.get(n).deref()}return u.get(n);case E:return Se(n)}return n},H=e=>se(e,m),W={[v]:(e,t,n)=>h(e.apply(t,n)),[T]:(e,t)=>h(new e(...t)),[S]:(e,t,n)=>h(ue(e,t,n)),[x]:(e,t)=>h(pe(e,t)),[j]:e=>h(he(e)),[A]:(e,t)=>h(e[t]),[O]:(e,t)=>{const n=fe(e,t);return n?re(_,ke(n,h)):re(k,n)},[R]:(e,t)=>h(t in e),[P]:e=>h(de(e)),[N]:e=>re(g,ge(e).map(h)),[I]:e=>h(ye(e)),[$]:(e,t,n)=>h(me(e,t,n)),[M]:(e,t)=>h(we(e,t)),[F](e){l.delete(u.get(e)),u.delete(e)}};return n[s]=(e,t,...n)=>{switch(e){case v:n[0]=H(n[0]),n[1]=n[1].map(H);break;case T:n[0]=n[0].map(H);break;case S:{const[e,t]=n;n[0]=H(e);const{get:r,set:s,value:o}=t;r&&(t.get=H(r)),s&&(t.set=H(s)),o&&(t.value=H(o));break}default:n=n.map(H)}return W[e](H(t),...n)},{proxy:n,[e.toLowerCase()]:f,[`is${e}Proxy`]:()=>!1}}})(\"Window\",!0),Oe=(e=>{let t=0;const n=new Map,r=new Map,s=Symbol();return function(o,a,i){const c=this?.transform||xe,{[a]:l}=o,u=new Map,p=e=>{u.delete(e),l(F,f(e))},f=ve(((e,o)=>{if(s in o)return te(o[s]);if(e===y){if(o=c(o),!r.has(o)){let e;for(;r.has(e=String(t++)););n.set(o,e),r.set(e,o)}return re(e,n.get(o))}if(!(o instanceof Ee)){o=c(o);for(const e in o)o[e]=f(o[e])}return re(e,o)})),h=(e,t,n)=>{if(!u.has(n)){const r=t===y?(e=>ne.bind(e))(e):e,s=new Proxy(r,k);return u.set(n,new WeakRef(s)),le(n,p,{return:s,token:!1})}return u.get(n).deref()},d=e=>se(e,((t,n)=>{switch(t){case _:if(null===n)return globalThis;case g:return typeof n===w?h(e,t,n):n;case y:return typeof n===b?r.get(n):h(e,t,n);case E:return Se(n)}return n})),m=(e,t,...n)=>d(l(e,te(t),...n)),k={[v]:(e,t,n)=>m(v,e,f(t),n.map(f)),[T]:(e,t)=>m(T,e,t.map(f)),[S]:(e,t,n)=>{const{get:r,set:s,value:o}=n;return typeof r===y&&(n.get=f(r)),typeof s===y&&(n.set=f(s)),typeof o===y&&(n.value=f(o)),m(S,e,f(t),n)},[x]:(e,t)=>m(x,e,f(t)),[j]:e=>m(j,e),[A]:(e,t)=>t===s?e:m(A,e,f(t)),[O]:(e,t)=>{const n=m(O,e,f(t));return n&&ke(n,d)},[R]:(e,t)=>t===s||m(R,e,f(t)),[P]:e=>m(P,e),[N]:e=>m(N,e).map(d),[I]:e=>m(I,e),[$]:(e,t,n)=>m($,e,f(t),f(n)),[M]:(e,t)=>m(M,e,f(t))};o[i]=(e,t,s,o)=>{switch(e){case v:return d(t).apply(d(s),o.map(d));case F:{const e=d(t);n.delete(r.get(e)),r.delete(e)}}};const H=new Proxy(re(_,null),k);return{[e.toLowerCase()]:H,[`is${e}Proxy`]:e=>typeof e===_&&!!e&&s in e,proxy:o}}})(\"Window\"),je=typeof Worker===y?Worker:class{};const Re=new WeakMap,Pe=(e,...t)=>{const n=Z(e,...t);if(!Re.has(n)){const r=e instanceof je?Ae:Oe;Re.set(n,r.call(t.at(0),n,h,d))}return Re.get(n)};Pe.transfer=Z.transfer;const Ne={object(...e){return this.string(function(e){for(var t=e[0],n=1,r=arguments.length;n<r;n++)t+=arguments[n]+e[n];return t}(...e))},string(e){for(const t of e.split(/[\\r\\n]+/))if(t.trim().length){/^(\\s+)/.test(t)&&(e=e.replace(new RegExp(\"^\"+RegExp.$1,\"gm\"),\"\"));break}return e}};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 Ie=e=>e.arrayBuffer(),$e=e=>e.json(),Me=e=>e.text(),Fe=new WeakMap,He=e=>{const t=e||console,n={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 Fe.set(t,n),t}}},We=({FS:e,PATH:t,PATH_FS:n},r,s)=>{const o=n.resolve(r);return e.mkdirTree(t.dirname(o)),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},Ce=e=>{const t=e.split(\"/\");return t.pop(),t.join(\"/\")},De=(e,t)=>{const n=[];for(const r of t.split(\"/\"))\".\"!==r&&(n.push(r),r&&e.mkdir(n.join(\"/\")))},Le=(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(/^\\/+/,\"/\")},Be=e=>{const t=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,\"\"))).filter((e=>\"\"!==e&&\".\"!==e)).join(\"/\");return e[0].startsWith(\"/\")?`/${t}`:t},Ue=(e,t)=>fetch(at(t,Je.get(e))),Je=new WeakMap,qe=(e,t,n)=>st((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(Ze(r))return r.map((n=>({url:Be([e,n]),path:Be([t,n])})));const s=n||e.slice(1+e.lastIndexOf(\"/\"));return[{url:e,path:Be([t,s])}]}))})(n).map((({url:r,path:s})=>Ue(n,r).then(Ie).then((n=>e.writeFile(t,s,n)))))),Ge=(e,t)=>t.endsWith(\"/\")?`${t}${e.split(\"/\").pop()}`:t,Ke=(e,t)=>e.replace(/\\{.+?\\}/g,(e=>{if(!t.has(e))throw new SyntaxError(`Invalid template: ${e}`);return t.get(e)})),Ye=(e,t,n)=>st((e=>{const t=new Map,n=new Set,r=[];for(const[s,o]of rt(e))if(/^\\{.+\\}$/.test(s)){if(t.has(s))throw new SyntaxError(`Duplicated template: ${s}`);t.set(s,Ke(o,t))}else{const e=Ke(s,t),a=Ge(e,Ke(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:r,path:s})=>Ue(n,r).then(Ie).then((n=>e.writeFile(t,s,n)))))),ze=typeof document===k,Xe=({main:e,worker:t})=>{const n=[];if(t&&ze)for(let[e,r]of rt(t))e=at(e,Je.get(t)),n.push(ht(e,r));if(e&&!ze)for(let[t,r]of rt(e))t=at(t,Je.get(e)),gt(t)?dt(t):n.push(ht(t,r));return st(n)},Ve=(e,...t)=>Ne[typeof e](e,...t),{isArray:Ze}=Array,{assign:Qe,create:et,defineProperties:tt,defineProperty:nt,entries:rt}=Object,{all:st,resolve:ot}=new Proxy(Promise,{get:(e,t)=>e[t].bind(e)}),at=(e,t=location.href)=>new URL(e,t.replace(/^blob:/,\"\")).href,it=(e,t,n,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${t}:${n}`,{bubbles:!0,detail:{worker:r}}))},ct=e=>Function(`'use strict';return (${e})`)(),lt=Symbol.for(\"polyscript.js_modules\"),ut=new Map;nt(globalThis,lt,{value:ut}),new Proxy(ut,{get:(e,t)=>e.get(t),has:(e,t)=>e.has(t),ownKeys:e=>[...e.keys()]});const pt=(e,t)=>!t.startsWith(\"_\"),ft=(e,t)=>new Proxy(e,{has:pt,get:(e,n)=>e[t][n]}),ht=(e,t)=>import(e).then((e=>{ut.set(t,{...e})})),dt=e=>new Promise(((t,n)=>{document.querySelector(`link[href=\"${e}\"]`)&&t(),document.head.append(Qe(document.createElement(\"link\"),{rel:\"stylesheet\",href:e,onload:t,onerror:n}))})),gt=e=>/\\.css/i.test(new URL(e).pathname),yt=(e,t)=>e.has(t),mt=e=>[...e.keys()];var wt=(e,t,n)=>{let r=globalThis[lt],s=\"\";if(n){s=Je.get(n);for(let[e,t]of rt(n)){let n=r.get(t);n&&!Ze(n)||(r.set(t,n||(n=[])),n.push(e))}}return((e,t,n,r)=>new Proxy(e,{has:yt,ownKeys:mt,get:(e,s)=>{let o=e.get(s);if(Ze(o)){let a=o;o=null;for(let e of a)e=at(e,r),gt(e)?n.importCSS(e):(n.importJS(e,s),o=t[lt].get(s));e.set(s,o)}return o}}))(r,e,t,s)};const _t=(e,t,n)=>{e.registerJsModule(t,n)},bt=(e,t,...n)=>{try{return e.runPython(Ve(t),...n)}catch(t){Fe.get(e).stderr(t)}},Et=async(e,t,...n)=>{try{return await e.runPythonAsync(Ve(t),...n)}catch(t){Fe.get(e).stderr(t)}},kt=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){Fe.get(e).stderr(t)}};var vt=(new TextEncoder).encode('from uio import StringIO\\nimport sys\\n\\nclass Response:\\n def __init__(self, f):\\n self.raw = f\\n self.encoding = \"utf-8\"\\n self._cached = None\\n\\n def close(self):\\n if self.raw:\\n self.raw.close()\\n self.raw = None\\n self._cached = None\\n\\n @property\\n def content(self):\\n if self._cached is None:\\n try:\\n self._cached = self.raw.read()\\n finally:\\n self.raw.close()\\n self.raw = None\\n return self._cached\\n\\n @property\\n def text(self):\\n return str(self.content, self.encoding)\\n\\n def json(self):\\n import ujson\\n\\n return ujson.loads(self.content)\\n\\n\\n# TODO try to support streaming xhr requests, a-la pyodide-http\\nHEADERS_TO_IGNORE = (\"user-agent\",)\\n\\n\\ntry:\\n import js\\nexcept Exception as err:\\n raise OSError(\"This version of urequests can only be used in the browser\")\\n\\n# TODO try to support streaming xhr requests, a-la pyodide-http\\n\\nHEADERS_TO_IGNORE = (\"user-agent\",)\\n\\n\\ndef request(\\n method,\\n url,\\n data=None,\\n json=None,\\n headers={},\\n stream=None,\\n auth=None,\\n timeout=None,\\n parse_headers=True,\\n):\\n from js import XMLHttpRequest\\n\\n xhr = XMLHttpRequest.new()\\n xhr.withCredentials = False\\n\\n if auth is not None:\\n import ubinascii\\n\\n username, password = auth\\n xhr.open(method, url, False, username, password)\\n else:\\n xhr.open(method, url, False)\\n\\n for name, value in headers.items():\\n if name.lower() not in HEADERS_TO_IGNORE:\\n xhr.setRequestHeader(name, value)\\n\\n if timeout:\\n xhr.timeout = int(timeout * 1000)\\n\\n if json is not None:\\n assert data is None\\n import ujson\\n\\n data = ujson.dumps(json)\\n # s.write(b\"Content-Type: application/json\\\\r\\\\n\")\\n xhr.setRequestHeader(\"Content-Type\", \"application/json\")\\n\\n xhr.send(data)\\n\\n # Emulates the construction process in the original urequests\\n resp = Response(StringIO(xhr.responseText))\\n resp.status_code = xhr.status\\n resp.reason = xhr.statusText\\n resp.headers = xhr.getAllResponseHeaders()\\n\\n return resp\\n\\n\\n# Other methods - head, post, put, patch, delete - are not used by\\n# mip and therefore not included\\n\\n\\ndef get(url, **kw):\\n return request(\"GET\", url, **kw)\\n\\n\\n# Content below this line is from the Micropython MIP package and is covered\\n# by the applicable MIT license:\\n# \\n# THE SOFTWARE IS PROVIDED βAS ISβ, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \\n# DEALINGS IN THE SOFTWARE.\\n\\n# MicroPython package installer\\n# MIT license; Copyright (c) 2022 Jim Mussared\\n\\n\\n_PACKAGE_INDEX = const(\"https://micropython.org/pi/v2\")\\n_CHUNK_SIZE = 128\\n\\n\\n# This implements os.makedirs(os.dirname(path))\\ndef _ensure_path_exists(path):\\n import os\\n\\n split = path.split(\"/\")\\n\\n # Handle paths starting with \"/\".\\n if not split[0]:\\n split.pop(0)\\n split[0] = \"/\" + split[0]\\n\\n prefix = \"\"\\n for i in range(len(split) - 1):\\n prefix += split[i]\\n try:\\n os.stat(prefix)\\n except:\\n os.mkdir(prefix)\\n prefix += \"/\"\\n\\n\\n# Copy from src (stream) to dest (function-taking-bytes)\\ndef _chunk(src, dest):\\n buf = memoryview(bytearray(_CHUNK_SIZE))\\n while True:\\n n = src.readinto(buf)\\n if n == 0:\\n break\\n dest(buf if n == _CHUNK_SIZE else buf[:n])\\n\\n\\n# Check if the specified path exists and matches the hash.\\ndef _check_exists(path, short_hash):\\n import os\\n\\n try:\\n import binascii\\n import hashlib\\n\\n with open(path, \"rb\") as f:\\n hs256 = hashlib.sha256()\\n _chunk(f, hs256.update)\\n existing_hash = str(binascii.hexlify(hs256.digest())[: len(short_hash)], \"utf-8\")\\n return existing_hash == short_hash\\n except:\\n return False\\n\\n\\ndef _rewrite_url(url, branch=None):\\n if not branch:\\n branch = \"HEAD\"\\n if url.startswith(\"github:\"):\\n url = url[7:].split(\"/\")\\n url = (\\n \"https://raw.githubusercontent.com/\"\\n + url[0]\\n + \"/\"\\n + url[1]\\n + \"/\"\\n + branch\\n + \"/\"\\n + \"/\".join(url[2:])\\n )\\n return url\\n\\n\\ndef _download_file(url, dest):\\n response = get(url)\\n try:\\n if response.status_code != 200:\\n print(\"Error\", response.status_code, \"requesting\", url)\\n return False\\n\\n print(\"Copying:\", dest)\\n _ensure_path_exists(dest)\\n with open(dest, \"wb\") as f:\\n _chunk(response.raw, f.write)\\n\\n return True\\n finally:\\n response.close()\\n\\n\\ndef _install_json(package_json_url, index, target, version, mpy):\\n response = get(_rewrite_url(package_json_url, version))\\n try:\\n if response.status_code != 200:\\n print(\"Package not found:\", package_json_url)\\n return False\\n\\n package_json = response.json()\\n finally:\\n response.close()\\n for target_path, short_hash in package_json.get(\"hashes\", ()):\\n fs_target_path = target + \"/\" + target_path\\n if _check_exists(fs_target_path, short_hash):\\n print(\"Exists:\", fs_target_path)\\n else:\\n file_url = \"{}/file/{}/{}\".format(index, short_hash[:2], short_hash)\\n if not _download_file(file_url, fs_target_path):\\n print(\"File not found: {} {}\".format(target_path, short_hash))\\n return False\\n for target_path, url in package_json.get(\"urls\", ()):\\n fs_target_path = target + \"/\" + target_path\\n if not _download_file(_rewrite_url(url, version), fs_target_path):\\n print(\"File not found: {} {}\".format(target_path, url))\\n return False\\n for dep, dep_version in package_json.get(\"deps\", ()):\\n if not _install_package(dep, index, target, dep_version, mpy):\\n return False\\n return True\\n\\n\\ndef _install_package(package, index, target, version, mpy):\\n if (\\n package.startswith(\"http://\")\\n or package.startswith(\"https://\")\\n or package.startswith(\"github:\")\\n ):\\n if package.endswith(\".py\") or package.endswith(\".mpy\"):\\n print(\"Downloading {} to {}\".format(package, target))\\n return _download_file(\\n _rewrite_url(package, version), target + \"/\" + package.rsplit(\"/\")[-1]\\n )\\n else:\\n if not package.endswith(\".json\"):\\n if not package.endswith(\"/\"):\\n package += \"/\"\\n package += \"package.json\"\\n print(\"Installing {} to {}\".format(package, target))\\n else:\\n if not version:\\n version = \"latest\"\\n print(\"Installing {} ({}) from {} to {}\".format(package, version, index, target))\\n\\n mpy_version = (\\n sys.implementation._mpy & 0xFF if mpy and hasattr(sys.implementation, \"_mpy\") else \"py\"\\n )\\n\\n package = \"{}/package/{}/{}/{}.json\".format(index, mpy_version, package, version)\\n\\n return _install_json(package, index, target, version, mpy)\\n\\n\\ndef install(package, index=None, target=None, version=None, mpy=True):\\n if not target:\\n for p in sys.path:\\n if p.endswith(\"/lib\"):\\n target = p\\n break\\n else:\\n print(\"Unable to find lib dir in sys.path\")\\n return\\n\\n if not index:\\n index = _PACKAGE_INDEX\\n\\n if _install_package(package, index.rstrip(\"/\"), target, version, mpy):\\n print(\"Done\")\\n else:\\n print(\"Package may be partially installed\")\\n');var Tt={type:\"micropython\",module:(e=\"1.21.0-279\")=>`https://cdn.jsdelivr.net/npm/@micropython/micropython-webassembly-pyscript@${e}/micropython.mjs`,async engine({loadMicroPython:e},t,n){const{stderr:r,stdout:s,get:o}=He();n=n.replace(/\\.m?js$/,\".wasm\");const a=await o(e({stderr:r,stdout:s,url:n}));if(t.files&&await Ye(this,a,t.files),t.fetch&&await qe(this,a,t.fetch),t.js_modules&&await Xe(t.js_modules),this.writeFile(a,\"./mip.py\",vt),t.packages){const e=a.pyimport(\"mip\");for(const n of t.packages)e.install(n)}return a},registerJSModule:_t,run:bt,runAsync:Et,runEvent:kt,transform:(e,t)=>t instanceof e.PyProxy?e.PyProxy.toJs(t):t,writeFile:({FS:e,_module:{PATH:t,PATH_FS:n}},r,s)=>We({FS:e,PATH:t,PATH_FS:n},r,s)};const St={dict_converter:Object.fromEntries};var xt={type:\"pyodide\",module:(e=\"0.24.1\")=>`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},t,n){const{stderr:r,stdout:s,get:o}=He(),a=n.slice(0,n.lastIndexOf(\"/\")),i=await o(e({stderr:r,stdout:s,indexURL:a}));if(t.files&&await Ye(this,i,t.files),t.fetch&&await qe(this,i,t.fetch),t.js_modules&&await Xe(t.js_modules),t.packages){await i.loadPackage(\"micropip\");const e=await i.pyimport(\"micropip\");await e.install(t.packages,{keep_going:!0}),e.destroy()}return i},registerJSModule:_t,run:bt,runAsync:Et,runEvent:kt,transform:(e,t)=>t instanceof e.ffi.PyProxy?t.toJs(St):t,writeFile:({FS:e,PATH:t,_module:{PATH_FS:n}},r,s)=>We({FS:e,PATH:t,PATH_FS:n},r,s)};const At=\"ruby-wasm-wasi\",Ot=At.replace(/\\W+/g,\"_\");var jt={type:At,experimental:!0,module:(e=\"2.2.0\")=>`https://cdn.jsdelivr.net/npm/ruby-3_2-wasm-wasi@${e}/dist/browser.esm.js`,async engine({DefaultRubyVM:e},t,n){const r=await fetch(`${n.slice(0,n.lastIndexOf(\"/\"))}/ruby.wasm`),s=await WebAssembly.compile(await r.arrayBuffer()),{vm:o}=await e(s);return t.files&&await Ye(this,o,t.files),t.fetch&&await qe(this,o,t.fetch),t.js_modules&&await Xe(t.js_modules),o},registerJSModule(e,t,n){t=t.replace(/\\W+/g,\"__\");const r=`__module_${Ot}_${t}`;globalThis[r]=n,this.run(e,`require \"js\";$${t}=JS.global[:${r}]`),delete globalThis[r]},run:(e,t,...n)=>e.eval(Ve(t),...n),runAsync:(e,t,...n)=>e.evalAsync(Ve(t),...n),async runEvent(e,t,n){if(/^xworker\\.(on\\w+)$/.test(t)){const{$1:t}=RegExp,r=`__module_${Ot}_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 ${At}`)}};var Rt={type:\"wasmoon\",module:(e=\"1.16.0\")=>`https://cdn.jsdelivr.net/npm/wasmoon@${e}/+esm`,async engine({LuaFactory:e,LuaLibraries:t},n){const{stderr:r,stdout:s,get:o}=He(),a=await o((new e).createEngine());return a.global.getTable(t.Base,(e=>{a.global.setField(e,\"print\",s),a.global.setField(e,\"printErr\",r)})),n.files&&await Ye(this,a,n.files),n.fetch&&await qe(this,a,n.fetch),n.js_modules&&await Xe(n.js_modules),a},registerJSModule:(e,t,n)=>{e.global.set(t,n)},run:(e,t,...n)=>{try{return e.doStringSync(Ve(t),...n)}catch(t){Fe.get(e).stderr(t)}},runAsync:async(e,t,...n)=>{try{return await e.doString(Ve(t),...n)}catch(t){Fe.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){Fe.get(e).stderr(t)}},transform:(e,t)=>t,writeFile:({cmodule:{module:{FS:e}}},t,n)=>((e,t,n)=>(De(e,Ce(t)),t=Le(e,t),e.writeFile(t,new Uint8Array(n),{canOwn:!0})))(e,t,n)};const Pt=new Map,Nt=new Map,It=new Proxy(new Map,{get(e,t){if(!e.has(t)){const[n,...r]=t.split(\"@\"),s=Pt.get(n),o=/^(?:\\.?\\.?\\/|https?:\\/\\/)/i.test(r)?r.join(\"@\"):s.module(...r);e.set(t,{url:o,module:import(o),engine:s.engine.bind(s)})}const{url:n,module:r,engine:s}=e.get(t);return(e,o)=>r.then((r=>{Nt.set(t,e);for(const t of[\"files\",\"fetch\"]){const n=e?.[t];n&&Je.set(n,o)}for(const t of[\"main\",\"worker\"]){const n=e?.js_modules?.[t];n&&Je.set(n,o)}return s(r,e,n)}))}}),$t=e=>{for(const t of[].concat(e.type))Pt.set(t,e)};for(const e of[Tt,xt,jt,Rt])$t(e);const Mt=async e=>(await import(\"https://cdn.jsdelivr.net/npm/basic-toml@0.3.1/es.js\")).parse(e),Ft=(e,t,n={})=>{if(t){const[e,r]=(e=>{let t=typeof e;return\"string\"===t&&/\\.(json|toml|txt)$/.test(e)?t=RegExp.$1:e=\"./config.txt\",[at(e),t]})(t);if(\"json\"===r)n=fetch(e).then($e);else if(\"toml\"===r)n=fetch(e).then(Me).then(Mt);else if(\"string\"===r)try{n=JSON.parse(t)}catch(e){n=Mt(t)}else\"object\"===r&&t&&(n=t);t=e}return ot(n).then((n=>It[e](n,t)))},Ht=\"BeforeRun\",Wt=\"AfterRun\",Ct=[`code${Ht}`,`code${Ht}Async`,`code${Wt}`,`code${Wt}Async`],Dt=[\"onWorker\",\"onReady\",`on${Ht}`,`on${Ht}Async`,`on${Wt}`,`on${Wt}Async`];function Lt(e,t){const{run:n,runAsync:r}=Pt.get(this.type);return{...e,run:n.bind(this,t),runAsync:r.bind(this,t)}}const Bt=(e,t,n,r,s,o)=>{if(s||o){const a=Lt.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}}};try{new SharedArrayBuffer(4)}catch(e){throw new Error([\"Unable to use SharedArrayBuffer due insecure environment.\",\"Please read requirements in MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements\"].join(\"\\n\"))}let Ut,Jt,qt;const Gt=(e,t)=>{addEventListener(e,t||(async t=>{try{await Ut,Jt(`xworker.on${e}`,t)}catch(e){postMessage(e)}}),!!t&&{once:!0})},{parse:Kt,stringify:Yt}=p,{proxy:zt,window:Xt,isWindowProxy:Vt}=Pe(self,{parse:Kt,stringify:Yt,transform:e=>qt?qt(e):e}),Zt={sync:zt,window:Xt,isWindowProxy:Vt,onmessage:console.info,onerror:console.error,onmessageerror:console.warn,postMessage:postMessage.bind(self)};Gt(\"message\",(({data:{options:e,config:t,code:n,hooks:r}})=>{Ut=(async()=>{try{const{id:s,tag:o,type:a,custom:i,version:c,config:l,async:u}=e,p=((e,t=\"\")=>`${e}@${t}`.replace(/@$/,\"\"))(a,c),f=await Ft(p,t,l),h=Nt.get(p).js_modules?.main,d=et(Pt.get(a)),g=((e,t,n,r)=>({type:t,config:n,interpreter:r,io:Fe.get(r),run:(t,...n)=>e.run(r,t,...n),runAsync:(t,...n)=>e.runAsync(r,t,...n),runEvent:(...t)=>e.runEvent(r,...t)}))(d,i||a,l,f);let y=\"run\";if(u&&(y+=\"Async\"),r){const e=((e,t)=>(n,r)=>{const s=e[t].bind(e);e[t]=(e,t,...o)=>s(e,`${r?n:t}\\n${r?t:n}`,...o)})(d,y);let t,n,s=\"\",o=\"\";for(const e of Ct){const t=r[e];if(t){const n=e.endsWith(\"Async\");(n&&u||!n&&!u)&&(e.startsWith(\"codeBefore\")?s=t:o=t)}}o&&e(o,!1),s&&e(s,!0);for(const e of Dt.slice(2)){const s=r[e];if(s){const r=e.endsWith(\"Async\");if(r&&u||!r&&!u){const r=ct(s);e.startsWith(\"onBefore\")?t=r:n=r}}}Bt(d,g,Zt,u,t,n)}const{CustomEvent:m,document:w}=Xt,_=s&&w.getElementById(s)||null,b=e=>it(_,i||a,e,!0,m),E=wt(Xt,zt,h);let k=\"\";return((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}`,ft(r,e));t.registerJSModule(n,s,r)})(a,d,f,E),d.registerJSModule(f,\"polyscript\",{xworker:Zt,currentScript:_,js_modules:E,get target(){return!k&&_&&(\"SCRIPT\"===o?_.after(Qe(w.createElement(`script-${i||a}`),{id:k=`${s}-target`})):(k=s,_.replaceChildren(),_.style.display=\"block\")),k}}),Jt=d.runEvent.bind(d,f),qt=d.transform.bind(d,f),_&&b(\"ready\"),r?.onReady&&ct(r?.onReady).call(d,Lt.call(d,g,f),Zt),await d[y](f,n),_&&b(\"done\"),f}catch(e){postMessage(e)}})(),Gt(\"error\"),Gt(\"message\"),Gt(\"messageerror\")}));\n"],{type:'application/javascript'})),{type:'module'}); | ||
module.exports = () => new Worker(URL.createObjectURL(new Blob(["const e=\"object\"==typeof self?self:globalThis,t=t=>((t,n)=>{const r=(e,n)=>(t.set(n,e),e),s=o=>{if(t.has(o))return t.get(o);const[a,i]=n[o];switch(a){case 0:case-1:return r(i,o);case 1:{const e=r([],o);for(const t of i)e.push(s(t));return e}case 2:{const e=r({},o);for(const[t,n]of i)e[s(t)]=s(n);return e}case 3:return r(new Date(i),o);case 4:{const{source:e,flags:t}=i;return r(new RegExp(e,t),o)}case 5:{const e=r(new Map,o);for(const[t,n]of i)e.set(s(t),s(n));return e}case 6:{const e=r(new Set,o);for(const t of i)e.add(s(t));return e}case 7:{const{name:t,message:n}=i;return r(new e[t](n),o)}case 8:return r(BigInt(i),o);case\"BigInt\":return r(Object(BigInt(i)),o)}return r(new e[a](i),o)};return s})(new Map,t)(0),n=\"\",{toString:r}={},{keys:s}=Object,o=e=>{const t=typeof e;if(\"object\"!==t||!e)return[0,t];const s=r.call(e).slice(8,-1);switch(s){case\"Array\":return[1,n];case\"Object\":return[2,n];case\"Date\":return[3,n];case\"RegExp\":return[4,n];case\"Map\":return[5,n];case\"Set\":return[6,n]}return s.includes(\"Array\")?[1,s]:s.includes(\"Error\")?[7,s]:[2,s]},a=([e,t])=>0===e&&(\"function\"===t||\"symbol\"===t),i=(e,{json:t,lossy:n}={})=>{const r=[];return((e,t,n,r)=>{const i=(e,t)=>{const s=r.push(e)-1;return n.set(t,s),s},c=r=>{if(n.has(r))return n.get(r);let[l,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=\"ac6c1995-0675-46af-a99f-7fa298fa4e6d\",h=\"M\"+f,d=\"T\"+f,g=\"array\",y=\"function\",m=\"null\",w=\"number\",_=\"object\",b=\"string\",E=\"symbol\",k=\"undefined\",v=\"apply\",T=\"construct\",S=\"defineProperty\",x=\"deleteProperty\",A=\"get\",O=\"getOwnPropertyDescriptor\",j=\"getPrototypeOf\",R=\"has\",P=\"isExtensible\",N=\"ownKeys\",I=\"preventExtensions\",$=\"set\",M=\"setPrototypeOf\",F=\"delete\";var H=e=>({value:new Promise((t=>{let n=new Worker(\"data:application/javascript,onmessage%3D(%7Bdata%3Ab%7D)%3D%3E(Atomics.wait(b%2C0)%2CpostMessage(0))\");n.onmessage=t,n.postMessage(e)}))})\n/*! (c) Andrea Giammarchi - ISC */;const{Int32Array:W,Map:C,SharedArrayBuffer:D,Uint16Array:L}=globalThis,{BYTES_PER_ELEMENT:B}=W,{BYTES_PER_ELEMENT:U}=L,{isArray:J}=Array,{notify:q,wait:G,waitAsync:K}=Atomics,Y=new WeakSet,z=new WeakMap,X={value:{then:e=>e()}};let V=0;const Z=(e,{parse:t=JSON.parse,stringify:n=JSON.stringify,transform:r,interrupt:s}=JSON)=>{if(!z.has(e)){const o=(t,...n)=>e.postMessage({[f]:n},{transfer:t}),a=typeof s===y?s:s?.handler,i=s?.delay||42,c=new TextDecoder(\"utf-16\"),l=(e,t)=>e?(K||H)(t,0):(a?((e,t,n)=>{for(;\"timed-out\"===G(e,0,0,t);)n()})(t,i,a):G(t,0),X);let u=!1;z.set(e,new Proxy(new C,{[R]:(e,t)=>\"string\"==typeof t&&!t.startsWith(\"_\"),[A]:(n,s)=>\"then\"===s?null:(...n)=>{const a=V++;let i=new W(new D(2*B)),p=[];Y.has(n.at(-1)||p)&&Y.delete(p=n.pop()),o(p,a,i,s,r?n.map(r):n);const f=e!==globalThis;let h=0;return u&&f&&(h=setTimeout(console.warn,1e3,`ππ - Possible deadlock if proxy.${s}(...args) is awaited`)),l(f,i).value.then((()=>{clearTimeout(h);const e=i[1];if(!e)return;const n=U*e;return i=new W(new D(n+n%B)),o([],a,i),l(f,i).value.then((()=>t(c.decode(new L(i.buffer).slice(0,e)))))}))},[$](t,s,o){const a=typeof o;if(a!==y)throw new Error(`Unable to assign ${s} as ${a}`);if(!t.size){const s=new C;e.addEventListener(\"message\",(async e=>{const o=e.data?.[f];if(J(o)){e.stopImmediatePropagation();const[a,i,...c]=o;let l;if(c.length){const[e,o]=c;if(t.has(e)){u=!0;try{const c=await t.get(e)(...o);if(void 0!==c){const e=n(r?r(c):c);s.set(a,e),i[1]=e.length}}catch(e){l=e}finally{u=!1}}else l=new Error(`Unsupported action: ${e}`);i[0]=1}else{const e=s.get(a);s.delete(a);for(let t=new L(i.buffer),n=0;n<e.length;n++)t[n]=e.charCodeAt(n)}if(q(i,0),l)throw l}}))}return!!t.set(s,o)}}))}return z.get(e)};Z.transfer=(...e)=>(Y.add(e),e);const{isArray:Q}=Array,ee=(e,t)=>t,te=e=>typeof e===y?(e=>e())(e):e;function ne(){return this}const re=(e,t)=>e===g?[t]:{t:e,v:t},se=(e,t=ee)=>{let n=typeof e,r=e;return n===_&&(Q(e)?(n=g,r=e.at(0)):({t:n,v:r}=e)),t(n,r)},oe=(e,t)=>e===y?t:re(e,t),ae=(e,t=oe)=>{const n=null===e?m:typeof e;return t(n===_&&Q(e)?g:n,e)},ie=new FinalizationRegistry((([e,t,n])=>{n&&console.debug(`Held value ${String(t)} not relevant anymore`),e(t)})),ce=Object.create(null),le=(e,t,{debug:n,return:r,token:s=e}=ce)=>{const o=r||new Proxy(e,ce),a=[o,[t,e,!!n]];return!1!==s&&a.push(s),ie.register(...a),o},{defineProperty:ue,deleteProperty:pe,getOwnPropertyDescriptor:fe,getPrototypeOf:he,isExtensible:de,ownKeys:ge,preventExtensions:ye,set:me,setPrototypeOf:we}=Reflect,{assign:_e,create:be}=Object,Ee=he(Int8Array),ke=(e,t)=>{const{get:n,set:r,value:s}=e;return n&&(e.get=t(n)),r&&(e.set=t(r)),s&&(e.value=t(s)),e},ve=e=>t=>ae(t,((t,n)=>{switch(t){case m:return re(m,n);case _:if(n===globalThis)return re(t,null);case g:case y:return e(t,n);case\"boolean\":case w:case b:case k:case\"bigint\":return re(t,n);case E:{if(Te.has(n))return re(t,Te.get(n));let e=Symbol.keyFor(n);if(e)return re(t,`.${e}`)}}throw new TypeError(`Unable to handle this ${t}: ${String(n)}`)})),Te=new Map(ge(Symbol).filter((e=>typeof Symbol[e]===E)).map((e=>[Symbol[e],e]))),Se=e=>{if(e.startsWith(\".\"))return Symbol.for(e.slice(1));for(const[t,n]of Te)if(n===e)return t},xe=e=>e;var Ae=((e,t)=>{const n=t&&new WeakMap;if(t){const{addEventListener:e}=EventTarget.prototype;ue(EventTarget.prototype,\"addEventListener\",{value(t,r,...s){return s.at(0)?.invoke&&(n.has(this)||n.set(this,new Map),n.get(this).set(t,[].concat(s[0].invoke)),delete s[0].invoke),e.call(this,t,r,...s)}})}const r=t&&(e=>{const{currentTarget:t,target:r,type:s}=e;for(const o of n.get(t||r)?.get(s)||[])e[o]()});return function(n,s,o,...a){let i=0,c=this?.transform||xe;const l=new Map,u=new Map,{[o]:p}=n,f=a.length?_e(be(globalThis),...a):globalThis,h=ve(((e,t)=>{if(!l.has(t)){let n;for(;u.has(n=i++););l.set(t,n),u.set(n,e===y?t:c(t))}return re(e,l.get(t))})),d=e=>{p(F,re(b,e))},m=(e,n)=>{switch(e){case _:if(null==n)return f;case g:if(typeof n===w)return u.get(n);if(!(n instanceof Ee))for(const e in n)n[e]=H(n[e]);return n;case y:if(typeof n===b){if(!u.has(n)){const e=function(...e){return t&&e.at(0)instanceof Event&&r(...e),p(v,re(y,n),h(this),e.map(h))};return u.set(n,new WeakRef(e)),le(n,d,{return:e,token:!1})}return u.get(n).deref()}return u.get(n);case E:return Se(n)}return n},H=e=>se(e,m),W={[v]:(e,t,n)=>h(e.apply(t,n)),[T]:(e,t)=>h(new e(...t)),[S]:(e,t,n)=>h(ue(e,t,n)),[x]:(e,t)=>h(pe(e,t)),[j]:e=>h(he(e)),[A]:(e,t)=>h(e[t]),[O]:(e,t)=>{const n=fe(e,t);return n?re(_,ke(n,h)):re(k,n)},[R]:(e,t)=>h(t in e),[P]:e=>h(de(e)),[N]:e=>re(g,ge(e).map(h)),[I]:e=>h(ye(e)),[$]:(e,t,n)=>h(me(e,t,n)),[M]:(e,t)=>h(we(e,t)),[F](e){l.delete(u.get(e)),u.delete(e)}};return n[s]=(e,t,...n)=>{switch(e){case v:n[0]=H(n[0]),n[1]=n[1].map(H);break;case T:n[0]=n[0].map(H);break;case S:{const[e,t]=n;n[0]=H(e);const{get:r,set:s,value:o}=t;r&&(t.get=H(r)),s&&(t.set=H(s)),o&&(t.value=H(o));break}default:n=n.map(H)}return W[e](H(t),...n)},{proxy:n,[e.toLowerCase()]:f,[`is${e}Proxy`]:()=>!1}}})(\"Window\",!0),Oe=(e=>{let t=0;const n=new Map,r=new Map,s=Symbol();return function(o,a,i){const c=this?.transform||xe,{[a]:l}=o,u=new Map,p=e=>{u.delete(e),l(F,f(e))},f=ve(((e,o)=>{if(s in o)return te(o[s]);if(e===y){if(o=c(o),!r.has(o)){let e;for(;r.has(e=String(t++)););n.set(o,e),r.set(e,o)}return re(e,n.get(o))}if(!(o instanceof Ee)){o=c(o);for(const e in o)o[e]=f(o[e])}return re(e,o)})),h=(e,t,n)=>{if(!u.has(n)){const r=t===y?(e=>ne.bind(e))(e):e,s=new Proxy(r,k);return u.set(n,new WeakRef(s)),le(n,p,{return:s,token:!1})}return u.get(n).deref()},d=e=>se(e,((t,n)=>{switch(t){case _:if(null===n)return globalThis;case g:return typeof n===w?h(e,t,n):n;case y:return typeof n===b?r.get(n):h(e,t,n);case E:return Se(n)}return n})),m=(e,t,...n)=>d(l(e,te(t),...n)),k={[v]:(e,t,n)=>m(v,e,f(t),n.map(f)),[T]:(e,t)=>m(T,e,t.map(f)),[S]:(e,t,n)=>{const{get:r,set:s,value:o}=n;return typeof r===y&&(n.get=f(r)),typeof s===y&&(n.set=f(s)),typeof o===y&&(n.value=f(o)),m(S,e,f(t),n)},[x]:(e,t)=>m(x,e,f(t)),[j]:e=>m(j,e),[A]:(e,t)=>t===s?e:m(A,e,f(t)),[O]:(e,t)=>{const n=m(O,e,f(t));return n&&ke(n,d)},[R]:(e,t)=>t===s||m(R,e,f(t)),[P]:e=>m(P,e),[N]:e=>m(N,e).map(d),[I]:e=>m(I,e),[$]:(e,t,n)=>m($,e,f(t),f(n)),[M]:(e,t)=>m(M,e,f(t))};o[i]=(e,t,s,o)=>{switch(e){case v:return d(t).apply(d(s),o.map(d));case F:{const e=d(t);n.delete(r.get(e)),r.delete(e)}}};const H=new Proxy(re(_,null),k);return{[e.toLowerCase()]:H,[`is${e}Proxy`]:e=>typeof e===_&&!!e&&s in e,proxy:o}}})(\"Window\"),je=typeof Worker===y?Worker:class{};const Re=new WeakMap,Pe=(e,...t)=>{const n=Z(e,...t);if(!Re.has(n)){const r=e instanceof je?Ae:Oe;Re.set(n,r.call(t.at(0),n,h,d))}return Re.get(n)};Pe.transfer=Z.transfer;const Ne={object(...e){return this.string(function(e){for(var t=e[0],n=1,r=arguments.length;n<r;n++)t+=arguments[n]+e[n];return t}(...e))},string(e){for(const t of e.split(/[\\r\\n]+/))if(t.trim().length){/^(\\s+)/.test(t)&&(e=e.replace(new RegExp(\"^\"+RegExp.$1,\"gm\"),\"\"));break}return e}};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 Ie=e=>e.arrayBuffer(),$e=e=>e.json(),Me=e=>e.text(),Fe=new WeakMap,He=e=>{const t=e||console,n={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 Fe.set(t,n),t}}},We=({FS:e,PATH:t,PATH_FS:n},r,s)=>{const o=n.resolve(r);return e.mkdirTree(t.dirname(o)),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},Ce=e=>{const t=e.split(\"/\");return t.pop(),t.join(\"/\")},De=(e,t)=>{const n=[];for(const r of t.split(\"/\"))\".\"!==r&&(n.push(r),r&&e.mkdir(n.join(\"/\")))},Le=(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(/^\\/+/,\"/\")},Be=e=>{const t=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,\"\"))).filter((e=>\"\"!==e&&\".\"!==e)).join(\"/\");return e[0].startsWith(\"/\")?`/${t}`:t},Ue=(e,t)=>fetch(at(t,Je.get(e))),Je=new WeakMap,qe=(e,t,n)=>st((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(Ze(r))return r.map((n=>({url:Be([e,n]),path:Be([t,n])})));const s=n||e.slice(1+e.lastIndexOf(\"/\"));return[{url:e,path:Be([t,s])}]}))})(n).map((({url:r,path:s})=>Ue(n,r).then(Ie).then((n=>e.writeFile(t,s,n)))))),Ge=(e,t)=>t.endsWith(\"/\")?`${t}${e.split(\"/\").pop()}`:t,Ke=(e,t)=>e.replace(/\\{.+?\\}/g,(e=>{if(!t.has(e))throw new SyntaxError(`Invalid template: ${e}`);return t.get(e)})),Ye=(e,t,n)=>st((e=>{const t=new Map,n=new Set,r=[];for(const[s,o]of rt(e))if(/^\\{.+\\}$/.test(s)){if(t.has(s))throw new SyntaxError(`Duplicated template: ${s}`);t.set(s,Ke(o,t))}else{const e=Ke(s,t),a=Ge(e,Ke(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:r,path:s})=>Ue(n,r).then(Ie).then((n=>e.writeFile(t,s,n)))))),ze=typeof document===k,Xe=({main:e,worker:t})=>{const n=[];if(t&&ze)for(let[e,r]of rt(t))e=at(e,Je.get(t)),n.push(ht(e,r));if(e&&!ze)for(let[t,r]of rt(e))t=at(t,Je.get(e)),gt(t)?dt(t):n.push(ht(t,r));return st(n)},Ve=(e,...t)=>Ne[typeof e](e,...t),{isArray:Ze}=Array,{assign:Qe,create:et,defineProperties:tt,defineProperty:nt,entries:rt}=Object,{all:st,resolve:ot}=new Proxy(Promise,{get:(e,t)=>e[t].bind(e)}),at=(e,t=location.href)=>new URL(e,t.replace(/^blob:/,\"\")).href,it=(e,t,n,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${t}:${n}`,{bubbles:!0,detail:{worker:r}}))},ct=e=>Function(`'use strict';return (${e})`)(),lt=Symbol.for(\"polyscript.js_modules\"),ut=new Map;nt(globalThis,lt,{value:ut}),new Proxy(ut,{get:(e,t)=>e.get(t),has:(e,t)=>e.has(t),ownKeys:e=>[...e.keys()]});const pt=(e,t)=>!t.startsWith(\"_\"),ft=(e,t)=>new Proxy(e,{has:pt,get:(e,n)=>e[t][n]}),ht=(e,t)=>import(e).then((e=>{ut.set(t,{...e})})),dt=e=>new Promise(((t,n)=>{document.querySelector(`link[href=\"${e}\"]`)&&t(),document.head.append(Qe(document.createElement(\"link\"),{rel:\"stylesheet\",href:e,onload:t,onerror:n}))})),gt=e=>/\\.css/i.test(new URL(e).pathname),yt=(e,t)=>e.has(t),mt=e=>[...e.keys()];var wt=(e,t,n)=>{let r=globalThis[lt],s=\"\";if(n){s=Je.get(n);for(let[e,t]of rt(n)){let n=r.get(t);n&&!Ze(n)||(r.set(t,n||(n=[])),n.push(e))}}return((e,t,n,r)=>new Proxy(e,{has:yt,ownKeys:mt,get:(e,s)=>{let o=e.get(s);if(Ze(o)){let a=o;o=null;for(let e of a)e=at(e,r),gt(e)?n.importCSS(e):(n.importJS(e,s),o=t[lt].get(s));e.set(s,o)}return o}}))(r,e,t,s)};const _t=(e,t,n)=>{e.registerJsModule(t,n)},bt=(e,t,...n)=>{try{return e.runPython(Ve(t),...n)}catch(t){Fe.get(e).stderr(t)}},Et=async(e,t,...n)=>{try{return await e.runPythonAsync(Ve(t),...n)}catch(t){Fe.get(e).stderr(t)}},kt=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){Fe.get(e).stderr(t)}};var vt=(new TextEncoder).encode('from uio import StringIO\\nimport sys\\n\\nclass Response:\\n def __init__(self, f):\\n self.raw = f\\n self.encoding = \"utf-8\"\\n self._cached = None\\n\\n def close(self):\\n if self.raw:\\n self.raw.close()\\n self.raw = None\\n self._cached = None\\n\\n @property\\n def content(self):\\n if self._cached is None:\\n try:\\n self._cached = self.raw.read()\\n finally:\\n self.raw.close()\\n self.raw = None\\n return self._cached\\n\\n @property\\n def text(self):\\n return str(self.content, self.encoding)\\n\\n def json(self):\\n import ujson\\n\\n return ujson.loads(self.content)\\n\\n\\n# TODO try to support streaming xhr requests, a-la pyodide-http\\nHEADERS_TO_IGNORE = (\"user-agent\",)\\n\\n\\ntry:\\n import js\\nexcept Exception as err:\\n raise OSError(\"This version of urequests can only be used in the browser\")\\n\\n# TODO try to support streaming xhr requests, a-la pyodide-http\\n\\nHEADERS_TO_IGNORE = (\"user-agent\",)\\n\\n\\ndef request(\\n method,\\n url,\\n data=None,\\n json=None,\\n headers={},\\n stream=None,\\n auth=None,\\n timeout=None,\\n parse_headers=True,\\n):\\n from js import XMLHttpRequest\\n\\n xhr = XMLHttpRequest.new()\\n xhr.withCredentials = False\\n\\n if auth is not None:\\n import ubinascii\\n\\n username, password = auth\\n xhr.open(method, url, False, username, password)\\n else:\\n xhr.open(method, url, False)\\n\\n for name, value in headers.items():\\n if name.lower() not in HEADERS_TO_IGNORE:\\n xhr.setRequestHeader(name, value)\\n\\n if timeout:\\n xhr.timeout = int(timeout * 1000)\\n\\n if json is not None:\\n assert data is None\\n import ujson\\n\\n data = ujson.dumps(json)\\n # s.write(b\"Content-Type: application/json\\\\r\\\\n\")\\n xhr.setRequestHeader(\"Content-Type\", \"application/json\")\\n\\n xhr.send(data)\\n\\n # Emulates the construction process in the original urequests\\n resp = Response(StringIO(xhr.responseText))\\n resp.status_code = xhr.status\\n resp.reason = xhr.statusText\\n resp.headers = xhr.getAllResponseHeaders()\\n\\n return resp\\n\\n\\n# Other methods - head, post, put, patch, delete - are not used by\\n# mip and therefore not included\\n\\n\\ndef get(url, **kw):\\n return request(\"GET\", url, **kw)\\n\\n\\n# Content below this line is from the Micropython MIP package and is covered\\n# by the applicable MIT license:\\n# \\n# THE SOFTWARE IS PROVIDED βAS ISβ, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \\n# DEALINGS IN THE SOFTWARE.\\n\\n# MicroPython package installer\\n# MIT license; Copyright (c) 2022 Jim Mussared\\n\\n\\n_PACKAGE_INDEX = const(\"https://micropython.org/pi/v2\")\\n_CHUNK_SIZE = 128\\n\\n\\n# This implements os.makedirs(os.dirname(path))\\ndef _ensure_path_exists(path):\\n import os\\n\\n split = path.split(\"/\")\\n\\n # Handle paths starting with \"/\".\\n if not split[0]:\\n split.pop(0)\\n split[0] = \"/\" + split[0]\\n\\n prefix = \"\"\\n for i in range(len(split) - 1):\\n prefix += split[i]\\n try:\\n os.stat(prefix)\\n except:\\n os.mkdir(prefix)\\n prefix += \"/\"\\n\\n\\n# Copy from src (stream) to dest (function-taking-bytes)\\ndef _chunk(src, dest):\\n buf = memoryview(bytearray(_CHUNK_SIZE))\\n while True:\\n n = src.readinto(buf)\\n if n == 0:\\n break\\n dest(buf if n == _CHUNK_SIZE else buf[:n])\\n\\n\\n# Check if the specified path exists and matches the hash.\\ndef _check_exists(path, short_hash):\\n import os\\n\\n try:\\n import binascii\\n import hashlib\\n\\n with open(path, \"rb\") as f:\\n hs256 = hashlib.sha256()\\n _chunk(f, hs256.update)\\n existing_hash = str(binascii.hexlify(hs256.digest())[: len(short_hash)], \"utf-8\")\\n return existing_hash == short_hash\\n except:\\n return False\\n\\n\\ndef _rewrite_url(url, branch=None):\\n if not branch:\\n branch = \"HEAD\"\\n if url.startswith(\"github:\"):\\n url = url[7:].split(\"/\")\\n url = (\\n \"https://raw.githubusercontent.com/\"\\n + url[0]\\n + \"/\"\\n + url[1]\\n + \"/\"\\n + branch\\n + \"/\"\\n + \"/\".join(url[2:])\\n )\\n return url\\n\\n\\ndef _download_file(url, dest):\\n response = get(url)\\n try:\\n if response.status_code != 200:\\n print(\"Error\", response.status_code, \"requesting\", url)\\n return False\\n\\n print(\"Copying:\", dest)\\n _ensure_path_exists(dest)\\n with open(dest, \"wb\") as f:\\n _chunk(response.raw, f.write)\\n\\n return True\\n finally:\\n response.close()\\n\\n\\ndef _install_json(package_json_url, index, target, version, mpy):\\n response = get(_rewrite_url(package_json_url, version))\\n try:\\n if response.status_code != 200:\\n print(\"Package not found:\", package_json_url)\\n return False\\n\\n package_json = response.json()\\n finally:\\n response.close()\\n for target_path, short_hash in package_json.get(\"hashes\", ()):\\n fs_target_path = target + \"/\" + target_path\\n if _check_exists(fs_target_path, short_hash):\\n print(\"Exists:\", fs_target_path)\\n else:\\n file_url = \"{}/file/{}/{}\".format(index, short_hash[:2], short_hash)\\n if not _download_file(file_url, fs_target_path):\\n print(\"File not found: {} {}\".format(target_path, short_hash))\\n return False\\n for target_path, url in package_json.get(\"urls\", ()):\\n fs_target_path = target + \"/\" + target_path\\n if not _download_file(_rewrite_url(url, version), fs_target_path):\\n print(\"File not found: {} {}\".format(target_path, url))\\n return False\\n for dep, dep_version in package_json.get(\"deps\", ()):\\n if not _install_package(dep, index, target, dep_version, mpy):\\n return False\\n return True\\n\\n\\ndef _install_package(package, index, target, version, mpy):\\n if (\\n package.startswith(\"http://\")\\n or package.startswith(\"https://\")\\n or package.startswith(\"github:\")\\n ):\\n if package.endswith(\".py\") or package.endswith(\".mpy\"):\\n print(\"Downloading {} to {}\".format(package, target))\\n return _download_file(\\n _rewrite_url(package, version), target + \"/\" + package.rsplit(\"/\")[-1]\\n )\\n else:\\n if not package.endswith(\".json\"):\\n if not package.endswith(\"/\"):\\n package += \"/\"\\n package += \"package.json\"\\n print(\"Installing {} to {}\".format(package, target))\\n else:\\n if not version:\\n version = \"latest\"\\n print(\"Installing {} ({}) from {} to {}\".format(package, version, index, target))\\n\\n mpy_version = (\\n sys.implementation._mpy & 0xFF if mpy and hasattr(sys.implementation, \"_mpy\") else \"py\"\\n )\\n\\n package = \"{}/package/{}/{}/{}.json\".format(index, mpy_version, package, version)\\n\\n return _install_json(package, index, target, version, mpy)\\n\\n\\ndef install(package, index=None, target=None, version=None, mpy=True):\\n if not target:\\n for p in sys.path:\\n if p.endswith(\"/lib\"):\\n target = p\\n break\\n else:\\n print(\"Unable to find lib dir in sys.path\")\\n return\\n\\n if not index:\\n index = _PACKAGE_INDEX\\n\\n if _install_package(package, index.rstrip(\"/\"), target, version, mpy):\\n print(\"Done\")\\n else:\\n print(\"Package may be partially installed\")\\n');var Tt={type:\"micropython\",module:(e=\"1.21.0-279\")=>`https://cdn.jsdelivr.net/npm/@micropython/micropython-webassembly-pyscript@${e}/micropython.mjs`,async engine({loadMicroPython:e},t,n){const{stderr:r,stdout:s,get:o}=He();n=n.replace(/\\.m?js$/,\".wasm\");const a=await o(e({stderr:r,stdout:s,url:n}));if(t.files&&await Ye(this,a,t.files),t.fetch&&await qe(this,a,t.fetch),t.js_modules&&await Xe(t.js_modules),this.writeFile(a,\"./mip.py\",vt),t.packages){const e=a.pyimport(\"mip\");for(const n of t.packages)e.install(n)}return a},registerJSModule:_t,run:bt,runAsync:Et,runEvent:kt,transform:(e,t)=>t instanceof e.PyProxy?e.PyProxy.toJs(t):t,writeFile:({FS:e,_module:{PATH:t,PATH_FS:n}},r,s)=>We({FS:e,PATH:t,PATH_FS:n},r,s)};const St={dict_converter:Object.fromEntries};var xt={type:\"pyodide\",module:(e=\"0.24.1\")=>`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},t,n){const{stderr:r,stdout:s,get:o}=He(),a=n.slice(0,n.lastIndexOf(\"/\")),i=await o(e({stderr:r,stdout:s,indexURL:a}));if(t.files&&await Ye(this,i,t.files),t.fetch&&await qe(this,i,t.fetch),t.js_modules&&await Xe(t.js_modules),t.packages){await i.loadPackage(\"micropip\");const e=await i.pyimport(\"micropip\");await e.install(t.packages,{keep_going:!0}),e.destroy()}return i},registerJSModule:_t,run:bt,runAsync:Et,runEvent:kt,transform:(e,t)=>t instanceof e.ffi.PyProxy?t.toJs(St):t,writeFile:({FS:e,PATH:t,_module:{PATH_FS:n}},r,s)=>We({FS:e,PATH:t,PATH_FS:n},r,s)};const At=\"ruby-wasm-wasi\",Ot=At.replace(/\\W+/g,\"_\");var jt={type:At,experimental:!0,module:(e=\"2.2.0\")=>`https://cdn.jsdelivr.net/npm/ruby-3_2-wasm-wasi@${e}/dist/browser.esm.js`,async engine({DefaultRubyVM:e},t,n){const r=await fetch(`${n.slice(0,n.lastIndexOf(\"/\"))}/ruby.wasm`),s=await WebAssembly.compile(await r.arrayBuffer()),{vm:o}=await e(s);return t.files&&await Ye(this,o,t.files),t.fetch&&await qe(this,o,t.fetch),t.js_modules&&await Xe(t.js_modules),o},registerJSModule(e,t,n){t=t.replace(/\\W+/g,\"__\");const r=`__module_${Ot}_${t}`;globalThis[r]=n,this.run(e,`require \"js\";$${t}=JS.global[:${r}]`),delete globalThis[r]},run:(e,t,...n)=>e.eval(Ve(t),...n),runAsync:(e,t,...n)=>e.evalAsync(Ve(t),...n),async runEvent(e,t,n){if(/^xworker\\.(on\\w+)$/.test(t)){const{$1:t}=RegExp,r=`__module_${Ot}_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 ${At}`)}};var Rt={type:\"wasmoon\",module:(e=\"1.16.0\")=>`https://cdn.jsdelivr.net/npm/wasmoon@${e}/+esm`,async engine({LuaFactory:e,LuaLibraries:t},n){const{stderr:r,stdout:s,get:o}=He(),a=await o((new e).createEngine());return a.global.getTable(t.Base,(e=>{a.global.setField(e,\"print\",s),a.global.setField(e,\"printErr\",r)})),n.files&&await Ye(this,a,n.files),n.fetch&&await qe(this,a,n.fetch),n.js_modules&&await Xe(n.js_modules),a},registerJSModule:(e,t,n)=>{e.global.set(t,n)},run:(e,t,...n)=>{try{return e.doStringSync(Ve(t),...n)}catch(t){Fe.get(e).stderr(t)}},runAsync:async(e,t,...n)=>{try{return await e.doString(Ve(t),...n)}catch(t){Fe.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){Fe.get(e).stderr(t)}},transform:(e,t)=>t,writeFile:({cmodule:{module:{FS:e}}},t,n)=>((e,t,n)=>(De(e,Ce(t)),t=Le(e,t),e.writeFile(t,new Uint8Array(n),{canOwn:!0})))(e,t,n)};const Pt=new Map,Nt=new Map,It=new Proxy(new Map,{get(e,t){if(!e.has(t)){const[n,...r]=t.split(\"@\"),s=Pt.get(n),o=/^(?:\\.?\\.?\\/|https?:\\/\\/)/i.test(r)?r.join(\"@\"):s.module(...r);e.set(t,{url:o,module:import(o),engine:s.engine.bind(s)})}const{url:n,module:r,engine:s}=e.get(t);return(e,o)=>r.then((r=>{Nt.set(t,e);for(const t of[\"files\",\"fetch\"]){const n=e?.[t];n&&Je.set(n,o)}for(const t of[\"main\",\"worker\"]){const n=e?.js_modules?.[t];n&&Je.set(n,o)}return s(r,e,n)}))}}),$t=e=>{for(const t of[].concat(e.type))Pt.set(t,e)};for(const e of[Tt,xt,jt,Rt])$t(e);const Mt=async e=>(await import(\"https://cdn.jsdelivr.net/npm/basic-toml@0.3.1/es.js\")).parse(e),Ft=e=>{try{return JSON.parse(e)}catch(t){return Mt(e)}},Ht=(e,t,n={})=>{if(t){const[e,r]=(e=>{let t=typeof e;return\"string\"===t&&/\\.(json|toml|txt)$/.test(e)?t=RegExp.$1:e=\"./config.txt\",[at(e),t]})(t);\"json\"===r?n=fetch(e).then($e):\"toml\"===r?n=fetch(e).then(Me).then(Mt):\"string\"===r?n=Ft(t):\"object\"===r&&t?n=t:\"txt\"===r&&\"string\"==typeof n&&(n=Ft(n)),t=e}return ot(n).then((n=>It[e](n,t)))},Wt=\"BeforeRun\",Ct=\"AfterRun\",Dt=[`code${Wt}`,`code${Wt}Async`,`code${Ct}`,`code${Ct}Async`],Lt=[\"onWorker\",\"onReady\",`on${Wt}`,`on${Wt}Async`,`on${Ct}`,`on${Ct}Async`];function Bt(e,t){const{run:n,runAsync:r}=Pt.get(this.type);return{...e,run:n.bind(this,t),runAsync:r.bind(this,t)}}const Ut=(e,t,n,r,s,o)=>{if(s||o){const a=Bt.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}}};try{new SharedArrayBuffer(4)}catch(e){throw new Error([\"Unable to use SharedArrayBuffer due insecure environment.\",\"Please read requirements in MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements\"].join(\"\\n\"))}let Jt,qt,Gt;const Kt=(e,t)=>{addEventListener(e,t||(async t=>{try{await Jt,qt(`xworker.on${e}`,t)}catch(e){postMessage(e)}}),!!t&&{once:!0})},{parse:Yt,stringify:zt}=p,{proxy:Xt,window:Vt,isWindowProxy:Zt}=Pe(self,{parse:Yt,stringify:zt,transform:e=>Gt?Gt(e):e}),Qt={sync:Xt,window:Vt,isWindowProxy:Zt,onmessage:console.info,onerror:console.error,onmessageerror:console.warn,postMessage:postMessage.bind(self)};Kt(\"message\",(({data:{options:e,config:t,code:n,hooks:r}})=>{Jt=(async()=>{try{const{id:s,tag:o,type:a,custom:i,version:c,config:l,async:u}=e,p=((e,t=\"\")=>`${e}@${t}`.replace(/@$/,\"\"))(a,c),f=await Ht(p,t,l),h=Nt.get(p).js_modules?.main,d=et(Pt.get(a)),g=((e,t,n,r)=>({type:t,config:n,interpreter:r,io:Fe.get(r),run:(t,...n)=>e.run(r,t,...n),runAsync:(t,...n)=>e.runAsync(r,t,...n),runEvent:(...t)=>e.runEvent(r,...t)}))(d,i||a,l,f);let y=\"run\";if(u&&(y+=\"Async\"),r){const e=((e,t)=>(n,r)=>{const s=e[t].bind(e);e[t]=(e,t,...o)=>s(e,`${r?n:t}\\n${r?t:n}`,...o)})(d,y);let t,n,s=\"\",o=\"\";for(const e of Dt){const t=r[e];if(t){const n=e.endsWith(\"Async\");(n&&u||!n&&!u)&&(e.startsWith(\"codeBefore\")?s=t:o=t)}}o&&e(o,!1),s&&e(s,!0);for(const e of Lt.slice(2)){const s=r[e];if(s){const r=e.endsWith(\"Async\");if(r&&u||!r&&!u){const r=ct(s);e.startsWith(\"onBefore\")?t=r:n=r}}}Ut(d,g,Qt,u,t,n)}const{CustomEvent:m,document:w}=Vt,_=s&&w.getElementById(s)||null,b=e=>it(_,i||a,e,!0,m),E=wt(Vt,Xt,h);let k=\"\";return((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}`,ft(r,e));t.registerJSModule(n,s,r)})(a,d,f,E),d.registerJSModule(f,\"polyscript\",{xworker:Qt,currentScript:_,js_modules:E,get target(){return!k&&_&&(\"SCRIPT\"===o?_.after(Qe(w.createElement(`script-${i||a}`),{id:k=`${s}-target`})):(k=s,_.replaceChildren(),_.style.display=\"block\")),k}}),qt=d.runEvent.bind(d,f),Gt=d.transform.bind(d,f),_&&b(\"ready\"),r?.onReady&&ct(r?.onReady).call(d,Bt.call(d,g,f),Qt),await d[y](f,n),_&&b(\"done\"),f}catch(e){postMessage(e)}})(),Kt(\"error\"),Kt(\"message\"),Kt(\"messageerror\")}));\n"],{type:'application/javascript'})),{type:'module'}); |
@@ -6,5 +6,5 @@ import { interpreter } from './interpreters.js'; | ||
// REQUIRES INTEGRATION TEST | ||
/* c8 ignore start */ | ||
export const getConfigURLAndType = config => { | ||
// REQUIRES INTEGRATION TEST | ||
/* c8 ignore start */ | ||
let type = typeof config; | ||
@@ -16,5 +16,13 @@ if (type === 'string' && /\.(json|toml|txt)$/.test(config)) | ||
return [absoluteURL(config), type]; | ||
/* c8 ignore stop */ | ||
}; | ||
const parseString = config => { | ||
try { | ||
return JSON.parse(config); | ||
} catch (_) { | ||
return parse(config); | ||
} | ||
}; | ||
/* c8 ignore stop */ | ||
/** | ||
@@ -40,9 +48,7 @@ * Parse a generic config if it came from an attribute either as URL | ||
} else if (type === 'string') { | ||
try { | ||
options = JSON.parse(config); | ||
} catch (_) { | ||
options = parse(config); | ||
} | ||
options = parseString(config); | ||
} else if (type === 'object' && config) { | ||
options = config; | ||
} else if (type === 'txt' && typeof options === 'string') { | ||
options = parseString(options); | ||
} | ||
@@ -49,0 +55,0 @@ config = absolute; |
/* c8 ignore next */ | ||
export default () => new Worker(URL.createObjectURL(new Blob(["const e=\"object\"==typeof self?self:globalThis,t=t=>((t,n)=>{const r=(e,n)=>(t.set(n,e),e),s=o=>{if(t.has(o))return t.get(o);const[a,i]=n[o];switch(a){case 0:case-1:return r(i,o);case 1:{const e=r([],o);for(const t of i)e.push(s(t));return e}case 2:{const e=r({},o);for(const[t,n]of i)e[s(t)]=s(n);return e}case 3:return r(new Date(i),o);case 4:{const{source:e,flags:t}=i;return r(new RegExp(e,t),o)}case 5:{const e=r(new Map,o);for(const[t,n]of i)e.set(s(t),s(n));return e}case 6:{const e=r(new Set,o);for(const t of i)e.add(s(t));return e}case 7:{const{name:t,message:n}=i;return r(new e[t](n),o)}case 8:return r(BigInt(i),o);case\"BigInt\":return r(Object(BigInt(i)),o)}return r(new e[a](i),o)};return s})(new Map,t)(0),n=\"\",{toString:r}={},{keys:s}=Object,o=e=>{const t=typeof e;if(\"object\"!==t||!e)return[0,t];const s=r.call(e).slice(8,-1);switch(s){case\"Array\":return[1,n];case\"Object\":return[2,n];case\"Date\":return[3,n];case\"RegExp\":return[4,n];case\"Map\":return[5,n];case\"Set\":return[6,n]}return s.includes(\"Array\")?[1,s]:s.includes(\"Error\")?[7,s]:[2,s]},a=([e,t])=>0===e&&(\"function\"===t||\"symbol\"===t),i=(e,{json:t,lossy:n}={})=>{const r=[];return((e,t,n,r)=>{const i=(e,t)=>{const s=r.push(e)-1;return n.set(t,s),s},c=r=>{if(n.has(r))return n.get(r);let[l,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=\"ac6c1995-0675-46af-a99f-7fa298fa4e6d\",h=\"M\"+f,d=\"T\"+f,g=\"array\",y=\"function\",m=\"null\",w=\"number\",_=\"object\",b=\"string\",E=\"symbol\",k=\"undefined\",v=\"apply\",T=\"construct\",S=\"defineProperty\",x=\"deleteProperty\",A=\"get\",O=\"getOwnPropertyDescriptor\",j=\"getPrototypeOf\",R=\"has\",P=\"isExtensible\",N=\"ownKeys\",I=\"preventExtensions\",$=\"set\",M=\"setPrototypeOf\",F=\"delete\";var H=e=>({value:new Promise((t=>{let n=new Worker(\"data:application/javascript,onmessage%3D(%7Bdata%3Ab%7D)%3D%3E(Atomics.wait(b%2C0)%2CpostMessage(0))\");n.onmessage=t,n.postMessage(e)}))})\n/*! (c) Andrea Giammarchi - ISC */;const{Int32Array:W,Map:C,SharedArrayBuffer:D,Uint16Array:L}=globalThis,{BYTES_PER_ELEMENT:B}=W,{BYTES_PER_ELEMENT:U}=L,{isArray:J}=Array,{notify:q,wait:G,waitAsync:K}=Atomics,Y=new WeakSet,z=new WeakMap,X={value:{then:e=>e()}};let V=0;const Z=(e,{parse:t=JSON.parse,stringify:n=JSON.stringify,transform:r,interrupt:s}=JSON)=>{if(!z.has(e)){const o=(t,...n)=>e.postMessage({[f]:n},{transfer:t}),a=typeof s===y?s:s?.handler,i=s?.delay||42,c=new TextDecoder(\"utf-16\"),l=(e,t)=>e?(K||H)(t,0):(a?((e,t,n)=>{for(;\"timed-out\"===G(e,0,0,t);)n()})(t,i,a):G(t,0),X);let u=!1;z.set(e,new Proxy(new C,{[R]:(e,t)=>\"string\"==typeof t&&!t.startsWith(\"_\"),[A]:(n,s)=>\"then\"===s?null:(...n)=>{const a=V++;let i=new W(new D(2*B)),p=[];Y.has(n.at(-1)||p)&&Y.delete(p=n.pop()),o(p,a,i,s,r?n.map(r):n);const f=e!==globalThis;let h=0;return u&&f&&(h=setTimeout(console.warn,1e3,`ππ - Possible deadlock if proxy.${s}(...args) is awaited`)),l(f,i).value.then((()=>{clearTimeout(h);const e=i[1];if(!e)return;const n=U*e;return i=new W(new D(n+n%B)),o([],a,i),l(f,i).value.then((()=>t(c.decode(new L(i.buffer).slice(0,e)))))}))},[$](t,s,o){const a=typeof o;if(a!==y)throw new Error(`Unable to assign ${s} as ${a}`);if(!t.size){const s=new C;e.addEventListener(\"message\",(async e=>{const o=e.data?.[f];if(J(o)){e.stopImmediatePropagation();const[a,i,...c]=o;let l;if(c.length){const[e,o]=c;if(t.has(e)){u=!0;try{const c=await t.get(e)(...o);if(void 0!==c){const e=n(r?r(c):c);s.set(a,e),i[1]=e.length}}catch(e){l=e}finally{u=!1}}else l=new Error(`Unsupported action: ${e}`);i[0]=1}else{const e=s.get(a);s.delete(a);for(let t=new L(i.buffer),n=0;n<e.length;n++)t[n]=e.charCodeAt(n)}if(q(i,0),l)throw l}}))}return!!t.set(s,o)}}))}return z.get(e)};Z.transfer=(...e)=>(Y.add(e),e);const{isArray:Q}=Array,ee=(e,t)=>t,te=e=>typeof e===y?(e=>e())(e):e;function ne(){return this}const re=(e,t)=>e===g?[t]:{t:e,v:t},se=(e,t=ee)=>{let n=typeof e,r=e;return n===_&&(Q(e)?(n=g,r=e.at(0)):({t:n,v:r}=e)),t(n,r)},oe=(e,t)=>e===y?t:re(e,t),ae=(e,t=oe)=>{const n=null===e?m:typeof e;return t(n===_&&Q(e)?g:n,e)},ie=new FinalizationRegistry((([e,t,n])=>{n&&console.debug(`Held value ${String(t)} not relevant anymore`),e(t)})),ce=Object.create(null),le=(e,t,{debug:n,return:r,token:s=e}=ce)=>{const o=r||new Proxy(e,ce),a=[o,[t,e,!!n]];return!1!==s&&a.push(s),ie.register(...a),o},{defineProperty:ue,deleteProperty:pe,getOwnPropertyDescriptor:fe,getPrototypeOf:he,isExtensible:de,ownKeys:ge,preventExtensions:ye,set:me,setPrototypeOf:we}=Reflect,{assign:_e,create:be}=Object,Ee=he(Int8Array),ke=(e,t)=>{const{get:n,set:r,value:s}=e;return n&&(e.get=t(n)),r&&(e.set=t(r)),s&&(e.value=t(s)),e},ve=e=>t=>ae(t,((t,n)=>{switch(t){case m:return re(m,n);case _:if(n===globalThis)return re(t,null);case g:case y:return e(t,n);case\"boolean\":case w:case b:case k:case\"bigint\":return re(t,n);case E:{if(Te.has(n))return re(t,Te.get(n));let e=Symbol.keyFor(n);if(e)return re(t,`.${e}`)}}throw new TypeError(`Unable to handle this ${t}: ${String(n)}`)})),Te=new Map(ge(Symbol).filter((e=>typeof Symbol[e]===E)).map((e=>[Symbol[e],e]))),Se=e=>{if(e.startsWith(\".\"))return Symbol.for(e.slice(1));for(const[t,n]of Te)if(n===e)return t},xe=e=>e;var Ae=((e,t)=>{const n=t&&new WeakMap;if(t){const{addEventListener:e}=EventTarget.prototype;ue(EventTarget.prototype,\"addEventListener\",{value(t,r,...s){return s.at(0)?.invoke&&(n.has(this)||n.set(this,new Map),n.get(this).set(t,[].concat(s[0].invoke)),delete s[0].invoke),e.call(this,t,r,...s)}})}const r=t&&(e=>{const{currentTarget:t,target:r,type:s}=e;for(const o of n.get(t||r)?.get(s)||[])e[o]()});return function(n,s,o,...a){let i=0,c=this?.transform||xe;const l=new Map,u=new Map,{[o]:p}=n,f=a.length?_e(be(globalThis),...a):globalThis,h=ve(((e,t)=>{if(!l.has(t)){let n;for(;u.has(n=i++););l.set(t,n),u.set(n,e===y?t:c(t))}return re(e,l.get(t))})),d=e=>{p(F,re(b,e))},m=(e,n)=>{switch(e){case _:if(null==n)return f;case g:if(typeof n===w)return u.get(n);if(!(n instanceof Ee))for(const e in n)n[e]=H(n[e]);return n;case y:if(typeof n===b){if(!u.has(n)){const e=function(...e){return t&&e.at(0)instanceof Event&&r(...e),p(v,re(y,n),h(this),e.map(h))};return u.set(n,new WeakRef(e)),le(n,d,{return:e,token:!1})}return u.get(n).deref()}return u.get(n);case E:return Se(n)}return n},H=e=>se(e,m),W={[v]:(e,t,n)=>h(e.apply(t,n)),[T]:(e,t)=>h(new e(...t)),[S]:(e,t,n)=>h(ue(e,t,n)),[x]:(e,t)=>h(pe(e,t)),[j]:e=>h(he(e)),[A]:(e,t)=>h(e[t]),[O]:(e,t)=>{const n=fe(e,t);return n?re(_,ke(n,h)):re(k,n)},[R]:(e,t)=>h(t in e),[P]:e=>h(de(e)),[N]:e=>re(g,ge(e).map(h)),[I]:e=>h(ye(e)),[$]:(e,t,n)=>h(me(e,t,n)),[M]:(e,t)=>h(we(e,t)),[F](e){l.delete(u.get(e)),u.delete(e)}};return n[s]=(e,t,...n)=>{switch(e){case v:n[0]=H(n[0]),n[1]=n[1].map(H);break;case T:n[0]=n[0].map(H);break;case S:{const[e,t]=n;n[0]=H(e);const{get:r,set:s,value:o}=t;r&&(t.get=H(r)),s&&(t.set=H(s)),o&&(t.value=H(o));break}default:n=n.map(H)}return W[e](H(t),...n)},{proxy:n,[e.toLowerCase()]:f,[`is${e}Proxy`]:()=>!1}}})(\"Window\",!0),Oe=(e=>{let t=0;const n=new Map,r=new Map,s=Symbol();return function(o,a,i){const c=this?.transform||xe,{[a]:l}=o,u=new Map,p=e=>{u.delete(e),l(F,f(e))},f=ve(((e,o)=>{if(s in o)return te(o[s]);if(e===y){if(o=c(o),!r.has(o)){let e;for(;r.has(e=String(t++)););n.set(o,e),r.set(e,o)}return re(e,n.get(o))}if(!(o instanceof Ee)){o=c(o);for(const e in o)o[e]=f(o[e])}return re(e,o)})),h=(e,t,n)=>{if(!u.has(n)){const r=t===y?(e=>ne.bind(e))(e):e,s=new Proxy(r,k);return u.set(n,new WeakRef(s)),le(n,p,{return:s,token:!1})}return u.get(n).deref()},d=e=>se(e,((t,n)=>{switch(t){case _:if(null===n)return globalThis;case g:return typeof n===w?h(e,t,n):n;case y:return typeof n===b?r.get(n):h(e,t,n);case E:return Se(n)}return n})),m=(e,t,...n)=>d(l(e,te(t),...n)),k={[v]:(e,t,n)=>m(v,e,f(t),n.map(f)),[T]:(e,t)=>m(T,e,t.map(f)),[S]:(e,t,n)=>{const{get:r,set:s,value:o}=n;return typeof r===y&&(n.get=f(r)),typeof s===y&&(n.set=f(s)),typeof o===y&&(n.value=f(o)),m(S,e,f(t),n)},[x]:(e,t)=>m(x,e,f(t)),[j]:e=>m(j,e),[A]:(e,t)=>t===s?e:m(A,e,f(t)),[O]:(e,t)=>{const n=m(O,e,f(t));return n&&ke(n,d)},[R]:(e,t)=>t===s||m(R,e,f(t)),[P]:e=>m(P,e),[N]:e=>m(N,e).map(d),[I]:e=>m(I,e),[$]:(e,t,n)=>m($,e,f(t),f(n)),[M]:(e,t)=>m(M,e,f(t))};o[i]=(e,t,s,o)=>{switch(e){case v:return d(t).apply(d(s),o.map(d));case F:{const e=d(t);n.delete(r.get(e)),r.delete(e)}}};const H=new Proxy(re(_,null),k);return{[e.toLowerCase()]:H,[`is${e}Proxy`]:e=>typeof e===_&&!!e&&s in e,proxy:o}}})(\"Window\"),je=typeof Worker===y?Worker:class{};const Re=new WeakMap,Pe=(e,...t)=>{const n=Z(e,...t);if(!Re.has(n)){const r=e instanceof je?Ae:Oe;Re.set(n,r.call(t.at(0),n,h,d))}return Re.get(n)};Pe.transfer=Z.transfer;const Ne={object(...e){return this.string(function(e){for(var t=e[0],n=1,r=arguments.length;n<r;n++)t+=arguments[n]+e[n];return t}(...e))},string(e){for(const t of e.split(/[\\r\\n]+/))if(t.trim().length){/^(\\s+)/.test(t)&&(e=e.replace(new RegExp(\"^\"+RegExp.$1,\"gm\"),\"\"));break}return e}};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 Ie=e=>e.arrayBuffer(),$e=e=>e.json(),Me=e=>e.text(),Fe=new WeakMap,He=e=>{const t=e||console,n={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 Fe.set(t,n),t}}},We=({FS:e,PATH:t,PATH_FS:n},r,s)=>{const o=n.resolve(r);return e.mkdirTree(t.dirname(o)),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},Ce=e=>{const t=e.split(\"/\");return t.pop(),t.join(\"/\")},De=(e,t)=>{const n=[];for(const r of t.split(\"/\"))\".\"!==r&&(n.push(r),r&&e.mkdir(n.join(\"/\")))},Le=(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(/^\\/+/,\"/\")},Be=e=>{const t=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,\"\"))).filter((e=>\"\"!==e&&\".\"!==e)).join(\"/\");return e[0].startsWith(\"/\")?`/${t}`:t},Ue=(e,t)=>fetch(at(t,Je.get(e))),Je=new WeakMap,qe=(e,t,n)=>st((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(Ze(r))return r.map((n=>({url:Be([e,n]),path:Be([t,n])})));const s=n||e.slice(1+e.lastIndexOf(\"/\"));return[{url:e,path:Be([t,s])}]}))})(n).map((({url:r,path:s})=>Ue(n,r).then(Ie).then((n=>e.writeFile(t,s,n)))))),Ge=(e,t)=>t.endsWith(\"/\")?`${t}${e.split(\"/\").pop()}`:t,Ke=(e,t)=>e.replace(/\\{.+?\\}/g,(e=>{if(!t.has(e))throw new SyntaxError(`Invalid template: ${e}`);return t.get(e)})),Ye=(e,t,n)=>st((e=>{const t=new Map,n=new Set,r=[];for(const[s,o]of rt(e))if(/^\\{.+\\}$/.test(s)){if(t.has(s))throw new SyntaxError(`Duplicated template: ${s}`);t.set(s,Ke(o,t))}else{const e=Ke(s,t),a=Ge(e,Ke(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:r,path:s})=>Ue(n,r).then(Ie).then((n=>e.writeFile(t,s,n)))))),ze=typeof document===k,Xe=({main:e,worker:t})=>{const n=[];if(t&&ze)for(let[e,r]of rt(t))e=at(e,Je.get(t)),n.push(ht(e,r));if(e&&!ze)for(let[t,r]of rt(e))t=at(t,Je.get(e)),gt(t)?dt(t):n.push(ht(t,r));return st(n)},Ve=(e,...t)=>Ne[typeof e](e,...t),{isArray:Ze}=Array,{assign:Qe,create:et,defineProperties:tt,defineProperty:nt,entries:rt}=Object,{all:st,resolve:ot}=new Proxy(Promise,{get:(e,t)=>e[t].bind(e)}),at=(e,t=location.href)=>new URL(e,t.replace(/^blob:/,\"\")).href,it=(e,t,n,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${t}:${n}`,{bubbles:!0,detail:{worker:r}}))},ct=e=>Function(`'use strict';return (${e})`)(),lt=Symbol.for(\"polyscript.js_modules\"),ut=new Map;nt(globalThis,lt,{value:ut}),new Proxy(ut,{get:(e,t)=>e.get(t),has:(e,t)=>e.has(t),ownKeys:e=>[...e.keys()]});const pt=(e,t)=>!t.startsWith(\"_\"),ft=(e,t)=>new Proxy(e,{has:pt,get:(e,n)=>e[t][n]}),ht=(e,t)=>import(e).then((e=>{ut.set(t,{...e})})),dt=e=>new Promise(((t,n)=>{document.querySelector(`link[href=\"${e}\"]`)&&t(),document.head.append(Qe(document.createElement(\"link\"),{rel:\"stylesheet\",href:e,onload:t,onerror:n}))})),gt=e=>/\\.css/i.test(new URL(e).pathname),yt=(e,t)=>e.has(t),mt=e=>[...e.keys()];var wt=(e,t,n)=>{let r=globalThis[lt],s=\"\";if(n){s=Je.get(n);for(let[e,t]of rt(n)){let n=r.get(t);n&&!Ze(n)||(r.set(t,n||(n=[])),n.push(e))}}return((e,t,n,r)=>new Proxy(e,{has:yt,ownKeys:mt,get:(e,s)=>{let o=e.get(s);if(Ze(o)){let a=o;o=null;for(let e of a)e=at(e,r),gt(e)?n.importCSS(e):(n.importJS(e,s),o=t[lt].get(s));e.set(s,o)}return o}}))(r,e,t,s)};const _t=(e,t,n)=>{e.registerJsModule(t,n)},bt=(e,t,...n)=>{try{return e.runPython(Ve(t),...n)}catch(t){Fe.get(e).stderr(t)}},Et=async(e,t,...n)=>{try{return await e.runPythonAsync(Ve(t),...n)}catch(t){Fe.get(e).stderr(t)}},kt=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){Fe.get(e).stderr(t)}};var vt=(new TextEncoder).encode('from uio import StringIO\\nimport sys\\n\\nclass Response:\\n def __init__(self, f):\\n self.raw = f\\n self.encoding = \"utf-8\"\\n self._cached = None\\n\\n def close(self):\\n if self.raw:\\n self.raw.close()\\n self.raw = None\\n self._cached = None\\n\\n @property\\n def content(self):\\n if self._cached is None:\\n try:\\n self._cached = self.raw.read()\\n finally:\\n self.raw.close()\\n self.raw = None\\n return self._cached\\n\\n @property\\n def text(self):\\n return str(self.content, self.encoding)\\n\\n def json(self):\\n import ujson\\n\\n return ujson.loads(self.content)\\n\\n\\n# TODO try to support streaming xhr requests, a-la pyodide-http\\nHEADERS_TO_IGNORE = (\"user-agent\",)\\n\\n\\ntry:\\n import js\\nexcept Exception as err:\\n raise OSError(\"This version of urequests can only be used in the browser\")\\n\\n# TODO try to support streaming xhr requests, a-la pyodide-http\\n\\nHEADERS_TO_IGNORE = (\"user-agent\",)\\n\\n\\ndef request(\\n method,\\n url,\\n data=None,\\n json=None,\\n headers={},\\n stream=None,\\n auth=None,\\n timeout=None,\\n parse_headers=True,\\n):\\n from js import XMLHttpRequest\\n\\n xhr = XMLHttpRequest.new()\\n xhr.withCredentials = False\\n\\n if auth is not None:\\n import ubinascii\\n\\n username, password = auth\\n xhr.open(method, url, False, username, password)\\n else:\\n xhr.open(method, url, False)\\n\\n for name, value in headers.items():\\n if name.lower() not in HEADERS_TO_IGNORE:\\n xhr.setRequestHeader(name, value)\\n\\n if timeout:\\n xhr.timeout = int(timeout * 1000)\\n\\n if json is not None:\\n assert data is None\\n import ujson\\n\\n data = ujson.dumps(json)\\n # s.write(b\"Content-Type: application/json\\\\r\\\\n\")\\n xhr.setRequestHeader(\"Content-Type\", \"application/json\")\\n\\n xhr.send(data)\\n\\n # Emulates the construction process in the original urequests\\n resp = Response(StringIO(xhr.responseText))\\n resp.status_code = xhr.status\\n resp.reason = xhr.statusText\\n resp.headers = xhr.getAllResponseHeaders()\\n\\n return resp\\n\\n\\n# Other methods - head, post, put, patch, delete - are not used by\\n# mip and therefore not included\\n\\n\\ndef get(url, **kw):\\n return request(\"GET\", url, **kw)\\n\\n\\n# Content below this line is from the Micropython MIP package and is covered\\n# by the applicable MIT license:\\n# \\n# THE SOFTWARE IS PROVIDED βAS ISβ, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \\n# DEALINGS IN THE SOFTWARE.\\n\\n# MicroPython package installer\\n# MIT license; Copyright (c) 2022 Jim Mussared\\n\\n\\n_PACKAGE_INDEX = const(\"https://micropython.org/pi/v2\")\\n_CHUNK_SIZE = 128\\n\\n\\n# This implements os.makedirs(os.dirname(path))\\ndef _ensure_path_exists(path):\\n import os\\n\\n split = path.split(\"/\")\\n\\n # Handle paths starting with \"/\".\\n if not split[0]:\\n split.pop(0)\\n split[0] = \"/\" + split[0]\\n\\n prefix = \"\"\\n for i in range(len(split) - 1):\\n prefix += split[i]\\n try:\\n os.stat(prefix)\\n except:\\n os.mkdir(prefix)\\n prefix += \"/\"\\n\\n\\n# Copy from src (stream) to dest (function-taking-bytes)\\ndef _chunk(src, dest):\\n buf = memoryview(bytearray(_CHUNK_SIZE))\\n while True:\\n n = src.readinto(buf)\\n if n == 0:\\n break\\n dest(buf if n == _CHUNK_SIZE else buf[:n])\\n\\n\\n# Check if the specified path exists and matches the hash.\\ndef _check_exists(path, short_hash):\\n import os\\n\\n try:\\n import binascii\\n import hashlib\\n\\n with open(path, \"rb\") as f:\\n hs256 = hashlib.sha256()\\n _chunk(f, hs256.update)\\n existing_hash = str(binascii.hexlify(hs256.digest())[: len(short_hash)], \"utf-8\")\\n return existing_hash == short_hash\\n except:\\n return False\\n\\n\\ndef _rewrite_url(url, branch=None):\\n if not branch:\\n branch = \"HEAD\"\\n if url.startswith(\"github:\"):\\n url = url[7:].split(\"/\")\\n url = (\\n \"https://raw.githubusercontent.com/\"\\n + url[0]\\n + \"/\"\\n + url[1]\\n + \"/\"\\n + branch\\n + \"/\"\\n + \"/\".join(url[2:])\\n )\\n return url\\n\\n\\ndef _download_file(url, dest):\\n response = get(url)\\n try:\\n if response.status_code != 200:\\n print(\"Error\", response.status_code, \"requesting\", url)\\n return False\\n\\n print(\"Copying:\", dest)\\n _ensure_path_exists(dest)\\n with open(dest, \"wb\") as f:\\n _chunk(response.raw, f.write)\\n\\n return True\\n finally:\\n response.close()\\n\\n\\ndef _install_json(package_json_url, index, target, version, mpy):\\n response = get(_rewrite_url(package_json_url, version))\\n try:\\n if response.status_code != 200:\\n print(\"Package not found:\", package_json_url)\\n return False\\n\\n package_json = response.json()\\n finally:\\n response.close()\\n for target_path, short_hash in package_json.get(\"hashes\", ()):\\n fs_target_path = target + \"/\" + target_path\\n if _check_exists(fs_target_path, short_hash):\\n print(\"Exists:\", fs_target_path)\\n else:\\n file_url = \"{}/file/{}/{}\".format(index, short_hash[:2], short_hash)\\n if not _download_file(file_url, fs_target_path):\\n print(\"File not found: {} {}\".format(target_path, short_hash))\\n return False\\n for target_path, url in package_json.get(\"urls\", ()):\\n fs_target_path = target + \"/\" + target_path\\n if not _download_file(_rewrite_url(url, version), fs_target_path):\\n print(\"File not found: {} {}\".format(target_path, url))\\n return False\\n for dep, dep_version in package_json.get(\"deps\", ()):\\n if not _install_package(dep, index, target, dep_version, mpy):\\n return False\\n return True\\n\\n\\ndef _install_package(package, index, target, version, mpy):\\n if (\\n package.startswith(\"http://\")\\n or package.startswith(\"https://\")\\n or package.startswith(\"github:\")\\n ):\\n if package.endswith(\".py\") or package.endswith(\".mpy\"):\\n print(\"Downloading {} to {}\".format(package, target))\\n return _download_file(\\n _rewrite_url(package, version), target + \"/\" + package.rsplit(\"/\")[-1]\\n )\\n else:\\n if not package.endswith(\".json\"):\\n if not package.endswith(\"/\"):\\n package += \"/\"\\n package += \"package.json\"\\n print(\"Installing {} to {}\".format(package, target))\\n else:\\n if not version:\\n version = \"latest\"\\n print(\"Installing {} ({}) from {} to {}\".format(package, version, index, target))\\n\\n mpy_version = (\\n sys.implementation._mpy & 0xFF if mpy and hasattr(sys.implementation, \"_mpy\") else \"py\"\\n )\\n\\n package = \"{}/package/{}/{}/{}.json\".format(index, mpy_version, package, version)\\n\\n return _install_json(package, index, target, version, mpy)\\n\\n\\ndef install(package, index=None, target=None, version=None, mpy=True):\\n if not target:\\n for p in sys.path:\\n if p.endswith(\"/lib\"):\\n target = p\\n break\\n else:\\n print(\"Unable to find lib dir in sys.path\")\\n return\\n\\n if not index:\\n index = _PACKAGE_INDEX\\n\\n if _install_package(package, index.rstrip(\"/\"), target, version, mpy):\\n print(\"Done\")\\n else:\\n print(\"Package may be partially installed\")\\n');var Tt={type:\"micropython\",module:(e=\"1.21.0-279\")=>`https://cdn.jsdelivr.net/npm/@micropython/micropython-webassembly-pyscript@${e}/micropython.mjs`,async engine({loadMicroPython:e},t,n){const{stderr:r,stdout:s,get:o}=He();n=n.replace(/\\.m?js$/,\".wasm\");const a=await o(e({stderr:r,stdout:s,url:n}));if(t.files&&await Ye(this,a,t.files),t.fetch&&await qe(this,a,t.fetch),t.js_modules&&await Xe(t.js_modules),this.writeFile(a,\"./mip.py\",vt),t.packages){const e=a.pyimport(\"mip\");for(const n of t.packages)e.install(n)}return a},registerJSModule:_t,run:bt,runAsync:Et,runEvent:kt,transform:(e,t)=>t instanceof e.PyProxy?e.PyProxy.toJs(t):t,writeFile:({FS:e,_module:{PATH:t,PATH_FS:n}},r,s)=>We({FS:e,PATH:t,PATH_FS:n},r,s)};const St={dict_converter:Object.fromEntries};var xt={type:\"pyodide\",module:(e=\"0.24.1\")=>`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},t,n){const{stderr:r,stdout:s,get:o}=He(),a=n.slice(0,n.lastIndexOf(\"/\")),i=await o(e({stderr:r,stdout:s,indexURL:a}));if(t.files&&await Ye(this,i,t.files),t.fetch&&await qe(this,i,t.fetch),t.js_modules&&await Xe(t.js_modules),t.packages){await i.loadPackage(\"micropip\");const e=await i.pyimport(\"micropip\");await e.install(t.packages,{keep_going:!0}),e.destroy()}return i},registerJSModule:_t,run:bt,runAsync:Et,runEvent:kt,transform:(e,t)=>t instanceof e.ffi.PyProxy?t.toJs(St):t,writeFile:({FS:e,PATH:t,_module:{PATH_FS:n}},r,s)=>We({FS:e,PATH:t,PATH_FS:n},r,s)};const At=\"ruby-wasm-wasi\",Ot=At.replace(/\\W+/g,\"_\");var jt={type:At,experimental:!0,module:(e=\"2.2.0\")=>`https://cdn.jsdelivr.net/npm/ruby-3_2-wasm-wasi@${e}/dist/browser.esm.js`,async engine({DefaultRubyVM:e},t,n){const r=await fetch(`${n.slice(0,n.lastIndexOf(\"/\"))}/ruby.wasm`),s=await WebAssembly.compile(await r.arrayBuffer()),{vm:o}=await e(s);return t.files&&await Ye(this,o,t.files),t.fetch&&await qe(this,o,t.fetch),t.js_modules&&await Xe(t.js_modules),o},registerJSModule(e,t,n){t=t.replace(/\\W+/g,\"__\");const r=`__module_${Ot}_${t}`;globalThis[r]=n,this.run(e,`require \"js\";$${t}=JS.global[:${r}]`),delete globalThis[r]},run:(e,t,...n)=>e.eval(Ve(t),...n),runAsync:(e,t,...n)=>e.evalAsync(Ve(t),...n),async runEvent(e,t,n){if(/^xworker\\.(on\\w+)$/.test(t)){const{$1:t}=RegExp,r=`__module_${Ot}_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 ${At}`)}};var Rt={type:\"wasmoon\",module:(e=\"1.16.0\")=>`https://cdn.jsdelivr.net/npm/wasmoon@${e}/+esm`,async engine({LuaFactory:e,LuaLibraries:t},n){const{stderr:r,stdout:s,get:o}=He(),a=await o((new e).createEngine());return a.global.getTable(t.Base,(e=>{a.global.setField(e,\"print\",s),a.global.setField(e,\"printErr\",r)})),n.files&&await Ye(this,a,n.files),n.fetch&&await qe(this,a,n.fetch),n.js_modules&&await Xe(n.js_modules),a},registerJSModule:(e,t,n)=>{e.global.set(t,n)},run:(e,t,...n)=>{try{return e.doStringSync(Ve(t),...n)}catch(t){Fe.get(e).stderr(t)}},runAsync:async(e,t,...n)=>{try{return await e.doString(Ve(t),...n)}catch(t){Fe.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){Fe.get(e).stderr(t)}},transform:(e,t)=>t,writeFile:({cmodule:{module:{FS:e}}},t,n)=>((e,t,n)=>(De(e,Ce(t)),t=Le(e,t),e.writeFile(t,new Uint8Array(n),{canOwn:!0})))(e,t,n)};const Pt=new Map,Nt=new Map,It=new Proxy(new Map,{get(e,t){if(!e.has(t)){const[n,...r]=t.split(\"@\"),s=Pt.get(n),o=/^(?:\\.?\\.?\\/|https?:\\/\\/)/i.test(r)?r.join(\"@\"):s.module(...r);e.set(t,{url:o,module:import(o),engine:s.engine.bind(s)})}const{url:n,module:r,engine:s}=e.get(t);return(e,o)=>r.then((r=>{Nt.set(t,e);for(const t of[\"files\",\"fetch\"]){const n=e?.[t];n&&Je.set(n,o)}for(const t of[\"main\",\"worker\"]){const n=e?.js_modules?.[t];n&&Je.set(n,o)}return s(r,e,n)}))}}),$t=e=>{for(const t of[].concat(e.type))Pt.set(t,e)};for(const e of[Tt,xt,jt,Rt])$t(e);const Mt=async e=>(await import(\"https://cdn.jsdelivr.net/npm/basic-toml@0.3.1/es.js\")).parse(e),Ft=(e,t,n={})=>{if(t){const[e,r]=(e=>{let t=typeof e;return\"string\"===t&&/\\.(json|toml|txt)$/.test(e)?t=RegExp.$1:e=\"./config.txt\",[at(e),t]})(t);if(\"json\"===r)n=fetch(e).then($e);else if(\"toml\"===r)n=fetch(e).then(Me).then(Mt);else if(\"string\"===r)try{n=JSON.parse(t)}catch(e){n=Mt(t)}else\"object\"===r&&t&&(n=t);t=e}return ot(n).then((n=>It[e](n,t)))},Ht=\"BeforeRun\",Wt=\"AfterRun\",Ct=[`code${Ht}`,`code${Ht}Async`,`code${Wt}`,`code${Wt}Async`],Dt=[\"onWorker\",\"onReady\",`on${Ht}`,`on${Ht}Async`,`on${Wt}`,`on${Wt}Async`];function Lt(e,t){const{run:n,runAsync:r}=Pt.get(this.type);return{...e,run:n.bind(this,t),runAsync:r.bind(this,t)}}const Bt=(e,t,n,r,s,o)=>{if(s||o){const a=Lt.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}}};try{new SharedArrayBuffer(4)}catch(e){throw new Error([\"Unable to use SharedArrayBuffer due insecure environment.\",\"Please read requirements in MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements\"].join(\"\\n\"))}let Ut,Jt,qt;const Gt=(e,t)=>{addEventListener(e,t||(async t=>{try{await Ut,Jt(`xworker.on${e}`,t)}catch(e){postMessage(e)}}),!!t&&{once:!0})},{parse:Kt,stringify:Yt}=p,{proxy:zt,window:Xt,isWindowProxy:Vt}=Pe(self,{parse:Kt,stringify:Yt,transform:e=>qt?qt(e):e}),Zt={sync:zt,window:Xt,isWindowProxy:Vt,onmessage:console.info,onerror:console.error,onmessageerror:console.warn,postMessage:postMessage.bind(self)};Gt(\"message\",(({data:{options:e,config:t,code:n,hooks:r}})=>{Ut=(async()=>{try{const{id:s,tag:o,type:a,custom:i,version:c,config:l,async:u}=e,p=((e,t=\"\")=>`${e}@${t}`.replace(/@$/,\"\"))(a,c),f=await Ft(p,t,l),h=Nt.get(p).js_modules?.main,d=et(Pt.get(a)),g=((e,t,n,r)=>({type:t,config:n,interpreter:r,io:Fe.get(r),run:(t,...n)=>e.run(r,t,...n),runAsync:(t,...n)=>e.runAsync(r,t,...n),runEvent:(...t)=>e.runEvent(r,...t)}))(d,i||a,l,f);let y=\"run\";if(u&&(y+=\"Async\"),r){const e=((e,t)=>(n,r)=>{const s=e[t].bind(e);e[t]=(e,t,...o)=>s(e,`${r?n:t}\\n${r?t:n}`,...o)})(d,y);let t,n,s=\"\",o=\"\";for(const e of Ct){const t=r[e];if(t){const n=e.endsWith(\"Async\");(n&&u||!n&&!u)&&(e.startsWith(\"codeBefore\")?s=t:o=t)}}o&&e(o,!1),s&&e(s,!0);for(const e of Dt.slice(2)){const s=r[e];if(s){const r=e.endsWith(\"Async\");if(r&&u||!r&&!u){const r=ct(s);e.startsWith(\"onBefore\")?t=r:n=r}}}Bt(d,g,Zt,u,t,n)}const{CustomEvent:m,document:w}=Xt,_=s&&w.getElementById(s)||null,b=e=>it(_,i||a,e,!0,m),E=wt(Xt,zt,h);let k=\"\";return((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}`,ft(r,e));t.registerJSModule(n,s,r)})(a,d,f,E),d.registerJSModule(f,\"polyscript\",{xworker:Zt,currentScript:_,js_modules:E,get target(){return!k&&_&&(\"SCRIPT\"===o?_.after(Qe(w.createElement(`script-${i||a}`),{id:k=`${s}-target`})):(k=s,_.replaceChildren(),_.style.display=\"block\")),k}}),Jt=d.runEvent.bind(d,f),qt=d.transform.bind(d,f),_&&b(\"ready\"),r?.onReady&&ct(r?.onReady).call(d,Lt.call(d,g,f),Zt),await d[y](f,n),_&&b(\"done\"),f}catch(e){postMessage(e)}})(),Gt(\"error\"),Gt(\"message\"),Gt(\"messageerror\")}));\n"],{type:'application/javascript'})),{type:'module'}); | ||
export default () => new Worker(URL.createObjectURL(new Blob(["const e=\"object\"==typeof self?self:globalThis,t=t=>((t,n)=>{const r=(e,n)=>(t.set(n,e),e),s=o=>{if(t.has(o))return t.get(o);const[a,i]=n[o];switch(a){case 0:case-1:return r(i,o);case 1:{const e=r([],o);for(const t of i)e.push(s(t));return e}case 2:{const e=r({},o);for(const[t,n]of i)e[s(t)]=s(n);return e}case 3:return r(new Date(i),o);case 4:{const{source:e,flags:t}=i;return r(new RegExp(e,t),o)}case 5:{const e=r(new Map,o);for(const[t,n]of i)e.set(s(t),s(n));return e}case 6:{const e=r(new Set,o);for(const t of i)e.add(s(t));return e}case 7:{const{name:t,message:n}=i;return r(new e[t](n),o)}case 8:return r(BigInt(i),o);case\"BigInt\":return r(Object(BigInt(i)),o)}return r(new e[a](i),o)};return s})(new Map,t)(0),n=\"\",{toString:r}={},{keys:s}=Object,o=e=>{const t=typeof e;if(\"object\"!==t||!e)return[0,t];const s=r.call(e).slice(8,-1);switch(s){case\"Array\":return[1,n];case\"Object\":return[2,n];case\"Date\":return[3,n];case\"RegExp\":return[4,n];case\"Map\":return[5,n];case\"Set\":return[6,n]}return s.includes(\"Array\")?[1,s]:s.includes(\"Error\")?[7,s]:[2,s]},a=([e,t])=>0===e&&(\"function\"===t||\"symbol\"===t),i=(e,{json:t,lossy:n}={})=>{const r=[];return((e,t,n,r)=>{const i=(e,t)=>{const s=r.push(e)-1;return n.set(t,s),s},c=r=>{if(n.has(r))return n.get(r);let[l,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=\"ac6c1995-0675-46af-a99f-7fa298fa4e6d\",h=\"M\"+f,d=\"T\"+f,g=\"array\",y=\"function\",m=\"null\",w=\"number\",_=\"object\",b=\"string\",E=\"symbol\",k=\"undefined\",v=\"apply\",T=\"construct\",S=\"defineProperty\",x=\"deleteProperty\",A=\"get\",O=\"getOwnPropertyDescriptor\",j=\"getPrototypeOf\",R=\"has\",P=\"isExtensible\",N=\"ownKeys\",I=\"preventExtensions\",$=\"set\",M=\"setPrototypeOf\",F=\"delete\";var H=e=>({value:new Promise((t=>{let n=new Worker(\"data:application/javascript,onmessage%3D(%7Bdata%3Ab%7D)%3D%3E(Atomics.wait(b%2C0)%2CpostMessage(0))\");n.onmessage=t,n.postMessage(e)}))})\n/*! (c) Andrea Giammarchi - ISC */;const{Int32Array:W,Map:C,SharedArrayBuffer:D,Uint16Array:L}=globalThis,{BYTES_PER_ELEMENT:B}=W,{BYTES_PER_ELEMENT:U}=L,{isArray:J}=Array,{notify:q,wait:G,waitAsync:K}=Atomics,Y=new WeakSet,z=new WeakMap,X={value:{then:e=>e()}};let V=0;const Z=(e,{parse:t=JSON.parse,stringify:n=JSON.stringify,transform:r,interrupt:s}=JSON)=>{if(!z.has(e)){const o=(t,...n)=>e.postMessage({[f]:n},{transfer:t}),a=typeof s===y?s:s?.handler,i=s?.delay||42,c=new TextDecoder(\"utf-16\"),l=(e,t)=>e?(K||H)(t,0):(a?((e,t,n)=>{for(;\"timed-out\"===G(e,0,0,t);)n()})(t,i,a):G(t,0),X);let u=!1;z.set(e,new Proxy(new C,{[R]:(e,t)=>\"string\"==typeof t&&!t.startsWith(\"_\"),[A]:(n,s)=>\"then\"===s?null:(...n)=>{const a=V++;let i=new W(new D(2*B)),p=[];Y.has(n.at(-1)||p)&&Y.delete(p=n.pop()),o(p,a,i,s,r?n.map(r):n);const f=e!==globalThis;let h=0;return u&&f&&(h=setTimeout(console.warn,1e3,`ππ - Possible deadlock if proxy.${s}(...args) is awaited`)),l(f,i).value.then((()=>{clearTimeout(h);const e=i[1];if(!e)return;const n=U*e;return i=new W(new D(n+n%B)),o([],a,i),l(f,i).value.then((()=>t(c.decode(new L(i.buffer).slice(0,e)))))}))},[$](t,s,o){const a=typeof o;if(a!==y)throw new Error(`Unable to assign ${s} as ${a}`);if(!t.size){const s=new C;e.addEventListener(\"message\",(async e=>{const o=e.data?.[f];if(J(o)){e.stopImmediatePropagation();const[a,i,...c]=o;let l;if(c.length){const[e,o]=c;if(t.has(e)){u=!0;try{const c=await t.get(e)(...o);if(void 0!==c){const e=n(r?r(c):c);s.set(a,e),i[1]=e.length}}catch(e){l=e}finally{u=!1}}else l=new Error(`Unsupported action: ${e}`);i[0]=1}else{const e=s.get(a);s.delete(a);for(let t=new L(i.buffer),n=0;n<e.length;n++)t[n]=e.charCodeAt(n)}if(q(i,0),l)throw l}}))}return!!t.set(s,o)}}))}return z.get(e)};Z.transfer=(...e)=>(Y.add(e),e);const{isArray:Q}=Array,ee=(e,t)=>t,te=e=>typeof e===y?(e=>e())(e):e;function ne(){return this}const re=(e,t)=>e===g?[t]:{t:e,v:t},se=(e,t=ee)=>{let n=typeof e,r=e;return n===_&&(Q(e)?(n=g,r=e.at(0)):({t:n,v:r}=e)),t(n,r)},oe=(e,t)=>e===y?t:re(e,t),ae=(e,t=oe)=>{const n=null===e?m:typeof e;return t(n===_&&Q(e)?g:n,e)},ie=new FinalizationRegistry((([e,t,n])=>{n&&console.debug(`Held value ${String(t)} not relevant anymore`),e(t)})),ce=Object.create(null),le=(e,t,{debug:n,return:r,token:s=e}=ce)=>{const o=r||new Proxy(e,ce),a=[o,[t,e,!!n]];return!1!==s&&a.push(s),ie.register(...a),o},{defineProperty:ue,deleteProperty:pe,getOwnPropertyDescriptor:fe,getPrototypeOf:he,isExtensible:de,ownKeys:ge,preventExtensions:ye,set:me,setPrototypeOf:we}=Reflect,{assign:_e,create:be}=Object,Ee=he(Int8Array),ke=(e,t)=>{const{get:n,set:r,value:s}=e;return n&&(e.get=t(n)),r&&(e.set=t(r)),s&&(e.value=t(s)),e},ve=e=>t=>ae(t,((t,n)=>{switch(t){case m:return re(m,n);case _:if(n===globalThis)return re(t,null);case g:case y:return e(t,n);case\"boolean\":case w:case b:case k:case\"bigint\":return re(t,n);case E:{if(Te.has(n))return re(t,Te.get(n));let e=Symbol.keyFor(n);if(e)return re(t,`.${e}`)}}throw new TypeError(`Unable to handle this ${t}: ${String(n)}`)})),Te=new Map(ge(Symbol).filter((e=>typeof Symbol[e]===E)).map((e=>[Symbol[e],e]))),Se=e=>{if(e.startsWith(\".\"))return Symbol.for(e.slice(1));for(const[t,n]of Te)if(n===e)return t},xe=e=>e;var Ae=((e,t)=>{const n=t&&new WeakMap;if(t){const{addEventListener:e}=EventTarget.prototype;ue(EventTarget.prototype,\"addEventListener\",{value(t,r,...s){return s.at(0)?.invoke&&(n.has(this)||n.set(this,new Map),n.get(this).set(t,[].concat(s[0].invoke)),delete s[0].invoke),e.call(this,t,r,...s)}})}const r=t&&(e=>{const{currentTarget:t,target:r,type:s}=e;for(const o of n.get(t||r)?.get(s)||[])e[o]()});return function(n,s,o,...a){let i=0,c=this?.transform||xe;const l=new Map,u=new Map,{[o]:p}=n,f=a.length?_e(be(globalThis),...a):globalThis,h=ve(((e,t)=>{if(!l.has(t)){let n;for(;u.has(n=i++););l.set(t,n),u.set(n,e===y?t:c(t))}return re(e,l.get(t))})),d=e=>{p(F,re(b,e))},m=(e,n)=>{switch(e){case _:if(null==n)return f;case g:if(typeof n===w)return u.get(n);if(!(n instanceof Ee))for(const e in n)n[e]=H(n[e]);return n;case y:if(typeof n===b){if(!u.has(n)){const e=function(...e){return t&&e.at(0)instanceof Event&&r(...e),p(v,re(y,n),h(this),e.map(h))};return u.set(n,new WeakRef(e)),le(n,d,{return:e,token:!1})}return u.get(n).deref()}return u.get(n);case E:return Se(n)}return n},H=e=>se(e,m),W={[v]:(e,t,n)=>h(e.apply(t,n)),[T]:(e,t)=>h(new e(...t)),[S]:(e,t,n)=>h(ue(e,t,n)),[x]:(e,t)=>h(pe(e,t)),[j]:e=>h(he(e)),[A]:(e,t)=>h(e[t]),[O]:(e,t)=>{const n=fe(e,t);return n?re(_,ke(n,h)):re(k,n)},[R]:(e,t)=>h(t in e),[P]:e=>h(de(e)),[N]:e=>re(g,ge(e).map(h)),[I]:e=>h(ye(e)),[$]:(e,t,n)=>h(me(e,t,n)),[M]:(e,t)=>h(we(e,t)),[F](e){l.delete(u.get(e)),u.delete(e)}};return n[s]=(e,t,...n)=>{switch(e){case v:n[0]=H(n[0]),n[1]=n[1].map(H);break;case T:n[0]=n[0].map(H);break;case S:{const[e,t]=n;n[0]=H(e);const{get:r,set:s,value:o}=t;r&&(t.get=H(r)),s&&(t.set=H(s)),o&&(t.value=H(o));break}default:n=n.map(H)}return W[e](H(t),...n)},{proxy:n,[e.toLowerCase()]:f,[`is${e}Proxy`]:()=>!1}}})(\"Window\",!0),Oe=(e=>{let t=0;const n=new Map,r=new Map,s=Symbol();return function(o,a,i){const c=this?.transform||xe,{[a]:l}=o,u=new Map,p=e=>{u.delete(e),l(F,f(e))},f=ve(((e,o)=>{if(s in o)return te(o[s]);if(e===y){if(o=c(o),!r.has(o)){let e;for(;r.has(e=String(t++)););n.set(o,e),r.set(e,o)}return re(e,n.get(o))}if(!(o instanceof Ee)){o=c(o);for(const e in o)o[e]=f(o[e])}return re(e,o)})),h=(e,t,n)=>{if(!u.has(n)){const r=t===y?(e=>ne.bind(e))(e):e,s=new Proxy(r,k);return u.set(n,new WeakRef(s)),le(n,p,{return:s,token:!1})}return u.get(n).deref()},d=e=>se(e,((t,n)=>{switch(t){case _:if(null===n)return globalThis;case g:return typeof n===w?h(e,t,n):n;case y:return typeof n===b?r.get(n):h(e,t,n);case E:return Se(n)}return n})),m=(e,t,...n)=>d(l(e,te(t),...n)),k={[v]:(e,t,n)=>m(v,e,f(t),n.map(f)),[T]:(e,t)=>m(T,e,t.map(f)),[S]:(e,t,n)=>{const{get:r,set:s,value:o}=n;return typeof r===y&&(n.get=f(r)),typeof s===y&&(n.set=f(s)),typeof o===y&&(n.value=f(o)),m(S,e,f(t),n)},[x]:(e,t)=>m(x,e,f(t)),[j]:e=>m(j,e),[A]:(e,t)=>t===s?e:m(A,e,f(t)),[O]:(e,t)=>{const n=m(O,e,f(t));return n&&ke(n,d)},[R]:(e,t)=>t===s||m(R,e,f(t)),[P]:e=>m(P,e),[N]:e=>m(N,e).map(d),[I]:e=>m(I,e),[$]:(e,t,n)=>m($,e,f(t),f(n)),[M]:(e,t)=>m(M,e,f(t))};o[i]=(e,t,s,o)=>{switch(e){case v:return d(t).apply(d(s),o.map(d));case F:{const e=d(t);n.delete(r.get(e)),r.delete(e)}}};const H=new Proxy(re(_,null),k);return{[e.toLowerCase()]:H,[`is${e}Proxy`]:e=>typeof e===_&&!!e&&s in e,proxy:o}}})(\"Window\"),je=typeof Worker===y?Worker:class{};const Re=new WeakMap,Pe=(e,...t)=>{const n=Z(e,...t);if(!Re.has(n)){const r=e instanceof je?Ae:Oe;Re.set(n,r.call(t.at(0),n,h,d))}return Re.get(n)};Pe.transfer=Z.transfer;const Ne={object(...e){return this.string(function(e){for(var t=e[0],n=1,r=arguments.length;n<r;n++)t+=arguments[n]+e[n];return t}(...e))},string(e){for(const t of e.split(/[\\r\\n]+/))if(t.trim().length){/^(\\s+)/.test(t)&&(e=e.replace(new RegExp(\"^\"+RegExp.$1,\"gm\"),\"\"));break}return e}};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 Ie=e=>e.arrayBuffer(),$e=e=>e.json(),Me=e=>e.text(),Fe=new WeakMap,He=e=>{const t=e||console,n={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 Fe.set(t,n),t}}},We=({FS:e,PATH:t,PATH_FS:n},r,s)=>{const o=n.resolve(r);return e.mkdirTree(t.dirname(o)),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},Ce=e=>{const t=e.split(\"/\");return t.pop(),t.join(\"/\")},De=(e,t)=>{const n=[];for(const r of t.split(\"/\"))\".\"!==r&&(n.push(r),r&&e.mkdir(n.join(\"/\")))},Le=(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(/^\\/+/,\"/\")},Be=e=>{const t=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,\"\"))).filter((e=>\"\"!==e&&\".\"!==e)).join(\"/\");return e[0].startsWith(\"/\")?`/${t}`:t},Ue=(e,t)=>fetch(at(t,Je.get(e))),Je=new WeakMap,qe=(e,t,n)=>st((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(Ze(r))return r.map((n=>({url:Be([e,n]),path:Be([t,n])})));const s=n||e.slice(1+e.lastIndexOf(\"/\"));return[{url:e,path:Be([t,s])}]}))})(n).map((({url:r,path:s})=>Ue(n,r).then(Ie).then((n=>e.writeFile(t,s,n)))))),Ge=(e,t)=>t.endsWith(\"/\")?`${t}${e.split(\"/\").pop()}`:t,Ke=(e,t)=>e.replace(/\\{.+?\\}/g,(e=>{if(!t.has(e))throw new SyntaxError(`Invalid template: ${e}`);return t.get(e)})),Ye=(e,t,n)=>st((e=>{const t=new Map,n=new Set,r=[];for(const[s,o]of rt(e))if(/^\\{.+\\}$/.test(s)){if(t.has(s))throw new SyntaxError(`Duplicated template: ${s}`);t.set(s,Ke(o,t))}else{const e=Ke(s,t),a=Ge(e,Ke(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:r,path:s})=>Ue(n,r).then(Ie).then((n=>e.writeFile(t,s,n)))))),ze=typeof document===k,Xe=({main:e,worker:t})=>{const n=[];if(t&&ze)for(let[e,r]of rt(t))e=at(e,Je.get(t)),n.push(ht(e,r));if(e&&!ze)for(let[t,r]of rt(e))t=at(t,Je.get(e)),gt(t)?dt(t):n.push(ht(t,r));return st(n)},Ve=(e,...t)=>Ne[typeof e](e,...t),{isArray:Ze}=Array,{assign:Qe,create:et,defineProperties:tt,defineProperty:nt,entries:rt}=Object,{all:st,resolve:ot}=new Proxy(Promise,{get:(e,t)=>e[t].bind(e)}),at=(e,t=location.href)=>new URL(e,t.replace(/^blob:/,\"\")).href,it=(e,t,n,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${t}:${n}`,{bubbles:!0,detail:{worker:r}}))},ct=e=>Function(`'use strict';return (${e})`)(),lt=Symbol.for(\"polyscript.js_modules\"),ut=new Map;nt(globalThis,lt,{value:ut}),new Proxy(ut,{get:(e,t)=>e.get(t),has:(e,t)=>e.has(t),ownKeys:e=>[...e.keys()]});const pt=(e,t)=>!t.startsWith(\"_\"),ft=(e,t)=>new Proxy(e,{has:pt,get:(e,n)=>e[t][n]}),ht=(e,t)=>import(e).then((e=>{ut.set(t,{...e})})),dt=e=>new Promise(((t,n)=>{document.querySelector(`link[href=\"${e}\"]`)&&t(),document.head.append(Qe(document.createElement(\"link\"),{rel:\"stylesheet\",href:e,onload:t,onerror:n}))})),gt=e=>/\\.css/i.test(new URL(e).pathname),yt=(e,t)=>e.has(t),mt=e=>[...e.keys()];var wt=(e,t,n)=>{let r=globalThis[lt],s=\"\";if(n){s=Je.get(n);for(let[e,t]of rt(n)){let n=r.get(t);n&&!Ze(n)||(r.set(t,n||(n=[])),n.push(e))}}return((e,t,n,r)=>new Proxy(e,{has:yt,ownKeys:mt,get:(e,s)=>{let o=e.get(s);if(Ze(o)){let a=o;o=null;for(let e of a)e=at(e,r),gt(e)?n.importCSS(e):(n.importJS(e,s),o=t[lt].get(s));e.set(s,o)}return o}}))(r,e,t,s)};const _t=(e,t,n)=>{e.registerJsModule(t,n)},bt=(e,t,...n)=>{try{return e.runPython(Ve(t),...n)}catch(t){Fe.get(e).stderr(t)}},Et=async(e,t,...n)=>{try{return await e.runPythonAsync(Ve(t),...n)}catch(t){Fe.get(e).stderr(t)}},kt=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){Fe.get(e).stderr(t)}};var vt=(new TextEncoder).encode('from uio import StringIO\\nimport sys\\n\\nclass Response:\\n def __init__(self, f):\\n self.raw = f\\n self.encoding = \"utf-8\"\\n self._cached = None\\n\\n def close(self):\\n if self.raw:\\n self.raw.close()\\n self.raw = None\\n self._cached = None\\n\\n @property\\n def content(self):\\n if self._cached is None:\\n try:\\n self._cached = self.raw.read()\\n finally:\\n self.raw.close()\\n self.raw = None\\n return self._cached\\n\\n @property\\n def text(self):\\n return str(self.content, self.encoding)\\n\\n def json(self):\\n import ujson\\n\\n return ujson.loads(self.content)\\n\\n\\n# TODO try to support streaming xhr requests, a-la pyodide-http\\nHEADERS_TO_IGNORE = (\"user-agent\",)\\n\\n\\ntry:\\n import js\\nexcept Exception as err:\\n raise OSError(\"This version of urequests can only be used in the browser\")\\n\\n# TODO try to support streaming xhr requests, a-la pyodide-http\\n\\nHEADERS_TO_IGNORE = (\"user-agent\",)\\n\\n\\ndef request(\\n method,\\n url,\\n data=None,\\n json=None,\\n headers={},\\n stream=None,\\n auth=None,\\n timeout=None,\\n parse_headers=True,\\n):\\n from js import XMLHttpRequest\\n\\n xhr = XMLHttpRequest.new()\\n xhr.withCredentials = False\\n\\n if auth is not None:\\n import ubinascii\\n\\n username, password = auth\\n xhr.open(method, url, False, username, password)\\n else:\\n xhr.open(method, url, False)\\n\\n for name, value in headers.items():\\n if name.lower() not in HEADERS_TO_IGNORE:\\n xhr.setRequestHeader(name, value)\\n\\n if timeout:\\n xhr.timeout = int(timeout * 1000)\\n\\n if json is not None:\\n assert data is None\\n import ujson\\n\\n data = ujson.dumps(json)\\n # s.write(b\"Content-Type: application/json\\\\r\\\\n\")\\n xhr.setRequestHeader(\"Content-Type\", \"application/json\")\\n\\n xhr.send(data)\\n\\n # Emulates the construction process in the original urequests\\n resp = Response(StringIO(xhr.responseText))\\n resp.status_code = xhr.status\\n resp.reason = xhr.statusText\\n resp.headers = xhr.getAllResponseHeaders()\\n\\n return resp\\n\\n\\n# Other methods - head, post, put, patch, delete - are not used by\\n# mip and therefore not included\\n\\n\\ndef get(url, **kw):\\n return request(\"GET\", url, **kw)\\n\\n\\n# Content below this line is from the Micropython MIP package and is covered\\n# by the applicable MIT license:\\n# \\n# THE SOFTWARE IS PROVIDED βAS ISβ, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \\n# DEALINGS IN THE SOFTWARE.\\n\\n# MicroPython package installer\\n# MIT license; Copyright (c) 2022 Jim Mussared\\n\\n\\n_PACKAGE_INDEX = const(\"https://micropython.org/pi/v2\")\\n_CHUNK_SIZE = 128\\n\\n\\n# This implements os.makedirs(os.dirname(path))\\ndef _ensure_path_exists(path):\\n import os\\n\\n split = path.split(\"/\")\\n\\n # Handle paths starting with \"/\".\\n if not split[0]:\\n split.pop(0)\\n split[0] = \"/\" + split[0]\\n\\n prefix = \"\"\\n for i in range(len(split) - 1):\\n prefix += split[i]\\n try:\\n os.stat(prefix)\\n except:\\n os.mkdir(prefix)\\n prefix += \"/\"\\n\\n\\n# Copy from src (stream) to dest (function-taking-bytes)\\ndef _chunk(src, dest):\\n buf = memoryview(bytearray(_CHUNK_SIZE))\\n while True:\\n n = src.readinto(buf)\\n if n == 0:\\n break\\n dest(buf if n == _CHUNK_SIZE else buf[:n])\\n\\n\\n# Check if the specified path exists and matches the hash.\\ndef _check_exists(path, short_hash):\\n import os\\n\\n try:\\n import binascii\\n import hashlib\\n\\n with open(path, \"rb\") as f:\\n hs256 = hashlib.sha256()\\n _chunk(f, hs256.update)\\n existing_hash = str(binascii.hexlify(hs256.digest())[: len(short_hash)], \"utf-8\")\\n return existing_hash == short_hash\\n except:\\n return False\\n\\n\\ndef _rewrite_url(url, branch=None):\\n if not branch:\\n branch = \"HEAD\"\\n if url.startswith(\"github:\"):\\n url = url[7:].split(\"/\")\\n url = (\\n \"https://raw.githubusercontent.com/\"\\n + url[0]\\n + \"/\"\\n + url[1]\\n + \"/\"\\n + branch\\n + \"/\"\\n + \"/\".join(url[2:])\\n )\\n return url\\n\\n\\ndef _download_file(url, dest):\\n response = get(url)\\n try:\\n if response.status_code != 200:\\n print(\"Error\", response.status_code, \"requesting\", url)\\n return False\\n\\n print(\"Copying:\", dest)\\n _ensure_path_exists(dest)\\n with open(dest, \"wb\") as f:\\n _chunk(response.raw, f.write)\\n\\n return True\\n finally:\\n response.close()\\n\\n\\ndef _install_json(package_json_url, index, target, version, mpy):\\n response = get(_rewrite_url(package_json_url, version))\\n try:\\n if response.status_code != 200:\\n print(\"Package not found:\", package_json_url)\\n return False\\n\\n package_json = response.json()\\n finally:\\n response.close()\\n for target_path, short_hash in package_json.get(\"hashes\", ()):\\n fs_target_path = target + \"/\" + target_path\\n if _check_exists(fs_target_path, short_hash):\\n print(\"Exists:\", fs_target_path)\\n else:\\n file_url = \"{}/file/{}/{}\".format(index, short_hash[:2], short_hash)\\n if not _download_file(file_url, fs_target_path):\\n print(\"File not found: {} {}\".format(target_path, short_hash))\\n return False\\n for target_path, url in package_json.get(\"urls\", ()):\\n fs_target_path = target + \"/\" + target_path\\n if not _download_file(_rewrite_url(url, version), fs_target_path):\\n print(\"File not found: {} {}\".format(target_path, url))\\n return False\\n for dep, dep_version in package_json.get(\"deps\", ()):\\n if not _install_package(dep, index, target, dep_version, mpy):\\n return False\\n return True\\n\\n\\ndef _install_package(package, index, target, version, mpy):\\n if (\\n package.startswith(\"http://\")\\n or package.startswith(\"https://\")\\n or package.startswith(\"github:\")\\n ):\\n if package.endswith(\".py\") or package.endswith(\".mpy\"):\\n print(\"Downloading {} to {}\".format(package, target))\\n return _download_file(\\n _rewrite_url(package, version), target + \"/\" + package.rsplit(\"/\")[-1]\\n )\\n else:\\n if not package.endswith(\".json\"):\\n if not package.endswith(\"/\"):\\n package += \"/\"\\n package += \"package.json\"\\n print(\"Installing {} to {}\".format(package, target))\\n else:\\n if not version:\\n version = \"latest\"\\n print(\"Installing {} ({}) from {} to {}\".format(package, version, index, target))\\n\\n mpy_version = (\\n sys.implementation._mpy & 0xFF if mpy and hasattr(sys.implementation, \"_mpy\") else \"py\"\\n )\\n\\n package = \"{}/package/{}/{}/{}.json\".format(index, mpy_version, package, version)\\n\\n return _install_json(package, index, target, version, mpy)\\n\\n\\ndef install(package, index=None, target=None, version=None, mpy=True):\\n if not target:\\n for p in sys.path:\\n if p.endswith(\"/lib\"):\\n target = p\\n break\\n else:\\n print(\"Unable to find lib dir in sys.path\")\\n return\\n\\n if not index:\\n index = _PACKAGE_INDEX\\n\\n if _install_package(package, index.rstrip(\"/\"), target, version, mpy):\\n print(\"Done\")\\n else:\\n print(\"Package may be partially installed\")\\n');var Tt={type:\"micropython\",module:(e=\"1.21.0-279\")=>`https://cdn.jsdelivr.net/npm/@micropython/micropython-webassembly-pyscript@${e}/micropython.mjs`,async engine({loadMicroPython:e},t,n){const{stderr:r,stdout:s,get:o}=He();n=n.replace(/\\.m?js$/,\".wasm\");const a=await o(e({stderr:r,stdout:s,url:n}));if(t.files&&await Ye(this,a,t.files),t.fetch&&await qe(this,a,t.fetch),t.js_modules&&await Xe(t.js_modules),this.writeFile(a,\"./mip.py\",vt),t.packages){const e=a.pyimport(\"mip\");for(const n of t.packages)e.install(n)}return a},registerJSModule:_t,run:bt,runAsync:Et,runEvent:kt,transform:(e,t)=>t instanceof e.PyProxy?e.PyProxy.toJs(t):t,writeFile:({FS:e,_module:{PATH:t,PATH_FS:n}},r,s)=>We({FS:e,PATH:t,PATH_FS:n},r,s)};const St={dict_converter:Object.fromEntries};var xt={type:\"pyodide\",module:(e=\"0.24.1\")=>`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},t,n){const{stderr:r,stdout:s,get:o}=He(),a=n.slice(0,n.lastIndexOf(\"/\")),i=await o(e({stderr:r,stdout:s,indexURL:a}));if(t.files&&await Ye(this,i,t.files),t.fetch&&await qe(this,i,t.fetch),t.js_modules&&await Xe(t.js_modules),t.packages){await i.loadPackage(\"micropip\");const e=await i.pyimport(\"micropip\");await e.install(t.packages,{keep_going:!0}),e.destroy()}return i},registerJSModule:_t,run:bt,runAsync:Et,runEvent:kt,transform:(e,t)=>t instanceof e.ffi.PyProxy?t.toJs(St):t,writeFile:({FS:e,PATH:t,_module:{PATH_FS:n}},r,s)=>We({FS:e,PATH:t,PATH_FS:n},r,s)};const At=\"ruby-wasm-wasi\",Ot=At.replace(/\\W+/g,\"_\");var jt={type:At,experimental:!0,module:(e=\"2.2.0\")=>`https://cdn.jsdelivr.net/npm/ruby-3_2-wasm-wasi@${e}/dist/browser.esm.js`,async engine({DefaultRubyVM:e},t,n){const r=await fetch(`${n.slice(0,n.lastIndexOf(\"/\"))}/ruby.wasm`),s=await WebAssembly.compile(await r.arrayBuffer()),{vm:o}=await e(s);return t.files&&await Ye(this,o,t.files),t.fetch&&await qe(this,o,t.fetch),t.js_modules&&await Xe(t.js_modules),o},registerJSModule(e,t,n){t=t.replace(/\\W+/g,\"__\");const r=`__module_${Ot}_${t}`;globalThis[r]=n,this.run(e,`require \"js\";$${t}=JS.global[:${r}]`),delete globalThis[r]},run:(e,t,...n)=>e.eval(Ve(t),...n),runAsync:(e,t,...n)=>e.evalAsync(Ve(t),...n),async runEvent(e,t,n){if(/^xworker\\.(on\\w+)$/.test(t)){const{$1:t}=RegExp,r=`__module_${Ot}_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 ${At}`)}};var Rt={type:\"wasmoon\",module:(e=\"1.16.0\")=>`https://cdn.jsdelivr.net/npm/wasmoon@${e}/+esm`,async engine({LuaFactory:e,LuaLibraries:t},n){const{stderr:r,stdout:s,get:o}=He(),a=await o((new e).createEngine());return a.global.getTable(t.Base,(e=>{a.global.setField(e,\"print\",s),a.global.setField(e,\"printErr\",r)})),n.files&&await Ye(this,a,n.files),n.fetch&&await qe(this,a,n.fetch),n.js_modules&&await Xe(n.js_modules),a},registerJSModule:(e,t,n)=>{e.global.set(t,n)},run:(e,t,...n)=>{try{return e.doStringSync(Ve(t),...n)}catch(t){Fe.get(e).stderr(t)}},runAsync:async(e,t,...n)=>{try{return await e.doString(Ve(t),...n)}catch(t){Fe.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){Fe.get(e).stderr(t)}},transform:(e,t)=>t,writeFile:({cmodule:{module:{FS:e}}},t,n)=>((e,t,n)=>(De(e,Ce(t)),t=Le(e,t),e.writeFile(t,new Uint8Array(n),{canOwn:!0})))(e,t,n)};const Pt=new Map,Nt=new Map,It=new Proxy(new Map,{get(e,t){if(!e.has(t)){const[n,...r]=t.split(\"@\"),s=Pt.get(n),o=/^(?:\\.?\\.?\\/|https?:\\/\\/)/i.test(r)?r.join(\"@\"):s.module(...r);e.set(t,{url:o,module:import(o),engine:s.engine.bind(s)})}const{url:n,module:r,engine:s}=e.get(t);return(e,o)=>r.then((r=>{Nt.set(t,e);for(const t of[\"files\",\"fetch\"]){const n=e?.[t];n&&Je.set(n,o)}for(const t of[\"main\",\"worker\"]){const n=e?.js_modules?.[t];n&&Je.set(n,o)}return s(r,e,n)}))}}),$t=e=>{for(const t of[].concat(e.type))Pt.set(t,e)};for(const e of[Tt,xt,jt,Rt])$t(e);const Mt=async e=>(await import(\"https://cdn.jsdelivr.net/npm/basic-toml@0.3.1/es.js\")).parse(e),Ft=e=>{try{return JSON.parse(e)}catch(t){return Mt(e)}},Ht=(e,t,n={})=>{if(t){const[e,r]=(e=>{let t=typeof e;return\"string\"===t&&/\\.(json|toml|txt)$/.test(e)?t=RegExp.$1:e=\"./config.txt\",[at(e),t]})(t);\"json\"===r?n=fetch(e).then($e):\"toml\"===r?n=fetch(e).then(Me).then(Mt):\"string\"===r?n=Ft(t):\"object\"===r&&t?n=t:\"txt\"===r&&\"string\"==typeof n&&(n=Ft(n)),t=e}return ot(n).then((n=>It[e](n,t)))},Wt=\"BeforeRun\",Ct=\"AfterRun\",Dt=[`code${Wt}`,`code${Wt}Async`,`code${Ct}`,`code${Ct}Async`],Lt=[\"onWorker\",\"onReady\",`on${Wt}`,`on${Wt}Async`,`on${Ct}`,`on${Ct}Async`];function Bt(e,t){const{run:n,runAsync:r}=Pt.get(this.type);return{...e,run:n.bind(this,t),runAsync:r.bind(this,t)}}const Ut=(e,t,n,r,s,o)=>{if(s||o){const a=Bt.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}}};try{new SharedArrayBuffer(4)}catch(e){throw new Error([\"Unable to use SharedArrayBuffer due insecure environment.\",\"Please read requirements in MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements\"].join(\"\\n\"))}let Jt,qt,Gt;const Kt=(e,t)=>{addEventListener(e,t||(async t=>{try{await Jt,qt(`xworker.on${e}`,t)}catch(e){postMessage(e)}}),!!t&&{once:!0})},{parse:Yt,stringify:zt}=p,{proxy:Xt,window:Vt,isWindowProxy:Zt}=Pe(self,{parse:Yt,stringify:zt,transform:e=>Gt?Gt(e):e}),Qt={sync:Xt,window:Vt,isWindowProxy:Zt,onmessage:console.info,onerror:console.error,onmessageerror:console.warn,postMessage:postMessage.bind(self)};Kt(\"message\",(({data:{options:e,config:t,code:n,hooks:r}})=>{Jt=(async()=>{try{const{id:s,tag:o,type:a,custom:i,version:c,config:l,async:u}=e,p=((e,t=\"\")=>`${e}@${t}`.replace(/@$/,\"\"))(a,c),f=await Ht(p,t,l),h=Nt.get(p).js_modules?.main,d=et(Pt.get(a)),g=((e,t,n,r)=>({type:t,config:n,interpreter:r,io:Fe.get(r),run:(t,...n)=>e.run(r,t,...n),runAsync:(t,...n)=>e.runAsync(r,t,...n),runEvent:(...t)=>e.runEvent(r,...t)}))(d,i||a,l,f);let y=\"run\";if(u&&(y+=\"Async\"),r){const e=((e,t)=>(n,r)=>{const s=e[t].bind(e);e[t]=(e,t,...o)=>s(e,`${r?n:t}\\n${r?t:n}`,...o)})(d,y);let t,n,s=\"\",o=\"\";for(const e of Dt){const t=r[e];if(t){const n=e.endsWith(\"Async\");(n&&u||!n&&!u)&&(e.startsWith(\"codeBefore\")?s=t:o=t)}}o&&e(o,!1),s&&e(s,!0);for(const e of Lt.slice(2)){const s=r[e];if(s){const r=e.endsWith(\"Async\");if(r&&u||!r&&!u){const r=ct(s);e.startsWith(\"onBefore\")?t=r:n=r}}}Ut(d,g,Qt,u,t,n)}const{CustomEvent:m,document:w}=Vt,_=s&&w.getElementById(s)||null,b=e=>it(_,i||a,e,!0,m),E=wt(Vt,Xt,h);let k=\"\";return((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}`,ft(r,e));t.registerJSModule(n,s,r)})(a,d,f,E),d.registerJSModule(f,\"polyscript\",{xworker:Qt,currentScript:_,js_modules:E,get target(){return!k&&_&&(\"SCRIPT\"===o?_.after(Qe(w.createElement(`script-${i||a}`),{id:k=`${s}-target`})):(k=s,_.replaceChildren(),_.style.display=\"block\")),k}}),qt=d.runEvent.bind(d,f),Gt=d.transform.bind(d,f),_&&b(\"ready\"),r?.onReady&&ct(r?.onReady).call(d,Bt.call(d,g,f),Qt),await d[y](f,n),_&&b(\"done\"),f}catch(e){postMessage(e)}})(),Kt(\"error\"),Kt(\"message\"),Kt(\"messageerror\")}));\n"],{type:'application/javascript'})),{type:'module'}); |
{ | ||
"name": "polyscript", | ||
"version": "0.6.10", | ||
"version": "0.6.11", | ||
"description": "PyScript single core to rule them all", | ||
@@ -86,4 +86,4 @@ "main": "./cjs/index.js", | ||
"worker": { | ||
"blob": "sha256-i90tEVanhmmwEz+mU1PW8KkH5hVhi6Pp56j4Pfycepk=" | ||
"blob": "sha256-NQG5tdwaYJm7GRn5Svs9tqF5lQoMbroGkZdOpa+AZ/c=" | ||
} | ||
} |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
20
487445
84
3540
5