@volter/browser-substrate 0.1.110 → 0.1.112
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/shell/assets/browser-opfs-filesystem-worker-TLQsaODy.js +3 -0
- package/dist/shell/assets/{browser-sandbox-bridge-D83LgnQx.js → browser-sandbox-bridge-CmMlTDpO.js} +2 -2
- package/dist/shell/assets/{filesystem-host-Bz80KA3H.js → filesystem-host-D98WfBoD.js} +1 -1
- package/dist/shell/assets/{filesystem-host-DiM0ruXt.js → filesystem-host-EfkgP9Jh.js} +2 -2
- package/dist/shell/assets/{filesystem-worker-B_zvdiVO.js → filesystem-worker-51BLqPs5.js} +3 -3
- package/dist/shell/assets/{fork-worker-BcogGro3.js → fork-worker-hBikLg_q.js} +1 -1
- package/dist/shell/assets/{node-execution-worker-aad84e7ccac38d49.js → node-execution-worker-5e417bedc3429b5c.js} +1 -1
- package/dist/shell/assets/{sandbox-eUWD4AMK.js → sandbox-qgjYY5Gr.js} +1 -1
- package/dist/shell/assets/{shell-17SQHc7q.js → shell-C0qfPTpQ.js} +4 -4
- package/dist/shell/assets/{worker-BjKdS6e6.js → worker-BZ-Txq9L.js} +20 -20
- package/dist/shell/assets/{worker-program-worker-DfQzwSkL.js → worker-program-worker-B_u8gbzh.js} +7 -7
- package/dist/shell/index.html +2 -2
- package/dist/shell/node-execution-worker.js +7 -4
- package/dist/shell/python-execution-worker.js +6 -3
- package/dist/shell/python-runtime-snapshot.bin +0 -0
- package/dist/shell/python-runtime-snapshot.json +1 -1
- package/dist/shell/sandbox.html +2 -2
- package/package.json +1 -1
- package/dist/shell/assets/browser-opfs-filesystem-worker-DF78_MSS.js +0 -3
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const Gt=["file","directory","symlink"],kn=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,An=new TextEncoder,On=new TextDecoder;function _r(m){let o=2166136261;for(let a=0;a<m.length;a+=1)o^=m.charCodeAt(a),o=Math.imul(o,16777619);return o>>>0}function Sr(m,o){const a=[...m.keys()];for(const F of a)if(kn.test(F))throw new Error("A path in the store is not well-formed UTF-16.");const d=new Map;for(let F=0;F<a.length;F+=1)d.set(a[F],F);for(const F of o.keys())d.has(F)||(d.set(F,a.length),a.push(F));const h=a.length,E=new Map,y=new Uint32Array(h);let S=0;for(let F=0;F<h;F+=1){const $=a[F];let G=!0;for(let oe=0;oe<$.length;oe+=1)if($.charCodeAt(oe)>=128){G=!1;break}G||E.set(F,An.encode($)),y[F]=G?$.length:E.get(F).length,S+=y[F]}let P=0;for(const F of o.values())P+=F.size;let A=1;for(;A<h*2;)A<<=1;const I=24,M=Wt(I+h*6*4,8),x=M+h*3*8,T=x+A*4,w=T+P*4,C=new SharedArrayBuffer(Wt(w+S,8));new Uint32Array(C,0,6).set([2019846480,h,A,P,S,m.size]);const H=new Uint32Array(C,I,h*6),z=new Float64Array(C,M,h*3),_e=new Uint32Array(C,x,A),Ze=new Uint32Array(C,T,P),me=new Uint8Array(C,w,S);let ie=0,v=0;for(let F=0;F<h;F+=1){const $=a[F],G=F*6,oe=E.get(F);if(oe)me.set(oe,ie);else for(let b=0;b<$.length;b+=1)me[ie+b]=$.charCodeAt(b);const O=y[F];H[G+0]=ie,H[G+1]=O,ie+=O;let Y=oe?0:32;const q=m.get($);if(q){Y|=1|Gt.indexOf(q.type)<<3,q.pack&&(Y|=4),H[G+3]=q.mode;const b=F*3;z[b+0]=q.mtimeMs,z[b+1]=q.offset,z[b+2]=q.length}const Ee=o.get($);if(Ee){Y|=2,H[G+4]=v,H[G+5]=Ee.size;for(const b of Ee){const R=d.get(`${$}/${b}`);if(R===void 0)throw new Error(`The store's children name ${$}/${b}, which its index does not hold.`);Ze[v++]=R}}H[G+2]=Y;let we=_r($)&A-1;for(;_e[we]!==0;)we=we+1&A-1;_e[we]=F+1}if(v!==P)throw new Error("The shared index's children did not add up.");return C}function Wt(m,o){return Math.ceil(m/o)*o}class Ie{buffer;count;entryCount;records;numbers;table;childList;strings;mask;constructor(o){const a=new Uint32Array(o,0,6);if(a[0]!==2019846480)throw new Error("Not a shared store index.");const[,d,h,E,y,S]=a;this.buffer=o,this.count=d,this.entryCount=S;const P=24,A=Wt(P+d*6*4,8),I=A+d*3*8,M=I+h*4,x=M+E*4;this.records=new Uint32Array(o,P,d*6),this.numbers=new Float64Array(o,A,d*3),this.table=new Uint32Array(o,I,h),this.childList=new Uint32Array(o,M,E),this.strings=new Uint8Array(o,x,y),this.mask=h-1}find(o){let a=_r(o)&this.mask;for(;;){const d=this.table[a];if(d===0)return-1;if(this.pathIs(d-1,o))return d-1;a=a+1&this.mask}}entry(o){const a=o*6,d=this.records[a+2];if(!(d&1))return;const h=o*3,E={type:Gt[d>>>3&3],mode:this.records[a+3],mtimeMs:this.numbers[h+0],offset:this.numbers[h+1],length:this.numbers[h+2]};return d&4&&(E.pack="packages"),E}typeAt(o){const a=this.records[o*6+2];return a&1?Gt[a>>>3&3]:void 0}hasEntry(o){return(this.records[o*6+2]&1)!==0}childNames(o){const a=o*6;if(!(this.records[a+2]&2))return;const d=this.records[a+4],h=this.records[a+1]+1,E=[];for(let y=0;y<this.records[a+5];y+=1){const S=this.childList[d+y]*6;E.push(this.decode(this.records[S+0]+h,this.records[S+1]-h,(this.records[S+2]&32)!==0))}return E}path(o){const a=o*6;return this.decode(this.records[a+0],this.records[a+1],(this.records[a+2]&32)!==0)}decode(o,a,d){if(!d)return On.decode(this.strings.slice(o,o+a));let h="";for(let E=o,y=o+a;E<y;E+=4096)h+=String.fromCharCode.apply(null,this.strings.subarray(E,Math.min(y,E+4096)));return h}pathIs(o,a){const d=o*6,h=this.records[d+0],E=this.records[d+1];if(!(this.records[d+2]&32))return this.path(o)===a;if(E!==a.length)return!1;for(let y=0;y<E;y+=1)if(this.strings[h+y]!==a.charCodeAt(y))return!1;return!0}}const re=Symbol("deleted");function vr(m,o){return m===o||!!m&&!!o&&m.type===o.type&&m.offset===o.offset&&m.length===o.length&&m.pack===o.pack&&m.mode===o.mode&&m.mtimeMs===o.mtimeMs&&m.capacity===o.capacity}class Ne{base;overlay=new Map;delta=0;constructor(o){this.base=o}get[Symbol.toStringTag](){return"Map"}get size(){return this.base.entryCount+this.delta}get(o){const a=this.overlay.get(o);if(a!==void 0)return a===re?void 0:a;const d=this.base.find(o);return d<0?void 0:this.base.entry(d)}typeOf(o){const a=this.overlay.get(o);if(a!==void 0)return a===re?void 0:a.type;const d=this.base.find(o);return d<0?void 0:this.base.typeAt(d)}has(o){const a=this.overlay.get(o);if(a!==void 0)return a!==re;const d=this.base.find(o);return d>=0&&this.base.hasEntry(d)}set(o,a){this.has(o)||(this.delta+=1);const d=this.base.find(o);return d>=0&&vr(this.base.entry(d),a)?this.overlay.delete(o):this.overlay.set(o,a),this}delete(o){if(!this.has(o))return!1;const a=this.base.find(o);return a>=0&&this.base.hasEntry(a)?this.overlay.set(o,re):this.overlay.delete(o),this.delta-=1,!0}clear(){throw new Error("A reader's index is not cleared; it is replaced.")}*entries(){for(const[o,a]of this.overlay)a!==re&&(yield[o,a]);for(let o=0;o<this.base.count;o+=1){if(!this.base.hasEntry(o))continue;const a=this.base.path(o);this.overlay.has(a)||(yield[a,this.base.entry(o)])}}*keys(){for(const[o]of this.entries())yield o}*values(){for(const[,o]of this.entries())yield o}[Symbol.iterator](){return this.entries()}forEach(o,a){for(const[d,h]of this.entries())o.call(a,h,d,this)}*changed(){for(const[o,a]of this.overlay)a!==re&&(yield[o,a])}*changes(){for(const[o,a]of this.overlay)yield[o,a===re?null:a]}get overlaid(){return this.overlay.size}boundedChanges(){if(this.overlay.size>65536)return;const o=[];let a=0;for(const[d,h]of this.changes()){if(a+=d.length*2+128,a>8*1024*1024)return;o.push([d,h])}return o}}class Et{base;overlay=new Map;constructor(o){this.base=o}get(o){const a=this.overlay.get(o);if(a!==void 0)return a===re?void 0:a;const d=this.base.find(o),h=d<0?void 0:this.base.childNames(d);return h?new Set(h):void 0}mutable(o){const a=this.overlay.get(o);if(a!==void 0&&a!==re)return a;const d=new Set(a===re?[]:this.get(o)??[]);return this.overlay.set(o,d),d}delete(o){this.overlay.set(o,re)}}const Pn="supercode-browser-filesystems",xe="packages",Tn="state.json",br="/image-range-worker.js",kr="image-ranges.json",Fn=2;function $t(m){const o=m;if(!o||o.version!==1||!Number.isSafeInteger(o.bytes)||o.bytes<0||!Array.isArray(o.parts)||o.image!==void 0&&(typeof o.image!="string"||!/^[a-f0-9]{16,64}$/u.test(o.image))||o.parts.length>1e5)throw new Error("Invalid immutable image ranges.");let a=0;for(const d of o.parts){if(!d||d.offset!==a||!Number.isSafeInteger(d.raw)||d.raw<0||!Number.isSafeInteger(d.bytes)||d.bytes<0||d.bytes>1024*1024*1024||d.raw>1024*1024*1024||typeof d.sha256!="string"||!/^[a-f0-9]{64}$/u.test(d.sha256)||typeof d.url!="string"||!/^\/substrate\/[A-Za-z0-9._/-]+$/u.test(d.url)||d.url.split("/").some(h=>h==="."||h===".."))throw new Error("Invalid immutable image part.");if(a+=d.raw,!Number.isSafeInteger(a))throw new Error("Immutable image ranges exceed the offset limit.")}if(a!==o.bytes)throw new Error("Immutable image ranges do not cover their reservation.");return o}const Ar=new Map;class In{ranges;directory;identity;receiptKey;client;worker;port;prefetchers=[];state;completed;firstRead;closed=!1;ready=!1;startup;cancelStartup;sharedCompletion;constructor(o,a,d,h,E,y){if(this.ranges=o,this.directory=a,this.identity=d,this.receiptKey=E,this.client=y,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(y?.state??new SharedArrayBuffer(o.parts.length*Int32Array.BYTES_PER_ELEMENT)),this.state.length!==o.parts.length)throw new Error("The image reader's line has the wrong range count.");const S=o.parts.length,P=h??new SharedArrayBuffer((2*S+1)*Int32Array.BYTES_PER_ELEMENT);if(P.byteLength!==S*Int32Array.BYTES_PER_ELEMENT&&P.byteLength!==(2*S+1)*Int32Array.BYTES_PER_ELEMENT)throw new Error("The image completion seed has the wrong range count.");this.completed=new Int32Array(P,0,S),this.firstRead=P.byteLength>S*Int32Array.BYTES_PER_ELEMENT?new Int32Array(P,S*Int32Array.BYTES_PER_ELEMENT,S+1):void 0,this.sharedCompletion=h!==void 0;for(const A of o.parts)Object.freeze(A);Object.freeze(o.parts),Object.freeze(o)}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 o=!1;for(let a=0;a<this.completed.length;a+=1)if(Atomics.load(this.completed,a)!==2){o=!0;break}if(!o){this.ready=!0,this.client?.port.close();return}if(this.client){const a=this.port=this.client.port;a.onmessage=d=>{d.data?.type!=="closing"||this.port!==a||(a.close(),this.port=void 0,this.closed||this.startMaterializer().catch(h=>console.warn("This process's image reader could not start its own materializer after its line closed.",h)))},a.start(),this.ready=!0;return}return this.startMaterializer()}startMaterializer(){const o=Date.now(),a=new Worker(br,{type:"module",name:"immutable-image-materializer"}),d=this.ready;return d||(this.worker=a),a.addEventListener("error",()=>this.fail()),a.addEventListener("messageerror",()=>this.fail()),this.startup=new Promise((h,E)=>{const y=()=>{clearTimeout(I),a.removeEventListener("message",A),a.removeEventListener("error",S),a.removeEventListener("messageerror",S),this.cancelStartup=void 0},S=()=>P(new Error("The immutable image materializer could not initialize; reload to retry.")),P=M=>{y(),a.terminate(),d||(this.closed=!0,this.fail()),E(M)},A=M=>{if(M.data?.identity===this.identity){if(M.data.type==="init-error"){P(new Error(`The immutable image materializer could not initialize: ${String(M.data.error)}`));return}M.data.type==="ready"&&(console.log(`[boot-trace] ${JSON.stringify({event:"materializer-ready",at:Date.now(),ms:Date.now()-o})}`),y(),this.ready=!0,this.worker=a,h())}},I=setTimeout(()=>P(new Error("The immutable image materializer did not initialize within 10 seconds; reload to retry.")),1e4);this.cancelStartup=P,a.addEventListener("message",A),a.addEventListener("error",S),a.addEventListener("messageerror",S);try{a.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(M){P(M instanceof Error?M:new Error(String(M)))}}),this.startup}readDigests(){const o=this.firstRead;if(!o)return;const a=this.ranges.parts.length,d=[];for(let h=0;h<a;h+=1){const E=Atomics.load(o,h),y=this.ranges.parts[h];E>0&&y.raw>0&&d.push([E,y.sha256])}return d.sort((h,E)=>h[0]-E[0]).map(([,h])=>h)}completedDigests(){const o=[];for(let a=0;a<this.completed.length;a+=1){const d=this.ranges.parts[a];d.raw>0&&Atomics.load(this.completed,a)===2&&o.push(d.sha256)}return o}prefetch(o,a=[]){if(this.closed||!this.ready||!this.worker)return{queued:0,done:Promise.resolve()};const d=new Map;for(let S=0;S<this.ranges.parts.length;S+=1){const P=this.ranges.parts[S];if(P.raw===0)continue;const A=d.get(P.sha256);A?A.push(S):d.set(P.sha256,[S])}const h=[];for(const S of new Set(o))for(const P of d.get(S)??[])Atomics.load(this.completed,P)!==2&&h.push(P);const E=a.length>0&&h.length>0?Math.min(a.length,8):Math.min(Fn,Math.ceil(h.length/32)),y=[];for(let S=0;S<E;S+=1){const P=h.filter((x,T)=>T%E===S),A=new Worker(br,{type:"module",name:"immutable-image-prefetch"});this.prefetchers.push(A);let I;y.push(new Promise(x=>{I=x}));const M=()=>{A.terminate(),this.prefetchers=this.prefetchers.filter(x=>x!==A),I()};A.addEventListener("error",M),A.addEventListener("messageerror",M),A.addEventListener("message",x=>{x.data?.identity===this.identity&&(x.data.type==="ready"?A.postMessage(a.length>0?{type:"prefetch-stream",url:a[S]}:{type:"prefetch",indices:P}):(x.data.type==="prefetched"||x.data.type==="init-error")&&M())}),A.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:h.length,done:Promise.all(y).then(()=>{})}}ensure(o,a){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(a===0||o>=this.ranges.bytes)return;const d=Math.min(o+a,this.ranges.bytes);let h=0,E=this.ranges.parts.length;for(;h<E;){const y=h+E>>>1,S=this.ranges.parts[y];S.offset+S.raw<=o?h=y+1:E=y}for(let y=h;y<this.ranges.parts.length;y+=1){const S=this.ranges.parts[y];if(S.offset>=d)break;const P=this.firstRead;if(P&&Atomics.load(P,y)===0&&Atomics.compareExchange(P,y,0,Atomics.add(P,this.ranges.parts.length,1)+1),Atomics.load(this.completed,y)===2)continue;const A=this.worker??this.port;if(!A)throw new Error("This immutable image reader's line closed and its own materializer is still starting; retry the read.");A.postMessage({type:"read",index:y});const I=performance.now(),M=I+3e4;for(;Atomics.load(this.state,y)===0;){const w=M-performance.now();if(w<=0||Atomics.wait(this.state,y,0,w)==="timed-out")throw this.close(),new Error(`The image's immutable part ${S.url} did not arrive within 30 seconds; reload to retry.`)}const x=performance.now()-I,T=Ar.get(this.identity)??{ranges:0,ms:0};if(T.ranges+=1,T.ms+=x,Ar.set(this.identity,T),console.log(`[boot-trace] ${JSON.stringify({event:"image-blocked",at:Date.now(),reader:this.identity,index:y,range:S.sha256.slice(0,16),ms:Math.round(x)})}`),Atomics.load(this.state,y)!==2)throw new Error(`The image's immutable part ${S.url} could not be verified or stored; see the worker error and reload to retry.`)}}lineForReader(){const o=this.worker??this.port;if(this.closed||!this.ready||!o)return;const a=new MessageChannel,d=new SharedArrayBuffer(this.ranges.parts.length*Int32Array.BYTES_PER_ELEMENT);return o.postMessage({type:"client",port:a.port1,state:d},[a.port1]),{port:a.port2,state:d}}fail(){for(let o=0;o<this.state.length;o+=1)Atomics.compareExchange(this.state,o,0,-1)===0&&Atomics.notify(this.state,o)}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 o=this.worker;o&&(o.postMessage({type:"closing"}),setTimeout(()=>o.terminate(),250));for(const a of this.prefetchers)a.dispatchEvent(new Event("error"));this.prefetchers=[]}}const Nt="/packages",St="supercode-browser-packages",Me=new TextEncoder,He=new TextDecoder("utf-8",{fatal:!0}),xn=Pn,bt="generations",Or="atomic-staging",Ue=Tn,ne="index.json",Ht="index-log.bin",Ge="pack.bin",kt=8,Pr=64*1024*1024,Q=1024*1024*1024,Tr=10*1024*1024*1024,Mn=16*1024*1024*1024,Rn=["/workspace","/home","/opt"],Re=0,Fr=1,Ut=1e6,Ir=8*1024*1024,xr=250,_n=64*1024*1024,vn=256*1024*1024,Mr=4*1024*1024,We=493,At=420;function Dn(m,o={}){const a=o.limits?.maxBytes??Tr,d=o.limits?.maxEntries??Ut;if(!Number.isSafeInteger(a)||a<1||a>Tr||!Number.isSafeInteger(d)||d<1||d>Ut)throw new Error("Invalid OPFS workspace limits.");let h,E=!1,y=!1,S=!1,P,A=0,I=0,M,x,T,w=new Map,C=new Ot,_,H,z,_e,Ze,me,ie=0,v,F=0;const $=new Map,G=256*1024,oe=32;let O=0,Y,q=-1/0,Ee=0,we=0,b=0,R=0,W=0,Se=0,be=0,ee,et,se,ve=!1,je,jt=Promise.resolve(),De=0,N=!1,Le=!1,U,ke=0,ae=!1;function tt(){if(!(!U||ae)){if(b>2147483647){rt();return}Atomics.store(U,Fr,b)}}function rt(){!U||ae||(ae=!0,(Atomics.load(U,Re)&1)===0&&Atomics.add(U,Re,1))}function Ye(){ke+=1,ke===1&&U&&!ae&&Atomics.add(U,Re,1)}function Ke(){ke-=1,!(ke>0||!U||ae)&&(tt(),ae||Atomics.add(U,Re,1))}function Yt(){if(y)throw new Error("A store open for reading follows its owner's clock; it has none of its own.");return U||(U=new Int32Array(new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT)),U[Re]=ke>0||ae?1:0,tt()),U.buffer}let V;const Dr=8*1024*1024;let Kt=!1;function Lr(e){if(y||!U||!T||ve||ke>0||ae||N)return;const t=Atomics.load(U,Re);if(t&1)return;if(e?.overlays&&w instanceof Ne){const i=w.boundedChanges();if(i)return Tt({generation:T,index:w.base.buffer,changes:i,packBytes:O,logBytes:b,epoch:t,liveBytes:R,linked:A,linkedBytes:I})}if(V&&V.generation===T&&V.epoch===t&&b>=V.logBytes&&b-V.logBytes<=(e?.current?0:Dr))return Tt(V);let r;try{r=Sr(w,zr())}catch(i){console.warn(`[pack-store] no reader seed: ${i instanceof Error?i.message:String(i)}`);return}return V={generation:T,index:r,packBytes:O,logBytes:b,epoch:t,liveBytes:R,linked:A,linkedBytes:I},Cr(r),Tt(V)}function Tt(e){const t=o.packages?.imageCompletionSeed();return t?{...e,packagesImage:t}:e}function Br(){if(!(!z||!H||!T||ve||ke>0||N))return{generation:T,rangesDigest:H,completed:z.completionBuffer,...z.receiptKey?{metadata:{ranges:z.verifiedRanges,receiptKey:z.receiptKey}}:{}}}function Cr(e){const t=[];if(w instanceof Ne)for(const[i,n]of w.changed())n.capacity!==void 0&&t.push([i,n]);else for(const[i,n]of w)n.capacity!==void 0&&t.push([i,n]);const r=new Ie(e);w=new Ne(r),C=new Et(r);for(const[i,n]of t)w.set(i,n)}function zr(){if(C instanceof Ot)return C.map;const e=new Map;for(const t of w.keys()){const r=Te(t);if(r===t)continue;let i=e.get(r);i||(i=new Set,e.set(r,i)),i.add(t.slice(r.length+1))}return e}function $r(){!y||S||N||!v||at(b)}async function nt(e){if(N)throw new Error("This OPFS workspace is closing.");De+=1;let t,r=!1;try{return await e()}catch(i){throw r=!0,t=i,i}finally{if(De-=1,N&&De===0)try{gr()}catch(i){throw r?new AggregateError([t,i],"OPFS operation and deferred close both failed."):i}}}async function it(e){return ue(),De!==0?Promise.reject(new Error("Wait for the current OPFS storage operation before replacing its generation.")):(Le=!0,nt(async()=>{try{return await e()}finally{Le=!1}}))}function Nr(e){if(N)throw new Error("This OPFS workspace is closing.");const t=w.get(e);if(!t||t.type==="directory")throw new Error(`OPFS workspace file does not exist: ${e}`);return ot(t)}function Hr(e,t,r){if(N)throw new Error("This OPFS workspace is closing.");const i=w.get(e);if(!i||i.type==="directory")throw new Error(`OPFS workspace file does not exist: ${e}`);const n=Math.min(Math.max(0,t),i.length),s=Math.min(Math.max(0,r),i.length-n);if(i.pack){const c=o.packages;if(!c)throw new Error("This store has no shared package store to read from.");return c.readExtent(i.offset+n,s)}return st(i.offset+n,s)}function ot(e){if(e.pack){const t=o.packages;if(!t)throw new Error("This store has no shared package store to read from.");return t.readExtent(e.offset,e.length)}return st(e.offset,e.length)}function st(e,t){if(N)throw new Error("This OPFS workspace is closing.");const r=_;if(!r)throw new Error("OPFS filesystem worker is not initialized.");const i=new Uint8Array(t);if(t>0&&t<=G&&e>=0&&e+t<=F){let n=0;for(;n<t;){const s=e+n,c=Math.floor(s/G)*G;let f=$.get(c);if(!f&&(f=new Uint8Array(Math.min(G,F-c)),z?.ensure(c,f.byteLength),r.read(f,{at:c})!==f.byteLength))throw new Error("An OPFS package range could not be read completely.");$.delete(c),$.set(c,f),$.size>oe&&$.delete($.keys().next().value);const l=s-c,u=Math.min(t-n,f.byteLength-l);i.set(f.subarray(l,l+u),n),n+=u}return i}if(z?.ensure(e,t),t>0&&r.read(i,{at:e})!==t)throw new Error("An OPFS workspace file could not be read completely.");return i}async function Ur(e,t={}){if(N&&h||!h&&De!==0)throw new Error("Wait for this OPFS workspace to finish closing before opening it again.");if(ve)throw new Error("This OPFS store is already opening a workspace.");if(h){if(x!==Vt(e))throw new Error("Close this OPFS store before opening another workspace.");return w.size>0}ve=!0,N=!1;const r=new AbortController;je=r;try{w=new Map,C=new Ot,T=void 0,H=void 0,P=void 0,ee=void 0,se=void 0,O=b=R=W=A=I=0,fe=void 0,Se=be=Ee=we=0,q=-1/0,x=Vt(e),y=t.readOnly===!0,Ze=y?t.imageCompletion:void 0,me=y?t.imageLine:void 0,S=y&&t.extentsOnly===!0,E=t.shared===!0||y,E||await Kr(r.signal),r.signal.throwIfAborted();const i=await Wr();r.signal.throwIfAborted();try{const c=await i.getDirectoryHandle(xn,{create:!y});r.signal.throwIfAborted(),h=await c.getDirectoryHandle(x,{create:!y})}catch(c){if(r.signal.throwIfAborted(),y&&$e(c))return!1;throw c}r.signal.throwIfAborted();let n=gt(await Pe(h,Ue));if(r.signal.throwIfAborted(),!n&&y)return await It(),!1;if(!n&&E&&(await m.navigator.locks.request(St,{mode:"exclusive",signal:r.signal},async()=>{r.signal.throwIfAborted(),n=gt(await Pe(h,Ue)),r.signal.throwIfAborted(),n||(await It(),await ir({files:[],pack:new ArrayBuffer(0)}),await Bn(h))}),r.signal.throwIfAborted(),!n))return P=await ce(T,!1),r.signal.throwIfAborted(),!1;if(!n)return await It(),r.signal.throwIfAborted(),!1;const s=async c=>{let f;try{f=await ce(c.generation,!1)}catch(g){throw r.signal.throwIfAborted(),$e(g)?new Error("The committed OPFS workspace generation is missing. Stored generations were retained.",{cause:g}):g}if(r.signal.throwIfAborted(),T=c.generation,ie=c.initializedAt,H=c.imageRanges,P=f,S)return x===xe&&m.navigator.locks?await m.navigator.locks.request(St,{mode:"shared",signal:r.signal},async()=>{await Be(f),F=_.getSize()}):await Be(f),r.signal.throwIfAborted(),!0;const l=y?t.seed:void 0;if(l&&l.generation===c.generation){const g=new Ie(l.index);return w=new Ne(g),C=new Et(g),O=l.packBytes,l.changes&&qt({packBytes:l.packBytes,changes:l.changes}),await Be(f),r.signal.throwIfAborted(),b=l.logBytes,{liveBytes:R,linked:A,linkedBytes:I}=l,W=Math.max(0,O-R),Kt=!0,w.size>0}const u=y?void 0:await un(f);if(r.signal.throwIfAborted(),u){const g=new Ie(u.index);w=new Ne(g),C=new Et(g),{packBytes:O,liveBytes:R,linked:A,linkedBytes:I}=u;const p=Atomics.load(new Int32Array(Yt()),Re);V={generation:T,index:u.index,packBytes:O,liveBytes:R,linked:A,linkedBytes:I,logBytes:0,epoch:p}}else w=Bt(await Pe(f,ne)),r.signal.throwIfAborted(),ze(),O=Ft(w);await Be(f),r.signal.throwIfAborted();const k=u?await yn(u):0;return r.signal.throwIfAborted(),k&&(fe={generation:T,bytes:k},V&&(V.logBytes=k)),at(k,!!u),u?W=Math.max(0,O-R):Je(),rr(),E&&!y&&!u&&w.size>=1e4&&(pe(),await Xe(f,w,{access:v,bytes:b,packBytes:O})),E||(_.truncate(O),await cr(h,Or,!0),await xt(T),r.signal.throwIfAborted(),W>_n&&W>R&&await nn()),r.signal.throwIfAborted(),w.size>0};return E&&!y?await m.navigator.locks.request(St,{mode:"exclusive",signal:r.signal},async()=>{if(n=gt(await Pe(h,Ue)),!n)throw new Error("The committed package store state is missing. Stored data was retained.");return s(n)}):await s(n)}catch(i){const n=[i];try{Ce()}catch(s){n.push(s)}try{M?.()}catch(s){n.push(s)}throw M=void 0,h=void 0,n.length>1?new AggregateError(n,"OPFS workspace open and cleanup failed."):i}finally{ve=!1,je=void 0}}function Gr(e){return nt(()=>Jt(e?.whole===!0))}async function Jt(e=!1){if(S)throw new Error("A store opened for its extents alone has no index to follow.");if(y&&h){const s=gt(await Pe(h,Ue));if(!s)throw new Error("The committed OPFS workspace state is missing. Stored data was retained.");if(s.generation!==T||e){const c=await ce(s.generation,!1),f=Bt(await Pe(c,ne));O=Ft(f),s.generation!==T&&(T=s.generation,ie=s.initializedAt,H=s.imageRanges,await Be(c)),T=s.generation,P=c,w=f,ze(),at(),Je();return}}const t=v;if(!t||!P)return;const r=t.getSize();let i=!1;r<b&&(w=Bt(await Pe(P,ne)),ze(),O=Ft(w),b=0,i=!0);const n=b;at(b),(i||b!==n)&&Je()}async function Wr(){let e;for(let t=0;t<10;t+=1){je?.signal.throwIfAborted();try{return await m.navigator.storage.getDirectory()}catch(r){e=r,await new Promise(i=>setTimeout(i,200))}}throw e instanceof Error?e:new Error("This browser workspace's storage is unavailable.")}const jr=1e4;async function K(e,t){let r;const i=je?.signal;for(let s=0;s<2;s+=1){i?.throwIfAborted();const c=e.createSyncAccessHandle({mode:"readwrite-unsafe"});let f,l,u=!1;try{const k=new Promise((p,L)=>{l=()=>L(i?.reason??new DOMException("Workspace open was cancelled.","AbortError")),i?.addEventListener("abort",l,{once:!0}),i?.aborted&&l()}),g=await Promise.race([c.then(p=>({access:p})).catch(p=>{r=p}),new Promise(p=>{f=setTimeout(()=>p(void 0),jr)}),k]);if(i?.throwIfAborted(),g)return u=!0,g.access}finally{f!==void 0&&clearTimeout(f),l&&i?.removeEventListener("abort",l),u||c.then(k=>k.close(),()=>{}).catch(k=>console.error("Late workspace handle cleanup failed.",k))}if(r 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). ${r.message}`);await new Promise(k=>setTimeout(k,500))}const n=r instanceof Error?` (${r.message})`:"";throw new Error(`This browser workspace's ${t} is held by another page${n}.`)}async function Be(e){Ce();const t=await e.getFileHandle(Ge);_=await K(t,"store");try{if(_.getSize()<O)throw new Error("The committed OPFS workspace pack is incomplete. Stored data was retained.");const r=await e.getFileHandle(Ht);if(v=await K(r,"record of changes"),b=v.getSize(),H){const i=Ze,n=i&&i.generation===T&&i.rangesDigest===H?i:void 0;let s,c;if(n?.metadata){if(s=$t(n.metadata.ranges),c=n.metadata.receiptKey,!/^[a-f0-9]{64}$/u.test(c))throw new Error("The owner's immutable receipt key is invalid.")}else{const l=await(await e.getFileHandle(kr)).getFile(),u=new Uint8Array(await l.arrayBuffer());if(await de(u)!==H)throw new Error("The committed immutable image ranges have changed. Stored data was retained.");s=$t(JSON.parse(He.decode(u))),c=await de(Me.encode(JSON.stringify(s)))}if(s.bytes>_.getSize())throw new Error("The immutable image reservation is incomplete. Stored data was retained.");const f=n?me:void 0;f||me?.port.close(),me=void 0,z=new In(s,e,`${x}.${T}`,n?.completed,c,f),console.log(`[boot-trace] ${JSON.stringify({event:"image-reader-open",at:Date.now(),reader:`${x}.${T}`,offered:i!==void 0,shared:n!==void 0,...i&&!n?{offeredGeneration:i.generation,generation:T,rangesMatch:i.rangesDigest===H}:{}})}`),await z.initialize(),_e=s.image}}catch(r){throw Ce(),r}}function Ce(){z?.close(),z=void 0,_e=void 0;const e=_,t=v;_=void 0,v=void 0,b=0,F=0,$.clear();try{e?.close()}finally{t?.close()}}function at(e=0,t=!1){const r=v;if(!r)throw new Error("OPFS filesystem worker is not initialized.");const i=r.getSize();if(i<=e){b=i;return}const n=new Uint8Array(i-e);if(r.read(n,{at:e})!==n.byteLength)throw new Error("The OPFS workspace index log could not be read.");const s=_?.getSize()??1/0,c=new DataView(n.buffer);let f=0;const l=n.byteLength;for(;f+kt<=l;){const u=c.getUint32(f,!0),k=c.getUint32(f+4,!0),g=f+kt;if(u===0||u>Pr||g+u>l)break;const p=n.subarray(g,g+u);if(ur(p)!==k)break;let L;try{L=mn(JSON.parse(He.decode(p)))}catch{break}if(L.packBytes>s)break;qt(L,t),f=g+u}f!==l&&!E&&r.truncate(e+f),b=e+f}function qt(e,t=!1){for(const[r,i]of e.changes){const n=w.get(r);if(i&&vr(n,i)){ft(r);continue}t&&(n?.pack?(A-=1,I-=n.length):n&&(R-=n.length),i?.pack?(A+=1,I+=i.length):i&&(R+=i.length)),i===null?(w.delete(r),Qt(r)):(w.set(r,i),ft(r))}O=Math.max(O,e.packBytes)}function Je(){R=0,A=0,I=0;for(const e of w.values())e.pack?(A+=1,I+=e.length):R+=e.length;W=Math.max(0,O-R)}function Ft(e){let t=0;for(const r of e.values())r.pack||(t=Math.max(t,r.offset+r.length));return t}const Yr=5e3;async function Kr(e){if(!m.navigator.locks)return;if(!x)throw new Error("OPFS filesystem project is not initialized.");const t=new AbortController,r=setTimeout(()=>t.abort(),Yr);try{await new Promise((i,n)=>{m.navigator.locks.request(`supercode-browser-filesystem-${x}`,{mode:"exclusive",signal:e?AbortSignal.any([e,t.signal]):t.signal},async()=>{clearTimeout(r),i(),await new Promise(s=>{M=s})}).catch(()=>n(e?.aborted?e.reason:new Error("This browser workspace is already open in another tab.")))})}finally{clearTimeout(r)}}function Vt(e){if(typeof e!="string"||!/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/u.test(e))throw new Error("OPFS filesystem projectId is invalid.");return e}async function Ae(){if(!h)throw new Error("OPFS filesystem worker is not initialized.");return h}async function ce(e,t){return(await(await Ae()).getDirectoryHandle(bt,{create:t})).getDirectoryHandle(e,{create:t})}async function It(){let e;try{e=await(await Ae()).getDirectoryHandle(bt)}catch(t){if($e(t))return;throw t}for await(const t of e.entries())throw new Error("OPFS workspace state is missing but stored generations exist. Stored data was retained.")}async function xt(e){const t=await Ae();let r;try{r=await t.getDirectoryHandle(bt)}catch(i){if($e(i))return;throw i}for await(const[i]of r.entries())i!==e&&await fr(r,i)}function ue(){if(N)throw new Error("This OPFS workspace is closing.");if(Le)throw new Error("This OPFS workspace is replacing its generation; wait for that operation before writing.");if(y)throw new Error("This store is open for reading; its owner writes it.");if(se)throw se}async function Jr(e){yr(e)}let Mt=!1,ct=0,fe,Rt=!1;function Xt(){if(ct>0)return;const e=fe&&fe.generation===T&&fe.bytes<=b?fe.bytes:0;b-e>Ir&&!Mt&&(Mt=!0,(E?m.navigator.locks.request(St,{mode:"exclusive"},async()=>{if(!h||N)return;await Jt();const r=fe,i=r&&r.generation===T&&r.bytes<=b?r.bytes:0;b-i>Ir&&await wt()}):wt()).catch(r=>console.error("The workspace's log could not be checkpointed; it is replayed at the next open.",r)).finally(()=>{Mt=!1})),!E&&!Rt&&W>vn&&W>R&&(Rt=!0,nt(on).catch(t=>console.error("The workspace could not be compacted; it keeps its generation.",t)).finally(()=>{Rt=!1}))}async function qr(e){ue(),ct+=1;try{return await e()}finally{ct-=1,ct===0&&!N&&h&&Xt()}}function Vr(e,t){const r=he(e.path);if(e.operation==="write"){if(w.get(r)?.type==="directory")throw new Error(`OPFS write target is a directory: ${r}`);if(!(e.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const n=e.content;if(n.byteLength>Q)throw new Error(`${r} is ${n.byteLength} bytes; an OPFS workspace file holds at most ${Q}.`);lt(r,n.byteLength),Oe(r,t);const s=ht(n);J(r,{type:e.symlink?"symlink":"file",mode:e.mode??w.get(r)?.mode??At,mtimeMs:e.mtimeMs??Date.now(),offset:s,length:n.byteLength},t);return}if(e.operation==="append"){const n=w.get(r);if(n&&n.type!=="file")throw new Error(`OPFS append target is not a file: ${r}`);if(!(e.content instanceof Uint8Array))throw new Error("OPFS append requires file content.");const s=e.content,c=(n?.length??0)+s.byteLength;if(c>Q)throw new Error(`${r} is ${c} bytes; an OPFS workspace file holds at most ${Q}.`);lt(r,c),Oe(r,t);const f=e.mode??n?.mode??At,l=e.mtimeMs??Date.now(),u=n&&!n.pack?n.capacity??n.length:0;if(x!==xe&&n&&!n.pack&&n.length>0&&(c<=u||n.offset+u===O)){dt(n.offset+n.length,s),J(r,{...n,mode:f,mtimeMs:l,length:c,capacity:Math.max(u,c)},t),W-=Math.max(n.length,n.capacity??0),Se-=1,be-=n.length;return}const k=new Uint8Array(c);n&&n.length>0&&k.set(ot(n),0),k.set(s,c-s.byteLength);const g=ht(k),p=Math.min(Q,Math.max(c,c*2,64*1024));p>c&&nr(g+p),J(r,{type:"file",mode:f,mtimeMs:l,offset:g,length:c,capacity:p},t);return}if(e.operation==="write-at"){const n=w.get(r);if(n&&n.type!=="file")throw new Error(`OPFS write target is not a file: ${r}`);if(!(e.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const s=e.content,c=e.position,f=n?.length??0;if(s.byteLength===0&&n)return;const l=s.byteLength===0?f:Math.max(f,c+s.byteLength);if(l>Q)throw new Error(`${r} is ${l} bytes; an OPFS workspace file holds at most ${Q}.`);lt(r,l),Oe(r,t);const u=e.mode??n?.mode??At,k=e.mtimeMs??Date.now(),g=n&&!n.pack?n.capacity??n.length:0;if(x!==xe&&n&&!n.pack&&f>0&&(l<=g||n.offset+g===O)){if(c>f&&dt(n.offset+f,new Uint8Array(c-f)),et&&c<f){const X=Math.min(f,c+s.byteLength);et.push([n.offset+c,st(n.offset+c,X-c)])}dt(n.offset+c,s),J(r,{...n,mode:u,mtimeMs:k,length:l,capacity:Math.max(g,l)},t),l!==f&&(W-=Math.max(n.length,n.capacity??0),Se-=1,be-=n.length);return}const p=new Uint8Array(l);n&&f>0&&p.set(ot(n),0),s.byteLength>0&&p.set(s,c);const L=ht(p),B=Math.min(Q,Math.max(l,l*2,64*1024));B>l&&nr(L+B),J(r,{type:"file",mode:u,mtimeMs:k,offset:L,length:l,capacity:B},t);return}if(e.operation==="mkdir"){Oe(r,t);const n=w.get(r);if(n&&n.type!=="directory")throw new Error(`OPFS path is a file: ${r}`);J(r,{type:"directory",mode:e.mode??n?.mode??We,mtimeMs:e.mtimeMs??n?.mtimeMs??Date.now(),offset:0,length:0},t);return}if(e.operation==="remove"){vt(r,t),ye().includes(r)&&J(r,{type:"directory",mode:We,mtimeMs:Date.now(),offset:0,length:0},t);return}if(e.operation==="link"){Xr(r,tr(e.source),t);return}if(e.operation==="rename"){Qr(r,he(e.destination),t);return}const i=w.get(r);if(!i)throw new Error(`OPFS metadata target does not exist: ${r}`);J(r,{...i,mode:e.mode??i.mode,mtimeMs:e.mtimeMs??i.mtimeMs},t)}function J(e,t,r){const i=w.get(e);ee&&!ee.has(e)&&ee.set(e,i);const n=i!==void 0&&i.type===t.type&&i.offset===t.offset&&i.length===t.length&&i.pack===t.pack;i&&!n&&(Zt(i),i.type!=="directory"&&t.type!=="directory"&&i.length>0&&!i.pack&&(Se+=1,be+=i.length)),w.set(e,t),ft(e),n||(t.pack?(A+=1,I+=t.length):R+=t.length),r.push([e,t])}function ft(e){const t=Te(e);t!==e&&C.mutable(t).add(e.slice(t.length+1))}function Qt(e){const t=Te(e);C.get(t)?.has(e.slice(t.length+1))&&C.mutable(t).delete(e.slice(t.length+1)),C.delete(e)}function ze(){C=new Ot;for(const e of w.keys())ft(e)}function _t(e){const t=[],r=i=>{const n=w.get(i);if(!n)return;t.push([i,n]);const s=C.get(i);if(s)for(const c of s)r(`${i}/${c}`)};return r(e),t}function Zt(e,t){if(e.pack){A-=1,I-=e.length;return}R-=e.length,W+=Math.max(e.length,e.capacity??0)}function er(e,t){const r=w.get(e);r&&(ee&&!ee.has(e)&&ee.set(e,r),w.delete(e),Qt(e),Zt(r),t.push([e,null]))}function Xr(e,t,r){const i=o.packages;if(!i)throw new Error("This store has no shared package store to link from.");const n=tr(t),s=i.descendants(n);if(s.length===0)throw new Error(`The shared package store does not hold ${t}.`);Oe(e,r),vt(e,r),le(w.size+s.length);for(const[c,f]of s){const l=c===n?e:`${e}${c.slice(n.length)}`;J(l,f.type==="directory"?{type:"directory",mode:f.mode,mtimeMs:f.mtimeMs,offset:0,length:0}:{type:f.type,mode:f.mode,mtimeMs:f.mtimeMs,offset:f.offset,length:f.length,pack:xe},r)}}function Oe(e,t){const r=Te(e);if(r!==e&&w.get(r)?.type==="directory"){le(w.size+(w.has(e)?0:1));return}const i=[];let n=qe(e)??ye()[0];if(w.has(n)||i.push(n),e!==n)for(const c of Ct(hr(Te(e)))){n=`${n}/${c}`;const f=w.get(n);if(f&&f.type!=="directory")throw new Error(`OPFS path parent is a file: ${n}`);f||i.push(n)}le(w.size+i.length+(w.has(e)?0:1));const s=Date.now();for(const c of i)J(c,{type:"directory",mode:We,mtimeMs:s,offset:0,length:0},t)}function vt(e,t){for(const[r]of _t(e))er(r,t)}function Qr(e,t,r){if(e===t)return;if(t.startsWith(`${e}/`))throw new Error("An OPFS rename cannot move a directory into itself.");const i=_t(e);if(i.length===0){if(w.has(t))return;throw new Error(`OPFS rename source does not exist: ${e}`)}Oe(t,r),vt(t,r);for(const[n]of i)er(n,r);for(const[n,s]of i)J(`${t}${n.slice(e.length)}`,s,r);le(w.size)}function tr(e){if(typeof e!="string"||!e.startsWith(`${Nt}/`)||e.includes("\0")||e.length>4096)throw new Error("Invalid shared store path.");return Ct(e.slice(Nt.length+1)),e}function ye(){return x===xe?[Nt]:Rn}function qe(e){return ye().find(t=>e===t||e.startsWith(`${t}/`))}function lt(e,t){const r=w.get(e),i=r&&!r.pack?r.length:0,n=E?Mn:a;if(R-i+t>n){const s=E?"the origin's shared packages":"the project's own files";throw new Error(`OPFS workspace exceeds its byte limit: writing ${e} (${t} bytes) would take ${s} past ${n} bytes (${R} bytes held, ${i} replaced).`)}}function le(e){if(e>d)throw new Error("OPFS workspace exceeds its entry limit.")}function rr(){if(le(w.size),R>a)throw new Error(`OPFS workspace exceeds its byte limit: the project's own files hold ${R} bytes, past ${a}.`)}function dt(e,t){const r=_;if(!r)throw new Error("OPFS filesystem worker is not initialized.");let i=0;for(;i<t.byteLength;){const n=r.write(t.subarray(i),{at:e+i});if(n<=0)throw new Error("An OPFS workspace file could not be written completely.");i+=n}O=Math.max(O,e+t.byteLength)}function nr(e){const t=_;if(!t)throw new Error("OPFS filesystem worker is not initialized.");e<=O||(t.truncate(e),O=e)}function ht(e){const t=_;if(!t)throw new Error("OPFS filesystem worker is not initialized.");const r=O;let i=0;for(;i<e.byteLength;){const n=t.write(e.subarray(i),{at:r+i});if(n<=0)throw new Error("An OPFS workspace file could not be written completely.");i+=n}return O=r+e.byteLength,r}function Zr(e){const t=_;if(t.getSize()>=O&&e.getSize()>=b)return;t.flush(),e.flush();const r=t.getSize(),i=e.getSize();if(!(r>=O&&i>=b))throw Object.assign(new Error(`This browser is keeping less than the tab wrote (the store's pack holds ${r} of ${O} bytes, its log ${i} of ${b}): its storage is full, as a private window's is well below its quota.`),{name:"QuotaExceededError",code:"ENOSPC"})}function en(e,t={}){const r=v;if(!r||!_)throw new Error("OPFS filesystem worker is not initialized.");if(e.length===0)return;const i=Me.encode(JSON.stringify({packBytes:O,changes:e}));if(i.byteLength>Pr)throw new Error("An OPFS workspace index record exceeds its size limit.");const n=new Uint8Array(kt+i.byteLength),s=new DataView(n.buffer);s.setUint32(0,i.byteLength,!0),s.setUint32(4,ur(i),!0),n.set(i,kt);let c=0;for(;c<n.byteLength;){const f=r.write(n.subarray(c),{at:b+c});if(f<=0)throw new Error("The OPFS workspace index log could not be written completely.");c+=f}b+=n.byteLength,Zr(r),t.publish!==!1&&tt(),performance.now()-q>=xr?pe():Y===void 0&&(Y=setTimeout(pe,xr))}function pe(){if(Y!==void 0&&(clearTimeout(Y),Y=void 0),se)throw se;const e=performance.now();_?.flush(),v?.flush(),q=performance.now(),Ee+=1,we+=q-e}function wt(){const e=jt,t=nt(()=>e.catch(()=>{}).then(tn));return jt=t,t}async function tn(){if(ue(),!T)return;const e=T,t=v,r=await ce(e,!1);if(!t||t!==v||e!==T)throw new Error("OPFS workspace changed generations before its checkpoint could start.");pe();const i=b;if(await Xe(r,w,{access:t,bytes:i,packBytes:O}),e===T&&(fe={generation:e,bytes:i}),t===v&&e===T&&i===b){Ye();try{t.truncate(0),t.flush(),b=0,fe={generation:e,bytes:0}}finally{Ke()}}}function ir(e){return it(()=>rn(Dt(e)))}async function rn(e){const t=crypto.randomUUID(),r=await ce(t,!0),i=await r.getFileHandle(Ge,{create:!0}),n=await K(i,"store"),s=new Map;let c=0;try{for(const l of e.files){let u=0,k=0;if(l.type!=="directory"){const g=new Uint8Array(e.pack,l.offset??0,l.length??0);u=c,k=g.byteLength;let p=0;for(;p<k;){const L=n.write(g.subarray(p),{at:u+p});if(L<=0)throw new Error("An OPFS workspace file could not be written completely.");p+=L}c+=k}s.set(l.path,{type:l.type,mode:l.mode??(l.type==="directory"?We:At),mtimeMs:l.mtimeMs??Date.now(),offset:u,length:k})}for(const l of ye())s.has(l)||s.set(l,{type:"directory",mode:We,mtimeMs:Date.now(),offset:0,length:0});le(s.size),n.truncate(c),n.flush()}finally{n.close()}const f=await Xe(r,s);await ut(t,r,s,c,f)}async function nn(){await or(()=>!0)}async function on(){let e=!1,t=!1,r=!1;try{await sn(()=>{e=!0},()=>{t=!0},()=>{r=!0})}finally{e&&(t||r)?Ke():e&&rt()}}async function sn(e,t,r){const i=crypto.randomUUID(),n=await ce(i,!0),s=await K(await n.getFileHandle(Ge,{create:!0}),"store");let c,f=!1;try{c=await K(await n.getFileHandle(Ht,{create:!0}),"record of changes"),c.truncate(0);const l=new Uint8Array(Mr);let u=0;const k=D=>{if(D.pack)return{...D};if(D.type==="directory"||D.length===0)return{...D,offset:0,length:0};const j=_;if(!j)throw new Error("OPFS filesystem worker is not initialized.");const Fe=u;let te=0;for(;te<D.length;){const Qe=Math.min(l.byteLength,D.length-te),mr=l.subarray(0,Qe);if(z?.ensure(D.offset+te,Qe),j.read(mr,{at:D.offset+te})!==Qe)throw new Error("An OPFS workspace file could not be read completely.");let mt=0;for(;mt<Qe;){const Er=s.write(mr.subarray(mt),{at:Fe+te+mt});if(Er<=0)throw new Error("An OPFS workspace file could not be written completely.");mt+=Er}te+=Qe}u+=D.length;const{capacity:zt,...bn}=D;return{...bn,offset:Fe}},g=new Map;let p=performance.now();for(const[D,j]of[...w]){if(N||Le)return;w.get(D)===j&&(g.set(j,k(j)),performance.now()-p>8&&(await new Promise(Fe=>setTimeout(Fe,0)),p=performance.now()))}if(N||Le||!_||!v)return;Ye(),e();const L=new Map;for(const[D,j]of w)L.set(D,g.get(j)??k(j));s.truncate(u),s.flush(),c.flush(),pe();const B={pack:_,log:v};_=s,v=c,b=0,w=L,ze(),O=u,T=i,P=n,Je(),f=!0;const X=new Map(L);try{B.pack.close()}finally{B.log.close()}try{await Xe(n,X);const D={storageVersion:4,generation:i,initializedAt:Date.now()};await Ve(await Ae(),Ue,D)}catch(D){throw se=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:D}),se}t(),await xt(i)}finally{if(!f){r();try{s.close()}finally{c?.close()}await fr(await(await Ae()).getDirectoryHandle(bt),i)}}}async function an(e){ue(),Ye();try{await cn(e)}finally{Ke()}}async function cn(e){let t=!1;for(const[r,i]of w){if(!i.pack||i.length===0)continue;const n=e.get(i.offset);if(n===void 0)throw new Error(`The shared store no longer holds the bytes of ${r}.`);n!==i.offset&&(w.set(r,{...i,offset:n}),t=!0)}t&&await wt()}function or(e){return it(()=>fn(e))}async function fn(e){const t=_;if(!t)throw new Error("OPFS filesystem worker is not initialized.");const r=new Map,i=crypto.randomUUID(),n=await ce(i,!0),s=await n.getFileHandle(Ge,{create:!0}),c=await K(s,"store"),f=new Map,l=new Uint8Array(Mr);let u=0;try{for(const[g,p]of w){if(!e(g,p))continue;if(p.pack){f.set(g,{...p});continue}if(p.type==="directory"||p.length===0){f.set(g,{...p,offset:0,length:0});continue}const L=u;r.set(p.offset,L);let B=0;for(;B<p.length;){const j=Math.min(l.byteLength,p.length-B),Fe=l.subarray(0,j);if(z?.ensure(p.offset+B,j),t.read(Fe,{at:p.offset+B})!==j)throw new Error("An OPFS workspace file could not be read completely.");let te=0;for(;te<j;){const zt=c.write(Fe.subarray(te),{at:L+B+te});if(zt<=0)throw new Error("An OPFS workspace file could not be written completely.");te+=zt}B+=j}u+=p.length;const{capacity:X,...D}=p;f.set(g,{...D,offset:L,length:p.length})}c.truncate(u),c.flush()}finally{c.close()}const k=await Xe(n,f);return await ut(i,n,f,u,k),r}async function ut(e,t,r,i,n,s){Ye();try{await ln(e,t,r,i,n,s)}finally{Ke()}}async function ln(e,t,r,i,n,s){const c=await t.getFileHandle(Ht,{create:!0}),f=await K(c,"record of changes");try{f.truncate(0),f.flush()}finally{f.close()}const l={storageVersion:s?5:4,generation:e,initializedAt:Date.now(),...s?{imageRanges:s}:{}};if(await Ve(await Ae(),Ue,l),Ce(),T=e,ie=l.initializedAt,H=s,n){const u=new Ie(n.index);w=new Ne(u),C=new Et(u),V=void 0}else w=r,ze();O=i,P=t,await Be(t),n?({liveBytes:R,linked:A,linkedBytes:I}=n,W=Math.max(0,O-R)):Je(),E||await xt(e)}async function dn(e,t,r,i,n=!1){if(ue(),!E||x!==xe)throw new Error("Only the shared package store can reserve immutable image extents.");if(O!==0||[...w.values()].some(g=>g.type!=="directory"))return!1;const s=$t(i);if(s.bytes!==e.packBytes||e.entries>Ut||e.liveBytes>e.packBytes||t.byteLength!==e.json.raw||r.byteLength!==e.binary.raw||!await pt(t,e.json.sha256,n)||!await pt(r,e.binary.sha256,n))throw new Error("The image's prepared metadata does not match its document.");const c=t.subarray(0,4096).indexOf(10);if(c<0)throw new Error("The prepared index has no bounded retained header.");const f=JSON.parse(`${He.decode(t.subarray(0,c-1))}}`),l={packBytes:e.packBytes,liveBytes:e.liveBytes,linked:0,linkedBytes:0},u=f.retainedIndex;if(u.version!==1||u.digest!==await sr(e.binary.sha256,l)||u.packBytes!==l.packBytes||u.liveBytes!==l.liveBytes||u.linked!==0||u.linkedBytes!==0)throw new Error("The prepared index's retained measures are inconsistent.");const k=new SharedArrayBuffer(r.byteLength);if(new Uint8Array(k).set(r),new Ie(k).entryCount!==e.entries)throw new Error("The prepared index has the wrong number of entries.");return it(async()=>{const g=crypto.randomUUID(),p=await ce(g,!0),L=await p.getFileHandle(Ge,{create:!0}),B=await K(L,"immutable image reservation");try{B.truncate(e.packBytes),B.flush()}finally{B.close()}const X=Me.encode(JSON.stringify(s));return await ge(p,kr,X),await ge(p,yt,r),await ge(p,ne,t),await ut(g,p,new Map,e.packBytes,{index:k,...l},await de(X)),!0})}async function hn(e,t,r,i=!1,n){if(ue(),E||!o.packages||!n&&!o.packages.deferredImage)throw new Error("Prepared project paths require a verified shared image.");if(O!==0||[...w.values()].some(u=>u.type!=="directory"))return!1;if(t.byteLength!==e.json.raw||r.byteLength!==e.binary.raw||!await pt(t,e.json.sha256,i)||!await pt(r,e.binary.sha256,i))throw new Error("The image's prepared project does not match its descriptor.");const s=t.subarray(0,4096).indexOf(10);if(s<0)throw new Error("The prepared project has no bounded retained header.");const c=JSON.parse(`${He.decode(t.subarray(0,s-1))}}`).retainedIndex,f={packBytes:0,liveBytes:0,linked:e.linked,linkedBytes:e.linkedBytes};if(c.version!==1||c.digest!==await sr(e.binary.sha256,f)||c.packBytes!==0||c.liveBytes!==0||c.linked!==e.linked||c.linkedBytes!==e.linkedBytes)throw new Error("The prepared project's retained measures are inconsistent.");const l=new SharedArrayBuffer(r.byteLength);if(new Uint8Array(l).set(r),new Ie(l).entryCount!==e.entries||e.entries>d)throw new Error("The prepared project has invalid entry bounds.");return it(async()=>{const u=crypto.randomUUID(),k=await ce(u,!0),g=await k.getFileHandle(Ge,{create:!0}),p=await K(g,"prepared project");try{p.truncate(0),p.flush()}finally{p.close()}if(await ge(k,yt,r),await ge(k,ne,t),n&&!await n)return!1;if(!o.packages?.deferredImage)throw new Error("Prepared project paths require a verified shared image.");return await ut(u,k,new Map,0,{index:l,...f}),!0})}async function wn(){if(N)throw new Error("This OPFS workspace is closing.");if(!_)throw new Error("OPFS filesystem worker is not initialized.");const e=[],t=[...w.keys()].sort((c,f)=>wr(c)-wr(f)||(c<f?-1:1));let r=0;for(const c of w.values())c.type!=="directory"&&(r+=c.length);const i=new ArrayBuffer(r),n=new Uint8Array(i);let s=0;for(const c of t){const f=w.get(c);if(f.type==="directory"){e.push({path:c,type:"directory",mode:f.mode,mtimeMs:f.mtimeMs});continue}f.length>0&&n.set(ot(f),s),e.push({path:c,type:f.type,offset:s,length:f.length,mode:f.mode,mtimeMs:f.mtimeMs}),s+=f.length}for(const c of[...ye()].reverse())w.has(c)||e.unshift({path:c,type:"directory",mode:We,mtimeMs:Date.now()});return Dt({files:e,pack:i})}async function Ve(e,t,r){await ge(e,t,Me.encode(JSON.stringify(r)))}async function ge(e,t,r){const i=await(await Ae()).getDirectoryHandle(Or,{create:!0}),n=crypto.randomUUID(),s=await i.getFileHandle(n,{create:!0}),c=await K(s,"index");try{let f=0;for(;f<r.byteLength;){const l=c.write(r.subarray(f),{at:f});if(l<=0)throw new Error("An OPFS workspace file could not be written completely.");f+=l}c.truncate(r.byteLength),c.flush()}finally{c.close()}try{await s.move(e,t)}finally{await cr(i,n,!1)}}const yt="index.shared";async function de(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}async function pt(e,t,r){return r||await de(e)===t}function sr(e,t){const{packBytes:r,liveBytes:i,linked:n,linkedBytes:s,journalPrefix:c}=t;return de(Me.encode(`${JSON.stringify({packBytes:r,liveBytes:i,linked:n,linkedBytes:s,...c?{journalPrefix:c}:{}})}:${e}`))}async function ar(e,t){const{packBytes:r,liveBytes:i,linked:n,linkedBytes:s,journalPrefix:c}=t;return de(Me.encode(`${JSON.stringify({packBytes:r,liveBytes:i,linked:n,linkedBytes:s,...c?{journalPrefix:c}:{}})}:${await de(e)}`))}async function Xe(e,t,r){const i=gn(t);if(typeof SharedArrayBuffer>"u"||t.size<1e4){await Ve(e,ne,i);return}const n=new Map(i.entries),s=new Map,c={packBytes:r?.packBytes??0,liveBytes:0,linked:0,linkedBytes:0};for(const[L,B]of n){const X=Te(L);if(X!==L){let D=s.get(X);D||(D=new Set,s.set(X,D)),D.add(L.slice(X.length+1))}B.pack?(c.linked+=1,c.linkedBytes+=B.length):(c.liveBytes+=B.length,c.packBytes=Math.max(c.packBytes,B.offset+B.length))}let f;try{f=Sr(n,s)}catch{await Ve(e,ne,i);return}const l=JSON.stringify(i.entries),u=r?new Uint8Array(r.bytes):void 0;if(u&&r.access.read(u,{at:0})!==u.byteLength)throw new Error("The checkpoint's journal prefix could not be read completely.");const k=u?{bytes:u.byteLength,digest:await de(u)}:void 0,g=new Uint8Array(f).slice(),p={version:k?2:1,digest:await ar(g,{...c,...k?{journalPrefix:k}:{}}),...c,...k?{journalPrefix:k}:{}};try{await ge(e,yt,g)}catch{await Ve(e,ne,{entries:JSON.parse(l)});return}return await ge(e,ne,Me.encode(`{"retainedIndex":${JSON.stringify(p)},
|
|
2
|
+
"entries":${l}}`)),{index:f,...c}}async function un(e){if(!(typeof SharedArrayBuffer>"u"))try{const t=await e.getFileHandle(ne),r=await K(t,"index");let i;try{const g=new Uint8Array(Math.min(512,r.getSize())),p=r.read(g,{at:0});i=He.decode(g.subarray(0,p))}finally{r.close()}const n=i.split(`
|
|
3
|
+
`,1)[0];if(!n.startsWith('{"retainedIndex":')||!n.endsWith(","))return;const s=JSON.parse(n.slice(0,-1)+"}").retainedIndex;if(s.version!==1&&s.version!==2||!/^[a-f0-9]{64}$/u.test(s.digest)||![s.packBytes,s.liveBytes,s.linked,s.linkedBytes].every(g=>Number.isSafeInteger(g)&&g>=0)||s.version===1&&s.journalPrefix!==void 0||s.version===2&&(!s.journalPrefix||!Number.isSafeInteger(s.journalPrefix.bytes)||s.journalPrefix.bytes<0||!/^[a-f0-9]{64}$/u.test(s.journalPrefix.digest)))return;const c=await e.getFileHandle(yt),f=await K(c,"index");let l;try{const g=f.getSize();if(g>256*1024*1024||(l=new Uint8Array(g),f.read(l,{at:0})!==g))return}finally{f.close()}if(await ar(l,s)!==s.digest)return;const u=new SharedArrayBuffer(l.byteLength);new Uint8Array(u).set(l);const k=new Ie(u);return le(k.entryCount),{...s,index:u}}catch{return}}async function yn(e){const t=e.journalPrefix;if(!t||!v||!_||t.bytes>v.getSize()||e.packBytes>_.getSize())return 0;const r=new Uint8Array(t.bytes);return v.read(r,{at:0})!==r.byteLength?0:await de(r)===t.digest?t.bytes:0}async function Pe(e,t){let r;try{r=await e.getFileHandle(t)}catch(s){if($e(s))return;throw s}let i;if(y){i=await(await r.getFile()).text();try{return JSON.parse(i)}catch(s){throw new Error(`Invalid OPFS workspace metadata (${t}). Stored data was retained.`,{cause:s})}}const n=await K(r,"index");try{const s=n.getSize(),c=new Uint8Array(s);if(s>0&&n.read(c,{at:0})!==s)throw new Error("An OPFS workspace file could not be read completely.");i=He.decode(c)}finally{n.close()}try{return JSON.parse(i)}catch(s){throw new Error(`Invalid OPFS workspace metadata (${t}). Stored data was retained.`,{cause:s})}}async function cr(e,t,r){try{await e.removeEntry(t,{recursive:r})}catch(i){if(!$e(i))throw i}}async function fr(e,t){try{await e.removeEntry(t,{recursive:!0})}catch{}}function lr(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid OPFS filesystem mutation.");if(e.operation!=="write"&&e.operation!=="append"&&e.operation!=="write-at"&&e.operation!=="mkdir"&&e.operation!=="remove"&&e.operation!=="rename"&&e.operation!=="metadata"&&e.operation!=="link")throw new Error("Invalid OPFS filesystem mutation.");if(he(e.path),e.operation==="rename"&&he(e.destination),(e.operation==="write"||e.operation==="append"||e.operation==="write-at")&&!(e.content instanceof Uint8Array))throw new Error("Invalid OPFS file content.");if(e.operation==="write-at"&&(!Number.isSafeInteger(e.position)||e.position<0))throw new Error("Invalid OPFS write position.");return Lt(e),e}function pn(e){if(!Array.isArray(e)||e.length===0||e.length>128)throw new Error("Invalid OPFS filesystem mutation batch.");return e.map(t=>lr(t))}function Dt(e){if(!e||!Array.isArray(e.files)||e.files.length>d||!(e.pack instanceof ArrayBuffer))throw new Error("Invalid OPFS workspace snapshot.");const t=new Set,r=new Map(ye().map(n=>[n,"directory"]));let i=0;for(const n of e.files){if(!n||typeof n!="object")throw new Error("Invalid OPFS workspace snapshot entry.");if(he(n.path),n.type!=="file"&&n.type!=="directory"&&n.type!=="symlink"||t.has(n.path))throw new Error("Invalid or duplicate OPFS workspace entry.");if(t.add(n.path),r.set(n.path,n.type),ye().includes(n.path)&&n.type!=="directory")throw new Error("The OPFS workspace root must be a directory.");if(n.type!=="directory"){const s=n.offset??0,c=n.length??0;if(!Number.isSafeInteger(s)||!Number.isSafeInteger(c)||s<0||c<0||c>Q||s+c>e.pack.byteLength)throw new Error("Invalid OPFS workspace file.");if(i+=c,i>a)throw new Error("OPFS workspace exceeds its byte limit.")}else if((n.offset??0)!==0||(n.length??0)!==0)throw new Error("An OPFS workspace directory cannot contain file bytes.");Lt(n)}le(r.size);for(const n of e.files)if(!ye().includes(n.path)&&r.get(Te(n.path))!=="directory")throw new Error(`An OPFS workspace snapshot has no directory parent for ${n.path}.`);return e}function Lt(e){if(e.mode!==void 0&&(!Number.isSafeInteger(e.mode)||e.mode<0||e.mode>4095))throw new Error("Invalid OPFS file mode.");if(e.mtimeMs!==void 0&&(typeof e.mtimeMs!="number"||!Number.isFinite(e.mtimeMs)||e.mtimeMs<0))throw new Error("Invalid OPFS modification time.")}function gn(e){return{entries:[...e]}}function Bt(e){const t=new Map;if(e===void 0)throw new Error("The committed OPFS workspace index is missing. Stored data was retained.");if(!e||typeof e!="object"||!Array.isArray(e.entries))throw new Error("Invalid OPFS workspace index.");const r=e.entries;le(r.length);for(const i of r){if(!Array.isArray(i)||i.length!==2)throw new Error("Invalid OPFS workspace index entry.");const n=he(i[0]);if(t.has(n))throw new Error("Duplicate OPFS workspace index entry.");t.set(n,dr(i[1]))}return t}function dr(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid OPFS workspace index entry.");const t=e;if(t.type!=="file"&&t.type!=="directory"&&t.type!=="symlink")throw new Error("Invalid OPFS workspace index entry.");if(Lt(t),t.mode===void 0||t.mtimeMs===void 0)throw new Error("Invalid OPFS workspace index entry.");if(!Number.isSafeInteger(t.offset)||t.offset<0||!Number.isSafeInteger(t.length)||t.length<0||t.length>Q)throw new Error("Invalid OPFS workspace index extent.");if(t.pack!==void 0&&t.pack!==xe)throw new Error("Invalid OPFS workspace index entry.");return{type:t.type,mode:t.mode,mtimeMs:t.mtimeMs,offset:t.offset,length:t.length,...t.pack?{pack:t.pack}:{}}}function mn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid OPFS workspace index record.");const t=e;if(!Number.isSafeInteger(t.packBytes)||t.packBytes<0||!Array.isArray(t.changes))throw new Error("Invalid OPFS workspace index record.");const r=[];for(const i of t.changes){if(!Array.isArray(i)||i.length!==2)throw new Error("Invalid OPFS workspace index record.");r.push([he(i[0]),i[1]===null?null:dr(i[1])])}return{packBytes:t.packBytes,changes:r}}function gt(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid OPFS workspace state. Stored data was retained.");const t=e;if(t.storageVersion!==4&&t.storageVersion!==5||t.storageVersion===5&&(typeof t.imageRanges!="string"||!/^[a-f0-9]{64}$/u.test(t.imageRanges))||t.storageVersion===4&&t.imageRanges!==void 0||typeof t.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(t.generation)||typeof t.initializedAt!="number"||!Number.isFinite(t.initializedAt))throw new Error("Invalid or unsupported OPFS workspace state. Stored data was retained.");return t}function he(e){if(typeof e!="string"||qe(e)===void 0||e.includes("\0")||e.length>4096)throw new Error("Invalid OPFS workspace path.");return hr(e),e}function hr(e){const t=qe(e);if(t===void 0)throw new Error("Invalid OPFS workspace path.");const r=e===t?"":e.slice(t.length+1);return Ct(r),r}function Ct(e){const t=e===""?[]:e.split("/");if(t.some(r=>!r||r==="."||r===".."||r.includes("\0")))throw new Error("Invalid OPFS workspace path segment.");return t}function Te(e){const t=e.slice(0,e.lastIndexOf("/"));return t===""||qe(t)===void 0?qe(e)??e:t}function wr(e){let t=1;for(let r=0;r<e.length;r+=1)e.charCodeAt(r)===47&&(t+=1);return t}function $e(e){return e instanceof DOMException&&e.name==="NotFoundError"}function ur(e){let t=2166136261;for(let r=0;r<e.byteLength;r+=1)t^=e[r],t=Math.imul(t,16777619);return t>>>0}typeof addEventListener=="function"&&addEventListener("close",()=>{_?.flush(),v?.flush(),Ce(),M?.()});function yr(e,t={}){if(ue(),ee)throw new Error("An OPFS mutation batch cannot be nested.");for(const r of e)lr(r);return e.length?pr(r=>{for(const i of e)Vr(i,r)},t):[]}function En(e,t,r={}){if(ue(),ee)throw new Error("An OPFS mutation batch cannot be nested.");for(const i of t){if(he(i.path),i.type!=="file"&&i.type!=="directory"&&i.type!=="symlink")throw new Error(`OPFS extent ${i.path} has no valid type.`);if(i.type==="directory")continue;const{offset:n,length:s}=i;if(n===void 0||s===void 0||!Number.isSafeInteger(n)||!Number.isSafeInteger(s)||n<0||s<0||n+s>e.byteLength)throw new Error(`OPFS extent ${i.path} lies outside its bytes.`);if(s>Q)throw new Error(`${i.path} is ${s} bytes; an OPFS workspace file holds at most ${Q}.`)}return t.length?pr(i=>{const n=e.byteLength>0?ht(e):O;for(const s of t){const c=he(s.path);Oe(c,i);const f=w.get(c);if(s.type==="directory"){if(f&&f.type!=="directory")throw new Error(`OPFS path is a file: ${c}`);J(c,{type:"directory",mode:s.mode,mtimeMs:s.mtimeMs,offset:0,length:0},i);continue}if(f?.type==="directory")throw new Error(`OPFS write target is a directory: ${c}`);lt(c,s.length),J(c,{type:s.type,mode:s.mode,mtimeMs:s.mtimeMs,offset:n+s.offset,length:s.length},i)}},r):[]}function pr(e,t){if(!_||!v)throw new Error("OPFS filesystem worker is not initialized.");const r={packBytes:O,logBytes:b,liveBytes:R,deadBytes:W,rewrites:Se,rewrittenBytes:be,linked:A,linkedBytes:I},i=new Map;ee=i;const n=[];et=n;const s=[];try{return e(s),rr(),en(s,{publish:!t.durable}),t.durable&&(pe(),tt()),Xt(),s}catch(c){const f=U!==void 0&&!ae&&Atomics.load(U,Fr)!==r.logBytes;f&&Ye();for(const[l,u]of i)u===void 0?w.delete(l):w.set(l,u);ze();try{for(let l=n.length-1;l>=0;l-=1)dt(n[l][0],n[l][1])}catch(l){c=new AggregateError([c,l],"OPFS could not restore bytes a failed batch wrote over.")}({packBytes:O,logBytes:b,liveBytes:R,deadBytes:W,rewrites:Se,rewrittenBytes:be,linked:A,linkedBytes:I}=r),Y!==void 0&&(clearTimeout(Y),Y=void 0);try{v.truncate(b),v.flush(),_.truncate(O),_.flush()}catch(l){throw rt(),se=new AggregateError([c,l],"OPFS could not roll back a failed batch; reopen this workspace before writing again."),se}throw f&&Ke(),c}finally{ee=void 0,et=void 0}}function Sn(){if(ve){je?.abort(new DOMException("The workspace was closed while opening.","AbortError"));return}N||(N=!0,De===0&&gr())}function gr(){rt();try{pe()}finally{try{Ce()}finally{const e=M;M=void 0,h=void 0;try{e?.()}finally{o.ownsPackages&&o.packages?.close()}}}}return{initialize:Ur,opened:()=>h!==void 0&&!N,stats:()=>({entries:w.size,liveBytes:R,deadBytes:W,packBytes:O,rewrites:Se,rewrittenBytes:be,linked:A,linkedBytes:I,flushes:Ee,flushMs:we}),applyNow:yr,applyExtentsNow:En,close:Sn,readExtent:st,descendants:_t,retain:or,remapLinks:an,childrenOf:e=>[...C.get(e)??[]].sort(),refresh:Gr,follow:$r,clock:Yt,readerSeed:Lr,imageCompletionSeed:Br,imageLine:()=>z?.lineForReader()??o.packages?.imageLine(),imageStartupSet:()=>z?.readDigests()??z?.completedDigests()??[],prefetchImage:(e,t)=>z?.prefetch(e,t)??{queued:0,done:Promise.resolve()},seeded:()=>Kt,get logBytes(){return b},checkpoint:wt,deferMaintenance:qr,installPreparedImage:dn,installPreparedProject:hn,get deferredImage(){return _e},get imagePlacedAt(){return h&&H?ie:void 0},get entries(){return w},get packBytes(){return O},read:Nr,readRange:Hr,snapshot:wn,replace:ir,apply:Jr,flush:()=>{if(N||!h)throw new Error("This OPFS workspace is not open.");if(Le)throw new Error("Wait for the OPFS generation replacement before flushing it.");pe()},validateSnapshot:Dt,validateMutationBatch:pn}}const Ln="sweep.json";async function Bn(m){const a=await(await m.getFileHandle(Ln,{create:!0})).createWritable();await a.write(JSON.stringify({at:Date.now()})),await a.close()}class Ot{map=new Map;get(o){return this.map.get(o)}mutable(o){let a=this.map.get(o);return a||(a=new Set,this.map.set(o,a)),a}delete(o){this.map.delete(o)}}const Pt=globalThis,Z=Dn({navigator:Pt.navigator});let Rr=Promise.resolve();Pt.onmessage=m=>{Rr=Rr.catch(()=>{}).then(async()=>{try{const o=Date.now(),a=await Cn(m.data),d=Date.now()-o;if(d>5e3){const h=m.data.operation==="batch"?` of ${m.data.mutations?.length??0}`:"";console.warn(`The OPFS workspace worker took ${Math.round(d/1e3)} s on ${m.data.operation}${h}; the store holds ${Z.entries.size} entries and ${Math.round(Z.packBytes/1048576)} MiB.`)}Pt.postMessage({id:m.data.id,ok:!0,...a},a.snapshot?[a.snapshot.pack]:[])}catch(o){const a=o instanceof Error?o:new Error(String(o));console.error(`The OPFS workspace worker failed on ${m.data.operation}: ${a.message}`),Pt.postMessage({id:m.data.id,ok:!1,error:a.message,...a.stack?{errorStack:a.stack}:{}})}}).catch(()=>{})};async function Cn(m){if(m.operation==="initialize")return await Z.initialize(m.projectId)?{initialized:!0,snapshot:await Z.snapshot()}:{initialized:!1};if(!Z.opened())throw new Error("OPFS filesystem worker is not initialized.");if(m.operation==="flush")return Z.flush(),{};if(m.operation==="replace"){if(!m.snapshot)throw new Error("OPFS filesystem replacement requires a snapshot.");return await Z.replace(Z.validateSnapshot(m.snapshot)),{}}return m.operation==="batch"?(await Z.apply(Z.validateMutationBatch(m.mutations)),{}):(await Z.apply(Z.validateMutationBatch([m])),{})}
|