@volter/browser-substrate 0.1.114 → 0.1.116

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