@volter/browser-substrate 0.1.103 → 0.1.105
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/catalog/demand-input.json +133 -0
- package/dist/boot-screen.d.ts +2 -0
- package/dist/boot-screen.d.ts.map +1 -1
- package/dist/boot-screen.js +1 -1
- package/dist/boot-screen.js.map +1 -1
- package/dist/cli/archive.d.ts +1 -0
- package/dist/cli/archive.d.ts.map +1 -1
- package/dist/cli/archive.js +4 -4
- package/dist/cli/archive.js.map +1 -1
- package/dist/cli/build.d.ts +5 -1
- package/dist/cli/build.d.ts.map +1 -1
- package/dist/cli/build.js +21 -2
- package/dist/cli/build.js.map +1 -1
- package/dist/cli/cache-root.d.ts +7 -0
- package/dist/cli/cache-root.d.ts.map +1 -0
- package/dist/cli/cache-root.js +24 -0
- package/dist/cli/cache-root.js.map +1 -0
- package/dist/cli/companions.d.ts +1 -1
- package/dist/cli/companions.d.ts.map +1 -1
- package/dist/cli/companions.js +30 -16
- package/dist/cli/companions.js.map +1 -1
- package/dist/cli/dependency-plan-build.d.ts +4 -0
- package/dist/cli/dependency-plan-build.d.ts.map +1 -1
- package/dist/cli/dependency-plan-build.js +111 -30
- package/dist/cli/dependency-plan-build.js.map +1 -1
- package/dist/cli/docker-build.d.ts +1 -0
- package/dist/cli/docker-build.d.ts.map +1 -1
- package/dist/cli/docker-build.js +4 -4
- package/dist/cli/docker-build.js.map +1 -1
- package/dist/cli/dry-run.d.ts +4 -4
- package/dist/cli/dry-run.d.ts.map +1 -1
- package/dist/cli/dry-run.js +10 -9
- package/dist/cli/dry-run.js.map +1 -1
- package/dist/cli/generated-code.d.ts +2 -1
- package/dist/cli/generated-code.d.ts.map +1 -1
- package/dist/cli/generated-code.js +46 -16
- package/dist/cli/generated-code.js.map +1 -1
- package/dist/cli/host-build.d.ts +1 -0
- package/dist/cli/host-build.d.ts.map +1 -1
- package/dist/cli/host-build.js +10 -9
- package/dist/cli/host-build.js.map +1 -1
- package/dist/cli/host-managers.d.ts +3 -1
- package/dist/cli/host-managers.d.ts.map +1 -1
- package/dist/cli/host-managers.js +7 -3
- package/dist/cli/host-managers.js.map +1 -1
- package/dist/cli/image-layers.d.ts.map +1 -1
- package/dist/cli/image-layers.js +5 -2
- package/dist/cli/image-layers.js.map +1 -1
- package/dist/cli/main.d.ts +5 -1
- package/dist/cli/main.d.ts.map +1 -1
- package/dist/cli/main.js +97 -34
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/pack-publication.d.ts +2 -2
- package/dist/cli/pack-publication.d.ts.map +1 -1
- package/dist/cli/pack-publication.js +3 -3
- package/dist/cli/pack-publication.js.map +1 -1
- package/dist/cli/package-pack.d.ts +1 -1
- package/dist/cli/package-pack.d.ts.map +1 -1
- package/dist/cli/package-pack.js +7 -4
- package/dist/cli/package-pack.js.map +1 -1
- package/dist/cli/package-packs.d.ts +1 -0
- package/dist/cli/package-packs.d.ts.map +1 -1
- package/dist/cli/package-packs.js +84 -14
- package/dist/cli/package-packs.js.map +1 -1
- package/dist/cli/plan-tarballs.d.ts +1 -0
- package/dist/cli/plan-tarballs.d.ts.map +1 -1
- package/dist/cli/plan-tarballs.js +6 -3
- package/dist/cli/plan-tarballs.js.map +1 -1
- package/dist/cli/preparation-memory.d.ts +17 -0
- package/dist/cli/preparation-memory.d.ts.map +1 -0
- package/dist/cli/preparation-memory.js +367 -0
- package/dist/cli/preparation-memory.js.map +1 -0
- package/dist/cli/project-build.d.ts +1 -0
- package/dist/cli/project-build.d.ts.map +1 -1
- package/dist/cli/project-build.js +100 -71
- package/dist/cli/project-build.js.map +1 -1
- package/dist/cli/provision-catalog.d.ts +49 -0
- package/dist/cli/provision-catalog.d.ts.map +1 -0
- package/dist/cli/provision-catalog.js +72 -0
- package/dist/cli/provision-catalog.js.map +1 -0
- package/dist/cli/provision-demand.d.ts +45 -0
- package/dist/cli/provision-demand.d.ts.map +1 -0
- package/dist/cli/provision-demand.js +208 -0
- package/dist/cli/provision-demand.js.map +1 -0
- package/dist/cli/rolldown-binding.d.ts +1 -1
- package/dist/cli/rolldown-binding.d.ts.map +1 -1
- package/dist/cli/rolldown-binding.js +8 -4
- package/dist/cli/rolldown-binding.js.map +1 -1
- package/dist/cli/serve.d.ts +3 -0
- package/dist/cli/serve.d.ts.map +1 -1
- package/dist/cli/serve.js +9 -2
- package/dist/cli/serve.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +75 -31
- package/dist/index.js.map +1 -1
- package/dist/origin-reset.d.ts +4 -0
- package/dist/origin-reset.d.ts.map +1 -0
- package/dist/origin-reset.js +76 -0
- package/dist/origin-reset.js.map +1 -0
- package/dist/program-dom.d.ts +2 -0
- package/dist/program-dom.d.ts.map +1 -1
- package/dist/program-dom.js +11 -1
- package/dist/program-dom.js.map +1 -1
- package/dist/program-types.d.ts +2 -0
- package/dist/program-types.d.ts.map +1 -1
- package/dist/shell/assets/browser-opfs-filesystem-worker-CmF6UKMW.js +3 -0
- package/dist/shell/assets/browser-sandbox-bridge-C8nlSsT2.js +237 -0
- package/dist/shell/assets/{filesystem-host-DJbFuokb.js → filesystem-host-BzPlXSri.js} +1 -1
- package/dist/shell/assets/filesystem-host-Pq9IHKRx.js +3 -0
- package/dist/shell/assets/filesystem-worker-CC3pSXUP.js +5 -0
- package/dist/shell/assets/{fork-worker-BXY2kfdX.js → fork-worker-4YKQ4KTo.js} +1 -1
- package/dist/shell/assets/{node-execution-worker-7e8e0c5321ca0d10.js → node-execution-worker-3ddf5efbaa427e9d.js} +8 -8
- package/dist/shell/assets/{sandbox-bMeKqKBn.js → sandbox-mhFzIWaQ.js} +1 -1
- package/dist/shell/assets/{shell-DLIQ6jHu.js → shell-BZbhxnju.js} +763 -757
- package/dist/shell/assets/worker-BmHEnCyv.js +816 -0
- package/dist/shell/assets/{worker-program-worker-B4OcKVtV.js → worker-program-worker-DueMwljE.js} +10 -10
- package/dist/shell/brand/fonts/Geist-Variable.woff2 +0 -0
- package/dist/shell/brand/fonts/GeistMono-Variable.woff2 +0 -0
- package/dist/shell/brand/fonts/InstrumentSerif-Italic.woff2 +0 -0
- package/dist/shell/brand/fonts/InstrumentSerif-Regular.woff2 +0 -0
- package/dist/shell/brand/icons/app-window.svg +1 -0
- package/dist/shell/brand/icons/at-sign.svg +1 -0
- package/dist/shell/brand/icons/box.svg +1 -0
- package/dist/shell/brand/icons/chevron-right.svg +1 -0
- package/dist/shell/brand/icons/folder.svg +1 -0
- package/dist/shell/brand/icons/info.svg +1 -0
- package/dist/shell/brand/icons/key-round.svg +1 -0
- package/dist/shell/brand/icons/link.svg +1 -0
- package/dist/shell/brand/icons/monitor.svg +1 -0
- package/dist/shell/brand/icons/plus.svg +1 -0
- package/dist/shell/brand/icons/rotate-ccw.svg +1 -0
- package/dist/shell/brand/icons/share-2.svg +1 -0
- package/dist/shell/brand/icons/square-arrow-out-up-right.svg +1 -0
- package/dist/shell/brand/icons/terminal.svg +1 -0
- package/dist/shell/brand/icons/x.svg +1 -0
- package/dist/shell/brand/substrate.svg +1 -0
- package/dist/shell/brand/tokens.css +211 -0
- package/dist/shell/brand/wordmark.svg +1 -0
- package/dist/shell/index.html +5 -3
- package/dist/shell/node-execution-worker.js +16 -13
- package/dist/shell/node-host.html +2 -0
- package/dist/shell/python-execution-worker.js +15 -12
- package/dist/shell/python-host.html +2 -0
- package/dist/shell/python-runtime-snapshot.bin +0 -0
- package/dist/shell/python-runtime-snapshot.json +1 -1
- package/dist/shell/sandbox.html +4 -2
- package/dist/toolbar-styles.generated.d.ts +1 -1
- package/dist/toolbar-styles.generated.d.ts.map +1 -1
- package/dist/toolbar-styles.generated.js +1 -1
- package/dist/toolbar-styles.generated.js.map +1 -1
- package/dist/toolbar.d.ts.map +1 -1
- package/dist/toolbar.js +3 -1
- package/dist/toolbar.js.map +1 -1
- package/package.json +1 -1
- package/dist/shell/assets/browser-opfs-filesystem-worker-k2CPzPBU.js +0 -3
- package/dist/shell/assets/browser-sandbox-bridge-BJbQoc4f.js +0 -237
- package/dist/shell/assets/filesystem-host-yMcJuvmT.js +0 -3
- package/dist/shell/assets/filesystem-worker-BbsBhZ9p.js +0 -5
- package/dist/shell/assets/worker-Ce8bBwSJ.js +0 -816
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{d as at,e as Fe,r as Ee,B as Ci,W as Di,a as Ui,b as Hi,c as ji,f as Wi,F,g as En,h as Yi,i as bn,j as Gi}from"./fork-worker-BXY2kfdX.js";const zn=2019846480,or=6,ie=6,ft=3,rr=0,Ot=1,Ie=2,$n=3,_n=4,Cn=5,Dn=0,Un=1,Hn=2,nr=1,jn=2,Wn=4,ir=32,vr=3,Br=["file","directory","symlink"],Ki=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,Ji=new TextEncoder,Vi=new TextDecoder;function Yn(d){let e=2166136261;for(let t=0;t<d.length;t+=1)e^=d.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function Sn(d,e){const t=[...d.keys()];for(const N of t)if(Ki.test(N))throw new Error("A path in the store is not well-formed UTF-16.");const n=new Map;for(let N=0;N<t.length;N+=1)n.set(t[N],N);for(const N of e.keys())n.has(N)||(n.set(N,t.length),t.push(N));const s=t.length,f=new Map,o=new Uint32Array(s);let h=0;for(let N=0;N<s;N+=1){const H=t[N];let G=!0;for(let le=0;le<H.length;le+=1)if(H.charCodeAt(le)>=128){G=!1;break}G||f.set(N,Ji.encode(H)),o[N]=G?H.length:f.get(N).length,h+=o[N]}let w=0;for(const N of e.values())w+=N.size;let g=1;for(;g<s*2;)g<<=1;const E=or*4,S=Nr(E+s*ie*4,8),k=S+s*ft*8,I=k+g*4,p=I+w*4,L=new SharedArrayBuffer(Nr(p+h,8));new Uint32Array(L,0,or).set([zn,s,g,w,h,d.size]);const W=new Uint32Array(L,E,s*ie),D=new Float64Array(L,S,s*ft),Je=new Uint32Array(L,k,g),Ft=new Uint32Array(L,I,w),Be=new Uint8Array(L,p,h);let de=0,z=0;for(let N=0;N<s;N+=1){const H=t[N],G=N*ie,le=f.get(N);if(le)Be.set(le,de);else for(let P=0;P<H.length;P+=1)Be[de+P]=H.charCodeAt(P);const T=o[N];W[G+rr]=de,W[G+Ot]=T,de+=T;let q=le?0:ir;const ee=d.get(H);if(ee){q|=nr|Br.indexOf(ee.type)<<vr,ee.pack&&(q|=Wn),W[G+$n]=ee.mode;const P=N*ft;D[P+Dn]=ee.mtimeMs,D[P+Un]=ee.offset,D[P+Hn]=ee.length}const Ne=e.get(H);if(Ne){q|=jn,W[G+_n]=z,W[G+Cn]=Ne.size;for(const P of Ne){const R=n.get(`${H}/${P}`);if(R===void 0)throw new Error(`The store's children name ${H}/${P}, which its index does not hold.`);Ft[z++]=R}}W[G+Ie]=q;let Se=Yn(H)&g-1;for(;Je[Se]!==0;)Se=Se+1&g-1;Je[Se]=N+1}if(z!==w)throw new Error("The shared index's children did not add up.");return L}function Nr(d,e){return Math.ceil(d/e)*e}class Pe{buffer;count;entryCount;records;numbers;table;childList;strings;mask;constructor(e){const t=new Uint32Array(e,0,or);if(t[0]!==zn)throw new Error("Not a shared store index.");const[,n,s,f,o,h]=t;this.buffer=e,this.count=n,this.entryCount=h;const w=or*4,g=Nr(w+n*ie*4,8),E=g+n*ft*8,S=E+s*4,k=S+f*4;this.records=new Uint32Array(e,w,n*ie),this.numbers=new Float64Array(e,g,n*ft),this.table=new Uint32Array(e,E,s),this.childList=new Uint32Array(e,S,f),this.strings=new Uint8Array(e,k,o),this.mask=s-1}find(e){let t=Yn(e)&this.mask;for(;;){const n=this.table[t];if(n===0)return-1;if(this.pathIs(n-1,e))return n-1;t=t+1&this.mask}}entry(e){const t=e*ie,n=this.records[t+Ie];if(!(n&nr))return;const s=e*ft,f={type:Br[n>>>vr&3],mode:this.records[t+$n],mtimeMs:this.numbers[s+Dn],offset:this.numbers[s+Un],length:this.numbers[s+Hn]};return n&Wn&&(f.pack="packages"),f}typeAt(e){const t=this.records[e*ie+Ie];return t&nr?Br[t>>>vr&3]:void 0}hasEntry(e){return(this.records[e*ie+Ie]&nr)!==0}childNames(e){const t=e*ie;if(!(this.records[t+Ie]&jn))return;const n=this.records[t+_n],s=this.records[t+Ot]+1,f=[];for(let o=0;o<this.records[t+Cn];o+=1){const h=this.childList[n+o]*ie;f.push(this.decode(this.records[h+rr]+s,this.records[h+Ot]-s,(this.records[h+Ie]&ir)!==0))}return f}path(e){const t=e*ie;return this.decode(this.records[t+rr],this.records[t+Ot],(this.records[t+Ie]&ir)!==0)}decode(e,t,n){if(!n)return Vi.decode(this.strings.slice(e,e+t));let s="";for(let f=e,o=e+t;f<o;f+=4096)s+=String.fromCharCode.apply(null,this.strings.subarray(f,Math.min(o,f+4096)));return s}pathIs(e,t){const n=e*ie,s=this.records[n+rr],f=this.records[n+Ot];if(!(this.records[n+Ie]&ir))return this.path(e)===t;if(f!==t.length)return!1;for(let o=0;o<f;o+=1)if(this.strings[s+o]!==t.charCodeAt(o))return!1;return!0}}const ae=Symbol("deleted");function Gn(d,e){return d===e||!!d&&!!e&&d.type===e.type&&d.offset===e.offset&&d.length===e.length&&d.pack===e.pack&&d.mode===e.mode&&d.mtimeMs===e.mtimeMs&&d.capacity===e.capacity}class Ye{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===ae?void 0:t;const n=this.base.find(e);return n<0?void 0:this.base.entry(n)}typeOf(e){const t=this.overlay.get(e);if(t!==void 0)return t===ae?void 0:t.type;const n=this.base.find(e);return n<0?void 0:this.base.typeAt(n)}has(e){const t=this.overlay.get(e);if(t!==void 0)return t!==ae;const n=this.base.find(e);return n>=0&&this.base.hasEntry(n)}set(e,t){this.has(e)||(this.delta+=1);const n=this.base.find(e);return n>=0&&Gn(this.base.entry(n),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,ae):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!==ae&&(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[n,s]of this.entries())e.call(t,s,n,this)}*changed(){for(const[e,t]of this.overlay)t!==ae&&(yield[e,t])}*changes(){for(const[e,t]of this.overlay)yield[e,t===ae?null:t]}get overlaid(){return this.overlay.size}boundedChanges(){if(this.overlay.size>65536)return;const e=[];let t=0;for(const[n,s]of this.changes()){if(t+=n.length*2+128,t>8*1024*1024)return;e.push([n,s])}return e}}class It{base;overlay=new Map;constructor(e){this.base=e}get(e){const t=this.overlay.get(e);if(t!==void 0)return t===ae?void 0:t;const n=this.base.find(e),s=n<0?void 0:this.base.childNames(n);return s?new Set(s):void 0}mutable(e){const t=this.overlay.get(e);if(t!==void 0&&t!==ae)return t;const n=new Set(t===ae?[]:this.get(e)??[]);return this.overlay.set(e,n),n}delete(e){this.overlay.set(e,ae)}}function kn(d){const e=d.lastIndexOf("/");return e<=0?"/":d.slice(0,e)}function rt(d){return d==="/"?"":d}const qi="/opt/tree";function Xi(d){return`volter-tree-store-use:${d}`}function Zi(d,e=globalThis.navigator?.locks){if(!e)return Promise.resolve();let t=An.get(e);t||An.set(e,t=new Map);let n=t.get(d);if(!n){n=new Promise((f,o)=>{e.request(Xi(d),{mode:"shared"},()=>(f(),new Promise(()=>{}))).catch(o)});const s=t;n.catch(()=>s.delete(d)),t.set(d,n)}return n}const An=new WeakMap;function Qi(d,e){const t=new Pe(d.index),n=new Ye(t),s=new It(t),f={childrenOf:h=>[...s.get(rt(h))??[]].sort(),descendants(h){const w=[],g=E=>{const S=n.get(E);S&&w.push([E,S]);for(const k of s.get(rt(E))??[])g(`${rt(E)}/${k}`)};return g(h),w}};if(d.store!==void 0){const h=e?.get(d.store),w=d.roots?.[0]??"/",g=d.storeRoot??w,E=k=>g+k.slice(w==="/"?0:w.length),S=k=>{const I=n.get(k);if(!I||I.type==="directory")throw new Error(`The shared layer holds no file at ${k}.`);if(!h)throw new Error(`${k} is in the store ${d.store}, which this realm did not open.`);return h};return{entries:n,read:k=>S(k).read(E(k)),readRange:(k,I,p)=>S(k).readRange(E(k),I,p),readsByRange:()=>!0,...f}}if(!d.bytes)throw new Error("A shared layer holds neither its bytes nor a store of them.");const o=new Uint8Array(d.bytes);return{entries:n,read(h){const w=n.get(h);if(!w||w.type==="directory")throw new Error(`The shared layer holds no file at ${h}.`);return o.slice(w.offset,w.offset+w.length)},view(h){const w=n.get(h);if(!w||w.type==="directory")throw new Error(`The shared layer holds no file at ${h}.`);return o.subarray(w.offset,w.offset+w.length)},readRange(h,w,g){const E=n.get(h);if(!E||E.type==="directory")throw new Error(`The shared layer holds no file at ${h}.`);const S=Math.min(Math.max(0,w),E.length);return o.slice(E.offset+S,E.offset+Math.min(E.length,S+Math.max(0,g)))},childrenOf:h=>[...s.get(rt(h))??[]].sort(),descendants(h){const w=[],g=E=>{const S=n.get(E);S&&w.push([E,S]);for(const k of s.get(rt(E))??[])g(`${rt(E)}/${k}`)};return g(h),w}}}function es(d){if(d.length===1)return d[0];const e=(o,h)=>{if(o===0)return!1;for(let w=kn(h);;w=kn(w)){for(let g=0;g<o;g+=1){const E=d[g].entries.get(w);if(E&&E.type!=="directory")return!0}if(w==="/")return!1}},t=o=>{for(let h=0;h<d.length;h+=1)if(d[h].entries.has(o)&&!e(h,o))return h;return-1},n=o=>d[t(o)],s={get:o=>n(o)?.entries.get(o),has:o=>t(o)>=0,get size(){let o=0;for(const h of s)o+=1;return o},*[Symbol.iterator](){const o=new Set;for(let h=0;h<d.length;h+=1)for(const[w,g]of d[h].entries)o.has(w)||t(w)!==h||(o.add(w),yield[w,g])},*entries(){yield*s[Symbol.iterator]()},*keys(){for(const[o]of s)yield o},*values(){for(const[,o]of s)yield o},forEach(o){for(const[h,w]of s)o(w,h,s)}},f=o=>{const h=n(o)?.entries.get(o);return h&&h.type!=="directory"?[]:d.filter((w,g)=>{const E=w.entries.get(o);return(!E||E.type==="directory")&&!e(g,o)})};return{entries:s,read:o=>{const h=n(o);if(!h)throw new Error(`No lower tree holds ${o}.`);return h.read(o)},view:o=>{const h=n(o);if(!h)throw new Error(`No lower tree holds ${o}.`);return h.view?h.view(o):h.read(o)},readRange:(o,h,w)=>{const g=n(o);if(!g)throw new Error(`No lower tree holds ${o}.`);if(g.readRange)return g.readRange(o,h,w);const E=g.read(o),S=Math.min(Math.max(0,h),E.byteLength);return E.slice(S,Math.min(E.byteLength,S+Math.max(0,w)))},readsByRange:o=>n(o)?.readsByRange?.(o)??!1,childrenOf:o=>[...new Set(f(o).flatMap(h=>h.childrenOf(o)))].sort(),descendants:o=>{const h=[],w=new Set;for(const E of d)for(const[S]of E.descendants(o)){if(w.has(S))continue;w.add(S);const k=s.get(S);k&&h.push([S,k])}const g=h.findIndex(([E])=>E===o);return g>0&&h.unshift(...h.splice(g,1)),h}}}function Mn(d,e,t){const n=[...d?[d]:[],...(e??[]).map(s=>Qi(s,t))];return n.length===0?void 0:es(n)}const ts="supercode-browser-filesystems",xe="packages",rs="state.json",On="/image-range-worker.js",In="image-ranges.json",ns=2;function Or(d){const e=d;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 n of e.parts){if(!n||n.offset!==t||!Number.isSafeInteger(n.raw)||n.raw<0||!Number.isSafeInteger(n.bytes)||n.bytes<0||n.bytes>1024*1024*1024||n.raw>1024*1024*1024||typeof n.sha256!="string"||!/^[a-f0-9]{64}$/u.test(n.sha256)||typeof n.url!="string"||!/^\/substrate\/[A-Za-z0-9._/-]+$/u.test(n.url)||n.url.split("/").some(s=>s==="."||s===".."))throw new Error("Invalid immutable image part.");if(t+=n.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 is{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,n,s,f,o){if(this.ranges=e,this.directory=t,this.identity=n,this.receiptKey=f,this.client=o,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(o?.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,w=s??new SharedArrayBuffer((2*h+1)*Int32Array.BYTES_PER_ELEMENT);if(w.byteLength!==h*Int32Array.BYTES_PER_ELEMENT&&w.byteLength!==(2*h+1)*Int32Array.BYTES_PER_ELEMENT)throw new Error("The image completion seed has the wrong range count.");this.completed=new Int32Array(w,0,h),this.firstRead=w.byteLength>h*Int32Array.BYTES_PER_ELEMENT?new Int32Array(w,h*Int32Array.BYTES_PER_ELEMENT,h+1):void 0,this.sharedCompletion=s!==void 0;for(const g of e.parts)Object.freeze(g);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=n=>{n.data?.type!=="closing"||this.port!==t||(t.close(),this.port=void 0,this.closed||this.startMaterializer().catch(s=>console.warn("This process's image reader could not start its own materializer after its line closed.",s)))},t.start(),this.ready=!0;return}return this.startMaterializer()}startMaterializer(){const e=Date.now(),t=new Worker(On,{type:"module",name:"immutable-image-materializer"}),n=this.ready;return n||(this.worker=t),t.addEventListener("error",()=>this.fail()),t.addEventListener("messageerror",()=>this.fail()),this.startup=new Promise((s,f)=>{const o=()=>{clearTimeout(E),t.removeEventListener("message",g),t.removeEventListener("error",h),t.removeEventListener("messageerror",h),this.cancelStartup=void 0},h=()=>w(new Error("The immutable image materializer could not initialize; reload to retry.")),w=S=>{o(),t.terminate(),n||(this.closed=!0,this.fail()),f(S)},g=S=>{if(S.data?.identity===this.identity){if(S.data.type==="init-error"){w(new Error(`The immutable image materializer could not initialize: ${String(S.data.error)}`));return}S.data.type==="ready"&&(console.log(`[boot-trace] ${JSON.stringify({event:"materializer-ready",at:Date.now(),ms:Date.now()-e})}`),o(),this.ready=!0,this.worker=t,s())}},E=setTimeout(()=>w(new Error("The immutable image materializer did not initialize within 10 seconds; reload to retry.")),1e4);this.cancelStartup=w,t.addEventListener("message",g),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(S){w(S instanceof Error?S:new Error(String(S)))}}),this.startup}readDigests(){const e=this.firstRead;if(!e)return;const t=this.ranges.parts.length,n=[];for(let s=0;s<t;s+=1){const f=Atomics.load(e,s),o=this.ranges.parts[s];f>0&&o.raw>0&&n.push([f,o.sha256])}return n.sort((s,f)=>s[0]-f[0]).map(([,s])=>s)}completedDigests(){const e=[];for(let t=0;t<this.completed.length;t+=1){const n=this.ranges.parts[t];n.raw>0&&Atomics.load(this.completed,t)===2&&e.push(n.sha256)}return e}prefetch(e,t=[]){if(this.closed||!this.ready||!this.worker)return{queued:0,done:Promise.resolve()};const n=new Map;for(let h=0;h<this.ranges.parts.length;h+=1){const w=this.ranges.parts[h];if(w.raw===0)continue;const g=n.get(w.sha256);g?g.push(h):n.set(w.sha256,[h])}const s=[];for(const h of new Set(e))for(const w of n.get(h)??[])Atomics.load(this.completed,w)!==2&&s.push(w);const f=t.length>0&&s.length>0?Math.min(t.length,8):Math.min(ns,Math.ceil(s.length/32)),o=[];for(let h=0;h<f;h+=1){const w=s.filter((k,I)=>I%f===h),g=new Worker(On,{type:"module",name:"immutable-image-prefetch"});this.prefetchers.push(g);let E;o.push(new Promise(k=>{E=k}));const S=()=>{g.terminate(),this.prefetchers=this.prefetchers.filter(k=>k!==g),E()};g.addEventListener("error",S),g.addEventListener("messageerror",S),g.addEventListener("message",k=>{k.data?.identity===this.identity&&(k.data.type==="ready"?g.postMessage(t.length>0?{type:"prefetch-stream",url:t[h]}:{type:"prefetch",indices:w}):(k.data.type==="prefetched"||k.data.type==="init-error")&&S())}),g.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:s.length,done:Promise.all(o).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 n=Math.min(e+t,this.ranges.bytes);let s=0,f=this.ranges.parts.length;for(;s<f;){const o=s+f>>>1,h=this.ranges.parts[o];h.offset+h.raw<=e?s=o+1:f=o}for(let o=s;o<this.ranges.parts.length;o+=1){const h=this.ranges.parts[o];if(h.offset>=n)break;const w=this.firstRead;if(w&&Atomics.load(w,o)===0&&Atomics.compareExchange(w,o,0,Atomics.add(w,this.ranges.parts.length,1)+1),Atomics.load(this.completed,o)===2)continue;const g=this.worker??this.port;if(!g)throw new Error("This immutable image reader's line closed and its own materializer is still starting; retry the read.");g.postMessage({type:"read",index:o});const E=performance.now(),S=E+3e4;for(;Atomics.load(this.state,o)===0;){const k=S-performance.now();if(k<=0||Atomics.wait(this.state,o,0,k)==="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()-E,Atomics.load(this.state,o)!==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,n=new SharedArrayBuffer(this.ranges.parts.length*Int32Array.BYTES_PER_ELEMENT);return e.postMessage({type:"client",port:t.port1,state:n},[t.port1]),{port:t.port2,state:n}}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 Ir="/packages",qt="supercode-browser-packages",je=new TextEncoder,nt=new TextDecoder("utf-8",{fatal:!0}),ss=ts,Xt="generations",Pn="atomic-staging",it=rs,ce="index.json",Pr="index-log.bin",st="pack.bin",Zt=8,xn=64*1024*1024,ne=1024*1024*1024,Tn=4*1024*1024*1024,Kn=["/workspace","/home","/opt"],We=0,Fn=1,xr=1e6,Ln=8*1024*1024,vn=250,os=64*1024*1024,as=256*1024*1024,Bn=4*1024*1024,ot=493,Qt=420;function Rr(d,e={}){const t=e.limits?.maxBytes??Tn,n=e.limits?.maxEntries??xr;if(!Number.isSafeInteger(t)||t<1||t>Tn||!Number.isSafeInteger(n)||n<1||n>xr)throw new Error("Invalid OPFS workspace limits.");let s,f=!1,o=!1,h=!1,w,g=0,E=0,S,k,I,p=new Map,L=new er,v,W,D,Je,Ft,Be,de=0,z,N=0;const H=new Map,G=256*1024,le=32;let T=0,q,ee=-1/0,Ne=0,Se=0,P=0,R=0,K=0,Re=0,ze=0,se,Lt,he,Ve=!1,wt,jr=Promise.resolve(),qe=0,j=!1,Xe=!1,Y,$e=0,ue=!1;function vt(){if(!(!Y||ue)){if(P>2147483647){Bt();return}Atomics.store(Y,Fn,P)}}function Bt(){!Y||ue||(ue=!0,(Atomics.load(Y,We)&1)===0&&Atomics.add(Y,We,1))}function mt(){$e+=1,$e===1&&Y&&!ue&&Atomics.add(Y,We,1)}function gt(){$e-=1,!($e>0||!Y||ue)&&(vt(),ue||Atomics.add(Y,We,1))}function Wr(){if(o)throw new Error("A store open for reading follows its owner's clock; it has none of its own.");return Y||(Y=new Int32Array(new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT)),Y[We]=$e>0||ue?1:0,vt()),Y.buffer}let te;const Zn=8*1024*1024;let Yr=!1;function Qn(r){if(o||!Y||!I||Ve||$e>0||ue||j)return;const i=Atomics.load(Y,We);if(i&1)return;if(r?.overlays&&p instanceof Ye){const l=p.boundedChanges();if(l)return hr({generation:I,index:p.base.buffer,changes:l,packBytes:T,logBytes:P,epoch:i,liveBytes:R,linked:g,linkedBytes:E})}if(te&&te.generation===I&&te.epoch===i&&P>=te.logBytes&&P-te.logBytes<=(r?.current?0:Zn))return hr(te);let a;try{a=Sn(p,ri())}catch(l){console.warn(`[pack-store] no reader seed: ${l instanceof Error?l.message:String(l)}`);return}return te={generation:I,index:a,packBytes:T,logBytes:P,epoch:i,liveBytes:R,linked:g,linkedBytes:E},ti(a),hr(te)}function hr(r){const i=e.packages?.imageCompletionSeed();return i?{...r,packagesImage:i}:r}function ei(){if(!(!D||!W||!I||Ve||$e>0||j))return{generation:I,rangesDigest:W,completed:D.completionBuffer,...D.receiptKey?{metadata:{ranges:D.verifiedRanges,receiptKey:D.receiptKey}}:{}}}function ti(r){const i=[];if(p instanceof Ye)for(const[l,c]of p.changed())c.capacity!==void 0&&i.push([l,c]);else for(const[l,c]of p)c.capacity!==void 0&&i.push([l,c]);const a=new Pe(r);p=new Ye(a),L=new It(a);for(const[l,c]of i)p.set(l,c)}function ri(){if(L instanceof er)return L.map;const r=new Map;for(const i of p.keys()){const a=Ue(i);if(a===i)continue;let l=r.get(a);l||(l=new Set,r.set(a,l)),l.add(i.slice(a.length+1))}return r}function ni(){!o||h||j||!z||_t(P)}async function Nt(r){if(j)throw new Error("This OPFS workspace is closing.");qe+=1;let i,a=!1;try{return await r()}catch(l){throw a=!0,i=l,l}finally{if(qe-=1,j&&qe===0)try{mn()}catch(l){throw a?new AggregateError([i,l],"OPFS operation and deferred close both failed."):l}}}async function Rt(r){return ke(),qe!==0?Promise.reject(new Error("Wait for the current OPFS storage operation before replacing its generation.")):(Xe=!0,Nt(async()=>{try{return await r()}finally{Xe=!1}}))}function ii(r){if(j)throw new Error("This OPFS workspace is closing.");const i=p.get(r);if(!i||i.type==="directory")throw new Error(`OPFS workspace file does not exist: ${r}`);return zt(i)}function si(r,i,a){if(j)throw new Error("This OPFS workspace is closing.");const l=p.get(r);if(!l||l.type==="directory")throw new Error(`OPFS workspace file does not exist: ${r}`);const c=Math.min(Math.max(0,i),l.length),u=Math.min(Math.max(0,a),l.length-c);if(l.pack){const y=e.packages;if(!y)throw new Error("This store has no shared package store to read from.");return y.readExtent(l.offset+c,u)}return $t(l.offset+c,u)}function zt(r){if(r.pack){const i=e.packages;if(!i)throw new Error("This store has no shared package store to read from.");return i.readExtent(r.offset,r.length)}return $t(r.offset,r.length)}function $t(r,i){if(j)throw new Error("This OPFS workspace is closing.");const a=v;if(!a)throw new Error("OPFS filesystem worker is not initialized.");const l=new Uint8Array(i);if(i>0&&i<=G&&r>=0&&r+i<=N){let c=0;for(;c<i;){const u=r+c,y=Math.floor(u/G)*G;let m=H.get(y);if(!m&&(m=new Uint8Array(Math.min(G,N-y)),D?.ensure(y,m.byteLength),a.read(m,{at:y})!==m.byteLength))throw new Error("An OPFS package range could not be read completely.");H.delete(y),H.set(y,m),H.size>le&&H.delete(H.keys().next().value);const b=u-y,A=Math.min(i-c,m.byteLength-b);l.set(m.subarray(b,b+A),c),c+=A}return l}if(D?.ensure(r,i),i>0&&a.read(l,{at:r})!==i)throw new Error("An OPFS workspace file could not be read completely.");return l}async function oi(r,i={}){if(j&&s||!s&&qe!==0)throw new Error("Wait for this OPFS workspace to finish closing before opening it again.");if(Ve)throw new Error("This OPFS store is already opening a workspace.");if(s){if(k!==Jr(r))throw new Error("Close this OPFS store before opening another workspace.");return p.size>0}Ve=!0,j=!1;const a=new AbortController;wt=a;try{p=new Map,L=new er,I=void 0,W=void 0,w=void 0,se=void 0,he=void 0,T=P=R=K=g=E=0,we=void 0,Re=ze=Ne=Se=0,ee=-1/0,k=Jr(r),o=i.readOnly===!0,Ft=o?i.imageCompletion:void 0,Be=o?i.imageLine:void 0,h=o&&i.extentsOnly===!0,f=i.shared===!0||o,f||await li(a.signal),a.signal.throwIfAborted();const l=await ci();a.signal.throwIfAborted();try{const y=await l.getDirectoryHandle(ss,{create:!o});a.signal.throwIfAborted(),s=await y.getDirectoryHandle(k,{create:!o})}catch(y){if(a.signal.throwIfAborted(),o&&tt(y))return!1;throw y}a.signal.throwIfAborted();let c=Jt(await De(s,it));if(a.signal.throwIfAborted(),!c&&o)return await yr(),!1;if(!c&&f&&(await d.navigator.locks.request(qt,{mode:"exclusive",signal:a.signal},async()=>{a.signal.throwIfAborted(),c=Jt(await De(s,it)),a.signal.throwIfAborted(),c||(await yr(),await rn({files:[],pack:new ArrayBuffer(0)}),await ds(s))}),a.signal.throwIfAborted(),!c))return w=await ye(I,!1),a.signal.throwIfAborted(),!1;if(!c)return await yr(),a.signal.throwIfAborted(),!1;const u=async y=>{let m;try{m=await ye(y.generation,!1)}catch(O){throw a.signal.throwIfAborted(),tt(O)?new Error("The committed OPFS workspace generation is missing. Stored generations were retained.",{cause:O}):O}if(a.signal.throwIfAborted(),I=y.generation,de=y.initializedAt,W=y.imageRanges,w=m,h)return k===xe&&d.navigator.locks?await d.navigator.locks.request(qt,{mode:"shared",signal:a.signal},async()=>{await Ze(m),N=v.getSize()}):await Ze(m),a.signal.throwIfAborted(),!0;const b=o?i.seed:void 0;if(b&&b.generation===y.generation){const O=new Pe(b.index);return p=new Ye(O),L=new It(O),T=b.packBytes,b.changes&&Kr({packBytes:b.packBytes,changes:b.changes}),await Ze(m),a.signal.throwIfAborted(),P=b.logBytes,{liveBytes:R,linked:g,linkedBytes:E}=b,K=Math.max(0,T-R),Yr=!0,p.size>0}const A=o?void 0:await Li(m);if(a.signal.throwIfAborted(),A){const O=new Pe(A.index);p=new Ye(O),L=new It(O),{packBytes:T,liveBytes:R,linked:g,linkedBytes:E}=A;const M=Atomics.load(new Int32Array(Wr()),We);te={generation:I,index:A.index,packBytes:T,liveBytes:R,linked:g,linkedBytes:E,logBytes:0,epoch:M}}else p=kr(await De(m,ce)),a.signal.throwIfAborted(),et(),T=ur(p);await Ze(m),a.signal.throwIfAborted();const x=A?await vi(A):0;return a.signal.throwIfAborted(),x&&(we={generation:I,bytes:x},te&&(te.logBytes=x)),_t(x,!!A),A?K=Math.max(0,T-R):pt(),en(),f&&!o&&!A&&p.size>=1e4&&(Me(),await St(m,p,{access:z,bytes:P,packBytes:T})),f||(v.truncate(T),await an(s,Pn,!0),await wr(I),a.signal.throwIfAborted(),K>os&&K>R&&await Si()),a.signal.throwIfAborted(),p.size>0};return f&&!o?await d.navigator.locks.request(qt,{mode:"exclusive",signal:a.signal},async()=>{if(c=Jt(await De(s,it)),!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{Qe()}catch(u){c.push(u)}try{S?.()}catch(u){c.push(u)}throw S=void 0,s=void 0,c.length>1?new AggregateError(c,"OPFS workspace open and cleanup failed."):l}finally{Ve=!1,wt=void 0}}function ai(r){return Nt(()=>Gr(r?.whole===!0))}async function Gr(r=!1){if(h)throw new Error("A store opened for its extents alone has no index to follow.");if(o&&s){const u=Jt(await De(s,it));if(!u)throw new Error("The committed OPFS workspace state is missing. Stored data was retained.");if(u.generation!==I||r){const y=await ye(u.generation,!1),m=kr(await De(y,ce));T=ur(m),u.generation!==I&&(I=u.generation,de=u.initializedAt,W=u.imageRanges,await Ze(y)),I=u.generation,w=y,p=m,et(),_t(),pt();return}}const i=z;if(!i||!w)return;const a=i.getSize();let l=!1;a<P&&(p=kr(await De(w,ce)),et(),T=ur(p),P=0,l=!0);const c=P;_t(P),(l||P!==c)&&pt()}async function ci(){let r;for(let i=0;i<10;i+=1){wt?.signal.throwIfAborted();try{return await d.navigator.storage.getDirectory()}catch(a){r=a,await new Promise(l=>setTimeout(l,200))}}throw r instanceof Error?r:new Error("This browser workspace's storage is unavailable.")}const fi=1e4;async function X(r,i){let a;const l=wt?.signal;for(let u=0;u<2;u+=1){l?.throwIfAborted();const y=r.createSyncAccessHandle({mode:"readwrite-unsafe"});let m,b,A=!1;try{const x=new Promise((M,C)=>{b=()=>C(l?.reason??new DOMException("Workspace open was cancelled.","AbortError")),l?.addEventListener("abort",b,{once:!0}),l?.aborted&&b()}),O=await Promise.race([y.then(M=>({access:M})).catch(M=>{a=M}),new Promise(M=>{m=setTimeout(()=>M(void 0),fi)}),x]);if(l?.throwIfAborted(),O)return A=!0,O.access}finally{m!==void 0&&clearTimeout(m),b&&l?.removeEventListener("abort",b),A||y.then(x=>x.close(),()=>{}).catch(x=>console.error("Late workspace handle cleanup failed.",x))}if(a 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). ${a.message}`);await new Promise(x=>setTimeout(x,500))}const c=a instanceof Error?` (${a.message})`:"";throw new Error(`This browser workspace's ${i} is held by another page${c}.`)}async function Ze(r){Qe();const i=await r.getFileHandle(st);v=await X(i,"store");try{if(v.getSize()<T)throw new Error("The committed OPFS workspace pack is incomplete. Stored data was retained.");const a=await r.getFileHandle(Pr);if(z=await X(a,"record of changes"),P=z.getSize(),W){const l=Ft,c=l&&l.generation===I&&l.rangesDigest===W?l:void 0;let u,y;if(c?.metadata){if(u=Or(c.metadata.ranges),y=c.metadata.receiptKey,!/^[a-f0-9]{64}$/u.test(y))throw new Error("The owner's immutable receipt key is invalid.")}else{const b=await(await r.getFileHandle(In)).getFile(),A=new Uint8Array(await b.arrayBuffer());if(await ge(A)!==W)throw new Error("The committed immutable image ranges have changed. Stored data was retained.");u=Or(JSON.parse(nt.decode(A))),y=await ge(je.encode(JSON.stringify(u)))}if(u.bytes>v.getSize())throw new Error("The immutable image reservation is incomplete. Stored data was retained.");const m=c?Be:void 0;m||Be?.port.close(),Be=void 0,D=new is(u,r,`${k}.${I}`,c?.completed,y,m),await D.initialize(),Je=u.image}}catch(a){throw Qe(),a}}function Qe(){D?.close(),D=void 0,Je=void 0;const r=v,i=z;v=void 0,z=void 0,P=0,N=0,H.clear();try{r?.close()}finally{i?.close()}}function _t(r=0,i=!1){const a=z;if(!a)throw new Error("OPFS filesystem worker is not initialized.");const l=a.getSize();if(l<=r){P=l;return}const c=new Uint8Array(l-r);if(a.read(c,{at:r})!==c.byteLength)throw new Error("The OPFS workspace index log could not be read.");const u=v?.getSize()??1/0,y=new DataView(c.buffer);let m=0;const b=c.byteLength;for(;m+Zt<=b;){const A=y.getUint32(m,!0),x=y.getUint32(m+4,!0),O=m+Zt;if(A===0||A>xn||O+A>b)break;const M=c.subarray(O,O+A);if(un(M)!==x)break;let C;try{C=Ri(JSON.parse(nt.decode(M)))}catch{break}if(C.packBytes>u)break;Kr(C,i),m=O+A}m!==b&&!f&&a.truncate(r+m),P=r+m}function Kr(r,i=!1){for(const[a,l]of r.changes){const c=p.get(a);if(l&&Gn(c,l)){Dt(a);continue}i&&(c?.pack?(g-=1,E-=c.length):c&&(R-=c.length),l?.pack?(g+=1,E+=l.length):l&&(R+=l.length)),l===null?(p.delete(a),qr(a)):(p.set(a,l),Dt(a))}T=Math.max(T,r.packBytes)}function pt(){R=0,g=0,E=0;for(const r of p.values())r.pack?(g+=1,E+=r.length):R+=r.length;K=Math.max(0,T-R)}function ur(r){let i=0;for(const a of r.values())a.pack||(i=Math.max(i,a.offset+a.length));return i}const di=5e3;async function li(r){if(!d.navigator.locks)return;if(!k)throw new Error("OPFS filesystem project is not initialized.");const i=new AbortController,a=setTimeout(()=>i.abort(),di);try{await new Promise((l,c)=>{d.navigator.locks.request(`supercode-browser-filesystem-${k}`,{mode:"exclusive",signal:r?AbortSignal.any([r,i.signal]):i.signal},async()=>{clearTimeout(a),l(),await new Promise(u=>{S=u})}).catch(()=>c(r?.aborted?r.reason:new Error("This browser workspace is already open in another tab.")))})}finally{clearTimeout(a)}}function Jr(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 _e(){if(!s)throw new Error("OPFS filesystem worker is not initialized.");return s}async function ye(r,i){return(await(await _e()).getDirectoryHandle(Xt,{create:i})).getDirectoryHandle(r,{create:i})}async function yr(){let r;try{r=await(await _e()).getDirectoryHandle(Xt)}catch(i){if(tt(i))return;throw i}for await(const i of r.entries())throw new Error("OPFS workspace state is missing but stored generations exist. Stored data was retained.")}async function wr(r){const i=await _e();let a;try{a=await i.getDirectoryHandle(Xt)}catch(l){if(tt(l))return;throw l}for await(const[l]of a.entries())l!==r&&await cn(a,l)}function ke(){if(j)throw new Error("This OPFS workspace is closing.");if(Xe)throw new Error("This OPFS workspace is replacing its generation; wait for that operation before writing.");if(o)throw new Error("This store is open for reading; its owner writes it.");if(he)throw he}async function hi(r){yn(r)}let mr=!1,Ct=0,we,gr=!1;function Vr(){if(Ct>0)return;const r=we&&we.generation===I&&we.bytes<=P?we.bytes:0;P-r>Ln&&!mr&&(mr=!0,(f?d.navigator.locks.request(qt,{mode:"exclusive"},async()=>{if(!s||j)return;await Gr();const a=we,l=a&&a.generation===I&&a.bytes<=P?a.bytes:0;P-l>Ln&&await Wt()}):Wt()).catch(a=>console.error("The workspace's log could not be checkpointed; it is replayed at the next open.",a)).finally(()=>{mr=!1})),!f&&!gr&&K>as&&K>R&&(gr=!0,Nt(ki).catch(i=>console.error("The workspace could not be compacted; it keeps its generation.",i)).finally(()=>{gr=!1}))}async function ui(r){ke(),Ct+=1;try{return await r()}finally{Ct-=1,Ct===0&&!j&&s&&Vr()}}function yi(r,i){const a=pe(r.path);if(r.operation==="write"){if(p.get(a)?.type==="directory")throw new Error(`OPFS write target is a directory: ${a}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const c=r.content;if(c.byteLength>ne)throw new Error(`${a} is ${c.byteLength} bytes; an OPFS workspace file holds at most ${ne}.`);Ut(a,c.byteLength),Ce(a,i);const u=jt(c);Z(a,{type:r.symlink?"symlink":"file",mode:r.mode??p.get(a)?.mode??Qt,mtimeMs:r.mtimeMs??Date.now(),offset:u,length:c.byteLength},i);return}if(r.operation==="append"){const c=p.get(a);if(c&&c.type!=="file")throw new Error(`OPFS append target is not a file: ${a}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS append requires file content.");const u=r.content,y=(c?.length??0)+u.byteLength;if(y>ne)throw new Error(`${a} is ${y} bytes; an OPFS workspace file holds at most ${ne}.`);Ut(a,y),Ce(a,i);const m=r.mode??c?.mode??Qt,b=r.mtimeMs??Date.now(),A=c&&!c.pack?c.capacity??c.length:0;if(k!==xe&&c&&!c.pack&&c.length>0&&(y<=A||c.offset+A===T)){Ht(c.offset+c.length,u),Z(a,{...c,mode:m,mtimeMs:b,length:y,capacity:Math.max(A,y)},i),K-=Math.max(c.length,c.capacity??0),Re-=1,ze-=c.length;return}const x=new Uint8Array(y);c&&c.length>0&&x.set(zt(c),0),x.set(u,y-u.byteLength);const O=jt(x),M=Math.min(ne,Math.max(y,y*2,64*1024));M>y&&tn(O+M),Z(a,{type:"file",mode:m,mtimeMs:b,offset:O,length:y,capacity:M},i);return}if(r.operation==="write-at"){const c=p.get(a);if(c&&c.type!=="file")throw new Error(`OPFS write target is not a file: ${a}`);if(!(r.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const u=r.content,y=r.position,m=c?.length??0;if(u.byteLength===0&&c)return;const b=u.byteLength===0?m:Math.max(m,y+u.byteLength);if(b>ne)throw new Error(`${a} is ${b} bytes; an OPFS workspace file holds at most ${ne}.`);Ut(a,b),Ce(a,i);const A=r.mode??c?.mode??Qt,x=r.mtimeMs??Date.now(),O=c&&!c.pack?c.capacity??c.length:0;if(k!==xe&&c&&!c.pack&&m>0&&(b<=O||c.offset+O===T)){if(y>m&&Ht(c.offset+m,new Uint8Array(y-m)),Lt&&y<m){const re=Math.min(m,y+u.byteLength);Lt.push([c.offset+y,$t(c.offset+y,re-y)])}Ht(c.offset+y,u),Z(a,{...c,mode:A,mtimeMs:x,length:b,capacity:Math.max(O,b)},i),b!==m&&(K-=Math.max(c.length,c.capacity??0),Re-=1,ze-=c.length);return}const M=new Uint8Array(b);c&&m>0&&M.set(zt(c),0),u.byteLength>0&&M.set(u,y);const C=jt(M),U=Math.min(ne,Math.max(b,b*2,64*1024));U>b&&tn(C+U),Z(a,{type:"file",mode:A,mtimeMs:x,offset:C,length:b,capacity:U},i);return}if(r.operation==="mkdir"){Ce(a,i);const c=p.get(a);if(c&&c.type!=="directory")throw new Error(`OPFS path is a file: ${a}`);Z(a,{type:"directory",mode:r.mode??c?.mode??ot,mtimeMs:r.mtimeMs??c?.mtimeMs??Date.now(),offset:0,length:0},i);return}if(r.operation==="remove"){Er(a,i),Ae().includes(a)&&Z(a,{type:"directory",mode:ot,mtimeMs:Date.now(),offset:0,length:0},i);return}if(r.operation==="link"){wi(a,Qr(r.source),i);return}if(r.operation==="rename"){mi(a,pe(r.destination),i);return}const l=p.get(a);if(!l)throw new Error(`OPFS metadata target does not exist: ${a}`);Z(a,{...l,mode:r.mode??l.mode,mtimeMs:r.mtimeMs??l.mtimeMs},i)}function Z(r,i,a){const l=p.get(r);se&&!se.has(r)&&se.set(r,l);const c=l!==void 0&&l.type===i.type&&l.offset===i.offset&&l.length===i.length&&l.pack===i.pack;l&&!c&&(Xr(l),l.type!=="directory"&&i.type!=="directory"&&l.length>0&&!l.pack&&(Re+=1,ze+=l.length)),p.set(r,i),Dt(r),c||(i.pack?(g+=1,E+=i.length):R+=i.length),a.push([r,i])}function Dt(r){const i=Ue(r);i!==r&&L.mutable(i).add(r.slice(i.length+1))}function qr(r){const i=Ue(r);L.get(i)?.has(r.slice(i.length+1))&&L.mutable(i).delete(r.slice(i.length+1)),L.delete(r)}function et(){L=new er;for(const r of p.keys())Dt(r)}function pr(r){const i=[],a=l=>{const c=p.get(l);if(!c)return;i.push([l,c]);const u=L.get(l);if(u)for(const y of u)a(`${l}/${y}`)};return a(r),i}function Xr(r,i){if(r.pack){g-=1,E-=r.length;return}R-=r.length,K+=Math.max(r.length,r.capacity??0)}function Zr(r,i){const a=p.get(r);a&&(se&&!se.has(r)&&se.set(r,a),p.delete(r),qr(r),Xr(a),i.push([r,null]))}function wi(r,i,a){const l=e.packages;if(!l)throw new Error("This store has no shared package store to link from.");const c=Qr(i),u=l.descendants(c);if(u.length===0)throw new Error(`The shared package store does not hold ${i}.`);Ce(r,a),Er(r,a),me(p.size+u.length);for(const[y,m]of u){const b=y===c?r:`${r}${y.slice(c.length)}`;Z(b,m.type==="directory"?{type:"directory",mode:m.mode,mtimeMs:m.mtimeMs,offset:0,length:0}:{type:m.type,mode:m.mode,mtimeMs:m.mtimeMs,offset:m.offset,length:m.length,pack:xe},a)}}function Ce(r,i){const a=Ue(r);if(a!==r&&p.get(a)?.type==="directory"){me(p.size+(p.has(r)?0:1));return}const l=[];let c=Et(r)??Ae()[0];if(p.has(c)||l.push(c),r!==c)for(const y of Ar(ln(Ue(r)))){c=`${c}/${y}`;const m=p.get(c);if(m&&m.type!=="directory")throw new Error(`OPFS path parent is a file: ${c}`);m||l.push(c)}me(p.size+l.length+(p.has(r)?0:1));const u=Date.now();for(const y of l)Z(y,{type:"directory",mode:ot,mtimeMs:u,offset:0,length:0},i)}function Er(r,i){for(const[a]of pr(r))Zr(a,i)}function mi(r,i,a){if(r===i)return;if(i.startsWith(`${r}/`))throw new Error("An OPFS rename cannot move a directory into itself.");const l=pr(r);if(l.length===0){if(p.has(i))return;throw new Error(`OPFS rename source does not exist: ${r}`)}Ce(i,a),Er(i,a);for(const[c]of l)Zr(c,a);for(const[c,u]of l)Z(`${i}${c.slice(r.length)}`,u,a);me(p.size)}function Qr(r){if(typeof r!="string"||!r.startsWith(`${Ir}/`)||r.includes("\0")||r.length>4096)throw new Error("Invalid shared store path.");return Ar(r.slice(Ir.length+1)),r}function Ae(){return k===xe?[Ir]:Kn}function Et(r){return Ae().find(i=>r===i||r.startsWith(`${i}/`))}function Ut(r,i){const a=p.get(r),l=a&&!a.pack?a.length:0;if(R-l+i>t)throw new Error(`OPFS workspace exceeds its byte limit: writing ${r} (${i} bytes) would take the project's own files past ${t} bytes.`)}function me(r){if(r>n)throw new Error("OPFS workspace exceeds its entry limit.")}function en(){if(me(p.size),R>t)throw new Error(`OPFS workspace exceeds its byte limit: the project's own files hold ${R} bytes, past ${t}.`)}function Ht(r,i){const a=v;if(!a)throw new Error("OPFS filesystem worker is not initialized.");let l=0;for(;l<i.byteLength;){const c=a.write(i.subarray(l),{at:r+l});if(c<=0)throw new Error("An OPFS workspace file could not be written completely.");l+=c}T=Math.max(T,r+i.byteLength)}function tn(r){const i=v;if(!i)throw new Error("OPFS filesystem worker is not initialized.");r<=T||(i.truncate(r),T=r)}function jt(r){const i=v;if(!i)throw new Error("OPFS filesystem worker is not initialized.");const a=T;let l=0;for(;l<r.byteLength;){const c=i.write(r.subarray(l),{at:a+l});if(c<=0)throw new Error("An OPFS workspace file could not be written completely.");l+=c}return T=a+r.byteLength,a}function gi(r){const i=v;if(i.getSize()>=T&&r.getSize()>=P)return;i.flush(),r.flush();const a=i.getSize(),l=r.getSize();if(!(a>=T&&l>=P))throw Object.assign(new Error(`This browser is keeping less than the tab wrote (the store's pack holds ${a} of ${T} bytes, its log ${l} of ${P}): its storage is full, as a private window's is well below its quota.`),{name:"QuotaExceededError",code:"ENOSPC"})}function pi(r,i={}){const a=z;if(!a||!v)throw new Error("OPFS filesystem worker is not initialized.");if(r.length===0)return;const l=je.encode(JSON.stringify({packBytes:T,changes:r}));if(l.byteLength>xn)throw new Error("An OPFS workspace index record exceeds its size limit.");const c=new Uint8Array(Zt+l.byteLength),u=new DataView(c.buffer);u.setUint32(0,l.byteLength,!0),u.setUint32(4,un(l),!0),c.set(l,Zt);let y=0;for(;y<c.byteLength;){const m=a.write(c.subarray(y),{at:P+y});if(m<=0)throw new Error("The OPFS workspace index log could not be written completely.");y+=m}P+=c.byteLength,gi(a),i.publish!==!1&&vt(),performance.now()-ee>=vn?Me():q===void 0&&(q=setTimeout(Me,vn))}function Me(){if(q!==void 0&&(clearTimeout(q),q=void 0),he)throw he;const r=performance.now();v?.flush(),z?.flush(),ee=performance.now(),Ne+=1,Se+=ee-r}function Wt(){const r=jr,i=Nt(()=>r.catch(()=>{}).then(Ei));return jr=i,i}async function Ei(){if(ke(),!I)return;const r=I,i=z,a=await ye(r,!1);if(!i||i!==z||r!==I)throw new Error("OPFS workspace changed generations before its checkpoint could start.");Me();const l=P;if(await St(a,p,{access:i,bytes:l,packBytes:T}),r===I&&(we={generation:r,bytes:l}),i===z&&r===I&&l===P){mt();try{i.truncate(0),i.flush(),P=0,we={generation:r,bytes:0}}finally{gt()}}}function rn(r){return Rt(()=>bi(br(r)))}async function bi(r){const i=crypto.randomUUID(),a=await ye(i,!0),l=await a.getFileHandle(st,{create:!0}),c=await X(l,"store"),u=new Map;let y=0;try{for(const b of r.files){let A=0,x=0;if(b.type!=="directory"){const O=new Uint8Array(r.pack,b.offset??0,b.length??0);A=y,x=O.byteLength;let M=0;for(;M<x;){const C=c.write(O.subarray(M),{at:A+M});if(C<=0)throw new Error("An OPFS workspace file could not be written completely.");M+=C}y+=x}u.set(b.path,{type:b.type,mode:b.mode??(b.type==="directory"?ot:Qt),mtimeMs:b.mtimeMs??Date.now(),offset:A,length:x})}for(const b of Ae())u.has(b)||u.set(b,{type:"directory",mode:ot,mtimeMs:Date.now(),offset:0,length:0});me(u.size),c.truncate(y),c.flush()}finally{c.close()}const m=await St(a,u);await Yt(i,a,u,y,m)}async function Si(){await nn(()=>!0)}async function ki(){let r=!1,i=!1,a=!1;try{await Ai(()=>{r=!0},()=>{i=!0},()=>{a=!0})}finally{r&&(i||a)?gt():r&&Bt()}}async function Ai(r,i,a){const l=crypto.randomUUID(),c=await ye(l,!0),u=await X(await c.getFileHandle(st,{create:!0}),"store");let y,m=!1;try{y=await X(await c.getFileHandle(Pr,{create:!0}),"record of changes"),y.truncate(0);const b=new Uint8Array(Bn);let A=0;const x=$=>{if($.pack)return{...$};if($.type==="directory"||$.length===0)return{...$,offset:0,length:0};const J=v;if(!J)throw new Error("OPFS filesystem worker is not initialized.");const He=A;let oe=0;for(;oe<$.length;){const kt=Math.min(b.byteLength,$.length-oe),gn=b.subarray(0,kt);if(D?.ensure($.offset+oe,kt),J.read(gn,{at:$.offset+oe})!==kt)throw new Error("An OPFS workspace file could not be read completely.");let Vt=0;for(;Vt<kt;){const pn=u.write(gn.subarray(Vt),{at:He+oe+Vt});if(pn<=0)throw new Error("An OPFS workspace file could not be written completely.");Vt+=pn}oe+=kt}A+=$.length;const{capacity:Mr,..._i}=$;return{..._i,offset:He}},O=new Map;let M=performance.now();for(const[$,J]of[...p]){if(j||Xe)return;p.get($)===J&&(O.set(J,x(J)),performance.now()-M>8&&(await new Promise(He=>setTimeout(He,0)),M=performance.now()))}if(j||Xe||!v||!z)return;mt(),r();const C=new Map;for(const[$,J]of p)C.set($,O.get(J)??x(J));u.truncate(A),u.flush(),y.flush(),Me();const U={pack:v,log:z};v=u,z=y,P=0,p=C,et(),T=A,I=l,w=c,pt(),m=!0;const re=new Map(C);try{U.pack.close()}finally{U.log.close()}try{await St(c,re);const $={storageVersion:4,generation:l,initializedAt:Date.now()};await bt(await _e(),it,$)}catch($){throw he=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:$}),he}i(),await wr(l)}finally{if(!m){a();try{u.close()}finally{y?.close()}await cn(await(await _e()).getDirectoryHandle(Xt),l)}}}async function Mi(r){ke(),mt();try{await Oi(r)}finally{gt()}}async function Oi(r){let i=!1;for(const[a,l]of p){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 ${a}.`);c!==l.offset&&(p.set(a,{...l,offset:c}),i=!0)}i&&await Wt()}function nn(r){return Rt(()=>Ii(r))}async function Ii(r){const i=v;if(!i)throw new Error("OPFS filesystem worker is not initialized.");const a=new Map,l=crypto.randomUUID(),c=await ye(l,!0),u=await c.getFileHandle(st,{create:!0}),y=await X(u,"store"),m=new Map,b=new Uint8Array(Bn);let A=0;try{for(const[O,M]of p){if(!r(O,M))continue;if(M.pack){m.set(O,{...M});continue}if(M.type==="directory"||M.length===0){m.set(O,{...M,offset:0,length:0});continue}const C=A;a.set(M.offset,C);let U=0;for(;U<M.length;){const J=Math.min(b.byteLength,M.length-U),He=b.subarray(0,J);if(D?.ensure(M.offset+U,J),i.read(He,{at:M.offset+U})!==J)throw new Error("An OPFS workspace file could not be read completely.");let oe=0;for(;oe<J;){const Mr=y.write(He.subarray(oe),{at:C+U+oe});if(Mr<=0)throw new Error("An OPFS workspace file could not be written completely.");oe+=Mr}U+=J}A+=M.length;const{capacity:re,...$}=M;m.set(O,{...$,offset:C,length:M.length})}y.truncate(A),y.flush()}finally{y.close()}const x=await St(c,m);return await Yt(l,c,m,A,x),a}async function Yt(r,i,a,l,c,u){mt();try{await Pi(r,i,a,l,c,u)}finally{gt()}}async function Pi(r,i,a,l,c,u){const y=await i.getFileHandle(Pr,{create:!0}),m=await X(y,"record of changes");try{m.truncate(0),m.flush()}finally{m.close()}const b={storageVersion:u?5:4,generation:r,initializedAt:Date.now(),...u?{imageRanges:u}:{}};if(await bt(await _e(),it,b),Qe(),I=r,de=b.initializedAt,W=u,c){const A=new Pe(c.index);p=new Ye(A),L=new It(A),te=void 0}else p=a,et();T=l,w=i,await Ze(i),c?({liveBytes:R,linked:g,linkedBytes:E}=c,K=Math.max(0,T-R)):pt(),f||await wr(r)}async function xi(r,i,a,l,c=!1){if(ke(),!f||k!==xe)throw new Error("Only the shared package store can reserve immutable image extents.");if(T!==0||[...p.values()].some(O=>O.type!=="directory"))return!1;const u=Or(l);if(u.bytes!==r.packBytes||r.entries>xr||r.liveBytes>r.packBytes||i.byteLength!==r.json.raw||a.byteLength!==r.binary.raw||!await Kt(i,r.json.sha256,c)||!await Kt(a,r.binary.sha256,c))throw new Error("The image's prepared metadata does not match its document.");const y=i.subarray(0,4096).indexOf(10);if(y<0)throw new Error("The prepared index has no bounded retained header.");const m=JSON.parse(`${nt.decode(i.subarray(0,y-1))}}`),b={packBytes:r.packBytes,liveBytes:r.liveBytes,linked:0,linkedBytes:0},A=m.retainedIndex;if(A.version!==1||A.digest!==await sn(r.binary.sha256,b)||A.packBytes!==b.packBytes||A.liveBytes!==b.liveBytes||A.linked!==0||A.linkedBytes!==0)throw new Error("The prepared index's retained measures are inconsistent.");const x=new SharedArrayBuffer(a.byteLength);if(new Uint8Array(x).set(a),new Pe(x).entryCount!==r.entries)throw new Error("The prepared index has the wrong number of entries.");return Rt(async()=>{const O=crypto.randomUUID(),M=await ye(O,!0),C=await M.getFileHandle(st,{create:!0}),U=await X(C,"immutable image reservation");try{U.truncate(r.packBytes),U.flush()}finally{U.close()}const re=je.encode(JSON.stringify(u));return await Oe(M,In,re),await Oe(M,Gt,a),await Oe(M,ce,i),await Yt(O,M,new Map,r.packBytes,{index:x,...b},await ge(re)),!0})}async function Ti(r,i,a,l=!1,c){if(ke(),f||!e.packages||!c&&!e.packages.deferredImage)throw new Error("Prepared project paths require a verified shared image.");if(T!==0||[...p.values()].some(A=>A.type!=="directory"))return!1;if(i.byteLength!==r.json.raw||a.byteLength!==r.binary.raw||!await Kt(i,r.json.sha256,l)||!await Kt(a,r.binary.sha256,l))throw new Error("The image's prepared project does not match its descriptor.");const u=i.subarray(0,4096).indexOf(10);if(u<0)throw new Error("The prepared project has no bounded retained header.");const y=JSON.parse(`${nt.decode(i.subarray(0,u-1))}}`).retainedIndex,m={packBytes:0,liveBytes:0,linked:r.linked,linkedBytes:r.linkedBytes};if(y.version!==1||y.digest!==await sn(r.binary.sha256,m)||y.packBytes!==0||y.liveBytes!==0||y.linked!==r.linked||y.linkedBytes!==r.linkedBytes)throw new Error("The prepared project's retained measures are inconsistent.");const b=new SharedArrayBuffer(a.byteLength);if(new Uint8Array(b).set(a),new Pe(b).entryCount!==r.entries||r.entries>n)throw new Error("The prepared project has invalid entry bounds.");return Rt(async()=>{const A=crypto.randomUUID(),x=await ye(A,!0),O=await x.getFileHandle(st,{create:!0}),M=await X(O,"prepared project");try{M.truncate(0),M.flush()}finally{M.close()}if(await Oe(x,Gt,a),await Oe(x,ce,i),c&&!await c)return!1;if(!e.packages?.deferredImage)throw new Error("Prepared project paths require a verified shared image.");return await Yt(A,x,new Map,0,{index:b,...m}),!0})}async function Fi(){if(j)throw new Error("This OPFS workspace is closing.");if(!v)throw new Error("OPFS filesystem worker is not initialized.");const r=[],i=[...p.keys()].sort((y,m)=>hn(y)-hn(m)||(y<m?-1:1));let a=0;for(const y of p.values())y.type!=="directory"&&(a+=y.length);const l=new ArrayBuffer(a),c=new Uint8Array(l);let u=0;for(const y of i){const m=p.get(y);if(m.type==="directory"){r.push({path:y,type:"directory",mode:m.mode,mtimeMs:m.mtimeMs});continue}m.length>0&&c.set(zt(m),u),r.push({path:y,type:m.type,offset:u,length:m.length,mode:m.mode,mtimeMs:m.mtimeMs}),u+=m.length}for(const y of[...Ae()].reverse())p.has(y)||r.unshift({path:y,type:"directory",mode:ot,mtimeMs:Date.now()});return br({files:r,pack:l})}async function bt(r,i,a){await Oe(r,i,je.encode(JSON.stringify(a)))}async function Oe(r,i,a){const l=await(await _e()).getDirectoryHandle(Pn,{create:!0}),c=crypto.randomUUID(),u=await l.getFileHandle(c,{create:!0}),y=await X(u,"index");try{let m=0;for(;m<a.byteLength;){const b=y.write(a.subarray(m),{at:m});if(b<=0)throw new Error("An OPFS workspace file could not be written completely.");m+=b}y.truncate(a.byteLength),y.flush()}finally{y.close()}try{await u.move(r,i)}finally{await an(l,c,!1)}}const Gt="index.shared";async function ge(r){const i=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(i),a=>a.toString(16).padStart(2,"0")).join("")}async function Kt(r,i,a){return a||await ge(r)===i}function sn(r,i){const{packBytes:a,liveBytes:l,linked:c,linkedBytes:u,journalPrefix:y}=i;return ge(je.encode(`${JSON.stringify({packBytes:a,liveBytes:l,linked:c,linkedBytes:u,...y?{journalPrefix:y}:{}})}:${r}`))}async function on(r,i){const{packBytes:a,liveBytes:l,linked:c,linkedBytes:u,journalPrefix:y}=i;return ge(je.encode(`${JSON.stringify({packBytes:a,liveBytes:l,linked:c,linkedBytes:u,...y?{journalPrefix:y}:{}})}:${await ge(r)}`))}async function St(r,i,a){const l=Ni(i);if(typeof SharedArrayBuffer>"u"||i.size<1e4){await bt(r,ce,l);return}const c=new Map(l.entries),u=new Map,y={packBytes:a?.packBytes??0,liveBytes:0,linked:0,linkedBytes:0};for(const[C,U]of c){const re=Ue(C);if(re!==C){let $=u.get(re);$||($=new Set,u.set(re,$)),$.add(C.slice(re.length+1))}U.pack?(y.linked+=1,y.linkedBytes+=U.length):(y.liveBytes+=U.length,y.packBytes=Math.max(y.packBytes,U.offset+U.length))}let m;try{m=Sn(c,u)}catch{await bt(r,ce,l);return}const b=JSON.stringify(l.entries),A=a?new Uint8Array(a.bytes):void 0;if(A&&a.access.read(A,{at:0})!==A.byteLength)throw new Error("The checkpoint's journal prefix could not be read completely.");const x=A?{bytes:A.byteLength,digest:await ge(A)}:void 0,O=new Uint8Array(m).slice(),M={version:x?2:1,digest:await on(O,{...y,...x?{journalPrefix:x}:{}}),...y,...x?{journalPrefix:x}:{}};try{await Oe(r,Gt,O)}catch{await bt(r,ce,{entries:JSON.parse(b)});return}return await Oe(r,ce,je.encode(`{"retainedIndex":${JSON.stringify(M)},
|
|
2
|
-
"entries":${b}}`)),{index:m,...y}}async function Li(r){if(!(typeof SharedArrayBuffer>"u"))try{const i=await r.getFileHandle(ce),a=await X(i,"index");let l;try{const O=new Uint8Array(Math.min(512,a.getSize())),M=a.read(O,{at:0});l=nt.decode(O.subarray(0,M))}finally{a.close()}const c=l.split(`
|
|
3
|
-
`,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 y=await r.getFileHandle(Gt),m=await X(y,"index");let b;try{const O=m.getSize();if(O>256*1024*1024||(b=new Uint8Array(O),m.read(b,{at:0})!==O))return}finally{m.close()}if(await on(b,u)!==u.digest)return;const A=new SharedArrayBuffer(b.byteLength);new Uint8Array(A).set(b);const x=new Pe(A);return me(x.entryCount),{...u,index:A}}catch{return}}async function vi(r){const i=r.journalPrefix;if(!i||!z||!v||i.bytes>z.getSize()||r.packBytes>v.getSize())return 0;const a=new Uint8Array(i.bytes);return z.read(a,{at:0})!==a.byteLength?0:await ge(a)===i.digest?i.bytes:0}async function De(r,i){let a;try{a=await r.getFileHandle(i)}catch(u){if(tt(u))return;throw u}let l;if(o){l=await(await a.getFile()).text();try{return JSON.parse(l)}catch(u){throw new Error(`Invalid OPFS workspace metadata (${i}). Stored data was retained.`,{cause:u})}}const c=await X(a,"index");try{const u=c.getSize(),y=new Uint8Array(u);if(u>0&&c.read(y,{at:0})!==u)throw new Error("An OPFS workspace file could not be read completely.");l=nt.decode(y)}finally{c.close()}try{return JSON.parse(l)}catch(u){throw new Error(`Invalid OPFS workspace metadata (${i}). Stored data was retained.`,{cause:u})}}async function an(r,i,a){try{await r.removeEntry(i,{recursive:a})}catch(l){if(!tt(l))throw l}}async function cn(r,i){try{await r.removeEntry(i,{recursive:!0})}catch{}}function fn(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(pe(r.path),r.operation==="rename"&&pe(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 Sr(r),r}function Bi(r){if(!Array.isArray(r)||r.length===0||r.length>128)throw new Error("Invalid OPFS filesystem mutation batch.");return r.map(i=>fn(i))}function br(r){if(!r||!Array.isArray(r.files)||r.files.length>n||!(r.pack instanceof ArrayBuffer))throw new Error("Invalid OPFS workspace snapshot.");const i=new Set,a=new Map(Ae().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(pe(c.path),c.type!=="file"&&c.type!=="directory"&&c.type!=="symlink"||i.has(c.path))throw new Error("Invalid or duplicate OPFS workspace entry.");if(i.add(c.path),a.set(c.path,c.type),Ae().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,y=c.length??0;if(!Number.isSafeInteger(u)||!Number.isSafeInteger(y)||u<0||y<0||y>ne||u+y>r.pack.byteLength)throw new Error("Invalid OPFS workspace file.");if(l+=y,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.");Sr(c)}me(a.size);for(const c of r.files)if(!Ae().includes(c.path)&&a.get(Ue(c.path))!=="directory")throw new Error(`An OPFS workspace snapshot has no directory parent for ${c.path}.`);return r}function Sr(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 Ni(r){return{entries:[...r]}}function kr(r){const i=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 a=r.entries;me(a.length);for(const l of a){if(!Array.isArray(l)||l.length!==2)throw new Error("Invalid OPFS workspace index entry.");const c=pe(l[0]);if(i.has(c))throw new Error("Duplicate OPFS workspace index entry.");i.set(c,dn(l[1]))}return i}function dn(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid OPFS workspace index entry.");const i=r;if(i.type!=="file"&&i.type!=="directory"&&i.type!=="symlink")throw new Error("Invalid OPFS workspace index entry.");if(Sr(i),i.mode===void 0||i.mtimeMs===void 0)throw new Error("Invalid OPFS workspace index entry.");if(!Number.isSafeInteger(i.offset)||i.offset<0||!Number.isSafeInteger(i.length)||i.length<0||i.length>ne)throw new Error("Invalid OPFS workspace index extent.");if(i.pack!==void 0&&i.pack!==xe)throw new Error("Invalid OPFS workspace index entry.");return{type:i.type,mode:i.mode,mtimeMs:i.mtimeMs,offset:i.offset,length:i.length,...i.pack?{pack:i.pack}:{}}}function Ri(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid OPFS workspace index record.");const i=r;if(!Number.isSafeInteger(i.packBytes)||i.packBytes<0||!Array.isArray(i.changes))throw new Error("Invalid OPFS workspace index record.");const a=[];for(const l of i.changes){if(!Array.isArray(l)||l.length!==2)throw new Error("Invalid OPFS workspace index record.");a.push([pe(l[0]),l[1]===null?null:dn(l[1])])}return{packBytes:i.packBytes,changes:a}}function Jt(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 i=r;if(i.storageVersion!==4&&i.storageVersion!==5||i.storageVersion===5&&(typeof i.imageRanges!="string"||!/^[a-f0-9]{64}$/u.test(i.imageRanges))||i.storageVersion===4&&i.imageRanges!==void 0||typeof i.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(i.generation)||typeof i.initializedAt!="number"||!Number.isFinite(i.initializedAt))throw new Error("Invalid or unsupported OPFS workspace state. Stored data was retained.");return i}function pe(r){if(typeof r!="string"||Et(r)===void 0||r.includes("\0")||r.length>4096)throw new Error("Invalid OPFS workspace path.");return ln(r),r}function ln(r){const i=Et(r);if(i===void 0)throw new Error("Invalid OPFS workspace path.");const a=r===i?"":r.slice(i.length+1);return Ar(a),a}function Ar(r){const i=r===""?[]:r.split("/");if(i.some(a=>!a||a==="."||a===".."||a.includes("\0")))throw new Error("Invalid OPFS workspace path segment.");return i}function Ue(r){const i=r.slice(0,r.lastIndexOf("/"));return i===""||Et(i)===void 0?Et(r)??r:i}function hn(r){let i=1;for(let a=0;a<r.length;a+=1)r.charCodeAt(a)===47&&(i+=1);return i}function tt(r){return r instanceof DOMException&&r.name==="NotFoundError"}function un(r){let i=2166136261;for(let a=0;a<r.byteLength;a+=1)i^=r[a],i=Math.imul(i,16777619);return i>>>0}typeof addEventListener=="function"&&addEventListener("close",()=>{v?.flush(),z?.flush(),Qe(),S?.()});function yn(r,i={}){if(ke(),se)throw new Error("An OPFS mutation batch cannot be nested.");for(const a of r)fn(a);return r.length?wn(a=>{for(const l of r)yi(l,a)},i):[]}function zi(r,i,a={}){if(ke(),se)throw new Error("An OPFS mutation batch cannot be nested.");for(const l of i){if(pe(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 i.length?wn(l=>{const c=r.byteLength>0?jt(r):T;for(const u of i){const y=pe(u.path);Ce(y,l);const m=p.get(y);if(u.type==="directory"){if(m&&m.type!=="directory")throw new Error(`OPFS path is a file: ${y}`);Z(y,{type:"directory",mode:u.mode,mtimeMs:u.mtimeMs,offset:0,length:0},l);continue}if(m?.type==="directory")throw new Error(`OPFS write target is a directory: ${y}`);Ut(y,u.length),Z(y,{type:u.type,mode:u.mode,mtimeMs:u.mtimeMs,offset:c+u.offset,length:u.length},l)}},a):[]}function wn(r,i){if(!v||!z)throw new Error("OPFS filesystem worker is not initialized.");const a={packBytes:T,logBytes:P,liveBytes:R,deadBytes:K,rewrites:Re,rewrittenBytes:ze,linked:g,linkedBytes:E},l=new Map;se=l;const c=[];Lt=c;const u=[];try{return r(u),en(),pi(u,{publish:!i.durable}),i.durable&&(Me(),vt()),Vr(),u}catch(y){const m=Y!==void 0&&!ue&&Atomics.load(Y,Fn)!==a.logBytes;m&&mt();for(const[b,A]of l)A===void 0?p.delete(b):p.set(b,A);et();try{for(let b=c.length-1;b>=0;b-=1)Ht(c[b][0],c[b][1])}catch(b){y=new AggregateError([y,b],"OPFS could not restore bytes a failed batch wrote over.")}({packBytes:T,logBytes:P,liveBytes:R,deadBytes:K,rewrites:Re,rewrittenBytes:ze,linked:g,linkedBytes:E}=a),q!==void 0&&(clearTimeout(q),q=void 0);try{z.truncate(P),z.flush(),v.truncate(T),v.flush()}catch(b){throw Bt(),he=new AggregateError([y,b],"OPFS could not roll back a failed batch; reopen this workspace before writing again."),he}throw m&>(),y}finally{se=void 0,Lt=void 0}}function $i(){if(Ve){wt?.abort(new DOMException("The workspace was closed while opening.","AbortError"));return}j||(j=!0,qe===0&&mn())}function mn(){Bt();try{Me()}finally{try{Qe()}finally{const r=S;S=void 0,s=void 0;try{r?.()}finally{e.ownsPackages&&e.packages?.close()}}}}return{initialize:oi,opened:()=>s!==void 0&&!j,stats:()=>({entries:p.size,liveBytes:R,deadBytes:K,packBytes:T,rewrites:Re,rewrittenBytes:ze,linked:g,linkedBytes:E,flushes:Ne,flushMs:Se}),applyNow:yn,applyExtentsNow:zi,close:$i,readExtent:$t,descendants:pr,retain:nn,remapLinks:Mi,childrenOf:r=>[...L.get(r)??[]].sort(),refresh:ai,follow:ni,clock:Wr,readerSeed:Qn,imageCompletionSeed:ei,imageLine:()=>D?.lineForReader()??e.packages?.imageLine(),imageStartupSet:()=>D?.readDigests()??D?.completedDigests()??[],prefetchImage:(r,i)=>D?.prefetch(r,i)??{queued:0,done:Promise.resolve()},imageBlockedReads:()=>{const r=D?.blockedReads??{ranges:0,ms:0},i=e.packages?.imageBlockedReads()??{ranges:0,ms:0};return{ranges:r.ranges+i.ranges,ms:r.ms+i.ms}},seeded:()=>Yr,get logBytes(){return P},checkpoint:Wt,deferMaintenance:ui,installPreparedImage:xi,installPreparedProject:Ti,get deferredImage(){return Je},get imagePlacedAt(){return s&&W?de:void 0},get entries(){return p},get packBytes(){return T},read:ii,readRange:si,snapshot:Fi,replace:rn,apply:hi,flush:()=>{if(j||!s)throw new Error("This OPFS workspace is not open.");if(Xe)throw new Error("Wait for the OPFS generation replacement before flushing it.");Me()},validateSnapshot:br,validateMutationBatch:Bi}}async function cs(d,e,t,n){const s=Rr(d);await s.initialize(xe,{readOnly:!0,extentsOnly:!0});const f=Rr(d,{packages:s,ownsPackages:!0});let o;try{o=await f.initialize(e,{readOnly:!0,...t?{seed:t}:{}})}catch(h){throw f.close(),s.close(),h}if(!o&&!f.opened()){s.close();return}return f}const fs="sweep.json";async function ds(d){const t=await(await d.getFileHandle(fs,{create:!0})).createWritable();await t.write(JSON.stringify({at:Date.now()})),await t.close()}class er{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)}}class ar extends Map{names=new Map;static rooted(){const e=new ar;return e.set("/",ws()),e}set(e,t){if(!this.has(e)&&e!=="/"){const n=Te(e);let s=this.names.get(n);s||(s=new Set,this.names.set(n,s)),s.add(e.slice(n==="/"?1:n.length+1))}return super.set(e,t)}delete(e){if(!super.delete(e))return!1;const t=Te(e),n=this.names.get(t);return n?.delete(e.slice(t==="/"?1:t.length+1)),n?.size===0&&this.names.delete(t),!0}clear(){super.clear(),this.names.clear()}namesIn(e){return[...this.names.get(e)??[]]}subtree(e){const t=[],n=[e];for(;n.length>0;){const s=n.shift(),f=this.get(s);if(f){t.push([s,f]);for(const o of this.names.get(s)??[])n.push(s==="/"?`/${o}`:`${s}/${o}`)}}return t}}class Le{nodes=ar.rooted();lower;rangeBlocks=new Map;rangeBlockBytes=0;hidden=new Set;nextInode=2;mutationDepth=0;mutated=!1;mutationHandler;changedPaths;static fromSnapshot(e){const t=new Le;return t.replaceSnapshot(e),t}static fromStore(e,t){const n=new Le;return n.lower=e,n.mutate(()=>{const s=t.files.filter(f=>{const o=f,h=_(o.path);if(h==="/")return!1;if(o.content!==void 0)return!0;const w=e.entries.get(h);return!w||o.type==="directory"!=(w.type==="directory")?!0:o.mode!==void 0&&o.mode!==(w.mode&4095)||o.mtimeMs!==void 0&&o.mtimeMs!==w.mtimeMs});for(const f of s.sort((o,h)=>tr(o.path)-tr(h.path))){const o=f,h=_(o.path);if(o.type==="directory")n.node(h)||n.mkdirSync(h,{recursive:!0});else if(o.content!==void 0)n.writeFileSync(h,at(o.content));else if(!n.node(h))continue;const w=n.node(h);w&&(o.mode!==void 0&&(w.mode=o.mode),o.mtimeMs!==void 0&&(w.atimeMs=w.mtimeMs=o.mtimeMs))}n.mutated=!1}),n}node(e){const t=this.nodes.get(e);if(t||!this.lower||e==="/")return t;if(this.isHidden(e))return;const n=this.lower.entries.get(e);if(!n)return;const s=this.lowerNode(e,n);return this.nodes.set(e,s),s}lowerNode(e,t){const n=this.lower;return t.type==="directory"?{type:"directory",fromStore:!0,mode:t.mode&4095,atimeMs:t.mtimeMs,mtimeMs:t.mtimeMs,ino:this.nextInode++}:{type:"file",fromStore:!0,load:()=>n.view?n.view(e):n.read(e),...n.readRange&&t.length>=ls&&n.readsByRange?.(e)?{range:(s,f)=>this.readBlocks(e,t.length,s,f,(o,h)=>n.readRange(e,o,h))}:{},size:t.length,mode:t.mode&4095,atimeMs:t.mtimeMs,mtimeMs:t.mtimeMs,ino:this.nextInode++}}readBlocks(e,t,n,s,f){const o=Math.min(Math.max(0,n),t),h=Math.min(t,o+Math.max(0,s));if(h<=o)return new Uint8Array(0);if(h-o>us)return f(o,h-o);const w=Math.floor(o/At),g=Math.floor((h-1)/At),E=new Uint8Array(h-o);for(let S=w;S<=g;S+=1){const k=`${S}:${e}`;let I=this.rangeBlocks.get(k);if(I)this.rangeBlocks.delete(k);else for(I=f(S*At,At),this.rangeBlockBytes+=I.byteLength;this.rangeBlockBytes>hs&&this.rangeBlocks.size>0;){const[W,D]=this.rangeBlocks.entries().next().value;this.rangeBlocks.delete(W),this.rangeBlockBytes-=D.byteLength}this.rangeBlocks.set(k,I);const p=S*At,L=Math.max(o,p),v=Math.min(h,p+I.byteLength);v>L&&E.set(I.subarray(L-p,v-p),L-o)}return E}toStoreOverlaySnapshot(){if(!this.lower||this.hidden.size>0)return this.toSnapshot();const e=this.lower;return{files:[...this.nodes.entries()].filter(([n,s])=>{if(n==="/")return!1;const f=e.entries.get(n);return!(s.fromStore&&!s.dirty&&f&&s.mode===(f.mode&4095)&&s.mtimeMs===f.mtimeMs)}).map(([n,s])=>s.type==="directory"?{path:n,type:"directory",mode:s.mode,mtimeMs:s.mtimeMs}:s.load&&!s.dirty?this.sized(n,s):{path:n,type:"file",content:Fe(s.content??new Uint8Array),mode:s.mode,mtimeMs:s.mtimeMs})}}isHidden(e){if(this.hidden.size===0)return!1;for(let t=e;t!=="/";t=Te(t))if(this.hidden.has(t))return!0;return!1}hide(e){this.lower?.entries.has(e)&&this.hidden.add(e)}unhide(e){if(!(!this.lower||!this.isHidden(e))){this.hidden.delete(e);for(const t of this.lower.childrenOf(e))this.hidden.add(e==="/"?`/${t}`:`${e}/${t}`)}}everyNode(){const e=[...this.nodes.entries()];if(!this.lower)return e;for(const[t,n]of this.lower.entries)t==="/"||this.nodes.has(t)||this.isHidden(t)||e.push([t,this.lowerNode(t,n)]);return e}setMutationHandler(e){this.mutationHandler=e,this.changedPaths=e?new Set:void 0}takeChangedPaths(){const e=this.changedPaths??new Set;return this.changedPaths=this.changedPaths?new Set:void 0,e}dropChangedPaths(e){if(this.changedPaths)for(const t of e)this.changedPaths.delete(_(t))}writtenEntry(e,t=!1){const n=_(e),s=this.node(n);if(!s)return;const f={mode:s.mode,mtimeMs:s.mtimeMs};return s.type==="directory"?{path:n,type:"directory",...f}:t?{path:n,type:"file",bytes:this.bytesOf(s).slice(),...f}:{path:n,type:"file",content:Fe(this.bytesOf(s)),...f}}replaceSnapshot(e){this.mutate(()=>{const t=new Map(this.everyNode());this.lower=void 0,this.hidden.clear(),this.nodes=ar.rooted();for(const s of t.keys())this.markMutation(s);this.markMutation("/");const n=e.files.slice().sort((s,f)=>tr(s.path)-tr(f.path));for(const s of n){const f=s,o=_(f.path);if(o!=="/")if(f.type==="directory")this.mkdirSync(o,{recursive:!0});else if(f.content!==void 0){this.writeFileSync(o,at(f.content));const w=this.nodes.get(o);w&&(w.dirty=!1)}else{const w=t.get(o);this.mkdirSync(Te(o),{recursive:!0}),w?.type==="file"&&this.nodes.set(o,w)}const h=this.node(o);h&&(f.mode!==void 0&&(h.mode=f.mode),f.mtimeMs!==void 0&&(h.atimeMs=h.mtimeMs=f.mtimeMs),this.markMutation(o))}})}toSnapshot(){return{files:[...this.nodes.entries()].map(([e,t])=>t.type==="directory"?{path:e,type:"directory",mode:t.mode,mtimeMs:t.mtimeMs}:t.load&&!t.dirty?this.sized(e,t):{path:e,type:"file",content:Fe(t.content??new Uint8Array),mode:t.mode,mtimeMs:t.mtimeMs}).concat(this.untouchedStoreEntries())}}untouchedStoreEntries(){const e=[];if(!this.lower)return e;for(const[t,n]of this.lower.entries)t==="/"||this.nodes.has(t)||this.isHidden(t)||e.push(n.type==="directory"?{path:t,type:"directory",mode:n.mode&4095,mtimeMs:n.mtimeMs}:{path:t,type:"file",size:n.length,mode:n.mode&4095,mtimeMs:n.mtimeMs});return e}toWrittenSnapshot(){return{files:[...this.nodes.entries()].map(([e,t])=>t.type==="directory"?{path:e,type:"directory",mode:t.mode,mtimeMs:t.mtimeMs}:t.dirty?{path:e,type:"file",content:Fe(t.content??new Uint8Array),mode:t.mode,mtimeMs:t.mtimeMs}:this.sized(e,t)).concat(this.untouchedStoreEntries())}}sized(e,t){return{path:e,type:"file",size:t.content?.byteLength??t.size??0,mode:t.mode,mtimeMs:t.mtimeMs}}existsSync(e){return this.node(_(e))!==void 0}statSync(e){const t=_(e),n=this.node(t);if(!n)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);const s=n.content?.byteLength??n.size??0;return{isFile:()=>n.type==="file",isDirectory:()=>n.type==="directory",size:s,mode:n.mode,mtimeMs:n.mtimeMs,atimeMs:n.atimeMs,ctimeMs:n.mtimeMs,nlink:1,uid:1e3,gid:1e3,dev:1,ino:n.ino,rdev:0,blksize:4096,blocks:Math.ceil(s/512)}}lstatSync(e){return this.statSync(e)}async readFile(e){return this.readFileSync(e)}readFileSync(e){const t=_(e),n=this.node(t);if(!n)throw new Error(`ENOENT: no such file, open '${t}'`);if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return this.bytesOf(n).slice()}linkTargetSync(e,t,n,s,f=!1){const o=this.node(f?e:_(e));if(o?.type==="file"){if(o.link===void 0){const h=o.content?.byteLength??o.size??0;o.link=h<t||h>n?null:s(this.bytesOf(o))??null}return o.link??void 0}}bytesOf(e){return e.content===void 0&&e.load&&(e.content=e.load(),e.size=e.content.byteLength),e.content??new Uint8Array}viewRangeSync(e,t,n){const s=this.node(_(e));if(!s)throw new Error(`ENOENT: no such file, open '${_(e)}'`);if(s.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${_(e)}'`);return s.range&&s.content===void 0?s.range(t,n):this.bytesOf(s).subarray(t,t+n)}readRangeSync(e,t,n){const s=_(e),f=this.node(s);if(!f)throw new Error(`ENOENT: no such file, open '${s}'`);if(f.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${s}'`);return f.range&&f.content===void 0?f.range(t,n):this.bytesOf(f).slice(t,t+n)}writeRangeSync(e,t,n){this.mutate(()=>{const s=_(e);this.mkdirSync(Te(s),{recursive:!0});const f=this.isHidden(s);this.unhide(s);const o=f?this.nodes.get(s):this.node(s);if(o?.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${s}'`);const h=o?this.bytesOf(o):new Uint8Array,w=t+n.byteLength;let g;if(w<=h.byteLength)g=o?.dirty?h:h.slice();else if(w<=h.buffer.byteLength-h.byteOffset&&o?.dirty)g=new Uint8Array(h.buffer,h.byteOffset,w),g.fill(0,h.byteLength,t);else{const E=this.takeSpare(w);g=new Uint8Array(E??new ArrayBuffer(Math.max(w,h.byteLength*2,4096)),0,w),g.set(h),E&&g.fill(0,h.byteLength,t),o?.dirty&&this.release(h)}g.set(n,t),this.nodes.set(s,{type:"file",content:g,dirty:!0,mode:o?.type==="file"?o.mode:420,atimeMs:Ee(),mtimeMs:Ee(),ino:o?.type==="file"?o.ino:this.nextInode++}),this.markMutation(s)})}truncateSync(e,t){this.mutate(()=>{const n=_(e),s=this.node(n);if(!s)throw new Error(`ENOENT: no such file, truncate '${n}'`);if(s.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, truncate '${n}'`);let f;if(t===0&&s.content===void 0)f=new Uint8Array;else{const o=this.bytesOf(s),h=o.buffer.byteLength-o.byteOffset;s.dirty&&t<=h&&(h<=Tr||t*4>=h)?(f=new Uint8Array(o.buffer,o.byteOffset,t),f.fill(0,o.byteLength)):(f=new Uint8Array(t),f.set(o.subarray(0,t)),s.dirty&&this.release(o))}this.nodes.set(n,{type:"file",content:f,dirty:!0,mode:s.mode,atimeMs:Ee(),mtimeMs:Ee(),ino:s.ino}),this.markMutation(n)})}spares=[];release(e){const t=e.buffer;if(!(t instanceof ArrayBuffer)||t.byteLength<Tr||t.byteLength>Nn)return;this.spares.push(t);let n=this.spares.reduce((s,f)=>s+f.byteLength,0);for(;this.spares.length>ys||n>Nn;)n-=this.spares.shift().byteLength}takeSpare(e){const t=Math.max(e*4,Tr*4);let n=-1;return this.spares.forEach((s,f)=>{s.byteLength>=e&&s.byteLength<=t&&(n<0||s.byteLength<this.spares[n].byteLength)&&(n=f)}),n<0?void 0:this.spares.splice(n,1)[0]}writeFileSync(e,t){this.mutate(()=>{const n=_(e);this.mkdirSync(Te(n),{recursive:!0});const s=this.isHidden(n);this.unhide(n);const f=s?this.nodes.get(n):this.node(n);f?.type==="file"&&f.dirty&&f.content&&this.release(f.content),this.nodes.set(n,{type:"file",content:typeof t=="string"?new TextEncoder().encode(t):t.slice(),dirty:!0,mode:f?.type==="file"?f.mode:420,atimeMs:Ee(),mtimeMs:Ee(),ino:f?.type==="file"?f.ino:this.nextInode++}),this.markMutation(n)})}mkdirSync(e,t){this.mutate(()=>{const n=_(e);if(n==="/")return;if(!this.node(n)&&this.node(Te(n))?.type==="directory"){this.unhide(n);const h=Ee();this.nodes.set(n,{type:"directory",mode:493,atimeMs:h,mtimeMs:h,ino:this.nextInode++}),this.markMutation(n);return}const s=n.slice(1).split("/");let f="";for(let o=0;o<s.length;o+=1){f+=`/${s[o]}`;const h=this.node(f);if(h?.type==="file")throw new Error(`ENOTDIR: not a directory, mkdir '${f}'`);if(h)continue;if(!t?.recursive&&o!==s.length-1)throw new Error(`ENOENT: no such directory, mkdir '${f}'`);this.unhide(f);const w=Ee();this.nodes.set(f,{type:"directory",mode:493,atimeMs:w,mtimeMs:w,ino:this.nextInode++}),this.markMutation(f)}})}readdirSync(e){const t=_(e),n=this.node(t);if(!n)throw new Error(`ENOENT: no such directory, scandir '${t}'`);if(n.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);const s=new Set(this.nodes.namesIn(t));if(this.lower&&!this.isHidden(t)){const f=t==="/"?[...new Set([...this.lower.childrenOf("/"),...Kn.filter(o=>this.lower.entries.has(o)).map(o=>o.slice(1))])]:this.lower.childrenOf(t);for(const o of f)this.isHidden(t==="/"?`/${o}`:`${t}/${o}`)||s.add(o)}return[...s]}unlinkSync(e){this.mutate(()=>{const t=_(e),n=this.node(t);if(!n)throw new Error(`ENOENT: no such file, unlink '${t}'`);if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, unlink '${t}'`);n.dirty&&n.content&&this.release(n.content),this.nodes.delete(t),this.hide(t),this.markMutation(t)})}rmdirSync(e){this.mutate(()=>{const t=_(e);if(t==="/")throw new Error("EPERM: cannot remove root directory");const n=this.node(t);if(!n)throw new Error(`ENOENT: no such directory, rmdir '${t}'`);if(n.type!=="directory")throw new Error(`ENOTDIR: not a directory, rmdir '${t}'`);if(this.readdirSync(t).length>0)throw new Error(`ENOTEMPTY: directory not empty, rmdir '${t}'`);this.nodes.delete(t),this.hide(t),this.markMutation(t)})}renameSync(e,t){this.mutate(()=>{const n=_(e),s=_(t);if(!this.node(n))throw new Error(`ENOENT: no such file or directory, rename '${n}'`);if(this.mkdirSync(Te(s),{recursive:!0}),this.lower&&!this.isHidden(n))for(const[h]of this.lower.descendants(n))this.node(h);const o=this.nodes.subtree(n);for(const[h]of o)this.nodes.delete(h);this.hide(n),this.unhide(s);for(const[h,w]of o){if(w.type==="file"){const S=this.bytesOf(w);w.dirty||(w.content=S.slice()),w.dirty=!0}const g=`${s}${h.slice(n.length)}`,E=this.nodes.get(g);E?.type==="file"&&E.dirty&&E.content&&E!==w&&this.release(E.content),this.nodes.set(g,w),this.markMutation(h),this.markMutation(g)}})}reserveInodes(e){const t=this.nextInode;return this.nextInode+=e,t}restoreNodeSync(e,t){this.mutate(()=>{const n=_(e);this.unhide(n);const s=this.nodes.get(n);s?.type==="file"&&s.dirty&&s.content&&this.release(s.content),this.nodes.set(n,t.directory?{type:"directory",mode:t.mode&4095,atimeMs:t.atimeMs,mtimeMs:t.mtimeMs,ino:t.ino}:{type:"file",content:t.content??new Uint8Array,dirty:!0,mode:t.mode&4095,atimeMs:t.atimeMs,mtimeMs:t.mtimeMs,ino:t.ino}),this.markMutation(n)})}chmodSync(e,t){this.mutate(()=>{const n=_(e),s=this.node(n);if(!s)throw new Error(`ENOENT: no such file or directory, chmod '${n}'`);s.mode=t&4095,this.markMutation(n)})}utimesSync(e,t,n){this.mutate(()=>{const s=_(e),f=this.node(s);if(!f)throw new Error(`ENOENT: no such file or directory, utimes '${s}'`);f.atimeMs=typeof t=="number"?t:Number(t),f.mtimeMs=typeof n=="number"?n:Number(n),this.markMutation(s)})}mutate(e){this.mutationDepth+=1;try{return e()}finally{this.mutationDepth-=1,this.mutationDepth===0&&this.mutated&&(this.mutated=!1,this.mutationHandler?.())}}markMutation(e){this.mutated=!0,this.changedPaths?.add(_(e))}}const ls=1<<20,At=64*1024,hs=8*1024*1024,us=1<<20,Tr=64*1024,ys=2,Nn=32*1024*1024;function ws(){const d=Ee();return{type:"directory",mode:493,atimeMs:d,mtimeMs:d,ino:1}}function _(d){if(ms(d))return d;const e=[];for(const t of`/${d}`.split("/"))!t||t==="."||(t===".."?e.pop():e.push(t));return`/${e.join("/")}`}function ms(d){if(d.charCodeAt(0)!==47)return!1;if(d.length===1)return!0;let e=1;for(let t=1;t<=d.length;t+=1){if(t<d.length&&d.charCodeAt(t)!==47)continue;const n=t-e;if(n===0||d.charCodeAt(e)===46&&(n===1||n===2&&d.charCodeAt(e+1)===46))return!1;e=t+1}return!0}function Te(d){return d.slice(0,d.lastIndexOf("/"))||"/"}function tr(d){let e=1;for(let t=0;t<d.length;t+=1)d.charCodeAt(t)===47&&(e+=1);return e}const gs=`${qi}/.volter-tree-complete`;async function ps(d,e){const t=Rr(d);try{if((await t.initialize(e,{readOnly:!0})||t.opened())&&t.entries.has(gs))return t}catch(n){throw t.close(),n}t.close()}const Rn=new WeakMap;async function Es(d,e){const t=[...new Set((d??[]).flatMap(o=>o.store===void 0?[]:[o.store]))];if(t.length===0)return;e??={navigator:globalThis.navigator};const n=e;let s=Rn.get(n.navigator);s||Rn.set(n.navigator,s=new Map);const f=new Map;for(const o of t){let h=s.get(o);h||(h=Zi(o,n.navigator.locks).then(()=>ps(n,o)),s.set(o,h));let w;try{w=await h}catch(g){throw s.delete(o),new Error(`The installed tree ${o} would not open: ${g instanceof Error?g.message:String(g)}`,{cause:g})}if(!w)throw s.delete(o),new Error(`The installed tree ${o} is not on this origin's disk to read.`);f.set(o,w)}return f}let B=new Le,Fr,_r,ct,Jn;const V=new Map;let bs=1,zr,$r,dt;const Cr=new TextEncoder,yt=new TextDecoder;let Ke=!1,ut,Dr=0;const lt=[],ht=new Set;let be,xt,Ge=0,Lr=!1,sr=!1,Pt=0,cr,Mt=[],fr=!1;const ve=Symbol("retry");function xs(){cr?.()}function Ts(){sr=!1,Pt=0,cr=void 0,Ke=!1,ut=void 0,lt.length=0,ht.clear(),be=void 0,xt=void 0,dr=void 0,Ge=0,fr=!1,B=new Le,_r=void 0,V.clear()}function Fs(d){Ke=!0,ut=new Int32Array(d),Dr=Atomics.load(ut,0)}async function Ls(d){const e={data:d};lt.length=0,ht.clear(),xt=void 0,dr=void 0,be=void 0,Ge=0,fr=!1,sr=!1,Pt=0,cr=void 0,Mt=(d.privateRoots??[]).map(Os);{zr=void 0,$r=void 0;const t=await Es(d.layers);if(d.store){if(Fr=await cs({navigator:globalThis.navigator},d.store.projectId),!Fr)throw new Error("The project's store is not there to read.");B=Le.fromStore(Mn(Fr,d.layers,t),d.snapshot)}else d.layers?B=Le.fromStore(Mn(void 0,d.layers,t),d.snapshot):B=Le.fromSnapshot(d.snapshot);dt=(s,f)=>bn(B,s,f);const n=e.data.fileLocks?new Ci(e.data.fileLocks.channel):void 0;if(ct=d.sharedPipes,Jn=d.memory,_r=new Di({...ct?{descriptors:new Hi(new Wi(ct.descriptions),ct.table)}:{},filesystem:B,...d.filesystemPolicy?{filesystemPolicy:d.filesystemPolicy}:{},cwd:e.data.cwd,stdin:new Uint8Array,executablePath:e.data.executablePath,memory:()=>e.data.memory,emit:()=>-9n,descriptorMaximum:19999,pid:e.data.pid,...Mt.length?{privateRoots:Mt,privateTreeAdoptable:()=>V.size===0,onDiagnostic:s=>console.warn(s)}:{},...n&&e.data.fileLocks?{fileLocks:e.data.fileCoherence?new Ui(n,new ji(e.data.fileCoherence),B):n,lockOwner:e.data.fileLocks.owner}:{}}),e.data.updatePort){let s;const f=e.data.updatePort;f.start();const o=new Set,h=()=>{s&&clearTimeout(s),s=void 0;const S=B.takeChangedPaths();if(Mt.length>0)for(const p of S)Mt.some(L=>Is(p,L))&&S.delete(p);if(S.size===0)return;for(const p of S)o.add(p);const k=[],I=[];for(const p of S){const L=B.writtenEntry(p,!0);L?k.push(L):I.push(p)}(k.length>0||I.length>0)&&(f.postMessage({type:"filesystem",patch:{files:k,removed:I}},k.flatMap(p=>p.bytes?[p.bytes.buffer]:[])),w=!0)};let w=!1;$r=()=>{if(h(),!w)return;const S=new Int32Array(new SharedArrayBuffer(4));if(f.postMessage({type:"checkpoint",control:S.buffer}),Atomics.wait(S,0,0,3e4),Atomics.load(S,0)!==1)throw new Error("WALI filesystem spawn checkpoint failed.");w=!1};let g=!1,E=!1;if(zr=()=>{E||(h(),Ge=0,E=!0,fr=!0,f.postMessage({type:"finalized"}))},dt=(S,k)=>{if(E)throw new Error("The WALI filesystem is finalized.");h(),g=!0;try{let I=k;if(k){const p=new Map(k.files.map(L=>[L.path,L]));for(const L of[...S.files.map(v=>v.path),...S.removed]){if(o.has(L))continue;const v=Gi(B,L);v?p.set(L,v):p.delete(L)}I={files:[...p.values()]}}bn(B,S,I),B.takeChangedPaths(),f.postMessage({type:"imported",patch:S})}finally{g=!1}},Ke){xt=h,cr=()=>{sr=!0,f.postMessage({type:"port-closed",taken:Pt})};const S=new SharedArrayBuffer(1<<20,{maxByteLength:1<<30});be={control:new Int32Array(S,0,2),buffer:S},f.postMessage({type:"mailbox",buffer:S,doorbell:ut.buffer}),dr=k=>f.postMessage({type:"import-error",message:k instanceof Error?k.message:String(k)})}f.onmessage=S=>{if(!(S.data.type!=="import"||E||sr)){Pt=S.data.sequence??Pt;try{dt(S.data.patch,S.data.base)}catch(k){f.postMessage({type:"import-error",message:k instanceof Error?k.message:String(k)})}}},B.setMutationHandler(()=>{if(!(g||E)){if(Ke){Ge===0&&(Ge=performance.now());return}s??=setTimeout(h,0)}})}}}function Ss(d){const e=new Int32Array(d.control),t=new Uint8Array(d.payload),n={process:d.process??0};if(lt.push({control:e,payload:t,state:n}),d.releasePort){const s=d.releasePort;s.onmessage=()=>{V.get(n.process)?.descriptors.descriptors.exit(),V.delete(n.process),s.postMessage(!0),s.close()},s.start()}if(n.process!==0&&d.sharedPipes){const s=V.get(n.process).descriptors.descriptors;s.sharedEntries=new Int32Array(d.sharedPipes.table),s.entries.forEach((f,o)=>{f&&Atomics.store(s.sharedEntries,o,f.description)})}return d.port.onmessage=s=>{if(typeof s.data!="number"&&"kind"in s.data){Ss({...s.data,process:s.data.process??n.process});return}if(typeof s.data!="number"){const f=V.get(n.process);if(!f)throw new Error("Unknown inherited descriptor table");f.memory=s.data.memory;return}ks(e,t,n,s.data)},d.port.start(),lt[lt.length-1]}async function ks(d,e,t,n){if(Atomics.load(d,0)!==n)return;let s=-38,f=new Uint8Array;try{const o=Atomics.load(d,1);if(o===F.SyscallBinary){const k=qn(e,t);if(k===ve)return;const I=BigInt(k instanceof Promise?await k:k);if(Atomics.compareExchange(d,0,n,-n)!==n)return;(t.view??=new DataView(e.buffer,e.byteOffset,e.byteLength)).setBigInt64(0,I,!0),Atomics.store(d,2,0),Atomics.store(d,4,8),Atomics.store(d,0,n+1),Atomics.notify(d,0);return}const h=Xn(o,e,t);if(h){if(h.output.byteLength>e.byteLength)throw Object.assign(new Error("EMSGSIZE"),{code:"EMSGSIZE"});if(Atomics.compareExchange(d,0,n,-n)!==n)return;e.set(h.output),Atomics.store(d,2,h.result),Atomics.store(d,4,h.output.byteLength),Atomics.store(d,0,n+1),Atomics.notify(d,0);return}const w=Atomics.load(d,3),g=w>0?JSON.parse(yt.decode(e.slice(0,w))):{},E=Vn(o,g,t);if(E===ve)return;const S=E instanceof Promise?await E:E;f=S===void 0?new Uint8Array:Cr.encode(JSON.stringify(S)),s=0}catch(o){s=lr(o)}f.byteLength>e.byteLength&&(s=-90,f=new Uint8Array),Atomics.compareExchange(d,0,n,-n)===n&&(f.byteLength>0&&e.set(f),Atomics.store(d,2,s),Atomics.store(d,4,f.byteLength),Atomics.store(d,0,n+1),Atomics.notify(d,0))}function Tt(){return _r}function Vn(d,e,t){const n=t.process===0?Tt():V.get(t.process)?.descriptors;if(d===F.GetCwd)return n?.currentWorkingDirectory();if(d===F.CopyForExec||d===F.CopyForFork){if(!n)throw new Error("Missing parent descriptor table");const f={descriptors:n[d===F.CopyForFork?"copyForFork":"copyForExec"](()=>{if(!f.memory)throw new Error("Child memory is not attached");return f.memory},Array.isArray(e.stdio)?e.stdio.map(Q):void 0)},o=bs++;return V.set(o,f),{process:o}}if(d===F.CloseProcess){n?.descriptors.exit(),t.process!==0&&V.delete(t.process);return}const s=()=>fe(e.path);if(d===F.PrepareSpawn){$r?.();return}if(d===F.ImportPeerPatch){dt(e.patch);return}if(d===F.Exists)return B.existsSync(s());if(d===F.Stat||d===F.Lstat){const f=d===F.Lstat?B.lstatSync(s()):B.statSync(s());return{file:f.isFile(),directory:f.isDirectory(),symbolicLink:f.isSymbolicLink?.(),size:f.size,mode:f.mode,mtimeMs:f.mtimeMs,atimeMs:f.atimeMs,ctimeMs:f.ctimeMs,nlink:f.nlink,uid:f.uid,gid:f.gid,dev:f.dev,ino:f.ino,rdev:f.rdev,blksize:f.blksize,blocks:f.blocks}}if(d===F.ReadFile)return{content:Fe(B.readFileSync(s()))};if(d===F.WriteFile){B.writeFileSync(s(),at(fe(e.content)));return}if(d===F.ReadRange){const f=Q(e.offset),o=Q(e.length),h=B.readRangeSync?B.readRangeSync(s(),f,o):B.readFileSync(s()).subarray(f,f+o);return{content:Fe(h)}}if(d===F.WriteRange){const f=Q(e.offset),o=at(fe(e.content));if(B.writeRangeSync)B.writeRangeSync(s(),f,o);else{const h=B.existsSync(s())?B.readFileSync(s()):new Uint8Array,w=new Uint8Array(Math.max(h.byteLength,f+o.byteLength));w.set(h),w.set(o,f),B.writeFileSync(s(),w)}return}if(d===F.Mkdir){B.mkdirSync(s(),{recursive:e.recursive===!0});return}if(d===F.Readdir)return B.readdirSync(s());if(d===F.Unlink){B.unlinkSync(s());return}if(d===F.Rmdir){B.rmdirSync(s());return}if(d===F.Rename){B.renameSync(fe(e.from),fe(e.to));return}if(d===F.Snapshot)return B.toSnapshot();if(d===F.SnapshotSize||d===F.FinalSnapshotSize)return d===F.FinalSnapshotSize&&zr?.(),t.snapshot=Cr.encode(JSON.stringify(B.toSnapshot())),{length:t.snapshot.byteLength};if(d===F.SnapshotChunk){const f=Q(e.offset),o=Q(e.length);if(!t.snapshot||f<0||o<0||o>En||f+o>t.snapshot.byteLength)throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});const h=Fe(t.snapshot.subarray(f,f+o));return f+o===t.snapshot.byteLength&&delete t.snapshot,{content:h}}if(d===F.ReplaceSnapshot){B.replaceSnapshot(e.snapshot);return}if(d===F.ReplaceSnapshotStart||d===F.ImportPeerPatchStart){const f=Q(e.length);if(f<=0||f>256*1024*1024)throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});t.replacement={bytes:new Uint8Array(f),offset:0,peerPatch:d===F.ImportPeerPatchStart};return}if(d===F.ReplaceSnapshotChunk||d===F.ImportPeerPatchChunk){const f=Q(e.offset),o=at(fe(e.content)),h=t.replacement;if(!h||h.peerPatch!==(d===F.ImportPeerPatchChunk)||f!==h.offset||o.byteLength>En||f+o.byteLength>h.bytes.byteLength)throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});if(h.bytes.set(o,f),h.offset+=o.byteLength,h.offset===h.bytes.byteLength){delete t.replacement;const w=JSON.parse(yt.decode(h.bytes));h.peerPatch?dt(w):B.replaceSnapshot(w)}return}if(d===F.Syscall){if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});const f=fe(e.name),o=Ur(t,n)[f];if(!o)throw Object.assign(new Error("ENOSYS"),{code:"ENOSYS"});const h=Array.isArray(e.args)?e.args.map(g=>BigInt(fe(g))):[],w=Hr(f,o,h);return w===ve?ve:w instanceof Promise?w.then(g=>({result:String(g)})):{result:String(w)}}if(d===F.ReadForMapping){if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});const f=n.readForMapping(Q(e.fd),Q(e.offset),Q(e.length));return f?{content:Fe(f)}:{}}if(d===F.MappingPath){if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});const f=n.mappingPath(Q(e.fd));return f?{path:f}:{}}if(d===F.WriteForMapping){if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});return{written:n.writeForMapping(fe(e.path),Q(e.offset),at(fe(e.content)))}}throw Object.assign(new Error("ENOSYS"),{code:"ENOSYS"})}function Ur(d,e){const t=e.descriptors,n=d.handlers;if(n&&n.table===e&&n.entries===t.sharedEntries.buffer)return n.imports;const s=ct&&new Yi(()=>d.process===0?Jn:V.get(d.process).memory,{...ct,table:t.sharedEntries.buffer},t),f=s?s.imports(e.imports()):e.imports();return d.handlers={table:e,entries:t.sharedEntries.buffer,imports:f},f}function qn(d,e){const t=e.process===0?Tt():V.get(e.process)?.descriptors;if(!t)throw Object.assign(new Error("EIO"),{code:"EIO"});const n=e.view??=new DataView(d.buffer,d.byteOffset,d.byteLength),s=d[0],f=yt.decode(d.slice(8+s*8,8+s*8+d[1])),o=[];for(let w=0;w<s;w+=1)o.push(n.getBigInt64(8+w*8,!0));const h=Ur(e,t)[f];if(!h)throw Object.assign(new Error("ENOSYS"),{code:"ENOSYS"});return Hr(f,h,o)}function Hr(d,e,t){let n;if(d==="SYS_flock"){const s=Number(t[1]??0);(s&4)===0&&(s&8)===0&&(n=[...t],n[1]=BigInt(s|4))}else if(d==="SYS_fcntl"){const s=Number(t[1]??0);(s===7||s===38)&&(n=[...t],n[1]=BigInt(s===7?6:37))}if(!n)return e(...t)??0;if(Ke){const s=e(...n)??0;return BigInt(s)===-11n?ve:s}return As(e,n)}async function As(d,e){for(;;){const t=d(...e)??0;if(BigInt(t)!==-11n)return t;await new Promise(n=>setTimeout(n,5))}}function fe(d){if(typeof d!="string")throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});return d}function Q(d){if(typeof d!="number"||!Number.isSafeInteger(d))throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});return d}function lr(d){const e=d instanceof Error?d.message:String(d),t=typeof d=="object"&&d!==null&&"code"in d?String(d.code):/\b(E[A-Z]+)\b/u.exec(e)?.[1]??"EIO";return-({ENOENT:2,EBADF:9,EACCES:13,EEXIST:17,ENOTDIR:20,EISDIR:21,EINVAL:22,EMFILE:24,ENOSPC:28,ESPIPE:29,ERANGE:34,ENOSYS:38,ENOTEMPTY:39,EMSGSIZE:90}[t]??5)}function Ms(d){const{control:e,payload:t,state:n}=d,s=Atomics.load(e,0);if(s<=0||(s&1)===0)return!1;let f=-38,o=new Uint8Array,h,w;try{const g=Atomics.load(e,1);if(g===F.SyscallBinary){const E=qn(t,n);if(E===ve)return ht.add(d),!1;if(E instanceof Promise)throw new Error("EIO: an asynchronous syscall on the main thread");h=BigInt(E)}else if((w=Xn(g,t,n))!==void 0)o=w.output;else{const E=Atomics.load(e,3),S=E>0?JSON.parse(yt.decode(t.slice(0,E))):{},k=Vn(g,S,n);if(k===ve)return ht.add(d),!1;if(k instanceof Promise)throw new Error("EIO: an asynchronous operation on the main thread");o=k===void 0?new Uint8Array:Cr.encode(JSON.stringify(k))}f=w?.result??0}catch(g){f=lr(g),h=void 0}return ht.delete(d),o.byteLength>t.byteLength&&(f=-90,o=new Uint8Array),Atomics.compareExchange(e,0,s,-s)!==s||(h!==void 0?((n.view??=new DataView(t.buffer,t.byteOffset,t.byteLength)).setBigInt64(0,h,!0),o=new Uint8Array(8)):o.byteLength>0&&t.set(o),Atomics.store(e,2,f),Atomics.store(e,4,h!==void 0?8:o.byteLength),Atomics.store(e,0,s+1),Atomics.notify(e,0)),!0}function vs(){return Ke?Atomics.load(ut,0)!==Dr||ht.size>0:!1}function Bs(d=!1){if(!(!Ke||Lr)){Lr=!0;try{if(Dr=Atomics.load(ut,0),be&&!fr&&Atomics.load(be.control,0)===1)try{const e=Atomics.load(be.control,1),t=JSON.parse(yt.decode(new Uint8Array(be.buffer,8,e).slice()));Atomics.store(be.control,0,0),t.type==="import"&&dt(t.patch,t.base)}catch(e){Atomics.store(be.control,0,0),dr?.(e)}for(const e of lt)Ms(e);xt&&Ge!==0&&d&&(Ge=0,xt())}finally{Lr=!1}}}let dr;function Xn(d,e,t){if(d!==F.ReadForMappingBinary&&d!==F.WriteForMappingBinary)return;const n=t.process===0?Tt():V.get(t.process)?.descriptors;if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});const s=t.view??=new DataView(e.buffer,e.byteOffset,e.byteLength);if(d===F.ReadForMappingBinary){const g=Math.min(s.getInt32(16,!0),e.byteLength),E=n.readForMapping(s.getInt32(0,!0),s.getFloat64(8,!0),g);return E?{result:0,output:E}:{result:1,output:new Uint8Array}}const f=s.getUint32(8,!0),o=s.getUint32(12,!0),h=yt.decode(e.slice(16,16+f)),w=n.writeForMapping(h,s.getFloat64(0,!0),e.slice(16+f,16+f+o));return{result:0,output:new Uint8Array([w?1:0])}}function Os(d){return`/${d.split("/").filter(Boolean).join("/")}`}function Is(d,e){return e==="/"||d===e||d.startsWith(`${e}/`)}function Ns(d,e,t){try{const n=d.state,s=n.process===0?Tt():V.get(n.process)?.descriptors;if(!s)throw Object.assign(new Error("EIO"),{code:"EIO"});const f=Ur(n,s)[e];if(!f)throw Object.assign(new Error("ENOSYS"),{code:"ENOSYS"});const o=Hr(e,f,t);if(o===ve)return;if(o instanceof Promise)throw new Error("EIO: an asynchronous syscall on the main thread");return BigInt(o)}catch(n){return{failed:lr(n)}}}function Rs(d){const e=d.state,t=e.process===0?Tt():V.get(e.process)?.descriptors;if(!t)throw Object.assign(new Error("EIO"),{code:"EIO"});const n=e.direct;if(n&&n.table===t)return n.handlers;const s={imports:t.imports(),errno:lr,owns:f=>t.ownsFile(f)};return e.direct={table:t,handlers:s},s}export{Ss as attachChannel,xs as closeHostPort,Rs as handlersNow,Fs as hostInThread,vs as hostWaiting,Ls as initializeHost,Bs as pumpHost,Ts as resetHost,Ms as serveNow,Ns as syscallNow,Is as underRoot};
|