@volter/browser-substrate 0.1.100 → 0.1.102

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,18 @@
1
- const Ns="EINSTALLREFUSED",Vn="[install-trap-record]";class Kn extends Error{request;code=Ns;constructor(e){super(eo(e)),this.request=e,this.name="InstallRefusedError"}}const Qn=Symbol.for("browser-substrate.install-recorder"),Xn=Symbol.for("browser-substrate.install-trapped");function Ms(s){const e=globalThis;throw(e[Xn]??=[]).push(s),e[Qn]?.(s),console.error(`[install-trap] ${s.door}: ${s.subject}`),console.info(`${Vn} ${JSON.stringify(s)}`),new Kn(s)}function Zn(s){return typeof s!="object"||s===null?!1:s.code===Ns?!0:/^REFUSED \([^)]+\): /u.test(String(s.message??""))}function eo(s){return[`REFUSED (${s.door}): ${s.subject}`,"","The tab never installs, downloads, extracts or builds a dependency, and never runs a setup step. Everything a","project uses reaches it prepared, with the image or from the catalog, and this was not. Nothing was attempted.","",...s.fix?[`To fix it: ${s.fix}`]:["To fix it, prepare the image again on a machine, from the project's folder:",""," npx @volter/browser-substrate dev"]].join(`
2
- `)}const Fs=2019846480,Vt=6,oe=6,rt=3,Ht=0,ut=1,Pe=2,Ls=3,$s=4,Rs=5,Bs=0,Ds=1,Cs=2,Jt=1,zs=2,Us=4,Gt=32,br=3,kr=["file","directory","symlink"],to=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,ro=new TextEncoder,so=new TextDecoder;function js(s){let e=2166136261;for(let t=0;t<s.length;t+=1)e^=s.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function os(s,e){const t=[...s.keys()];for(const x of t)if(to.test(x))throw new Error("A path in the store is not well-formed UTF-16.");const o=new Map;for(let x=0;x<t.length;x+=1)o.set(t[x],x);for(const x of e.keys())o.has(x)||(o.set(x,t.length),t.push(x));const a=t.length,d=new Map,f=new Uint32Array(a);let h=0;for(let x=0;x<a;x+=1){const A=t[x];let D=!0;for(let H=0;H<A.length;H+=1)if(A.charCodeAt(H)>=128){D=!1;break}D||d.set(x,ro.encode(A)),f[x]=D?A.length:d.get(x).length,h+=f[x]}let m=0;for(const x of e.values())m+=x.size;let w=1;for(;w<a*2;)w<<=1;const b=Vt*4,k=Er(b+a*oe*4,8),P=k+a*rt*8,F=P+w*4,g=F+m*4,U=new SharedArrayBuffer(Er(g+h,8));new Uint32Array(U,0,Vt).set([Fs,a,w,m,h,s.size]);const G=new Uint32Array(U,b,a*oe),j=new Float64Array(U,k,a*rt),_e=new Uint32Array(U,P,w),T=new Uint32Array(U,F,m),R=new Uint8Array(U,g,h);let L=0,S=0;for(let x=0;x<a;x+=1){const A=t[x],D=x*oe,H=d.get(x);if(H)R.set(H,L);else for(let N=0;N<A.length;N+=1)R[L+N]=A.charCodeAt(N);const v=f[x];G[D+Ht]=L,G[D+ut]=v,L+=v;let K=H?0:Gt;const te=s.get(A);if(te){K|=Jt|kr.indexOf(te.type)<<br,te.pack&&(K|=Us),G[D+Ls]=te.mode;const N=x*rt;j[N+Bs]=te.mtimeMs,j[N+Ds]=te.offset,j[N+Cs]=te.length}const ve=e.get(A);if(ve){K|=zs,G[D+$s]=S,G[D+Rs]=ve.size;for(const N of ve){const B=o.get(`${A}/${N}`);if(B===void 0)throw new Error(`The store's children name ${A}/${N}, which its index does not hold.`);T[S++]=B}}G[D+Pe]=K;let ge=js(A)&w-1;for(;_e[ge]!==0;)ge=ge+1&w-1;_e[ge]=x+1}if(S!==m)throw new Error("The shared index's children did not add up.");return U}function Er(s,e){return Math.ceil(s/e)*e}class Re{buffer;count;entryCount;records;numbers;table;childList;strings;mask;constructor(e){const t=new Uint32Array(e,0,Vt);if(t[0]!==Fs)throw new Error("Not a shared store index.");const[,o,a,d,f,h]=t;this.buffer=e,this.count=o,this.entryCount=h;const m=Vt*4,w=Er(m+o*oe*4,8),b=w+o*rt*8,k=b+a*4,P=k+d*4;this.records=new Uint32Array(e,m,o*oe),this.numbers=new Float64Array(e,w,o*rt),this.table=new Uint32Array(e,b,a),this.childList=new Uint32Array(e,k,d),this.strings=new Uint8Array(e,P,f),this.mask=a-1}find(e){let t=js(e)&this.mask;for(;;){const o=this.table[t];if(o===0)return-1;if(this.pathIs(o-1,e))return o-1;t=t+1&this.mask}}entry(e){const t=e*oe,o=this.records[t+Pe];if(!(o&Jt))return;const a=e*rt,d={type:kr[o>>>br&3],mode:this.records[t+Ls],mtimeMs:this.numbers[a+Bs],offset:this.numbers[a+Ds],length:this.numbers[a+Cs]};return o&Us&&(d.pack="packages"),d}typeAt(e){const t=this.records[e*oe+Pe];return t&Jt?kr[t>>>br&3]:void 0}hasEntry(e){return(this.records[e*oe+Pe]&Jt)!==0}childNames(e){const t=e*oe;if(!(this.records[t+Pe]&zs))return;const o=this.records[t+$s],a=this.records[t+ut]+1,d=[];for(let f=0;f<this.records[t+Rs];f+=1){const h=this.childList[o+f]*oe;d.push(this.decode(this.records[h+Ht]+a,this.records[h+ut]-a,(this.records[h+Pe]&Gt)!==0))}return d}path(e){const t=e*oe;return this.decode(this.records[t+Ht],this.records[t+ut],(this.records[t+Pe]&Gt)!==0)}decode(e,t,o){if(!o)return so.decode(this.strings.slice(e,e+t));let a="";for(let d=e,f=e+t;d<f;d+=4096)a+=String.fromCharCode.apply(null,this.strings.subarray(d,Math.min(f,d+4096)));return a}pathIs(e,t){const o=e*oe,a=this.records[o+Ht],d=this.records[o+ut];if(!(this.records[o+Pe]&Gt))return this.path(e)===t;if(d!==t.length)return!1;for(let f=0;f<d;f+=1)if(this.strings[a+f]!==t.charCodeAt(f))return!1;return!0}}const le=Symbol("deleted");function qs(s,e){return s===e||!!s&&!!e&&s.type===e.type&&s.offset===e.offset&&s.length===e.length&&s.pack===e.pack&&s.mode===e.mode&&s.mtimeMs===e.mtimeMs&&s.capacity===e.capacity}class Ke{base;overlay=new Map;delta=0;constructor(e){this.base=e}get[Symbol.toStringTag](){return"Map"}get size(){return this.base.entryCount+this.delta}get(e){const t=this.overlay.get(e);if(t!==void 0)return t===le?void 0:t;const o=this.base.find(e);return o<0?void 0:this.base.entry(o)}typeOf(e){const t=this.overlay.get(e);if(t!==void 0)return t===le?void 0:t.type;const o=this.base.find(e);return o<0?void 0:this.base.typeAt(o)}has(e){const t=this.overlay.get(e);if(t!==void 0)return t!==le;const o=this.base.find(e);return o>=0&&this.base.hasEntry(o)}set(e,t){this.has(e)||(this.delta+=1);const o=this.base.find(e);return o>=0&&qs(this.base.entry(o),t)?this.overlay.delete(e):this.overlay.set(e,t),this}delete(e){if(!this.has(e))return!1;const t=this.base.find(e);return t>=0&&this.base.hasEntry(t)?this.overlay.set(e,le):this.overlay.delete(e),this.delta-=1,!0}clear(){throw new Error("A reader's index is not cleared; it is replaced.")}*entries(){for(const[e,t]of this.overlay)t!==le&&(yield[e,t]);for(let e=0;e<this.base.count;e+=1){if(!this.base.hasEntry(e))continue;const t=this.base.path(e);this.overlay.has(t)||(yield[t,this.base.entry(e)])}}*keys(){for(const[e]of this.entries())yield e}*values(){for(const[,e]of this.entries())yield e}[Symbol.iterator](){return this.entries()}forEach(e,t){for(const[o,a]of this.entries())e.call(t,a,o,this)}*changed(){for(const[e,t]of this.overlay)t!==le&&(yield[e,t])}*changes(){for(const[e,t]of this.overlay)yield[e,t===le?null:t]}get overlaid(){return this.overlay.size}boundedChanges(){if(this.overlay.size>65536)return;const e=[];let t=0;for(const[o,a]of this.changes()){if(t+=o.length*2+128,t>8*1024*1024)return;e.push([o,a])}return e}}class $t{base;overlay=new Map;constructor(e){this.base=e}get(e){const t=this.overlay.get(e);if(t!==void 0)return t===le?void 0:t;const o=this.base.find(e),a=o<0?void 0:this.base.childNames(o);return a?new Set(a):void 0}mutable(e){const t=this.overlay.get(e);if(t!==void 0&&t!==le)return t;const o=new Set(t===le?[]:this.get(e)??[]);return this.overlay.set(e,o),o}delete(e){this.overlay.set(e,le)}}const no="supercode-browser-filesystems",xe="packages",oo="state.json",is="/image-range-worker.js",as="image-ranges.json",io=2;function ur(s){const e=s;if(!e||e.version!==1||!Number.isSafeInteger(e.bytes)||e.bytes<0||!Array.isArray(e.parts)||e.image!==void 0&&(typeof e.image!="string"||!/^[a-f0-9]{16,64}$/u.test(e.image))||e.parts.length>1e5)throw new Error("Invalid immutable image ranges.");let t=0;for(const o of e.parts){if(!o||o.offset!==t||!Number.isSafeInteger(o.raw)||o.raw<0||!Number.isSafeInteger(o.bytes)||o.bytes<0||o.bytes>1024*1024*1024||o.raw>1024*1024*1024||typeof o.sha256!="string"||!/^[a-f0-9]{64}$/u.test(o.sha256)||typeof o.url!="string"||!/^\/substrate\/[A-Za-z0-9._/-]+$/u.test(o.url)||o.url.split("/").some(a=>a==="."||a===".."))throw new Error("Invalid immutable image part.");if(t+=o.raw,!Number.isSafeInteger(t))throw new Error("Immutable image ranges exceed the offset limit.")}if(t!==e.bytes)throw new Error("Immutable image ranges do not cover their reservation.");return e}class ao{ranges;directory;identity;receiptKey;client;worker;port;prefetchers=[];state;completed;firstRead;closed=!1;ready=!1;startup;cancelStartup;sharedCompletion;blocked={ranges:0,ms:0};constructor(e,t,o,a,d,f){if(this.ranges=e,this.directory=t,this.identity=o,this.receiptKey=d,this.client=f,typeof Worker>"u"||typeof SharedArrayBuffer>"u")throw new Error("This browser cannot materialize an immutable image during a synchronous read.");if(this.state=new Int32Array(f?.state??new SharedArrayBuffer(e.parts.length*Int32Array.BYTES_PER_ELEMENT)),this.state.length!==e.parts.length)throw new Error("The image reader's line has the wrong range count.");const h=e.parts.length,m=a??new SharedArrayBuffer((2*h+1)*Int32Array.BYTES_PER_ELEMENT);if(m.byteLength!==h*Int32Array.BYTES_PER_ELEMENT&&m.byteLength!==(2*h+1)*Int32Array.BYTES_PER_ELEMENT)throw new Error("The image completion seed has the wrong range count.");this.completed=new Int32Array(m,0,h),this.firstRead=m.byteLength>h*Int32Array.BYTES_PER_ELEMENT?new Int32Array(m,h*Int32Array.BYTES_PER_ELEMENT,h+1):void 0,this.sharedCompletion=a!==void 0;for(const w of e.parts)Object.freeze(w);Object.freeze(e.parts),Object.freeze(e)}get completionBuffer(){return this.completed.buffer}get verifiedRanges(){return this.ranges}async initialize(){if(this.closed)throw new Error("This immutable image reader is closed.");if(this.ready)return;if(this.startup)return this.startup;let e=!1;for(let t=0;t<this.completed.length;t+=1)if(Atomics.load(this.completed,t)!==2){e=!0;break}if(!e){this.ready=!0,this.client?.port.close();return}if(this.client){const t=this.port=this.client.port;t.onmessage=o=>{o.data?.type!=="closing"||this.port!==t||(t.close(),this.port=void 0,this.closed||this.startMaterializer().catch(a=>console.warn("This process's image reader could not start its own materializer after its line closed.",a)))},t.start(),this.ready=!0;return}return this.startMaterializer()}startMaterializer(){const e=Date.now(),t=new Worker(is,{type:"module",name:"immutable-image-materializer"}),o=this.ready;return o||(this.worker=t),t.addEventListener("error",()=>this.fail()),t.addEventListener("messageerror",()=>this.fail()),this.startup=new Promise((a,d)=>{const f=()=>{clearTimeout(b),t.removeEventListener("message",w),t.removeEventListener("error",h),t.removeEventListener("messageerror",h),this.cancelStartup=void 0},h=()=>m(new Error("The immutable image materializer could not initialize; reload to retry.")),m=k=>{f(),t.terminate(),o||(this.closed=!0,this.fail()),d(k)},w=k=>{if(k.data?.identity===this.identity){if(k.data.type==="init-error"){m(new Error(`The immutable image materializer could not initialize: ${String(k.data.error)}`));return}k.data.type==="ready"&&(console.log(`[boot-trace] ${JSON.stringify({event:"materializer-ready",at:Date.now(),ms:Date.now()-e})}`),f(),this.ready=!0,this.worker=t,a())}},b=setTimeout(()=>m(new Error("The immutable image materializer did not initialize within 10 seconds; reload to retry.")),1e4);this.cancelStartup=m,t.addEventListener("message",w),t.addEventListener("error",h),t.addEventListener("messageerror",h);try{t.postMessage({type:"init",ranges:this.ranges,directory:this.directory,identity:this.identity,state:this.state.buffer,completed:this.completed.buffer,sharedCompletion:this.sharedCompletion,...this.receiptKey?{receiptKey:this.receiptKey}:{}})}catch(k){m(k instanceof Error?k:new Error(String(k)))}}),this.startup}readDigests(){const e=this.firstRead;if(!e)return;const t=this.ranges.parts.length,o=[];for(let a=0;a<t;a+=1){const d=Atomics.load(e,a),f=this.ranges.parts[a];d>0&&f.raw>0&&o.push([d,f.sha256])}return o.sort((a,d)=>a[0]-d[0]).map(([,a])=>a)}completedDigests(){const e=[];for(let t=0;t<this.completed.length;t+=1){const o=this.ranges.parts[t];o.raw>0&&Atomics.load(this.completed,t)===2&&e.push(o.sha256)}return e}prefetch(e,t=[]){if(this.closed||!this.ready||!this.worker)return{queued:0,done:Promise.resolve()};const o=new Map;for(let h=0;h<this.ranges.parts.length;h+=1){const m=this.ranges.parts[h];if(m.raw===0)continue;const w=o.get(m.sha256);w?w.push(h):o.set(m.sha256,[h])}const a=[];for(const h of new Set(e))for(const m of o.get(h)??[])Atomics.load(this.completed,m)!==2&&a.push(m);const d=t.length>0&&a.length>0?Math.min(t.length,8):Math.min(io,Math.ceil(a.length/32)),f=[];for(let h=0;h<d;h+=1){const m=a.filter((P,F)=>F%d===h),w=new Worker(is,{type:"module",name:"immutable-image-prefetch"});this.prefetchers.push(w);let b;f.push(new Promise(P=>{b=P}));const k=()=>{w.terminate(),this.prefetchers=this.prefetchers.filter(P=>P!==w),b()};w.addEventListener("error",k),w.addEventListener("messageerror",k),w.addEventListener("message",P=>{P.data?.identity===this.identity&&(P.data.type==="ready"?w.postMessage(t.length>0?{type:"prefetch-stream",url:t[h]}:{type:"prefetch",indices:m}):(P.data.type==="prefetched"||P.data.type==="init-error")&&k())}),w.postMessage({type:"init",ranges:this.ranges,directory:this.directory,identity:this.identity,state:new SharedArrayBuffer(this.state.byteLength),completed:this.completed.buffer,sharedCompletion:!0,...this.receiptKey?{receiptKey:this.receiptKey}:{}})}return{queued:a.length,done:Promise.all(f).then(()=>{})}}get blockedReads(){return{...this.blocked}}ensure(e,t){if(this.closed)throw new Error("This immutable image reader is closed.");if(!this.ready)throw new Error("This immutable image reader has not finished asynchronous initialization.");if(t===0||e>=this.ranges.bytes)return;const o=Math.min(e+t,this.ranges.bytes);let a=0,d=this.ranges.parts.length;for(;a<d;){const f=a+d>>>1,h=this.ranges.parts[f];h.offset+h.raw<=e?a=f+1:d=f}for(let f=a;f<this.ranges.parts.length;f+=1){const h=this.ranges.parts[f];if(h.offset>=o)break;const m=this.firstRead;if(m&&Atomics.load(m,f)===0&&Atomics.compareExchange(m,f,0,Atomics.add(m,this.ranges.parts.length,1)+1),Atomics.load(this.completed,f)===2)continue;const w=this.worker??this.port;if(!w)throw new Error("This immutable image reader's line closed and its own materializer is still starting; retry the read.");w.postMessage({type:"read",index:f});const b=performance.now(),k=b+3e4;for(;Atomics.load(this.state,f)===0;){const P=k-performance.now();if(P<=0||Atomics.wait(this.state,f,0,P)==="timed-out")throw this.close(),new Error(`The image's immutable part ${h.url} did not arrive within 30 seconds; reload to retry.`)}if(this.blocked.ranges+=1,this.blocked.ms+=performance.now()-b,Atomics.load(this.state,f)!==2)throw new Error(`The image's immutable part ${h.url} could not be verified or stored; see the worker error and reload to retry.`)}}lineForReader(){const e=this.worker??this.port;if(this.closed||!this.ready||!e)return;const t=new MessageChannel,o=new SharedArrayBuffer(this.ranges.parts.length*Int32Array.BYTES_PER_ELEMENT);return e.postMessage({type:"client",port:t.port1,state:o},[t.port1]),{port:t.port2,state:o}}fail(){for(let e=0;e<this.state.length;e+=1)Atomics.compareExchange(this.state,e,0,-1)===0&&Atomics.notify(this.state,e)}close(){if(this.closed)return;if(this.closed=!0,this.cancelStartup){this.cancelStartup(new Error("This immutable image reader closed during initialization."));return}this.fail(),this.port?.close();const e=this.worker;e&&(e.postMessage({type:"closing"}),setTimeout(()=>e.terminate(),250));for(const t of this.prefetchers)t.dispatchEvent(new Event("error"));this.prefetchers=[]}}const pr="/packages",Rt="supercode-browser-packages",Be=new TextEncoder,Qe=new TextDecoder("utf-8",{fatal:!0}),co=no,Bt="generations",cs="atomic-staging",Xe=oo,de="index.json",hr="index-log.bin",Ze="pack.bin",Dt=8,ls=64*1024*1024,ne=1024*1024*1024,ds=4*1024*1024*1024,lo=["/workspace","/home","/opt"],De=0,fs=1,wr=1e6,us=8*1024*1024,ps=250,fo=64*1024*1024,uo=256*1024*1024,hs=4*1024*1024,et=493,Ct=420;function ws(s,e={}){const t=e.limits?.maxBytes??ds,o=e.limits?.maxEntries??wr;if(!Number.isSafeInteger(t)||t<1||t>ds||!Number.isSafeInteger(o)||o<1||o>wr)throw new Error("Invalid OPFS workspace limits.");let a,d=!1,f=!1,h=!1,m,w=0,b=0,k,P,F,g=new Map,U=new zt,$,G,j,_e,T,R,L=0,S,x=0;const A=new Map,D=256*1024,H=32;let v=0,K,te=-1/0,ve=0,ge=0,N=0,B=0,Q=0,Ie=0,Oe=0,ae,mt,fe,qe=!1,nt,Tr=Promise.resolve(),We=0,Y=!1,He=!1,V,Te=0,ue=!1;function yt(){if(!(!V||ue)){if(N>2147483647){_t();return}Atomics.store(V,fs,N)}}function _t(){!V||ue||(ue=!0,(Atomics.load(V,De)&1)===0&&Atomics.add(V,De,1))}function ot(){Te+=1,Te===1&&V&&!ue&&Atomics.add(V,De,1)}function it(){Te-=1,!(Te>0||!V||ue)&&(yt(),ue||Atomics.add(V,De,1))}function Nr(){if(f)throw new Error("A store open for reading follows its owner's clock; it has none of its own.");return V||(V=new Int32Array(new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT)),V[De]=Te>0||ue?1:0,yt()),V.buffer}let re;const cn=8*1024*1024;let Mr=!1;function ln(r){if(f||!V||!F||qe||Te>0||ue||Y)return;const n=Atomics.load(V,De);if(n&1)return;if(r?.overlays&&g instanceof Ke){const l=g.boundedChanges();if(l)return Zt({generation:F,index:g.base.buffer,changes:l,packBytes:v,logBytes:N,epoch:n,liveBytes:B,linked:w,linkedBytes:b})}if(re&&re.generation===F&&re.epoch===n&&N>=re.logBytes&&N-re.logBytes<=(r?.current?0:cn))return Zt(re);let i;try{i=os(g,un())}catch(l){console.warn(`[pack-store] no reader seed: ${l instanceof Error?l.message:String(l)}`);return}return re={generation:F,index:i,packBytes:v,logBytes:N,epoch:n,liveBytes:B,linked:w,linkedBytes:b},fn(i),Zt(re)}function Zt(r){const n=e.packages?.imageCompletionSeed();return n?{...r,packagesImage:n}:r}function dn(){if(!(!j||!G||!F||qe||Te>0||Y))return{generation:F,rangesDigest:G,completed:j.completionBuffer,...j.receiptKey?{metadata:{ranges:j.verifiedRanges,receiptKey:j.receiptKey}}:{}}}function fn(r){const n=[];if(g instanceof Ke)for(const[l,c]of g.changed())c.capacity!==void 0&&n.push([l,c]);else for(const[l,c]of g)c.capacity!==void 0&&n.push([l,c]);const i=new Re(r);g=new Ke(i),U=new $t(i);for(const[l,c]of n)g.set(l,c)}function un(){if(U instanceof zt)return U.map;const r=new Map;for(const n of g.keys()){const i=Le(n);if(i===n)continue;let l=r.get(i);l||(l=new Set,r.set(i,l)),l.add(n.slice(i.length+1))}return r}function pn(){!f||h||Y||!S||St(N)}async function gt(r){if(Y)throw new Error("This OPFS workspace is closing.");We+=1;let n,i=!1;try{return await r()}catch(l){throw i=!0,n=l,l}finally{if(We-=1,Y&&We===0)try{rs()}catch(l){throw i?new AggregateError([n,l],"OPFS operation and deferred close both failed."):l}}}async function bt(r){return be(),We!==0?Promise.reject(new Error("Wait for the current OPFS storage operation before replacing its generation.")):(He=!0,gt(async()=>{try{return await r()}finally{He=!1}}))}function hn(r){if(Y)throw new Error("This OPFS workspace is closing.");const n=g.get(r);if(!n||n.type==="directory")throw new Error(`OPFS workspace file does not exist: ${r}`);return kt(n)}function wn(r,n,i){if(Y)throw new Error("This OPFS workspace is closing.");const l=g.get(r);if(!l||l.type==="directory")throw new Error(`OPFS workspace file does not exist: ${r}`);const c=Math.min(Math.max(0,n),l.length),u=Math.min(Math.max(0,i),l.length-c);if(l.pack){const p=e.packages;if(!p)throw new Error("This store has no shared package store to read from.");return p.readExtent(l.offset+c,u)}return Et(l.offset+c,u)}function kt(r){if(r.pack){const n=e.packages;if(!n)throw new Error("This store has no shared package store to read from.");return n.readExtent(r.offset,r.length)}return Et(r.offset,r.length)}function Et(r,n){if(Y)throw new Error("This OPFS workspace is closing.");const i=$;if(!i)throw new Error("OPFS filesystem worker is not initialized.");const l=new Uint8Array(n);if(n>0&&n<=D&&r>=0&&r+n<=x){let c=0;for(;c<n;){const u=r+c,p=Math.floor(u/D)*D;let y=A.get(p);if(!y&&(y=new Uint8Array(Math.min(D,x-p)),j?.ensure(p,y.byteLength),i.read(y,{at:p})!==y.byteLength))throw new Error("An OPFS package range could not be read completely.");A.delete(p),A.set(p,y),A.size>H&&A.delete(A.keys().next().value);const _=u-p,E=Math.min(n-c,y.byteLength-_);l.set(y.subarray(_,_+E),c),c+=E}return l}if(j?.ensure(r,n),n>0&&i.read(l,{at:r})!==n)throw new Error("An OPFS workspace file could not be read completely.");return l}async function mn(r,n={}){if(Y&&a||!a&&We!==0)throw new Error("Wait for this OPFS workspace to finish closing before opening it again.");if(qe)throw new Error("This OPFS store is already opening a workspace.");if(a){if(P!==$r(r))throw new Error("Close this OPFS store before opening another workspace.");return g.size>0}qe=!0,Y=!1;const i=new AbortController;nt=i;try{g=new Map,U=new zt,F=void 0,G=void 0,m=void 0,ae=void 0,fe=void 0,v=N=B=Q=w=b=0,he=void 0,Ie=Oe=ve=ge=0,te=-1/0,P=$r(r),f=n.readOnly===!0,T=f?n.imageCompletion:void 0,R=f?n.imageLine:void 0,h=f&&n.extentsOnly===!0,d=n.shared===!0||f,d||await kn(i.signal),i.signal.throwIfAborted();const l=await _n();i.signal.throwIfAborted();try{const p=await l.getDirectoryHandle(co,{create:!f});i.signal.throwIfAborted(),a=await p.getDirectoryHandle(P,{create:!f})}catch(p){if(i.signal.throwIfAborted(),f&&Ve(p))return!1;throw p}i.signal.throwIfAborted();let c=Ft(await Fe(a,Xe));if(i.signal.throwIfAborted(),!c&&f)return await tr(),!1;if(!c&&d&&(await s.navigator.locks.request(Rt,{mode:"exclusive",signal:i.signal},async()=>{i.signal.throwIfAborted(),c=Ft(await Fe(a,Xe)),i.signal.throwIfAborted(),c||(await tr(),await qr({files:[],pack:new ArrayBuffer(0)}),await wo(a))}),i.signal.throwIfAborted(),!c))return m=await pe(F,!1),i.signal.throwIfAborted(),!1;if(!c)return await tr(),i.signal.throwIfAborted(),!1;const u=async p=>{let y;try{y=await pe(p.generation,!1)}catch(O){throw i.signal.throwIfAborted(),Ve(O)?new Error("The committed OPFS workspace generation is missing. Stored generations were retained.",{cause:O}):O}if(i.signal.throwIfAborted(),F=p.generation,L=p.initializedAt,G=p.imageRanges,m=y,h)return P===xe&&s.navigator.locks?await s.navigator.locks.request(Rt,{mode:"shared",signal:i.signal},async()=>{await Je(y),x=$.getSize()}):await Je(y),i.signal.throwIfAborted(),!0;const _=f?n.seed:void 0;if(_&&_.generation===p.generation){const O=new Re(_.index);return g=new Ke(O),U=new $t(O),v=_.packBytes,_.changes&&Lr({packBytes:_.packBytes,changes:_.changes}),await Je(y),i.signal.throwIfAborted(),N=_.logBytes,{liveBytes:B,linked:w,linkedBytes:b}=_,Q=Math.max(0,v-B),Mr=!0,g.size>0}const E=f?void 0:await Un(y);if(i.signal.throwIfAborted(),E){const O=new Re(E.index);g=new Ke(O),U=new $t(O),{packBytes:v,liveBytes:B,linked:w,linkedBytes:b}=E;const I=Atomics.load(new Int32Array(Nr()),De);re={generation:F,index:E.index,packBytes:v,liveBytes:B,linked:w,linkedBytes:b,logBytes:0,epoch:I}}else g=lr(await Fe(y,de)),i.signal.throwIfAborted(),Ye(),v=er(g);await Je(y),i.signal.throwIfAborted();const M=E?await jn(E):0;return i.signal.throwIfAborted(),M&&(he={generation:F,bytes:M},re&&(re.logBytes=M)),St(M,!!E),E?Q=Math.max(0,v-B):at(),Ur(),d&&!f&&!E&&g.size>=1e4&&(Ee(),await dt(y,g,{access:S,bytes:N,packBytes:v})),d||($.truncate(v),await Gr(a,cs,!0),await rr(F),i.signal.throwIfAborted(),Q>fo&&Q>B&&await Nn()),i.signal.throwIfAborted(),g.size>0};return d&&!f?await s.navigator.locks.request(Rt,{mode:"exclusive",signal:i.signal},async()=>{if(c=Ft(await Fe(a,Xe)),!c)throw new Error("The committed package store state is missing. Stored data was retained.");return u(c)}):await u(c)}catch(l){const c=[l];try{Ge()}catch(u){c.push(u)}try{k?.()}catch(u){c.push(u)}throw k=void 0,a=void 0,c.length>1?new AggregateError(c,"OPFS workspace open and cleanup failed."):l}finally{qe=!1,nt=void 0}}function yn(r){return gt(()=>Fr(r?.whole===!0))}async function Fr(r=!1){if(h)throw new Error("A store opened for its extents alone has no index to follow.");if(f&&a){const u=Ft(await Fe(a,Xe));if(!u)throw new Error("The committed OPFS workspace state is missing. Stored data was retained.");if(u.generation!==F||r){const p=await pe(u.generation,!1),y=lr(await Fe(p,de));v=er(y),u.generation!==F&&(F=u.generation,L=u.initializedAt,G=u.imageRanges,await Je(p)),F=u.generation,m=p,g=y,Ye(),St(),at();return}}const n=S;if(!n||!m)return;const i=n.getSize();let l=!1;i<N&&(g=lr(await Fe(m,de)),Ye(),v=er(g),N=0,l=!0);const c=N;St(N),(l||N!==c)&&at()}async function _n(){let r;for(let n=0;n<10;n+=1){nt?.signal.throwIfAborted();try{return await s.navigator.storage.getDirectory()}catch(i){r=i,await new Promise(l=>setTimeout(l,200))}}throw r instanceof Error?r:new Error("This browser workspace's storage is unavailable.")}const gn=1e4;async function Z(r,n){let i;const l=nt?.signal;for(let u=0;u<2;u+=1){l?.throwIfAborted();const p=r.createSyncAccessHandle({mode:"readwrite-unsafe"});let y,_,E=!1;try{const M=new Promise((I,q)=>{_=()=>q(l?.reason??new DOMException("Workspace open was cancelled.","AbortError")),l?.addEventListener("abort",_,{once:!0}),l?.aborted&&_()}),O=await Promise.race([p.then(I=>({access:I})).catch(I=>{i=I}),new Promise(I=>{y=setTimeout(()=>I(void 0),gn)}),M]);if(l?.throwIfAborted(),O)return E=!0,O.access}finally{y!==void 0&&clearTimeout(y),_&&l?.removeEventListener("abort",_),E||p.then(M=>M.close(),()=>{}).catch(M=>console.error("Late workspace handle cleanup failed.",M))}if(i instanceof TypeError)throw new Error(`This browser cannot share a workspace's files between pages: its file access handles have no readwrite-unsafe mode (Chrome 121 or newer has one). ${i.message}`);await new Promise(M=>setTimeout(M,500))}const c=i instanceof Error?` (${i.message})`:"";throw new Error(`This browser workspace's ${n} is held by another page${c}.`)}async function Je(r){Ge();const n=await r.getFileHandle(Ze);$=await Z(n,"store");try{if($.getSize()<v)throw new Error("The committed OPFS workspace pack is incomplete. Stored data was retained.");const i=await r.getFileHandle(hr);if(S=await Z(i,"record of changes"),N=S.getSize(),G){const l=T,c=l&&l.generation===F&&l.rangesDigest===G?l:void 0;let u,p;if(c?.metadata){if(u=ur(c.metadata.ranges),p=c.metadata.receiptKey,!/^[a-f0-9]{64}$/u.test(p))throw new Error("The owner's immutable receipt key is invalid.")}else{const _=await(await r.getFileHandle(as)).getFile(),E=new Uint8Array(await _.arrayBuffer());if(await me(E)!==G)throw new Error("The committed immutable image ranges have changed. Stored data was retained.");u=ur(JSON.parse(Qe.decode(E))),p=await me(Be.encode(JSON.stringify(u)))}if(u.bytes>$.getSize())throw new Error("The immutable image reservation is incomplete. Stored data was retained.");const y=c?R:void 0;y||R?.port.close(),R=void 0,j=new ao(u,r,`${P}.${F}`,c?.completed,p,y),await j.initialize(),_e=u.image}}catch(i){throw Ge(),i}}function Ge(){j?.close(),j=void 0,_e=void 0;const r=$,n=S;$=void 0,S=void 0,N=0,x=0,A.clear();try{r?.close()}finally{n?.close()}}function St(r=0,n=!1){const i=S;if(!i)throw new Error("OPFS filesystem worker is not initialized.");const l=i.getSize();if(l<=r){N=l;return}const c=new Uint8Array(l-r);if(i.read(c,{at:r})!==c.byteLength)throw new Error("The OPFS workspace index log could not be read.");const u=$?.getSize()??1/0,p=new DataView(c.buffer);let y=0;const _=c.byteLength;for(;y+Dt<=_;){const E=p.getUint32(y,!0),M=p.getUint32(y+4,!0),O=y+Dt;if(E===0||E>ls||O+E>_)break;const I=c.subarray(O,O+E);if(Zr(I)!==M)break;let q;try{q=Hn(JSON.parse(Qe.decode(I)))}catch{break}if(q.packBytes>u)break;Lr(q,n),y=O+E}y!==_&&!d&&i.truncate(r+y),N=r+y}function Lr(r,n=!1){for(const[i,l]of r.changes){const c=g.get(i);if(l&&qs(c,l)){xt(i);continue}n&&(c?.pack?(w-=1,b-=c.length):c&&(B-=c.length),l?.pack?(w+=1,b+=l.length):l&&(B+=l.length)),l===null?(g.delete(i),Br(i)):(g.set(i,l),xt(i))}v=Math.max(v,r.packBytes)}function at(){B=0,w=0,b=0;for(const r of g.values())r.pack?(w+=1,b+=r.length):B+=r.length;Q=Math.max(0,v-B)}function er(r){let n=0;for(const i of r.values())i.pack||(n=Math.max(n,i.offset+i.length));return n}const bn=5e3;async function kn(r){if(!s.navigator.locks)return;if(!P)throw new Error("OPFS filesystem project is not initialized.");const n=new AbortController,i=setTimeout(()=>n.abort(),bn);try{await new Promise((l,c)=>{s.navigator.locks.request(`supercode-browser-filesystem-${P}`,{mode:"exclusive",signal:r?AbortSignal.any([r,n.signal]):n.signal},async()=>{clearTimeout(i),l(),await new Promise(u=>{k=u})}).catch(()=>c(r?.aborted?r.reason:new Error("This browser workspace is already open in another tab.")))})}finally{clearTimeout(i)}}function $r(r){if(typeof r!="string"||!/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/u.test(r))throw new Error("OPFS filesystem projectId is invalid.");return r}async function Ne(){if(!a)throw new Error("OPFS filesystem worker is not initialized.");return a}async function pe(r,n){return(await(await Ne()).getDirectoryHandle(Bt,{create:n})).getDirectoryHandle(r,{create:n})}async function tr(){let r;try{r=await(await Ne()).getDirectoryHandle(Bt)}catch(n){if(Ve(n))return;throw n}for await(const n of r.entries())throw new Error("OPFS workspace state is missing but stored generations exist. Stored data was retained.")}async function rr(r){const n=await Ne();let i;try{i=await n.getDirectoryHandle(Bt)}catch(l){if(Ve(l))return;throw l}for await(const[l]of i.entries())l!==r&&await Yr(i,l)}function be(){if(Y)throw new Error("This OPFS workspace is closing.");if(He)throw new Error("This OPFS workspace is replacing its generation; wait for that operation before writing.");if(f)throw new Error("This store is open for reading; its owner writes it.");if(fe)throw fe}async function En(r){es(r)}let sr=!1,Pt=0,he,nr=!1;function Rr(){if(Pt>0)return;const r=he&&he.generation===F&&he.bytes<=N?he.bytes:0;N-r>us&&!sr&&(sr=!0,(d?s.navigator.locks.request(Rt,{mode:"exclusive"},async()=>{if(!a||Y)return;await Fr();const i=he,l=i&&i.generation===F&&i.bytes<=N?i.bytes:0;N-l>us&&await Ot()}):Ot()).catch(i=>console.error("The workspace's log could not be checkpointed; it is replayed at the next open.",i)).finally(()=>{sr=!1})),!d&&!nr&&Q>uo&&Q>B&&(nr=!0,gt(Mn).catch(n=>console.error("The workspace could not be compacted; it keeps its generation.",n)).finally(()=>{nr=!1}))}async function Sn(r){be(),Pt+=1;try{return await r()}finally{Pt-=1,Pt===0&&!Y&&a&&Rr()}}function Pn(r,n){const i=ye(r.path);if(r.operation==="write"){if(g.get(i)?.type==="directory")throw new Error(`OPFS write target is a directory: ${i}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const c=r.content;if(c.byteLength>ne)throw new Error(`${i} is ${c.byteLength} bytes; an OPFS workspace file holds at most ${ne}.`);At(i,c.byteLength),Me(i,n);const u=It(c);ee(i,{type:r.symlink?"symlink":"file",mode:r.mode??g.get(i)?.mode??Ct,mtimeMs:r.mtimeMs??Date.now(),offset:u,length:c.byteLength},n);return}if(r.operation==="append"){const c=g.get(i);if(c&&c.type!=="file")throw new Error(`OPFS append target is not a file: ${i}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS append requires file content.");const u=r.content,p=(c?.length??0)+u.byteLength;if(p>ne)throw new Error(`${i} is ${p} bytes; an OPFS workspace file holds at most ${ne}.`);At(i,p),Me(i,n);const y=r.mode??c?.mode??Ct,_=r.mtimeMs??Date.now(),E=c&&!c.pack?c.capacity??c.length:0;if(P!==xe&&c&&!c.pack&&c.length>0&&(p<=E||c.offset+E===v)){vt(c.offset+c.length,u),ee(i,{...c,mode:y,mtimeMs:_,length:p,capacity:Math.max(E,p)},n),Q-=Math.max(c.length,c.capacity??0),Ie-=1,Oe-=c.length;return}const M=new Uint8Array(p);c&&c.length>0&&M.set(kt(c),0),M.set(u,p-u.byteLength);const O=It(M),I=Math.min(ne,Math.max(p,p*2,64*1024));I>p&&jr(O+I),ee(i,{type:"file",mode:y,mtimeMs:_,offset:O,length:p,capacity:I},n);return}if(r.operation==="write-at"){const c=g.get(i);if(c&&c.type!=="file")throw new Error(`OPFS write target is not a file: ${i}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const u=r.content,p=r.position,y=c?.length??0;if(u.byteLength===0&&c)return;const _=u.byteLength===0?y:Math.max(y,p+u.byteLength);if(_>ne)throw new Error(`${i} is ${_} bytes; an OPFS workspace file holds at most ${ne}.`);At(i,_),Me(i,n);const E=r.mode??c?.mode??Ct,M=r.mtimeMs??Date.now(),O=c&&!c.pack?c.capacity??c.length:0;if(P!==xe&&c&&!c.pack&&y>0&&(_<=O||c.offset+O===v)){if(p>y&&vt(c.offset+y,new Uint8Array(p-y)),mt&&p<y){const se=Math.min(y,p+u.byteLength);mt.push([c.offset+p,Et(c.offset+p,se-p)])}vt(c.offset+p,u),ee(i,{...c,mode:E,mtimeMs:M,length:_,capacity:Math.max(O,_)},n),_!==y&&(Q-=Math.max(c.length,c.capacity??0),Ie-=1,Oe-=c.length);return}const I=new Uint8Array(_);c&&y>0&&I.set(kt(c),0),u.byteLength>0&&I.set(u,p);const q=It(I),W=Math.min(ne,Math.max(_,_*2,64*1024));W>_&&jr(q+W),ee(i,{type:"file",mode:E,mtimeMs:M,offset:q,length:_,capacity:W},n);return}if(r.operation==="mkdir"){Me(i,n);const c=g.get(i);if(c&&c.type!=="directory")throw new Error(`OPFS path is a file: ${i}`);ee(i,{type:"directory",mode:r.mode??c?.mode??et,mtimeMs:r.mtimeMs??c?.mtimeMs??Date.now(),offset:0,length:0},n);return}if(r.operation==="remove"){ir(i,n),ke().includes(i)&&ee(i,{type:"directory",mode:et,mtimeMs:Date.now(),offset:0,length:0},n);return}if(r.operation==="link"){xn(i,zr(r.source),n);return}if(r.operation==="rename"){An(i,ye(r.destination),n);return}const l=g.get(i);if(!l)throw new Error(`OPFS metadata target does not exist: ${i}`);ee(i,{...l,mode:r.mode??l.mode,mtimeMs:r.mtimeMs??l.mtimeMs},n)}function ee(r,n,i){const l=g.get(r);ae&&!ae.has(r)&&ae.set(r,l);const c=l!==void 0&&l.type===n.type&&l.offset===n.offset&&l.length===n.length&&l.pack===n.pack;l&&!c&&(Dr(l),l.type!=="directory"&&n.type!=="directory"&&l.length>0&&!l.pack&&(Ie+=1,Oe+=l.length)),g.set(r,n),xt(r),c||(n.pack?(w+=1,b+=n.length):B+=n.length),i.push([r,n])}function xt(r){const n=Le(r);n!==r&&U.mutable(n).add(r.slice(n.length+1))}function Br(r){const n=Le(r);U.get(n)?.has(r.slice(n.length+1))&&U.mutable(n).delete(r.slice(n.length+1)),U.delete(r)}function Ye(){U=new zt;for(const r of g.keys())xt(r)}function or(r){const n=[],i=l=>{const c=g.get(l);if(!c)return;n.push([l,c]);const u=U.get(l);if(u)for(const p of u)i(`${l}/${p}`)};return i(r),n}function Dr(r,n){if(r.pack){w-=1,b-=r.length;return}B-=r.length,Q+=Math.max(r.length,r.capacity??0)}function Cr(r,n){const i=g.get(r);i&&(ae&&!ae.has(r)&&ae.set(r,i),g.delete(r),Br(r),Dr(i),n.push([r,null]))}function xn(r,n,i){const l=e.packages;if(!l)throw new Error("This store has no shared package store to link from.");const c=zr(n),u=l.descendants(c);if(u.length===0)throw new Error(`The shared package store does not hold ${n}.`);Me(r,i),ir(r,i),we(g.size+u.length);for(const[p,y]of u){const _=p===c?r:`${r}${p.slice(c.length)}`;ee(_,y.type==="directory"?{type:"directory",mode:y.mode,mtimeMs:y.mtimeMs,offset:0,length:0}:{type:y.type,mode:y.mode,mtimeMs:y.mtimeMs,offset:y.offset,length:y.length,pack:xe},i)}}function Me(r,n){const i=Le(r);if(i!==r&&g.get(i)?.type==="directory"){we(g.size+(g.has(r)?0:1));return}const l=[];let c=ct(r)??ke()[0];if(g.has(c)||l.push(c),r!==c)for(const p of dr(Qr(Le(r)))){c=`${c}/${p}`;const y=g.get(c);if(y&&y.type!=="directory")throw new Error(`OPFS path parent is a file: ${c}`);y||l.push(c)}we(g.size+l.length+(g.has(r)?0:1));const u=Date.now();for(const p of l)ee(p,{type:"directory",mode:et,mtimeMs:u,offset:0,length:0},n)}function ir(r,n){for(const[i]of or(r))Cr(i,n)}function An(r,n,i){if(r===n)return;if(n.startsWith(`${r}/`))throw new Error("An OPFS rename cannot move a directory into itself.");const l=or(r);if(l.length===0){if(g.has(n))return;throw new Error(`OPFS rename source does not exist: ${r}`)}Me(n,i),ir(n,i);for(const[c]of l)Cr(c,i);for(const[c,u]of l)ee(`${n}${c.slice(r.length)}`,u,i);we(g.size)}function zr(r){if(typeof r!="string"||!r.startsWith(`${pr}/`)||r.includes("\0")||r.length>4096)throw new Error("Invalid shared store path.");return dr(r.slice(pr.length+1)),r}function ke(){return P===xe?[pr]:lo}function ct(r){return ke().find(n=>r===n||r.startsWith(`${n}/`))}function At(r,n){const i=g.get(r),l=i&&!i.pack?i.length:0;if(B-l+n>t)throw new Error(`OPFS workspace exceeds its byte limit: writing ${r} (${n} bytes) would take the project's own files past ${t} bytes.`)}function we(r){if(r>o)throw new Error("OPFS workspace exceeds its entry limit.")}function Ur(){if(we(g.size),B>t)throw new Error(`OPFS workspace exceeds its byte limit: the project's own files hold ${B} bytes, past ${t}.`)}function vt(r,n){const i=$;if(!i)throw new Error("OPFS filesystem worker is not initialized.");let l=0;for(;l<n.byteLength;){const c=i.write(n.subarray(l),{at:r+l});if(c<=0)throw new Error("An OPFS workspace file could not be written completely.");l+=c}v=Math.max(v,r+n.byteLength)}function jr(r){const n=$;if(!n)throw new Error("OPFS filesystem worker is not initialized.");r<=v||(n.truncate(r),v=r)}function It(r){const n=$;if(!n)throw new Error("OPFS filesystem worker is not initialized.");const i=v;let l=0;for(;l<r.byteLength;){const c=n.write(r.subarray(l),{at:i+l});if(c<=0)throw new Error("An OPFS workspace file could not be written completely.");l+=c}return v=i+r.byteLength,i}function vn(r){const n=$;if(n.getSize()>=v&&r.getSize()>=N)return;n.flush(),r.flush();const i=n.getSize(),l=r.getSize();if(!(i>=v&&l>=N))throw Object.assign(new Error(`This browser is keeping less than the tab wrote (the store's pack holds ${i} of ${v} bytes, its log ${l} of ${N}): its storage is full, as a private window's is well below its quota.`),{name:"QuotaExceededError",code:"ENOSPC"})}function In(r,n={}){const i=S;if(!i||!$)throw new Error("OPFS filesystem worker is not initialized.");if(r.length===0)return;const l=Be.encode(JSON.stringify({packBytes:v,changes:r}));if(l.byteLength>ls)throw new Error("An OPFS workspace index record exceeds its size limit.");const c=new Uint8Array(Dt+l.byteLength),u=new DataView(c.buffer);u.setUint32(0,l.byteLength,!0),u.setUint32(4,Zr(l),!0),c.set(l,Dt);let p=0;for(;p<c.byteLength;){const y=i.write(c.subarray(p),{at:N+p});if(y<=0)throw new Error("The OPFS workspace index log could not be written completely.");p+=y}N+=c.byteLength,vn(i),n.publish!==!1&&yt(),performance.now()-te>=ps?Ee():K===void 0&&(K=setTimeout(Ee,ps))}function Ee(){if(K!==void 0&&(clearTimeout(K),K=void 0),fe)throw fe;const r=performance.now();$?.flush(),S?.flush(),te=performance.now(),ve+=1,ge+=te-r}function Ot(){const r=Tr,n=gt(()=>r.catch(()=>{}).then(On));return Tr=n,n}async function On(){if(be(),!F)return;const r=F,n=S,i=await pe(r,!1);if(!n||n!==S||r!==F)throw new Error("OPFS workspace changed generations before its checkpoint could start.");Ee();const l=N;if(await dt(i,g,{access:n,bytes:l,packBytes:v}),r===F&&(he={generation:r,bytes:l}),n===S&&r===F&&l===N){ot();try{n.truncate(0),n.flush(),N=0,he={generation:r,bytes:0}}finally{it()}}}function qr(r){return bt(()=>Tn(ar(r)))}async function Tn(r){const n=crypto.randomUUID(),i=await pe(n,!0),l=await i.getFileHandle(Ze,{create:!0}),c=await Z(l,"store"),u=new Map;let p=0;try{for(const _ of r.files){let E=0,M=0;if(_.type!=="directory"){const O=new Uint8Array(r.pack,_.offset??0,_.length??0);E=p,M=O.byteLength;let I=0;for(;I<M;){const q=c.write(O.subarray(I),{at:E+I});if(q<=0)throw new Error("An OPFS workspace file could not be written completely.");I+=q}p+=M}u.set(_.path,{type:_.type,mode:_.mode??(_.type==="directory"?et:Ct),mtimeMs:_.mtimeMs??Date.now(),offset:E,length:M})}for(const _ of ke())u.has(_)||u.set(_,{type:"directory",mode:et,mtimeMs:Date.now(),offset:0,length:0});we(u.size),c.truncate(p),c.flush()}finally{c.close()}const y=await dt(i,u);await Tt(n,i,u,p,y)}async function Nn(){await Wr(()=>!0)}async function Mn(){let r=!1,n=!1,i=!1;try{await Fn(()=>{r=!0},()=>{n=!0},()=>{i=!0})}finally{r&&(n||i)?it():r&&_t()}}async function Fn(r,n,i){const l=crypto.randomUUID(),c=await pe(l,!0),u=await Z(await c.getFileHandle(Ze,{create:!0}),"store");let p,y=!1;try{p=await Z(await c.getFileHandle(hr,{create:!0}),"record of changes"),p.truncate(0);const _=new Uint8Array(hs);let E=0;const M=z=>{if(z.pack)return{...z};if(z.type==="directory"||z.length===0)return{...z,offset:0,length:0};const X=$;if(!X)throw new Error("OPFS filesystem worker is not initialized.");const $e=E;let ce=0;for(;ce<z.length;){const ft=Math.min(_.byteLength,z.length-ce),ss=_.subarray(0,ft);if(j?.ensure(z.offset+ce,ft),X.read(ss,{at:z.offset+ce})!==ft)throw new Error("An OPFS workspace file could not be read completely.");let Lt=0;for(;Lt<ft;){const ns=u.write(ss.subarray(Lt),{at:$e+ce+Lt});if(ns<=0)throw new Error("An OPFS workspace file could not be written completely.");Lt+=ns}ce+=ft}E+=z.length;const{capacity:fr,...Yn}=z;return{...Yn,offset:$e}},O=new Map;let I=performance.now();for(const[z,X]of[...g]){if(Y||He)return;g.get(z)===X&&(O.set(X,M(X)),performance.now()-I>8&&(await new Promise($e=>setTimeout($e,0)),I=performance.now()))}if(Y||He||!$||!S)return;ot(),r();const q=new Map;for(const[z,X]of g)q.set(z,O.get(X)??M(X));u.truncate(E),u.flush(),p.flush(),Ee();const W={pack:$,log:S};$=u,S=p,N=0,g=q,Ye(),v=E,F=l,m=c,at(),y=!0;const se=new Map(q);try{W.pack.close()}finally{W.log.close()}try{await dt(c,se);const z={storageVersion:4,generation:l,initializedAt:Date.now()};await lt(await Ne(),Xe,z)}catch(z){throw fe=new Error("The workspace moved to a compacted generation it could not record; it takes no more writes, which its next open would discard.",{cause:z}),fe}n(),await rr(l)}finally{if(!y){i();try{u.close()}finally{p?.close()}await Yr(await(await Ne()).getDirectoryHandle(Bt),l)}}}async function Ln(r){be(),ot();try{await $n(r)}finally{it()}}async function $n(r){let n=!1;for(const[i,l]of g){if(!l.pack||l.length===0)continue;const c=r.get(l.offset);if(c===void 0)throw new Error(`The shared store no longer holds the bytes of ${i}.`);c!==l.offset&&(g.set(i,{...l,offset:c}),n=!0)}n&&await Ot()}function Wr(r){return bt(()=>Rn(r))}async function Rn(r){const n=$;if(!n)throw new Error("OPFS filesystem worker is not initialized.");const i=new Map,l=crypto.randomUUID(),c=await pe(l,!0),u=await c.getFileHandle(Ze,{create:!0}),p=await Z(u,"store"),y=new Map,_=new Uint8Array(hs);let E=0;try{for(const[O,I]of g){if(!r(O,I))continue;if(I.pack){y.set(O,{...I});continue}if(I.type==="directory"||I.length===0){y.set(O,{...I,offset:0,length:0});continue}const q=E;i.set(I.offset,q);let W=0;for(;W<I.length;){const X=Math.min(_.byteLength,I.length-W),$e=_.subarray(0,X);if(j?.ensure(I.offset+W,X),n.read($e,{at:I.offset+W})!==X)throw new Error("An OPFS workspace file could not be read completely.");let ce=0;for(;ce<X;){const fr=p.write($e.subarray(ce),{at:q+W+ce});if(fr<=0)throw new Error("An OPFS workspace file could not be written completely.");ce+=fr}W+=X}E+=I.length;const{capacity:se,...z}=I;y.set(O,{...z,offset:q,length:I.length})}p.truncate(E),p.flush()}finally{p.close()}const M=await dt(c,y);return await Tt(l,c,y,E,M),i}async function Tt(r,n,i,l,c,u){ot();try{await Bn(r,n,i,l,c,u)}finally{it()}}async function Bn(r,n,i,l,c,u){const p=await n.getFileHandle(hr,{create:!0}),y=await Z(p,"record of changes");try{y.truncate(0),y.flush()}finally{y.close()}const _={storageVersion:u?5:4,generation:r,initializedAt:Date.now(),...u?{imageRanges:u}:{}};if(await lt(await Ne(),Xe,_),Ge(),F=r,L=_.initializedAt,G=u,c){const E=new Re(c.index);g=new Ke(E),U=new $t(E),re=void 0}else g=i,Ye();v=l,m=n,await Je(n),c?({liveBytes:B,linked:w,linkedBytes:b}=c,Q=Math.max(0,v-B)):at(),d||await rr(r)}async function Dn(r,n,i,l,c=!1){if(be(),!d||P!==xe)throw new Error("Only the shared package store can reserve immutable image extents.");if(v!==0||[...g.values()].some(O=>O.type!=="directory"))return!1;const u=ur(l);if(u.bytes!==r.packBytes||r.entries>wr||r.liveBytes>r.packBytes||n.byteLength!==r.json.raw||i.byteLength!==r.binary.raw||!await Mt(n,r.json.sha256,c)||!await Mt(i,r.binary.sha256,c))throw new Error("The image's prepared metadata does not match its document.");const p=n.subarray(0,4096).indexOf(10);if(p<0)throw new Error("The prepared index has no bounded retained header.");const y=JSON.parse(`${Qe.decode(n.subarray(0,p-1))}}`),_={packBytes:r.packBytes,liveBytes:r.liveBytes,linked:0,linkedBytes:0},E=y.retainedIndex;if(E.version!==1||E.digest!==await Hr(r.binary.sha256,_)||E.packBytes!==_.packBytes||E.liveBytes!==_.liveBytes||E.linked!==0||E.linkedBytes!==0)throw new Error("The prepared index's retained measures are inconsistent.");const M=new SharedArrayBuffer(i.byteLength);if(new Uint8Array(M).set(i),new Re(M).entryCount!==r.entries)throw new Error("The prepared index has the wrong number of entries.");return bt(async()=>{const O=crypto.randomUUID(),I=await pe(O,!0),q=await I.getFileHandle(Ze,{create:!0}),W=await Z(q,"immutable image reservation");try{W.truncate(r.packBytes),W.flush()}finally{W.close()}const se=Be.encode(JSON.stringify(u));return await Se(I,as,se),await Se(I,Nt,i),await Se(I,de,n),await Tt(O,I,new Map,r.packBytes,{index:M,..._},await me(se)),!0})}async function Cn(r,n,i,l=!1,c){if(be(),d||!e.packages||!c&&!e.packages.deferredImage)throw new Error("Prepared project paths require a verified shared image.");if(v!==0||[...g.values()].some(E=>E.type!=="directory"))return!1;if(n.byteLength!==r.json.raw||i.byteLength!==r.binary.raw||!await Mt(n,r.json.sha256,l)||!await Mt(i,r.binary.sha256,l))throw new Error("The image's prepared project does not match its descriptor.");const u=n.subarray(0,4096).indexOf(10);if(u<0)throw new Error("The prepared project has no bounded retained header.");const p=JSON.parse(`${Qe.decode(n.subarray(0,u-1))}}`).retainedIndex,y={packBytes:0,liveBytes:0,linked:r.linked,linkedBytes:r.linkedBytes};if(p.version!==1||p.digest!==await Hr(r.binary.sha256,y)||p.packBytes!==0||p.liveBytes!==0||p.linked!==r.linked||p.linkedBytes!==r.linkedBytes)throw new Error("The prepared project's retained measures are inconsistent.");const _=new SharedArrayBuffer(i.byteLength);if(new Uint8Array(_).set(i),new Re(_).entryCount!==r.entries||r.entries>o)throw new Error("The prepared project has invalid entry bounds.");return bt(async()=>{const E=crypto.randomUUID(),M=await pe(E,!0),O=await M.getFileHandle(Ze,{create:!0}),I=await Z(O,"prepared project");try{I.truncate(0),I.flush()}finally{I.close()}if(await Se(M,Nt,i),await Se(M,de,n),c&&!await c)return!1;if(!e.packages?.deferredImage)throw new Error("Prepared project paths require a verified shared image.");return await Tt(E,M,new Map,0,{index:_,...y}),!0})}async function zn(){if(Y)throw new Error("This OPFS workspace is closing.");if(!$)throw new Error("OPFS filesystem worker is not initialized.");const r=[],n=[...g.keys()].sort((p,y)=>Xr(p)-Xr(y)||(p<y?-1:1));let i=0;for(const p of g.values())p.type!=="directory"&&(i+=p.length);const l=new ArrayBuffer(i),c=new Uint8Array(l);let u=0;for(const p of n){const y=g.get(p);if(y.type==="directory"){r.push({path:p,type:"directory",mode:y.mode,mtimeMs:y.mtimeMs});continue}y.length>0&&c.set(kt(y),u),r.push({path:p,type:y.type,offset:u,length:y.length,mode:y.mode,mtimeMs:y.mtimeMs}),u+=y.length}for(const p of[...ke()].reverse())g.has(p)||r.unshift({path:p,type:"directory",mode:et,mtimeMs:Date.now()});return ar({files:r,pack:l})}async function lt(r,n,i){await Se(r,n,Be.encode(JSON.stringify(i)))}async function Se(r,n,i){const l=await(await Ne()).getDirectoryHandle(cs,{create:!0}),c=crypto.randomUUID(),u=await l.getFileHandle(c,{create:!0}),p=await Z(u,"index");try{let y=0;for(;y<i.byteLength;){const _=p.write(i.subarray(y),{at:y});if(_<=0)throw new Error("An OPFS workspace file could not be written completely.");y+=_}p.truncate(i.byteLength),p.flush()}finally{p.close()}try{await u.move(r,n)}finally{await Gr(l,c,!1)}}const Nt="index.shared";async function me(r){const n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Mt(r,n,i){return i||await me(r)===n}function Hr(r,n){const{packBytes:i,liveBytes:l,linked:c,linkedBytes:u,journalPrefix:p}=n;return me(Be.encode(`${JSON.stringify({packBytes:i,liveBytes:l,linked:c,linkedBytes:u,...p?{journalPrefix:p}:{}})}:${r}`))}async function Jr(r,n){const{packBytes:i,liveBytes:l,linked:c,linkedBytes:u,journalPrefix:p}=n;return me(Be.encode(`${JSON.stringify({packBytes:i,liveBytes:l,linked:c,linkedBytes:u,...p?{journalPrefix:p}:{}})}:${await me(r)}`))}async function dt(r,n,i){const l=Wn(n);if(typeof SharedArrayBuffer>"u"||n.size<1e4){await lt(r,de,l);return}const c=new Map(l.entries),u=new Map,p={packBytes:i?.packBytes??0,liveBytes:0,linked:0,linkedBytes:0};for(const[q,W]of c){const se=Le(q);if(se!==q){let z=u.get(se);z||(z=new Set,u.set(se,z)),z.add(q.slice(se.length+1))}W.pack?(p.linked+=1,p.linkedBytes+=W.length):(p.liveBytes+=W.length,p.packBytes=Math.max(p.packBytes,W.offset+W.length))}let y;try{y=os(c,u)}catch{await lt(r,de,l);return}const _=JSON.stringify(l.entries),E=i?new Uint8Array(i.bytes):void 0;if(E&&i.access.read(E,{at:0})!==E.byteLength)throw new Error("The checkpoint's journal prefix could not be read completely.");const M=E?{bytes:E.byteLength,digest:await me(E)}:void 0,O=new Uint8Array(y).slice(),I={version:M?2:1,digest:await Jr(O,{...p,...M?{journalPrefix:M}:{}}),...p,...M?{journalPrefix:M}:{}};try{await Se(r,Nt,O)}catch{await lt(r,de,{entries:JSON.parse(_)});return}return await Se(r,de,Be.encode(`{"retainedIndex":${JSON.stringify(I)},
1
+ const Ts="EINSTALLREFUSED",Vn="[install-trap-record]";class Kn extends Error{request;code=Ts;constructor(e){super(eo(e)),this.request=e,this.name="InstallRefusedError"}}const Qn=Symbol.for("browser-substrate.install-recorder"),Xn=Symbol.for("browser-substrate.install-trapped");function Ms(s){const e=globalThis;throw(e[Xn]??=[]).push(s),e[Qn]?.(s),console.error(`[install-trap] ${s.door}: ${s.subject}`),console.info(`${Vn} ${JSON.stringify(s)}`),new Kn(s)}function Zn(s){return typeof s!="object"||s===null?!1:s.code===Ts?!0:/^REFUSED \([^)]+\): /u.test(String(s.message??""))}function eo(s){return[`REFUSED (${s.door}): ${s.subject}`,"","The tab never installs, downloads, extracts or builds a dependency, and never runs a setup step. Everything a","project uses reaches it prepared, with the image or from the catalog, and this was not. Nothing was attempted.","",...s.fix?[`To fix it: ${s.fix}`]:["To fix it, prepare the image again on a machine, from the project's folder:",""," npx @volter/browser-substrate dev"]].join(`
2
+ `)}const Fs=2019846480,Vt=6,oe=6,rt=3,Ht=0,ft=1,Pe=2,Ls=3,$s=4,Rs=5,Bs=0,Cs=1,Ds=2,Jt=1,zs=2,Us=4,Gt=32,br=3,kr=["file","directory","symlink"],to=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,ro=new TextEncoder,so=new TextDecoder;function js(s){let e=2166136261;for(let t=0;t<s.length;t+=1)e^=s.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function os(s,e){const t=[...s.keys()];for(const x of t)if(to.test(x))throw new Error("A path in the store is not well-formed UTF-16.");const o=new Map;for(let x=0;x<t.length;x+=1)o.set(t[x],x);for(const x of e.keys())o.has(x)||(o.set(x,t.length),t.push(x));const a=t.length,d=new Map,u=new Uint32Array(a);let h=0;for(let x=0;x<a;x+=1){const A=t[x];let C=!0;for(let H=0;H<A.length;H+=1)if(A.charCodeAt(H)>=128){C=!1;break}C||d.set(x,ro.encode(A)),u[x]=C?A.length:d.get(x).length,h+=u[x]}let m=0;for(const x of e.values())m+=x.size;let w=1;for(;w<a*2;)w<<=1;const b=Vt*4,k=Er(b+a*oe*4,8),P=k+a*rt*8,F=P+w*4,g=F+m*4,U=new SharedArrayBuffer(Er(g+h,8));new Uint32Array(U,0,Vt).set([Fs,a,w,m,h,s.size]);const G=new Uint32Array(U,b,a*oe),j=new Float64Array(U,k,a*rt),_e=new Uint32Array(U,P,w),N=new Uint32Array(U,F,m),R=new Uint8Array(U,g,h);let L=0,S=0;for(let x=0;x<a;x+=1){const A=t[x],C=x*oe,H=d.get(x);if(H)R.set(H,L);else for(let T=0;T<A.length;T+=1)R[L+T]=A.charCodeAt(T);const v=u[x];G[C+Ht]=L,G[C+ft]=v,L+=v;let K=H?0:Gt;const te=s.get(A);if(te){K|=Jt|kr.indexOf(te.type)<<br,te.pack&&(K|=Us),G[C+Ls]=te.mode;const T=x*rt;j[T+Bs]=te.mtimeMs,j[T+Cs]=te.offset,j[T+Ds]=te.length}const ve=e.get(A);if(ve){K|=zs,G[C+$s]=S,G[C+Rs]=ve.size;for(const T of ve){const B=o.get(`${A}/${T}`);if(B===void 0)throw new Error(`The store's children name ${A}/${T}, which its index does not hold.`);N[S++]=B}}G[C+Pe]=K;let ge=js(A)&w-1;for(;_e[ge]!==0;)ge=ge+1&w-1;_e[ge]=x+1}if(S!==m)throw new Error("The shared index's children did not add up.");return U}function Er(s,e){return Math.ceil(s/e)*e}class Re{buffer;count;entryCount;records;numbers;table;childList;strings;mask;constructor(e){const t=new Uint32Array(e,0,Vt);if(t[0]!==Fs)throw new Error("Not a shared store index.");const[,o,a,d,u,h]=t;this.buffer=e,this.count=o,this.entryCount=h;const m=Vt*4,w=Er(m+o*oe*4,8),b=w+o*rt*8,k=b+a*4,P=k+d*4;this.records=new Uint32Array(e,m,o*oe),this.numbers=new Float64Array(e,w,o*rt),this.table=new Uint32Array(e,b,a),this.childList=new Uint32Array(e,k,d),this.strings=new Uint8Array(e,P,u),this.mask=a-1}find(e){let t=js(e)&this.mask;for(;;){const o=this.table[t];if(o===0)return-1;if(this.pathIs(o-1,e))return o-1;t=t+1&this.mask}}entry(e){const t=e*oe,o=this.records[t+Pe];if(!(o&Jt))return;const a=e*rt,d={type:kr[o>>>br&3],mode:this.records[t+Ls],mtimeMs:this.numbers[a+Bs],offset:this.numbers[a+Cs],length:this.numbers[a+Ds]};return o&Us&&(d.pack="packages"),d}typeAt(e){const t=this.records[e*oe+Pe];return t&Jt?kr[t>>>br&3]:void 0}hasEntry(e){return(this.records[e*oe+Pe]&Jt)!==0}childNames(e){const t=e*oe;if(!(this.records[t+Pe]&zs))return;const o=this.records[t+$s],a=this.records[t+ft]+1,d=[];for(let u=0;u<this.records[t+Rs];u+=1){const h=this.childList[o+u]*oe;d.push(this.decode(this.records[h+Ht]+a,this.records[h+ft]-a,(this.records[h+Pe]&Gt)!==0))}return d}path(e){const t=e*oe;return this.decode(this.records[t+Ht],this.records[t+ft],(this.records[t+Pe]&Gt)!==0)}decode(e,t,o){if(!o)return so.decode(this.strings.slice(e,e+t));let a="";for(let d=e,u=e+t;d<u;d+=4096)a+=String.fromCharCode.apply(null,this.strings.subarray(d,Math.min(u,d+4096)));return a}pathIs(e,t){const o=e*oe,a=this.records[o+Ht],d=this.records[o+ft];if(!(this.records[o+Pe]&Gt))return this.path(e)===t;if(d!==t.length)return!1;for(let u=0;u<d;u+=1)if(this.strings[a+u]!==t.charCodeAt(u))return!1;return!0}}const le=Symbol("deleted");function qs(s,e){return s===e||!!s&&!!e&&s.type===e.type&&s.offset===e.offset&&s.length===e.length&&s.pack===e.pack&&s.mode===e.mode&&s.mtimeMs===e.mtimeMs&&s.capacity===e.capacity}class Ke{base;overlay=new Map;delta=0;constructor(e){this.base=e}get[Symbol.toStringTag](){return"Map"}get size(){return this.base.entryCount+this.delta}get(e){const t=this.overlay.get(e);if(t!==void 0)return t===le?void 0:t;const o=this.base.find(e);return o<0?void 0:this.base.entry(o)}typeOf(e){const t=this.overlay.get(e);if(t!==void 0)return t===le?void 0:t.type;const o=this.base.find(e);return o<0?void 0:this.base.typeAt(o)}has(e){const t=this.overlay.get(e);if(t!==void 0)return t!==le;const o=this.base.find(e);return o>=0&&this.base.hasEntry(o)}set(e,t){this.has(e)||(this.delta+=1);const o=this.base.find(e);return o>=0&&qs(this.base.entry(o),t)?this.overlay.delete(e):this.overlay.set(e,t),this}delete(e){if(!this.has(e))return!1;const t=this.base.find(e);return t>=0&&this.base.hasEntry(t)?this.overlay.set(e,le):this.overlay.delete(e),this.delta-=1,!0}clear(){throw new Error("A reader's index is not cleared; it is replaced.")}*entries(){for(const[e,t]of this.overlay)t!==le&&(yield[e,t]);for(let e=0;e<this.base.count;e+=1){if(!this.base.hasEntry(e))continue;const t=this.base.path(e);this.overlay.has(t)||(yield[t,this.base.entry(e)])}}*keys(){for(const[e]of this.entries())yield e}*values(){for(const[,e]of this.entries())yield e}[Symbol.iterator](){return this.entries()}forEach(e,t){for(const[o,a]of this.entries())e.call(t,a,o,this)}*changed(){for(const[e,t]of this.overlay)t!==le&&(yield[e,t])}*changes(){for(const[e,t]of this.overlay)yield[e,t===le?null:t]}get overlaid(){return this.overlay.size}boundedChanges(){if(this.overlay.size>65536)return;const e=[];let t=0;for(const[o,a]of this.changes()){if(t+=o.length*2+128,t>8*1024*1024)return;e.push([o,a])}return e}}class $t{base;overlay=new Map;constructor(e){this.base=e}get(e){const t=this.overlay.get(e);if(t!==void 0)return t===le?void 0:t;const o=this.base.find(e),a=o<0?void 0:this.base.childNames(o);return a?new Set(a):void 0}mutable(e){const t=this.overlay.get(e);if(t!==void 0&&t!==le)return t;const o=new Set(t===le?[]:this.get(e)??[]);return this.overlay.set(e,o),o}delete(e){this.overlay.set(e,le)}}const no="supercode-browser-filesystems",xe="packages",oo="state.json",is="/image-range-worker.js",as="image-ranges.json",io=2;function fr(s){const e=s;if(!e||e.version!==1||!Number.isSafeInteger(e.bytes)||e.bytes<0||!Array.isArray(e.parts)||e.image!==void 0&&(typeof e.image!="string"||!/^[a-f0-9]{16,64}$/u.test(e.image))||e.parts.length>1e5)throw new Error("Invalid immutable image ranges.");let t=0;for(const o of e.parts){if(!o||o.offset!==t||!Number.isSafeInteger(o.raw)||o.raw<0||!Number.isSafeInteger(o.bytes)||o.bytes<0||o.bytes>1024*1024*1024||o.raw>1024*1024*1024||typeof o.sha256!="string"||!/^[a-f0-9]{64}$/u.test(o.sha256)||typeof o.url!="string"||!/^\/substrate\/[A-Za-z0-9._/-]+$/u.test(o.url)||o.url.split("/").some(a=>a==="."||a===".."))throw new Error("Invalid immutable image part.");if(t+=o.raw,!Number.isSafeInteger(t))throw new Error("Immutable image ranges exceed the offset limit.")}if(t!==e.bytes)throw new Error("Immutable image ranges do not cover their reservation.");return e}class ao{ranges;directory;identity;receiptKey;client;worker;port;prefetchers=[];state;completed;firstRead;closed=!1;ready=!1;startup;cancelStartup;sharedCompletion;blocked={ranges:0,ms:0};constructor(e,t,o,a,d,u){if(this.ranges=e,this.directory=t,this.identity=o,this.receiptKey=d,this.client=u,typeof Worker>"u"||typeof SharedArrayBuffer>"u")throw new Error("This browser cannot materialize an immutable image during a synchronous read.");if(this.state=new Int32Array(u?.state??new SharedArrayBuffer(e.parts.length*Int32Array.BYTES_PER_ELEMENT)),this.state.length!==e.parts.length)throw new Error("The image reader's line has the wrong range count.");const h=e.parts.length,m=a??new SharedArrayBuffer((2*h+1)*Int32Array.BYTES_PER_ELEMENT);if(m.byteLength!==h*Int32Array.BYTES_PER_ELEMENT&&m.byteLength!==(2*h+1)*Int32Array.BYTES_PER_ELEMENT)throw new Error("The image completion seed has the wrong range count.");this.completed=new Int32Array(m,0,h),this.firstRead=m.byteLength>h*Int32Array.BYTES_PER_ELEMENT?new Int32Array(m,h*Int32Array.BYTES_PER_ELEMENT,h+1):void 0,this.sharedCompletion=a!==void 0;for(const w of e.parts)Object.freeze(w);Object.freeze(e.parts),Object.freeze(e)}get completionBuffer(){return this.completed.buffer}get verifiedRanges(){return this.ranges}async initialize(){if(this.closed)throw new Error("This immutable image reader is closed.");if(this.ready)return;if(this.startup)return this.startup;let e=!1;for(let t=0;t<this.completed.length;t+=1)if(Atomics.load(this.completed,t)!==2){e=!0;break}if(!e){this.ready=!0,this.client?.port.close();return}if(this.client){const t=this.port=this.client.port;t.onmessage=o=>{o.data?.type!=="closing"||this.port!==t||(t.close(),this.port=void 0,this.closed||this.startMaterializer().catch(a=>console.warn("This process's image reader could not start its own materializer after its line closed.",a)))},t.start(),this.ready=!0;return}return this.startMaterializer()}startMaterializer(){const e=Date.now(),t=new Worker(is,{type:"module",name:"immutable-image-materializer"}),o=this.ready;return o||(this.worker=t),t.addEventListener("error",()=>this.fail()),t.addEventListener("messageerror",()=>this.fail()),this.startup=new Promise((a,d)=>{const u=()=>{clearTimeout(b),t.removeEventListener("message",w),t.removeEventListener("error",h),t.removeEventListener("messageerror",h),this.cancelStartup=void 0},h=()=>m(new Error("The immutable image materializer could not initialize; reload to retry.")),m=k=>{u(),t.terminate(),o||(this.closed=!0,this.fail()),d(k)},w=k=>{if(k.data?.identity===this.identity){if(k.data.type==="init-error"){m(new Error(`The immutable image materializer could not initialize: ${String(k.data.error)}`));return}k.data.type==="ready"&&(console.log(`[boot-trace] ${JSON.stringify({event:"materializer-ready",at:Date.now(),ms:Date.now()-e})}`),u(),this.ready=!0,this.worker=t,a())}},b=setTimeout(()=>m(new Error("The immutable image materializer did not initialize within 10 seconds; reload to retry.")),1e4);this.cancelStartup=m,t.addEventListener("message",w),t.addEventListener("error",h),t.addEventListener("messageerror",h);try{t.postMessage({type:"init",ranges:this.ranges,directory:this.directory,identity:this.identity,state:this.state.buffer,completed:this.completed.buffer,sharedCompletion:this.sharedCompletion,...this.receiptKey?{receiptKey:this.receiptKey}:{}})}catch(k){m(k instanceof Error?k:new Error(String(k)))}}),this.startup}readDigests(){const e=this.firstRead;if(!e)return;const t=this.ranges.parts.length,o=[];for(let a=0;a<t;a+=1){const d=Atomics.load(e,a),u=this.ranges.parts[a];d>0&&u.raw>0&&o.push([d,u.sha256])}return o.sort((a,d)=>a[0]-d[0]).map(([,a])=>a)}completedDigests(){const e=[];for(let t=0;t<this.completed.length;t+=1){const o=this.ranges.parts[t];o.raw>0&&Atomics.load(this.completed,t)===2&&e.push(o.sha256)}return e}prefetch(e,t=[]){if(this.closed||!this.ready||!this.worker)return{queued:0,done:Promise.resolve()};const o=new Map;for(let h=0;h<this.ranges.parts.length;h+=1){const m=this.ranges.parts[h];if(m.raw===0)continue;const w=o.get(m.sha256);w?w.push(h):o.set(m.sha256,[h])}const a=[];for(const h of new Set(e))for(const m of o.get(h)??[])Atomics.load(this.completed,m)!==2&&a.push(m);const d=t.length>0&&a.length>0?Math.min(t.length,8):Math.min(io,Math.ceil(a.length/32)),u=[];for(let h=0;h<d;h+=1){const m=a.filter((P,F)=>F%d===h),w=new Worker(is,{type:"module",name:"immutable-image-prefetch"});this.prefetchers.push(w);let b;u.push(new Promise(P=>{b=P}));const k=()=>{w.terminate(),this.prefetchers=this.prefetchers.filter(P=>P!==w),b()};w.addEventListener("error",k),w.addEventListener("messageerror",k),w.addEventListener("message",P=>{P.data?.identity===this.identity&&(P.data.type==="ready"?w.postMessage(t.length>0?{type:"prefetch-stream",url:t[h]}:{type:"prefetch",indices:m}):(P.data.type==="prefetched"||P.data.type==="init-error")&&k())}),w.postMessage({type:"init",ranges:this.ranges,directory:this.directory,identity:this.identity,state:new SharedArrayBuffer(this.state.byteLength),completed:this.completed.buffer,sharedCompletion:!0,...this.receiptKey?{receiptKey:this.receiptKey}:{}})}return{queued:a.length,done:Promise.all(u).then(()=>{})}}get blockedReads(){return{...this.blocked}}ensure(e,t){if(this.closed)throw new Error("This immutable image reader is closed.");if(!this.ready)throw new Error("This immutable image reader has not finished asynchronous initialization.");if(t===0||e>=this.ranges.bytes)return;const o=Math.min(e+t,this.ranges.bytes);let a=0,d=this.ranges.parts.length;for(;a<d;){const u=a+d>>>1,h=this.ranges.parts[u];h.offset+h.raw<=e?a=u+1:d=u}for(let u=a;u<this.ranges.parts.length;u+=1){const h=this.ranges.parts[u];if(h.offset>=o)break;const m=this.firstRead;if(m&&Atomics.load(m,u)===0&&Atomics.compareExchange(m,u,0,Atomics.add(m,this.ranges.parts.length,1)+1),Atomics.load(this.completed,u)===2)continue;const w=this.worker??this.port;if(!w)throw new Error("This immutable image reader's line closed and its own materializer is still starting; retry the read.");w.postMessage({type:"read",index:u});const b=performance.now(),k=b+3e4;for(;Atomics.load(this.state,u)===0;){const P=k-performance.now();if(P<=0||Atomics.wait(this.state,u,0,P)==="timed-out")throw this.close(),new Error(`The image's immutable part ${h.url} did not arrive within 30 seconds; reload to retry.`)}if(this.blocked.ranges+=1,this.blocked.ms+=performance.now()-b,Atomics.load(this.state,u)!==2)throw new Error(`The image's immutable part ${h.url} could not be verified or stored; see the worker error and reload to retry.`)}}lineForReader(){const e=this.worker??this.port;if(this.closed||!this.ready||!e)return;const t=new MessageChannel,o=new SharedArrayBuffer(this.ranges.parts.length*Int32Array.BYTES_PER_ELEMENT);return e.postMessage({type:"client",port:t.port1,state:o},[t.port1]),{port:t.port2,state:o}}fail(){for(let e=0;e<this.state.length;e+=1)Atomics.compareExchange(this.state,e,0,-1)===0&&Atomics.notify(this.state,e)}close(){if(this.closed)return;if(this.closed=!0,this.cancelStartup){this.cancelStartup(new Error("This immutable image reader closed during initialization."));return}this.fail(),this.port?.close();const e=this.worker;e&&(e.postMessage({type:"closing"}),setTimeout(()=>e.terminate(),250));for(const t of this.prefetchers)t.dispatchEvent(new Event("error"));this.prefetchers=[]}}const pr="/packages",Rt="supercode-browser-packages",Be=new TextEncoder,Qe=new TextDecoder("utf-8",{fatal:!0}),co=no,Bt="generations",cs="atomic-staging",Xe=oo,de="index.json",hr="index-log.bin",Ze="pack.bin",Ct=8,ls=64*1024*1024,ne=1024*1024*1024,ds=4*1024*1024*1024,lo=["/workspace","/home","/opt"],Ce=0,us=1,wr=1e6,fs=8*1024*1024,ps=250,uo=64*1024*1024,fo=256*1024*1024,hs=4*1024*1024,et=493,Dt=420;function ws(s,e={}){const t=e.limits?.maxBytes??ds,o=e.limits?.maxEntries??wr;if(!Number.isSafeInteger(t)||t<1||t>ds||!Number.isSafeInteger(o)||o<1||o>wr)throw new Error("Invalid OPFS workspace limits.");let a,d=!1,u=!1,h=!1,m,w=0,b=0,k,P,F,g=new Map,U=new zt,$,G,j,_e,N,R,L=0,S,x=0;const A=new Map,C=256*1024,H=32;let v=0,K,te=-1/0,ve=0,ge=0,T=0,B=0,Q=0,Ie=0,Oe=0,ae,mt,ue,qe=!1,nt,Nr=Promise.resolve(),We=0,Y=!1,He=!1,V,Ne=0,fe=!1;function yt(){if(!(!V||fe)){if(T>2147483647){_t();return}Atomics.store(V,us,T)}}function _t(){!V||fe||(fe=!0,(Atomics.load(V,Ce)&1)===0&&Atomics.add(V,Ce,1))}function ot(){Ne+=1,Ne===1&&V&&!fe&&Atomics.add(V,Ce,1)}function it(){Ne-=1,!(Ne>0||!V||fe)&&(yt(),fe||Atomics.add(V,Ce,1))}function Tr(){if(u)throw new Error("A store open for reading follows its owner's clock; it has none of its own.");return V||(V=new Int32Array(new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT)),V[Ce]=Ne>0||fe?1:0,yt()),V.buffer}let re;const cn=8*1024*1024;let Mr=!1;function ln(r){if(u||!V||!F||qe||Ne>0||fe||Y)return;const n=Atomics.load(V,Ce);if(n&1)return;if(r?.overlays&&g instanceof Ke){const l=g.boundedChanges();if(l)return Zt({generation:F,index:g.base.buffer,changes:l,packBytes:v,logBytes:T,epoch:n,liveBytes:B,linked:w,linkedBytes:b})}if(re&&re.generation===F&&re.epoch===n&&T>=re.logBytes&&T-re.logBytes<=(r?.current?0:cn))return Zt(re);let i;try{i=os(g,fn())}catch(l){console.warn(`[pack-store] no reader seed: ${l instanceof Error?l.message:String(l)}`);return}return re={generation:F,index:i,packBytes:v,logBytes:T,epoch:n,liveBytes:B,linked:w,linkedBytes:b},un(i),Zt(re)}function Zt(r){const n=e.packages?.imageCompletionSeed();return n?{...r,packagesImage:n}:r}function dn(){if(!(!j||!G||!F||qe||Ne>0||Y))return{generation:F,rangesDigest:G,completed:j.completionBuffer,...j.receiptKey?{metadata:{ranges:j.verifiedRanges,receiptKey:j.receiptKey}}:{}}}function un(r){const n=[];if(g instanceof Ke)for(const[l,c]of g.changed())c.capacity!==void 0&&n.push([l,c]);else for(const[l,c]of g)c.capacity!==void 0&&n.push([l,c]);const i=new Re(r);g=new Ke(i),U=new $t(i);for(const[l,c]of n)g.set(l,c)}function fn(){if(U instanceof zt)return U.map;const r=new Map;for(const n of g.keys()){const i=Le(n);if(i===n)continue;let l=r.get(i);l||(l=new Set,r.set(i,l)),l.add(n.slice(i.length+1))}return r}function pn(){!u||h||Y||!S||St(T)}async function gt(r){if(Y)throw new Error("This OPFS workspace is closing.");We+=1;let n,i=!1;try{return await r()}catch(l){throw i=!0,n=l,l}finally{if(We-=1,Y&&We===0)try{rs()}catch(l){throw i?new AggregateError([n,l],"OPFS operation and deferred close both failed."):l}}}async function bt(r){return be(),We!==0?Promise.reject(new Error("Wait for the current OPFS storage operation before replacing its generation.")):(He=!0,gt(async()=>{try{return await r()}finally{He=!1}}))}function hn(r){if(Y)throw new Error("This OPFS workspace is closing.");const n=g.get(r);if(!n||n.type==="directory")throw new Error(`OPFS workspace file does not exist: ${r}`);return kt(n)}function wn(r,n,i){if(Y)throw new Error("This OPFS workspace is closing.");const l=g.get(r);if(!l||l.type==="directory")throw new Error(`OPFS workspace file does not exist: ${r}`);const c=Math.min(Math.max(0,n),l.length),f=Math.min(Math.max(0,i),l.length-c);if(l.pack){const p=e.packages;if(!p)throw new Error("This store has no shared package store to read from.");return p.readExtent(l.offset+c,f)}return Et(l.offset+c,f)}function kt(r){if(r.pack){const n=e.packages;if(!n)throw new Error("This store has no shared package store to read from.");return n.readExtent(r.offset,r.length)}return Et(r.offset,r.length)}function Et(r,n){if(Y)throw new Error("This OPFS workspace is closing.");const i=$;if(!i)throw new Error("OPFS filesystem worker is not initialized.");const l=new Uint8Array(n);if(n>0&&n<=C&&r>=0&&r+n<=x){let c=0;for(;c<n;){const f=r+c,p=Math.floor(f/C)*C;let y=A.get(p);if(!y&&(y=new Uint8Array(Math.min(C,x-p)),j?.ensure(p,y.byteLength),i.read(y,{at:p})!==y.byteLength))throw new Error("An OPFS package range could not be read completely.");A.delete(p),A.set(p,y),A.size>H&&A.delete(A.keys().next().value);const _=f-p,E=Math.min(n-c,y.byteLength-_);l.set(y.subarray(_,_+E),c),c+=E}return l}if(j?.ensure(r,n),n>0&&i.read(l,{at:r})!==n)throw new Error("An OPFS workspace file could not be read completely.");return l}async function mn(r,n={}){if(Y&&a||!a&&We!==0)throw new Error("Wait for this OPFS workspace to finish closing before opening it again.");if(qe)throw new Error("This OPFS store is already opening a workspace.");if(a){if(P!==$r(r))throw new Error("Close this OPFS store before opening another workspace.");return g.size>0}qe=!0,Y=!1;const i=new AbortController;nt=i;try{g=new Map,U=new zt,F=void 0,G=void 0,m=void 0,ae=void 0,ue=void 0,v=T=B=Q=w=b=0,he=void 0,Ie=Oe=ve=ge=0,te=-1/0,P=$r(r),u=n.readOnly===!0,N=u?n.imageCompletion:void 0,R=u?n.imageLine:void 0,h=u&&n.extentsOnly===!0,d=n.shared===!0||u,d||await kn(i.signal),i.signal.throwIfAborted();const l=await _n();i.signal.throwIfAborted();try{const p=await l.getDirectoryHandle(co,{create:!u});i.signal.throwIfAborted(),a=await p.getDirectoryHandle(P,{create:!u})}catch(p){if(i.signal.throwIfAborted(),u&&Ve(p))return!1;throw p}i.signal.throwIfAborted();let c=Ft(await Fe(a,Xe));if(i.signal.throwIfAborted(),!c&&u)return await tr(),!1;if(!c&&d&&(await s.navigator.locks.request(Rt,{mode:"exclusive",signal:i.signal},async()=>{i.signal.throwIfAborted(),c=Ft(await Fe(a,Xe)),i.signal.throwIfAborted(),c||(await tr(),await qr({files:[],pack:new ArrayBuffer(0)}),await wo(a))}),i.signal.throwIfAborted(),!c))return m=await pe(F,!1),i.signal.throwIfAborted(),!1;if(!c)return await tr(),i.signal.throwIfAborted(),!1;const f=async p=>{let y;try{y=await pe(p.generation,!1)}catch(O){throw i.signal.throwIfAborted(),Ve(O)?new Error("The committed OPFS workspace generation is missing. Stored generations were retained.",{cause:O}):O}if(i.signal.throwIfAborted(),F=p.generation,L=p.initializedAt,G=p.imageRanges,m=y,h)return P===xe&&s.navigator.locks?await s.navigator.locks.request(Rt,{mode:"shared",signal:i.signal},async()=>{await Je(y),x=$.getSize()}):await Je(y),i.signal.throwIfAborted(),!0;const _=u?n.seed:void 0;if(_&&_.generation===p.generation){const O=new Re(_.index);return g=new Ke(O),U=new $t(O),v=_.packBytes,_.changes&&Lr({packBytes:_.packBytes,changes:_.changes}),await Je(y),i.signal.throwIfAborted(),T=_.logBytes,{liveBytes:B,linked:w,linkedBytes:b}=_,Q=Math.max(0,v-B),Mr=!0,g.size>0}const E=u?void 0:await Un(y);if(i.signal.throwIfAborted(),E){const O=new Re(E.index);g=new Ke(O),U=new $t(O),{packBytes:v,liveBytes:B,linked:w,linkedBytes:b}=E;const I=Atomics.load(new Int32Array(Tr()),Ce);re={generation:F,index:E.index,packBytes:v,liveBytes:B,linked:w,linkedBytes:b,logBytes:0,epoch:I}}else g=lr(await Fe(y,de)),i.signal.throwIfAborted(),Ye(),v=er(g);await Je(y),i.signal.throwIfAborted();const M=E?await jn(E):0;return i.signal.throwIfAborted(),M&&(he={generation:F,bytes:M},re&&(re.logBytes=M)),St(M,!!E),E?Q=Math.max(0,v-B):at(),Ur(),d&&!u&&!E&&g.size>=1e4&&(Ee(),await dt(y,g,{access:S,bytes:T,packBytes:v})),d||($.truncate(v),await Gr(a,cs,!0),await rr(F),i.signal.throwIfAborted(),Q>uo&&Q>B&&await Tn()),i.signal.throwIfAborted(),g.size>0};return d&&!u?await s.navigator.locks.request(Rt,{mode:"exclusive",signal:i.signal},async()=>{if(c=Ft(await Fe(a,Xe)),!c)throw new Error("The committed package store state is missing. Stored data was retained.");return f(c)}):await f(c)}catch(l){const c=[l];try{Ge()}catch(f){c.push(f)}try{k?.()}catch(f){c.push(f)}throw k=void 0,a=void 0,c.length>1?new AggregateError(c,"OPFS workspace open and cleanup failed."):l}finally{qe=!1,nt=void 0}}function yn(r){return gt(()=>Fr(r?.whole===!0))}async function Fr(r=!1){if(h)throw new Error("A store opened for its extents alone has no index to follow.");if(u&&a){const f=Ft(await Fe(a,Xe));if(!f)throw new Error("The committed OPFS workspace state is missing. Stored data was retained.");if(f.generation!==F||r){const p=await pe(f.generation,!1),y=lr(await Fe(p,de));v=er(y),f.generation!==F&&(F=f.generation,L=f.initializedAt,G=f.imageRanges,await Je(p)),F=f.generation,m=p,g=y,Ye(),St(),at();return}}const n=S;if(!n||!m)return;const i=n.getSize();let l=!1;i<T&&(g=lr(await Fe(m,de)),Ye(),v=er(g),T=0,l=!0);const c=T;St(T),(l||T!==c)&&at()}async function _n(){let r;for(let n=0;n<10;n+=1){nt?.signal.throwIfAborted();try{return await s.navigator.storage.getDirectory()}catch(i){r=i,await new Promise(l=>setTimeout(l,200))}}throw r instanceof Error?r:new Error("This browser workspace's storage is unavailable.")}const gn=1e4;async function Z(r,n){let i;const l=nt?.signal;for(let f=0;f<2;f+=1){l?.throwIfAborted();const p=r.createSyncAccessHandle({mode:"readwrite-unsafe"});let y,_,E=!1;try{const M=new Promise((I,q)=>{_=()=>q(l?.reason??new DOMException("Workspace open was cancelled.","AbortError")),l?.addEventListener("abort",_,{once:!0}),l?.aborted&&_()}),O=await Promise.race([p.then(I=>({access:I})).catch(I=>{i=I}),new Promise(I=>{y=setTimeout(()=>I(void 0),gn)}),M]);if(l?.throwIfAborted(),O)return E=!0,O.access}finally{y!==void 0&&clearTimeout(y),_&&l?.removeEventListener("abort",_),E||p.then(M=>M.close(),()=>{}).catch(M=>console.error("Late workspace handle cleanup failed.",M))}if(i instanceof TypeError)throw new Error(`This browser cannot share a workspace's files between pages: its file access handles have no readwrite-unsafe mode (Chrome 121 or newer has one). ${i.message}`);await new Promise(M=>setTimeout(M,500))}const c=i instanceof Error?` (${i.message})`:"";throw new Error(`This browser workspace's ${n} is held by another page${c}.`)}async function Je(r){Ge();const n=await r.getFileHandle(Ze);$=await Z(n,"store");try{if($.getSize()<v)throw new Error("The committed OPFS workspace pack is incomplete. Stored data was retained.");const i=await r.getFileHandle(hr);if(S=await Z(i,"record of changes"),T=S.getSize(),G){const l=N,c=l&&l.generation===F&&l.rangesDigest===G?l:void 0;let f,p;if(c?.metadata){if(f=fr(c.metadata.ranges),p=c.metadata.receiptKey,!/^[a-f0-9]{64}$/u.test(p))throw new Error("The owner's immutable receipt key is invalid.")}else{const _=await(await r.getFileHandle(as)).getFile(),E=new Uint8Array(await _.arrayBuffer());if(await me(E)!==G)throw new Error("The committed immutable image ranges have changed. Stored data was retained.");f=fr(JSON.parse(Qe.decode(E))),p=await me(Be.encode(JSON.stringify(f)))}if(f.bytes>$.getSize())throw new Error("The immutable image reservation is incomplete. Stored data was retained.");const y=c?R:void 0;y||R?.port.close(),R=void 0,j=new ao(f,r,`${P}.${F}`,c?.completed,p,y),await j.initialize(),_e=f.image}}catch(i){throw Ge(),i}}function Ge(){j?.close(),j=void 0,_e=void 0;const r=$,n=S;$=void 0,S=void 0,T=0,x=0,A.clear();try{r?.close()}finally{n?.close()}}function St(r=0,n=!1){const i=S;if(!i)throw new Error("OPFS filesystem worker is not initialized.");const l=i.getSize();if(l<=r){T=l;return}const c=new Uint8Array(l-r);if(i.read(c,{at:r})!==c.byteLength)throw new Error("The OPFS workspace index log could not be read.");const f=$?.getSize()??1/0,p=new DataView(c.buffer);let y=0;const _=c.byteLength;for(;y+Ct<=_;){const E=p.getUint32(y,!0),M=p.getUint32(y+4,!0),O=y+Ct;if(E===0||E>ls||O+E>_)break;const I=c.subarray(O,O+E);if(Zr(I)!==M)break;let q;try{q=Hn(JSON.parse(Qe.decode(I)))}catch{break}if(q.packBytes>f)break;Lr(q,n),y=O+E}y!==_&&!d&&i.truncate(r+y),T=r+y}function Lr(r,n=!1){for(const[i,l]of r.changes){const c=g.get(i);if(l&&qs(c,l)){xt(i);continue}n&&(c?.pack?(w-=1,b-=c.length):c&&(B-=c.length),l?.pack?(w+=1,b+=l.length):l&&(B+=l.length)),l===null?(g.delete(i),Br(i)):(g.set(i,l),xt(i))}v=Math.max(v,r.packBytes)}function at(){B=0,w=0,b=0;for(const r of g.values())r.pack?(w+=1,b+=r.length):B+=r.length;Q=Math.max(0,v-B)}function er(r){let n=0;for(const i of r.values())i.pack||(n=Math.max(n,i.offset+i.length));return n}const bn=5e3;async function kn(r){if(!s.navigator.locks)return;if(!P)throw new Error("OPFS filesystem project is not initialized.");const n=new AbortController,i=setTimeout(()=>n.abort(),bn);try{await new Promise((l,c)=>{s.navigator.locks.request(`supercode-browser-filesystem-${P}`,{mode:"exclusive",signal:r?AbortSignal.any([r,n.signal]):n.signal},async()=>{clearTimeout(i),l(),await new Promise(f=>{k=f})}).catch(()=>c(r?.aborted?r.reason:new Error("This browser workspace is already open in another tab.")))})}finally{clearTimeout(i)}}function $r(r){if(typeof r!="string"||!/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/u.test(r))throw new Error("OPFS filesystem projectId is invalid.");return r}async function Te(){if(!a)throw new Error("OPFS filesystem worker is not initialized.");return a}async function pe(r,n){return(await(await Te()).getDirectoryHandle(Bt,{create:n})).getDirectoryHandle(r,{create:n})}async function tr(){let r;try{r=await(await Te()).getDirectoryHandle(Bt)}catch(n){if(Ve(n))return;throw n}for await(const n of r.entries())throw new Error("OPFS workspace state is missing but stored generations exist. Stored data was retained.")}async function rr(r){const n=await Te();let i;try{i=await n.getDirectoryHandle(Bt)}catch(l){if(Ve(l))return;throw l}for await(const[l]of i.entries())l!==r&&await Yr(i,l)}function be(){if(Y)throw new Error("This OPFS workspace is closing.");if(He)throw new Error("This OPFS workspace is replacing its generation; wait for that operation before writing.");if(u)throw new Error("This store is open for reading; its owner writes it.");if(ue)throw ue}async function En(r){es(r)}let sr=!1,Pt=0,he,nr=!1;function Rr(){if(Pt>0)return;const r=he&&he.generation===F&&he.bytes<=T?he.bytes:0;T-r>fs&&!sr&&(sr=!0,(d?s.navigator.locks.request(Rt,{mode:"exclusive"},async()=>{if(!a||Y)return;await Fr();const i=he,l=i&&i.generation===F&&i.bytes<=T?i.bytes:0;T-l>fs&&await Ot()}):Ot()).catch(i=>console.error("The workspace's log could not be checkpointed; it is replayed at the next open.",i)).finally(()=>{sr=!1})),!d&&!nr&&Q>fo&&Q>B&&(nr=!0,gt(Mn).catch(n=>console.error("The workspace could not be compacted; it keeps its generation.",n)).finally(()=>{nr=!1}))}async function Sn(r){be(),Pt+=1;try{return await r()}finally{Pt-=1,Pt===0&&!Y&&a&&Rr()}}function Pn(r,n){const i=ye(r.path);if(r.operation==="write"){if(g.get(i)?.type==="directory")throw new Error(`OPFS write target is a directory: ${i}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const c=r.content;if(c.byteLength>ne)throw new Error(`${i} is ${c.byteLength} bytes; an OPFS workspace file holds at most ${ne}.`);At(i,c.byteLength),Me(i,n);const f=It(c);ee(i,{type:r.symlink?"symlink":"file",mode:r.mode??g.get(i)?.mode??Dt,mtimeMs:r.mtimeMs??Date.now(),offset:f,length:c.byteLength},n);return}if(r.operation==="append"){const c=g.get(i);if(c&&c.type!=="file")throw new Error(`OPFS append target is not a file: ${i}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS append requires file content.");const f=r.content,p=(c?.length??0)+f.byteLength;if(p>ne)throw new Error(`${i} is ${p} bytes; an OPFS workspace file holds at most ${ne}.`);At(i,p),Me(i,n);const y=r.mode??c?.mode??Dt,_=r.mtimeMs??Date.now(),E=c&&!c.pack?c.capacity??c.length:0;if(P!==xe&&c&&!c.pack&&c.length>0&&(p<=E||c.offset+E===v)){vt(c.offset+c.length,f),ee(i,{...c,mode:y,mtimeMs:_,length:p,capacity:Math.max(E,p)},n),Q-=Math.max(c.length,c.capacity??0),Ie-=1,Oe-=c.length;return}const M=new Uint8Array(p);c&&c.length>0&&M.set(kt(c),0),M.set(f,p-f.byteLength);const O=It(M),I=Math.min(ne,Math.max(p,p*2,64*1024));I>p&&jr(O+I),ee(i,{type:"file",mode:y,mtimeMs:_,offset:O,length:p,capacity:I},n);return}if(r.operation==="write-at"){const c=g.get(i);if(c&&c.type!=="file")throw new Error(`OPFS write target is not a file: ${i}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const f=r.content,p=r.position,y=c?.length??0;if(f.byteLength===0&&c)return;const _=f.byteLength===0?y:Math.max(y,p+f.byteLength);if(_>ne)throw new Error(`${i} is ${_} bytes; an OPFS workspace file holds at most ${ne}.`);At(i,_),Me(i,n);const E=r.mode??c?.mode??Dt,M=r.mtimeMs??Date.now(),O=c&&!c.pack?c.capacity??c.length:0;if(P!==xe&&c&&!c.pack&&y>0&&(_<=O||c.offset+O===v)){if(p>y&&vt(c.offset+y,new Uint8Array(p-y)),mt&&p<y){const se=Math.min(y,p+f.byteLength);mt.push([c.offset+p,Et(c.offset+p,se-p)])}vt(c.offset+p,f),ee(i,{...c,mode:E,mtimeMs:M,length:_,capacity:Math.max(O,_)},n),_!==y&&(Q-=Math.max(c.length,c.capacity??0),Ie-=1,Oe-=c.length);return}const I=new Uint8Array(_);c&&y>0&&I.set(kt(c),0),f.byteLength>0&&I.set(f,p);const q=It(I),W=Math.min(ne,Math.max(_,_*2,64*1024));W>_&&jr(q+W),ee(i,{type:"file",mode:E,mtimeMs:M,offset:q,length:_,capacity:W},n);return}if(r.operation==="mkdir"){Me(i,n);const c=g.get(i);if(c&&c.type!=="directory")throw new Error(`OPFS path is a file: ${i}`);ee(i,{type:"directory",mode:r.mode??c?.mode??et,mtimeMs:r.mtimeMs??c?.mtimeMs??Date.now(),offset:0,length:0},n);return}if(r.operation==="remove"){ir(i,n),ke().includes(i)&&ee(i,{type:"directory",mode:et,mtimeMs:Date.now(),offset:0,length:0},n);return}if(r.operation==="link"){xn(i,zr(r.source),n);return}if(r.operation==="rename"){An(i,ye(r.destination),n);return}const l=g.get(i);if(!l)throw new Error(`OPFS metadata target does not exist: ${i}`);ee(i,{...l,mode:r.mode??l.mode,mtimeMs:r.mtimeMs??l.mtimeMs},n)}function ee(r,n,i){const l=g.get(r);ae&&!ae.has(r)&&ae.set(r,l);const c=l!==void 0&&l.type===n.type&&l.offset===n.offset&&l.length===n.length&&l.pack===n.pack;l&&!c&&(Cr(l),l.type!=="directory"&&n.type!=="directory"&&l.length>0&&!l.pack&&(Ie+=1,Oe+=l.length)),g.set(r,n),xt(r),c||(n.pack?(w+=1,b+=n.length):B+=n.length),i.push([r,n])}function xt(r){const n=Le(r);n!==r&&U.mutable(n).add(r.slice(n.length+1))}function Br(r){const n=Le(r);U.get(n)?.has(r.slice(n.length+1))&&U.mutable(n).delete(r.slice(n.length+1)),U.delete(r)}function Ye(){U=new zt;for(const r of g.keys())xt(r)}function or(r){const n=[],i=l=>{const c=g.get(l);if(!c)return;n.push([l,c]);const f=U.get(l);if(f)for(const p of f)i(`${l}/${p}`)};return i(r),n}function Cr(r,n){if(r.pack){w-=1,b-=r.length;return}B-=r.length,Q+=Math.max(r.length,r.capacity??0)}function Dr(r,n){const i=g.get(r);i&&(ae&&!ae.has(r)&&ae.set(r,i),g.delete(r),Br(r),Cr(i),n.push([r,null]))}function xn(r,n,i){const l=e.packages;if(!l)throw new Error("This store has no shared package store to link from.");const c=zr(n),f=l.descendants(c);if(f.length===0)throw new Error(`The shared package store does not hold ${n}.`);Me(r,i),ir(r,i),we(g.size+f.length);for(const[p,y]of f){const _=p===c?r:`${r}${p.slice(c.length)}`;ee(_,y.type==="directory"?{type:"directory",mode:y.mode,mtimeMs:y.mtimeMs,offset:0,length:0}:{type:y.type,mode:y.mode,mtimeMs:y.mtimeMs,offset:y.offset,length:y.length,pack:xe},i)}}function Me(r,n){const i=Le(r);if(i!==r&&g.get(i)?.type==="directory"){we(g.size+(g.has(r)?0:1));return}const l=[];let c=ct(r)??ke()[0];if(g.has(c)||l.push(c),r!==c)for(const p of dr(Qr(Le(r)))){c=`${c}/${p}`;const y=g.get(c);if(y&&y.type!=="directory")throw new Error(`OPFS path parent is a file: ${c}`);y||l.push(c)}we(g.size+l.length+(g.has(r)?0:1));const f=Date.now();for(const p of l)ee(p,{type:"directory",mode:et,mtimeMs:f,offset:0,length:0},n)}function ir(r,n){for(const[i]of or(r))Dr(i,n)}function An(r,n,i){if(r===n)return;if(n.startsWith(`${r}/`))throw new Error("An OPFS rename cannot move a directory into itself.");const l=or(r);if(l.length===0){if(g.has(n))return;throw new Error(`OPFS rename source does not exist: ${r}`)}Me(n,i),ir(n,i);for(const[c]of l)Dr(c,i);for(const[c,f]of l)ee(`${n}${c.slice(r.length)}`,f,i);we(g.size)}function zr(r){if(typeof r!="string"||!r.startsWith(`${pr}/`)||r.includes("\0")||r.length>4096)throw new Error("Invalid shared store path.");return dr(r.slice(pr.length+1)),r}function ke(){return P===xe?[pr]:lo}function ct(r){return ke().find(n=>r===n||r.startsWith(`${n}/`))}function At(r,n){const i=g.get(r),l=i&&!i.pack?i.length:0;if(B-l+n>t)throw new Error(`OPFS workspace exceeds its byte limit: writing ${r} (${n} bytes) would take the project's own files past ${t} bytes.`)}function we(r){if(r>o)throw new Error("OPFS workspace exceeds its entry limit.")}function Ur(){if(we(g.size),B>t)throw new Error(`OPFS workspace exceeds its byte limit: the project's own files hold ${B} bytes, past ${t}.`)}function vt(r,n){const i=$;if(!i)throw new Error("OPFS filesystem worker is not initialized.");let l=0;for(;l<n.byteLength;){const c=i.write(n.subarray(l),{at:r+l});if(c<=0)throw new Error("An OPFS workspace file could not be written completely.");l+=c}v=Math.max(v,r+n.byteLength)}function jr(r){const n=$;if(!n)throw new Error("OPFS filesystem worker is not initialized.");r<=v||(n.truncate(r),v=r)}function It(r){const n=$;if(!n)throw new Error("OPFS filesystem worker is not initialized.");const i=v;let l=0;for(;l<r.byteLength;){const c=n.write(r.subarray(l),{at:i+l});if(c<=0)throw new Error("An OPFS workspace file could not be written completely.");l+=c}return v=i+r.byteLength,i}function vn(r){const n=$;if(n.getSize()>=v&&r.getSize()>=T)return;n.flush(),r.flush();const i=n.getSize(),l=r.getSize();if(!(i>=v&&l>=T))throw Object.assign(new Error(`This browser is keeping less than the tab wrote (the store's pack holds ${i} of ${v} bytes, its log ${l} of ${T}): its storage is full, as a private window's is well below its quota.`),{name:"QuotaExceededError",code:"ENOSPC"})}function In(r,n={}){const i=S;if(!i||!$)throw new Error("OPFS filesystem worker is not initialized.");if(r.length===0)return;const l=Be.encode(JSON.stringify({packBytes:v,changes:r}));if(l.byteLength>ls)throw new Error("An OPFS workspace index record exceeds its size limit.");const c=new Uint8Array(Ct+l.byteLength),f=new DataView(c.buffer);f.setUint32(0,l.byteLength,!0),f.setUint32(4,Zr(l),!0),c.set(l,Ct);let p=0;for(;p<c.byteLength;){const y=i.write(c.subarray(p),{at:T+p});if(y<=0)throw new Error("The OPFS workspace index log could not be written completely.");p+=y}T+=c.byteLength,vn(i),n.publish!==!1&&yt(),performance.now()-te>=ps?Ee():K===void 0&&(K=setTimeout(Ee,ps))}function Ee(){if(K!==void 0&&(clearTimeout(K),K=void 0),ue)throw ue;const r=performance.now();$?.flush(),S?.flush(),te=performance.now(),ve+=1,ge+=te-r}function Ot(){const r=Nr,n=gt(()=>r.catch(()=>{}).then(On));return Nr=n,n}async function On(){if(be(),!F)return;const r=F,n=S,i=await pe(r,!1);if(!n||n!==S||r!==F)throw new Error("OPFS workspace changed generations before its checkpoint could start.");Ee();const l=T;if(await dt(i,g,{access:n,bytes:l,packBytes:v}),r===F&&(he={generation:r,bytes:l}),n===S&&r===F&&l===T){ot();try{n.truncate(0),n.flush(),T=0,he={generation:r,bytes:0}}finally{it()}}}function qr(r){return bt(()=>Nn(ar(r)))}async function Nn(r){const n=crypto.randomUUID(),i=await pe(n,!0),l=await i.getFileHandle(Ze,{create:!0}),c=await Z(l,"store"),f=new Map;let p=0;try{for(const _ of r.files){let E=0,M=0;if(_.type!=="directory"){const O=new Uint8Array(r.pack,_.offset??0,_.length??0);E=p,M=O.byteLength;let I=0;for(;I<M;){const q=c.write(O.subarray(I),{at:E+I});if(q<=0)throw new Error("An OPFS workspace file could not be written completely.");I+=q}p+=M}f.set(_.path,{type:_.type,mode:_.mode??(_.type==="directory"?et:Dt),mtimeMs:_.mtimeMs??Date.now(),offset:E,length:M})}for(const _ of ke())f.has(_)||f.set(_,{type:"directory",mode:et,mtimeMs:Date.now(),offset:0,length:0});we(f.size),c.truncate(p),c.flush()}finally{c.close()}const y=await dt(i,f);await Nt(n,i,f,p,y)}async function Tn(){await Wr(()=>!0)}async function Mn(){let r=!1,n=!1,i=!1;try{await Fn(()=>{r=!0},()=>{n=!0},()=>{i=!0})}finally{r&&(n||i)?it():r&&_t()}}async function Fn(r,n,i){const l=crypto.randomUUID(),c=await pe(l,!0),f=await Z(await c.getFileHandle(Ze,{create:!0}),"store");let p,y=!1;try{p=await Z(await c.getFileHandle(hr,{create:!0}),"record of changes"),p.truncate(0);const _=new Uint8Array(hs);let E=0;const M=z=>{if(z.pack)return{...z};if(z.type==="directory"||z.length===0)return{...z,offset:0,length:0};const X=$;if(!X)throw new Error("OPFS filesystem worker is not initialized.");const $e=E;let ce=0;for(;ce<z.length;){const ut=Math.min(_.byteLength,z.length-ce),ss=_.subarray(0,ut);if(j?.ensure(z.offset+ce,ut),X.read(ss,{at:z.offset+ce})!==ut)throw new Error("An OPFS workspace file could not be read completely.");let Lt=0;for(;Lt<ut;){const ns=f.write(ss.subarray(Lt),{at:$e+ce+Lt});if(ns<=0)throw new Error("An OPFS workspace file could not be written completely.");Lt+=ns}ce+=ut}E+=z.length;const{capacity:ur,...Yn}=z;return{...Yn,offset:$e}},O=new Map;let I=performance.now();for(const[z,X]of[...g]){if(Y||He)return;g.get(z)===X&&(O.set(X,M(X)),performance.now()-I>8&&(await new Promise($e=>setTimeout($e,0)),I=performance.now()))}if(Y||He||!$||!S)return;ot(),r();const q=new Map;for(const[z,X]of g)q.set(z,O.get(X)??M(X));f.truncate(E),f.flush(),p.flush(),Ee();const W={pack:$,log:S};$=f,S=p,T=0,g=q,Ye(),v=E,F=l,m=c,at(),y=!0;const se=new Map(q);try{W.pack.close()}finally{W.log.close()}try{await dt(c,se);const z={storageVersion:4,generation:l,initializedAt:Date.now()};await lt(await Te(),Xe,z)}catch(z){throw ue=new Error("The workspace moved to a compacted generation it could not record; it takes no more writes, which its next open would discard.",{cause:z}),ue}n(),await rr(l)}finally{if(!y){i();try{f.close()}finally{p?.close()}await Yr(await(await Te()).getDirectoryHandle(Bt),l)}}}async function Ln(r){be(),ot();try{await $n(r)}finally{it()}}async function $n(r){let n=!1;for(const[i,l]of g){if(!l.pack||l.length===0)continue;const c=r.get(l.offset);if(c===void 0)throw new Error(`The shared store no longer holds the bytes of ${i}.`);c!==l.offset&&(g.set(i,{...l,offset:c}),n=!0)}n&&await Ot()}function Wr(r){return bt(()=>Rn(r))}async function Rn(r){const n=$;if(!n)throw new Error("OPFS filesystem worker is not initialized.");const i=new Map,l=crypto.randomUUID(),c=await pe(l,!0),f=await c.getFileHandle(Ze,{create:!0}),p=await Z(f,"store"),y=new Map,_=new Uint8Array(hs);let E=0;try{for(const[O,I]of g){if(!r(O,I))continue;if(I.pack){y.set(O,{...I});continue}if(I.type==="directory"||I.length===0){y.set(O,{...I,offset:0,length:0});continue}const q=E;i.set(I.offset,q);let W=0;for(;W<I.length;){const X=Math.min(_.byteLength,I.length-W),$e=_.subarray(0,X);if(j?.ensure(I.offset+W,X),n.read($e,{at:I.offset+W})!==X)throw new Error("An OPFS workspace file could not be read completely.");let ce=0;for(;ce<X;){const ur=p.write($e.subarray(ce),{at:q+W+ce});if(ur<=0)throw new Error("An OPFS workspace file could not be written completely.");ce+=ur}W+=X}E+=I.length;const{capacity:se,...z}=I;y.set(O,{...z,offset:q,length:I.length})}p.truncate(E),p.flush()}finally{p.close()}const M=await dt(c,y);return await Nt(l,c,y,E,M),i}async function Nt(r,n,i,l,c,f){ot();try{await Bn(r,n,i,l,c,f)}finally{it()}}async function Bn(r,n,i,l,c,f){const p=await n.getFileHandle(hr,{create:!0}),y=await Z(p,"record of changes");try{y.truncate(0),y.flush()}finally{y.close()}const _={storageVersion:f?5:4,generation:r,initializedAt:Date.now(),...f?{imageRanges:f}:{}};if(await lt(await Te(),Xe,_),Ge(),F=r,L=_.initializedAt,G=f,c){const E=new Re(c.index);g=new Ke(E),U=new $t(E),re=void 0}else g=i,Ye();v=l,m=n,await Je(n),c?({liveBytes:B,linked:w,linkedBytes:b}=c,Q=Math.max(0,v-B)):at(),d||await rr(r)}async function Cn(r,n,i,l,c=!1){if(be(),!d||P!==xe)throw new Error("Only the shared package store can reserve immutable image extents.");if(v!==0||[...g.values()].some(O=>O.type!=="directory"))return!1;const f=fr(l);if(f.bytes!==r.packBytes||r.entries>wr||r.liveBytes>r.packBytes||n.byteLength!==r.json.raw||i.byteLength!==r.binary.raw||!await Mt(n,r.json.sha256,c)||!await Mt(i,r.binary.sha256,c))throw new Error("The image's prepared metadata does not match its document.");const p=n.subarray(0,4096).indexOf(10);if(p<0)throw new Error("The prepared index has no bounded retained header.");const y=JSON.parse(`${Qe.decode(n.subarray(0,p-1))}}`),_={packBytes:r.packBytes,liveBytes:r.liveBytes,linked:0,linkedBytes:0},E=y.retainedIndex;if(E.version!==1||E.digest!==await Hr(r.binary.sha256,_)||E.packBytes!==_.packBytes||E.liveBytes!==_.liveBytes||E.linked!==0||E.linkedBytes!==0)throw new Error("The prepared index's retained measures are inconsistent.");const M=new SharedArrayBuffer(i.byteLength);if(new Uint8Array(M).set(i),new Re(M).entryCount!==r.entries)throw new Error("The prepared index has the wrong number of entries.");return bt(async()=>{const O=crypto.randomUUID(),I=await pe(O,!0),q=await I.getFileHandle(Ze,{create:!0}),W=await Z(q,"immutable image reservation");try{W.truncate(r.packBytes),W.flush()}finally{W.close()}const se=Be.encode(JSON.stringify(f));return await Se(I,as,se),await Se(I,Tt,i),await Se(I,de,n),await Nt(O,I,new Map,r.packBytes,{index:M,..._},await me(se)),!0})}async function Dn(r,n,i,l=!1,c){if(be(),d||!e.packages||!c&&!e.packages.deferredImage)throw new Error("Prepared project paths require a verified shared image.");if(v!==0||[...g.values()].some(E=>E.type!=="directory"))return!1;if(n.byteLength!==r.json.raw||i.byteLength!==r.binary.raw||!await Mt(n,r.json.sha256,l)||!await Mt(i,r.binary.sha256,l))throw new Error("The image's prepared project does not match its descriptor.");const f=n.subarray(0,4096).indexOf(10);if(f<0)throw new Error("The prepared project has no bounded retained header.");const p=JSON.parse(`${Qe.decode(n.subarray(0,f-1))}}`).retainedIndex,y={packBytes:0,liveBytes:0,linked:r.linked,linkedBytes:r.linkedBytes};if(p.version!==1||p.digest!==await Hr(r.binary.sha256,y)||p.packBytes!==0||p.liveBytes!==0||p.linked!==r.linked||p.linkedBytes!==r.linkedBytes)throw new Error("The prepared project's retained measures are inconsistent.");const _=new SharedArrayBuffer(i.byteLength);if(new Uint8Array(_).set(i),new Re(_).entryCount!==r.entries||r.entries>o)throw new Error("The prepared project has invalid entry bounds.");return bt(async()=>{const E=crypto.randomUUID(),M=await pe(E,!0),O=await M.getFileHandle(Ze,{create:!0}),I=await Z(O,"prepared project");try{I.truncate(0),I.flush()}finally{I.close()}if(await Se(M,Tt,i),await Se(M,de,n),c&&!await c)return!1;if(!e.packages?.deferredImage)throw new Error("Prepared project paths require a verified shared image.");return await Nt(E,M,new Map,0,{index:_,...y}),!0})}async function zn(){if(Y)throw new Error("This OPFS workspace is closing.");if(!$)throw new Error("OPFS filesystem worker is not initialized.");const r=[],n=[...g.keys()].sort((p,y)=>Xr(p)-Xr(y)||(p<y?-1:1));let i=0;for(const p of g.values())p.type!=="directory"&&(i+=p.length);const l=new ArrayBuffer(i),c=new Uint8Array(l);let f=0;for(const p of n){const y=g.get(p);if(y.type==="directory"){r.push({path:p,type:"directory",mode:y.mode,mtimeMs:y.mtimeMs});continue}y.length>0&&c.set(kt(y),f),r.push({path:p,type:y.type,offset:f,length:y.length,mode:y.mode,mtimeMs:y.mtimeMs}),f+=y.length}for(const p of[...ke()].reverse())g.has(p)||r.unshift({path:p,type:"directory",mode:et,mtimeMs:Date.now()});return ar({files:r,pack:l})}async function lt(r,n,i){await Se(r,n,Be.encode(JSON.stringify(i)))}async function Se(r,n,i){const l=await(await Te()).getDirectoryHandle(cs,{create:!0}),c=crypto.randomUUID(),f=await l.getFileHandle(c,{create:!0}),p=await Z(f,"index");try{let y=0;for(;y<i.byteLength;){const _=p.write(i.subarray(y),{at:y});if(_<=0)throw new Error("An OPFS workspace file could not be written completely.");y+=_}p.truncate(i.byteLength),p.flush()}finally{p.close()}try{await f.move(r,n)}finally{await Gr(l,c,!1)}}const Tt="index.shared";async function me(r){const n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Mt(r,n,i){return i||await me(r)===n}function Hr(r,n){const{packBytes:i,liveBytes:l,linked:c,linkedBytes:f,journalPrefix:p}=n;return me(Be.encode(`${JSON.stringify({packBytes:i,liveBytes:l,linked:c,linkedBytes:f,...p?{journalPrefix:p}:{}})}:${r}`))}async function Jr(r,n){const{packBytes:i,liveBytes:l,linked:c,linkedBytes:f,journalPrefix:p}=n;return me(Be.encode(`${JSON.stringify({packBytes:i,liveBytes:l,linked:c,linkedBytes:f,...p?{journalPrefix:p}:{}})}:${await me(r)}`))}async function dt(r,n,i){const l=Wn(n);if(typeof SharedArrayBuffer>"u"||n.size<1e4){await lt(r,de,l);return}const c=new Map(l.entries),f=new Map,p={packBytes:i?.packBytes??0,liveBytes:0,linked:0,linkedBytes:0};for(const[q,W]of c){const se=Le(q);if(se!==q){let z=f.get(se);z||(z=new Set,f.set(se,z)),z.add(q.slice(se.length+1))}W.pack?(p.linked+=1,p.linkedBytes+=W.length):(p.liveBytes+=W.length,p.packBytes=Math.max(p.packBytes,W.offset+W.length))}let y;try{y=os(c,f)}catch{await lt(r,de,l);return}const _=JSON.stringify(l.entries),E=i?new Uint8Array(i.bytes):void 0;if(E&&i.access.read(E,{at:0})!==E.byteLength)throw new Error("The checkpoint's journal prefix could not be read completely.");const M=E?{bytes:E.byteLength,digest:await me(E)}:void 0,O=new Uint8Array(y).slice(),I={version:M?2:1,digest:await Jr(O,{...p,...M?{journalPrefix:M}:{}}),...p,...M?{journalPrefix:M}:{}};try{await Se(r,Tt,O)}catch{await lt(r,de,{entries:JSON.parse(_)});return}return await Se(r,de,Be.encode(`{"retainedIndex":${JSON.stringify(I)},
3
3
  "entries":${_}}`)),{index:y,...p}}async function Un(r){if(!(typeof SharedArrayBuffer>"u"))try{const n=await r.getFileHandle(de),i=await Z(n,"index");let l;try{const O=new Uint8Array(Math.min(512,i.getSize())),I=i.read(O,{at:0});l=Qe.decode(O.subarray(0,I))}finally{i.close()}const c=l.split(`
4
- `,1)[0];if(!c.startsWith('{"retainedIndex":')||!c.endsWith(","))return;const u=JSON.parse(c.slice(0,-1)+"}").retainedIndex;if(u.version!==1&&u.version!==2||!/^[a-f0-9]{64}$/u.test(u.digest)||![u.packBytes,u.liveBytes,u.linked,u.linkedBytes].every(O=>Number.isSafeInteger(O)&&O>=0)||u.version===1&&u.journalPrefix!==void 0||u.version===2&&(!u.journalPrefix||!Number.isSafeInteger(u.journalPrefix.bytes)||u.journalPrefix.bytes<0||!/^[a-f0-9]{64}$/u.test(u.journalPrefix.digest)))return;const p=await r.getFileHandle(Nt),y=await Z(p,"index");let _;try{const O=y.getSize();if(O>256*1024*1024||(_=new Uint8Array(O),y.read(_,{at:0})!==O))return}finally{y.close()}if(await Jr(_,u)!==u.digest)return;const E=new SharedArrayBuffer(_.byteLength);new Uint8Array(E).set(_);const M=new Re(E);return we(M.entryCount),{...u,index:E}}catch{return}}async function jn(r){const n=r.journalPrefix;if(!n||!S||!$||n.bytes>S.getSize()||r.packBytes>$.getSize())return 0;const i=new Uint8Array(n.bytes);return S.read(i,{at:0})!==i.byteLength?0:await me(i)===n.digest?n.bytes:0}async function Fe(r,n){let i;try{i=await r.getFileHandle(n)}catch(u){if(Ve(u))return;throw u}let l;if(f){l=await(await i.getFile()).text();try{return JSON.parse(l)}catch(u){throw new Error(`Invalid OPFS workspace metadata (${n}). Stored data was retained.`,{cause:u})}}const c=await Z(i,"index");try{const u=c.getSize(),p=new Uint8Array(u);if(u>0&&c.read(p,{at:0})!==u)throw new Error("An OPFS workspace file could not be read completely.");l=Qe.decode(p)}finally{c.close()}try{return JSON.parse(l)}catch(u){throw new Error(`Invalid OPFS workspace metadata (${n}). Stored data was retained.`,{cause:u})}}async function Gr(r,n,i){try{await r.removeEntry(n,{recursive:i})}catch(l){if(!Ve(l))throw l}}async function Yr(r,n){try{await r.removeEntry(n,{recursive:!0})}catch{}}function Vr(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid OPFS filesystem mutation.");if(r.operation!=="write"&&r.operation!=="append"&&r.operation!=="write-at"&&r.operation!=="mkdir"&&r.operation!=="remove"&&r.operation!=="rename"&&r.operation!=="metadata"&&r.operation!=="link")throw new Error("Invalid OPFS filesystem mutation.");if(ye(r.path),r.operation==="rename"&&ye(r.destination),(r.operation==="write"||r.operation==="append"||r.operation==="write-at")&&!(r.content instanceof Uint8Array))throw new Error("Invalid OPFS file content.");if(r.operation==="write-at"&&(!Number.isSafeInteger(r.position)||r.position<0))throw new Error("Invalid OPFS write position.");return cr(r),r}function qn(r){if(!Array.isArray(r)||r.length===0||r.length>128)throw new Error("Invalid OPFS filesystem mutation batch.");return r.map(n=>Vr(n))}function ar(r){if(!r||!Array.isArray(r.files)||r.files.length>o||!(r.pack instanceof ArrayBuffer))throw new Error("Invalid OPFS workspace snapshot.");const n=new Set,i=new Map(ke().map(c=>[c,"directory"]));let l=0;for(const c of r.files){if(!c||typeof c!="object")throw new Error("Invalid OPFS workspace snapshot entry.");if(ye(c.path),c.type!=="file"&&c.type!=="directory"&&c.type!=="symlink"||n.has(c.path))throw new Error("Invalid or duplicate OPFS workspace entry.");if(n.add(c.path),i.set(c.path,c.type),ke().includes(c.path)&&c.type!=="directory")throw new Error("The OPFS workspace root must be a directory.");if(c.type!=="directory"){const u=c.offset??0,p=c.length??0;if(!Number.isSafeInteger(u)||!Number.isSafeInteger(p)||u<0||p<0||p>ne||u+p>r.pack.byteLength)throw new Error("Invalid OPFS workspace file.");if(l+=p,l>t)throw new Error("OPFS workspace exceeds its byte limit.")}else if((c.offset??0)!==0||(c.length??0)!==0)throw new Error("An OPFS workspace directory cannot contain file bytes.");cr(c)}we(i.size);for(const c of r.files)if(!ke().includes(c.path)&&i.get(Le(c.path))!=="directory")throw new Error(`An OPFS workspace snapshot has no directory parent for ${c.path}.`);return r}function cr(r){if(r.mode!==void 0&&(!Number.isSafeInteger(r.mode)||r.mode<0||r.mode>4095))throw new Error("Invalid OPFS file mode.");if(r.mtimeMs!==void 0&&(typeof r.mtimeMs!="number"||!Number.isFinite(r.mtimeMs)||r.mtimeMs<0))throw new Error("Invalid OPFS modification time.")}function Wn(r){return{entries:[...r]}}function lr(r){const n=new Map;if(r===void 0)throw new Error("The committed OPFS workspace index is missing. Stored data was retained.");if(!r||typeof r!="object"||!Array.isArray(r.entries))throw new Error("Invalid OPFS workspace index.");const i=r.entries;we(i.length);for(const l of i){if(!Array.isArray(l)||l.length!==2)throw new Error("Invalid OPFS workspace index entry.");const c=ye(l[0]);if(n.has(c))throw new Error("Duplicate OPFS workspace index entry.");n.set(c,Kr(l[1]))}return n}function Kr(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid OPFS workspace index entry.");const n=r;if(n.type!=="file"&&n.type!=="directory"&&n.type!=="symlink")throw new Error("Invalid OPFS workspace index entry.");if(cr(n),n.mode===void 0||n.mtimeMs===void 0)throw new Error("Invalid OPFS workspace index entry.");if(!Number.isSafeInteger(n.offset)||n.offset<0||!Number.isSafeInteger(n.length)||n.length<0||n.length>ne)throw new Error("Invalid OPFS workspace index extent.");if(n.pack!==void 0&&n.pack!==xe)throw new Error("Invalid OPFS workspace index entry.");return{type:n.type,mode:n.mode,mtimeMs:n.mtimeMs,offset:n.offset,length:n.length,...n.pack?{pack:n.pack}:{}}}function Hn(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid OPFS workspace index record.");const n=r;if(!Number.isSafeInteger(n.packBytes)||n.packBytes<0||!Array.isArray(n.changes))throw new Error("Invalid OPFS workspace index record.");const i=[];for(const l of n.changes){if(!Array.isArray(l)||l.length!==2)throw new Error("Invalid OPFS workspace index record.");i.push([ye(l[0]),l[1]===null?null:Kr(l[1])])}return{packBytes:n.packBytes,changes:i}}function Ft(r){if(r===void 0)return;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid OPFS workspace state. Stored data was retained.");const n=r;if(n.storageVersion!==4&&n.storageVersion!==5||n.storageVersion===5&&(typeof n.imageRanges!="string"||!/^[a-f0-9]{64}$/u.test(n.imageRanges))||n.storageVersion===4&&n.imageRanges!==void 0||typeof n.generation!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(n.generation)||typeof n.initializedAt!="number"||!Number.isFinite(n.initializedAt))throw new Error("Invalid or unsupported OPFS workspace state. Stored data was retained.");return n}function ye(r){if(typeof r!="string"||ct(r)===void 0||r.includes("\0")||r.length>4096)throw new Error("Invalid OPFS workspace path.");return Qr(r),r}function Qr(r){const n=ct(r);if(n===void 0)throw new Error("Invalid OPFS workspace path.");const i=r===n?"":r.slice(n.length+1);return dr(i),i}function dr(r){const n=r===""?[]:r.split("/");if(n.some(i=>!i||i==="."||i===".."||i.includes("\0")))throw new Error("Invalid OPFS workspace path segment.");return n}function Le(r){const n=r.slice(0,r.lastIndexOf("/"));return n===""||ct(n)===void 0?ct(r)??r:n}function Xr(r){let n=1;for(let i=0;i<r.length;i+=1)r.charCodeAt(i)===47&&(n+=1);return n}function Ve(r){return r instanceof DOMException&&r.name==="NotFoundError"}function Zr(r){let n=2166136261;for(let i=0;i<r.byteLength;i+=1)n^=r[i],n=Math.imul(n,16777619);return n>>>0}typeof addEventListener=="function"&&addEventListener("close",()=>{$?.flush(),S?.flush(),Ge(),k?.()});function es(r,n={}){if(be(),ae)throw new Error("An OPFS mutation batch cannot be nested.");for(const i of r)Vr(i);return r.length?ts(i=>{for(const l of r)Pn(l,i)},n):[]}function Jn(r,n,i={}){if(be(),ae)throw new Error("An OPFS mutation batch cannot be nested.");for(const l of n){if(ye(l.path),l.type!=="file"&&l.type!=="directory"&&l.type!=="symlink")throw new Error(`OPFS extent ${l.path} has no valid type.`);if(l.type==="directory")continue;const{offset:c,length:u}=l;if(c===void 0||u===void 0||!Number.isSafeInteger(c)||!Number.isSafeInteger(u)||c<0||u<0||c+u>r.byteLength)throw new Error(`OPFS extent ${l.path} lies outside its bytes.`);if(u>ne)throw new Error(`${l.path} is ${u} bytes; an OPFS workspace file holds at most ${ne}.`)}return n.length?ts(l=>{const c=r.byteLength>0?It(r):v;for(const u of n){const p=ye(u.path);Me(p,l);const y=g.get(p);if(u.type==="directory"){if(y&&y.type!=="directory")throw new Error(`OPFS path is a file: ${p}`);ee(p,{type:"directory",mode:u.mode,mtimeMs:u.mtimeMs,offset:0,length:0},l);continue}if(y?.type==="directory")throw new Error(`OPFS write target is a directory: ${p}`);At(p,u.length),ee(p,{type:u.type,mode:u.mode,mtimeMs:u.mtimeMs,offset:c+u.offset,length:u.length},l)}},i):[]}function ts(r,n){if(!$||!S)throw new Error("OPFS filesystem worker is not initialized.");const i={packBytes:v,logBytes:N,liveBytes:B,deadBytes:Q,rewrites:Ie,rewrittenBytes:Oe,linked:w,linkedBytes:b},l=new Map;ae=l;const c=[];mt=c;const u=[];try{return r(u),Ur(),In(u,{publish:!n.durable}),n.durable&&(Ee(),yt()),Rr(),u}catch(p){const y=V!==void 0&&!ue&&Atomics.load(V,fs)!==i.logBytes;y&&ot();for(const[_,E]of l)E===void 0?g.delete(_):g.set(_,E);Ye();try{for(let _=c.length-1;_>=0;_-=1)vt(c[_][0],c[_][1])}catch(_){p=new AggregateError([p,_],"OPFS could not restore bytes a failed batch wrote over.")}({packBytes:v,logBytes:N,liveBytes:B,deadBytes:Q,rewrites:Ie,rewrittenBytes:Oe,linked:w,linkedBytes:b}=i),K!==void 0&&(clearTimeout(K),K=void 0);try{S.truncate(N),S.flush(),$.truncate(v),$.flush()}catch(_){throw _t(),fe=new AggregateError([p,_],"OPFS could not roll back a failed batch; reopen this workspace before writing again."),fe}throw y&&it(),p}finally{ae=void 0,mt=void 0}}function Gn(){if(qe){nt?.abort(new DOMException("The workspace was closed while opening.","AbortError"));return}Y||(Y=!0,We===0&&rs())}function rs(){_t();try{Ee()}finally{try{Ge()}finally{const r=k;k=void 0,a=void 0;try{r?.()}finally{e.ownsPackages&&e.packages?.close()}}}}return{initialize:mn,opened:()=>a!==void 0&&!Y,stats:()=>({entries:g.size,liveBytes:B,deadBytes:Q,packBytes:v,rewrites:Ie,rewrittenBytes:Oe,linked:w,linkedBytes:b,flushes:ve,flushMs:ge}),applyNow:es,applyExtentsNow:Jn,close:Gn,readExtent:Et,descendants:or,retain:Wr,remapLinks:Ln,childrenOf:r=>[...U.get(r)??[]].sort(),refresh:yn,follow:pn,clock:Nr,readerSeed:ln,imageCompletionSeed:dn,imageLine:()=>j?.lineForReader()??e.packages?.imageLine(),imageStartupSet:()=>j?.readDigests()??j?.completedDigests()??[],prefetchImage:(r,n)=>j?.prefetch(r,n)??{queued:0,done:Promise.resolve()},imageBlockedReads:()=>{const r=j?.blockedReads??{ranges:0,ms:0},n=e.packages?.imageBlockedReads()??{ranges:0,ms:0};return{ranges:r.ranges+n.ranges,ms:r.ms+n.ms}},seeded:()=>Mr,get logBytes(){return N},checkpoint:Ot,deferMaintenance:Sn,installPreparedImage:Dn,installPreparedProject:Cn,get deferredImage(){return _e},get imagePlacedAt(){return a&&G?L:void 0},get entries(){return g},get packBytes(){return v},read:hn,readRange:wn,snapshot:zn,replace:qr,apply:En,flush:()=>{if(Y||!a)throw new Error("This OPFS workspace is not open.");if(He)throw new Error("Wait for the OPFS generation replacement before flushing it.");Ee()},validateSnapshot:ar,validateMutationBatch:qn}}async function po(s,e,t,o){const a=ws(s);await a.initialize(xe,{readOnly:!0,extentsOnly:!0});const d=ws(s,{packages:a,ownsPackages:!0});let f;try{f=await d.initialize(e,{readOnly:!0,...t?{seed:t}:{}})}catch(h){throw d.close(),a.close(),h}if(!f&&!d.opened()){a.close();return}return d}const ho="sweep.json";async function wo(s){const t=await(await s.getFileHandle(ho,{create:!0})).createWritable();await t.write(JSON.stringify({at:Date.now()})),await t.close()}class zt{map=new Map;get(e){return this.map.get(e)}mutable(e){let t=this.map.get(e);return t||(t=new Set,this.map.set(e,t)),t}delete(e){this.map.delete(e)}}function mo(s){const e=s.toBase64;if(typeof e=="function")return e.call(s);let t="";for(let o=0;o<s.byteLength;o+=32768)t+=String.fromCharCode(...s.subarray(o,o+32768));return btoa(t)}function Ws(s){const e=Uint8Array.fromBase64;if(typeof e=="function")return e(s);const t=atob(s),o=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)o[a]=t.charCodeAt(a);return o}function yo(s,e,t){const{appended:o,superseded:a}=t?_o(s,e,t):{appended:new Map,superseded:new Set},d=[...e.removed].sort((h,m)=>Ut(m)-Ut(h));for(const h of d)s.existsSync(h)&&(s.statSync(h).isDirectory()?s.rmdirSync(h):s.unlinkSync(h));const f=[...e.files].filter(h=>!a.has(h.path)).sort((h,m)=>Ut(h.path)-Ut(m.path));for(const h of f){if(h.type==="directory")s.existsSync(h.path)&&!s.statSync(h.path).isDirectory()&&s.unlinkSync(h.path),s.mkdirSync(h.path,{recursive:!0});else if(Ue(h)){s.existsSync(h.path)&&s.statSync(h.path).isDirectory()&&s.rmdirSync(h.path);const m=h.path.slice(0,h.path.lastIndexOf("/"))||"/";m!=="/"&&!s.existsSync(m)&&s.mkdirSync(m,{recursive:!0});const w=s.existsSync(h.path)?s.statSync(h.path).mode:void 0,b=w!==void 0&&(w&128)===0;b&&s.chmodSync?.(h.path,w&4095|128),s.writeFileSync(h.path,o.get(h.path)??pt(h)),b&&h.mode===void 0&&s.chmodSync?.(h.path,w&4095)}else if(!s.existsSync(h.path)||s.statSync(h.path).isDirectory())continue;h.mode!==void 0&&s.chmodSync?.(h.path,h.mode),h.mtimeMs!==void 0&&s.utimesSync?.(h.path,new Date(h.mtimeMs),new Date(h.mtimeMs))}}function _o(s,e,t){const o=new Map,a=new Set,d=t.byPath,f=d instanceof Map?d:new Map(t.files.map(w=>[w.path,w])),h=new Map(e.files.map(w=>[w.path,w])),m=new Set([...e.files.map(w=>w.path),...e.removed]);for(const w of m){const b=f.get(w),k=So(s,w);if(b!==void 0&&yr(b,h.get(w))||k===void 0&&h.get(w)!==void 0)continue;const P=h.get(w);if(!(k!==void 0&&P!==void 0&&P.type===k.type&&(C(P).mtimeMs??0)>(C(k).mtimeMs??0))&&!(b!==void 0&&k!==void 0&&b.type===k.type&&(C(k).mtimeMs??0)<(C(b).mtimeMs??0))&&!yr(b,k)&&!yr(h.get(w),k)){if(bo(b,k,h.get(w)))continue;const F=go(s,w,b,k,h.get(w),t.bytesOf?.bind(t));if(F){o.set(w,F);continue}const g=h.get(w);if(b!==void 0&&k!==void 0&&g!==void 0&&g.type===k.type&&(C(g).mtimeMs??0)>=(C(b).mtimeMs??0)&&(C(k).mtimeMs??0)>(C(g).mtimeMs??0)&&(C(k).mtimeMs??0)>(C(b).mtimeMs??0)){a.add(w);continue}throw new Error(`Browser filesystem write conflict at ${w}. ${JSON.stringify({base:mr(b),current:mr(k),proposed:mr(h.get(w))})}`)}}return{appended:o,superseded:a}}function go(s,e,t,o,a,d){if(t?.type!=="file"||o?.type!=="file"||a?.type!=="file"||!Ue(a)||!s.readFileSync||C(o).mode!==C(a).mode)return;const f=Ue(t)?pt(t):d?.(e);if(!f||f.length===0)return;const h=pt(a),m=s.readFileSync(e),w=typeof m=="string"?new TextEncoder().encode(m):m,b=P=>P.length>=f.length&&Js(P.subarray(0,f.length),f);if(h.length<=f.length||!b(h)||!b(w))return;const k=new Uint8Array(w.length+h.length-f.length);return k.set(w,0),k.set(h.subarray(f.length),w.length),k}function mr(s){return s?{type:s.type,...C(s)}:null}function bo(s,e,t){return e?.type!=="directory"||t?.type!=="directory"?!1:s===void 0?C(e).mode===C(t).mode:C(e).mode===C(t).mode&&s.type==="directory"&&C(s).mode===C(e).mode}function ko(s,e){const t=new Set(e.removed),o=new Map(e.files.map(d=>[d.path,d])),a=[];for(const d of s.files){if(t.has(d.path))continue;const f=o.get(d.path);if(f){a.push(f),o.delete(d.path);continue}a.push(d)}for(const d of o.values())a.push(d);return{files:a}}function Eo(s,e,t={}){const o=new Map(s.files.map(d=>[d.path,d])),a=new Map(e.files.map(d=>[d.path,d]));return{files:e.files.filter(d=>{const f=o.get(d.path);return d.path==="/"&&!f?!1:!f||f.type!==d.type||!Hs(f,d)||t.written===!0&&d.type==="file"&&!Ue(f)&&Ue(d)||C(f).mode!==C(d).mode||C(f).mtimeMs!==C(d).mtimeMs}),removed:s.files.flatMap(d=>a.has(d.path)?[]:[d.path])}}function Ut(s){let e=1;for(let t=0;t<s.length;t+=1)s.charCodeAt(t)===47&&(e+=1);return e}function So(s,e){if(!s.existsSync(e))return;const t=s.statSync(e),o={...t.mode!==void 0?{mode:t.mode}:{},...t.mtimeMs!==void 0?{mtimeMs:t.mtimeMs}:{}};return t.isDirectory()?{path:e,type:"directory",...o}:{path:e,type:"file",...t.size!==void 0?{size:t.size}:{},...o}}function yr(s,e){return s===void 0?e===void 0:e!==void 0&&s.type===e.type&&Hs(s,e)&&C(s).mode===C(e).mode&&C(s).mtimeMs===C(e).mtimeMs}function C(s){const e=s;return{...e.mode===void 0?{}:{mode:e.mode&4095},...e.mtimeMs===void 0?{}:{mtimeMs:e.mtimeMs}}}function Hs(s,e){return s.type!=="file"||e.type!=="file"?!0:s.content!==void 0&&e.content!==void 0?s.content===e.content:Ue(s)&&Ue(e)?Js(pt(s),pt(e)):ms(s)===ms(e)}function ms(s){if(s.size!==void 0)return s.size;if(s.bytes!==void 0)return s.bytes.byteLength;if(s.content===void 0)return;const e=s.content.endsWith("==")?2:s.content.endsWith("=")?1:0;return Math.floor(s.content.length*3/4)-e}function Ue(s){return s!==void 0&&(s.bytes!==void 0||s.content!==void 0)}function pt(s){return s.bytes??(s.content===void 0?void 0:Ws(s.content))}function Js(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;let t=0;if(s.byteOffset%4===0&&e.byteOffset%4===0){const o=s.byteLength>>>2,a=new Uint32Array(s.buffer,s.byteOffset,o),d=new Uint32Array(e.buffer,e.byteOffset,o);for(let f=0;f<o;f+=1)if(a[f]!==d[f])return!1;t=o<<2}for(;t<s.byteLength;t+=1)if(s[t]!==e[t])return!1;return!0}const Or="314.0.6",Po=`https://cdn.jsdelivr.net/pyodide/v${Or}/full/`,xo=[{file:"pyodide.mjs",integrity:"sha256-aeP2zOw+FLRl32C+V3ymL1NiUUBrmgDM4BnqxSUqJJU=",bytes:17931},{file:"pyodide.asm.mjs",integrity:"sha256-KsXro2XsEoOcdcA7ObO+HdY7eYhSzEYLAUtSI4vgQvc=",bytes:1250344},{file:"pyodide.asm.wasm",integrity:"sha256-OgoA3+qjSKwg+e8JkEIz0y0z9kQzlmLUrzaPiiAQ83o=",bytes:9598218},{file:"python_stdlib.zip",integrity:"sha256-gMW+a6v+AylwaXA0EMPClATc8lJdKxKHRrrlU2+Ugx8=",bytes:2545564},{file:"pyodide-lock.json",integrity:"sha256-P9rvCenjZcheACc3cg+NCrjyeMHCRKLd5qN2Y89IitQ=",bytes:114440}];function Ao(s){const e=xo.find(t=>t.file===s);if(!e)throw new Error(`Pyodide ${Or} publishes no pinned ${s}.`);return e}async function vo(s){const e=new Uint8Array(await crypto.subtle.digest("SHA-256",s));let t="";for(const o of e)t+=String.fromCharCode(o);return`sha256-${btoa(t)}`}async function ys(s,e){const t=Ao(s),o=await vo(e);if(o!==t.integrity)throw new Error(`Pyodide ${Or} ${s} is ${o}, not the pinned ${t.integrity}.`)}const J="/workspace";let _s,Yt="program";function Io(){return Yt}async function Oo(s,e){const t=Yt;Yt=s;try{return await e()}finally{Yt=t}}async function To(s){return new Uint8Array(await new Response(new Blob([s]).stream().pipeThrough(new DecompressionStream("gzip"))).arrayBuffer())}function Gs(s=Po,e){return _s??=(async()=>{const t=e?await To(e).catch(()=>{}):void 0,o=async(a,d)=>{if(t)try{const f=await a.loadPyodide({...d,_loadSnapshot:t});return await f.runPythonAsync(`import random
5
- random.seed()`),delete f._api?.config?._loadSnapshot,f}catch(f){console.warn(`[python] the interpreter snapshot did not restore; starting Python: ${f instanceof Error?f.message:String(f)}`)}return await a.loadPyodide(d)};return Oo("runtime",async()=>{if(s.startsWith("/")){const b=await import(`file://${s}pyodide.mjs`),k=await import(`file://${s}pyodide.asm.mjs`);return await o(b,{indexURL:s,createPyodideModule:k.default})}const[a,d]=await Promise.all([fetch(`${s}pyodide.mjs`),fetch(`${s}pyodide.asm.mjs`)]);if(!a.ok)throw new Error(`Could not load Pyodide (${a.status}).`);if(!d.ok)throw new Error(`Could not load the Pyodide runtime module (${d.status}).`);const[f,h]=await Promise.all([a.bytes(),d.bytes()]);await ys("pyodide.mjs",f),await ys("pyodide.asm.mjs",h);const m=URL.createObjectURL(new Blob([f],{type:"text/javascript"})),w=URL.createObjectURL(new Blob([h],{type:"text/javascript"}));try{const b=await import(m),k=await import(w);return await o(b,{indexURL:s,createPyodideModule:k.default})}finally{URL.revokeObjectURL(m),URL.revokeObjectURL(w)}})})(),_s}const No=16384;function Mo(s){return{existsSync:e=>s.analyzePath(e).exists,statSync:e=>{const t=s.stat(e),o=(t.mode&61440)===No;return{isDirectory:()=>o,...typeof t.size=="number"?{size:t.size}:{},...Sr(t)}},readFile:e=>Promise.resolve(s.readFile(e)),writeFileSync:(e,t)=>s.writeFile(e,typeof t=="string"?new TextEncoder().encode(t):t),mkdirSync:e=>s.mkdirTree(e),unlinkSync:e=>s.unlink(e),rmdirSync:e=>s.rmdir(e),chmodSync:(e,t)=>s.chmod(e,t),utimesSync:(e,t,o)=>s.utime(e,gs(t),gs(o))}}function Fo(s,e,t){yo(Mo(s),e,t)}function gs(s){return s instanceof Date?s.getTime():s}function Lo(s,e){Qs(s,J),s.mkdirTree(J);const t=e.files.slice().sort((o,a)=>bs(o.path)-bs(a.path));for(const o of t)o.path!==J&&!o.path.startsWith(`${J}/`)||(o.type==="directory"?s.mkdirTree(o.path):(s.mkdirTree(o.path.slice(0,o.path.lastIndexOf("/"))||"/"),s.writeFile(o.path,$o(o.content??""))));for(const o of t){const a=o;a.path!==J&&!a.path.startsWith(`${J}/`)||(a.mode!==void 0&&s.chmod(a.path,a.mode),a.mtimeMs!==void 0&&s.utime(a.path,a.mtimeMs,a.mtimeMs))}}function Ys(s,e){const o=[...e.files.filter(a=>a.path!==J&&!a.path.startsWith(`${J}/`))];return Ks(s,J,o),{files:o}}function Kt(s,e){const t=s.startsWith("/")?s:`${e}/${s}`,o=[];for(const a of t.split("/"))!a||a==="."||(a===".."?o.pop():o.push(a));return`/${o.join("/")}`}function je(s){return s.slice(s.lastIndexOf("/")+1)}function Vs(s){let e="";for(let t=0;t<s.byteLength;t+=32768)e+=String.fromCharCode(...s.subarray(t,t+32768));return btoa(e)}function $o(s){const e=atob(s);return Uint8Array.from(e,t=>t.charCodeAt(0))}function Ks(s,e,t){const o=s.stat(e),a=Sr(o);t.push({path:e,type:"directory",...a});for(const d of s.readdir(e)){if(d==="."||d==="..")continue;const f=`${e}/${d}`,h=s.stat(f);(h.mode&61440)===16384?Ks(s,f,t):t.push({path:f,type:"file",content:Vs(s.readFile(f)),...Sr(h)})}}function Qs(s,e){if(s.analyzePath(e).exists)for(const t of s.readdir(e)){if(t==="."||t==="..")continue;const o=`${e}/${t}`;(s.stat(o).mode&61440)===16384?(Qs(s,o),s.rmdir(o)):s.unlink(o)}}function bs(s){let e=1;for(let t=0;t<s.length;t+=1)s.charCodeAt(t)===47&&(e+=1);return e}function Sr(s){const e=s.mtime instanceof Date?s.mtime.getTime():s.mtime;return{mode:s.mode&4095,...typeof e=="number"&&Number.isFinite(e)?{mtimeMs:e}:{}}}const Pr=16384,Ro=32768,ks=44;function Bo(s,e){const t=s,o=t.filesystems?.MEMFS;if(!o||typeof t.mount!="function"||typeof o.createNode!="function")return;const a={dirty:new Set,removed:new Set},d=()=>t.genericErrors?.[ks]??new t.ErrnoError(ks),f=T=>T.packPath??J;function h(T,R,L){const S=e.entries.get(L);if(!S)throw d();const x=S.mode&4095|(S.type==="directory"?Pr:Ro),A=o.createNode(T,R,x,0);return A.packPath=L,A.timestamp=S.mtimeMs,A.atime=A.mtime=A.ctime=S.mtimeMs,S.type==="directory"?(A.packListed=!1,A.node_ops=P(A.node_ops)):(A.packLoaded=!1,A.usedBytes=S.length,A.node_ops=g(A.node_ops),A.stream_ops=$(A.stream_ops)),A}function m(T){if(T.packLoaded!==!1||!T.packPath)return;const R=e.read(T.packPath);T.contents=R,T.usedBytes=R.byteLength,T.packLoaded=!0}function w(T){t.isDir(T.mode)||a.dirty.add(b(T))}function b(T){const R=[];let L=T;for(;L&&L.parent!==L;)R.unshift(L.name),L=L.parent;return`${J}/${R.join("/")}`.replace(/\/+$/u,"")||J}const k=new WeakMap;function P(T){const R=k.get(T);if(R)return R;const L={...T,lookup:(S,x)=>{const A=`${f(S)}/${x}`;if(!a.removed.has(A)&&e.entries.has(A))return h(S,x,A);throw d()},readdir:S=>{const x=T.readdir(S),A=new Set(x),D=f(S);for(const H of e.childrenOf(D))a.removed.has(`${D}/${H}`)||A.add(H);return[...A]},mknod:(S,x,A,D)=>{const H=`${f(S)}/${x}`;a.removed.delete(H);const v=T.mknod(S,x,A,D);return v.packPath=H,t.isDir(A)?(v.packListed=!0,v.node_ops=P(v.node_ops)):(v.packLoaded=!0,a.dirty.add(H),v.node_ops=g(v.node_ops),v.stream_ops=$(v.stream_ops)),v},unlink:(S,x)=>{const A=`${f(S)}/${x}`;T.unlink(S,x),a.dirty.delete(A),a.removed.add(A)},rmdir:(S,x)=>{const A=`${f(S)}/${x}`;for(const D of e.childrenOf(A))if(!a.removed.has(`${A}/${D}`))throw new t.ErrnoError(55);T.rmdir(S,x),a.removed.add(A)},rename:(S,x,A)=>{const D=b(S);t.isFile(S.mode)?m(S):G(S),T.rename(S,x,A);const H=`${f(x)}/${A}`;j(S,D,H),a.removed.add(D),a.removed.delete(H)}};return k.set(T,L),L}const F=new WeakMap;function g(T){const R=F.get(T);if(R)return R;const L={...T,setattr:(S,x)=>{x.size!==void 0&&m(S),T.setattr(S,x),(x.size!==void 0||x.mode!==void 0||x.timestamp!==void 0)&&w(S)}};return F.set(T,L),L}const U=new WeakMap;function $(T){const R=U.get(T);if(R)return R;const L={...T,open:S=>{m(S.node),T.open?.(S)},write:(S,x,A,D,H,v)=>{m(S.node);const K=T.write(S,x,A,D,H,v);return w(S.node),K}};return U.set(T,L),L}function G(T){const R=f(T);for(const L of e.childrenOf(R)){if(a.removed.has(`${R}/${L}`))continue;const x=T.contents[L]??h(T,L,`${R}/${L}`);t.isDir(x.mode)?G(x):m(x)}T.packListed=!0}function j(T,R,L){if(T.packPath=L,t.isFile(T.mode)){a.dirty.delete(R),a.dirty.add(L);return}for(const[S,x]of Object.entries(T.contents))j(x,`${R}/${S}`,`${L}/${S}`)}const _e={mount:()=>{const T=o.createNode(null,"/",Pr|493,0);return T.packPath=J,T.node_ops=P(T.node_ops),T}};if(t.analyzePath(J).exists){try{t.unmount(J)}catch{}try{t.rmdir(J)}catch{}}return t.mkdirTree(J),t.mount(_e,{},J),a}function Do(s,e,t){const o=t.files.filter(d=>d.path!==J&&!d.path.startsWith(`${J}/`)),a=d=>{const f=s.stat(d),h=f.mtime instanceof Date?f.mtime.getTime():f.mtime,m={mode:f.mode&4095,...typeof h=="number"&&Number.isFinite(h)?{mtimeMs:h}:{}};if((f.mode&61440)===Pr){o.push({path:d,type:"directory",...m});for(const w of s.readdir(d))w==="."||w===".."||a(`${d}/${w}`);return}e.dirty.has(d)?o.push({path:d,type:"file",content:Vs(s.readFile(d)),...m}):o.push({path:d,type:"file",...typeof f.size=="number"?{size:f.size}:{},...m})};return a(J),{files:o}}const Ce="/workspace/.supercode/python-requirements.txt",Es=64,Co=256;async function zo(s){const e=Ho(s.FS);e.length!==0&&(Ms({door:"pip install",subject:`${e.join(" ")}, recorded in ${Ce} by an earlier session`,fix:`a Python project's packages cannot yet be carried as packs; remove ${Ce} to run Python without them.`}),await Xs(s,e),en(s.FS,await Zs(s)))}async function Uo(s,e){e.requirements.length!==0&&(await Xs(s,e.requirements),en(s.FS,await Zs(s)))}function jo(s){const e=new Map;let t;for(const o of s.split(`
6
- `)){const a=o.trim();if(a==="[[package]]"){t=void 0;continue}if(a.startsWith("[")&&a!=="[[package]]"){t=void 0;continue}const d=/^name\s*=\s*"([^"]+)"$/u.exec(a);if(d){t=d[1];continue}const f=/^version\s*=\s*"([^"]+)"$/u.exec(a);f&&t&&!e.has(t)&&e.set(t,f[1])}return e}function qo(s,e){const t=/^[A-Za-z0-9._-]+/u.exec(s.trim())?.[0];if(!t)return s;const o=e.get(t)??e.get(t.toLowerCase())??e.get(t.replace(/_/gu,"-").toLowerCase());return o?`${t}==${o}`:s}function Wo(s,e,t){const o=je(e[0]??""),a=o==="pip"||o==="pip3"?e.slice(1):(o==="python"||o==="python3")&&e[1]==="-m"&&e[2]==="pip"?e.slice(3):void 0;if(!a)return;if(a[0]!=="install")throw new Error("pip in the tab supports only `pip install <packages> [-r requirements.txt]`, and only as a temporary path: a project's Python dependencies are meant to be prepared on a machine by `npx @volter/browser-substrate dev`.");const d=[];let f=!1;for(let m=1;m<a.length;m+=1){const w=a[m];if(!(w==="--disable-pip-version-check"||w==="-q"||w==="--quiet")){if(w==="-r"||w==="--requirement"){const b=a[++m];if(!b)throw new Error(`${w} requires a file path.`);const k=Kt(b,t);if(!s.analyzePath(k).exists)throw new Error(`pip: requirements file not found: ${k}`);d.push(...tn(new TextDecoder().decode(s.readFile(k)))),f=!0;continue}if(w.startsWith("-"))throw new Error(`browser pip does not support option: ${w}`);d.push(w)}}if(d.length===0&&!f)throw new Error("pip install requires at least one package.");const h=Kt("uv.lock",t);if(s.analyzePath(h).exists){const m=jo(new TextDecoder().decode(s.readFile(h)));if(m.size>0){const w=d.map(b=>qo(b,m));return st(w),{requirements:w,lockfile:{file:"uv.lock",pins:m.size}}}}return st(d),{requirements:d}}async function Xs(s,e){st(e),Ms({door:"pip install",subject:e.join(" "),detail:{requirements:e.join(" ")},fix:"a Python project's packages cannot yet be carried as packs, so the tab cannot provide them."})}async function Zs(s){const e=await s.runPythonAsync(`
4
+ `,1)[0];if(!c.startsWith('{"retainedIndex":')||!c.endsWith(","))return;const f=JSON.parse(c.slice(0,-1)+"}").retainedIndex;if(f.version!==1&&f.version!==2||!/^[a-f0-9]{64}$/u.test(f.digest)||![f.packBytes,f.liveBytes,f.linked,f.linkedBytes].every(O=>Number.isSafeInteger(O)&&O>=0)||f.version===1&&f.journalPrefix!==void 0||f.version===2&&(!f.journalPrefix||!Number.isSafeInteger(f.journalPrefix.bytes)||f.journalPrefix.bytes<0||!/^[a-f0-9]{64}$/u.test(f.journalPrefix.digest)))return;const p=await r.getFileHandle(Tt),y=await Z(p,"index");let _;try{const O=y.getSize();if(O>256*1024*1024||(_=new Uint8Array(O),y.read(_,{at:0})!==O))return}finally{y.close()}if(await Jr(_,f)!==f.digest)return;const E=new SharedArrayBuffer(_.byteLength);new Uint8Array(E).set(_);const M=new Re(E);return we(M.entryCount),{...f,index:E}}catch{return}}async function jn(r){const n=r.journalPrefix;if(!n||!S||!$||n.bytes>S.getSize()||r.packBytes>$.getSize())return 0;const i=new Uint8Array(n.bytes);return S.read(i,{at:0})!==i.byteLength?0:await me(i)===n.digest?n.bytes:0}async function Fe(r,n){let i;try{i=await r.getFileHandle(n)}catch(f){if(Ve(f))return;throw f}let l;if(u){l=await(await i.getFile()).text();try{return JSON.parse(l)}catch(f){throw new Error(`Invalid OPFS workspace metadata (${n}). Stored data was retained.`,{cause:f})}}const c=await Z(i,"index");try{const f=c.getSize(),p=new Uint8Array(f);if(f>0&&c.read(p,{at:0})!==f)throw new Error("An OPFS workspace file could not be read completely.");l=Qe.decode(p)}finally{c.close()}try{return JSON.parse(l)}catch(f){throw new Error(`Invalid OPFS workspace metadata (${n}). Stored data was retained.`,{cause:f})}}async function Gr(r,n,i){try{await r.removeEntry(n,{recursive:i})}catch(l){if(!Ve(l))throw l}}async function Yr(r,n){try{await r.removeEntry(n,{recursive:!0})}catch{}}function Vr(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid OPFS filesystem mutation.");if(r.operation!=="write"&&r.operation!=="append"&&r.operation!=="write-at"&&r.operation!=="mkdir"&&r.operation!=="remove"&&r.operation!=="rename"&&r.operation!=="metadata"&&r.operation!=="link")throw new Error("Invalid OPFS filesystem mutation.");if(ye(r.path),r.operation==="rename"&&ye(r.destination),(r.operation==="write"||r.operation==="append"||r.operation==="write-at")&&!(r.content instanceof Uint8Array))throw new Error("Invalid OPFS file content.");if(r.operation==="write-at"&&(!Number.isSafeInteger(r.position)||r.position<0))throw new Error("Invalid OPFS write position.");return cr(r),r}function qn(r){if(!Array.isArray(r)||r.length===0||r.length>128)throw new Error("Invalid OPFS filesystem mutation batch.");return r.map(n=>Vr(n))}function ar(r){if(!r||!Array.isArray(r.files)||r.files.length>o||!(r.pack instanceof ArrayBuffer))throw new Error("Invalid OPFS workspace snapshot.");const n=new Set,i=new Map(ke().map(c=>[c,"directory"]));let l=0;for(const c of r.files){if(!c||typeof c!="object")throw new Error("Invalid OPFS workspace snapshot entry.");if(ye(c.path),c.type!=="file"&&c.type!=="directory"&&c.type!=="symlink"||n.has(c.path))throw new Error("Invalid or duplicate OPFS workspace entry.");if(n.add(c.path),i.set(c.path,c.type),ke().includes(c.path)&&c.type!=="directory")throw new Error("The OPFS workspace root must be a directory.");if(c.type!=="directory"){const f=c.offset??0,p=c.length??0;if(!Number.isSafeInteger(f)||!Number.isSafeInteger(p)||f<0||p<0||p>ne||f+p>r.pack.byteLength)throw new Error("Invalid OPFS workspace file.");if(l+=p,l>t)throw new Error("OPFS workspace exceeds its byte limit.")}else if((c.offset??0)!==0||(c.length??0)!==0)throw new Error("An OPFS workspace directory cannot contain file bytes.");cr(c)}we(i.size);for(const c of r.files)if(!ke().includes(c.path)&&i.get(Le(c.path))!=="directory")throw new Error(`An OPFS workspace snapshot has no directory parent for ${c.path}.`);return r}function cr(r){if(r.mode!==void 0&&(!Number.isSafeInteger(r.mode)||r.mode<0||r.mode>4095))throw new Error("Invalid OPFS file mode.");if(r.mtimeMs!==void 0&&(typeof r.mtimeMs!="number"||!Number.isFinite(r.mtimeMs)||r.mtimeMs<0))throw new Error("Invalid OPFS modification time.")}function Wn(r){return{entries:[...r]}}function lr(r){const n=new Map;if(r===void 0)throw new Error("The committed OPFS workspace index is missing. Stored data was retained.");if(!r||typeof r!="object"||!Array.isArray(r.entries))throw new Error("Invalid OPFS workspace index.");const i=r.entries;we(i.length);for(const l of i){if(!Array.isArray(l)||l.length!==2)throw new Error("Invalid OPFS workspace index entry.");const c=ye(l[0]);if(n.has(c))throw new Error("Duplicate OPFS workspace index entry.");n.set(c,Kr(l[1]))}return n}function Kr(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid OPFS workspace index entry.");const n=r;if(n.type!=="file"&&n.type!=="directory"&&n.type!=="symlink")throw new Error("Invalid OPFS workspace index entry.");if(cr(n),n.mode===void 0||n.mtimeMs===void 0)throw new Error("Invalid OPFS workspace index entry.");if(!Number.isSafeInteger(n.offset)||n.offset<0||!Number.isSafeInteger(n.length)||n.length<0||n.length>ne)throw new Error("Invalid OPFS workspace index extent.");if(n.pack!==void 0&&n.pack!==xe)throw new Error("Invalid OPFS workspace index entry.");return{type:n.type,mode:n.mode,mtimeMs:n.mtimeMs,offset:n.offset,length:n.length,...n.pack?{pack:n.pack}:{}}}function Hn(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid OPFS workspace index record.");const n=r;if(!Number.isSafeInteger(n.packBytes)||n.packBytes<0||!Array.isArray(n.changes))throw new Error("Invalid OPFS workspace index record.");const i=[];for(const l of n.changes){if(!Array.isArray(l)||l.length!==2)throw new Error("Invalid OPFS workspace index record.");i.push([ye(l[0]),l[1]===null?null:Kr(l[1])])}return{packBytes:n.packBytes,changes:i}}function Ft(r){if(r===void 0)return;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid OPFS workspace state. Stored data was retained.");const n=r;if(n.storageVersion!==4&&n.storageVersion!==5||n.storageVersion===5&&(typeof n.imageRanges!="string"||!/^[a-f0-9]{64}$/u.test(n.imageRanges))||n.storageVersion===4&&n.imageRanges!==void 0||typeof n.generation!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(n.generation)||typeof n.initializedAt!="number"||!Number.isFinite(n.initializedAt))throw new Error("Invalid or unsupported OPFS workspace state. Stored data was retained.");return n}function ye(r){if(typeof r!="string"||ct(r)===void 0||r.includes("\0")||r.length>4096)throw new Error("Invalid OPFS workspace path.");return Qr(r),r}function Qr(r){const n=ct(r);if(n===void 0)throw new Error("Invalid OPFS workspace path.");const i=r===n?"":r.slice(n.length+1);return dr(i),i}function dr(r){const n=r===""?[]:r.split("/");if(n.some(i=>!i||i==="."||i===".."||i.includes("\0")))throw new Error("Invalid OPFS workspace path segment.");return n}function Le(r){const n=r.slice(0,r.lastIndexOf("/"));return n===""||ct(n)===void 0?ct(r)??r:n}function Xr(r){let n=1;for(let i=0;i<r.length;i+=1)r.charCodeAt(i)===47&&(n+=1);return n}function Ve(r){return r instanceof DOMException&&r.name==="NotFoundError"}function Zr(r){let n=2166136261;for(let i=0;i<r.byteLength;i+=1)n^=r[i],n=Math.imul(n,16777619);return n>>>0}typeof addEventListener=="function"&&addEventListener("close",()=>{$?.flush(),S?.flush(),Ge(),k?.()});function es(r,n={}){if(be(),ae)throw new Error("An OPFS mutation batch cannot be nested.");for(const i of r)Vr(i);return r.length?ts(i=>{for(const l of r)Pn(l,i)},n):[]}function Jn(r,n,i={}){if(be(),ae)throw new Error("An OPFS mutation batch cannot be nested.");for(const l of n){if(ye(l.path),l.type!=="file"&&l.type!=="directory"&&l.type!=="symlink")throw new Error(`OPFS extent ${l.path} has no valid type.`);if(l.type==="directory")continue;const{offset:c,length:f}=l;if(c===void 0||f===void 0||!Number.isSafeInteger(c)||!Number.isSafeInteger(f)||c<0||f<0||c+f>r.byteLength)throw new Error(`OPFS extent ${l.path} lies outside its bytes.`);if(f>ne)throw new Error(`${l.path} is ${f} bytes; an OPFS workspace file holds at most ${ne}.`)}return n.length?ts(l=>{const c=r.byteLength>0?It(r):v;for(const f of n){const p=ye(f.path);Me(p,l);const y=g.get(p);if(f.type==="directory"){if(y&&y.type!=="directory")throw new Error(`OPFS path is a file: ${p}`);ee(p,{type:"directory",mode:f.mode,mtimeMs:f.mtimeMs,offset:0,length:0},l);continue}if(y?.type==="directory")throw new Error(`OPFS write target is a directory: ${p}`);At(p,f.length),ee(p,{type:f.type,mode:f.mode,mtimeMs:f.mtimeMs,offset:c+f.offset,length:f.length},l)}},i):[]}function ts(r,n){if(!$||!S)throw new Error("OPFS filesystem worker is not initialized.");const i={packBytes:v,logBytes:T,liveBytes:B,deadBytes:Q,rewrites:Ie,rewrittenBytes:Oe,linked:w,linkedBytes:b},l=new Map;ae=l;const c=[];mt=c;const f=[];try{return r(f),Ur(),In(f,{publish:!n.durable}),n.durable&&(Ee(),yt()),Rr(),f}catch(p){const y=V!==void 0&&!fe&&Atomics.load(V,us)!==i.logBytes;y&&ot();for(const[_,E]of l)E===void 0?g.delete(_):g.set(_,E);Ye();try{for(let _=c.length-1;_>=0;_-=1)vt(c[_][0],c[_][1])}catch(_){p=new AggregateError([p,_],"OPFS could not restore bytes a failed batch wrote over.")}({packBytes:v,logBytes:T,liveBytes:B,deadBytes:Q,rewrites:Ie,rewrittenBytes:Oe,linked:w,linkedBytes:b}=i),K!==void 0&&(clearTimeout(K),K=void 0);try{S.truncate(T),S.flush(),$.truncate(v),$.flush()}catch(_){throw _t(),ue=new AggregateError([p,_],"OPFS could not roll back a failed batch; reopen this workspace before writing again."),ue}throw y&&it(),p}finally{ae=void 0,mt=void 0}}function Gn(){if(qe){nt?.abort(new DOMException("The workspace was closed while opening.","AbortError"));return}Y||(Y=!0,We===0&&rs())}function rs(){_t();try{Ee()}finally{try{Ge()}finally{const r=k;k=void 0,a=void 0;try{r?.()}finally{e.ownsPackages&&e.packages?.close()}}}}return{initialize:mn,opened:()=>a!==void 0&&!Y,stats:()=>({entries:g.size,liveBytes:B,deadBytes:Q,packBytes:v,rewrites:Ie,rewrittenBytes:Oe,linked:w,linkedBytes:b,flushes:ve,flushMs:ge}),applyNow:es,applyExtentsNow:Jn,close:Gn,readExtent:Et,descendants:or,retain:Wr,remapLinks:Ln,childrenOf:r=>[...U.get(r)??[]].sort(),refresh:yn,follow:pn,clock:Tr,readerSeed:ln,imageCompletionSeed:dn,imageLine:()=>j?.lineForReader()??e.packages?.imageLine(),imageStartupSet:()=>j?.readDigests()??j?.completedDigests()??[],prefetchImage:(r,n)=>j?.prefetch(r,n)??{queued:0,done:Promise.resolve()},imageBlockedReads:()=>{const r=j?.blockedReads??{ranges:0,ms:0},n=e.packages?.imageBlockedReads()??{ranges:0,ms:0};return{ranges:r.ranges+n.ranges,ms:r.ms+n.ms}},seeded:()=>Mr,get logBytes(){return T},checkpoint:Ot,deferMaintenance:Sn,installPreparedImage:Cn,installPreparedProject:Dn,get deferredImage(){return _e},get imagePlacedAt(){return a&&G?L:void 0},get entries(){return g},get packBytes(){return v},read:hn,readRange:wn,snapshot:zn,replace:qr,apply:En,flush:()=>{if(Y||!a)throw new Error("This OPFS workspace is not open.");if(He)throw new Error("Wait for the OPFS generation replacement before flushing it.");Ee()},validateSnapshot:ar,validateMutationBatch:qn}}async function po(s,e,t,o){const a=ws(s);await a.initialize(xe,{readOnly:!0,extentsOnly:!0});const d=ws(s,{packages:a,ownsPackages:!0});let u;try{u=await d.initialize(e,{readOnly:!0,...t?{seed:t}:{}})}catch(h){throw d.close(),a.close(),h}if(!u&&!d.opened()){a.close();return}return d}const ho="sweep.json";async function wo(s){const t=await(await s.getFileHandle(ho,{create:!0})).createWritable();await t.write(JSON.stringify({at:Date.now()})),await t.close()}class zt{map=new Map;get(e){return this.map.get(e)}mutable(e){let t=this.map.get(e);return t||(t=new Set,this.map.set(e,t)),t}delete(e){this.map.delete(e)}}function mo(s){const e=s.toBase64;if(typeof e=="function")return e.call(s);let t="";for(let o=0;o<s.byteLength;o+=32768)t+=String.fromCharCode(...s.subarray(o,o+32768));return btoa(t)}function Ws(s){const e=Uint8Array.fromBase64;if(typeof e=="function")return e(s);const t=atob(s),o=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)o[a]=t.charCodeAt(a);return o}function yo(s,e,t){const{appended:o,superseded:a}=t?_o(s,e,t):{appended:new Map,superseded:new Set},d=[...e.removed].sort((h,m)=>Ut(m)-Ut(h));for(const h of d)s.existsSync(h)&&(s.statSync(h).isDirectory()?s.rmdirSync(h):s.unlinkSync(h));const u=[...e.files].filter(h=>!a.has(h.path)).sort((h,m)=>Ut(h.path)-Ut(m.path));for(const h of u){if(h.type==="directory")s.existsSync(h.path)&&!s.statSync(h.path).isDirectory()&&s.unlinkSync(h.path),s.mkdirSync(h.path,{recursive:!0});else if(Ue(h)){s.existsSync(h.path)&&s.statSync(h.path).isDirectory()&&s.rmdirSync(h.path);const m=h.path.slice(0,h.path.lastIndexOf("/"))||"/";m!=="/"&&!s.existsSync(m)&&s.mkdirSync(m,{recursive:!0});const w=s.existsSync(h.path)?s.statSync(h.path).mode:void 0,b=w!==void 0&&(w&128)===0;b&&s.chmodSync?.(h.path,w&4095|128),s.writeFileSync(h.path,o.get(h.path)??pt(h)),b&&h.mode===void 0&&s.chmodSync?.(h.path,w&4095)}else if(!s.existsSync(h.path)||s.statSync(h.path).isDirectory())continue;h.mode!==void 0&&s.chmodSync?.(h.path,h.mode),h.mtimeMs!==void 0&&s.utimesSync?.(h.path,new Date(h.mtimeMs),new Date(h.mtimeMs))}}function _o(s,e,t){const o=new Map,a=new Set,d=t.byPath,u=d instanceof Map?d:new Map(t.files.map(w=>[w.path,w])),h=new Map(e.files.map(w=>[w.path,w])),m=new Set([...e.files.map(w=>w.path),...e.removed]);for(const w of m){const b=u.get(w),k=So(s,w);if(b!==void 0&&yr(b,h.get(w))||k===void 0&&h.get(w)!==void 0)continue;const P=h.get(w);if(!(k!==void 0&&P!==void 0&&P.type===k.type&&(D(P).mtimeMs??0)>(D(k).mtimeMs??0))&&!(b!==void 0&&k!==void 0&&b.type===k.type&&(D(k).mtimeMs??0)<(D(b).mtimeMs??0))&&!yr(b,k)&&!yr(h.get(w),k)){if(bo(b,k,h.get(w)))continue;const F=go(s,w,b,k,h.get(w),t.bytesOf?.bind(t));if(F){o.set(w,F);continue}const g=h.get(w);if(b!==void 0&&k!==void 0&&g!==void 0&&g.type===k.type&&(D(g).mtimeMs??0)>=(D(b).mtimeMs??0)&&(D(k).mtimeMs??0)>(D(g).mtimeMs??0)&&(D(k).mtimeMs??0)>(D(b).mtimeMs??0)){a.add(w);continue}throw new Error(`Browser filesystem write conflict at ${w}. ${JSON.stringify({base:mr(b),current:mr(k),proposed:mr(h.get(w))})}`)}}return{appended:o,superseded:a}}function go(s,e,t,o,a,d){if(t?.type!=="file"||o?.type!=="file"||a?.type!=="file"||!Ue(a)||!s.readFileSync||D(o).mode!==D(a).mode)return;const u=Ue(t)?pt(t):d?.(e);if(!u||u.length===0)return;const h=pt(a),m=s.readFileSync(e),w=typeof m=="string"?new TextEncoder().encode(m):m,b=P=>P.length>=u.length&&Js(P.subarray(0,u.length),u);if(h.length<=u.length||!b(h)||!b(w))return;const k=new Uint8Array(w.length+h.length-u.length);return k.set(w,0),k.set(h.subarray(u.length),w.length),k}function mr(s){return s?{type:s.type,...D(s)}:null}function bo(s,e,t){return e?.type!=="directory"||t?.type!=="directory"?!1:s===void 0?D(e).mode===D(t).mode:D(e).mode===D(t).mode&&s.type==="directory"&&D(s).mode===D(e).mode}function ko(s,e){const t=new Set(e.removed),o=new Map(e.files.map(d=>[d.path,d])),a=[];for(const d of s.files){if(t.has(d.path))continue;const u=o.get(d.path);if(u){a.push(u),o.delete(d.path);continue}a.push(d)}for(const d of o.values())a.push(d);return{files:a}}function Eo(s,e,t={}){const o=new Map(s.files.map(d=>[d.path,d])),a=new Map(e.files.map(d=>[d.path,d]));return{files:e.files.filter(d=>{const u=o.get(d.path);return d.path==="/"&&!u?!1:!u||u.type!==d.type||!Hs(u,d)||t.written===!0&&d.type==="file"&&!Ue(u)&&Ue(d)||D(u).mode!==D(d).mode||D(u).mtimeMs!==D(d).mtimeMs}),removed:s.files.flatMap(d=>a.has(d.path)?[]:[d.path])}}function Ut(s){let e=1;for(let t=0;t<s.length;t+=1)s.charCodeAt(t)===47&&(e+=1);return e}function So(s,e){if(!s.existsSync(e))return;const t=s.statSync(e),o={...t.mode!==void 0?{mode:t.mode}:{},...t.mtimeMs!==void 0?{mtimeMs:t.mtimeMs}:{}};return t.isDirectory()?{path:e,type:"directory",...o}:{path:e,type:"file",...t.size!==void 0?{size:t.size}:{},...o}}function yr(s,e){return s===void 0?e===void 0:e!==void 0&&s.type===e.type&&Hs(s,e)&&D(s).mode===D(e).mode&&D(s).mtimeMs===D(e).mtimeMs}function D(s){const e=s;return{...e.mode===void 0?{}:{mode:e.mode&4095},...e.mtimeMs===void 0?{}:{mtimeMs:e.mtimeMs}}}function Hs(s,e){return s.type!=="file"||e.type!=="file"?!0:s.content!==void 0&&e.content!==void 0?s.content===e.content:Ue(s)&&Ue(e)?Js(pt(s),pt(e)):ms(s)===ms(e)}function ms(s){if(s.size!==void 0)return s.size;if(s.bytes!==void 0)return s.bytes.byteLength;if(s.content===void 0)return;const e=s.content.endsWith("==")?2:s.content.endsWith("=")?1:0;return Math.floor(s.content.length*3/4)-e}function Ue(s){return s!==void 0&&(s.bytes!==void 0||s.content!==void 0)}function pt(s){return s.bytes??(s.content===void 0?void 0:Ws(s.content))}function Js(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;let t=0;if(s.byteOffset%4===0&&e.byteOffset%4===0){const o=s.byteLength>>>2,a=new Uint32Array(s.buffer,s.byteOffset,o),d=new Uint32Array(e.buffer,e.byteOffset,o);for(let u=0;u<o;u+=1)if(a[u]!==d[u])return!1;t=o<<2}for(;t<s.byteLength;t+=1)if(s[t]!==e[t])return!1;return!0}const Or="314.0.6",Po=`https://cdn.jsdelivr.net/pyodide/v${Or}/full/`,xo=[{file:"pyodide.mjs",integrity:"sha256-aeP2zOw+FLRl32C+V3ymL1NiUUBrmgDM4BnqxSUqJJU=",bytes:17931},{file:"pyodide.asm.mjs",integrity:"sha256-KsXro2XsEoOcdcA7ObO+HdY7eYhSzEYLAUtSI4vgQvc=",bytes:1250344},{file:"pyodide.asm.wasm",integrity:"sha256-OgoA3+qjSKwg+e8JkEIz0y0z9kQzlmLUrzaPiiAQ83o=",bytes:9598218},{file:"python_stdlib.zip",integrity:"sha256-gMW+a6v+AylwaXA0EMPClATc8lJdKxKHRrrlU2+Ugx8=",bytes:2545564},{file:"pyodide-lock.json",integrity:"sha256-P9rvCenjZcheACc3cg+NCrjyeMHCRKLd5qN2Y89IitQ=",bytes:114440}];function Ao(s){const e=xo.find(t=>t.file===s);if(!e)throw new Error(`Pyodide ${Or} publishes no pinned ${s}.`);return e}async function vo(s){const e=new Uint8Array(await crypto.subtle.digest("SHA-256",s));let t="";for(const o of e)t+=String.fromCharCode(o);return`sha256-${btoa(t)}`}async function ys(s,e){const t=Ao(s),o=await vo(e);if(o!==t.integrity)throw new Error(`Pyodide ${Or} ${s} is ${o}, not the pinned ${t.integrity}.`)}const J="/workspace";let _s,Yt="program";function Io(){return Yt}async function Oo(s,e){const t=Yt;Yt=s;try{return await e()}finally{Yt=t}}async function No(s){return new Uint8Array(await new Response(new Blob([s]).stream().pipeThrough(new DecompressionStream("gzip"))).arrayBuffer())}function Gs(s=Po,e){return _s??=(async()=>{const t=e?await No(e).catch(()=>{}):void 0,o=async(a,d)=>{if(t)try{const u=await a.loadPyodide({...d,_loadSnapshot:t});return await u.runPythonAsync(`import random
5
+ random.seed()`),delete u._api?.config?._loadSnapshot,u}catch(u){console.warn(`[python] the interpreter snapshot did not restore; starting Python: ${u instanceof Error?u.message:String(u)}`)}return await a.loadPyodide(d)};return Oo("runtime",async()=>{if(s.startsWith("/")){const b=await import(`file://${s}pyodide.mjs`),k=await import(`file://${s}pyodide.asm.mjs`);return await o(b,{indexURL:s,createPyodideModule:k.default})}const[a,d]=await Promise.all([fetch(`${s}pyodide.mjs`),fetch(`${s}pyodide.asm.mjs`)]);if(!a.ok)throw new Error(`Could not load Pyodide (${a.status}).`);if(!d.ok)throw new Error(`Could not load the Pyodide runtime module (${d.status}).`);const[u,h]=await Promise.all([a.bytes(),d.bytes()]);await ys("pyodide.mjs",u),await ys("pyodide.asm.mjs",h);const m=URL.createObjectURL(new Blob([u],{type:"text/javascript"})),w=URL.createObjectURL(new Blob([h],{type:"text/javascript"}));try{const b=await import(m),k=await import(w);return await o(b,{indexURL:s,createPyodideModule:k.default})}finally{URL.revokeObjectURL(m),URL.revokeObjectURL(w)}})})(),_s}const To=16384;function Mo(s){return{existsSync:e=>s.analyzePath(e).exists,statSync:e=>{const t=s.stat(e),o=(t.mode&61440)===To;return{isDirectory:()=>o,...typeof t.size=="number"?{size:t.size}:{},...Sr(t)}},readFile:e=>Promise.resolve(s.readFile(e)),writeFileSync:(e,t)=>s.writeFile(e,typeof t=="string"?new TextEncoder().encode(t):t),mkdirSync:e=>s.mkdirTree(e),unlinkSync:e=>s.unlink(e),rmdirSync:e=>s.rmdir(e),chmodSync:(e,t)=>s.chmod(e,t),utimesSync:(e,t,o)=>s.utime(e,gs(t),gs(o))}}function Fo(s,e,t){yo(Mo(s),e,t)}function gs(s){return typeof s=="number"?s:Number(s)}function Lo(s,e){Qs(s,J),s.mkdirTree(J);const t=e.files.slice().sort((o,a)=>bs(o.path)-bs(a.path));for(const o of t)o.path!==J&&!o.path.startsWith(`${J}/`)||(o.type==="directory"?s.mkdirTree(o.path):(s.mkdirTree(o.path.slice(0,o.path.lastIndexOf("/"))||"/"),s.writeFile(o.path,$o(o.content??""))));for(const o of t){const a=o;a.path!==J&&!a.path.startsWith(`${J}/`)||(a.mode!==void 0&&s.chmod(a.path,a.mode),a.mtimeMs!==void 0&&s.utime(a.path,a.mtimeMs,a.mtimeMs))}}function Ys(s,e){const o=[...e.files.filter(a=>a.path!==J&&!a.path.startsWith(`${J}/`))];return Ks(s,J,o),{files:o}}function Kt(s,e){const t=s.startsWith("/")?s:`${e}/${s}`,o=[];for(const a of t.split("/"))!a||a==="."||(a===".."?o.pop():o.push(a));return`/${o.join("/")}`}function je(s){return s.slice(s.lastIndexOf("/")+1)}function Vs(s){let e="";for(let t=0;t<s.byteLength;t+=32768)e+=String.fromCharCode(...s.subarray(t,t+32768));return btoa(e)}function $o(s){const e=atob(s);return Uint8Array.from(e,t=>t.charCodeAt(0))}function Ks(s,e,t){const o=s.stat(e),a=Sr(o);t.push({path:e,type:"directory",...a});for(const d of s.readdir(e)){if(d==="."||d==="..")continue;const u=`${e}/${d}`,h=s.stat(u);(h.mode&61440)===16384?Ks(s,u,t):t.push({path:u,type:"file",content:Vs(s.readFile(u)),...Sr(h)})}}function Qs(s,e){if(s.analyzePath(e).exists)for(const t of s.readdir(e)){if(t==="."||t==="..")continue;const o=`${e}/${t}`;(s.stat(o).mode&61440)===16384?(Qs(s,o),s.rmdir(o)):s.unlink(o)}}function bs(s){let e=1;for(let t=0;t<s.length;t+=1)s.charCodeAt(t)===47&&(e+=1);return e}function Sr(s){const e=typeof s.mtime=="number"?s.mtime:Number(s.mtime);return{mode:s.mode&4095,...typeof e=="number"&&Number.isFinite(e)?{mtimeMs:e}:{}}}const Pr=16384,Ro=32768,ks=44;function Bo(s,e){const t=s,o=t.filesystems?.MEMFS;if(!o||typeof t.mount!="function"||typeof o.createNode!="function")return;const a={dirty:new Set,removed:new Set},d=()=>t.genericErrors?.[ks]??new t.ErrnoError(ks),u=N=>N.packPath??J;function h(N,R,L){const S=e.entries.get(L);if(!S)throw d();const x=S.mode&4095|(S.type==="directory"?Pr:Ro),A=o.createNode(N,R,x,0);return A.packPath=L,A.timestamp=S.mtimeMs,A.atime=A.mtime=A.ctime=S.mtimeMs,S.type==="directory"?(A.packListed=!1,A.node_ops=P(A.node_ops)):(A.packLoaded=!1,A.usedBytes=S.length,A.node_ops=g(A.node_ops),A.stream_ops=$(A.stream_ops)),A}function m(N){if(N.packLoaded!==!1||!N.packPath)return;const R=e.read(N.packPath);N.contents=R,N.usedBytes=R.byteLength,N.packLoaded=!0}function w(N){t.isDir(N.mode)||a.dirty.add(b(N))}function b(N){const R=[];let L=N;for(;L&&L.parent!==L;)R.unshift(L.name),L=L.parent;return`${J}/${R.join("/")}`.replace(/\/+$/u,"")||J}const k=new WeakMap;function P(N){const R=k.get(N);if(R)return R;const L={...N,lookup:(S,x)=>{const A=`${u(S)}/${x}`;if(!a.removed.has(A)&&e.entries.has(A))return h(S,x,A);throw d()},readdir:S=>{const x=N.readdir(S),A=new Set(x),C=u(S);for(const H of e.childrenOf(C))a.removed.has(`${C}/${H}`)||A.add(H);return[...A]},mknod:(S,x,A,C)=>{const H=`${u(S)}/${x}`;a.removed.delete(H);const v=N.mknod(S,x,A,C);return v.packPath=H,t.isDir(A)?(v.packListed=!0,v.node_ops=P(v.node_ops)):(v.packLoaded=!0,a.dirty.add(H),v.node_ops=g(v.node_ops),v.stream_ops=$(v.stream_ops)),v},unlink:(S,x)=>{const A=`${u(S)}/${x}`;N.unlink(S,x),a.dirty.delete(A),a.removed.add(A)},rmdir:(S,x)=>{const A=`${u(S)}/${x}`;for(const C of e.childrenOf(A))if(!a.removed.has(`${A}/${C}`))throw new t.ErrnoError(55);N.rmdir(S,x),a.removed.add(A)},rename:(S,x,A)=>{const C=b(S);t.isFile(S.mode)?m(S):G(S),N.rename(S,x,A);const H=`${u(x)}/${A}`;j(S,C,H),a.removed.add(C),a.removed.delete(H)}};return k.set(N,L),L}const F=new WeakMap;function g(N){const R=F.get(N);if(R)return R;const L={...N,setattr:(S,x)=>{x.size!==void 0&&m(S),N.setattr(S,x),(x.size!==void 0||x.mode!==void 0||x.timestamp!==void 0)&&w(S)}};return F.set(N,L),L}const U=new WeakMap;function $(N){const R=U.get(N);if(R)return R;const L={...N,open:S=>{m(S.node),N.open?.(S)},write:(S,x,A,C,H,v)=>{m(S.node);const K=N.write(S,x,A,C,H,v);return w(S.node),K}};return U.set(N,L),L}function G(N){const R=u(N);for(const L of e.childrenOf(R)){if(a.removed.has(`${R}/${L}`))continue;const x=N.contents[L]??h(N,L,`${R}/${L}`);t.isDir(x.mode)?G(x):m(x)}N.packListed=!0}function j(N,R,L){if(N.packPath=L,t.isFile(N.mode)){a.dirty.delete(R),a.dirty.add(L);return}for(const[S,x]of Object.entries(N.contents))j(x,`${R}/${S}`,`${L}/${S}`)}const _e={mount:()=>{const N=o.createNode(null,"/",Pr|493,0);return N.packPath=J,N.node_ops=P(N.node_ops),N}};if(t.analyzePath(J).exists){try{t.unmount(J)}catch{}try{t.rmdir(J)}catch{}}return t.mkdirTree(J),t.mount(_e,{},J),a}function Co(s,e,t){const o=t.files.filter(d=>d.path!==J&&!d.path.startsWith(`${J}/`)),a=d=>{const u=s.stat(d),h=typeof u.mtime=="number"?u.mtime:Number(u.mtime),m={mode:u.mode&4095,...typeof h=="number"&&Number.isFinite(h)?{mtimeMs:h}:{}};if((u.mode&61440)===Pr){o.push({path:d,type:"directory",...m});for(const w of s.readdir(d))w==="."||w===".."||a(`${d}/${w}`);return}e.dirty.has(d)?o.push({path:d,type:"file",content:Vs(s.readFile(d)),...m}):o.push({path:d,type:"file",...typeof u.size=="number"?{size:u.size}:{},...m})};return a(J),{files:o}}const De="/workspace/.supercode/python-requirements.txt",Es=64,Do=256;async function zo(s){const e=Ho(s.FS);e.length!==0&&(Ms({door:"pip install",subject:`${e.join(" ")}, recorded in ${De} by an earlier session`,fix:`a Python project's packages cannot yet be carried as packs; remove ${De} to run Python without them.`}),await Xs(s,e),en(s.FS,await Zs(s)))}async function Uo(s,e){e.requirements.length!==0&&(await Xs(s,e.requirements),en(s.FS,await Zs(s)))}function jo(s){const e=new Map;let t;for(const o of s.split(`
6
+ `)){const a=o.trim();if(a==="[[package]]"){t=void 0;continue}if(a.startsWith("[")&&a!=="[[package]]"){t=void 0;continue}const d=/^name\s*=\s*"([^"]+)"$/u.exec(a);if(d){t=d[1];continue}const u=/^version\s*=\s*"([^"]+)"$/u.exec(a);u&&t&&!e.has(t)&&e.set(t,u[1])}return e}function qo(s,e){const t=/^[A-Za-z0-9._-]+/u.exec(s.trim())?.[0];if(!t)return s;const o=e.get(t)??e.get(t.toLowerCase())??e.get(t.replace(/_/gu,"-").toLowerCase());return o?`${t}==${o}`:s}function Wo(s,e,t){const o=je(e[0]??""),a=o==="pip"||o==="pip3"?e.slice(1):(o==="python"||o==="python3")&&e[1]==="-m"&&e[2]==="pip"?e.slice(3):void 0;if(!a)return;if(a[0]!=="install")throw new Error("pip in the tab supports only `pip install <packages> [-r requirements.txt]`, and only as a temporary path: a project's Python dependencies are meant to be prepared on a machine by `npx @volter/browser-substrate dev`.");const d=[];let u=!1;for(let m=1;m<a.length;m+=1){const w=a[m];if(!(w==="--disable-pip-version-check"||w==="-q"||w==="--quiet")){if(w==="-r"||w==="--requirement"){const b=a[++m];if(!b)throw new Error(`${w} requires a file path.`);const k=Kt(b,t);if(!s.analyzePath(k).exists)throw new Error(`pip: requirements file not found: ${k}`);d.push(...tn(new TextDecoder().decode(s.readFile(k)))),u=!0;continue}if(w.startsWith("-"))throw new Error(`browser pip does not support option: ${w}`);d.push(w)}}if(d.length===0&&!u)throw new Error("pip install requires at least one package.");const h=Kt("uv.lock",t);if(s.analyzePath(h).exists){const m=jo(new TextDecoder().decode(s.readFile(h)));if(m.size>0){const w=d.map(b=>qo(b,m));return st(w),{requirements:w,lockfile:{file:"uv.lock",pins:m.size}}}}return st(d),{requirements:d}}async function Xs(s,e){st(e),Ms({door:"pip install",subject:e.join(" "),detail:{requirements:e.join(" ")},fix:"a Python project's packages cannot yet be carried as packs, so the tab cannot provide them."})}async function Zs(s){const e=await s.runPythonAsync(`
7
7
  import json, micropip
8
8
  json.dumps(sorted(
9
9
  f"{name}=={package.version}"
10
10
  for name, package in micropip.list().items()
11
11
  if name.lower() != "micropip"
12
12
  ))
13
- `),t=JSON.parse(String(e));if(!Array.isArray(t)||t.some(o=>typeof o!="string"))throw new Error("micropip returned an invalid package inventory.");return st(t),t}function Ho(s){return s.analyzePath(Ce).exists?tn(new TextDecoder().decode(s.readFile(Ce))):[]}function en(s,e){st(e),s.mkdirTree(Ce.slice(0,Ce.lastIndexOf("/"))),s.writeFile(Ce,new TextEncoder().encode(`${e.join(`
13
+ `),t=JSON.parse(String(e));if(!Array.isArray(t)||t.some(o=>typeof o!="string"))throw new Error("micropip returned an invalid package inventory.");return st(t),t}function Ho(s){return s.analyzePath(De).exists?tn(new TextDecoder().decode(s.readFile(De))):[]}function en(s,e){st(e),s.mkdirTree(De.slice(0,De.lastIndexOf("/"))),s.writeFile(De,new TextEncoder().encode(`${e.join(`
14
14
  `)}
15
- `))}function tn(s){const e=s.split(/\r?\n/u).map(t=>t.replace(/\s+#.*$/u,"").trim()).filter(Boolean);return st(e),e}function st(s){if(s.length>Es)throw new Error(`Python package limit is ${Es}.`);for(const e of s){if(!e||e.length>Co||/[\u0000-\u001f\u007f]/u.test(e))throw new Error("Invalid Python package requirement.");if(/^(?:https?|emfs):/iu.test(e)||e.endsWith(".whl"))throw new Error("Direct wheel URLs are not accepted; install a named package from the verified index.")}}const Jo=String.raw`
15
+ `))}function tn(s){const e=s.split(/\r?\n/u).map(t=>t.replace(/\s+#.*$/u,"").trim()).filter(Boolean);return st(e),e}function st(s){if(s.length>Es)throw new Error(`Python package limit is ${Es}.`);for(const e of s){if(!e||e.length>Do||/[\u0000-\u001f\u007f]/u.test(e))throw new Error("Invalid Python package requirement.");if(/^(?:https?|emfs):/iu.test(e)||e.endsWith(".whl"))throw new Error("Direct wheel URLs are not accepted; install a named package from the verified index.")}}const Jo=String.raw`
16
16
  import asyncio, base64, json
17
17
  from urllib.parse import urlsplit
18
18
 
@@ -316,7 +316,7 @@ async def __browser_runtime_handle_asgi(payload_json, streaming=False):
316
316
  "headers": __browser_runtime_asgi_headers(response_start),
317
317
  "bodyBase64": base64.b64encode(b"".join(response_chunks)).decode("ascii"),
318
318
  })
319
- `;class Go{pyodide;port;commit;acknowledgements=new Map;nextRequestId=1;requestQueue=Promise.resolve();constructor(e,t,o){this.pyodide=e,this.port=t,this.commit=o,e.globals.set("__browser_runtime_asgi_websocket_callback",a=>{const d=JSON.parse(String(a));d.type==="opened"?this.port.postMessage({type:"websocket-opened",connectionId:d.connectionId,protocol:d.protocol??""}):d.type==="message"?this.port.postMessage({type:"websocket-message",connectionId:d.connectionId,data:d.kind==="binary"?{kind:"binary",base64:d.base64??""}:{kind:"text",text:d.text??""}}):d.type==="close"?this.port.postMessage({type:"websocket-close",connectionId:d.connectionId,code:d.code??1e3,reason:d.reason??"",clean:d.clean!==!1}):d.type==="error"&&this.port.postMessage({type:"websocket-error",connectionId:d.connectionId,error:d.error??"Python ASGI WebSocket failed."})}),t.onmessage=a=>{const d=a.data;if(d.type==="ack"){const f=this.acknowledgements.get(d.requestId);if(!f)return;this.acknowledgements.delete(d.requestId),f(d.result);return}this.requestQueue=this.requestQueue.then(()=>d.type==="http-request"?this.handleRequest(d):this.handleWebSocket(d))},t.start()}listenStatic(e,t){return this.listen({type:"listen",requestId:0,port:e,server:"static",root:t})}listenWsgi(e){return this.listen({type:"listen",requestId:0,port:e,server:"wsgi"})}listenAsgi(e){return this.listen({type:"listen",requestId:0,port:e,server:"asgi"})}idle(){return this.requestQueue}listen(e){const t=this.nextRequestId++;return new Promise(o=>{const a=setTimeout(()=>{this.acknowledgements.delete(t),o(-110)},5e3);this.acknowledgements.set(t,d=>{clearTimeout(a),o(d)}),this.port.postMessage({...e,requestId:t})})}async handleRequest(e){const t=e.application==="asgi"&&e.streaming===!0;try{const o=JSON.stringify({method:e.method,url:e.url,headers:e.headers,bodyBase64:e.bodyBase64}),a=e.application==="asgi"?"__browser_runtime_handle_asgi":"__browser_runtime_handle_wsgi";t&&this.pyodide.globals.set("__browser_runtime_asgi_stream_callback",m=>{const w=JSON.parse(String(m));w.type==="start"?this.port.postMessage({type:"http-stream-start",requestId:e.requestId,statusCode:w.statusCode??500,statusMessage:w.statusMessage??"",headers:w.headers??{}}):w.type==="chunk"&&this.port.postMessage({type:"http-stream-chunk",requestId:e.requestId,bodyBase64:w.bodyBase64??""})});const d=e.application==="asgi"?`await ${a}(${JSON.stringify(o)}, ${t?"True":"False"})`:`${a}(${JSON.stringify(o)})`,f=await this.pyodide.runPythonAsync(d);if(t){await this.commit(),this.port.postMessage({type:"http-stream-end",requestId:e.requestId});return}const h=JSON.parse(String(f));await this.commit(),this.port.postMessage({type:"http-response",requestId:e.requestId,...h})}catch(o){if(e.application==="asgi"&&e.streaming===!0){this.port.postMessage({type:"http-stream-error",requestId:e.requestId,error:o instanceof Error?o.message:String(o)});return}this.port.postMessage({type:"http-response",requestId:e.requestId,statusCode:500,statusMessage:"Internal Server Error",headers:{},bodyBase64:"",error:o instanceof Error?o.message:String(o)})}finally{t&&this.pyodide.globals.set("__browser_runtime_asgi_stream_callback",()=>{})}}async handleWebSocket(e){const t=JSON.stringify(e);try{e.type==="websocket-open"?await this.pyodide.runPythonAsync(`await __browser_runtime_open_asgi_websocket(${JSON.stringify(t)})`):await this.pyodide.runPythonAsync(`await __browser_runtime_asgi_websocket_event(${JSON.stringify(t)})`)}catch(o){this.port.postMessage({type:"websocket-error",connectionId:e.connectionId,error:o instanceof Error?o.message:String(o)}),this.port.postMessage({type:"websocket-close",connectionId:e.connectionId,code:1011,reason:"Python ASGI WebSocket failed",clean:!1})}}}function Yo(s,e,t,o){return`
319
+ `;class Go{pyodide;port;commit;acknowledgements=new Map;nextRequestId=1;requestQueue=Promise.resolve();constructor(e,t,o){this.pyodide=e,this.port=t,this.commit=o,e.globals.set("__browser_runtime_asgi_websocket_callback",a=>{const d=JSON.parse(String(a));d.type==="opened"?this.port.postMessage({type:"websocket-opened",connectionId:d.connectionId,protocol:d.protocol??""}):d.type==="message"?this.port.postMessage({type:"websocket-message",connectionId:d.connectionId,data:d.kind==="binary"?{kind:"binary",base64:d.base64??""}:{kind:"text",text:d.text??""}}):d.type==="close"?this.port.postMessage({type:"websocket-close",connectionId:d.connectionId,code:d.code??1e3,reason:d.reason??"",clean:d.clean!==!1}):d.type==="error"&&this.port.postMessage({type:"websocket-error",connectionId:d.connectionId,error:d.error??"Python ASGI WebSocket failed."})}),t.onmessage=a=>{const d=a.data;if(d.type==="ack"){const u=this.acknowledgements.get(d.requestId);if(!u)return;this.acknowledgements.delete(d.requestId),u(d.result);return}this.requestQueue=this.requestQueue.then(()=>d.type==="http-request"?this.handleRequest(d):this.handleWebSocket(d))},t.start()}listenStatic(e,t){return this.listen({type:"listen",requestId:0,port:e,server:"static",root:t})}listenWsgi(e){return this.listen({type:"listen",requestId:0,port:e,server:"wsgi"})}listenAsgi(e){return this.listen({type:"listen",requestId:0,port:e,server:"asgi"})}idle(){return this.requestQueue}listen(e){const t=this.nextRequestId++;return new Promise(o=>{const a=setTimeout(()=>{this.acknowledgements.delete(t),o(-110)},5e3);this.acknowledgements.set(t,d=>{clearTimeout(a),o(d)}),this.port.postMessage({...e,requestId:t})})}async handleRequest(e){const t=e.application==="asgi"&&e.streaming===!0;try{const o=JSON.stringify({method:e.method,url:e.url,headers:e.headers,bodyBase64:e.bodyBase64}),a=e.application==="asgi"?"__browser_runtime_handle_asgi":"__browser_runtime_handle_wsgi";t&&this.pyodide.globals.set("__browser_runtime_asgi_stream_callback",m=>{const w=JSON.parse(String(m));w.type==="start"?this.port.postMessage({type:"http-stream-start",requestId:e.requestId,statusCode:w.statusCode??500,statusMessage:w.statusMessage??"",headers:w.headers??{}}):w.type==="chunk"&&this.port.postMessage({type:"http-stream-chunk",requestId:e.requestId,bodyBase64:w.bodyBase64??""})});const d=e.application==="asgi"?`await ${a}(${JSON.stringify(o)}, ${t?"True":"False"})`:`${a}(${JSON.stringify(o)})`,u=await this.pyodide.runPythonAsync(d);if(t){await this.commit(),this.port.postMessage({type:"http-stream-end",requestId:e.requestId});return}const h=JSON.parse(String(u));await this.commit(),this.port.postMessage({type:"http-response",requestId:e.requestId,...h})}catch(o){if(e.application==="asgi"&&e.streaming===!0){this.port.postMessage({type:"http-stream-error",requestId:e.requestId,error:o instanceof Error?o.message:String(o)});return}this.port.postMessage({type:"http-response",requestId:e.requestId,statusCode:500,statusMessage:"Internal Server Error",headers:{},bodyBase64:"",error:o instanceof Error?o.message:String(o)})}finally{t&&this.pyodide.globals.set("__browser_runtime_asgi_stream_callback",()=>{})}}async handleWebSocket(e){const t=JSON.stringify(e);try{e.type==="websocket-open"?await this.pyodide.runPythonAsync(`await __browser_runtime_open_asgi_websocket(${JSON.stringify(t)})`):await this.pyodide.runPythonAsync(`await __browser_runtime_asgi_websocket_event(${JSON.stringify(t)})`)}catch(o){this.port.postMessage({type:"websocket-error",connectionId:e.connectionId,error:o instanceof Error?o.message:String(o)}),this.port.postMessage({type:"websocket-close",connectionId:e.connectionId,code:1011,reason:"Python ASGI WebSocket failed",clean:!1})}}}function Yo(s,e,t,o){return`
320
320
  import os, sys
321
321
  os.chdir(${JSON.stringify(s)})
322
322
  os.environ.clear()
@@ -395,7 +395,7 @@ def __browser_runtime_handle_wsgi(payload_json):
395
395
  "headers": response_headers,
396
396
  "bodyBase64": base64.b64encode(response_body).decode("ascii"),
397
397
  })
398
- `,Ps=16*1024*1024,Vo=3e4,Ko=5*6e4;class Qo{port;applyChanges;enabled;nextRequestId=1;constructor(e,t,o,a=!0){this.port=t,this.applyChanges=o,this.enabled=a,e.globals.set("__browser_runtime_run_process",d=>this.run(d)),e.globals.set("__browser_runtime_process_exchange",d=>this.exchange(d))}run(e){this.assertEnabled();const t=JSON.parse(e),o=new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT),a=new SharedArrayBuffer(Ps),d=new Int32Array(o),f=this.nextRequestId++;if(this.port.postMessage({type:"process-run",requestId:f,...t,control:o,response:a}),Atomics.wait(d,0,0,Vo)==="timed-out"||Atomics.load(d,0)!==1)throw this.port.postMessage({type:"process-cancel",requestId:f}),new Error("Python subprocess timed out after 30 seconds.");const m=Atomics.load(d,1);if(!Number.isSafeInteger(m)||m<0||m>a.byteLength)throw new Error("Invalid Python subprocess response.");const w=new Uint8Array(m);w.set(new Uint8Array(a,0,m));const b=JSON.parse(new TextDecoder().decode(w));if(b.error)throw new Error(b.error);if(!b.result||!b.patch)throw new Error("Incomplete Python subprocess response.");return this.applyChanges(b.patch),JSON.stringify(b.result)}exchange(e){this.assertEnabled();const t=JSON.parse(e),o=new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT),a=new SharedArrayBuffer(Ps),d=new Int32Array(o);if(this.port.postMessage({...t,requestId:this.nextRequestId++,control:o,response:a}),Atomics.wait(d,0,0,Ko)==="timed-out"||Atomics.load(d,0)!==1)throw new Error("Python Popen operation timed out after 5 minutes.");const h=Atomics.load(d,1);if(!Number.isSafeInteger(h)||h<0||h>a.byteLength)throw new Error("Invalid Python Popen response.");const m=new Uint8Array(h);m.set(new Uint8Array(a,0,h));const w=JSON.parse(new TextDecoder().decode(m));if(w.patch&&this.applyChanges(w.patch),w.error)throw new Error(w.error);return JSON.stringify(w)}assertEnabled(){if(!this.enabled)throw new Error("Python subprocesses require a same-origin shared-memory worker.")}}const Xo=String.raw`
398
+ `,Ps=16*1024*1024,Vo=3e4,Ko=5*6e4;class Qo{port;applyChanges;enabled;nextRequestId=1;constructor(e,t,o,a=!0){this.port=t,this.applyChanges=o,this.enabled=a,e.globals.set("__browser_runtime_run_process",d=>this.run(d)),e.globals.set("__browser_runtime_process_exchange",d=>this.exchange(d))}run(e){this.assertEnabled();const t=JSON.parse(e),o=new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT),a=new SharedArrayBuffer(Ps),d=new Int32Array(o),u=this.nextRequestId++;if(this.port.postMessage({type:"process-run",requestId:u,...t,control:o,response:a}),Atomics.wait(d,0,0,Vo)==="timed-out"||Atomics.load(d,0)!==1)throw this.port.postMessage({type:"process-cancel",requestId:u}),new Error("Python subprocess timed out after 30 seconds.");const m=Atomics.load(d,1);if(!Number.isSafeInteger(m)||m<0||m>a.byteLength)throw new Error("Invalid Python subprocess response.");const w=new Uint8Array(m);w.set(new Uint8Array(a,0,m));const b=JSON.parse(new TextDecoder().decode(w));if(b.error)throw new Error(b.error);if(!b.result||!b.patch)throw new Error("Incomplete Python subprocess response.");return this.applyChanges(b.patch),JSON.stringify(b.result)}exchange(e){this.assertEnabled();const t=JSON.parse(e),o=new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT),a=new SharedArrayBuffer(Ps),d=new Int32Array(o);if(this.port.postMessage({...t,requestId:this.nextRequestId++,control:o,response:a}),Atomics.wait(d,0,0,Ko)==="timed-out"||Atomics.load(d,0)!==1)throw new Error("Python Popen operation timed out after 5 minutes.");const h=Atomics.load(d,1);if(!Number.isSafeInteger(h)||h<0||h>a.byteLength)throw new Error("Invalid Python Popen response.");const m=new Uint8Array(h);m.set(new Uint8Array(a,0,h));const w=JSON.parse(new TextDecoder().decode(m));if(w.patch&&this.applyChanges(w.patch),w.error)throw new Error(w.error);return JSON.stringify(w)}assertEnabled(){if(!this.enabled)throw new Error("Python subprocesses require a same-origin shared-memory worker.")}}const Xo=String.raw`
399
399
  import base64 as __browser_runtime_base64
400
400
  import codecs as _browser_runtime_codecs
401
401
  import json as __browser_runtime_json
@@ -722,7 +722,7 @@ __browser_runtime_subprocess.run = __browser_runtime_subprocess_run
722
722
  __browser_runtime_subprocess.call = __browser_runtime_subprocess_call
723
723
  __browser_runtime_subprocess.check_call = __browser_runtime_subprocess_check_call
724
724
  __browser_runtime_subprocess.Popen = __browser_runtime_BrowserPopen
725
- `,xs=-4,_r=3;class Qt{channel;control;payload;encoder=new TextEncoder;decoder=new TextDecoder("utf-8",{fatal:!0});nextRequestId=1;constructor(e){this.channel=e,this.control=new Int32Array(e.control),this.payload=new Uint8Array(e.payload)}static waited={calls:0,ms:0};request(e){const t=performance.now();try{return this.requestNow(e)}finally{Qt.waited.calls+=1,Qt.waited.ms+=performance.now()-t}}requestNow(e){if(Atomics.load(this.control,_r))return{result:xs};const t=this.encoder.encode(JSON.stringify(e));if(t.byteLength>this.payload.byteLength)return{result:-90};if(Atomics.load(this.control,0)!==0)throw new Error("Concurrent file-lock RPC on one channel.");const o=this.nextRequestId;this.nextRequestId=o>=1073741821?1:o+2,this.control.fill(0,0,_r),this.payload.set(t),Atomics.store(this.control,1,t.byteLength),Atomics.store(this.control,0,o);try{for(this.channel.port.postMessage(o);Atomics.load(this.control,0)!==o+1;){if(Atomics.load(this.control,_r))return{result:xs};const f=Atomics.load(this.control,0);f!==o+1&&Atomics.wait(this.control,0,f)}const a=Atomics.load(this.control,2);if(a<1||a>this.payload.byteLength)return{result:-5};const d=JSON.parse(this.decoder.decode(this.payload.slice(0,a)));return!d||!Number.isSafeInteger(d.result)?{result:-5}:d}finally{Atomics.store(this.control,0,0)}}}var Ae;(function(s){s[s.Inspect=1]="Inspect",s[s.Read=2]="Read",s[s.WriteStart=3]="WriteStart",s[s.WriteChunk=4]="WriteChunk",s[s.WriteFinish=5]="WriteFinish",s[s.Remove=6]="Remove"})(Ae||(Ae={}));const jt=512*1024,As=256*1024*1024,vs=5,Zo=new TextEncoder,ei=new TextDecoder("utf-8",{fatal:!0});class ti{channel;control;payload;nextRequestId=1;constructor(e){this.channel=e,this.control=new Int32Array(e.control),this.payload=new Uint8Array(e.payload)}pull(e){const t=this.call(Ae.Inspect,{path:e});if(!t.exists)return;const o=xr(t.length,0,As),a=new Uint8Array(o);for(let d=0;d<o;d+=jt){const f=Math.min(jt,o-d),h=this.call(Ae.Read,{path:e,offset:d,length:f}),m=Ws(h.content);if(m.byteLength!==f)throw new Error("Invalid coherent file response.");a.set(m,d)}return{bytes:a,...t.mode===void 0?{}:{mode:t.mode},...t.mtimeMs===void 0?{}:{mtimeMs:t.mtimeMs},parents:ri(e,t.parents)}}push(e,t){if(!t){this.call(Ae.Remove,{path:e});return}if(t.bytes.byteLength>As)throw new Error("Coherent file exceeds 256 MiB.");this.call(Ae.WriteStart,{path:e,length:t.bytes.byteLength,...t.mode===void 0?{}:{mode:t.mode},...t.mtimeMs===void 0?{}:{mtimeMs:t.mtimeMs},...t.parents===void 0?{}:{parents:t.parents}});for(let o=0;o<t.bytes.byteLength;o+=jt){const a=t.bytes.subarray(o,o+jt);this.call(Ae.WriteChunk,{offset:o,content:mo(a)})}this.call(Ae.WriteFinish)}call(e,t={}){const o=()=>{if(Atomics.load(this.control,vs))throw Object.assign(new Error("Browser file coherence was cancelled."),{errno:125})};o();const a=Zo.encode(JSON.stringify(t));if(a.byteLength>this.payload.byteLength)throw new Error("File-coherence request is too large.");if(Atomics.load(this.control,0)!==0)throw new Error("Concurrent file-coherence RPC on one channel.");const d=this.nextRequestId;this.nextRequestId=d>=1073741821?1:d+2,this.control.fill(0,0,vs),this.payload.set(a),Atomics.store(this.control,1,e),Atomics.store(this.control,3,a.byteLength),Atomics.store(this.control,0,d);try{for(this.channel.port.postMessage(d);Atomics.load(this.control,0)!==d+1;){o();const w=Atomics.load(this.control,0);w!==d+1&&Atomics.wait(this.control,0,w)}const f=Atomics.load(this.control,2),h=xr(Atomics.load(this.control,4),0,this.payload.byteLength),m=h===0?void 0:JSON.parse(ei.decode(this.payload.slice(0,h)));if(f<0)throw Object.assign(new Error(`Browser file coherence failed with ${f}.`),{errno:-f});return m}finally{Atomics.store(this.control,0,0)}}}function Is(s){const e=s.replace(/-(?:journal|shm|wal)$/u,"");return[e,`${e}-journal`,`${e}-wal`,`${e}-shm`]}function ri(s,e){if(e===void 0)return[];const t=new Set(si(s));if(!Array.isArray(e)||e.length>t.size)throw ze("Invalid coherent file parents.");return e.map(o=>{if(typeof o!="object"||o===null)throw ze("Invalid coherent file parent.");const a=o,d=rn(a.path);if(!t.delete(d))throw ze("Coherent metadata must name distinct ancestors of its file.");return{path:d,...ni(a)}})}function si(s){const e=[];for(const t of rn(s).split("/"))!t||t==="."||(t===".."?e.pop():e.push(t));return e.slice(0,-1).map((t,o)=>`/${e.slice(0,o+1).join("/")}`)}function ni(s){const e=s.mode===void 0?void 0:xr(s.mode,0,65535),t=s.mtimeMs===void 0?void 0:ii(s.mtimeMs);return{...e===void 0?{}:{mode:e},...t===void 0?{}:{mtimeMs:t}}}function rn(s){const e=oi(s);if(!e.startsWith("/")||e.length>4096||e.includes("\0"))throw ze("Invalid coherent file path.");return e}function oi(s){if(typeof s!="string")throw ze("Expected a string.");return s}function xr(s,e,t){if(!Number.isSafeInteger(s)||s<e||s>t)throw ze("Expected a bounded integer.");return s}function ii(s){if(typeof s!="number"||!Number.isFinite(s))throw ze("Expected a finite number.");return s}function ze(s){return Object.assign(new Error(s),{errno:22})}class ai{filesystem;locks;coherence;counts=new Map;owner;constructor(e,t,o,a){this.filesystem=e,this.locks=t,this.coherence=o,this.owner=`${a}:sqlite`}install(e){return e.globals.set("_browser_runtime_sqlite_acquire",t=>this.acquire(t)),e.globals.set("_browser_runtime_sqlite_release",t=>this.release(t)),e.runPythonAsync(ci)}releaseAll(){for(const e of[...this.counts.keys()])this.counts.set(e,1),this.release(e)}acquire(e){if(!e.startsWith("/")||e.includes("\0"))throw new Error("Invalid SQLite path.");const t=this.counts.get(e)??0;if(t>0){this.counts.set(e,t+1);return}const o=this.locks.request({operation:"set",owner:this.owner,namespace:"posix",path:e,range:{start:0},mode:"write",pid:1,blocking:!0});if(o.result<0)throw new Error(`SQLite lock acquisition failed with ${o.result}.`);try{for(const a of Is(e))this.writeLocal(a,this.coherence.pull(a));this.counts.set(e,1)}catch(a){throw this.locks.request({operation:"unlock",owner:this.owner,namespace:"posix",path:e,range:{start:0}}),a}}release(e){const t=this.counts.get(e)??0;if(t>1){this.counts.set(e,t-1);return}if(t===0)return;for(const a of Is(e))this.coherence.push(a,this.readLocal(a));const o=this.locks.request({operation:"unlock",owner:this.owner,namespace:"posix",path:e,range:{start:0}});if(o.result<0)throw new Error(`SQLite lock release failed with ${o.result}.`);this.counts.delete(e)}readLocal(e){if(!this.filesystem.analyzePath(e).exists)return;const t=this.filesystem.stat(e);if((t.mode&61440)===16384)return;const o=t.mtime instanceof Date?t.mtime.getTime():t.mtime;return{bytes:this.filesystem.readFile(e),mode:t.mode&4095,...typeof o=="number"&&Number.isFinite(o)?{mtimeMs:o}:{}}}writeLocal(e,t){if(!t){this.filesystem.analyzePath(e).exists&&(this.filesystem.stat(e).mode&61440)!==16384&&this.filesystem.unlink(e);return}const o=e.slice(0,e.lastIndexOf("/"))||"/";this.filesystem.analyzePath(o).exists||this.filesystem.mkdirTree(o),this.filesystem.writeFile(e,t.bytes),t.mode!==void 0&&this.filesystem.chmod(e,t.mode),t.mtimeMs!==void 0&&this.filesystem.utime(e,t.mtimeMs,t.mtimeMs)}}const ci=String.raw`
725
+ `,xs=-4,_r=3;class Qt{channel;control;payload;encoder=new TextEncoder;decoder=new TextDecoder("utf-8",{fatal:!0});nextRequestId=1;constructor(e){this.channel=e,this.control=new Int32Array(e.control),this.payload=new Uint8Array(e.payload)}static waited={calls:0,ms:0};request(e){const t=performance.now();try{return this.requestNow(e)}finally{Qt.waited.calls+=1,Qt.waited.ms+=performance.now()-t}}requestNow(e){if(Atomics.load(this.control,_r))return{result:xs};const t=this.encoder.encode(JSON.stringify(e));if(t.byteLength>this.payload.byteLength)return{result:-90};if(Atomics.load(this.control,0)!==0)throw new Error("Concurrent file-lock RPC on one channel.");const o=this.nextRequestId;this.nextRequestId=o>=1073741821?1:o+2,this.control.fill(0,0,_r),this.payload.set(t),Atomics.store(this.control,1,t.byteLength),Atomics.store(this.control,0,o);try{for(this.channel.port.postMessage(o);Atomics.load(this.control,0)!==o+1;){if(Atomics.load(this.control,_r))return{result:xs};const u=Atomics.load(this.control,0);u!==o+1&&Atomics.wait(this.control,0,u)}const a=Atomics.load(this.control,2);if(a<1||a>this.payload.byteLength)return{result:-5};const d=JSON.parse(this.decoder.decode(this.payload.slice(0,a)));return!d||!Number.isSafeInteger(d.result)?{result:-5}:d}finally{Atomics.store(this.control,0,0)}}}var Ae;(function(s){s[s.Inspect=1]="Inspect",s[s.Read=2]="Read",s[s.WriteStart=3]="WriteStart",s[s.WriteChunk=4]="WriteChunk",s[s.WriteFinish=5]="WriteFinish",s[s.Remove=6]="Remove"})(Ae||(Ae={}));const jt=512*1024,As=256*1024*1024,vs=5,Zo=new TextEncoder,ei=new TextDecoder("utf-8",{fatal:!0});class ti{channel;control;payload;nextRequestId=1;constructor(e){this.channel=e,this.control=new Int32Array(e.control),this.payload=new Uint8Array(e.payload)}pull(e){const t=this.call(Ae.Inspect,{path:e});if(!t.exists)return;const o=xr(t.length,0,As),a=new Uint8Array(o);for(let d=0;d<o;d+=jt){const u=Math.min(jt,o-d),h=this.call(Ae.Read,{path:e,offset:d,length:u}),m=Ws(h.content);if(m.byteLength!==u)throw new Error("Invalid coherent file response.");a.set(m,d)}return{bytes:a,...t.mode===void 0?{}:{mode:t.mode},...t.mtimeMs===void 0?{}:{mtimeMs:t.mtimeMs},parents:ri(e,t.parents)}}push(e,t){if(!t){this.call(Ae.Remove,{path:e});return}if(t.bytes.byteLength>As)throw new Error("Coherent file exceeds 256 MiB.");this.call(Ae.WriteStart,{path:e,length:t.bytes.byteLength,...t.mode===void 0?{}:{mode:t.mode},...t.mtimeMs===void 0?{}:{mtimeMs:t.mtimeMs},...t.parents===void 0?{}:{parents:t.parents}});for(let o=0;o<t.bytes.byteLength;o+=jt){const a=t.bytes.subarray(o,o+jt);this.call(Ae.WriteChunk,{offset:o,content:mo(a)})}this.call(Ae.WriteFinish)}call(e,t={}){const o=()=>{if(Atomics.load(this.control,vs))throw Object.assign(new Error("Browser file coherence was cancelled."),{errno:125})};o();const a=Zo.encode(JSON.stringify(t));if(a.byteLength>this.payload.byteLength)throw new Error("File-coherence request is too large.");if(Atomics.load(this.control,0)!==0)throw new Error("Concurrent file-coherence RPC on one channel.");const d=this.nextRequestId;this.nextRequestId=d>=1073741821?1:d+2,this.control.fill(0,0,vs),this.payload.set(a),Atomics.store(this.control,1,e),Atomics.store(this.control,3,a.byteLength),Atomics.store(this.control,0,d);try{for(this.channel.port.postMessage(d);Atomics.load(this.control,0)!==d+1;){o();const w=Atomics.load(this.control,0);w!==d+1&&Atomics.wait(this.control,0,w)}const u=Atomics.load(this.control,2),h=xr(Atomics.load(this.control,4),0,this.payload.byteLength),m=h===0?void 0:JSON.parse(ei.decode(this.payload.slice(0,h)));if(u<0)throw Object.assign(new Error(`Browser file coherence failed with ${u}.`),{errno:-u});return m}finally{Atomics.store(this.control,0,0)}}}function Is(s){const e=s.replace(/-(?:journal|shm|wal)$/u,"");return[e,`${e}-journal`,`${e}-wal`,`${e}-shm`]}function ri(s,e){if(e===void 0)return[];const t=new Set(si(s));if(!Array.isArray(e)||e.length>t.size)throw ze("Invalid coherent file parents.");return e.map(o=>{if(typeof o!="object"||o===null)throw ze("Invalid coherent file parent.");const a=o,d=rn(a.path);if(!t.delete(d))throw ze("Coherent metadata must name distinct ancestors of its file.");return{path:d,...ni(a)}})}function si(s){const e=[];for(const t of rn(s).split("/"))!t||t==="."||(t===".."?e.pop():e.push(t));return e.slice(0,-1).map((t,o)=>`/${e.slice(0,o+1).join("/")}`)}function ni(s){const e=s.mode===void 0?void 0:xr(s.mode,0,65535),t=s.mtimeMs===void 0?void 0:ii(s.mtimeMs);return{...e===void 0?{}:{mode:e},...t===void 0?{}:{mtimeMs:t}}}function rn(s){const e=oi(s);if(!e.startsWith("/")||e.length>4096||e.includes("\0"))throw ze("Invalid coherent file path.");return e}function oi(s){if(typeof s!="string")throw ze("Expected a string.");return s}function xr(s,e,t){if(!Number.isSafeInteger(s)||s<e||s>t)throw ze("Expected a bounded integer.");return s}function ii(s){if(typeof s!="number"||!Number.isFinite(s))throw ze("Expected a finite number.");return s}function ze(s){return Object.assign(new Error(s),{errno:22})}class ai{filesystem;locks;coherence;counts=new Map;owner;constructor(e,t,o,a){this.filesystem=e,this.locks=t,this.coherence=o,this.owner=`${a}:sqlite`}install(e){return e.globals.set("_browser_runtime_sqlite_acquire",t=>this.acquire(t)),e.globals.set("_browser_runtime_sqlite_release",t=>this.release(t)),e.runPythonAsync(ci)}releaseAll(){for(const e of[...this.counts.keys()])this.counts.set(e,1),this.release(e)}acquire(e){if(!e.startsWith("/")||e.includes("\0"))throw new Error("Invalid SQLite path.");const t=this.counts.get(e)??0;if(t>0){this.counts.set(e,t+1);return}const o=this.locks.request({operation:"set",owner:this.owner,namespace:"posix",path:e,range:{start:0},mode:"write",pid:1,blocking:!0});if(o.result<0)throw new Error(`SQLite lock acquisition failed with ${o.result}.`);try{for(const a of Is(e))this.writeLocal(a,this.coherence.pull(a));this.counts.set(e,1)}catch(a){throw this.locks.request({operation:"unlock",owner:this.owner,namespace:"posix",path:e,range:{start:0}}),a}}release(e){const t=this.counts.get(e)??0;if(t>1){this.counts.set(e,t-1);return}if(t===0)return;for(const a of Is(e))this.coherence.push(a,this.readLocal(a));const o=this.locks.request({operation:"unlock",owner:this.owner,namespace:"posix",path:e,range:{start:0}});if(o.result<0)throw new Error(`SQLite lock release failed with ${o.result}.`);this.counts.delete(e)}readLocal(e){if(!this.filesystem.analyzePath(e).exists)return;const t=this.filesystem.stat(e);if((t.mode&61440)===16384)return;const o=typeof t.mtime=="number"?t.mtime:Number(t.mtime);return{bytes:this.filesystem.readFile(e),mode:t.mode&4095,...typeof o=="number"&&Number.isFinite(o)?{mtimeMs:o}:{}}}writeLocal(e,t){if(!t){this.filesystem.analyzePath(e).exists&&(this.filesystem.stat(e).mode&61440)!==16384&&this.filesystem.unlink(e);return}const o=e.slice(0,e.lastIndexOf("/"))||"/";this.filesystem.analyzePath(o).exists||this.filesystem.mkdirTree(o),this.filesystem.writeFile(e,t.bytes),t.mode!==void 0&&this.filesystem.chmod(e,t.mode),t.mtimeMs!==void 0&&this.filesystem.utime(e,t.mtimeMs,t.mtimeMs)}}const ci=String.raw`
726
726
  import os as _browser_runtime_sqlite_os, sqlite3 as _browser_runtime_sqlite
727
727
 
728
728
  _browser_runtime_sqlite_connect_original = _browser_runtime_sqlite.connect
@@ -774,16 +774,16 @@ def _browser_runtime_sqlite_connect(database, *args, **kwargs):
774
774
 
775
775
  _browser_runtime_sqlite.connect = _browser_runtime_sqlite_connect
776
776
  _browser_runtime_sqlite.dbapi2.connect = _browser_runtime_sqlite_connect
777
- `,sn=globalThis;let li=1;const Ar=new Map;let nn=!1,Os=!1,vr,wt,on,ht;function Xt(s){const e=Eo(ht??wt??{files:[]},s);return ht=s,e}function di(s,e){const t=ht??wt??{files:[]};Fo(s.FS,e,t),ht=ko(t,e)}let tt=s=>Ys(s.FS,wt??{files:[]}),gr,fi=1;const Ir=new Map;bi();sn.onmessage=s=>{const e=s.data;if(e.type==="run"){ui(e);return}if(e.type==="prepare"){Gs(e.runtimeIndexUrl,e.runtimeSnapshot).catch(()=>{});return}if(e.type==="shutdown"){_i();return}if(e.type==="network-response"||e.type==="network-error"){const o=Ir.get(e.requestId);if(!o)return;Ir.delete(e.requestId),e.type==="network-error"?o.reject(new Error(e.error)):o.resolve(new Response(e.body,{status:e.status,statusText:e.statusText,headers:e.headers}));return}const t=Ar.get(e.commitId);t&&(Ar.delete(e.commitId),e.error?t.reject(new Error(e.error)):t.resolve())};async function ui(s){let e,t;wt=s.filesystem,ht=s.filesystem;try{if(e=await Gs(s.runtimeIndexUrl,s.runtimeSnapshot),e.setStdout({batched:P=>ie({type:"stdout",chunk:`${P}
777
+ `,sn=globalThis;let li=1;const Ar=new Map;let nn=!1,Os=!1,vr,wt,on,ht;function Xt(s){const e=Eo(ht??wt??{files:[]},s);return ht=s,e}function di(s,e){const t=ht??wt??{files:[]};Fo(s.FS,e,t),ht=ko(t,e)}let tt=s=>Ys(s.FS,wt??{files:[]}),gr,ui=1;const Ir=new Map;bi();sn.onmessage=s=>{const e=s.data;if(e.type==="run"){fi(e);return}if(e.type==="prepare"){Gs(e.runtimeIndexUrl,e.runtimeSnapshot).catch(()=>{});return}if(e.type==="shutdown"){_i();return}if(e.type==="network-response"||e.type==="network-error"){const o=Ir.get(e.requestId);if(!o)return;Ir.delete(e.requestId),e.type==="network-error"?o.reject(new Error(e.error)):o.resolve(new Response(e.body,{status:e.status,statusText:e.statusText,headers:e.headers}));return}const t=Ar.get(e.commitId);t&&(Ar.delete(e.commitId),e.error?t.reject(new Error(e.error)):t.resolve())};async function fi(s){let e,t;wt=s.filesystem,ht=s.filesystem;try{if(e=await Gs(s.runtimeIndexUrl,s.runtimeSnapshot),e.setStdout({batched:P=>ie({type:"stdout",chunk:`${P}
778
778
  `})}),e.setStderr({batched:P=>ie({type:"stderr",chunk:`${P}
779
- `})}),s.store){const P=await po({navigator:sn.navigator},s.store.projectId);if(!P)throw new Error("The project's store is not there to read.");gr=P;const F=Bo(e.FS,P);if(!F)throw new Error("This Pyodide exposes no filesystem to mount the workspace over.");tt=g=>Do(g.FS,F,s.filesystem)}else Lo(e.FS,s.filesystem),tt=P=>Ys(P.FS,s.filesystem);s.fileLocks&&s.fileCoherence&&(t=new ai(e.FS,new Qt(s.fileLocks.channel),new ti(s.fileCoherence),s.fileLocks.owner),await t.install(e)),on=()=>tt(e);const o=()=>yi(tt(e)),a=new Go(e,s.serverPort,o);new Qo(e,s.serverPort,P=>di(e,P),s.sharedMemoryChannels),await e.runPythonAsync(Xo),await e.runPythonAsync(`
779
+ `})}),s.store){const P=await po({navigator:sn.navigator},s.store.projectId);if(!P)throw new Error("The project's store is not there to read.");gr=P;const F=Bo(e.FS,P);if(!F)throw new Error("This Pyodide exposes no filesystem to mount the workspace over.");tt=g=>Co(g.FS,F,s.filesystem)}else Lo(e.FS,s.filesystem),tt=P=>Ys(P.FS,s.filesystem);s.fileLocks&&s.fileCoherence&&(t=new ai(e.FS,new Qt(s.fileLocks.channel),new ti(s.fileCoherence),s.fileLocks.owner),await t.install(e)),on=()=>tt(e);const o=()=>yi(tt(e)),a=new Go(e,s.serverPort,o);new Qo(e,s.serverPort,P=>di(e,P),s.sharedMemoryChannels),await e.runPythonAsync(Xo),await e.runPythonAsync(`
780
780
  import base64 as __browser_runtime_stdin_base64, io as __browser_runtime_stdin_io, sys as __browser_runtime_stdin_sys
781
781
  __browser_runtime_stdin_sys.stdin = __browser_runtime_stdin_io.TextIOWrapper(
782
782
  __browser_runtime_stdin_io.BytesIO(__browser_runtime_stdin_base64.b64decode(${JSON.stringify(s.stdinBase64)})),
783
783
  encoding="utf-8",
784
784
  )
785
- `),Ts(async()=>{t?.releaseAll(),await o(),qt(130,e)});const d=hi(s.argv,s.cwd);if(d){const P=await a.listenStatic(d.port,d.root);if(P<0)throw new Error(`python http.server could not listen on port ${d.port} (${P}).`);ie({type:"stdout",chunk:`Serving HTTP on 0.0.0.0 port ${d.port} (http://localhost:${d.port}/) ...
786
- `}),await Wt();return}await zo(e);const f=Wo(e.FS,s.argv,s.cwd);if(f){await Uo(e,f),ie({type:"stdout",chunk:`Successfully installed ${f.requirements.join(" ")}
785
+ `),Ns(async()=>{t?.releaseAll(),await o(),qt(130,e)});const d=hi(s.argv,s.cwd);if(d){const P=await a.listenStatic(d.port,d.root);if(P<0)throw new Error(`python http.server could not listen on port ${d.port} (${P}).`);ie({type:"stdout",chunk:`Serving HTTP on 0.0.0.0 port ${d.port} (http://localhost:${d.port}/) ...
786
+ `}),await Wt();return}await zo(e);const u=Wo(e.FS,s.argv,s.cwd);if(u){await Uo(e,u),ie({type:"stdout",chunk:`Successfully installed ${u.requirements.join(" ")}
787
787
  `}),t?.releaseAll(),qt(0,e);return}const h=mi(s.argv);if(h){await e.runPythonAsync(`
788
788
  import importlib, os, sys
789
789
  os.chdir(${JSON.stringify(s.cwd)})
@@ -798,7 +798,7 @@ for __browser_runtime_asgi_part in ${JSON.stringify(h.attribute.split("."))}:
798
798
  __browser_runtime_asgi_app = getattr(__browser_runtime_asgi_app, __browser_runtime_asgi_part)
799
799
  __browser_runtime_asgi_port = ${h.port}
800
800
  `),await e.runPythonAsync(Jo),await e.runPythonAsync("await __browser_runtime_start_asgi_lifespan()"),await o();const P=await a.listenAsgi(h.port);if(P<0)throw new Error(`Python ASGI app could not listen on port ${h.port} (${P}).`);ie({type:"stdout",chunk:`Serving Python ASGI app on http://localhost:${h.port}/ ...
801
- `}),Ts(async()=>{await a.idle(),await e.runPythonAsync("await __browser_runtime_stop_asgi_websockets()"),await e.runPythonAsync("await __browser_runtime_stop_asgi_lifespan()"),t?.releaseAll(),await o(),qt(130,e)}),await Wt();return}const m=wi(s.argv,s.env);if(m){await e.runPythonAsync(`
801
+ `}),Ns(async()=>{await a.idle(),await e.runPythonAsync("await __browser_runtime_stop_asgi_websockets()"),await e.runPythonAsync("await __browser_runtime_stop_asgi_lifespan()"),t?.releaseAll(),await o(),qt(130,e)}),await Wt();return}const m=wi(s.argv,s.env);if(m){await e.runPythonAsync(`
802
802
  import importlib, os, sys
803
803
  os.chdir(${JSON.stringify(s.cwd)})
804
804
  os.environ.clear()
@@ -813,4 +813,4 @@ for __browser_runtime_wsgi_part in ${JSON.stringify(m.attribute.split("."))}:
813
813
  __browser_runtime_wsgi_port = ${m.port}
814
814
  `),await e.runPythonAsync(Ss),await o();const P=await a.listenWsgi(m.port);if(P<0)throw new Error(`Python WSGI app could not listen on port ${m.port} (${P}).`);ie({type:"stdout",chunk:`Serving Python WSGI app on http://localhost:${m.port}/ ...
815
815
  `}),await Wt();return}const{code:w,argv:b}=pi(e.FS,s.argv,s.cwd);await e.runPythonAsync(Yo(s.cwd,s.env,b,w));const k=Number(await e.runPythonAsync("int(globals().get('__browser_runtime_wsgi_port', 0))"));if(k>0){await e.runPythonAsync(Ss),await o();const P=await a.listenWsgi(k);if(P<0)throw new Error(`Python WSGI app could not listen on port ${k} (${P}).`);ie({type:"stdout",chunk:`Serving Python WSGI app on http://localhost:${k}/ ...
816
- `}),await Wt();return}t?.releaseAll(),qt(0,e)}catch(o){try{t?.releaseAll()}catch{}const a=Zn(o),d=a?o.message:o instanceof Error?o.stack??o.message:String(o);let f={files:[],removed:[]};try{e&&(f=Xt(tt(e)))}catch{}ie({type:"result",exitCode:a?2:1,patch:f,error:d})}finally{gr?.close(),gr=void 0}}function pi(s,e,t){const o=je(e[0]??""),a=o==="python"||o==="python3"?e.slice(1):e;if(a[0]==="-c"&&a[1]!==void 0)return{code:a[1],argv:["-c",...a.slice(2)]};const d=a[0];if(!d||d.startsWith("-"))throw new Error("usage: python [-c command] | script.py [args...]");const f=Kt(d,t);if(!s.analyzePath(f).exists)throw new Error(`python: can't open file '${d}': No such file or directory`);return{code:new TextDecoder().decode(s.readFile(f)),argv:[d,...a.slice(1)]}}function hi(s,e){const t=je(s[0]??""),o=t==="python"||t==="python3"?s.slice(1):s;if(o[0]!=="-m"||o[1]!=="http.server")return;let a=8e3,d=e;for(let f=2;f<o.length;f+=1)o[f]==="--directory"&&o[f+1]?d=Kt(o[++f],e):o[f].startsWith("-")||(a=Number(o[f]));if(!Number.isSafeInteger(a)||a<=0||a>65535)throw new Error("http.server port must be 1..65535.");return{port:a,root:d}}function wi(s,e){const t=je(s[0]??""),o=t==="python"||t==="python3"?s.slice(1):s,a=o[0]==="-m"&&o[1]==="gunicorn"?o.slice(2):je(o[0]??"")==="gunicorn"?o.slice(1):void 0;if(!a)return;let d=Number(e.PORT??"")||8e3,f;const h=new Set(["-w","--workers","-k","--worker-class","-t","--timeout","--graceful-timeout","--keep-alive","--access-logfile","--error-logfile","--log-level","--log-file","-c","--config","--chdir","-n","--name","-u","--user","-g","--group","--threads","--max-requests"]);for(let b=0;b<a.length;b+=1){const k=a[b];if(k==="--bind"||k==="-b"){const P=a[++b]??"",F=Number(P.slice(P.lastIndexOf(":")+1));Number.isSafeInteger(F)&&F>0&&(d=F)}else if(k.startsWith("--bind=")){const P=Number(k.slice(k.lastIndexOf(":")+1));Number.isSafeInteger(P)&&P>0&&(d=P)}else if(h.has(k))b+=1;else{if(k.startsWith("-"))continue;if(!f)f=k;else throw new Error(`browser gunicorn does not support argument: ${k}`)}}if(!f)throw new Error("gunicorn requires a WSGI target such as wsgi:app.");const[m,w="application"]=f.split(":",2);if(!m||!/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/u.test(m)||!/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/u.test(w))throw new Error("Invalid gunicorn WSGI target.");return{module:m,attribute:w,port:d}}function mi(s){const e=je(s[0]??""),t=e==="python"||e==="python3"?s.slice(1):s,o=t[0]==="-m"&&t[1]==="uvicorn"?t.slice(2):je(t[0]??"")==="uvicorn"?t.slice(1):void 0;if(!o)return;let a=8e3,d;for(let m=0;m<o.length;m+=1)if(o[m]==="--port"&&o[m+1])a=Number(o[++m]);else if(o[m]==="--host"&&o[m+1])m+=1;else{if(o[m]==="--no-access-log")continue;if(o[m].startsWith("-"))throw new Error(`browser uvicorn does not support option: ${o[m]}`);if(!d)d=o[m];else throw new Error(`browser uvicorn does not support argument: ${o[m]}`)}if(!d||!d.includes(":"))throw new Error("uvicorn requires an ASGI target such as main:app.");const[f,h]=d.split(":",2);if(!f||!h||!/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/u.test(f)||!/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/u.test(h))throw new Error("Invalid uvicorn ASGI target.");if(!Number.isSafeInteger(a)||a<=0||a>65535)throw new Error("uvicorn port must be 1..65535.");return{module:f,attribute:h,port:a}}function qt(s,e){ie({type:"result",exitCode:s,patch:Xt(tt(e))})}function yi(s){const e=li++;return new Promise((t,o)=>{Ar.set(e,{resolve:t,reject:o}),ie({type:"commit",commitId:e,patch:Xt(s)})})}function Ts(s){vr=s,an()}function _i(){nn=!0,an()}function an(){const s=wt;!nn||Os||!vr||!s||(Os=!0,vr().catch(e=>ie({type:"result",exitCode:1,patch:Xt(gi(s)),error:e instanceof Error?e.stack??e.message:String(e)})))}function gi(s){try{return on?.()??s}catch{return s}}function Wt(){return new Promise(()=>{})}function bi(){Object.defineProperty(globalThis,"fetch",{value:async(e,t)=>{const o=new Request(e,t),a=fi++,d=[];o.headers.forEach((m,w)=>d.push([w,m]));const f=o.method==="GET"||o.method==="HEAD"?new ArrayBuffer(0):await o.arrayBuffer(),h=new Promise((m,w)=>Ir.set(a,{resolve:m,reject:w}));return ie({type:"network-request",requestId:a,purpose:Io(),url:o.url,method:o.method,headers:d,body:f},[f]),h},configurable:!1,writable:!1});for(const e of["XMLHttpRequest","WebSocket","EventSource","BroadcastChannel","SharedWorker"])try{Object.defineProperty(globalThis,e,{value:void 0,configurable:!1,writable:!1})}catch{}}function ie(s,e=[]){postMessage(s,e)}
816
+ `}),await Wt();return}t?.releaseAll(),qt(0,e)}catch(o){try{t?.releaseAll()}catch{}const a=Zn(o),d=a?o.message:o instanceof Error?o.stack??o.message:String(o);let u={files:[],removed:[]};try{e&&(u=Xt(tt(e)))}catch{}ie({type:"result",exitCode:a?2:1,patch:u,error:d})}finally{gr?.close(),gr=void 0}}function pi(s,e,t){const o=je(e[0]??""),a=o==="python"||o==="python3"?e.slice(1):e;if(a[0]==="-c"&&a[1]!==void 0)return{code:a[1],argv:["-c",...a.slice(2)]};const d=a[0];if(!d||d.startsWith("-"))throw new Error("usage: python [-c command] | script.py [args...]");const u=Kt(d,t);if(!s.analyzePath(u).exists)throw new Error(`python: can't open file '${d}': No such file or directory`);return{code:new TextDecoder().decode(s.readFile(u)),argv:[d,...a.slice(1)]}}function hi(s,e){const t=je(s[0]??""),o=t==="python"||t==="python3"?s.slice(1):s;if(o[0]!=="-m"||o[1]!=="http.server")return;let a=8e3,d=e;for(let u=2;u<o.length;u+=1)o[u]==="--directory"&&o[u+1]?d=Kt(o[++u],e):o[u].startsWith("-")||(a=Number(o[u]));if(!Number.isSafeInteger(a)||a<=0||a>65535)throw new Error("http.server port must be 1..65535.");return{port:a,root:d}}function wi(s,e){const t=je(s[0]??""),o=t==="python"||t==="python3"?s.slice(1):s,a=o[0]==="-m"&&o[1]==="gunicorn"?o.slice(2):je(o[0]??"")==="gunicorn"?o.slice(1):void 0;if(!a)return;let d=Number(e.PORT??"")||8e3,u;const h=new Set(["-w","--workers","-k","--worker-class","-t","--timeout","--graceful-timeout","--keep-alive","--access-logfile","--error-logfile","--log-level","--log-file","-c","--config","--chdir","-n","--name","-u","--user","-g","--group","--threads","--max-requests"]);for(let b=0;b<a.length;b+=1){const k=a[b];if(k==="--bind"||k==="-b"){const P=a[++b]??"",F=Number(P.slice(P.lastIndexOf(":")+1));Number.isSafeInteger(F)&&F>0&&(d=F)}else if(k.startsWith("--bind=")){const P=Number(k.slice(k.lastIndexOf(":")+1));Number.isSafeInteger(P)&&P>0&&(d=P)}else if(h.has(k))b+=1;else{if(k.startsWith("-"))continue;if(!u)u=k;else throw new Error(`browser gunicorn does not support argument: ${k}`)}}if(!u)throw new Error("gunicorn requires a WSGI target such as wsgi:app.");const[m,w="application"]=u.split(":",2);if(!m||!/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/u.test(m)||!/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/u.test(w))throw new Error("Invalid gunicorn WSGI target.");return{module:m,attribute:w,port:d}}function mi(s){const e=je(s[0]??""),t=e==="python"||e==="python3"?s.slice(1):s,o=t[0]==="-m"&&t[1]==="uvicorn"?t.slice(2):je(t[0]??"")==="uvicorn"?t.slice(1):void 0;if(!o)return;let a=8e3,d;for(let m=0;m<o.length;m+=1)if(o[m]==="--port"&&o[m+1])a=Number(o[++m]);else if(o[m]==="--host"&&o[m+1])m+=1;else{if(o[m]==="--no-access-log")continue;if(o[m].startsWith("-"))throw new Error(`browser uvicorn does not support option: ${o[m]}`);if(!d)d=o[m];else throw new Error(`browser uvicorn does not support argument: ${o[m]}`)}if(!d||!d.includes(":"))throw new Error("uvicorn requires an ASGI target such as main:app.");const[u,h]=d.split(":",2);if(!u||!h||!/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/u.test(u)||!/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/u.test(h))throw new Error("Invalid uvicorn ASGI target.");if(!Number.isSafeInteger(a)||a<=0||a>65535)throw new Error("uvicorn port must be 1..65535.");return{module:u,attribute:h,port:a}}function qt(s,e){ie({type:"result",exitCode:s,patch:Xt(tt(e))})}function yi(s){const e=li++;return new Promise((t,o)=>{Ar.set(e,{resolve:t,reject:o}),ie({type:"commit",commitId:e,patch:Xt(s)})})}function Ns(s){vr=s,an()}function _i(){nn=!0,an()}function an(){const s=wt;!nn||Os||!vr||!s||(Os=!0,vr().catch(e=>ie({type:"result",exitCode:1,patch:Xt(gi(s)),error:e instanceof Error?e.stack??e.message:String(e)})))}function gi(s){try{return on?.()??s}catch{return s}}function Wt(){return new Promise(()=>{})}function bi(){Object.defineProperty(globalThis,"fetch",{value:async(e,t)=>{const o=new Request(e,t),a=ui++,d=[];o.headers.forEach((m,w)=>d.push([w,m]));const u=o.method==="GET"||o.method==="HEAD"?new ArrayBuffer(0):await o.arrayBuffer(),h=new Promise((m,w)=>Ir.set(a,{resolve:m,reject:w}));return ie({type:"network-request",requestId:a,purpose:Io(),url:o.url,method:o.method,headers:d,body:u},[u]),h},configurable:!1,writable:!1});for(const e of["XMLHttpRequest","WebSocket","EventSource","BroadcastChannel","SharedWorker"])try{Object.defineProperty(globalThis,e,{value:void 0,configurable:!1,writable:!1})}catch{}}function ie(s,e=[]){postMessage(s,e)}