@volter/browser-substrate 0.1.130 → 0.1.132
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/catalog/demand-input.json +23 -26
- package/catalog/published/profile.json +4 -1
- package/catalog/published/v1/artifacts/sha256/0dde568b5b331900694620b905a098b230fdcec99bdd4dae8555f716fbbdc31e +0 -0
- package/catalog/published/v1/artifacts/sha256/0dde568b5b331900694620b905a098b230fdcec99bdd4dae8555f716fbbdc31e.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/0e6d21ea3c0794519406e3a629fda659ba5e160048aabef334e11c39ffe3141f +0 -0
- package/catalog/published/v1/artifacts/sha256/0e6d21ea3c0794519406e3a629fda659ba5e160048aabef334e11c39ffe3141f.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/1ad26ae231b3b0924f19cf59eba59a14eab9d81e23d4a6f4963a73223bf1599e +0 -0
- package/catalog/published/v1/artifacts/sha256/1ad26ae231b3b0924f19cf59eba59a14eab9d81e23d4a6f4963a73223bf1599e.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/22c4e8bb098c8892abbc219a0779f2c2325c7b1b7fe86af3fcbc10b41e88cab3 +0 -0
- package/catalog/published/v1/artifacts/sha256/22c4e8bb098c8892abbc219a0779f2c2325c7b1b7fe86af3fcbc10b41e88cab3.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/2aec86c0de68469758763716b490a5976b6efc86395dbda20094d3e00f19e237 +0 -0
- package/catalog/published/v1/artifacts/sha256/2aec86c0de68469758763716b490a5976b6efc86395dbda20094d3e00f19e237.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/2eb1afb25f97181a7024d4f20027572766baf5e298f10c81bf6cf14b3935ffa1 +0 -0
- package/catalog/published/v1/artifacts/sha256/2eb1afb25f97181a7024d4f20027572766baf5e298f10c81bf6cf14b3935ffa1.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/44bdc4eb993af76098524b457050eba6de0eef2a3aaf3e44cad1d1bf37feb0ed +0 -0
- package/catalog/published/v1/artifacts/sha256/44bdc4eb993af76098524b457050eba6de0eef2a3aaf3e44cad1d1bf37feb0ed.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/44f224bdc27dca8669603a7f69a15091fb05816b03cc7cdf74bb7c033d679bda +0 -0
- package/catalog/published/v1/artifacts/sha256/44f224bdc27dca8669603a7f69a15091fb05816b03cc7cdf74bb7c033d679bda.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/608dce53b0510adebcc35c4fc8cbd03fdcd2b0aef46c97408a58004b695560ec +0 -0
- package/catalog/published/v1/artifacts/sha256/608dce53b0510adebcc35c4fc8cbd03fdcd2b0aef46c97408a58004b695560ec.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/68fd1d330615dcc53916a8d028cf0e4f0eec89b9fc240e025f2e4afa3898334d +0 -0
- package/catalog/published/v1/artifacts/sha256/68fd1d330615dcc53916a8d028cf0e4f0eec89b9fc240e025f2e4afa3898334d.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/7ea6e9ae767d25851bcb6e522af3fb2f29e280554ed8caedda3440e70eafd640 +0 -0
- package/catalog/published/v1/artifacts/sha256/7ea6e9ae767d25851bcb6e522af3fb2f29e280554ed8caedda3440e70eafd640.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/857efce895fedba5f4d143b759ad5c7ec532cf89cf1b3cd775abc01a92613e2b +0 -0
- package/catalog/published/v1/artifacts/sha256/857efce895fedba5f4d143b759ad5c7ec532cf89cf1b3cd775abc01a92613e2b.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/a087c9be0888ff3cccf9ef844851fc4d45c11f905d11a0543549af3c002ac0aa +0 -0
- package/catalog/published/v1/artifacts/sha256/a087c9be0888ff3cccf9ef844851fc4d45c11f905d11a0543549af3c002ac0aa.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/a2bc367802986f1c5297fc6e95ee8f0b1496eca41dbb129090c43dd798c7320a +0 -0
- package/catalog/published/v1/artifacts/sha256/a2bc367802986f1c5297fc6e95ee8f0b1496eca41dbb129090c43dd798c7320a.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/a519dc170d76d7e9705c79e1b40ea36b1b8d46410f788bbb73a92a0ded37b216 +0 -0
- package/catalog/published/v1/artifacts/sha256/a519dc170d76d7e9705c79e1b40ea36b1b8d46410f788bbb73a92a0ded37b216.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/ae0706d25f0209e750d9f1b227fe8b12aea31d684ff7133207938a7a86bd7cac +0 -0
- package/catalog/published/v1/artifacts/sha256/ae0706d25f0209e750d9f1b227fe8b12aea31d684ff7133207938a7a86bd7cac.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/b5b8c43607702daef23b2f3df3099d07e8c8e392d55305b0a28aae3bac7a41a8 +0 -0
- package/catalog/published/v1/artifacts/sha256/b5b8c43607702daef23b2f3df3099d07e8c8e392d55305b0a28aae3bac7a41a8.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/c2f1c0fa4f79f465a9681abaac1e31b9cf8cb0b217698ee1d2c0ff810fcf3ef2 +0 -0
- package/catalog/published/v1/artifacts/sha256/c2f1c0fa4f79f465a9681abaac1e31b9cf8cb0b217698ee1d2c0ff810fcf3ef2.headers.json +1 -0
- package/catalog/published/v1/artifacts/sha256/c3ce5504bd36dca993a3233aae4bcf98a15932c3cc955b380a584ca9b3654fe6 +0 -0
- package/catalog/published/v1/artifacts/sha256/c3ce5504bd36dca993a3233aae4bcf98a15932c3cc955b380a584ca9b3654fe6.headers.json +1 -0
- package/catalog/published/v1/catalog.json +1 -1
- package/catalog/published/v1/catalogs/sha256/{05968a229c8b3f8b54472842cf7fae36c242e29640c4bfdf4d016f544e56b081.json → 1e2e4636d3edc259d161938c35d244579d714ee550dd437dd8052527257c4913.json} +1 -1
- package/catalog/published/v1/locks/sha256/8774e29a90421e258ffe794479f490f0bb9a5ad18992501f4a4b8724946bc5ea.json +1 -0
- package/catalog/published/v1/locks/sha256/8774e29a90421e258ffe794479f490f0bb9a5ad18992501f4a4b8724946bc5ea.json.headers.json +1 -0
- package/catalog/published/v1/locks/sha256/a0afe6eb2bf01c70330f3254aebdc632c88b37e8f74bf94630aa032082e9f8aa.json +1 -0
- package/catalog/published/v1/locks/sha256/a0afe6eb2bf01c70330f3254aebdc632c88b37e8f74bf94630aa032082e9f8aa.json.headers.json +1 -0
- package/catalog/published/v1/locks/sha256/d620d587eef3abfe242655f425c1b58593a16ec44df6fe6c581cf43187ed2a44.json +1 -0
- package/catalog/published/v1/locks/sha256/d620d587eef3abfe242655f425c1b58593a16ec44df6fe6c581cf43187ed2a44.json.headers.json +1 -0
- package/catalog/published/v1/locks/sha256/e2aa898376ac7441136725b07cca237aa954908e4cfc1f23a9fe00cf7de09682.json +1 -0
- package/catalog/published/v1/locks/sha256/e2aa898376ac7441136725b07cca237aa954908e4cfc1f23a9fe00cf7de09682.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/1d81bbc0eb949801ae8923812ecdce0084767419f64e89a55151cd148f5cd1b2.json +1 -0
- package/catalog/published/v1/manifests/sha256/1d81bbc0eb949801ae8923812ecdce0084767419f64e89a55151cd148f5cd1b2.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/2fb69681c1296589abbe43727a663d01d9d8479bc6d5fa8721f42ffe0c3561a7.json +1 -0
- package/catalog/published/v1/manifests/sha256/2fb69681c1296589abbe43727a663d01d9d8479bc6d5fa8721f42ffe0c3561a7.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/36c9274254103e78c5348ad791fed667516140b7af0642099bbf47ef4f53d890.json +1 -0
- package/catalog/published/v1/manifests/sha256/36c9274254103e78c5348ad791fed667516140b7af0642099bbf47ef4f53d890.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/3e3a36367e510235bd5bde86ad43eec365ea0104540b07d369b0ef3f9ada03bc.json +1 -0
- package/catalog/published/v1/manifests/sha256/3e3a36367e510235bd5bde86ad43eec365ea0104540b07d369b0ef3f9ada03bc.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/4936c927e6c26f0059ca3e0640df8c789b81a14087ebc5eef3beb1610e5bd04c.json +1 -0
- package/catalog/published/v1/manifests/sha256/4936c927e6c26f0059ca3e0640df8c789b81a14087ebc5eef3beb1610e5bd04c.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/50bffdc836ab04fe3a629b6b05de0e397608535b54301afa1928f5c56ebbe5cc.json +1 -0
- package/catalog/published/v1/manifests/sha256/50bffdc836ab04fe3a629b6b05de0e397608535b54301afa1928f5c56ebbe5cc.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/55b16f905125ae8d99528e202f7adf93efd406872a01ca87215b89421127891a.json +1 -0
- package/catalog/published/v1/manifests/sha256/55b16f905125ae8d99528e202f7adf93efd406872a01ca87215b89421127891a.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/5c157348675c4e2c4c4ac4361a290eb9a6d4d94234b3c88f2de32ea02a378ebf.json +1 -0
- package/catalog/published/v1/manifests/sha256/5c157348675c4e2c4c4ac4361a290eb9a6d4d94234b3c88f2de32ea02a378ebf.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/790ec3d63c661336b53562800f79d2c1d5514bba3cae4598c14ee6d27e494215.json +1 -0
- package/catalog/published/v1/manifests/sha256/790ec3d63c661336b53562800f79d2c1d5514bba3cae4598c14ee6d27e494215.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/87547c854971ef1a71229fea31b8b23ff79eb086b86ddbab3c8932fcb99be7ff.json +1 -0
- package/catalog/published/v1/manifests/sha256/87547c854971ef1a71229fea31b8b23ff79eb086b86ddbab3c8932fcb99be7ff.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/8bdf05b266f5e88ba2285c5df8c4669c9563615db49b2232108f9b5a520e937b.json +1 -0
- package/catalog/published/v1/manifests/sha256/8bdf05b266f5e88ba2285c5df8c4669c9563615db49b2232108f9b5a520e937b.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/947574aab78b0dd25696ebd0818c37fd7fb5ff155b6da475989586cf111d9b00.json +1 -0
- package/catalog/published/v1/manifests/sha256/947574aab78b0dd25696ebd0818c37fd7fb5ff155b6da475989586cf111d9b00.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/b37369ce5ea8ee2d6a33547fd869ff288515d06721a603dda497c29efa1961c1.json +1 -0
- package/catalog/published/v1/manifests/sha256/b37369ce5ea8ee2d6a33547fd869ff288515d06721a603dda497c29efa1961c1.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/b7e0146b018e2778913230fd5776c959cd8d4252cb1ee5ff4781dccac79b8530.json +1 -0
- package/catalog/published/v1/manifests/sha256/b7e0146b018e2778913230fd5776c959cd8d4252cb1ee5ff4781dccac79b8530.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/c31843879803e9f3462643279eb736cf5fa02628062a1a93ad600af32a171b2c.json +1 -0
- package/catalog/published/v1/manifests/sha256/c31843879803e9f3462643279eb736cf5fa02628062a1a93ad600af32a171b2c.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/c3bc41ee338d6b67a11b68b7557d54c177391332db2ab10226e26c8bc4e209c3.json +1 -0
- package/catalog/published/v1/manifests/sha256/c3bc41ee338d6b67a11b68b7557d54c177391332db2ab10226e26c8bc4e209c3.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/ddb91a53e5dd7c86d9ace7d8582d2b8b5ea94a64bc80aef18ca0011dd5123aa5.json +1 -0
- package/catalog/published/v1/manifests/sha256/ddb91a53e5dd7c86d9ace7d8582d2b8b5ea94a64bc80aef18ca0011dd5123aa5.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/f5f894715fe5d8717576410d44710db17ae99fa71a7c98cf6306589f8b59b9fa.json +1 -0
- package/catalog/published/v1/manifests/sha256/f5f894715fe5d8717576410d44710db17ae99fa71a7c98cf6306589f8b59b9fa.json.headers.json +1 -0
- package/catalog/published/v1/manifests/sha256/f9da999dfff0f40cebba66f90924b57ad4a3aee3532c468fe4d5a3bbb72d0e30.json +1 -0
- package/catalog/published/v1/manifests/sha256/f9da999dfff0f40cebba66f90924b57ad4a3aee3532c468fe4d5a3bbb72d0e30.json.headers.json +1 -0
- package/dist/cli/host-managers.d.ts.map +1 -1
- package/dist/cli/host-managers.js +24 -3
- package/dist/cli/host-managers.js.map +1 -1
- package/dist/cli/provision-catalog.d.ts.map +1 -1
- package/dist/cli/provision-catalog.js +18 -2
- package/dist/cli/provision-catalog.js.map +1 -1
- package/dist/shell/assets/{node-execution-worker-5794fb3c5541adf1.js → node-execution-worker-8963896fc0b53580.js} +2 -2
- package/dist/shell/assets/{shell-DWB5HWvM.js → shell-DaFiRjDJ.js} +461 -461
- package/dist/shell/index.html +1 -1
- package/dist/shell/node-execution-worker.js +1 -1
- package/package.json +1 -1
- /package/catalog/published/v1/catalogs/sha256/{05968a229c8b3f8b54472842cf7fae36c242e29640c4bfdf4d016f544e56b081.json.headers.json → 1e2e4636d3edc259d161938c35d244579d714ee550dd437dd8052527257c4913.json.headers.json} +0 -0
|
@@ -5889,7 +5889,7 @@ while (true) {
|
|
|
5889
5889
|
}
|
|
5890
5890
|
}`)(require2,consoleWrapper,process22,buffer2);replGen.next();return{eval(code22){const transformed=code22.replace(/^\s*(const|let)\s+/gm,"var ");const exprResult=replGen.next("("+transformed+")").value;if(!exprResult.error){replGen.next();return exprResult.value}replGen.next();const stmtResult=replGen.next(transformed).value;if(stmtResult.error){replGen.next();throw stmtResult.error}replGen.next();return stmtResult.value}}}};function execute(code22,vfs2,options){const runtime=new Runtime(vfs2,options);return runtime.execute(code22)}forGuestRealm(()=>{if(typeof globalThis.setImmediate==="undefined"){takeFromHost(globalThis,"setImmediate",(fn2,...args)=>setTimeout(fn2,0,...args));takeFromHost(globalThis,"clearImmediate",id2=>clearTimeout(id2))}});forGuestRealm(()=>{if(typeof globalThis.Request==="function"&&!globalThis.Request.__substrateHeaderGuard){const Native=globalThis.Request;const kept=new WeakMap;class NodeRequest extends Native{constructor(input,init){init=withNodeRequestBody(init);super(input,init);rememberRequestBodySource(this,input,init);const asked=new Headers((init==null?void 0:init.headers)??(input instanceof Native?input.headers:void 0));const headers=new Headers(super.headers);asked.forEach((value,name)=>{if(!headers.has(name))headers.set(name,value)});kept.set(this,headers)}get headers(){return kept.get(this)??super.headers}clone(){const copy2=super.clone();rememberRequestBodySource(copy2,this);return new NodeRequest(copy2,{headers:this.headers})}}Object.defineProperty(NodeRequest,"__substrateHeaderGuard",{value:true});Object.defineProperty(NodeRequest,"name",{value:"Request",configurable:true});takeFromHost(globalThis,"Request",NodeRequest)}});forGuestRealm(()=>{installNodeResponse(globalThis)});forGuestRealm(()=>{const kIsClosedPromise=Symbol.for("nodejs.webstream.isClosedPromise");const Native=globalThis.ReadableStream;if(typeof Native!=="function"||Native.__substrateClosedPromise)return;const Tracked=new Proxy(Native,{construct(target,args,newTarget){let resolve2;let reject;const promise=new Promise((yes,no2)=>{resolve2=yes;reject=no2});promise.then(void 0,()=>{});const source=args[0];const track2=controller=>{const close2=controller.close;const error=controller.error;if(typeof close2==="function")controller.close=function(...rest){const result=close2.apply(this,rest);resolve2();return result};if(typeof error==="function")controller.error=function(...rest){reject(rest[0]);return error.apply(this,rest)}};const failed=cause=>{reject(cause);throw cause};const wrapped=Object.create(source??null);wrapped.start=controller=>{var _a22;track2(controller);try{return(_a22=source==null?void 0:source.start)==null?void 0:_a22.call(source,controller)}catch(cause){return failed(cause)}};if(typeof(source==null?void 0:source.pull)==="function"){const pull=source.pull;wrapped.pull=controller=>{try{return Promise.resolve(pull.call(source,controller)).catch(failed)}catch(cause){return failed(cause)}}}wrapped.cancel=reason=>{var _a22;resolve2();return(_a22=source==null?void 0:source.cancel)==null?void 0:_a22.call(source,reason)};const stream=Reflect.construct(target,[wrapped,...args.slice(1)],newTarget===Tracked?target:newTarget);Object.defineProperty(stream,kIsClosedPromise,{value:{promise,resolve:resolve2,reject},configurable:true});return stream}});Object.defineProperty(Tracked,"__substrateClosedPromise",{value:true});takeFromHost(globalThis,"ReadableStream",Tracked)});forGuestRealm(__substrateStackTracePolyfill);forGuestRealm(__substrateCallSiteFileNames);forGuestRealm(__substrateTextDecoderPolyfill);function __substrateTextDecoderPolyfill(){const OriginalTextDecoder=globalThis.TextDecoder;if(OriginalTextDecoder.__substrateBinaryEncodings)return;class PolyfillTextDecoder{constructor(encoding="utf-8",options){__publicField2(this,"encoding");__publicField2(this,"decoder",null);this.encoding=encoding.toLowerCase();const validTextEncodings=["utf-8","utf8","utf-16le","utf-16be","utf-16","ascii","iso-8859-1","latin1","windows-1252"];if(validTextEncodings.includes(this.encoding)){try{this.decoder=new OriginalTextDecoder(encoding,options)}catch{this.decoder=new OriginalTextDecoder("utf-8",options)}}}decode(input,options){if(this.decoder){return this.decoder.decode(input,options)}if(!input)return"";const bytes2=input instanceof ArrayBuffer?new Uint8Array(input):new Uint8Array(input.buffer,input.byteOffset,input.byteLength);if(this.encoding==="base64"){return uint8ToBase64(bytes2)}if(this.encoding==="base64url"){return uint8ToBase64(bytes2).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}if(this.encoding==="hex"){return uint8ToHex(bytes2)}return new OriginalTextDecoder("utf-8").decode(input,options)}get fatal(){var _a22;return((_a22=this.decoder)==null?void 0:_a22.fatal)??false}get ignoreBOM(){var _a22;return((_a22=this.decoder)==null?void 0:_a22.ignoreBOM)??false}}Object.defineProperty(PolyfillTextDecoder,"__substrateBinaryEncodings",{value:true});takeFromHost(globalThis,"TextDecoder",PolyfillTextDecoder)}function __substrateStackTracePolyfill(){if(typeof Error.captureStackTrace==="function")return;if(Error.stackTraceLimit===void 0){takeFromHost(Error,"stackTraceLimit",10)}function parseStack(stack){if(!stack)return[];const frames=[];const lines=stack.split("\n");for(const raw of lines){const line=raw.trim();if(!line||line.startsWith("Error")||line.startsWith("TypeError"))continue;let fn2="",file2="",lineNo=0,colNo=0;const safariMatch=line.match(/^(.*)@(.*?):(\d+):(\d+)$/);if(safariMatch){fn2=safariMatch[1]||"";file2=safariMatch[2];lineNo=parseInt(safariMatch[3],10);colNo=parseInt(safariMatch[4],10);frames.push({fn:fn2,file:file2,line:lineNo,col:colNo});continue}const chromeMatch=line.match(/^at\s+(?:(.+?)\s+\()?(.*?):(\d+):(\d+)\)?$/);if(chromeMatch){fn2=chromeMatch[1]||"";file2=chromeMatch[2];lineNo=parseInt(chromeMatch[3],10);colNo=parseInt(chromeMatch[4],10);frames.push({fn:fn2,file:file2,line:lineNo,col:colNo});continue}}return frames}function createCallSite(frame){return{getFileName:()=>frame.file||null,getLineNumber:()=>frame.line||null,getColumnNumber:()=>frame.col||null,getFunctionName:()=>frame.fn||null,getMethodName:()=>frame.fn||null,getTypeName:()=>null,getThis:()=>void 0,getFunction:()=>void 0,getEvalOrigin:()=>void 0,isNative:()=>false,isConstructor:()=>false,isToplevel:()=>!frame.fn,isEval:()=>false,toString:()=>frame.fn?`${frame.fn} (${frame.file}:${frame.line}:${frame.col})`:`${frame.file}:${frame.line}:${frame.col}`}}function buildCallSites(stack,constructorOpt){const frames=parseStack(stack);let startIdx=0;if(constructorOpt&&constructorOpt.name){for(let i22=0;i22<frames.length;i22++){if(frames[i22].fn===constructorOpt.name){startIdx=i22+1;break}}}return frames.slice(startIdx).map(createCallSite)}const stackSymbol=Symbol("rawStack");defineOnHost(Error.prototype,"stack",{get(){const rawStack=this[stackSymbol];if(rawStack!==void 0&&typeof Error.prepareStackTrace==="function"){const callSites=buildCallSites(rawStack);try{return Error.prepareStackTrace(this,callSites)}catch{return rawStack}}return rawStack},set(value){this[stackSymbol]=value},configurable:true,enumerable:false});const captureStackTrace=function(target,constructorOpt){const savedPrepare=Error.prepareStackTrace;Error.prepareStackTrace=void 0;const err22=new Error;const rawStack=err22.stack||"";Error.prepareStackTrace=savedPrepare;if(typeof savedPrepare==="function"){const callSites=buildCallSites(rawStack,constructorOpt);try{target.stack=savedPrepare(target,callSites)}catch(e2){console.warn("[tabnode] Error.prepareStackTrace threw:",e2);target.stack=rawStack}}else{target.stack=rawStack}};takeFromHost(Error,"captureStackTrace",captureStackTrace)}function __substrateCallSiteFileNames(){var _a22;if(typeof Error.captureStackTrace!=="function")return;const held=Object.getOwnPropertyDescriptor(Error,"prepareStackTrace");if((_a22=held==null?void 0:held.get)==null?void 0:_a22.__substrateNamesFrames)return;if(held!==void 0&&held.configurable===false)return;const named=site=>new Proxy(site,{get(target,key){if(key==="getFileName")return()=>{var _a32;return target.getFileName()??(((_a32=target.getScriptNameOrSourceURL)==null?void 0:_a32.call(target))||null)};const value=Reflect.get(target,key);return typeof value==="function"?value.bind(target):value}});let guestPrepare=held&&!held.get&&!held.set?held.value:void 0;const namers=new WeakMap;const guests=new WeakMap;const namerFor=prepare=>{let namer=namers.get(prepare);if(!namer){namer=(error,sites)=>prepare(error,sites.map(named));namers.set(prepare,namer);guests.set(namer,prepare)}return namer};const overridingFor=guest=>{const known=typeof guest==="function"?overridings.get(guest):overridingNone;if(known)return known;const overriding=(error,sites)=>{const override=error!==null&&typeof error==="object"?stackOverrides.get(error):void 0;if(override){stackOverrides.delete(error);return override(error,sites.map(named))}if(typeof guest==="function")return namerFor(guest)(error,sites);return`${Error.prototype.toString.call(error)}${sites.map(site=>`
|
|
5891
5891
|
at ${String(site)}`).join("")}`};guests.set(overriding,guest);if(typeof guest==="function")overridings.set(guest,overriding);else overridingNone=overriding;return overriding};const overridings=new WeakMap;let overridingNone;const get2=()=>stackOverrides.size>0?overridingFor(guestPrepare):typeof guestPrepare==="function"?namerFor(guestPrepare):guestPrepare;get2.__substrateNamesFrames=true;defineOnHost(Error,"prepareStackTrace",{get:get2,set(prepare){guestPrepare=typeof prepare==="function"&&guests.has(prepare)?guests.get(prepare):prepare},configurable:true,enumerable:false})}var WorkerRuntime=class{constructor(vfs2,options={}){__publicField2(this,"worker");__publicField2(this,"workerApi");__publicField2(this,"vfs");__publicField2(this,"options");__publicField2(this,"initialized");__publicField2(this,"changeListener",null);__publicField2(this,"deleteListener",null);this.vfs=vfs2;this.options=options;this.worker=new Worker("/assets/runtime-worker-DbsIaU2Q.js",{type:"module"});this.workerApi=wrap(this.worker);this.initialized=this.initWorker();this.setupVFSListeners()}async initWorker(){const snapshot=this.vfs.toSnapshot();const workerOptions2={cwd:this.options.cwd,env:this.options.env};await this.workerApi.init(snapshot,workerOptions2);if(this.options.onConsole){await this.workerApi.setConsoleCallback(proxy(this.options.onConsole))}console.log("[WorkerRuntime] Worker initialized")}setupVFSListeners(){this.changeListener=(path22,content)=>{this.workerApi.syncFile(path22,content)};this.vfs.on("change",this.changeListener);this.deleteListener=path22=>{this.workerApi.syncFile(path22,null)};this.vfs.on("delete",this.deleteListener)}async execute(code22,filename){await this.initialized;return this.workerApi.execute(code22,filename)}async runFile(filename){await this.initialized;return this.workerApi.runFile(filename)}clearCache(){this.workerApi.clearCache()}getVFS(){return this.vfs}terminate(){if(this.changeListener){this.vfs.off("change",this.changeListener)}if(this.deleteListener){this.vfs.off("delete",this.deleteListener)}this.worker.terminate();console.log("[WorkerRuntime] Worker terminated")}};function isWorkerAvailable(){return typeof Worker!=="undefined"}var AsyncRuntimeWrapper=class{constructor(vfs2,options={}){__publicField2(this,"runtime");this.runtime=new Runtime(vfs2,options)}async execute(code22,filename){return Promise.resolve(this.runtime.execute(code22,filename))}async runFile(filename){return Promise.resolve(this.runtime.runFile(filename))}clearCache(){this.runtime.clearCache()}getVFS(){return this.runtime.getVFS()}getSyncRuntime(){return this.runtime}};async function createRuntime(vfs2,options={}){const{useWorker=false,...runtimeOptions}=options;const shouldUseWorker=useWorker===true||useWorker==="auto"?isWorkerAvailable():false;if(shouldUseWorker){const workerRuntime=new WorkerRuntime(vfs2,runtimeOptions);await workerRuntime.execute("/* worker ready check */","/__worker_init__.js");return workerRuntime}return new AsyncRuntimeWrapper(vfs2,runtimeOptions)}var DuplexStreamHandle=class extends LibuvStreamWrap{constructor(transport2){super();__publicField2(this,"pendingWrite");this.transport=transport2;transport2.pause();transport2.on("data",chunk=>{transport2.pause();this.receive(chunk)});transport2.on("end",()=>this.receiveEof());transport2.on("error",()=>{var _a22;(_a22=this.pendingWrite)==null?void 0:_a22.call(this,UV_ECONNRESET);this.receiveError(UV_ECONNRESET)});transport2.on("close",()=>{var _a22;(_a22=this.pendingWrite)==null?void 0:_a22.call(this,UV_ECONNRESET);this.receiveEof()})}readStop(){this.transport.pause();return super.readStop()}flushInbound(){super.flushInbound();if(this.reading&&!this.closed&&!this.inboundEof)this.transport.resume()}dispatchWrite(req,buffer2){if(this.closed)return UV_EBADF;streamBaseState[kBytesWritten]=buffer2.byteLength;streamBaseState[kLastWriteWasAsync]=1;this.writeQueueSize=buffer2.byteLength;let offset2=0;let complete=false;const finish=status=>{if(complete)return;complete=true;this.pendingWrite=void 0;this.writeQueueSize=0;queueMicrotask(()=>{var _a22;return(_a22=req.oncomplete)==null?void 0:_a22.call(req,status)})};this.pendingWrite=finish;const next2=()=>{if(complete)return;if(this.closed){finish(UV_EBADF);return}if(offset2===buffer2.byteLength){finish(0);return}const bytes2=buffer2.slice(offset2,offset2+64*1024);offset2+=bytes2.byteLength;this.transport.write(bytes2,error=>{if(error){finish(UV_ECONNRESET);return}this.bytesWritten+=bytes2.byteLength;this.writeQueueSize-=bytes2.byteLength;next2()})};queueMicrotask(next2);return 0}shutdown(req){if(this.closed)return UV_EBADF;this.transport.end(()=>{var _a22;return(_a22=req.oncomplete)==null?void 0:_a22.call(req,0)});return 0}onCloseHandle(){var _a22;(_a22=this.pendingWrite)==null?void 0:_a22.call(this,UV_EBADF);this.transport.destroy()}getsockname(){return UV_ENOTSUP}getpeername(){return UV_ENOTSUP}setNoDelay(){return 0}setKeepAlive(){return 0}};var unsupported=detail=>Object.assign(new Error(`HTTP transport does not support ${detail}.`),{code:"ERR_HTTP_TRANSPORT_UNSUPPORTED"});var local=host2=>host2==="localhost"||host2==="::1"||host2==="[::1]"||/^127\./u.test(host2);var tlsOptions=["ca","cert","key","pfx","passphrase","ciphers","secureContext","checkServerIdentity","minVersion","maxVersion","secureProtocol","secureOptions","session","ALPNProtocols","pskCallback"];function installHttpClientTransport(factory,transportOptions={}){const installed22=new WeakMap;const live2=new Set;const collected=new FinalizationRegistry(ref2=>live2.delete(ref2));const install22=(Agent,protocol,require2)=>{const prototype=Agent.prototype;if(installed22.has(prototype))return;const original=prototype.createConnection;const connect2=function(options,callback){var _a22;const host2=String(options.hostname??options.host??"localhost").toLowerCase();const hostPort=local(host2)&&!options.socketPath&&((_a22=transportOptions.hostPorts)==null?void 0:_a22.call(transportOptions).has(Number(options.port??(protocol==="https:"?443:80))));if(!hostPort&&(protocol==="http:"&&(local(host2)||options.socketPath)||protocol==="https:"&&local(host2)&&!options.socketPath)){return original.call(this,options,callback)}try{if(options.socketPath||options.localAddress||options.localPort||options.lookup||options.family)throw unsupported("custom socket routing");if(protocol==="https:"&&(tlsOptions.some(key=>options[key]!==void 0)||options.rejectUnauthorized===false||options.servername!==void 0&&options.servername!==host2))throw unsupported("custom TLS options");const authority=new URL(`${protocol}//${host2.includes(":")&&!host2.startsWith("[")?`[${host2}]`:host2}:${options.port??(protocol==="https:"?443:80)}`);return connection(authority,factory(),require2)}catch(cause){queueMicrotask(()=>callback(cause instanceof Error?cause:new Error(String(cause))));return void 0}};prototype.createConnection=connect2;installed22.set(prototype,{original,connect:connect2});const ref2=new WeakRef(prototype);live2.add(ref2);collected.register(prototype,ref2,ref2)};install22(httpModule.Agent,"http:");install22(httpsModule.Agent,"https:");const unsubscribe=onNodeLibLoaded((name,value,require2)=>{if(name==="_http_agent")install22(value.Agent,"http:",require2);if(name==="https")install22(value.Agent,"https:",require2)});return()=>{unsubscribe();for(const ref2 of live2){const prototype=ref2.deref();const held=prototype&&installed22.get(prototype);if(prototype&&held&&prototype.createConnection===held.connect)prototype.createConnection=held.original;collected.unregister(ref2)}live2.clear()}}function connection(origin,exchange2,require2){const streams2=require2?require2("stream"):streamModule;const net=require2?require2("net"):netModule;const http=require2?require2("http"):httpModule;const pair=streams2.duplexPair({highWaterMark:64*1024});const client=new net.Socket({handle:new DuplexStreamHandle(pair[0]),readable:true,writable:true});const peer=new net.Socket({handle:new DuplexStreamHandle(pair[1]),readable:true,writable:true});peer.unref();const controller=new AbortController;let reader;const fail3=cause=>{const error=cause instanceof Error?cause:new Error(String(cause));controller.abort(error);client.destroy(error);peer.destroy()};client.once("close",()=>{controller.abort(new Error("HTTP client connection closed."));void(reader==null?void 0:reader.cancel(controller.signal.reason).catch(()=>{}));peer.destroy()});peer.on("error",fail3);const server=http.createServer({maxHeaderSize:32*1024,requestTimeout:0,headersTimeout:0},(request,response)=>{void(async()=>{var _a22,_b22;if(!request.url.startsWith("/")||request.url.startsWith("//"))throw unsupported("absolute-form request targets");const url2=new URL(request.url,origin);if(url2.origin!==origin.origin)throw unsupported("a request target that changes origin");const headers=[];const connectionHeaders=new Set;for(let i22=0;i22<request.rawHeaders.length;i22+=2){const name=request.rawHeaders[i22],value=request.rawHeaders[i22+1];const lower=name.toLowerCase();if(["expect","upgrade","trailer","te"].includes(lower))throw unsupported(`${lower} headers`);if(lower==="host"){if(value.toLowerCase()!==origin.host)throw unsupported("a Host header different from the destination");continue}if(lower==="connection")for(const token of value.split(","))connectionHeaders.add(token.trim().toLowerCase());headers.push([name,value])}const outgoing=headers.filter(([name])=>!["connection","keep-alive","transfer-encoding"].includes(name.toLowerCase())&&!connectionHeaders.has(name.toLowerCase()));const carriesBody=request.headers["transfer-encoding"]!==void 0||Number(request.headers["content-length"]??0)>0;const Readable2=streams2.Readable;const body=carriesBody?Readable2.toWeb(request,{strategy:{highWaterMark:64*1024,size:chunk=>chunk.byteLength}}):void 0;if(!carriesBody)request.resume();const result=await exchange2({url:url2.href,method:request.method,headers:outgoing,...body?{body}:{},signal:controller.signal,profile:"server-http"});if(controller.signal.aborted){await((_a22=result.body)==null?void 0:_a22.cancel(controller.signal.reason));return}response.shouldKeepAlive=false;response.sendDate=false;response.writeHead(result.status,result.statusText,result.headers.flat());reader=(_b22=result.body)==null?void 0:_b22.getReader();try{for(;;){controller.signal.throwIfAborted();const next2=reader?await reader.read():{done:true,value:void 0};if(next2.done)break;if(!response.write(next2.value))await new Promise((resolve2,reject)=>{const abort=()=>{response.removeListener("drain",drain);reject(controller.signal.reason)};const drain=()=>{controller.signal.removeEventListener("abort",abort);resolve2()};response.once("drain",drain);controller.signal.addEventListener("abort",abort,{once:true});if(controller.signal.aborted)abort()})}response.end()}catch(cause){await(reader==null?void 0:reader.cancel(cause).catch(()=>{}));throw cause}finally{reader==null?void 0:reader.releaseLock();reader=void 0}})().catch(fail3)});for(const name of["connect","upgrade","checkContinue","checkExpectation"])server.on(name,()=>fail3(unsupported(name)));server.on("clientError",fail3);server.emit("connection",peer);return client}var DEFAULT_REGISTRY="https://registry.npmjs.org";var Registry=class{constructor(options={}){__publicField2(this,"registryUrl");__publicField2(this,"registryScopes");__publicField2(this,"cache");this.registryUrl=options.registry||DEFAULT_REGISTRY;this.registryScopes=options.registryScopes;this.cache=options.cache||new Map}registryFor(packageName){const scopes2=this.registryScopes??globalThis.__browserRuntimeRegistryScopes;if(scopes2&&typeof packageName==="string"){const scope4=packageName.startsWith("@")&&packageName.includes("/")?packageName.slice(0,packageName.indexOf("/")):packageName;const url2=scopes2[scope4]??scopes2[packageName];if(typeof url2==="string"&&url2!=="")return url2.endsWith("/")?url2.slice(0,-1):url2}return this.registryUrl}async getPackageManifest(packageName){if(this.cache.has(packageName)){return this.cache.get(packageName)}const __docs=globalThis.__browserRuntimeLockfileManifests;const __doc=__docs instanceof Map?__docs.get(packageName):void 0;if(__doc){const __tarball=`${this.registryFor(packageName)}/${encodePackageName(packageName)}/-/${packageName.slice(packageName.lastIndexOf("/")+1)}-${__doc.version}.tgz`;const __manifest={"dist-tags":{latest:__doc.version},versions:{[__doc.version]:{name:packageName,version:__doc.version,dist:{tarball:__tarball},dependencies:__doc.dependencies,...__doc.peerDependencies?{peerDependencies:__doc.peerDependencies,peerDependenciesMeta:__doc.peerDependenciesMeta||{}}:{},...__doc.optionalDependencies?{optionalDependencies:__doc.optionalDependencies}:{}}}};this.cache.set(packageName,__manifest);return __manifest}const __pins=globalThis.__browserRuntimeLockfilePins;const __pin=__pins instanceof Map?__pins.get(packageName):void 0;if(typeof __pin==="string"){const pinnedUrl=`${this.registryFor(packageName)}/${encodePackageName(packageName)}/${__pin}`;const pinnedResponse=await fetch(pinnedUrl,{headers:{Accept:"application/json"}});if(pinnedResponse.ok){const versionData=await pinnedResponse.json();if(versionData&&versionData.dist&&versionData.dist.tarball){const pinnedManifest={"dist-tags":{latest:__pin},versions:{[__pin]:versionData}};this.cache.set(packageName,pinnedManifest);return pinnedManifest}}}const url2=`${this.registryFor(packageName)}/${encodePackageName(packageName)}`;const response=await fetch(url2,{headers:{Accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8"}});if(!response.ok){if(response.status===404){throw new Error(`Package not found: ${packageName}`)}throw new Error(`Failed to fetch package ${packageName}: ${response.status}`)}const manifest=await response.json();this.cache.set(packageName,manifest);return manifest}async getPackageVersion(packageName,version2){const manifest=await this.getPackageManifest(packageName);if(manifest["dist-tags"][version2]){version2=manifest["dist-tags"][version2]}const versionData=manifest.versions[version2];if(!versionData){throw new Error(`Version ${version2} not found for package ${packageName}`)}return versionData}async getLatestVersion(packageName){const manifest=await this.getPackageManifest(packageName);return manifest["dist-tags"].latest}async getVersions(packageName){const manifest=await this.getPackageManifest(packageName);return Object.keys(manifest.versions)}async downloadTarball(tarballUrl){const response=await fetch(tarballUrl);if(!response.ok){throw new Error(`Failed to download tarball: ${response.status}`)}return response.arrayBuffer()}clearCache(){this.cache.clear()}};function encodePackageName(name){return name.replace("/","%2f")}new Registry;function parseVersion(version2){const match2=version2.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!match2)return null;return{major:parseInt(match2[1],10),minor:parseInt(match2[2],10),patch:parseInt(match2[3],10),prerelease:match2[4]}}function compareVersions(a,b){const parsedA=parseVersion(a);const parsedB=parseVersion(b);if(!parsedA||!parsedB){return a.localeCompare(b)}if(parsedA.major!==parsedB.major){return parsedA.major-parsedB.major}if(parsedA.minor!==parsedB.minor){return parsedA.minor-parsedB.minor}if(parsedA.patch!==parsedB.patch){return parsedA.patch-parsedB.patch}if(parsedA.prerelease&&!parsedB.prerelease)return-1;if(!parsedA.prerelease&&parsedB.prerelease)return 1;if(parsedA.prerelease&&parsedB.prerelease){return parsedA.prerelease.localeCompare(parsedB.prerelease)}return 0}function satisfies(version2,range22){const parsed=parseVersion(version2);if(!parsed)return false;if(parsed.prerelease&&!range22.includes("-")){return false}range22=range22.trim();range22=range22.replace(/^=\s*/,"").replace(/^v(?=\d)/,"");range22=range22.replace(/(>=|<=|>|<|=)\s*(\d+)(\.\d+)?(?![.\d])/g,(__m,__op,__major,__minor)=>__op+" "+__major+(__minor===void 0?".0.0":__minor+".0"));const __browserRuntimePartialRange=range22.match(/^([~^])(\d+)(?:\.(\d+))?(?:\.(\d+))?$/);if(__browserRuntimePartialRange){const operator=__browserRuntimePartialRange[1];const major=Number(__browserRuntimePartialRange[2]);const hasMinor=__browserRuntimePartialRange[3]!==void 0;const hasPatch=__browserRuntimePartialRange[4]!==void 0;const minor=Number(__browserRuntimePartialRange[3]??0);const patch=Number(__browserRuntimePartialRange[4]??0);const lower=major+"."+minor+"."+patch;let upper;if(operator==="~"){upper=hasMinor?major+"."+(minor+1)+".0":major+1+".0.0"}else if(major>0||!hasMinor){upper=major+1+".0.0"}else if(minor>0||!hasPatch){upper="0."+(minor+1)+".0"}else{upper="0.0."+(patch+1)}return compareVersions(version2,lower)>=0&&compareVersions(version2,upper)<0}if(/^\d+\.\d+\.\d+/.test(range22)&&!range22.includes(" ")){const rangeMatch=range22.match(/^(\d+\.\d+\.\d+(?:-[^\s]+)?)/);if(rangeMatch){return compareVersions(version2,rangeMatch[1])===0}}if(range22==="*"||range22==="latest"||range22===""){return true}if(range22.includes("||")){return range22.split("||").some(r10=>satisfies(version2,r10.trim()))}if(range22.includes(" - ")){const[min2,max2]=range22.split(" - ").map(s10=>s10.trim());return compareVersions(version2,min2)>=0&&compareVersions(version2,max2)<=0}const operatorMatches=range22.match(/(>=|<=|>|<|=)?\s*(\d+\.\d+\.\d+(?:-[^\s]*)?)/g);if(operatorMatches&&operatorMatches.length>1){return operatorMatches.every(match2=>{const m=match2.match(/^(>=|<=|>|<|=)?\s*(\d+\.\d+\.\d+(?:-[^\s]*)?)$/);if(!m)return true;const op2=m[1]||"=";const ver=m[2];switch(op2){case">=":return compareVersions(version2,ver)>=0;case"<=":return compareVersions(version2,ver)<=0;case">":return compareVersions(version2,ver)>0;case"<":return compareVersions(version2,ver)<0;case"=":return compareVersions(version2,ver)===0;default:return compareVersions(version2,ver)===0}})}if(range22.startsWith("^")){const base=range22.slice(1);const baseParsed=parseVersion(base);if(!baseParsed)return false;if(parsed.major!==baseParsed.major){return false}if(baseParsed.major===0){if(baseParsed.minor!==0&&parsed.minor!==baseParsed.minor){return false}if(baseParsed.minor===0&&parsed.minor!==0){return false}}return compareVersions(version2,base)>=0}if(range22.startsWith("~")){const base=range22.slice(1);const baseParsed=parseVersion(base);if(!baseParsed)return false;if(parsed.major!==baseParsed.major||parsed.minor!==baseParsed.minor){return false}return compareVersions(version2,base)>=0}if(range22.startsWith(">=")){const base=range22.slice(2).trim();return compareVersions(version2,base)>=0}if(range22.startsWith(">")){const base=range22.slice(1).trim();return compareVersions(version2,base)>0}if(range22.startsWith("<=")){const base=range22.slice(2).trim();return compareVersions(version2,base)<=0}if(range22.startsWith("<")){const base=range22.slice(1).trim();return compareVersions(version2,base)<0}if(range22.includes("x")||range22.includes("X")||/^\d+$/.test(range22)||/^\d+\.\d+$/.test(range22)){const parts=range22.replace(/[xX]/g,"").split(".").filter(Boolean);if(parts.length===1){return parsed.major===parseInt(parts[0],10)}if(parts.length===2){return parsed.major===parseInt(parts[0],10)&&parsed.minor===parseInt(parts[1],10)}}if(range22.includes(" ")){const conditions=range22.split(/\s+/).filter(Boolean);return conditions.every(r10=>satisfies(version2,r10))}return compareVersions(version2,range22)===0}function findBestVersion(versions,range22){const sorted=[...versions].sort((a,b)=>compareVersions(b,a));for(const version2 of sorted){if(satisfies(version2,range22)){return version2}}return null}async function resolveDependencies(packageName,versionRange="latest",options={}){const registry=options.registry||new Registry;const context2={registry,resolved:new Map,resolving:new Set,options};await resolvePackage(packageName,versionRange,context2);context2.resolved.__nested=context2.nested;return context2.resolved}async function resolveFromPackageJson(packageJson,options={}){const registry=options.registry||new Registry;const context2={registry,resolved:new Map,resolving:new Set,options};const deps={...packageJson.dependencies};if(options.includeDev&&packageJson.devDependencies){Object.assign(deps,packageJson.devDependencies)}const __pins=globalThis.__browserRuntimeLockfilePins;if(__pins instanceof Map&&__pins.size>0){const __names=[...__pins.keys()];for(let __index=0;__index<__names.length;__index+=32){await Promise.all(__names.slice(__index,__index+32).map(name3=>registry.getPackageManifest(name3).catch(()=>void 0)))}}context2.rootDeps=new Map;for(const[name,range22]of Object.entries(deps)){await resolvePackage(name,range22,context2,void 0,"choose")}for(const[name,range22]of Object.entries(deps)){await resolvePackage(name,range22,context2,void 0,"descend")}context2.resolved.__nested=context2.nested;return context2.resolved}async function __browserRuntimeNest(packageName,versionRange,context2,parentKey,registryName=packageName){const records=globalThis.__browserRuntimeLockfileRecords;const versions=records instanceof Map?records.get(packageName):void 0;if(!versions)return;const candidates=[...versions.keys()].filter(version22=>satisfies(version22,versionRange)).sort((a,b)=>compareVersions(b,a));const version2=candidates[0];if(!version2)return;const nestedKey=parentKey?`${parentKey}/node_modules/${packageName}`:packageName;context2.nested??(context2.nested=new Map);if(context2.nested.has(nestedKey)||context2.resolving.has(nestedKey))return;context2.resolving.add(nestedKey);try{const doc=versions.get(version2);const tarballUrl=doc.resolved||`${context2.registry.registryFor(registryName)}/${encodePackageName(registryName)}/-/${registryName.slice(registryName.lastIndexOf("/")+1)}-${version2}.tgz`;context2.nested.set(nestedKey,{name:packageName,version:version2,tarballUrl,dependencies:doc.dependencies||{}});const deps={};if(doc.peerDependencies){const meta=doc.peerDependenciesMeta||{};for(const[name2,range22]of Object.entries(doc.peerDependencies)){if(!(meta[name2]&&meta[name2].optional))deps[name2]=range22}}Object.assign(deps,doc.dependencies);if(context2.options.includeOptional&&doc.optionalDependencies)Object.assign(deps,doc.optionalDependencies);for(const[depName,depRange]of Object.entries(deps)){await resolvePackage(depName,depRange,context2,nestedKey)}}finally{context2.resolving.delete(nestedKey)}}async function resolvePackage(packageName,versionRange,context2,__parent,phase){var _a22,_b22,_c22;if(phase==="descend"){const chosen=(_a22=context2.rootDeps)==null?void 0:_a22.get(packageName);if(!chosen)return;context2.rootDeps.delete(packageName);await descendInto(packageName,chosen,context2);return}let __registryName=packageName;if(typeof versionRange==="string"&&versionRange.startsWith("npm:")){const __spec=versionRange.slice(4);const __at=__spec.lastIndexOf("@");__registryName=__at>0?__spec.slice(0,__at):__spec;versionRange=__at>0?__spec.slice(__at+1):"latest"}const{registry,resolved,resolving,options}=context2;const key=`${packageName}@${versionRange}`;if(resolving.has(key)){return}if(resolved.has(packageName)){const existing=resolved.get(packageName);if(satisfies(existing.version,versionRange)){return}await __browserRuntimeNest(packageName,versionRange,context2,__parent,typeof __registryName==="string"?__registryName:packageName);return}resolving.add(key);try{(_b22=options.onProgress)==null?void 0:_b22.call(options,`Resolving ${packageName}@${versionRange}`);const manifest=await registry.getPackageManifest(__registryName);const versions=Object.keys(manifest.versions);let targetVersion;const __pinned=globalThis.__browserRuntimeLockfilePins;const __pin=__pinned instanceof Map?__pinned.get(__registryName):void 0;if(typeof __pin==="string"&&manifest.versions[__pin]){const versionData2=manifest.versions[__pin];const resolvedPackage2={name:packageName,version:__pin,tarballUrl:versionData2.dist.tarball,dependencies:versionData2.dependencies||{}};resolved.set(packageName,resolvedPackage2);const deps2={};if(versionData2.peerDependencies){const meta2=versionData2.peerDependenciesMeta||{};for(const[name3,range22]of Object.entries(versionData2.peerDependencies)){if(!(meta2[name3]==null?void 0:meta2[name3].optional))deps2[name3]=range22}}Object.assign(deps2,versionData2.dependencies);if(options.includeOptional&&versionData2.optionalDependencies){Object.assign(deps2,versionData2.optionalDependencies)}if(phase==="choose")context2.rootDeps.set(packageName,deps2);else await descendInto(packageName,deps2,context2);if(!satisfies(__pin,versionRange))await __browserRuntimeNest(packageName,versionRange,context2,__parent,__registryName);return}if(versionRange==="latest"||versionRange==="*"){targetVersion=manifest["dist-tags"].latest}else if(manifest["dist-tags"][versionRange]){targetVersion=manifest["dist-tags"][versionRange]}else{const best=findBestVersion(versions,versionRange);if(!best){throw new Error(`No matching version found for ${packageName}@${versionRange}`)}targetVersion=best}const versionData=manifest.versions[targetVersion];const resolvedPackage={name:packageName,version:targetVersion,tarballUrl:versionData.dist.tarball,dependencies:versionData.dependencies||{}};resolved.set(packageName,resolvedPackage);const deps={};if(versionData.peerDependencies){const meta=versionData.peerDependenciesMeta||{};for(const[name,range22]of Object.entries(versionData.peerDependencies)){if(!((_c22=meta[name])==null?void 0:_c22.optional)){deps[name]=range22}}}Object.assign(deps,versionData.dependencies);if(options.includeOptional&&versionData.optionalDependencies){Object.assign(deps,versionData.optionalDependencies)}if(phase==="choose")context2.rootDeps.set(packageName,deps);else await descendInto(packageName,deps,context2)}finally{resolving.delete(key)}}async function descendInto(packageName,deps,context2){const depEntries=Object.entries(deps);if(depEntries.length===0)return;const CONCURRENCY=8;for(let i22=0;i22<depEntries.length;i22+=CONCURRENCY){const batch=depEntries.slice(i22,i22+CONCURRENCY);await Promise.all(batch.map(([depName,depRange])=>resolvePackage(depName,depRange,context2,packageName)))}}function*parseTar(data2){new TextDecoder;let offset2=0;let __nextName;while(offset2<data2.length-512){const header=data2.slice(offset2,offset2+512);offset2+=512;if(header.every(b=>b===0)){break}const name=parseString(header,0,100);const mode=parseOctal(header,100,8);const size=parseOctal(header,124,12);const typeFlag=String.fromCharCode(header[156]);const linkName=parseString(header,157,100);const prefix2=parseString(header,345,155);if(!name){continue}const fullName=__nextName!==void 0?__nextName:prefix2?`${prefix2}/${name}`:name;__nextName=void 0;let type2;switch(typeFlag){case"0":case"\0":case"":type2="file";break;case"5":type2="directory";break;case"1":case"2":type2="symlink";break;default:type2="unknown"}let content;const __payload=size>0?Math.ceil(size/512)*512:0;if(typeFlag==="x"||typeFlag==="L"){const __text=new TextDecoder().decode(data2.slice(offset2,offset2+size));offset2+=__payload;if(typeFlag==="L"){__nextName=__text.replace(/\0+$/,"")}else{for(const __line of __text.split("\n")){const __match=/^\d+ path=(.*)$/.exec(__line);if(__match)__nextName=__match[1]}}continue}if(type2==="file"){content=size>0?data2.slice(offset2,offset2+size):new Uint8Array(0)}offset2+=__payload;yield{name:fullName,type:type2,size,mode,content,linkTarget:type2==="symlink"?linkName:void 0}}}function parseString(data2,offset2,length){const bytes2=data2.slice(offset2,offset2+length);const nullIndex=bytes2.indexOf(0);const actualBytes=nullIndex>=0?bytes2.slice(0,nullIndex):bytes2;return new TextDecoder().decode(actualBytes)}function parseOctal(data2,offset2,length){const str=parseString(data2,offset2,length).trim();return parseInt(str,8)||0}function decompress2(data2){const input=data2 instanceof Uint8Array?data2:new Uint8Array(data2);return pako.inflate(input)}function extractTarball(tarballData,vfs2,destPath,options={}){const{stripComponents=1,filter:filter2,onProgress}=options;onProgress==null?void 0:onProgress("Decompressing...");const tarData=decompress2(tarballData);const extractedFiles=[];for(const entry of parseTar(tarData)){if(entry.type!=="file"&&entry.type!=="directory"){continue}let entryPath=entry.name;if(stripComponents>0){const parts=entryPath.split("/").filter(Boolean);if(parts.length<=stripComponents){continue}entryPath=parts.slice(stripComponents).join("/")}if(filter2&&!filter2(entryPath)){continue}const fullPath=join2(destPath,entryPath);if(entry.type==="directory"){vfs2.mkdirSync(fullPath,{recursive:true})}else if(entry.type==="file"&&entry.content){const parentDir=dirname(fullPath);vfs2.mkdirSync(parentDir,{recursive:true});vfs2.writeFileSync(fullPath,entry.content);extractedFiles.push(fullPath)}}onProgress==null?void 0:onProgress(`Extracted ${extractedFiles.length} files`);return extractedFiles}globalThis[Symbol.for("@volter/browser-runtime/package-extract")]=extractTarball;async function __browserRuntimeInstallPool(items,size,work){let next2=0;await Promise.all(Array.from({length:Math.min(size,items.length)},async()=>{for(;;){const index2=next2++;if(index2>=items.length)return;await work(items[index2])}}))}async function downloadAndExtract(url2,vfs2,destPath,options={}){const{onProgress}=options;onProgress==null?void 0:onProgress(`Downloading ${url2}...`);const response=await fetch(url2);if(!response.ok){throw new Error(`Failed to download tarball: ${response.status}`)}const data2=await response.arrayBuffer();return extractTarball(data2,vfs2,destPath,options)}var isBrowser=typeof window!=="undefined";var NODE_DYNAMIC_IMPORT_BUILTINS=["stream/web","fs/promises","stream/promises","stream/consumers","timers/promises","dns/promises","readline/promises","path/posix","path/win32","util/types","assert/strict","assert","buffer","constants","child_process","cluster","crypto","dgram","dns","events","fs","http","http2","https","net","os","path","perf_hooks","querystring","readline","stream","string_decoder","timers","tls","url","util","v8","vm","worker_threads","zlib","async_hooks","inspector","module"];function lowerDynamicBuiltinImports(code22){let lowered=code22.replace(/\bimport\s*\(\s*["']node:([^"']+)["']\s*\)/g,'Promise.resolve(require("node:$1"))');for(const builtin of NODE_DYNAMIC_IMPORT_BUILTINS){const pattern=new RegExp(`\\bimport\\s*\\(\\s*["']${builtin}["']\\s*\\)`,"g");lowered=lowered.replace(pattern,`Promise.resolve(require("${builtin}"))`)}return lowered}async function initTransformer(){if(getEsbuildInstance())return;if(!isBrowser){console.log("[transform] Skipping esbuild init (not in browser)");return}if(window.__esbuild){console.log("[transform] Reusing existing esbuild instance");return}if(window.__esbuildInitPromise){return window.__esbuildInitPromise}window.__esbuildInitPromise=(async()=>{try{console.log("[transform] Loading esbuild-wasm...");const mod=await import(ESBUILD_WASM_ESM_CDN);const esbuildMod=mod.default||mod;try{await esbuildMod.initialize({wasmURL:ESBUILD_WASM_BINARY_CDN});console.log("[transform] esbuild-wasm initialized")}catch(initError){if(initError instanceof Error&&initError.message.includes('Cannot call "initialize" more than once')){console.log("[transform] esbuild-wasm already initialized, reusing")}else{throw initError}}window.__esbuild=esbuildMod}catch(error){console.error("[transform] Failed to initialize esbuild:",error);window.__esbuildInitPromise=void 0;throw error}})();return window.__esbuildInitPromise}function isTransformerReady(){if(getEsbuildInstance())return true;if(!isBrowser)return true;return window.__esbuild!==void 0}async function transformFile(code22,filename){if(!getEsbuildInstance()&&!isBrowser){return code22}if(!getEsbuildInstance()&&!window.__esbuild){await initTransformer()}const esbuild2=getEsbuildInstance()??window.__esbuild;if(!esbuild2){throw new Error("esbuild not initialized")}let loader="js";if(filename.endsWith(".jsx"))loader="jsx";else if(filename.endsWith(".ts"))loader="ts";else if(filename.endsWith(".tsx"))loader="tsx";else if(filename.endsWith(".mjs"))loader="js";try{const result=await esbuild2.transform(code22,{loader,format:"cjs",target:"esnext",platform:"neutral",define:{"import.meta.url":"import_meta.url","import.meta.dirname":"import_meta.dirname","import.meta.filename":"import_meta.filename","import.meta":"import_meta"}});const transformed=lowerDynamicBuiltinImports(result.code);return transformed}catch(error){const errorMsg=error instanceof Error?error.message:String(error);if(errorMsg.includes("Top-level await")){console.log(`[transform] Skipping ${filename} (has top-level await, likely CLI entry point)`);return code22}console.warn(`[transform] Failed to transform ${filename}:`,error);return code22}}function needsTransform(filename,code22){if(filename.endsWith(".mjs")){return true}if(filename.endsWith(".cjs")){return false}const hasImport=/\bimport\s+[\w{*'"]/m.test(code22);const hasExport=/\bexport\s+(?:default|const|let|var|function|class|{|\*)/m.test(code22);const hasImportMeta=/\bimport\.meta\b/.test(code22);return hasImport||hasExport||hasImportMeta}function hasDynamicNodeImports(code22){if(/\bimport\s*\(\s*["']node:/.test(code22)){return true}const names2=NODE_DYNAMIC_IMPORT_BUILTINS.map(name=>name.replace("/","\\/")).join("|");return new RegExp(`\\bimport\\s*\\(\\s*["'](?:${names2})["']\\s*\\)`).test(code22)}function patchDynamicImports(code22){return lowerDynamicBuiltinImports(code22)}async function transformPackage(vfs2,pkgPath,onProgress){let transformedCount=0;const jsFiles=findJsFiles(vfs2,pkgPath);onProgress==null?void 0:onProgress(` Transforming ${jsFiles.length} files in ${pkgPath}...`);const BATCH_SIZE=10;for(let i22=0;i22<jsFiles.length;i22+=BATCH_SIZE){const batch=jsFiles.slice(i22,i22+BATCH_SIZE);await Promise.all(batch.map(async filePath=>{try{const code22=vfs2.readFileSync(filePath,"utf8");if(needsTransform(filePath,code22)){const transformed=await transformFile(code22,filePath);vfs2.writeFileSync(filePath,transformed);transformedCount++}else if(hasDynamicNodeImports(code22)){const patched=patchDynamicImports(code22);vfs2.writeFileSync(filePath,patched);transformedCount++}}catch(error){console.warn(`[transform] Skipping ${filePath}:`,error)}}))}return transformedCount}function findJsFiles(vfs2,dir){const files=[];try{const entries=vfs2.readdirSync(dir);for(const entry of entries){const fullPath=dir+"/"+entry;try{const stat2=vfs2.statSync(fullPath);if(stat2.isDirectory()){if(entry!=="node_modules"){files.push(...findJsFiles(vfs2,fullPath))}}else if(entry.endsWith(".js")||entry.endsWith(".mjs")||entry.endsWith(".jsx")){files.push(fullPath)}}catch{}}}catch{}return files}var installTransformEnabled=false;function setInstallTransformEnabled(enabled){installTransformEnabled=enabled}function normalizeBin(pkgName,bin){if(!bin)return{};if(typeof bin==="string"){const cmdName=pkgName.includes("/")?pkgName.split("/").pop():pkgName;return{[cmdName]:bin}}return bin}var PackageManager=class{constructor(vfs2,options={}){__publicField2(this,"vfs");__publicField2(this,"registry");__publicField2(this,"cwd");this.vfs=vfs2;this.registry=new Registry(options);this.cwd=options.cwd||"/"}async install(packageSpec,options={}){const{onProgress}=options;const{name,version:version2}=parsePackageSpec(packageSpec);onProgress==null?void 0:onProgress(`Resolving ${name}@${version2||"latest"}...`);const resolved=await resolveDependencies(name,version2||"latest",{registry:this.registry,includeDev:options.includeDev,includeOptional:options.includeOptional,onProgress});const added=await this.installResolved(resolved,options);if(options.save||options.saveDev){const pkgToAdd=resolved.get(name);if(pkgToAdd){await this.updatePackageJson(name,`^${pkgToAdd.version}`,options.saveDev||false)}}onProgress==null?void 0:onProgress(`Installed ${resolved.size} packages`);return{installed:resolved,added}}async installFromPackageJson(options={}){var _a22;const{onProgress}=options;const pkgJsonPath=join2(this.cwd,"package.json");if(!this.vfs.existsSync(pkgJsonPath)){throw new Error("No package.json found")}const pkgJson=((_a22=this.vfs[Symbol.for("@volter/browser-node/workspace-install-manifests")])==null?void 0:_a22.get(this.cwd))??JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"));onProgress==null?void 0:onProgress("Resolving dependencies...");const resolved=await resolveFromPackageJson(pkgJson,{registry:this.registry,includeDev:options.includeDev,includeOptional:options.includeOptional,onProgress});const added=await this.installResolved(resolved,options);onProgress==null?void 0:onProgress(`Installed ${resolved.size} packages`);return{installed:resolved,added}}async installResolved(resolved,options){const{onProgress}=options;const added=[];const nodeModulesPath=join2(this.cwd,"node_modules");this.vfs.mkdirSync(nodeModulesPath,{recursive:true});const toInstall=[];for(const[name,pkg]of resolved){const pkgPath=join2(nodeModulesPath,name);const existingPkgJson=join2(pkgPath,"package.json");if(this.vfs.existsSync(existingPkgJson)){try{const existing=JSON.parse(this.vfs.readFileSync(existingPkgJson,"utf8"));if(existing.version===pkg.version){onProgress==null?void 0:onProgress(`Skipping ${name}@${pkg.version} (already installed)`);continue}}catch{}}toInstall.push({name,pkg,pkgPath})}for(const[nestedKey,pkg]of resolved.__nested instanceof Map?resolved.__nested:[]){toInstall.push({name:pkg.name,pkg,pkgPath:join2(nodeModulesPath,nestedKey)})}const shouldTransform=installTransformEnabled;if(shouldTransform&&!isTransformerReady()){onProgress==null?void 0:onProgress("Initializing ESM transformer...");await initTransformer()}const CONCURRENCY=16;onProgress==null?void 0:onProgress(`Installing ${toInstall.length} packages...`);await __browserRuntimeInstallPool(toInstall,CONCURRENCY,async({name,pkg,pkgPath})=>{onProgress==null?void 0:onProgress(` Downloading ${name}@${pkg.version}...`);const __installHook=globalThis[Symbol.for("@volter/browser-runtime/package-install")];if(!(__installHook&&await __installHook(name,pkg,pkgPath,this.vfs))){await downloadAndExtract(pkg.tarballUrl,this.vfs,pkgPath,{stripComponents:1})}if(shouldTransform){try{const count=await transformPackage(this.vfs,pkgPath,onProgress);if(count>0){onProgress==null?void 0:onProgress(` Transformed ${count} files in ${name}`)}}catch(transformError){onProgress==null?void 0:onProgress(` Warning: Transform failed for ${name}: ${transformError}`)}}try{const pkgJsonPath=join2(pkgPath,"package.json");if(this.vfs.existsSync(pkgJsonPath)){const pkgJson=JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"));const binEntries=normalizeBin(name,pkgJson.bin);const binDir=join2(pkgPath.slice(0,pkgPath.lastIndexOf("/node_modules/")+"/node_modules".length),".bin");for(const[cmdName,entryPath]of Object.entries(binEntries)){this.vfs.mkdirSync(binDir,{recursive:true});const targetPath=join2(pkgPath,entryPath);this.vfs.writeFileSync(join2(binDir,cmdName),`node "${targetPath}" "$@"
|
|
5892
|
-
`)}}}catch{}added.push(name)});await this.writeLockfile(resolved);return added}async writeLockfile(resolved){const lockfile={};for(const[name,pkg]of resolved){lockfile[name]={version:pkg.version,resolved:pkg.tarballUrl}}const lockfilePath=join2(this.cwd,"node_modules",".package-lock.json");this.vfs.writeFileSync(lockfilePath,JSON.stringify(lockfile,null,2))}async updatePackageJson(packageName,version2,isDev){const pkgJsonPath=join2(this.cwd,"package.json");let pkgJson={};if(this.vfs.existsSync(pkgJsonPath)){pkgJson=JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"))}const field=isDev?"devDependencies":"dependencies";if(!pkgJson[field]){pkgJson[field]={}}pkgJson[field][packageName]=version2;this.vfs.writeFileSync(pkgJsonPath,JSON.stringify(pkgJson,null,2))}list(){const nodeModulesPath=join2(this.cwd,"node_modules");if(!this.vfs.existsSync(nodeModulesPath)){return{}}const packages2={};const entries=this.vfs.readdirSync(nodeModulesPath);for(const entry of entries){if(entry.startsWith("."))continue;if(entry.startsWith("@")){const scopePath=join2(nodeModulesPath,entry);const scopedPkgs=this.vfs.readdirSync(scopePath);for(const scopedPkg of scopedPkgs){const pkgJsonPath=join2(scopePath,scopedPkg,"package.json");if(this.vfs.existsSync(pkgJsonPath)){const pkgJson=JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"));packages2[`${entry}/${scopedPkg}`]=pkgJson.version}}}else{const pkgJsonPath=join2(nodeModulesPath,entry,"package.json");if(this.vfs.existsSync(pkgJsonPath)){const pkgJson=JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"));packages2[entry]=pkgJson.version}}}return packages2}};function parsePackageSpec(spec){if(spec.startsWith("@")){const slashIndex=spec.indexOf("/");if(slashIndex===-1){throw new Error(`Invalid package spec: ${spec}`)}const afterSlash=spec.slice(slashIndex+1);const atIndex2=afterSlash.indexOf("@");if(atIndex2===-1){return{name:spec}}return{name:spec.slice(0,slashIndex+1+atIndex2),version:afterSlash.slice(atIndex2+1)}}const atIndex=spec.indexOf("@");if(atIndex===-1){return{name:spec}}return{name:spec.slice(0,atIndex),version:spec.slice(atIndex+1)}}async function install(packageSpec,vfs2,options){const pm=new PackageManager(vfs2);return pm.install(packageSpec,options)}var index=Object.freeze(Object.defineProperty({__proto__:null,PackageManager,Registry,install,parsePackageSpec,setInstallTransformEnabled},Symbol.toStringTag,{value:"Module"}));function __listening(port2){return listenerOnPort(port2)!==void 0}function requestHead(method,url2,headers,body){const lines=[`${method.toUpperCase()} ${url2} HTTP/1.1`];let hasLength=false;let hasEncoding=false;for(const[name,value]of Object.entries(headers)){const lower=name.toLowerCase();if(lower==="content-length")hasLength=true;if(lower==="transfer-encoding")hasEncoding=true;if(lower==="connection")continue;lines.push(`${name}: ${value}`)}if(!hasLength&&!hasEncoding)lines.push(`Content-Length: ${body?body.length:0}`);lines.push("Connection: close","","");return lines.join("\r\n")}function responseParser(collected,onHead,onChunk){const parser=new HTTPParser;parser.initialize(HTTPParser.RESPONSE,null,0,0);parser[HTTPParser.kOnHeadersComplete]=(_major,_minor,headers,_method,_url2,statusCode,statusMessage,upgrade)=>{if(collected.complete)return 0;collected.statusCode=statusCode;collected.statusMessage=statusMessage;collected.upgrade=upgrade;for(let index2=0;index2+1<headers.length;index2+=2){const name=headers[index2].toLowerCase();const value=headers[index2+1];collected.headers[name]=collected.headers[name]===void 0?value:`${collected.headers[name]}, ${value}`}onHead==null?void 0:onHead();return 0};parser[HTTPParser.kOnBody]=chunk=>{if(collected.complete)return;if(onChunk)onChunk(chunk);else collected.chunks.push(chunk)};parser[HTTPParser.kOnMessageComplete]=()=>{if(collected.complete)return collected.upgrade?0:-1;collected.complete=true;if(collected.upgrade)return 0;parser.pause();return-1};return parser}function emptyCollected(){return{statusCode:0,statusMessage:"",headers:{},chunks:[],complete:false,upgrade:false}}function ownedConcat(chunks){let total=0;for(const chunk of chunks)total+=chunk.byteLength;const joined=new Uint8Array(total);let at22=0;for(const chunk of chunks){joined.set(new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength),at22);at22+=chunk.byteLength}return joined}function serviceUnavailable(port2){return{statusCode:503,statusMessage:"Service Unavailable",headers:{"Content-Type":"text/plain"},body:ownedConcat([Buffer$9.from(`No server listening on port ${port2}`)])}}function __requestOverLoopback(port2,method,url2,headers,body){if(!__listening(port2))return Promise.resolve(serviceUnavailable(port2));return new Promise(resolve2=>{const collected=emptyCollected();const parser=responseParser(collected);let settled=false;const answer2=()=>{if(settled)return;settled=true;parser.free();resolve2({statusCode:collected.statusCode||502,statusMessage:collected.statusMessage,headers:collected.headers,body:ownedConcat(collected.chunks)})};const socket=netModule.connect({port:port2,host:"127.0.0.1"});socket.on("data",chunk=>{if(settled)return;const read=parser.execute(chunk);if(read instanceof Error){socket.destroy();answer2()}else if(collected.complete){socket.destroy();answer2()}});socket.on("end",()=>{if(!settled){parser.finish()}answer2()});socket.on("close",answer2);socket.on("error",()=>{if(settled)return;settled=true;parser.free();resolve2(serviceUnavailable(port2))});socket.write(requestHead(method,url2,headers,body));if(body&&body.length>0)socket.write(body)})}function __streamOverLoopback(port2,method,url2,headers,body,onStart,onChunk,onEnd,flow){if(!__listening(port2)){onStart(503,"Service Unavailable",{"Content-Type":"text/plain"});onEnd();return Promise.resolve()}return new Promise(resolve2=>{var _a22;const collected=emptyCollected();let started2=false;let ended2=false;const finish=()=>{if(ended2)return;ended2=true;parser.free();onEnd();resolve2()};const parser=responseParser(collected,()=>{started2=true;onStart(collected.statusCode,collected.statusMessage,collected.headers)},chunk=>onChunk(chunk));const socket=netModule.connect({port:port2,host:"127.0.0.1"});(_a22=flow==null?void 0:flow.control)==null?void 0:_a22.call(flow,()=>socket.pause(),()=>socket.resume());if(flow==null?void 0:flow.signal){if(flow.signal.aborted){socket.destroy();finish();return}flow.signal.addEventListener("abort",()=>{socket.destroy();finish()},{once:true})}socket.on("data",chunk=>{if(ended2)return;const read=parser.execute(chunk);if(read instanceof Error){socket.destroy();finish()}else if(collected.complete){socket.destroy();finish()}});socket.on("end",()=>{if(!ended2){parser.finish()}finish()});socket.on("close",finish);socket.on("error",()=>{if(!started2)onStart(503,"Service Unavailable",{"Content-Type":"text/plain"});finish()});socket.write(requestHead(method,url2,headers,body));if(body&&body.length>0)socket.write(body)})}function __upgradeOverLoopback(port2,method,url2,headers){if(!__listening(port2)){return Promise.resolve({statusCode:503,statusMessage:"Service Unavailable",headers:{},socket:null})}return new Promise(resolve2=>{const collected=emptyCollected();let settled=false;const parser=responseParser(collected);const socket=netModule.connect({port:port2,host:"127.0.0.1"});const fail3=()=>{if(settled)return;settled=true;parser.free();resolve2({statusCode:collected.statusCode||502,statusMessage:collected.statusMessage,headers:collected.headers,socket:null})};socket.on("data",chunk=>{if(settled)return;const read=parser.execute(chunk);if(read instanceof Error){socket.destroy();fail3();return}if(collected.upgrade||collected.statusCode===101){settled=true;parser.free();const consumed=typeof read==="number"?read:chunk.length;const rest=chunk.subarray(consumed);if(rest.length>0)socket.unshift(rest);resolve2({statusCode:collected.statusCode,statusMessage:collected.statusMessage,headers:collected.headers,socket});return}if(collected.complete){socket.destroy();fail3()}});socket.on("error",fail3);socket.on("close",fail3);const upgradeHeaders={...headers,Connection:"Upgrade"};const lines=[`${method.toUpperCase()} ${url2} HTTP/1.1`];for(const[name,value]of Object.entries(upgradeHeaders)){if(name.toLowerCase()==="connection")continue;lines.push(`${name}: ${value}`)}lines.push("Connection: Upgrade","","");socket.write(lines.join("\r\n"))})}var _encoder2=new TextEncoder;function guestListeningServer(port2,address){const hostname2=address;return{listening:true,address:()=>({port:port2,address:hostname2,family:hostname2.includes(":")?"IPv6":"IPv4"}),handleRequest:(method,url2,headers,body)=>__requestOverLoopback(port2,method,url2,headers,typeof body==="string"?Buffer$9.from(body):body)}}var __substrateUpgradeSockets=new Map;function __substrateFrame(opcode,payload,masked){const length=payload.length;const header=[128|opcode];if(length<126)header.push(128|length);else if(length<65536)header.push(128|126,length>>8,length&255);else header.push(128|127,0,0,0,0,length>>>24&255,length>>>16&255,length>>>8&255,length&255);const mask=[Math.random()*256|0,Math.random()*256|0,Math.random()*256|0,Math.random()*256|0];const out=new Uint8Array(header.length+mask.length+length);out.set(header,0);out.set(mask,header.length);for(let index2=0;index2<length;index2+=1)out[header.length+mask.length+index2]=payload[index2]^mask[index2&3];return out}function __substrateParseFrames(state,chunk,onFrame){const joined=state.pending.length?new Uint8Array([...state.pending,...chunk]):chunk;let offset2=0;for(;;){if(joined.length-offset2<2)break;const b02=joined[offset2],b12=joined[offset2+1];const fin=(b02&128)!==0,opcode=b02&15,masked=(b12&128)!==0;let length=b12&127,at22=offset2+2;if(length===126){if(joined.length-at22<2)break;length=joined[at22]<<8|joined[at22+1];at22+=2}else if(length===127){if(joined.length-at22<8)break;length=0;for(let index2=0;index2<8;index2+=1)length=length*256+joined[at22+index2];at22+=8}let mask;if(masked){if(joined.length-at22<4)break;mask=joined.subarray(at22,at22+4);at22+=4}if(joined.length-at22<length)break;const payload=joined.slice(at22,at22+length);if(mask)for(let index2=0;index2<length;index2+=1)payload[index2]^=mask[index2&3];offset2=at22+length;if(opcode===0&&state.fragments){state.fragments.parts.push(payload);if(fin){const parts=state.fragments.parts;const total=parts.reduce((sum,part)=>sum+part.length,0);const whole=new Uint8Array(total);let cursor=0;for(const part of parts){whole.set(part,cursor);cursor+=part.length}const op2=state.fragments.opcode;state.fragments=null;onFrame(op2,whole)}}else if(!fin&&(opcode===1||opcode===2))state.fragments={opcode,parts:[payload]};else onFrame(opcode,payload)}state.pending=joined.slice(offset2)}function __substrateUpgradeSocket(entry,socket){const end=socket;const bridge={push:frame=>{socket.write(frame)},destroy:()=>{socket.destroy()},get destroyed(){return socket.destroyed},onData:listener=>{socket.on("data",listener)}};let closed=false;const state={pending:new Uint8Array(0),fragments:null};const decoder22=new TextDecoder;const finish=(code22,reason)=>{if(closed)return;closed=true;__substrateUpgradeSockets.delete(entry.clientId);entry.channel.postMessage({type:"close",targetClient:entry.clientId,code:code22,reason})};const receive2=frame=>{if(!bridge.destroyed)bridge.push(frame)};bridge.onData(chunk=>{const bytes2=chunk;__substrateParseFrames(state,bytes2,(opcode,payload)=>{if(opcode===1)entry.channel.postMessage({type:"message",targetClient:entry.clientId,payload:decoder22.decode(payload)});else if(opcode===2)entry.channel.postMessage({type:"message",targetClient:entry.clientId,payload:payload.buffer.slice(payload.byteOffset,payload.byteOffset+payload.byteLength)});else if(opcode===8){const code22=payload.length>=2?payload[0]<<8|payload[1]:1005;finish(code22===1005?1e3:code22,payload.length>2?decoder22.decode(payload.subarray(2)):"");end.destroy()}else if(opcode===9)receive2(__substrateFrame(10,payload))})});end.on("close",()=>{finish(1e3,"");bridge.destroy()});end.deliver=payload=>{if(closed||end.destroyed)return;const bytes2=typeof payload==="string"?_encoder2.encode(payload):new Uint8Array(payload);receive2(__substrateFrame(typeof payload==="string"?1:2,bytes2))};end.disconnect=(code22,reason)=>{if(closed||end.destroyed)return;const text=_encoder2.encode(reason||"");const payload=new Uint8Array(2+text.length);payload[0]=code22>>8;payload[1]=code22&255;payload.set(text,2);receive2(__substrateFrame(8,payload));setTimeout(()=>{finish(code22,reason||"");end.destroy()},50)};return end}function __substrateRawUpgradeSocket(entry,socket){const end=socket;const bridge={push:data2=>{socket.write(data2)},destroy:()=>{socket.destroy()},end:()=>{socket.end()},get destroyed(){return socket.destroyed},onData:listener=>{socket.on("data",listener)}};let closed=false;const finish=(code22,reason)=>{if(closed)return;closed=true;__substrateUpgradeSockets.delete(entry.clientId);entry.channel.postMessage({type:"close",targetClient:entry.clientId,code:code22,reason})};bridge.onData(chunk=>{if(closed)return;entry.channel.postMessage({type:"message",targetClient:entry.clientId,payload:chunk.buffer.slice(chunk.byteOffset,chunk.byteOffset+chunk.byteLength)})});end.on("close",()=>{finish(1e3,"");bridge.destroy()});end.deliver=payload=>{if(closed||end.destroyed||bridge.destroyed)return;bridge.push(typeof payload==="string"?_encoder2.encode(payload):new Uint8Array(payload))};end.disconnect=(code22,reason)=>{if(closed||end.destroyed)return;bridge.end();finish(code22,reason||"");end.destroy()};return end}function __substrateListenForUpgrades(bridge){var _a22;if(typeof BroadcastChannel==="undefined")return null;const channel=new BroadcastChannel("vite-ws-channel");(_a22=channel.unref)==null?void 0:_a22.call(channel);channel.addEventListener("message",event=>{const data2=event.data;if(!data2||typeof data2!=="object")return;if(data2.type==="connect"){let url2;try{url2=new URL(data2.url)}catch{return}const port2=Number(url2.port);if(!__listening(port2))return;const record={clientId:data2.clientId,channel};const raw=data2.framing==="none";const key=uint8ToBase64(crypto.getRandomValues(new Uint8Array(16)));const protocols=Array.isArray(data2.protocols)?data2.protocols:[];void __upgradeOverLoopback(port2,"GET",url2.pathname+url2.search,{Host:typeof data2.host==="string"&&/^(?:\[[0-9a-f:.]+\]|[a-z0-9.-]+)(?::[0-9]{1,5})?$/iu.test(data2.host)?data2.host:url2.host,Upgrade:"websocket","Sec-WebSocket-Version":"13","Sec-WebSocket-Key":key,...protocols.length?{"Sec-WebSocket-Protocol":protocols.join(", ")}:{},...typeof data2.origin==="string"&&/^https?:\/\/[^/]+$/u.test(data2.origin)?{Origin:data2.origin}:{}}).then(result=>{if(result.statusCode!==101||!result.socket){channel.postMessage({type:"close",targetClient:data2.clientId,code:1006,reason:"upgrade refused"});return}const socket=raw?__substrateRawUpgradeSocket(record,result.socket):__substrateUpgradeSocket(record,result.socket);__substrateUpgradeSockets.set(data2.clientId,socket);channel.postMessage({type:"connected",targetClient:data2.clientId,protocol:result.headers["sec-websocket-protocol"]??(raw?protocols[0]??"":"")})})}else if(data2.type==="message"){const socket=__substrateUpgradeSockets.get(data2.clientId);if(socket)socket.deliver(data2.payload)}else if(data2.type==="disconnect"){const socket=__substrateUpgradeSockets.get(data2.clientId);if(socket)socket.disconnect(typeof data2.code==="number"?data2.code:1e3,typeof data2.reason==="string"?data2.reason:"")}});return channel}var ServerBridge=class extends PortBridge{constructor(options={}){super(options);__publicField2(this,"upgradeChannel",null);__publicField2(this,"guestServers",new WeakSet);this.watchGuestPorts();this.upgradeChannel=__substrateListenForUpgrades()}watchGuestPorts(){setPortWatchers((port2,address)=>{if(this.servers.has(port2))return;const hostname2=address||"0.0.0.0";const server=guestListeningServer(port2,hostname2);this.guestServers.add(server);this.registerServer(server,port2,hostname2)},port2=>{const entry=this.servers.get(port2);if(entry&&(entry.server===null||this.guestServers.has(entry.server))){if(entry.server)entry.server.listening=false;this.unregisterServer(port2)}})}close(){if(this.upgradeChannel){try{this.upgradeChannel.close()}catch{}this.upgradeChannel=null}super.close()}isGuest(entry){return entry.server===null||this.guestServers.has(entry.server)}requestGuest(port2,method,url2,headers,body){return __requestOverLoopback(port2,method,url2,headers,body)}streamGuest(port2,method,url2,headers,body,onStart,onChunk,onEnd,flow){return __streamOverLoopback(port2,method,url2,headers,body,onStart,onChunk,onEnd,flow)}bodyOf(bytes2){return Buffer$9.from(bytes2)}};var globalBridge=null;function getServerBridge(options){if(!globalBridge){globalBridge=new ServerBridge(options)}return globalBridge}function resetServerBridge(){globalBridge=null}var scopes=new WeakMap;var liveScopes=new Set;var NativeStreamScope=class{constructor(limits,emit2,ownerPid){__publicField2(this,"entries",new Map);__publicField2(this,"descriptors",new Map);__publicField2(this,"writes",new Map);__publicField2(this,"connects",new Map);__publicField2(this,"nextId",1);__publicField2(this,"pendingWriteBytes",0);__publicField2(this,"disposed",false);__publicField2(this,"limits");this.emit=emit2;this.ownerPid=ownerPid;if([limits.maxHandles,limits.maxReadChunkBytes,limits.maxQueuedBytes,limits.maxQueuedHandles,limits.maxPendingWriteBytes].some(value=>!Number.isSafeInteger(value)||value<1)||limits.maxReadChunkBytes>2147483647||limits.maxReadChunkBytes>limits.maxQueuedBytes||limits.maxReadChunkBytes>limits.maxPendingWriteBytes)throw new Error("Invalid native stream resource limits.");this.limits=Object.freeze({...limits});liveScopes.add(this)}handles(){var _a22;if(this.disposed)return[];const pid=(_a22=this.ownerPid)==null?void 0:_a22.call(this);return[...this.entries.values()].map(({handle,descriptor})=>({...pid!==void 0?{pid}:{},id:descriptor.id,kind:descriptor.kind,listening:!!handle.listening}))}entry(id2){return this.disposed?void 0:this.entries.get(id2)}publish(event){if(this.disposed)return;try{this.emit(event)}catch(cause){try{this.dispose()}catch(cleanup){throw new AggregateError([cause,cleanup],"Native stream event delivery and cleanup failed.")}throw cause}}claim(handle){if(this.disposed||!Number.isSafeInteger(this.nextId)||this.entries.size>=this.limits.maxHandles||scopes.has(handle))return void 0;const descriptor={id:this.nextId++,kind:handle instanceof TCP?"tcp":"pipe",type:handle.type};const entry={handle,descriptor};this.entries.set(descriptor.id,entry);scopes.set(handle,this);__adoptHandle(handle,null);handle.onconnection=(status,accepted)=>{const incoming2=status===0?this.claim(accepted):void 0;if(status===0&&!incoming2)accepted.close();this.publish({type:"connection",id:descriptor.id,status:status||(incoming2?0:UV_EMFILE),...incoming2?{handle:incoming2}:{}})};handle.onread=buffer2=>{const count=streamBaseState[kReadBytesOrError];const offset2=streamBaseState[kArrayBufferOffset];handle.readStop();const sent=handle.pendingHandle;handle.pendingHandle=null;let incoming2;if(sent!=null){if((sent instanceof TCP||sent instanceof Pipe)&&!sent.listening)incoming2=this.claim(sent);if(!incoming2){if(sent instanceof LibuvStreamWrap&&!scopes.has(sent)&&!sent.listening)sent.close();this.publish({type:"read",id:descriptor.id,status:UV_ENOTSUP});this.close(descriptor.id);return}}const bytes2=count>0?(buffer2?new Uint8Array(buffer2,offset2,count):entry.buffer.subarray(0,count)).slice():void 0;this.publish({type:"read",id:descriptor.id,status:count,...bytes2?{bytes:bytes2}:{},...incoming2?{handle:incoming2}:{}})};return{...descriptor}}call(operation){var _a22,_b22;if(this.disposed)return{status:UV_EBADF};if(operation.operation==="fdType"){if(!Number.isInteger(operation.fd)||operation.fd<0)return{status:UV_EINVAL};const id2=this.descriptors.get(operation.fd);const entry2=id2===void 0?void 0:this.entry(id2);return entry2?{status:0,handleType:entry2.descriptor.kind==="tcp"?"TCP":"PIPE"}:{status:UV_EBADF}}if(operation.operation==="create"){if(this.entries.size>=this.limits.maxHandles)return{status:UV_EMFILE};if(operation.kind!=="tcp"&&operation.kind!=="pipe"||!Number.isInteger(operation.type)||operation.type<0||operation.type>(operation.kind==="pipe"?2:1))return{status:UV_EINVAL};const handle2=operation.kind==="tcp"?new TCP(operation.type):new Pipe(operation.type);const descriptor=this.claim(handle2);if(!descriptor){handle2.close();return{status:UV_EMFILE}}return{status:0,handle:descriptor}}const entry=this.entry(operation.id);if(!entry)return{status:UV_EBADF};const handle=entry.handle;switch(operation.operation){case"duplicate":{if(handle.listening)return{status:UV_ENOTSUP};if(this.entries.size>=this.limits.maxHandles)return{status:UV_EMFILE};const copy2=handle.duplicate();const descriptor=this.claim(copy2);if(!descriptor){copy2.close();return{status:UV_EMFILE}}return{status:0,handle:descriptor}}case"pair":{const other=(_a22=this.entry(operation.peer))==null?void 0:_a22.handle;if(!other||handle.peer||other.peer||handle.listening||other.listening||other===handle)return{status:UV_EINVAL};LibuvStreamWrap.pair(handle,other);return{status:0}}case"bind":{if(typeof operation.address!=="string")return{status:UV_EINVAL};if(handle instanceof Pipe)return{status:handle.bind(operation.address)};if(!Number.isInteger(operation.port)||operation.port<0||operation.port>65535)return{status:UV_EINVAL};return{status:operation.ipv6?handle.bind6(operation.address,operation.port,operation.flags):handle.bind(operation.address,operation.port,operation.flags)}}case"listen":return{status:Number.isInteger(operation.backlog)&&operation.backlog>=0?handle.listen(operation.backlog):UV_EINVAL};case"connect":{if(this.connects.has(operation.id))return{status:UV_EALREADY};if(typeof operation.address!=="string"||!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};if(handle instanceof TCP&&(!Number.isInteger(operation.port)||operation.port<1||operation.port>65535))return{status:UV_EINVAL};this.connects.set(operation.id,operation.request);const request=handle instanceof TCP?new TCPConnectWrap:new PipeConnectWrap;request.oncomplete=status2=>{if(this.connects.get(operation.id)!==operation.request)return;this.connects.delete(operation.id);this.publish({type:"connect",id:operation.id,request:operation.request,status:status2})};const status=handle instanceof TCP?operation.ipv6?handle.connect6(request,operation.address,operation.port):handle.connect(request,operation.address,operation.port):handle.connect(request,operation.address);if(status!==0)this.connects.delete(operation.id);return{status}}case"open":{const inherited=this.descriptors.get(operation.fd);const held=inherited===void 0?void 0:this.entry(inherited);if(!held||held.descriptor.kind!==entry.descriptor.kind||handle.peer||handle.listening)return{status:UV_EBADF};if(held!==entry){if(handle instanceof TCP&&held.handle instanceof TCP){const local2={},remote={};if(held.handle.getsockname(local2)===0&&held.handle.getpeername(remote)===0)handle.adoptNames(local2,remote)}handle.takeOverFrom(held.handle);this.entries.delete(inherited);scopes.delete(held.handle);held.handle.close();this.descriptors.set(operation.fd,operation.id)}return{status:0}}case"readStart":entry.buffer??(entry.buffer=new Uint8Array(this.limits.maxReadChunkBytes));handle.useUserBuffer(entry.buffer);return{status:handle.readStart()};case"readStop":return{status:handle.readStop()};case"ref":handle.ref();return{status:0};case"unref":handle.unref();return{status:0};case"getsockname":case"getpeername":{if(!(handle instanceof TCP))return{status:UV_ENOTSUP};const address={};const status=handle[operation.operation](address);return{status,...status===0?{address}:{}}}case"shutdown":{if(!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};if(this.writes.has(operation.id))return{status:UV_EBUSY};const request=new ShutdownWrap;request.oncomplete=status=>this.publish({type:"shutdown",id:operation.id,request:operation.request,status});return{status:handle.shutdown(request)}}case"reset":if(!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};if(!(handle instanceof TCP))return{status:UV_ENOTSUP};(_b22=this.writes.get(operation.id))==null?void 0:_b22(UV_ECANCELED);return this.close(operation.id,operation.request,true);case"close":if(!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};return this.close(operation.id,operation.request)}}write(id2,bytes2,sentId){var _a22,_b22;const handle=(_a22=this.entry(id2))==null?void 0:_a22.handle;if(!handle)return Promise.resolve(UV_EBADF);if(this.writes.has(id2))return Promise.resolve(UV_EBUSY);if(bytes2.byteLength>this.limits.maxReadChunkBytes||this.pendingWriteBytes+bytes2.byteLength>this.limits.maxPendingWriteBytes)return Promise.resolve(UV_ENOBUFS);const sent=sentId===void 0?void 0:(_b22=this.entry(sentId))==null?void 0:_b22.handle;if(sentId!==void 0&&!sent)return Promise.resolve(UV_EBADF);if(sent&&(!(handle instanceof Pipe)||sent.listening||bytes2.byteLength===0))return Promise.resolve(UV_ENOTSUP);const owned2=new Uint8Array(bytes2.byteLength);owned2.set(bytes2);const retained=sent==null?void 0:sent.duplicate();if(retained)__adoptHandle(retained,null);this.pendingWriteBytes+=owned2.byteLength;return new Promise((resolve2,reject)=>{let ended2=false;let unsubscribe=()=>{};const finish=(status,failure)=>{if(ended2)return;ended2=true;unsubscribe();this.writes.delete(id2);this.pendingWriteBytes-=owned2.byteLength;try{retained==null?void 0:retained.close()}catch(cause){reject(cause);return}if(failure!==void 0)reject(failure);else resolve2(status)};const attempt=()=>{if(ended2)return;if(handle.closed||this.disposed){finish(UV_ECANCELED);return}if(!handle.peer){finish(UV_EPIPE);return}if(handle.peerQueuedBytes+owned2.byteLength>this.limits.maxQueuedBytes)return;if(retained&&handle.peerQueuedHandles>=this.limits.maxQueuedHandles)return;try{finish(handle.writeBuffer(new WriteWrap,owned2,retained))}catch(cause){finish(UV_ECANCELED,cause)}};this.writes.set(id2,finish);unsubscribe=handle.onPeerReadCapacity(attempt);attempt()})}inherit(fd2,source,id2){var _a22;if(this.disposed||!Number.isInteger(fd2)||fd2<0||this.descriptors.has(fd2))return{status:UV_EINVAL};if(this.entries.size>=this.limits.maxHandles)return{status:UV_EMFILE};const handle=(_a22=source.entry(id2))==null?void 0:_a22.handle;if(!handle)return{status:UV_EBADF};if(handle.listening)return{status:UV_ENOTSUP};const copy2=handle.duplicate();const descriptor=this.claim(copy2);if(!descriptor){copy2.close();return{status:UV_EMFILE}}this.descriptors.set(fd2,descriptor.id);return{status:0,handle:descriptor}}close(id2,request,reset2=false){var _a22;const entry=this.entries.get(id2);if(!entry)return{status:UV_EBADF};(_a22=this.writes.get(id2))==null?void 0:_a22(UV_ECANCELED);const connecting=this.connects.get(id2);this.connects.delete(id2);if(connecting!==void 0)this.publish({type:"connect",id:id2,request:connecting,status:UV_ECANCELED});this.entries.delete(id2);scopes.delete(entry.handle);for(const[fd2,held]of this.descriptors)if(held===id2)this.descriptors.delete(fd2);const complete=request===void 0?void 0:()=>this.publish({type:"close",id:id2,request,status:0});if(reset2)entry.handle.reset(complete);else entry.handle.close(complete);return{status:0}}dispose(){if(this.disposed)return;this.disposed=true;liveScopes.delete(this);const failures=[];for(const id2 of[...this.entries.keys()]){try{this.close(id2)}catch(cause){failures.push(cause)}}if(failures.length)throw new AggregateError(failures,"Native stream scope cleanup failed.")}};function nativeStreamOwnerPid(handle){var _a22,_b22;return(_b22=(_a22=scopes.get(handle))==null?void 0:_a22.ownerPid)==null?void 0:_b22.call(_a22)}function nativeStreamHandles(){return[...liveScopes].flatMap(scope4=>scope4.handles())}var __nextRunName=1;function createContainer(options){const vfs2=options&&options.vfs||new VirtualFS;const runtime=new Runtime(vfs2,options);const npmManager=new PackageManager(vfs2);const serverBridge=new ServerBridge({baseUrl:options==null?void 0:options.baseUrl,onServerReady:options==null?void 0:options.onServerReady});return{vfs:vfs2,runtime,npm:npmManager,serverBridge,execute:(code22,filename)=>runtime.execute(code22,filename),runFile:filename=>runtime.runFile(filename),run:(command,runOptions)=>{var _a22;if((_a22=runOptions==null?void 0:runOptions.signal)==null?void 0:_a22.aborted){return Promise.resolve({stdout:"",stderr:"",exitCode:130})}const processToken=typeof(runOptions==null?void 0:runOptions.processToken)==="string"&&runOptions.processToken.length>0?runOptions.processToken:`run-${__nextRunName++}`;registerRunStreams(processToken,{onStdout:runOptions==null?void 0:runOptions.onStdout,onStderr:runOptions==null?void 0:runOptions.onStderr,signal:runOptions==null?void 0:runOptions.signal,held:(runOptions==null?void 0:runOptions.held)===true,stdinStream:runOptions==null?void 0:runOptions.stdinStream,stdinOpen:(runOptions==null?void 0:runOptions.stdinStream)!==void 0,terminal:runOptions==null?void 0:runOptions.terminal});return new Promise(resolve2=>{runCommand(command,{cwd:runOptions==null?void 0:runOptions.cwd,env:runOptions==null?void 0:runOptions.env,stdin:typeof(runOptions==null?void 0:runOptions.stdin)==="string"?runOptions.stdin:void 0,processToken,vfs:vfs2},(error,stdout,stderr)=>{var _a32;releaseRunStreams(processToken);const terminatedBy=__takeTermination(processToken);resolve2({stdout:String(stdout),stderr:String(stderr),exitCode:((_a32=runOptions==null?void 0:runOptions.signal)==null?void 0:_a32.aborted)?143:error?error.code??1:0,...terminatedBy?{signal:terminatedBy}:{}})})})},pendingTimers:token=>{var _a22;return((_a22=__runFor(token))==null?void 0:_a22.pendingTimers())??0},processPorts:token=>__ownedServerPorts(token),portPid:port2=>{var _a22;const listener=listenerOnPort(port2);if(!listener)return void 0;return((_a22=runPid(ownerOf(listener)))==null?void 0:_a22.pid)??nativeStreamOwnerPid(listener)},streamHandles:()=>nativeStreamHandles(),signalProcess:(token,signal)=>__signalOwnedProcess(token,signal),stopProcess:token=>{const known=__runFor(token)!==void 0||__ownedServerPorts(token).length>0;__releaseOwnedServers(token,false);__releaseOwnedHandles(token);__stopOwnedProcess(token);return known},sendInput:(data2,token)=>sendStdin(data2,token),currentProcessToken:()=>__currentProcessToken(),runPid:token=>runPid(token===void 0?__currentProcessToken():token),processByPid,listenNet:(port2,onConnection)=>{const server=new Server(onConnection);server.listen(port2);__adoptHandle(server._handle,null);return()=>{server.close()}},createREPL:()=>runtime.createREPL(),on:(event,listener)=>{serverBridge.on(event,listener)}}}if(!Object.getOwnPropertyDescriptor(globalThis,"Buffer")){Object.defineProperty(globalThis,"Buffer",{configurable:true,enumerable:false,get:()=>bufferModule.Buffer})}function normalizeProcessFilesystemPolicy(value){if(!value||typeof value!=="object"||Object.keys(value).some(key=>key!=="writableRoots")||!Array.isArray(value.writableRoots)||value.writableRoots.length>128){throw new TypeError("Invalid process filesystem policy: expected up to 128 writableRoots.")}const roots=[...new Set(Array.from(value.writableRoots,absolutePolicyPath))].sort();return Object.freeze({writableRoots:Object.freeze(roots.filter(root2=>!roots.some(other=>other!==root2&&within(root2,other))))})}function intersectProcessFilesystemPolicies(parent2,child){const inherited=normalizeProcessFilesystemPolicy(parent2);if(child===void 0)return inherited;const requested=normalizeProcessFilesystemPolicy(child);return normalizeProcessFilesystemPolicy({writableRoots:inherited.writableRoots.flatMap(left=>requested.writableRoots.flatMap(right=>within(left,right)?[left]:within(right,left)?[right]:[]))})}function createProcessFilesystemMutationGuard(filesystem,requested){const policy=normalizeProcessFilesystemPolicy(requested);const permitted=path3=>policy.writableRoots.some(root2=>within(path3,root2));return input=>{const path3=absolutePolicyPath(input);if(!permitted(path3))deny(path3);let current3="";for(const part of path3.split("/").filter(Boolean)){current3+=`/${part}`;try{if(filesystem.lstatSync(current3).isSymbolicLink())deny(path3)}catch(error){if(error.code!=="ENOENT")throw error;if(!permitted(current3))deny(current3)}}return path3}}function absolutePolicyPath(path3){if(typeof path3!=="string"||!path3.startsWith("/")||path3.includes("\0")||path3.length>8192){throw new TypeError("Filesystem policy paths must be absolute paths without NUL bytes.")}const parts=[];for(const part of path3.split("/")){if(part==="..")parts.pop();else if(part&&part!==".")parts.push(part)}return`/${parts.join("/")}`}function within(path3,root2){return root2==="/"||path3===root2||path3.startsWith(`${root2}/`)}function deny(path3){throw Object.assign(new Error(`EACCES: process filesystem policy denies mutation of '${path3}'`),{code:"EACCES",path:path3})}async function forwardBrowserProcessInput(input,receive2,signal){signal.throwIfAborted();const iterator=input[Symbol.asyncIterator]();let finished=false;let rejectCancellation;const cancellation=new Promise((_resolve,reject)=>{rejectCancellation=reject});void cancellation.catch(()=>void 0);const abort=()=>rejectCancellation(signal.reason??new DOMException("Process input was cancelled.","AbortError"));signal.addEventListener("abort",abort,{once:true});try{for(;;){signal.throwIfAborted();const next2=await Promise.race([iterator.next(),cancellation]);signal.throwIfAborted();if(next2.done){finished=true;return}await Promise.race([Promise.resolve(receive2(next2.value)),cancellation])}}finally{signal.removeEventListener("abort",abort);if(!finished)void Promise.resolve().then(()=>iterator.return?.()).catch(()=>void 0)}}var BrowserProcessInputPipe=class{queued;ended=false;reading=false;failure;wake;write(bytes2){if(this.ended)return Promise.reject(this.failure??new Error("Process input is closed."));if(this.queued)return Promise.reject(new Error("Wait for the previous process input chunk to be consumed."));const consumed=new Promise((resolve2,reject)=>{this.queued={bytes:Uint8Array.from(bytes2),resolve:resolve2,reject}});this.notify();return consumed}end(){this.ended=true;this.notify()}cancel(cause=new DOMException("Process input was cancelled.","AbortError")){this.failure=cause;this.ended=true;this.queued?.reject(cause);this.queued=void 0;this.notify()}notify(){const wake=this.wake;this.wake=void 0;wake?.()}async*[Symbol.asyncIterator](){if(this.reading)throw new Error("Process input already has a reader.");this.reading=true;try{for(;;){if(this.failure!==void 0)throw this.failure;const next2=this.queued;if(next2){this.queued=void 0;next2.resolve();yield next2.bytes}else if(this.ended)return;else await new Promise(resolve2=>{this.wake=resolve2})}}finally{this.cancel()}}};function parseCommandWords(command){const words=[];let word="";let quote2="";let escaped=false;for(const character of command.trim()){if(escaped){word+=character;escaped=false;continue}if(character==="\\"&"e2!=="'"){escaped=true;continue}if(quote2){if(character===quote2)quote2="";else word+=character;continue}if(character==="'"||character==='"'){quote2=character;continue}if(/\s/u.test(character)){if(word){words.push(word);word=""}continue}if(/[|&;<>]/u.test(character))throw new Error("Shell operators require the shell runtime.");word+=character}if(escaped||quote2)throw new Error("Unterminated command quoting.");if(word)words.push(word);return words}function renderCommand(argv){return argv.map(value=>/^[A-Za-z0-9_./:@%+=,-]+$/u.test(value)?value:`'${value.replaceAll("'",`'\\''`)}'`).join(" ")}var PageNetSocketImpl=class{constructor(id2,post,onClosed){this.id=id2;this.post=post;this.onClosed=onClosed}id;post;onClosed;listeners=new Map;ended=false;outstanding=0;drainWaiters=[];on(event,listener){const list2=this.listeners.get(event)??[];list2.push(listener);this.listeners.set(event,list2);return this}write(chunk,done){if(this.ended)return false;const buffer2=Uint8Array.from(chunk).buffer;this.outstanding+=1;this.post({type:"net-data",socket:this.id,chunk:buffer2},[buffer2]);done?.();return true}taken(){this.outstanding=Math.max(0,this.outstanding-1);for(const waiter of[...this.drainWaiters]){if(this.outstanding>=waiter.below)continue;this.drainWaiters.splice(this.drainWaiters.indexOf(waiter),1);waiter.resume()}}drained(below){if(this.ended||this.outstanding<below)return Promise.resolve();return new Promise(resume=>this.drainWaiters.push({below,resume}))}end(){if(!this.ended){this.post({type:"net-end",socket:this.id});this.finish()}return this}destroy(){return this.end()}receive(chunk){if(this.ended)return;for(const listener of this.listeners.get("data")??[])listener(chunk)}finish(){if(this.ended)return;this.ended=true;this.onClosed();for(const waiter of this.drainWaiters.splice(0))waiter.resume();const listeners=[...this.listeners.get("end")??[],...this.listeners.get("close")??[]];this.listeners.clear();for(const listener of listeners)listener(void 0)}};var STATE=0;var STATUS=1;var PID=2;var PPID=3;var IDLE=0;var REQUEST=1;var WRITING=2;var DONE3=3;var CLOSED=4;var TIMEOUT_MS=3e4;var STREAM_REPLY_BYTES=4096;function serveNodeProcessRegistry(limits,ownerPid){if(limits)limits=Object.freeze({...limits});const streams2=limits?new NativeStreamScope(limits,event=>{const transfer2=event.type==="read"&&event.bytes?[event.bytes.buffer]:[];port1.postMessage({operation:"stream-event",event},transfer2)},ownerPid):void 0;const registry=createProcessRegistryScope();const{port1,port2}=new MessageChannel;const shared=new SharedArrayBuffer(4*Int32Array.BYTES_PER_ELEMENT);const control=new Int32Array(shared);const reply=limits?new SharedArrayBuffer(STREAM_REPLY_BYTES):void 0;const encoder11=new TextEncoder;let disposed=false;const dispose=()=>{if(disposed)return;disposed=true;Atomics.store(control,STATE,CLOSED);Atomics.notify(control,STATE);try{port1.postMessage({operation:"closed"})}finally{try{streams2?.dispose()}finally{registry.dispose();port1.onmessage=null;port1.onmessageerror=null;port1.close();port2.close()}}};port1.onmessage=({data:data2})=>{if(disposed)return;if(!data2||typeof data2!=="object"){dispose();return}if(data2.operation==="close"){dispose();return}if(data2.operation==="stream-write"){if(!streams2||!limits||!Number.isSafeInteger(data2.request)||data2.request<1||!Number.isSafeInteger(data2.id)||data2.id<1||data2.handle!==void 0&&(!Number.isSafeInteger(data2.handle)||data2.handle<1)||!(data2.bytes instanceof Uint8Array)||data2.bytes.byteLength>limits.maxReadChunkBytes){dispose();return}try{void streams2.write(data2.id,data2.bytes,data2.handle).then(status2=>{if(!disposed)port1.postMessage({operation:"stream-written",request:data2.request,status:status2})}).catch(()=>dispose())}catch{dispose()}return}if(data2.operation==="stream-post"){const call=data2.call;const closing=call?.operation==="close"||call?.operation==="reset"||call?.operation==="shutdown";if(!streams2||call?.operation!=="readStart"&&!closing||!Number.isSafeInteger(call.id)||call.id<1||closing&&(!Number.isSafeInteger(call.request)||call.request<1)){dispose();return}try{const{status:status2}=streams2.call(call);if(status2!==0){port1.postMessage({operation:"stream-event",event:closing?{type:call.operation==="shutdown"?"shutdown":"close",id:call.id,request:call.request,status:status2}:{type:"read",id:call.id,status:status2}})}}catch{dispose()}return}if(Atomics.compareExchange(control,STATE,REQUEST,WRITING)!==REQUEST)return;let identity;let replyLength=0;let status=0;try{switch(data2.operation){case"allocate":identity={pid:registry.allocate(),ppid:0};break;case"publish":if(typeof data2.token!=="string")throw new Error("Invalid process token.");registry.publish(data2.token,{pid:data2.pid,ppid:data2.ppid,...data2.argv!==void 0?{argv:data2.argv}:{},...data2.cwd!==void 0?{cwd:data2.cwd}:{},...data2.startedAt!==void 0?{startedAt:data2.startedAt}:{}});break;case"forget":if(typeof data2.token!=="string")throw new Error("Invalid process token.");registry.forget(data2.token);break;case"lookup":identity=registry.lookup(data2.pid);break;case"signal":if(!Number.isSafeInteger(data2.pid)||typeof data2.signal!=="string"||!/^SIG[A-Z0-9]{1,12}$/u.test(data2.signal)){throw new Error("Invalid process signal.")}identity=registry.signal(data2.pid,data2.signal)?{pid:data2.pid,ppid:0}:void 0;break;case"stream-call":{if(!streams2||!reply)throw new Error("Native stream transport was not granted.");const result=streams2.call(data2.call);const bytes2=encoder11.encode(JSON.stringify(result));if(bytes2.byteLength>reply.byteLength)throw new Error("Native stream reply exceeds its bound.");new Uint8Array(reply).set(bytes2);replyLength=bytes2.byteLength;break}default:throw new Error("Unknown process registry operation.")}}catch{if(data2.operation==="stream-call"){dispose();return}status=1}Atomics.store(control,STATUS,status);Atomics.store(control,PID,data2.operation==="stream-call"?replyLength:identity?.pid??0);Atomics.store(control,PPID,identity?.ppid??0);if(Atomics.compareExchange(control,STATE,WRITING,DONE3)===WRITING)Atomics.notify(control,STATE);else dispose()};port1.onmessageerror=dispose;port1.start();return{registry,channel:{port:port2,control:shared,...reply&&limits?{streams:{reply,limits}}:{}},...streams2?{streams:streams2}:{},dispose}}function exchange(channel,request,read){const control=new Int32Array(channel.control);if(Atomics.compareExchange(control,STATE,IDLE,REQUEST)!==IDLE)throw new Error("Process owner channel is unavailable.");let result;let status;try{channel.port.postMessage(request);const deadline=performance.now()+TIMEOUT_MS;for(;;){const state=Atomics.load(control,STATE);if(state===DONE3)break;if(state===CLOSED)throw new Error("Process owner stopped.");const remaining=deadline-performance.now();if(remaining<=0)throw new Error("Process owner did not answer within 30 seconds.");Atomics.wait(control,STATE,state,remaining)}status=Atomics.load(control,STATUS);result=read(control);if(Atomics.compareExchange(control,STATE,DONE3,IDLE)!==DONE3)throw new Error("Process owner stopped.")}catch(cause){Atomics.store(control,STATE,CLOSED);try{channel.port.postMessage({operation:"close"})}finally{channel.port.close()}throw cause}if(status!==0)throw new Error("Process owner refused an invalid or unowned identity.");return result}var NodeProcessRegistryClient=class{constructor(channel){this.channel=channel;if(channel.streams)this.streams=this.native=new NodeNativeStreamClient(channel)}channel;streams;native;allocate(){return this.call({operation:"allocate"}).pid}publish(token,identity){this.call({operation:"publish",token,...identity})}forget(token){this.call({operation:"forget",token})}lookup(pid){return this.call({operation:"lookup",pid})}signal(pid,signal){return this.call({operation:"signal",pid,signal})!==void 0}call(request){try{return exchange(this.channel,request,control=>{const pid=Atomics.load(control,PID);return pid===0?void 0:{pid,ppid:Atomics.load(control,PPID)}})}catch(cause){if(Atomics.load(new Int32Array(this.channel.control),STATE)===CLOSED)this.native?.dispose();throw cause}}};var NodeNativeStreamClient=class{constructor(channel){this.channel=channel;if(!channel.streams)throw new Error("Native stream transport was not granted.");this.metadata=channel.streams;this.limits=Object.freeze({...channel.streams.limits});channel.port.addEventListener("message",this.receive);channel.port.addEventListener("messageerror",this.failed);channel.port.start()}channel;limits;listeners=new Set;pending=new Map;writing=new Set;queued=[];pendingBytes=0;nextRequest=1;stopped=false;metadata;call(operation){try{return exchange(this.channel,{operation:"stream-call",call:operation},control=>{const length=Atomics.load(control,PID);if(length<1||length>this.metadata.reply.byteLength)throw new Error("Invalid native stream reply length.");const bytes2=new Uint8Array(this.metadata.reply,0,length).slice();return JSON.parse(new TextDecoder().decode(bytes2))})}catch(cause){this.dispose();throw cause}}post(operation){if(this.stopped||Atomics.load(new Int32Array(this.channel.control),STATE)===CLOSED){this.dispose();throw new Error("Native stream owner stopped.")}this.channel.port.postMessage({operation:"stream-post",call:operation})}write(id2,bytes2,handle){if(this.stopped||Atomics.load(new Int32Array(this.channel.control),STATE)===CLOSED){this.dispose();return Promise.reject(new Error("Native stream owner stopped."))}if(this.writing.has(id2)||this.pending.size>=this.limits.maxHandles||bytes2.byteLength>this.limits.maxReadChunkBytes||!Number.isSafeInteger(this.nextRequest))return Promise.reject(new Error("Native stream write exceeds its transport limits."));const request=this.nextRequest++;return new Promise((resolve2,reject)=>{this.pending.set(request,{id:id2,bytes:bytes2.byteLength,resolve:resolve2,reject});this.writing.add(id2);this.queued.push({request,id:id2,bytes:bytes2,...handle===void 0?{}:{handle}});this.flushWrites()})}flushWrites(){while(!this.stopped&&this.queued.length){const next2=this.queued[0];if(this.pendingBytes+next2.bytes.byteLength>this.limits.maxPendingWriteBytes)return;this.queued.shift();const owned2=new Uint8Array(next2.bytes.byteLength);owned2.set(next2.bytes);this.pendingBytes+=owned2.byteLength;try{this.channel.port.postMessage({operation:"stream-write",request:next2.request,id:next2.id,bytes:owned2,...next2.handle===void 0?{}:{handle:next2.handle}},[owned2.buffer])}catch{this.dispose()}}}onEvent(listener){if(this.stopped)throw new Error("Native stream owner stopped.");this.listeners.add(listener);return()=>{this.listeners.delete(listener)}}receive=({data:data2})=>{if(data2.operation==="closed"){this.dispose();return}if(data2.operation==="stream-event"){for(const listener of[...this.listeners])listener(data2.event)}else if(data2.operation==="stream-written"){const write=this.pending.get(data2.request);if(!write){this.dispose();return}this.pending.delete(data2.request);this.writing.delete(write.id);this.pendingBytes-=write.bytes;this.flushWrites();write.resolve(data2.status)}};failed=()=>{this.dispose()};dispose(){if(this.stopped)return;this.stopped=true;Atomics.store(new Int32Array(this.channel.control),STATE,CLOSED);try{this.channel.port.postMessage({operation:"close"})}finally{this.channel.port.removeEventListener("message",this.receive);this.channel.port.removeEventListener("messageerror",this.failed);this.channel.port.close();const cause=new Error("Native stream owner stopped.");for(const write of this.pending.values())write.reject(cause);this.pending.clear();this.queued.length=0;this.writing.clear();this.pendingBytes=0;const listeners=[...this.listeners];this.listeners.clear();const failures=[];for(const listener of listeners){try{listener({type:"closed"})}catch(error){failures.push(error)}}if(failures.length)throw new AggregateError(failures,"Native stream close delivery failed.")}}};var maximumChunk=64*1024;function validDescriptorNumber(fd2){return typeof fd2==="number"&&Number.isInteger(fd2)&&fd2>=3&&fd2<=63}var CrossOriginChildProcesses=class{constructor(run,send2){this.run=run;this.send=send2}run;send;children=new Map;disposed=false;receive(message){if(!["child-run","child-abort","child-stdin","child-stdin-end","child-resize","child-fd","child-fd-end"].includes(message.type))return false;if(this.disposed)return true;if(message.type==="child-run"){if(!Number.isSafeInteger(message.id)||message.id<1||this.children.has(message.id)){throw new Error("Invalid or duplicate child process identity.")}if(message.descriptors!==void 0&&(!Array.isArray(message.descriptors)||!message.descriptors.every(validDescriptorNumber)||new Set(message.descriptors).size!==message.descriptors.length)){throw new Error("Child process descriptors must be distinct integers from 3 through 63.")}void this.start(message).catch(cause=>console.error("Child process transport failed.",cause));return true}if(!("id"in message)||typeof message.id!=="number")return true;const child=this.children.get(message.id);if(!child)return true;if(message.type==="child-abort"){child.controller.abort();child.input?.cancel();for(const input of child.descriptors.values())input.cancel()}else if(message.type==="child-fd"||message.type==="child-fd-end"){const input=validDescriptorNumber(message.fd)?child.descriptors.get(message.fd):void 0;if(!input){child.controller.abort(new Error("Child process has no such descriptor."));return true}if(message.type==="child-fd-end"){input.end();return true}if(!(message.bytes instanceof ArrayBuffer)||message.bytes.byteLength>maximumChunk){const cause=new Error("Child process descriptor chunks must be at most 64 KiB.");child.controller.abort(cause);input.cancel(cause);return true}const fd2=message.fd;void input.write(new Uint8Array(message.bytes)).then(()=>{if(!this.disposed&&this.children.get(message.id)===child)this.send({type:"child-fd-consumed",id:message.id,fd:fd2})}).catch(cause=>{child.controller.abort(cause)})}else if(message.type==="child-stdin"){if(!child.input){child.controller.abort(new Error("Child process has no live input."));return true}if(message.bytes.byteLength>64*1024){const cause=new Error("Child process input chunks must be at most 64 KiB.");child.controller.abort(cause);child.input.cancel(cause);return true}void child.input.write(new Uint8Array(message.bytes)).then(()=>{if(!this.disposed&&this.children.get(message.id)===child)this.send({type:"child-input-consumed",id:message.id})}).catch(cause=>{if(!this.disposed&&this.children.get(message.id)===child)child.controller.abort(cause)})}else if(message.type==="child-stdin-end")child.input?.end();else if(message.type==="child-resize"&&child.terminal){child.terminal.columns=message.columns;child.terminal.rows=message.rows;for(const resize of[...child.resizes]){try{resize(message.columns,message.rows)}catch(cause){child.controller.abort(cause)}}}return true}detach(){this.close(false)}dispose(){this.close(true)}close(abort){if(this.disposed)return;this.disposed=true;for(const child of this.children.values()){if(abort){child.controller.abort();child.input?.cancel();for(const input of child.descriptors.values())input.cancel()}else{child.input?.end();for(const input of child.descriptors.values())input.end()}child.resizes.clear()}this.children.clear()}async start(message){const child={controller:new AbortController,resizes:new Set,descriptors:new Map((message.descriptors??[]).map(fd2=>[fd2,new BrowserProcessInputPipe])),...message.liveStdin?{input:new BrowserProcessInputPipe}:{}};if(message.terminal)child.terminal={...message.terminal,onResize:listener=>{child.resizes.add(listener);return()=>{child.resizes.delete(listener)}}};this.children.set(message.id,child);const descriptors={};for(const[fd2,input]of child.descriptors)descriptors[fd2]=this.descriptor(message.id,fd2,input,child);try{const result=await this.run(message,{...message.cwd!==void 0?{cwd:message.cwd}:{},...message.env!==void 0?{env:message.env}:{},...message.executablePath!==void 0?{executablePath:message.executablePath}:{},...message.filesystemPolicy!==void 0?{filesystemPolicy:message.filesystemPolicy}:{},...message.stdin!==void 0?{stdin:message.stdin}:{},...child.input?{stdinStream:child.input}:{},...child.terminal?{terminal:child.terminal}:{},...child.descriptors.size>0?{descriptors}:{},signal:child.controller.signal,onStdout:chunk=>{if(!this.disposed)this.send({type:"child-output",id:message.id,stream:"stdout",chunk})},onStderr:chunk=>{if(!this.disposed)this.send({type:"child-output",id:message.id,stream:"stderr",chunk})}});if(!this.disposed)this.send({type:"child-result",id:message.id,stdout:result.stdout,stderr:result.stderr,exitCode:result.exitCode,...result.signal?{signal:result.signal}:{}})}catch(cause){if(!this.disposed){try{this.send({type:"child-error",id:message.id,error:cause instanceof Error?cause.message:String(cause)})}catch(failure){console.error("Child process result transport failed.",failure)}}}finally{child.input?.cancel();for(const input of child.descriptors.values())input.cancel();child.resizes.clear();this.children.delete(message.id)}}descriptor(id2,fd2,input,child){let closed=false;const live2=()=>!closed&&!this.disposed&&this.children.get(id2)===child;return{input,write:bytes2=>{for(let offset2=0;offset2<bytes2.byteLength&&live2();offset2+=maximumChunk){const chunk=Uint8Array.from(bytes2.subarray(offset2,offset2+maximumChunk)).buffer;this.send({type:"child-fd-output",id:id2,fd:fd2,bytes:chunk},[chunk])}},end:()=>{if(!live2())return;closed=true;this.send({type:"child-fd-close",id:id2,fd:fd2})}}}};var STAT_FIELDS=["mode","mtimeMs","atimeMs","ctimeMs","birthtimeMs","nlink","uid","gid","dev","ino","rdev","blksize","blocks"];var STATE2=0;var OPERATION=1;var STATUS2=2;var INPUT_LENGTH=3;var OUTPUT_LENGTH=4;var TOTAL_LENGTH=5;var CONTROL_WORDS=8;var DEFAULT_PAYLOAD_BYTES=4*1024*1024;var REQUEST_TIMEOUT_MS=3e4;var encoder2=new TextEncoder;var decoder3=new TextDecoder;function createBrowserFilesystemChannel(payloadBytes=DEFAULT_PAYLOAD_BYTES){const{port1,port2}=new MessageChannel;const control=new SharedArrayBuffer(CONTROL_WORDS*Int32Array.BYTES_PER_ELEMENT);const payload=new SharedArrayBuffer(payloadBytes);return{holder:{port:port1,control,payload},reader:{port:port2,control,payload}}}function serveBrowserFilesystemChannel(filesystem,channel){const control=new Int32Array(channel.control);const payload=new Uint8Array(channel.payload);let staged=null;channel.port.onmessage=event=>{const requestId2=event.data;if(Atomics.load(control,STATE2)!==requestId2)return;let status=0;let output=new Uint8Array;let total=0;try{const operation=Atomics.load(control,OPERATION);const inputLength=Atomics.load(control,INPUT_LENGTH);const input=JSON.parse(decoder3.decode(payload.slice(0,inputLength)));if(operation===1){output=encoder2.encode(JSON.stringify(filesystem.existsSync(input.path)))}else if(operation===2||operation===13){if(operation===13&&!filesystem.lstatSync){throw Object.assign(new Error("The filesystem holder does not support lstat."),{code:"ENOTSUP"})}const stat2=input.throwIfNoEntry===false?operation===13?filesystem.lstatSync(input.path,{throwIfNoEntry:false}):filesystem.statSync(input.path,{throwIfNoEntry:false}):operation===13?filesystem.lstatSync(input.path):filesystem.statSync(input.path);if(stat2===void 0)output=encoder2.encode("null");else{const metadata=Object.fromEntries(STAT_FIELDS.filter(key=>stat2[key]!==void 0).map(key=>[key,stat2[key]]));output=encoder2.encode(JSON.stringify({...metadata,file:stat2.isFile(),directory:stat2.isDirectory(),symlink:stat2.isSymbolicLink?.()??false,size:stat2.size,mode:stat2.mode??420,mtimeMs:stat2.mtimeMs??0}))}}else if(operation===14&&filesystem.readlinkSync){output=encoder2.encode(JSON.stringify(filesystem.readlinkSync(input.path)))}else if(operation===15&&filesystem.symlinkSync&&typeof input.target==="string"){filesystem.symlinkSync(input.target,input.path)}else if(operation===4){output=encoder2.encode(JSON.stringify(filesystem.readdirSync(input.path)))}else if(operation===3){const bytes2=filesystem.readFileSync(input.path);total=bytes2.byteLength;const offset2=input.offset??0;output=bytes2.subarray(offset2,Math.min(total,offset2+payload.byteLength))}else if(operation===5){output=encoder2.encode(JSON.stringify(filesystem.realpathSync?.(input.path)??input.path))}else if(operation===6&&filesystem.writeFileSync){if(!Number.isSafeInteger(input.bytes)||input.bytes<0||inputLength+input.bytes>payload.byteLength)throw new Error("Invalid filesystem write length.");const piece=payload.slice(inputLength,inputLength+input.bytes);if(input.total===void 0){filesystem.writeFileSync(input.path,piece)}else{const offset2=input.offset??0;if(!Number.isSafeInteger(input.total)||input.total<0||offset2+piece.byteLength>input.total)throw new Error("Invalid filesystem write piece.");if(offset2===0)staged={path:input.path,bytes:new Uint8Array(input.total),received:0};if(!staged||staged.path!==input.path||staged.bytes.byteLength!==input.total||staged.received!==offset2){staged=null;throw new Error(`The filesystem channel received a write piece of ${input.path} out of order.`)}staged.bytes.set(piece,offset2);staged.received+=piece.byteLength;if(staged.received===input.total){const whole=staged.bytes;staged=null;filesystem.writeFileSync(input.path,whole)}}}else if(operation===16&&(filesystem.appendFileSync||filesystem.writeFileSync)){if(!Number.isSafeInteger(input.bytes)||input.bytes<0||inputLength+input.bytes>payload.byteLength)throw new Error("Invalid filesystem append length.");const piece=payload.slice(inputLength,inputLength+input.bytes);if(filesystem.appendFileSync)filesystem.appendFileSync(input.path,piece);else{const existing=filesystem.existsSync(input.path)?filesystem.readFileSync(input.path):new Uint8Array(0);const whole=new Uint8Array(existing.byteLength+piece.byteLength);whole.set(existing,0);whole.set(piece,existing.byteLength);filesystem.writeFileSync(input.path,whole)}}else if(operation===17&&(filesystem.writeAtSync||filesystem.writeFileSync)){if(!Number.isSafeInteger(input.bytes)||input.bytes<0||inputLength+input.bytes>payload.byteLength)throw new Error("Invalid filesystem write length.");if(!Number.isSafeInteger(input.position)||input.position<0)throw new Error("Invalid filesystem write position.");const piece=payload.slice(inputLength,inputLength+input.bytes);if(filesystem.writeAtSync)filesystem.writeAtSync(input.path,piece,input.position);else if(piece.byteLength===0&&filesystem.existsSync(input.path)){}else{const existing=filesystem.existsSync(input.path)?filesystem.readFileSync(input.path):new Uint8Array(0);const whole=new Uint8Array(Math.max(existing.byteLength,input.position+piece.byteLength));whole.set(existing,0);whole.set(piece,input.position);filesystem.writeFileSync(input.path,whole)}}else if(operation===7&&filesystem.mkdirSync){filesystem.mkdirSync(input.path,{recursive:input.recursive===true})}else if(operation===8&&filesystem.unlinkSync){filesystem.unlinkSync(input.path)}else if(operation===9&&filesystem.rmdirSync){filesystem.rmdirSync(input.path)}else if(operation===10&&filesystem.renameSync&&typeof input.to==="string"){filesystem.renameSync(input.path,input.to)}else if(operation===11&&filesystem.chmodSync&&Number.isInteger(input.mode)){filesystem.chmodSync(input.path,input.mode)}else if(operation===12&&filesystem.utimesSync&&Number.isFinite(input.atime)&&Number.isFinite(input.mtime)){filesystem.utimesSync(input.path,input.atimeDate?new Date(input.atime):input.atime,input.mtimeDate?new Date(input.mtime):input.mtime)}else{throw new Error(`Unsupported filesystem channel operation ${operation}.`)}if(output.byteLength>payload.byteLength)throw new Error("The filesystem channel answer exceeds its buffer.")}catch(cause){const error=cause;const message=cause instanceof Error?cause.message:String(cause);status=2;output=encoder2.encode(JSON.stringify({message,...typeof error?.code==="string"?{code:error.code}:{},...typeof error?.path==="string"?{path:error.path}:{}}));if(output.byteLength>payload.byteLength){status=1;output=encoder2.encode(message).subarray(0,payload.byteLength)}}if(Atomics.compareExchange(control,STATE2,requestId2,-requestId2)!==requestId2)return;payload.set(output);Atomics.store(control,STATUS2,status);Atomics.store(control,OUTPUT_LENGTH,output.byteLength);Atomics.store(control,TOTAL_LENGTH,total);Atomics.store(control,STATE2,requestId2+1);Atomics.notify(control,STATE2)};channel.port.start();return()=>{channel.port.onmessage=null;channel.port.close()}}var BrowserFilesystemChannelClient=class{constructor(channel){this.channel=channel;this.control=new Int32Array(channel.control);this.payload=new Uint8Array(channel.payload)}channel;control;payload;nextRequestId=1;existsSync(path3){return JSON.parse(decoder3.decode(this.call(1,{path:path3}).output))}statSync(path3,options){return this.stat(path3,2,options?.throwIfNoEntry!==false)}lstatSync(path3,options){return this.stat(path3,13,options?.throwIfNoEntry!==false)}stat(path3,operation,throwIfNoEntry){let bytes2;try{bytes2=this.call(operation,{path:path3,...throwIfNoEntry?{}:{throwIfNoEntry:false}}).output}catch(cause){if(!throwIfNoEntry&&cause.code==="ENOENT")return void 0;throw cause}const stat2=JSON.parse(decoder3.decode(bytes2));if(stat2===null){if(!throwIfNoEntry)return void 0;throw new Error("The filesystem holder returned absence for a throwing stat.")}return{...Object.fromEntries(STAT_FIELDS.filter(key=>stat2[key]!==void 0).map(key=>[key,stat2[key]])),isFile:()=>stat2.file,isDirectory:()=>stat2.directory,isSymbolicLink:()=>stat2.symlink===true,size:stat2.size,mode:stat2.mode,mtimeMs:stat2.mtimeMs,mtime:new Date(stat2.mtimeMs)}}readlinkSync(path3){return JSON.parse(decoder3.decode(this.call(14,{path:path3}).output))}symlinkSync(target,path3){this.call(15,{path:path3,target})}readdirSync(path3){return JSON.parse(decoder3.decode(this.call(4,{path:path3}).output))}realpathSync(path3){return JSON.parse(decoder3.decode(this.call(5,{path:path3}).output))}writeFileSync(path3,value){const bytes2=typeof value==="string"?encoder2.encode(value):value;const room=this.payload.byteLength-encoder2.encode(JSON.stringify({path:path3,bytes:bytes2.byteLength,offset:bytes2.byteLength,total:bytes2.byteLength})).byteLength;if(bytes2.byteLength<=room){this.call(6,{path:path3,bytes:bytes2.byteLength},bytes2);return}for(let offset2=0;offset2<bytes2.byteLength;offset2+=room){const piece=bytes2.subarray(offset2,Math.min(bytes2.byteLength,offset2+room));this.call(6,{path:path3,bytes:piece.byteLength,offset:offset2,total:bytes2.byteLength},piece)}}appendFileSync(path3,value){const bytes2=typeof value==="string"?encoder2.encode(value):value;const room=this.payload.byteLength-encoder2.encode(JSON.stringify({path:path3,bytes:bytes2.byteLength})).byteLength;if(bytes2.byteLength===0){this.call(16,{path:path3,bytes:0},bytes2);return}for(let offset2=0;offset2<bytes2.byteLength;offset2+=room){const piece=bytes2.subarray(offset2,Math.min(bytes2.byteLength,offset2+room));this.call(16,{path:path3,bytes:piece.byteLength},piece)}}writeAtSync(path3,value,position){const room=this.payload.byteLength-encoder2.encode(JSON.stringify({path:path3,position:position+value.byteLength,bytes:value.byteLength})).byteLength;if(value.byteLength===0){this.call(17,{path:path3,position,bytes:0},value);return}for(let offset2=0;offset2<value.byteLength;offset2+=room){const piece=value.subarray(offset2,Math.min(value.byteLength,offset2+room));this.call(17,{path:path3,position:position+offset2,bytes:piece.byteLength},piece)}}mkdirSync(path3,options){this.call(7,{path:path3,recursive:options?.recursive===true})}unlinkSync(path3){this.call(8,{path:path3})}rmdirSync(path3){this.call(9,{path:path3})}renameSync(path3,to2){this.call(10,{path:path3,to:to2})}chmodSync(path3,mode){this.call(11,{path:path3,mode})}utimesSync(path3,atime,mtime){this.call(12,{path:path3,atime:typeof atime==="number"?atime:Number(atime),mtime:typeof mtime==="number"?mtime:Number(mtime),atimeDate:typeof atime!=="number",mtimeDate:typeof mtime!=="number"})}readFileSync(path3,encoding){const first=this.call(3,{path:path3});let bytes2;if(first.output.byteLength>=first.total){bytes2=first.output}else{bytes2=new Uint8Array(first.total);bytes2.set(first.output,0);for(let offset2=first.output.byteLength;offset2<first.total;){const piece=this.call(3,{path:path3,offset:offset2});if(piece.output.byteLength===0)throw new Error(`The filesystem channel returned a short read of ${path3}.`);bytes2.set(piece.output,offset2);offset2+=piece.output.byteLength}}return encoding?decoder3.decode(bytes2):bytes2}call(operation,input,bytes2){const encoded=encoder2.encode(JSON.stringify(input));if(encoded.byteLength+(bytes2?.byteLength??0)>this.payload.byteLength)throw new Error("The filesystem channel request exceeds its buffer.");if(Atomics.load(this.control,STATE2)!==0)throw new Error("The filesystem channel is answering another request.");const requestId2=this.nextRequestId;this.nextRequestId=requestId2>=1073741821?1:requestId2+2;this.payload.set(encoded);if(bytes2)this.payload.set(bytes2,encoded.byteLength);Atomics.store(this.control,OPERATION,operation);Atomics.store(this.control,INPUT_LENGTH,encoded.byteLength);Atomics.store(this.control,STATE2,requestId2);this.channel.port.postMessage(requestId2);const deadline=Date.now()+REQUEST_TIMEOUT_MS;for(;;){const state=Atomics.load(this.control,STATE2);if(state===requestId2+1)break;if(state!==requestId2&&state!==-requestId2)throw new Error(`The filesystem channel is in state ${state} for request ${requestId2}.`);const remaining=Math.max(0,deadline-Date.now());if(remaining===0&&state===requestId2&&Atomics.compareExchange(this.control,STATE2,requestId2,0)===requestId2){throw new Error(`The filesystem holder did not answer within ${REQUEST_TIMEOUT_MS} ms.`)}Atomics.wait(this.control,STATE2,state,state===-requestId2?void 0:remaining)}const status=Atomics.load(this.control,STATUS2);const length=Atomics.load(this.control,OUTPUT_LENGTH);const total=Atomics.load(this.control,TOTAL_LENGTH);const output=this.payload.slice(0,length);Atomics.store(this.control,STATE2,0);if(status===2){const error=JSON.parse(decoder3.decode(output));throw Object.assign(new Error(error.message),error)}if(status!==0)throw new Error(decoder3.decode(output));return{output,total}}};function createConfinedNodeFilesystem(filesystem,policy){const writable=createProcessFilesystemMutationGuard(filesystem,policy);const view=new VirtualFS;Object.defineProperty(view,Symbol.for("@volter/browser-node/assert-filesystem-mutation"),{value:writable});const descriptors={existsSync:path3=>filesystem.existsSync(path3),statSync:(path3,options)=>filesystem.statSync(path3,options),lstatSync:(path3,options)=>filesystem.lstatSync(path3,options),readdirSync:path3=>filesystem.readdirSync(path3),realpathSync:path3=>filesystem.realpathSync(path3),readlinkSync:path3=>filesystem.readlinkSync(path3),accessSync:(path3,mode)=>filesystem.accessSync((mode??0)&2?writable(path3):path3,mode),readFileSync:(path3,encoding)=>{const bytes2=new Uint8Array(filesystem.readFileSync(path3));return encoding?new TextDecoder().decode(bytes2):bytes2},writeFileSync:(path3,bytes2)=>filesystem.writeFileSync(writable(path3),typeof bytes2==="string"?bytes2:new Uint8Array(bytes2)),appendFileSync:(path3,bytes2)=>filesystem.appendFileSync(writable(path3),typeof bytes2==="string"?bytes2:new Uint8Array(bytes2)),writeAtSync:(path3,bytes2,position)=>filesystem.writeAtSync(writable(path3),new Uint8Array(bytes2),position),mkdirSync:(path3,options)=>{if(options?.recursive&&filesystem.existsSync(path3)&&filesystem.lstatSync(path3).isDirectory()&&!filesystem.lstatSync(path3).isSymbolicLink())return;filesystem.mkdirSync(writable(path3),options)},unlinkSync:path3=>filesystem.unlinkSync(writable(path3)),rmdirSync:path3=>filesystem.rmdirSync(writable(path3)),renameSync:(from,to2)=>{const source=writable(from);const destination=writable(to2);filesystem.renameSync(source,destination)},chmodSync:(path3,mode)=>{const target=writable(path3);const change=Reflect.get(filesystem,"chmodSync");if(!change)unsupported2("chmod");change.call(filesystem,target,mode)},utimesSync:(path3,atime,mtime)=>{const target=writable(path3);const change=Reflect.get(filesystem,"utimesSync");if(!change)unsupported2("utimes");change.call(filesystem,target,atime,mtime)},symlinkSync:()=>unsupported2("symlink"),linkSync:()=>unsupported2("link"),toSnapshot:()=>structuredClone(filesystem.toSnapshot()),watch:filesystem.watch.bind(filesystem),on:(event,listener)=>{filesystem.on(event,listener);return view},off:(event,listener)=>{filesystem.off(event,listener);return view}};for(const[name,value]of Object.entries(descriptors)){Object.defineProperty(view,name,{value,configurable:false,writable:false})}return view}function unsupported2(operation){throw Object.assign(new Error(`Node filesystem does not support ${operation}.`),{code:"ENOTSUP"})}var MAGIC=2019846480;var HEADER_WORDS=6;var RECORD_WORDS=6;var RECORD_NUMBERS=3;var PATH_OFFSET=0;var PATH_LENGTH=1;var FLAGS3=2;var MODE=3;var CHILD_START=4;var CHILD_COUNT=5;var MTIME=0;var OFFSET=1;var LENGTH3=2;var HAS_ENTRY=1;var HAS_CHILDREN=2;var PACKED=4;var ASCII2=32;var TYPE_SHIFT=3;var TYPES=["file","directory","symlink"];var LONE_SURROGATE=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;var encoder3=new TextEncoder;var decoder4=new TextDecoder;function hashPath(path3){let hash2=2166136261;for(let index2=0;index2<path3.length;index2+=1){hash2^=path3.charCodeAt(index2);hash2=Math.imul(hash2,16777619)}return hash2>>>0}function encodeSharedIndex(entries,children){const paths=[...entries.keys()];for(const path3 of paths)if(LONE_SURROGATE.test(path3))throw new Error("A path in the store is not well-formed UTF-16.");const at3=new Map;for(let index2=0;index2<paths.length;index2+=1)at3.set(paths[index2],index2);for(const parent2 of children.keys())if(!at3.has(parent2)){at3.set(parent2,paths.length);paths.push(parent2)}const count=paths.length;const encoded=new Map;const byteLengths=new Uint32Array(count);let stringBytes=0;for(let index2=0;index2<count;index2+=1){const path3=paths[index2];let ascii=true;for(let unit=0;unit<path3.length;unit+=1)if(path3.charCodeAt(unit)>=128){ascii=false;break}if(!ascii)encoded.set(index2,encoder3.encode(path3));byteLengths[index2]=ascii?path3.length:encoded.get(index2).length;stringBytes+=byteLengths[index2]}let childTotal=0;for(const names2 of children.values())childTotal+=names2.size;let tableSize=1;while(tableSize<count*2)tableSize<<=1;const recordsAt=HEADER_WORDS*4;const numbersAt=align(recordsAt+count*RECORD_WORDS*4,8);const tableAt=numbersAt+count*RECORD_NUMBERS*8;const childListAt=tableAt+tableSize*4;const stringsAt=childListAt+childTotal*4;const buffer2=new SharedArrayBuffer(align(stringsAt+stringBytes,8));const header=new Uint32Array(buffer2,0,HEADER_WORDS);header.set([MAGIC,count,tableSize,childTotal,stringBytes,entries.size]);const records=new Uint32Array(buffer2,recordsAt,count*RECORD_WORDS);const numbers=new Float64Array(buffer2,numbersAt,count*RECORD_NUMBERS);const table=new Uint32Array(buffer2,tableAt,tableSize);const childList=new Uint32Array(buffer2,childListAt,childTotal);const strings2=new Uint8Array(buffer2,stringsAt,stringBytes);let stringCursor=0;let childCursor=0;for(let index2=0;index2<count;index2+=1){const path3=paths[index2];const word=index2*RECORD_WORDS;const other=encoded.get(index2);if(other)strings2.set(other,stringCursor);else for(let unit=0;unit<path3.length;unit+=1)strings2[stringCursor+unit]=path3.charCodeAt(unit);const length=byteLengths[index2];records[word+PATH_OFFSET]=stringCursor;records[word+PATH_LENGTH]=length;stringCursor+=length;let flags=other?0:ASCII2;const entry=entries.get(path3);if(entry){flags|=HAS_ENTRY|TYPES.indexOf(entry.type)<<TYPE_SHIFT;if(entry.pack)flags|=PACKED;records[word+MODE]=entry.mode;const number=index2*RECORD_NUMBERS;numbers[number+MTIME]=entry.mtimeMs;numbers[number+OFFSET]=entry.offset;numbers[number+LENGTH3]=entry.length}const names2=children.get(path3);if(names2){flags|=HAS_CHILDREN;records[word+CHILD_START]=childCursor;records[word+CHILD_COUNT]=names2.size;for(const name of names2){const child=at3.get(`${path3}/${name}`);if(child===void 0)throw new Error(`The store's children name ${path3}/${name}, which its index does not hold.`);childList[childCursor++]=child}}records[word+FLAGS3]=flags;let slot=hashPath(path3)&tableSize-1;while(table[slot]!==0)slot=slot+1&tableSize-1;table[slot]=index2+1}if(childCursor!==childTotal)throw new Error("The shared index's children did not add up.");return buffer2}function align(value,to2){return Math.ceil(value/to2)*to2}var SharedIndex=class{buffer;count;entryCount;records;numbers;table;childList;strings;mask;constructor(buffer2){const header=new Uint32Array(buffer2,0,HEADER_WORDS);if(header[0]!==MAGIC)throw new Error("Not a shared store index.");const[,count,tableSize,childTotal,stringBytes,entryCount]=header;this.buffer=buffer2;this.count=count;this.entryCount=entryCount;const recordsAt=HEADER_WORDS*4;const numbersAt=align(recordsAt+count*RECORD_WORDS*4,8);const tableAt=numbersAt+count*RECORD_NUMBERS*8;const childListAt=tableAt+tableSize*4;const stringsAt=childListAt+childTotal*4;this.records=new Uint32Array(buffer2,recordsAt,count*RECORD_WORDS);this.numbers=new Float64Array(buffer2,numbersAt,count*RECORD_NUMBERS);this.table=new Uint32Array(buffer2,tableAt,tableSize);this.childList=new Uint32Array(buffer2,childListAt,childTotal);this.strings=new Uint8Array(buffer2,stringsAt,stringBytes);this.mask=tableSize-1}find(path3){let slot=hashPath(path3)&this.mask;for(;;){const held=this.table[slot];if(held===0)return-1;if(this.pathIs(held-1,path3))return held-1;slot=slot+1&this.mask}}entry(record){const word=record*RECORD_WORDS;const flags=this.records[word+FLAGS3];if(!(flags&HAS_ENTRY))return void 0;const number=record*RECORD_NUMBERS;const entry={type:TYPES[flags>>>TYPE_SHIFT&3],mode:this.records[word+MODE],mtimeMs:this.numbers[number+MTIME],offset:this.numbers[number+OFFSET],length:this.numbers[number+LENGTH3]};if(flags&PACKED)entry.pack="packages";return entry}typeAt(record){const flags=this.records[record*RECORD_WORDS+FLAGS3];return flags&HAS_ENTRY?TYPES[flags>>>TYPE_SHIFT&3]:void 0}hasEntry(record){return(this.records[record*RECORD_WORDS+FLAGS3]&HAS_ENTRY)!==0}childNames(record){const word=record*RECORD_WORDS;if(!(this.records[word+FLAGS3]&HAS_CHILDREN))return void 0;const start=this.records[word+CHILD_START];const skip=this.records[word+PATH_LENGTH]+1;const names2=[];for(let index2=0;index2<this.records[word+CHILD_COUNT];index2+=1){const child=this.childList[start+index2]*RECORD_WORDS;names2.push(this.decode(this.records[child+PATH_OFFSET]+skip,this.records[child+PATH_LENGTH]-skip,(this.records[child+FLAGS3]&ASCII2)!==0))}return names2}path(record){const word=record*RECORD_WORDS;return this.decode(this.records[word+PATH_OFFSET],this.records[word+PATH_LENGTH],(this.records[word+FLAGS3]&ASCII2)!==0)}decode(start,length,ascii){if(!ascii)return decoder4.decode(this.strings.slice(start,start+length));let text="";for(let at3=start,end=start+length;at3<end;at3+=4096){text+=String.fromCharCode.apply(null,this.strings.subarray(at3,Math.min(end,at3+4096)))}return text}pathIs(record,path3){const word=record*RECORD_WORDS;const start=this.records[word+PATH_OFFSET];const length=this.records[word+PATH_LENGTH];if(!(this.records[word+FLAGS3]&ASCII2))return this.path(record)===path3;if(length!==path3.length)return false;for(let index2=0;index2<length;index2+=1)if(this.strings[start+index2]!==path3.charCodeAt(index2))return false;return true}};var DELETED=Symbol("deleted");function sameIndexEntry(left,right){return left===right||!!left&&!!right&&left.type===right.type&&left.offset===right.offset&&left.length===right.length&&left.pack===right.pack&&left.mode===right.mode&&left.mtimeMs===right.mtimeMs&&left.capacity===right.capacity}var OverlaidIndex=class{constructor(base){this.base=base}base;overlay=new Map;delta=0;get[Symbol.toStringTag](){return"Map"}get size(){return this.base.entryCount+this.delta}get(path3){const over=this.overlay.get(path3);if(over!==void 0)return over===DELETED?void 0:over;const record=this.base.find(path3);return record<0?void 0:this.base.entry(record)}typeOf(path3){const over=this.overlay.get(path3);if(over!==void 0)return over===DELETED?void 0:over.type;const record=this.base.find(path3);return record<0?void 0:this.base.typeAt(record)}has(path3){const over=this.overlay.get(path3);if(over!==void 0)return over!==DELETED;const record=this.base.find(path3);return record>=0&&this.base.hasEntry(record)}set(path3,entry){if(!this.has(path3))this.delta+=1;const record=this.base.find(path3);if(record>=0&&sameIndexEntry(this.base.entry(record),entry))this.overlay.delete(path3);else this.overlay.set(path3,entry);return this}delete(path3){if(!this.has(path3))return false;const record=this.base.find(path3);if(record>=0&&this.base.hasEntry(record))this.overlay.set(path3,DELETED);else this.overlay.delete(path3);this.delta-=1;return true}clear(){throw new Error("A reader's index is not cleared; it is replaced.")}*entries(){for(const[path3,entry]of this.overlay)if(entry!==DELETED)yield[path3,entry];for(let record=0;record<this.base.count;record+=1){if(!this.base.hasEntry(record))continue;const path3=this.base.path(record);if(this.overlay.has(path3))continue;yield[path3,this.base.entry(record)]}}*keys(){for(const[path3]of this.entries())yield path3}*values(){for(const[,entry]of this.entries())yield entry}[Symbol.iterator](){return this.entries()}forEach(callback,thisArg){for(const[path3,entry]of this.entries())callback.call(thisArg,entry,path3,this)}*changed(){for(const[path3,entry]of this.overlay)if(entry!==DELETED)yield[path3,entry]}*changes(){for(const[path3,entry]of this.overlay)yield[path3,entry===DELETED?null:entry]}get overlaid(){return this.overlay.size}boundedChanges(){if(this.overlay.size>65536)return void 0;const changes=[];let bytes2=0;for(const[path3,entry]of this.changes()){bytes2+=path3.length*2+128;if(bytes2>8*1024*1024)return void 0;changes.push([path3,entry])}return changes}};var OverlaidChildren=class{constructor(base){this.base=base}base;overlay=new Map;get(path3){const over=this.overlay.get(path3);if(over!==void 0)return over===DELETED?void 0:over;const record=this.base.find(path3);const names2=record<0?void 0:this.base.childNames(record);return names2?new Set(names2):void 0}mutable(path3){const over=this.overlay.get(path3);if(over!==void 0&&over!==DELETED)return over;const names2=new Set(over===DELETED?[]:this.get(path3)??[]);this.overlay.set(path3,names2);return names2}delete(path3){this.overlay.set(path3,DELETED)}};var STORE_BASE_DIRECTORY="supercode-browser-filesystems";var PACKAGES_STORE="packages";var STORE_STATE_FILE="state.json";var PACKAGES_ROOT="/packages";var BROWSER_PACK_RETENTION_ROOT="/opt/.browser-packs";var PACKAGES_LOCK="supercode-browser-packages";var PACKAGES_OPEN_LOCK="supercode-browser-packages-open";var encoder4=new TextEncoder;var decoder5=new TextDecoder("utf-8",{fatal:true});var BASE_DIRECTORY=STORE_BASE_DIRECTORY;var TREE_STORE_PREFIX="host-tree.";var GENERATIONS_DIRECTORY="generations";var STAGING_DIRECTORY="atomic-staging";var STATE_FILE=STORE_STATE_FILE;var INDEX_FILE="index.json";var LOG_FILE="index-log.bin";var PACK_FILE="pack.bin";var RECORD_HEADER_BYTES=8;var MAX_RECORD_BYTES=64*1024*1024;var MAX_FILE_BYTES=1024*1024*1024;var ORIGIN_QUOTA_SHARE=.95;var PROJECT_ROOTS=["/workspace","/home","/opt"];var STORE_CLOCK_EPOCH=0;var STORE_CLOCK_LOG=1;var MAX_ENTRIES=1e6;var MAX_LOG_BYTES=8*1024*1024;var FLUSH_WINDOW_MS=250;var COMPACTION_FLOOR_BYTES=64*1024*1024;var SESSION_COMPACTION_BYTES=256*1024*1024;var COPY_BUFFER_BYTES=4*1024*1024;var DIRECTORY_MODE=493;var FILE_MODE=420;function createPackStore(environment,options={}){const explicitBytes=options.limits?.maxBytes;const maximumEntries=options.limits?.maxEntries??MAX_ENTRIES;if(explicitBytes!==void 0&&(!Number.isSafeInteger(explicitBytes)||explicitBytes<1)||!Number.isSafeInteger(maximumEntries)||maximumEntries<1||maximumEntries>MAX_ENTRIES){throw new Error("Invalid OPFS workspace limits.")}let originRoom=Number.MAX_SAFE_INTEGER;let heldAtOpen;let project;let shared=false;let readOnly=false;let extentsOnly=false;let generationHandle;let linked=0;let linkedBytes=0;let releaseLock;let projectId;let generation;let entries=new Map;let children=new LocalChildren;let packAccess;let imageRangesDigest;let imageReader;let deferredImage;let receivedImageCompletion;let receivedImageLine;let generationInitializedAt=0;let logAccess;let immutableReadEnd=0;const readAhead=new Map;const READ_AHEAD_BYTES=256*1024;const READ_AHEAD_BLOCKS=32;let packBytes=0;let flushTimer;let lastFlushAt=-Infinity;let flushes=0;let flushMs=0;let logBytes=0;let liveBytes=0;let deadBytes=0;let rewrites=0;let rewrittenBytes=0;let mutationUndo;let bytesUndo;let mutationFailure;let initializing=false;let openingController;let checkpointTail=Promise.resolve();let activeStorageOperations=0;let closing=false;let rewritingGeneration=false;let clockView;let transitions=0;let clockClosed=false;function publishLog(){if(!clockView||clockClosed)return;if(logBytes>2147483647){retireClock();return}Atomics.store(clockView,STORE_CLOCK_LOG,logBytes)}function retireClock(){if(!clockView||clockClosed)return;clockClosed=true;if((Atomics.load(clockView,STORE_CLOCK_EPOCH)&1)===0)Atomics.add(clockView,STORE_CLOCK_EPOCH,1)}function beginTransition(){transitions+=1;if(transitions===1&&clockView&&!clockClosed)Atomics.add(clockView,STORE_CLOCK_EPOCH,1)}function endTransition(){transitions-=1;if(transitions>0||!clockView||clockClosed)return;publishLog();if(!clockClosed)Atomics.add(clockView,STORE_CLOCK_EPOCH,1)}function clock(){if(readOnly)throw new Error("A store open for reading follows its owner's clock; it has none of its own.");if(!clockView){clockView=new Int32Array(new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT));clockView[STORE_CLOCK_EPOCH]=transitions>0||clockClosed?1:0;publishLog()}return clockView.buffer}let seedCache;const SEED_REPLAY_BYTES=8*1024*1024;let startedFromSeed=false;function readerSeed(options2){if(readOnly||!clockView||!generation||initializing||transitions>0||clockClosed||closing)return void 0;const epoch=Atomics.load(clockView,STORE_CLOCK_EPOCH);if(epoch&1)return void 0;if(options2?.overlays&&entries instanceof OverlaidIndex){const changes=entries.boundedChanges();if(changes){return withImageCompletion({generation,index:entries.base.buffer,changes,packBytes,logBytes,epoch,liveBytes,linked,linkedBytes})}}if(seedCache&&seedCache.generation===generation&&seedCache.epoch===epoch&&logBytes>=seedCache.logBytes&&logBytes-seedCache.logBytes<=(options2?.current?0:SEED_REPLAY_BYTES))return withImageCompletion(seedCache);let index2;try{index2=encodeSharedIndex(entries,childrenMap())}catch(cause){console.warn(`[pack-store] no reader seed: ${cause instanceof Error?cause.message:String(cause)}`);return void 0}seedCache={generation,index:index2,packBytes,logBytes,epoch,liveBytes,linked,linkedBytes};standOnSeed(index2);return withImageCompletion(seedCache)}function withImageCompletion(seed){const packagesImage=options.packages?.imageCompletionSeed();return packagesImage?{...seed,packagesImage}:seed}function imageCompletionSeed(){if(!imageReader||!imageRangesDigest||!generation||initializing||transitions>0||closing)return void 0;return{generation,rangesDigest:imageRangesDigest,completed:imageReader.completionBuffer,...imageReader.receiptKey?{metadata:{ranges:imageReader.verifiedRanges,receiptKey:imageReader.receiptKey}}:{}}}function standOnSeed(index2){const roomy=[];if(entries instanceof OverlaidIndex){for(const[path3,entry]of entries.changed())if(entry.capacity!==void 0)roomy.push([path3,entry])}else{for(const[path3,entry]of entries)if(entry.capacity!==void 0)roomy.push([path3,entry])}const base=new SharedIndex(index2);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);for(const[path3,entry]of roomy)entries.set(path3,entry)}function childrenMap(){if(children instanceof LocalChildren)return children.map;const derived=new Map;for(const path3 of entries.keys()){const parent2=parentPath(path3);if(parent2===path3)continue;let names2=derived.get(parent2);if(!names2){names2=new Set;derived.set(parent2,names2)}names2.add(path3.slice(parent2.length+1))}return derived}function follow(){if(!readOnly||extentsOnly||closing||!logAccess)return;replayLog(logBytes)}async function ownStorageOperation(operation){if(closing)throw new Error("This OPFS workspace is closing.");activeStorageOperations+=1;let failure;let failed=false;try{return await operation()}catch(cause){failed=true;failure=cause;throw cause}finally{activeStorageOperations-=1;if(closing&&activeStorageOperations===0){try{closeStorage()}catch(cause){if(failed)throw new AggregateError([failure,cause],"OPFS operation and deferred close both failed.");throw cause}}}}async function rewriteGeneration(operation){assertWritable();if(activeStorageOperations!==0)return Promise.reject(new Error("Wait for the current OPFS storage operation before replacing its generation."));rewritingGeneration=true;return ownStorageOperation(async()=>{try{return await operation()}finally{rewritingGeneration=false}})}function read(path3){if(closing)throw new Error("This OPFS workspace is closing.");const entry=entries.get(path3);if(!entry||entry.type==="directory")throw new Error(`OPFS workspace file does not exist: ${path3}`);return readEntry(entry)}function readRange(path3,offset2,length){if(closing)throw new Error("This OPFS workspace is closing.");const entry=entries.get(path3);if(!entry||entry.type==="directory")throw new Error(`OPFS workspace file does not exist: ${path3}`);const start=Math.min(Math.max(0,offset2),entry.length);const count=Math.min(Math.max(0,length),entry.length-start);if(entry.pack){const packages2=options.packages;if(!packages2)throw new Error("This store has no shared package store to read from.");return packages2.readExtent(entry.offset+start,count)}return readExtent(entry.offset+start,count)}function readEntry(entry){if(entry.pack){const packages2=options.packages;if(!packages2)throw new Error("This store has no shared package store to read from.");return packages2.readExtent(entry.offset,entry.length)}return readExtent(entry.offset,entry.length)}function readExtent(offset2,length){if(closing)throw new Error("This OPFS workspace is closing.");const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");const value=new Uint8Array(length);if(length>0&&length<=READ_AHEAD_BYTES&&offset2>=0&&offset2+length<=immutableReadEnd){let copied=0;while(copied<length){const position=offset2+copied;const start=Math.floor(position/READ_AHEAD_BYTES)*READ_AHEAD_BYTES;let block=readAhead.get(start);if(!block){block=new Uint8Array(Math.min(READ_AHEAD_BYTES,immutableReadEnd-start));imageReader?.ensure(start,block.byteLength);if(access.read(block,{at:start})!==block.byteLength)throw new Error("An OPFS package range could not be read completely.")}readAhead.delete(start);readAhead.set(start,block);if(readAhead.size>READ_AHEAD_BLOCKS)readAhead.delete(readAhead.keys().next().value);const from=position-start;const count=Math.min(length-copied,block.byteLength-from);value.set(block.subarray(from,from+count),copied);copied+=count}return value}imageReader?.ensure(offset2,length);if(length>0&&access.read(value,{at:offset2})!==length){throw new Error("An OPFS workspace file could not be read completely.")}return value}async function initialize2(requestedProjectId,openOptions={}){if(closing&&project||!project&&activeStorageOperations!==0)throw new Error("Wait for this OPFS workspace to finish closing before opening it again.");if(initializing)throw new Error("This OPFS store is already opening a workspace.");if(project){if(projectId!==validProjectId(requestedProjectId))throw new Error("Close this OPFS store before opening another workspace.");return entries.size>0}initializing=true;closing=false;const opening=new AbortController;openingController=opening;try{entries=new Map;children=new LocalChildren;generation=void 0;imageRangesDigest=void 0;generationHandle=void 0;mutationUndo=void 0;mutationFailure=void 0;packBytes=logBytes=liveBytes=deadBytes=linked=linkedBytes=0;checkpointPrefix=void 0;rewrites=rewrittenBytes=flushes=flushMs=0;lastFlushAt=-Infinity;projectId=validProjectId(requestedProjectId);readOnly=openOptions.readOnly===true;receivedImageCompletion=readOnly?openOptions.imageCompletion:void 0;receivedImageLine=readOnly?openOptions.imageLine:void 0;extentsOnly=readOnly&&openOptions.extentsOnly===true;shared=openOptions.shared===true||readOnly;heldAtOpen=void 0;try{const estimate=await environment.navigator.storage.estimate?.();if(estimate?.quota)originRoom=Math.max(0,Math.floor(estimate.quota*ORIGIN_QUOTA_SHARE)-(estimate.usage??0))}catch{}if(!shared)await acquireSessionLock(opening.signal);opening.signal.throwIfAborted();const root2=await storageRoot();opening.signal.throwIfAborted();try{const base=await root2.getDirectoryHandle(BASE_DIRECTORY,{create:!readOnly});opening.signal.throwIfAborted();project=await base.getDirectoryHandle(projectId,{create:!readOnly})}catch(cause){opening.signal.throwIfAborted();if(readOnly&¬Found2(cause))return false;throw cause}opening.signal.throwIfAborted();let state=readStorageState(await readJson(project,STATE_FILE));opening.signal.throwIfAborted();if(!state&&readOnly){await assertNoUncommittedGenerations();return false}if(!state&&shared){await environment.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive",signal:opening.signal},async()=>{opening.signal.throwIfAborted();state=readStorageState(await readJson(project,STATE_FILE));opening.signal.throwIfAborted();if(!state){await assertNoUncommittedGenerations();await writeGeneration({files:[],pack:new ArrayBuffer(0)});await writeSweepMark(project)}});opening.signal.throwIfAborted();if(!state){generationHandle=await generationDirectory(generation,false);opening.signal.throwIfAborted();return false}}if(!state){await assertNoUncommittedGenerations();opening.signal.throwIfAborted();return false}const openCommitted=async state2=>{let directory2;try{directory2=await generationDirectory(state2.generation,false)}catch(cause){opening.signal.throwIfAborted();if(!notFound2(cause))throw cause;throw new Error("The committed OPFS workspace generation is missing. Stored generations were retained.",{cause})}opening.signal.throwIfAborted();generation=state2.generation;generationInitializedAt=state2.initializedAt;imageRangesDigest=state2.imageRanges;generationHandle=directory2;if(extentsOnly){if(projectId===PACKAGES_STORE&&environment.navigator.locks){await environment.navigator.locks.request(PACKAGES_LOCK,{mode:"shared",signal:opening.signal},async()=>{await openGenerationHandles(directory2);immutableReadEnd=packAccess.getSize()})}else await openGenerationHandles(directory2);opening.signal.throwIfAborted();return true}const seed=readOnly?openOptions.seed:void 0;if(seed&&seed.generation===state2.generation){const base=new SharedIndex(seed.index);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);packBytes=seed.packBytes;if(seed.changes)applyIndexRecord({packBytes:seed.packBytes,changes:seed.changes});await openGenerationHandles(directory2);opening.signal.throwIfAborted();logBytes=seed.logBytes;({liveBytes,linked,linkedBytes}=seed);deadBytes=Math.max(0,packBytes-liveBytes);startedFromSeed=true;return entries.size>0}const retained=!readOnly?await readRetainedIndex(directory2):void 0;opening.signal.throwIfAborted();if(retained){const base=new SharedIndex(retained.index);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);({packBytes,liveBytes,linked,linkedBytes}=retained);const epoch=Atomics.load(new Int32Array(clock()),STORE_CLOCK_EPOCH);seedCache={generation,index:retained.index,packBytes,liveBytes,linked,linkedBytes,logBytes:0,epoch}}else{entries=readIndex(await readJson(directory2,INDEX_FILE));opening.signal.throwIfAborted();rebuildChildren();packBytes=indexPackBytes(entries)}await openGenerationHandles(directory2);opening.signal.throwIfAborted();const represented=retained?await verifiedJournalPrefix(retained):0;opening.signal.throwIfAborted();if(represented){checkpointPrefix={generation,bytes:represented};if(seedCache)seedCache.logBytes=represented}replayLog(represented,!!retained);if(retained)deadBytes=Math.max(0,packBytes-liveBytes);else measureBytes();assertWorkspaceQuota();if(shared&&!readOnly&&!retained&&entries.size>=1e4){flushStorage();await writeIndexAtomically(directory2,entries,{access:logAccess,bytes:logBytes,packBytes})}if(!shared){packAccess.truncate(packBytes);await removeEntry(project,STAGING_DIRECTORY,true);await discardGenerations(generation);opening.signal.throwIfAborted();if(deadBytes>COMPACTION_FLOOR_BYTES&&deadBytes>liveBytes)await compact()}opening.signal.throwIfAborted();return entries.size>0};if(shared&&!readOnly){return await environment.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive",signal:opening.signal},async()=>{state=readStorageState(await readJson(project,STATE_FILE));if(!state)throw new Error("The committed package store state is missing. Stored data was retained.");return openCommitted(state)})}return await openCommitted(state)}catch(cause){const failures=[cause];try{closeGenerationHandles()}catch(error){failures.push(error)}try{releaseLock?.()}catch(error){failures.push(error)}releaseLock=void 0;project=void 0;if(failures.length>1)throw new AggregateError(failures,"OPFS workspace open and cleanup failed.");throw cause}finally{initializing=false;openingController=void 0}}function refresh(options2){return ownStorageOperation(()=>refreshStorage(options2?.whole===true))}async function refreshStorage(whole=false){if(extentsOnly)throw new Error("A store opened for its extents alone has no index to follow.");if(readOnly&&project){const state=readStorageState(await readJson(project,STATE_FILE));if(!state)throw new Error("The committed OPFS workspace state is missing. Stored data was retained.");if(state.generation!==generation||whole){const directory2=await generationDirectory(state.generation,false);const index2=readIndex(await readJson(directory2,INDEX_FILE));packBytes=indexPackBytes(index2);if(state.generation!==generation){generation=state.generation;generationInitializedAt=state.initializedAt;imageRangesDigest=state.imageRanges;await openGenerationHandles(directory2)}generation=state.generation;generationHandle=directory2;entries=index2;rebuildChildren();replayLog();measureBytes();return}}const access=logAccess;if(!access||!generationHandle)return;const size=access.getSize();let reread=false;if(size<logBytes){entries=readIndex(await readJson(generationHandle,INDEX_FILE));rebuildChildren();packBytes=indexPackBytes(entries);logBytes=0;reread=true}const before=logBytes;replayLog(logBytes);if(reread||logBytes!==before)measureBytes()}async function storageRoot(){let last;for(let attempt=0;attempt<10;attempt+=1){openingController?.signal.throwIfAborted();try{return await environment.navigator.storage.getDirectory()}catch(cause){last=cause;await new Promise(resolve2=>setTimeout(resolve2,200))}}throw last instanceof Error?last:new Error("This browser workspace's storage is unavailable.")}const OPEN_ATTEMPT_MS=1e4;async function openSyncAccess(handle,name){let refusal;const signal=openingController?.signal;for(let attempt=0;attempt<2;attempt+=1){signal?.throwIfAborted();const pending=handle.createSyncAccessHandle({mode:"readwrite-unsafe"});let timer;let abort;let claimed=false;try{const cancelled2=new Promise((_resolve,reject)=>{abort=()=>reject(signal?.reason??new DOMException("Workspace open was cancelled.","AbortError"));signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted)abort()});const opened=await Promise.race([pending.then(access=>({access})).catch(cause=>{refusal=cause;return void 0}),new Promise(resolve2=>{timer=setTimeout(()=>resolve2(void 0),OPEN_ATTEMPT_MS)}),cancelled2]);signal?.throwIfAborted();if(opened){claimed=true;return opened.access}}finally{if(timer!==void 0)clearTimeout(timer);if(abort)signal?.removeEventListener("abort",abort);if(!claimed)void pending.then(access=>access.close(),()=>void 0).catch(cause=>console.error("Late workspace handle cleanup failed.",cause))}if(refusal 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). ${refusal.message}`)}await new Promise(resolve2=>setTimeout(resolve2,500))}const reason=refusal instanceof Error?` (${refusal.message})`:"";throw new Error(`This browser workspace's ${name} is held by another page${reason}.`)}async function openGenerationHandles(directory2){closeGenerationHandles();const pack=await directory2.getFileHandle(PACK_FILE);packAccess=await openSyncAccess(pack,"store");try{if(packAccess.getSize()<packBytes)throw new Error("The committed OPFS workspace pack is incomplete. Stored data was retained.");const log=await directory2.getFileHandle(LOG_FILE);logAccess=await openSyncAccess(log,"record of changes");logBytes=logAccess.getSize();if(imageRangesDigest){const supplied=receivedImageCompletion;const completion=supplied&&supplied.generation===generation&&supplied.rangesDigest===imageRangesDigest?supplied:void 0;let ranges;let receiptKey;if(completion?.metadata){ranges=validateImageRanges(completion.metadata.ranges);receiptKey=completion.metadata.receiptKey;if(!/^[a-f0-9]{64}$/u.test(receiptKey))throw new Error("The owner's immutable receipt key is invalid.")}else{const file2=await(await directory2.getFileHandle(IMAGE_RANGES_FILE)).getFile();const bytes2=new Uint8Array(await file2.arrayBuffer());if(await indexDigest(bytes2)!==imageRangesDigest)throw new Error("The committed immutable image ranges have changed. Stored data was retained.");ranges=validateImageRanges(JSON.parse(decoder5.decode(bytes2)));receiptKey=await indexDigest(encoder4.encode(JSON.stringify(ranges)))}if(ranges.bytes>packAccess.getSize())throw new Error("The immutable image reservation is incomplete. Stored data was retained.");const line=completion?receivedImageLine:void 0;if(!line)receivedImageLine?.port.close();receivedImageLine=void 0;imageReader=new ImageRangeReader(ranges,directory2,`${projectId}.${generation}`,completion?.completed,receiptKey,line);console.log(`[boot-trace] ${JSON.stringify({event:"image-reader-open",at:Date.now(),reader:`${projectId}.${generation}`,offered:supplied!==void 0,shared:completion!==void 0,...supplied&&!completion?{offeredGeneration:supplied.generation,generation,rangesMatch:supplied.rangesDigest===imageRangesDigest}:{}})}`);await imageReader.initialize();deferredImage=ranges.image}}catch(cause){closeGenerationHandles();throw cause}}function closeGenerationHandles(){imageReader?.close();imageReader=void 0;deferredImage=void 0;const pack=packAccess,log=logAccess;packAccess=void 0;logAccess=void 0;logBytes=0;immutableReadEnd=0;readAhead.clear();try{pack?.close()}finally{log?.close()}}function replayLog(from=0,measureChanges=false){const access=logAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");const size=access.getSize();if(size<=from){logBytes=size;return}const buffer2=new Uint8Array(size-from);if(access.read(buffer2,{at:from})!==buffer2.byteLength)throw new Error("The OPFS workspace index log could not be read.");const packSize=packAccess?.getSize()??Infinity;const view=new DataView(buffer2.buffer);let offset2=0;const end=buffer2.byteLength;while(offset2+RECORD_HEADER_BYTES<=end){const length=view.getUint32(offset2,true);const checksum=view.getUint32(offset2+4,true);const start=offset2+RECORD_HEADER_BYTES;if(length===0||length>MAX_RECORD_BYTES||start+length>end)break;const body=buffer2.subarray(start,start+length);if(fingerprint2(body)!==checksum)break;let record;try{record=readIndexRecord(JSON.parse(decoder5.decode(body)))}catch{break}if(record.packBytes>packSize)break;applyIndexRecord(record,measureChanges);offset2=start+length}if(offset2!==end&&!shared)access.truncate(from+offset2);logBytes=from+offset2}function applyIndexRecord(record,measureChanges=false){for(const[path3,entry]of record.changes){const previous=entries.get(path3);if(entry&&sameIndexEntry(previous,entry)){attach(path3);continue}if(measureChanges){if(previous?.pack){linked-=1;linkedBytes-=previous.length}else if(previous)liveBytes-=previous.length;if(entry?.pack){linked+=1;linkedBytes+=entry.length}else if(entry)liveBytes+=entry.length}if(entry===null){entries.delete(path3);detach(path3)}else{entries.set(path3,entry);attach(path3)}}packBytes=Math.max(packBytes,record.packBytes)}function measureBytes(){liveBytes=0;linked=0;linkedBytes=0;for(const entry of entries.values()){if(entry.pack){linked+=1;linkedBytes+=entry.length}else liveBytes+=entry.length}deadBytes=Math.max(0,packBytes-liveBytes)}function indexPackBytes(index2){let end=0;for(const entry of index2.values())if(!entry.pack)end=Math.max(end,entry.offset+entry.length);return end}const SESSION_LOCK_WAIT_MS=5e3;async function acquireSessionLock(signal){if(!environment.navigator.locks)return;if(!projectId)throw new Error("OPFS filesystem project is not initialized.");const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),SESSION_LOCK_WAIT_MS);try{await new Promise((resolve2,reject)=>{void environment.navigator.locks.request(`supercode-browser-filesystem-${projectId}`,{mode:"exclusive",signal:signal?AbortSignal.any([signal,controller.signal]):controller.signal},async()=>{clearTimeout(timer);resolve2();await new Promise(release2=>{releaseLock=release2})}).catch(()=>reject(signal?.aborted?signal.reason:new Error("This browser workspace is already open in another tab.")))})}finally{clearTimeout(timer)}}function validProjectId(value){if(typeof value!=="string"||!/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/u.test(value)){throw new Error("OPFS filesystem projectId is invalid.")}return value}async function projectDirectory(){if(!project)throw new Error("OPFS filesystem worker is not initialized.");return project}async function generationDirectory(name,create2){const root2=await(await projectDirectory()).getDirectoryHandle(GENERATIONS_DIRECTORY,{create:create2});return root2.getDirectoryHandle(name,{create:create2})}async function assertNoUncommittedGenerations(){let directory2;try{directory2=await(await projectDirectory()).getDirectoryHandle(GENERATIONS_DIRECTORY)}catch(cause){if(notFound2(cause))return;throw cause}for await(const _entry of directory2.entries()){throw new Error("OPFS workspace state is missing but stored generations exist. Stored data was retained.")}}async function discardGenerations(retain2){const directory2=await projectDirectory();let root2;try{root2=await directory2.getDirectoryHandle(GENERATIONS_DIRECTORY)}catch(cause){if(notFound2(cause))return;throw cause}for await(const[name]of root2.entries()){if(name!==retain2)await removeGenerationQuietly(root2,name)}}function assertWritable(){if(closing)throw new Error("This OPFS workspace is closing.");if(rewritingGeneration)throw new Error("This OPFS workspace is replacing its generation; wait for that operation before writing.");if(readOnly)throw new Error("This store is open for reading; its owner writes it.");if(mutationFailure)throw mutationFailure}async function applyMutations(mutations){applyNow(mutations)}let checkpointPending=false;let maintenanceDeferrals=0;let checkpointPrefix;let compactingLive=false;function maintain(){if(maintenanceDeferrals>0)return;const represented=checkpointPrefix&&checkpointPrefix.generation===generation&&checkpointPrefix.bytes<=logBytes?checkpointPrefix.bytes:0;if(logBytes-represented>MAX_LOG_BYTES&&!checkpointPending){checkpointPending=true;const operation=shared?environment.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive"},async()=>{if(!project||closing)return;await refreshStorage();const prefix2=checkpointPrefix;const represented2=prefix2&&prefix2.generation===generation&&prefix2.bytes<=logBytes?prefix2.bytes:0;if(logBytes-represented2>MAX_LOG_BYTES)await checkpoint()}):checkpoint();void operation.catch(cause=>console.error("The workspace's log could not be checkpointed; it is replayed at the next open.",cause)).finally(()=>{checkpointPending=false})}if(!shared&&!compactingLive&&deadBytes>SESSION_COMPACTION_BYTES&&deadBytes>liveBytes){compactingLive=true;void ownStorageOperation(compactWhileWriting).catch(cause=>console.error("The workspace could not be compacted; it keeps its generation.",cause)).finally(()=>{compactingLive=false})}}async function deferMaintenance(operation){assertWritable();maintenanceDeferrals+=1;try{return await operation()}finally{maintenanceDeferrals-=1;if(maintenanceDeferrals===0&&!closing&&project)maintain()}}function applyMutation(mutation,changes){const path3=requiredPath2(mutation.path);if(mutation.operation==="write"){if(entries.get(path3)?.type==="directory")throw new Error(`OPFS write target is a directory: ${path3}`);if(!(mutation.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const value=mutation.content;if(value.byteLength>MAX_FILE_BYTES)throw new Error(`${path3} is ${value.byteLength} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`);assertBounds(path3,value.byteLength);createParents(path3,changes);const offset2=appendPack(value);setEntry(path3,{type:mutation.symlink?"symlink":"file",mode:mutation.mode??entries.get(path3)?.mode??FILE_MODE,mtimeMs:mutation.mtimeMs??Date.now(),offset:offset2,length:value.byteLength},changes);return}if(mutation.operation==="append"){const previous=entries.get(path3);if(previous&&previous.type!=="file")throw new Error(`OPFS append target is not a file: ${path3}`);if(!(mutation.content instanceof Uint8Array))throw new Error("OPFS append requires file content.");const added=mutation.content;const length=(previous?.length??0)+added.byteLength;if(length>MAX_FILE_BYTES)throw new Error(`${path3} is ${length} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`);assertBounds(path3,length);createParents(path3,changes);const mode=mutation.mode??previous?.mode??FILE_MODE;const mtimeMs=mutation.mtimeMs??Date.now();const room=previous&&!previous.pack?previous.capacity??previous.length:0;if(projectId!==PACKAGES_STORE&&previous&&!previous.pack&&previous.length>0&&(length<=room||previous.offset+room===packBytes)){writePackAt(previous.offset+previous.length,added);setEntry(path3,{...previous,mode,mtimeMs,length,capacity:Math.max(room,length)},changes);deadBytes-=Math.max(previous.length,previous.capacity??0);rewrites-=1;rewrittenBytes-=previous.length;return}const whole=new Uint8Array(length);if(previous&&previous.length>0)whole.set(readEntry(previous),0);whole.set(added,length-added.byteLength);const offset2=appendPack(whole);const capacity=Math.min(MAX_FILE_BYTES,Math.max(length,length*2,64*1024));if(capacity>length)reservePack(offset2+capacity);setEntry(path3,{type:"file",mode,mtimeMs,offset:offset2,length,capacity},changes);return}if(mutation.operation==="write-at"){const previous=entries.get(path3);if(previous&&previous.type!=="file")throw new Error(`OPFS write target is not a file: ${path3}`);if(!(mutation.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const bytes2=mutation.content;const position=mutation.position;const held=previous?.length??0;if(bytes2.byteLength===0&&previous)return;const length=bytes2.byteLength===0?held:Math.max(held,position+bytes2.byteLength);if(length>MAX_FILE_BYTES)throw new Error(`${path3} is ${length} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`);assertBounds(path3,length);createParents(path3,changes);const mode=mutation.mode??previous?.mode??FILE_MODE;const mtimeMs=mutation.mtimeMs??Date.now();const room=previous&&!previous.pack?previous.capacity??previous.length:0;if(projectId!==PACKAGES_STORE&&previous&&!previous.pack&&held>0&&(length<=room||previous.offset+room===packBytes)){if(position>held)writePackAt(previous.offset+held,new Uint8Array(position-held));if(bytesUndo&&position<held){const end=Math.min(held,position+bytes2.byteLength);bytesUndo.push([previous.offset+position,readExtent(previous.offset+position,end-position)])}writePackAt(previous.offset+position,bytes2);setEntry(path3,{...previous,mode,mtimeMs,length,capacity:Math.max(room,length)},changes);if(length!==held){deadBytes-=Math.max(previous.length,previous.capacity??0);rewrites-=1;rewrittenBytes-=previous.length}return}const whole=new Uint8Array(length);if(previous&&held>0)whole.set(readEntry(previous),0);if(bytes2.byteLength>0)whole.set(bytes2,position);const offset2=appendPack(whole);const capacity=Math.min(MAX_FILE_BYTES,Math.max(length,length*2,64*1024));if(capacity>length)reservePack(offset2+capacity);setEntry(path3,{type:"file",mode,mtimeMs,offset:offset2,length,capacity},changes);return}if(mutation.operation==="mkdir"){createParents(path3,changes);const existing=entries.get(path3);if(existing&&existing.type!=="directory")throw new Error(`OPFS path is a file: ${path3}`);setEntry(path3,{type:"directory",mode:mutation.mode??existing?.mode??DIRECTORY_MODE,mtimeMs:mutation.mtimeMs??existing?.mtimeMs??Date.now(),offset:0,length:0},changes);return}if(mutation.operation==="remove"){removeTree3(path3,changes);if(storeRoots().includes(path3)){setEntry(path3,{type:"directory",mode:DIRECTORY_MODE,mtimeMs:Date.now(),offset:0,length:0},changes)}return}if(mutation.operation==="link"){linkShared(path3,sharedPath(mutation.source),changes);return}if(mutation.operation==="rename"){renameTree(path3,requiredPath2(mutation.destination),changes);return}const entry=entries.get(path3);if(!entry)throw new Error(`OPFS metadata target does not exist: ${path3}`);setEntry(path3,{...entry,mode:mutation.mode??entry.mode,mtimeMs:mutation.mtimeMs??entry.mtimeMs},changes)}function setEntry(path3,entry,changes){const previous=entries.get(path3);if(mutationUndo&&!mutationUndo.has(path3))mutationUndo.set(path3,previous);const sameExtent=previous!==void 0&&previous.type===entry.type&&previous.offset===entry.offset&&previous.length===entry.length&&previous.pack===entry.pack;if(previous&&!sameExtent){forget(previous,path3);if(previous.type!=="directory"&&entry.type!=="directory"&&previous.length>0&&!previous.pack){rewrites+=1;rewrittenBytes+=previous.length}}entries.set(path3,entry);attach(path3);if(!sameExtent){if(entry.pack){linked+=1;linkedBytes+=entry.length}else liveBytes+=entry.length}changes.push([path3,entry])}function attach(path3){const parent2=parentPath(path3);if(parent2===path3)return;children.mutable(parent2).add(path3.slice(parent2.length+1))}function detach(path3){const parent2=parentPath(path3);if(children.get(parent2)?.has(path3.slice(parent2.length+1)))children.mutable(parent2).delete(path3.slice(parent2.length+1));children.delete(path3)}function rebuildChildren(){children=new LocalChildren;for(const path3 of entries.keys())attach(path3)}function descendants(prefix2){const found=[];const visit=path3=>{const entry=entries.get(path3);if(!entry)return;found.push([path3,entry]);const names2=children.get(path3);if(names2)for(const name of names2)visit(`${path3}/${name}`)};visit(prefix2);return found}function forget(previous,path3){if(previous.pack){linked-=1;linkedBytes-=previous.length;return}liveBytes-=previous.length;deadBytes+=Math.max(previous.length,previous.capacity??0)}function deleteEntry(path3,changes){const previous=entries.get(path3);if(!previous)return;if(mutationUndo&&!mutationUndo.has(path3))mutationUndo.set(path3,previous);entries.delete(path3);detach(path3);forget(previous,path3);changes.push([path3,null])}function linkShared(path3,source,changes){const packages2=options.packages;if(!packages2)throw new Error("This store has no shared package store to link from.");const prefix2=sharedPath(source);const files=packages2.descendants(prefix2);if(files.length===0)throw new Error(`The shared package store does not hold ${source}.`);createParents(path3,changes);removeTree3(path3,changes);assertEntryCount(entries.size+files.length);for(const[candidate,entry]of files){const target=candidate===prefix2?path3:`${path3}${candidate.slice(prefix2.length)}`;setEntry(target,entry.type==="directory"?{type:"directory",mode:entry.mode,mtimeMs:entry.mtimeMs,offset:0,length:0}:{type:entry.type,mode:entry.mode,mtimeMs:entry.mtimeMs,offset:entry.offset,length:entry.length,pack:PACKAGES_STORE},changes)}}function createParents(path3,changes){const above=parentPath(path3);if(above!==path3&&entries.get(above)?.type==="directory"){assertEntryCount(entries.size+(entries.has(path3)?0:1));return}const missing=[];let current3=rootOf(path3)??storeRoots()[0];if(!entries.has(current3))missing.push(current3);if(path3!==current3){for(const segment of segmentsOf(relativePath3(parentPath(path3)))){current3=`${current3}/${segment}`;const existing=entries.get(current3);if(existing&&existing.type!=="directory")throw new Error(`OPFS path parent is a file: ${current3}`);if(!existing)missing.push(current3)}}assertEntryCount(entries.size+missing.length+(entries.has(path3)?0:1));const now=Date.now();for(const directory2 of missing){setEntry(directory2,{type:"directory",mode:DIRECTORY_MODE,mtimeMs:now,offset:0,length:0},changes)}}function removeTree3(path3,changes){for(const[candidate]of descendants(path3))deleteEntry(candidate,changes)}function renameTree(source,destination,changes){if(source===destination)return;if(destination.startsWith(`${source}/`))throw new Error("An OPFS rename cannot move a directory into itself.");const moved=descendants(source);if(moved.length===0){if(entries.has(destination))return;throw new Error(`OPFS rename source does not exist: ${source}`)}createParents(destination,changes);removeTree3(destination,changes);for(const[path3]of moved)deleteEntry(path3,changes);for(const[path3,entry]of moved)setEntry(`${destination}${path3.slice(source.length)}`,entry,changes);assertEntryCount(entries.size)}function sharedPath(value){if(typeof value!=="string"||!value.startsWith(`${PACKAGES_ROOT}/`)||value.includes("\0")||value.length>4096){throw new Error("Invalid shared store path.")}segmentsOf(value.slice(PACKAGES_ROOT.length+1));return value}function storeRoots(){return projectId===PACKAGES_STORE?[PACKAGES_ROOT]:PROJECT_ROOTS}function rootOf(path3){return storeRoots().find(root2=>path3===root2||path3.startsWith(`${root2}/`))}function maximumBytes(){if(explicitBytes!==void 0)return explicitBytes;heldAtOpen??=liveBytes;return Math.min(Number.MAX_SAFE_INTEGER,heldAtOpen+originRoom)}function boundSource(){return explicitBytes!==void 0?"its configured limit":"the origin's storage quota"}function assertBounds(path3,bytes2){const previous=entries.get(path3);const replaced=previous&&!previous.pack?previous.length:0;const limit=maximumBytes();if(liveBytes-replaced+bytes2>limit){const holder=shared?"the origin's shared packages":"the project's own files";throw new Error(`OPFS workspace exceeds ${boundSource()}: writing ${path3} (${bytes2} bytes) would take ${holder} past ${limit} bytes (${liveBytes} bytes held, ${replaced} replaced).`)}}function assertEntryCount(count){if(count>maximumEntries)throw new Error("OPFS workspace exceeds its entry limit.")}function assertWorkspaceQuota(){assertEntryCount(entries.size);const limit=maximumBytes();if(liveBytes>limit)throw new Error(`OPFS workspace exceeds ${boundSource()}: ${shared?"the origin's shared packages":"the project's own files"} hold ${liveBytes} bytes, past ${limit}.`)}function writePackAt(offset2,value){const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");let written=0;while(written<value.byteLength){const count=access.write(value.subarray(written),{at:offset2+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}packBytes=Math.max(packBytes,offset2+value.byteLength)}function reservePack(end){const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");if(end<=packBytes)return;access.truncate(end);packBytes=end}function appendPack(value){const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");const offset2=packBytes;let written=0;while(written<value.byteLength){const count=access.write(value.subarray(written),{at:offset2+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}packBytes=offset2+value.byteLength;return offset2}function assertStored(log){const pack=packAccess;if(pack.getSize()>=packBytes&&log.getSize()>=logBytes)return;pack.flush();log.flush();const packSize=pack.getSize(),logSize=log.getSize();if(packSize>=packBytes&&logSize>=logBytes)return;throw Object.assign(new Error(`This browser is keeping less than the tab wrote (the store's pack holds ${packSize} of ${packBytes} bytes, its log ${logSize} of ${logBytes}): its storage is full, as a private window's is well below its quota.`),{name:"QuotaExceededError",code:"ENOSPC"})}function commit(changes,options2={}){const access=logAccess;if(!access||!packAccess)throw new Error("OPFS filesystem worker is not initialized.");if(changes.length===0)return;const body=encoder4.encode(JSON.stringify({packBytes,changes}));if(body.byteLength>MAX_RECORD_BYTES)throw new Error("An OPFS workspace index record exceeds its size limit.");const record=new Uint8Array(RECORD_HEADER_BYTES+body.byteLength);const view=new DataView(record.buffer);view.setUint32(0,body.byteLength,true);view.setUint32(4,fingerprint2(body),true);record.set(body,RECORD_HEADER_BYTES);let written=0;while(written<record.byteLength){const count=access.write(record.subarray(written),{at:logBytes+written});if(count<=0)throw new Error("The OPFS workspace index log could not be written completely.");written+=count}logBytes+=record.byteLength;assertStored(access);if(options2.publish!==false)publishLog();if(performance.now()-lastFlushAt>=FLUSH_WINDOW_MS)flushStorage();else if(flushTimer===void 0)flushTimer=setTimeout(flushStorage,FLUSH_WINDOW_MS)}function flushStorage(){if(flushTimer!==void 0){clearTimeout(flushTimer);flushTimer=void 0}if(mutationFailure)throw mutationFailure;const startedAt=performance.now();packAccess?.flush();logAccess?.flush();lastFlushAt=performance.now();flushes+=1;flushMs+=lastFlushAt-startedAt}function checkpoint(){const previous=checkpointTail;const operation=ownStorageOperation(()=>previous.catch(()=>void 0).then(checkpointStorage));checkpointTail=operation;return operation}async function checkpointStorage(){assertWritable();if(!generation)return;const checkpointGeneration=generation;const access=logAccess;const directory2=await generationDirectory(checkpointGeneration,false);if(!access||access!==logAccess||checkpointGeneration!==generation){throw new Error("OPFS workspace changed generations before its checkpoint could start.")}flushStorage();const checkpointBytes=logBytes;await writeIndexAtomically(directory2,entries,{access,bytes:checkpointBytes,packBytes});if(checkpointGeneration===generation)checkpointPrefix={generation:checkpointGeneration,bytes:checkpointBytes};if(access===logAccess&&checkpointGeneration===generation&&checkpointBytes===logBytes){beginTransition();try{access.truncate(0);access.flush();logBytes=0;checkpointPrefix={generation:checkpointGeneration,bytes:0}}finally{endTransition()}}}function writeGeneration(snapshot){return rewriteGeneration(()=>writeGenerationContents(validateSnapshot(snapshot)))}async function writeGenerationContents(snapshot){const next2=crypto.randomUUID();const directory2=await generationDirectory(next2,true);const handle=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(handle,"store");const index2=new Map;let cursor=0;try{for(const entry of snapshot.files){let offset2=0;let length=0;if(entry.type!=="directory"){const value=new Uint8Array(snapshot.pack,entry.offset??0,entry.length??0);offset2=cursor;length=value.byteLength;let written=0;while(written<length){const count=access.write(value.subarray(written),{at:offset2+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}cursor+=length}index2.set(entry.path,{type:entry.type,mode:entry.mode??(entry.type==="directory"?DIRECTORY_MODE:FILE_MODE),mtimeMs:entry.mtimeMs??Date.now(),offset:offset2,length})}for(const root2 of storeRoots()){if(!index2.has(root2))index2.set(root2,{type:"directory",mode:DIRECTORY_MODE,mtimeMs:Date.now(),offset:0,length:0})}assertEntryCount(index2.size);access.truncate(cursor);access.flush()}finally{access.close()}const prepared=await writeIndexAtomically(directory2,index2);await commitGeneration(next2,directory2,index2,cursor,prepared)}async function compact(){await retain(()=>true)}async function compactWhileWriting(){let transitioning=false;let named=false;let stayed=false;try{await compactWhileWritingIn(()=>{transitioning=true},()=>{named=true},()=>{stayed=true})}finally{if(transitioning&&(named||stayed))endTransition();else if(transitioning)retireClock()}}async function compactWhileWritingIn(began,named,stayed){const next2=crypto.randomUUID();const directory2=await generationDirectory(next2,true);const pack=await openSyncAccess(await directory2.getFileHandle(PACK_FILE,{create:true}),"store");let log;let switched=false;try{log=await openSyncAccess(await directory2.getFileHandle(LOG_FILE,{create:true}),"record of changes");log.truncate(0);const buffer2=new Uint8Array(COPY_BUFFER_BYTES);let cursor=0;const copy2=entry=>{if(entry.pack)return{...entry};if(entry.type==="directory"||entry.length===0)return{...entry,offset:0,length:0};const source=packAccess;if(!source)throw new Error("OPFS filesystem worker is not initialized.");const offset2=cursor;let copied=0;while(copied<entry.length){const span=Math.min(buffer2.byteLength,entry.length-copied);const chunk=buffer2.subarray(0,span);imageReader?.ensure(entry.offset+copied,span);if(source.read(chunk,{at:entry.offset+copied})!==span)throw new Error("An OPFS workspace file could not be read completely.");let written=0;while(written<span){const count=pack.write(chunk.subarray(written),{at:offset2+copied+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}copied+=span}cursor+=entry.length;const{capacity:_room,...extent}=entry;return{...extent,offset:offset2}};const copies=new Map;let sliceStart=performance.now();for(const[path3,entry]of[...entries]){if(closing||rewritingGeneration)return;if(entries.get(path3)!==entry)continue;copies.set(entry,copy2(entry));if(performance.now()-sliceStart>8){await new Promise(resolve2=>setTimeout(resolve2,0));sliceStart=performance.now()}}if(closing||rewritingGeneration||!packAccess||!logAccess)return;beginTransition();began();const index2=new Map;for(const[path3,entry]of entries)index2.set(path3,copies.get(entry)??copy2(entry));pack.truncate(cursor);pack.flush();log.flush();flushStorage();const previous={pack:packAccess,log:logAccess};packAccess=pack;logAccess=log;logBytes=0;entries=index2;rebuildChildren();packBytes=cursor;generation=next2;generationHandle=directory2;measureBytes();switched=true;const document2=new Map(index2);try{previous.pack.close()}finally{previous.log.close()}try{await writeIndexAtomically(directory2,document2);const state={storageVersion:4,generation:next2,initializedAt:Date.now()};await writeJsonAtomically(await projectDirectory(),STATE_FILE,state)}catch(cause){mutationFailure=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});throw mutationFailure}named();await discardGenerations(next2)}finally{if(!switched){stayed();try{pack.close()}finally{log?.close()}await removeGenerationQuietly(await(await projectDirectory()).getDirectoryHandle(GENERATIONS_DIRECTORY),next2)}}}async function remapLinks(moved){assertWritable();beginTransition();try{await remapLinksIn(moved)}finally{endTransition()}}async function remapLinksIn(moved){let changed=false;for(const[path3,entry]of entries){if(!entry.pack||entry.length===0)continue;const offset2=moved.get(entry.offset);if(offset2===void 0)throw new Error(`The shared store no longer holds the bytes of ${path3}.`);if(offset2===entry.offset)continue;entries.set(path3,{...entry,offset:offset2});changed=true}if(changed)await checkpoint()}function retain(keep){return rewriteGeneration(()=>retainGeneration(keep))}async function retainGeneration(keep){const source=packAccess;if(!source)throw new Error("OPFS filesystem worker is not initialized.");const moved=new Map;const next2=crypto.randomUUID();const directory2=await generationDirectory(next2,true);const handle=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(handle,"store");const index2=new Map;const buffer2=new Uint8Array(COPY_BUFFER_BYTES);let cursor=0;try{for(const[path3,entry]of entries){if(!keep(path3,entry))continue;if(entry.pack){index2.set(path3,{...entry});continue}if(entry.type==="directory"||entry.length===0){index2.set(path3,{...entry,offset:0,length:0});continue}const offset2=cursor;moved.set(entry.offset,offset2);let copied=0;while(copied<entry.length){const span=Math.min(buffer2.byteLength,entry.length-copied);const chunk=buffer2.subarray(0,span);imageReader?.ensure(entry.offset+copied,span);if(source.read(chunk,{at:entry.offset+copied})!==span){throw new Error("An OPFS workspace file could not be read completely.")}let written=0;while(written<span){const count=access.write(chunk.subarray(written),{at:offset2+copied+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}copied+=span}cursor+=entry.length;const{capacity:_room,...extent}=entry;index2.set(path3,{...extent,offset:offset2,length:entry.length})}access.truncate(cursor);access.flush()}finally{access.close()}const prepared=await writeIndexAtomically(directory2,index2);await commitGeneration(next2,directory2,index2,cursor,prepared);return moved}async function commitGeneration(name,directory2,index2,bytes2,prepared,rangesDigest){beginTransition();try{await commitGenerationIn(name,directory2,index2,bytes2,prepared,rangesDigest)}finally{endTransition()}}async function commitGenerationIn(name,directory2,index2,bytes2,prepared,rangesDigest){const journal=await directory2.getFileHandle(LOG_FILE,{create:true});const journalAccess=await openSyncAccess(journal,"record of changes");try{journalAccess.truncate(0);journalAccess.flush()}finally{journalAccess.close()}const state={storageVersion:rangesDigest?5:4,generation:name,initializedAt:Date.now(),...rangesDigest?{imageRanges:rangesDigest}:{}};await writeJsonAtomically(await projectDirectory(),STATE_FILE,state);closeGenerationHandles();generation=name;generationInitializedAt=state.initializedAt;imageRangesDigest=rangesDigest;if(prepared){const base=new SharedIndex(prepared.index);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);seedCache=void 0}else{entries=index2;rebuildChildren()}packBytes=bytes2;generationHandle=directory2;await openGenerationHandles(directory2);if(prepared){({liveBytes,linked,linkedBytes}=prepared);deadBytes=Math.max(0,packBytes-liveBytes)}else measureBytes();if(!shared)await discardGenerations(name)}async function installPreparedImage(prepared,json,binary,suppliedRanges,verified=false){assertWritable();if(!shared||projectId!==PACKAGES_STORE)throw new Error("Only the shared package store can reserve immutable image extents.");if(packBytes!==0||[...entries.values()].some(entry=>entry.type!=="directory"))return false;const ranges=validateImageRanges(suppliedRanges);if(ranges.bytes!==prepared.packBytes||prepared.entries>MAX_ENTRIES||prepared.liveBytes>prepared.packBytes||json.byteLength!==prepared.json.raw||binary.byteLength!==prepared.binary.raw||!await matchesDigest(json,prepared.json.sha256,verified)||!await matchesDigest(binary,prepared.binary.sha256,verified)){throw new Error("The image's prepared metadata does not match its document.")}const newline=json.subarray(0,4096).indexOf(10);if(newline<0)throw new Error("The prepared index has no bounded retained header.");const retained=JSON.parse(`${decoder5.decode(json.subarray(0,newline-1))}}`);const measures={packBytes:prepared.packBytes,liveBytes:prepared.liveBytes,linked:0,linkedBytes:0};const header=retained.retainedIndex;if(header.version!==1||header.digest!==await retainedIndexDigestOf(prepared.binary.sha256,measures)||header.packBytes!==measures.packBytes||header.liveBytes!==measures.liveBytes||header.linked!==0||header.linkedBytes!==0){throw new Error("The prepared index's retained measures are inconsistent.")}const index2=new SharedArrayBuffer(binary.byteLength);new Uint8Array(index2).set(binary);if(new SharedIndex(index2).entryCount!==prepared.entries)throw new Error("The prepared index has the wrong number of entries.");return rewriteGeneration(async()=>{const name=crypto.randomUUID();const directory2=await generationDirectory(name,true);const pack=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(pack,"immutable image reservation");try{access.truncate(prepared.packBytes);access.flush()}finally{access.close()}const rangeBytes=encoder4.encode(JSON.stringify(ranges));await writeBytesAtomically(directory2,IMAGE_RANGES_FILE,rangeBytes);await writeBytesAtomically(directory2,RETAINED_INDEX_FILE,binary);await writeBytesAtomically(directory2,INDEX_FILE,json);await commitGeneration(name,directory2,new Map,prepared.packBytes,{index:index2,...measures},await indexDigest(rangeBytes));return true})}async function installPreparedProject(prepared,json,binary,verified=false,imageInstalled){assertWritable();if(shared||!options.packages||!imageInstalled&&!options.packages.deferredImage)throw new Error("Prepared project paths require a verified shared image.");if(packBytes!==0||[...entries.values()].some(entry=>entry.type!=="directory"))return false;if(json.byteLength!==prepared.json.raw||binary.byteLength!==prepared.binary.raw||!await matchesDigest(json,prepared.json.sha256,verified)||!await matchesDigest(binary,prepared.binary.sha256,verified)){throw new Error("The image's prepared project does not match its descriptor.")}const newline=json.subarray(0,4096).indexOf(10);if(newline<0)throw new Error("The prepared project has no bounded retained header.");const header=JSON.parse(`${decoder5.decode(json.subarray(0,newline-1))}}`).retainedIndex;const measures={packBytes:0,liveBytes:0,linked:prepared.linked,linkedBytes:prepared.linkedBytes};if(header.version!==1||header.digest!==await retainedIndexDigestOf(prepared.binary.sha256,measures)||header.packBytes!==0||header.liveBytes!==0||header.linked!==prepared.linked||header.linkedBytes!==prepared.linkedBytes){throw new Error("The prepared project's retained measures are inconsistent.")}const index2=new SharedArrayBuffer(binary.byteLength);new Uint8Array(index2).set(binary);if(new SharedIndex(index2).entryCount!==prepared.entries||prepared.entries>maximumEntries)throw new Error("The prepared project has invalid entry bounds.");return rewriteGeneration(async()=>{const name=crypto.randomUUID();const directory2=await generationDirectory(name,true);const pack=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(pack,"prepared project");try{access.truncate(0);access.flush()}finally{access.close()}await writeBytesAtomically(directory2,RETAINED_INDEX_FILE,binary);await writeBytesAtomically(directory2,INDEX_FILE,json);if(imageInstalled&&!await imageInstalled)return false;if(!options.packages?.deferredImage)throw new Error("Prepared project paths require a verified shared image.");await commitGeneration(name,directory2,new Map,0,{index:index2,...measures});return true})}async function readSnapshot(){if(closing)throw new Error("This OPFS workspace is closing.");if(!packAccess)throw new Error("OPFS filesystem worker is not initialized.");const files=[];const paths=[...entries.keys()].sort((left,right)=>depth4(left)-depth4(right)||(left<right?-1:1));let total=0;for(const entry of entries.values())if(entry.type!=="directory")total+=entry.length;const pack=new ArrayBuffer(total);const view=new Uint8Array(pack);let cursor=0;for(const path3 of paths){const entry=entries.get(path3);if(entry.type==="directory"){files.push({path:path3,type:"directory",mode:entry.mode,mtimeMs:entry.mtimeMs});continue}if(entry.length>0)view.set(readEntry(entry),cursor);files.push({path:path3,type:entry.type,offset:cursor,length:entry.length,mode:entry.mode,mtimeMs:entry.mtimeMs});cursor+=entry.length}for(const root2 of[...storeRoots()].reverse()){if(!entries.has(root2))files.unshift({path:root2,type:"directory",mode:DIRECTORY_MODE,mtimeMs:Date.now()})}return validateSnapshot({files,pack})}async function writeJsonAtomically(directory2,name,value){await writeBytesAtomically(directory2,name,encoder4.encode(JSON.stringify(value)))}async function writeBytesAtomically(directory2,name,bytes2){const staging=await(await projectDirectory()).getDirectoryHandle(STAGING_DIRECTORY,{create:true});const temporaryName=crypto.randomUUID();const handle=await staging.getFileHandle(temporaryName,{create:true});const access=await openSyncAccess(handle,"index");try{let written=0;while(written<bytes2.byteLength){const count=access.write(bytes2.subarray(written),{at:written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}access.truncate(bytes2.byteLength);access.flush()}finally{access.close()}try{await handle.move(directory2,name)}finally{await removeEntry(staging,temporaryName,false)}}const RETAINED_INDEX_FILE="index.shared";async function indexDigest(bytes2){const hash2=await crypto.subtle.digest("SHA-256",bytes2);return Array.from(new Uint8Array(hash2),byte=>byte.toString(16).padStart(2,"0")).join("")}async function matchesDigest(bytes2,digest,verified){return verified||await indexDigest(bytes2)===digest}function retainedIndexDigestOf(binaryDigest,measures){const{packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,journalPrefix}=measures;return indexDigest(encoder4.encode(`${JSON.stringify({packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,...journalPrefix?{journalPrefix}:{}})}:${binaryDigest}`))}async function retainedIndexDigest(bytes2,measures){const{packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,journalPrefix}=measures;return indexDigest(encoder4.encode(`${JSON.stringify({packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,...journalPrefix?{journalPrefix}:{}})}:${await indexDigest(bytes2)}`))}async function writeIndexAtomically(directory2,index2,journal){const document2=indexDocument(index2);if(typeof SharedArrayBuffer==="undefined"||index2.size<1e4){await writeJsonAtomically(directory2,INDEX_FILE,document2);return}const snapshot=new Map(document2.entries);const names2=new Map;const measure={packBytes:journal?.packBytes??0,liveBytes:0,linked:0,linkedBytes:0};for(const[path3,entry]of snapshot){const parent2=parentPath(path3);if(parent2!==path3){let children2=names2.get(parent2);if(!children2){children2=new Set;names2.set(parent2,children2)}children2.add(path3.slice(parent2.length+1))}if(entry.pack){measure.linked+=1;measure.linkedBytes+=entry.length}else{measure.liveBytes+=entry.length;measure.packBytes=Math.max(measure.packBytes,entry.offset+entry.length)}}let encoded;try{encoded=encodeSharedIndex(snapshot,names2)}catch{await writeJsonAtomically(directory2,INDEX_FILE,document2);return}const json=JSON.stringify(document2.entries);const prefixBytes=journal?new Uint8Array(journal.bytes):void 0;if(prefixBytes&&journal.access.read(prefixBytes,{at:0})!==prefixBytes.byteLength){throw new Error("The checkpoint's journal prefix could not be read completely.")}const journalPrefix=prefixBytes?{bytes:prefixBytes.byteLength,digest:await indexDigest(prefixBytes)}:void 0;const bytes2=new Uint8Array(encoded).slice();const retained={version:journalPrefix?2:1,digest:await retainedIndexDigest(bytes2,{...measure,...journalPrefix?{journalPrefix}:{}}),...measure,...journalPrefix?{journalPrefix}:{}};try{await writeBytesAtomically(directory2,RETAINED_INDEX_FILE,bytes2)}catch{await writeJsonAtomically(directory2,INDEX_FILE,{entries:JSON.parse(json)});return}await writeBytesAtomically(directory2,INDEX_FILE,encoder4.encode(`{"retainedIndex":${JSON.stringify(retained)},
|
|
5892
|
+
`)}}}catch{}added.push(name)});await this.writeLockfile(resolved);return added}async writeLockfile(resolved){const lockfile={};for(const[name,pkg]of resolved){lockfile[name]={version:pkg.version,resolved:pkg.tarballUrl}}const lockfilePath=join2(this.cwd,"node_modules",".package-lock.json");this.vfs.writeFileSync(lockfilePath,JSON.stringify(lockfile,null,2))}async updatePackageJson(packageName,version2,isDev){const pkgJsonPath=join2(this.cwd,"package.json");let pkgJson={};if(this.vfs.existsSync(pkgJsonPath)){pkgJson=JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"))}const field=isDev?"devDependencies":"dependencies";if(!pkgJson[field]){pkgJson[field]={}}pkgJson[field][packageName]=version2;this.vfs.writeFileSync(pkgJsonPath,JSON.stringify(pkgJson,null,2))}list(){const nodeModulesPath=join2(this.cwd,"node_modules");if(!this.vfs.existsSync(nodeModulesPath)){return{}}const packages2={};const entries=this.vfs.readdirSync(nodeModulesPath);for(const entry of entries){if(entry.startsWith("."))continue;if(entry.startsWith("@")){const scopePath=join2(nodeModulesPath,entry);const scopedPkgs=this.vfs.readdirSync(scopePath);for(const scopedPkg of scopedPkgs){const pkgJsonPath=join2(scopePath,scopedPkg,"package.json");if(this.vfs.existsSync(pkgJsonPath)){const pkgJson=JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"));packages2[`${entry}/${scopedPkg}`]=pkgJson.version}}}else{const pkgJsonPath=join2(nodeModulesPath,entry,"package.json");if(this.vfs.existsSync(pkgJsonPath)){const pkgJson=JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"));packages2[entry]=pkgJson.version}}}return packages2}};function parsePackageSpec(spec){if(spec.startsWith("@")){const slashIndex=spec.indexOf("/");if(slashIndex===-1){throw new Error(`Invalid package spec: ${spec}`)}const afterSlash=spec.slice(slashIndex+1);const atIndex2=afterSlash.indexOf("@");if(atIndex2===-1){return{name:spec}}return{name:spec.slice(0,slashIndex+1+atIndex2),version:afterSlash.slice(atIndex2+1)}}const atIndex=spec.indexOf("@");if(atIndex===-1){return{name:spec}}return{name:spec.slice(0,atIndex),version:spec.slice(atIndex+1)}}async function install(packageSpec,vfs2,options){const pm=new PackageManager(vfs2);return pm.install(packageSpec,options)}var index=Object.freeze(Object.defineProperty({__proto__:null,PackageManager,Registry,install,parsePackageSpec,setInstallTransformEnabled},Symbol.toStringTag,{value:"Module"}));function __listening(port2){return listenerOnPort(port2)!==void 0}function requestHead(method,url2,headers,body){const lines=[`${method.toUpperCase()} ${url2} HTTP/1.1`];let hasLength=false;let hasEncoding=false;for(const[name,value]of Object.entries(headers)){const lower=name.toLowerCase();if(lower==="content-length")hasLength=true;if(lower==="transfer-encoding")hasEncoding=true;if(lower==="connection")continue;lines.push(`${name}: ${value}`)}if(!hasLength&&!hasEncoding)lines.push(`Content-Length: ${body?body.length:0}`);lines.push("Connection: close","","");return lines.join("\r\n")}function responseParser(collected,onHead,onChunk){const parser=new HTTPParser;parser.initialize(HTTPParser.RESPONSE,null,0,0);parser[HTTPParser.kOnHeadersComplete]=(_major,_minor,headers,_method,_url2,statusCode,statusMessage,upgrade)=>{if(collected.complete)return 0;collected.statusCode=statusCode;collected.statusMessage=statusMessage;collected.upgrade=upgrade;for(let index2=0;index2+1<headers.length;index2+=2){const name=headers[index2].toLowerCase();const value=headers[index2+1];collected.headers[name]=collected.headers[name]===void 0?value:`${collected.headers[name]}, ${value}`}onHead==null?void 0:onHead();return 0};parser[HTTPParser.kOnBody]=chunk=>{if(collected.complete)return;if(onChunk)onChunk(chunk);else collected.chunks.push(chunk)};parser[HTTPParser.kOnMessageComplete]=()=>{if(collected.complete)return collected.upgrade?0:-1;collected.complete=true;if(collected.upgrade)return 0;parser.pause();return-1};return parser}function emptyCollected(){return{statusCode:0,statusMessage:"",headers:{},chunks:[],complete:false,upgrade:false}}function ownedConcat(chunks){let total=0;for(const chunk of chunks)total+=chunk.byteLength;const joined=new Uint8Array(total);let at22=0;for(const chunk of chunks){joined.set(new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength),at22);at22+=chunk.byteLength}return joined}function serviceUnavailable(port2){return{statusCode:503,statusMessage:"Service Unavailable",headers:{"Content-Type":"text/plain"},body:ownedConcat([Buffer$9.from(`No server listening on port ${port2}`)])}}function __requestOverLoopback(port2,method,url2,headers,body){if(!__listening(port2))return Promise.resolve(serviceUnavailable(port2));return new Promise(resolve2=>{const collected=emptyCollected();const parser=responseParser(collected);let settled=false;const answer2=()=>{if(settled)return;settled=true;parser.free();resolve2({statusCode:collected.statusCode||502,statusMessage:collected.statusMessage,headers:collected.headers,body:ownedConcat(collected.chunks)})};const socket=netModule.connect({port:port2,host:"127.0.0.1"});socket.on("data",chunk=>{if(settled)return;const read=parser.execute(chunk);if(read instanceof Error){socket.destroy();answer2()}else if(collected.complete){socket.destroy();answer2()}});socket.on("end",()=>{if(!settled){parser.finish()}answer2()});socket.on("close",answer2);socket.on("error",()=>{if(settled)return;settled=true;parser.free();resolve2(serviceUnavailable(port2))});socket.write(requestHead(method,url2,headers,body));if(body&&body.length>0)socket.write(body)})}function __streamOverLoopback(port2,method,url2,headers,body,onStart,onChunk,onEnd,flow){if(!__listening(port2)){onStart(503,"Service Unavailable",{"Content-Type":"text/plain"});onEnd();return Promise.resolve()}return new Promise(resolve2=>{var _a22;const collected=emptyCollected();let started2=false;let ended2=false;const finish=()=>{if(ended2)return;ended2=true;parser.free();onEnd();resolve2()};const parser=responseParser(collected,()=>{started2=true;onStart(collected.statusCode,collected.statusMessage,collected.headers)},chunk=>onChunk(chunk));const socket=netModule.connect({port:port2,host:"127.0.0.1"});(_a22=flow==null?void 0:flow.control)==null?void 0:_a22.call(flow,()=>socket.pause(),()=>socket.resume());if(flow==null?void 0:flow.signal){if(flow.signal.aborted){socket.destroy();finish();return}flow.signal.addEventListener("abort",()=>{socket.destroy();finish()},{once:true})}socket.on("data",chunk=>{if(ended2)return;const read=parser.execute(chunk);if(read instanceof Error){socket.destroy();finish()}else if(collected.complete){socket.destroy();finish()}});socket.on("end",()=>{if(!ended2){parser.finish()}finish()});socket.on("close",finish);socket.on("error",()=>{if(!started2)onStart(503,"Service Unavailable",{"Content-Type":"text/plain"});finish()});socket.write(requestHead(method,url2,headers,body));if(body&&body.length>0)socket.write(body)})}function __upgradeOverLoopback(port2,method,url2,headers){if(!__listening(port2)){return Promise.resolve({statusCode:503,statusMessage:"Service Unavailable",headers:{},socket:null})}return new Promise(resolve2=>{const collected=emptyCollected();let settled=false;const parser=responseParser(collected);const socket=netModule.connect({port:port2,host:"127.0.0.1"});const fail3=()=>{if(settled)return;settled=true;parser.free();resolve2({statusCode:collected.statusCode||502,statusMessage:collected.statusMessage,headers:collected.headers,socket:null})};socket.on("data",chunk=>{if(settled)return;const read=parser.execute(chunk);if(read instanceof Error){socket.destroy();fail3();return}if(collected.upgrade||collected.statusCode===101){settled=true;parser.free();const consumed=typeof read==="number"?read:chunk.length;const rest=chunk.subarray(consumed);if(rest.length>0)socket.unshift(rest);resolve2({statusCode:collected.statusCode,statusMessage:collected.statusMessage,headers:collected.headers,socket});return}if(collected.complete){socket.destroy();fail3()}});socket.on("error",fail3);socket.on("close",fail3);const upgradeHeaders={...headers,Connection:"Upgrade"};const lines=[`${method.toUpperCase()} ${url2} HTTP/1.1`];for(const[name,value]of Object.entries(upgradeHeaders)){if(name.toLowerCase()==="connection")continue;lines.push(`${name}: ${value}`)}lines.push("Connection: Upgrade","","");socket.write(lines.join("\r\n"))})}var _encoder2=new TextEncoder;function guestListeningServer(port2,address){const hostname2=address;return{listening:true,address:()=>({port:port2,address:hostname2,family:hostname2.includes(":")?"IPv6":"IPv4"}),handleRequest:(method,url2,headers,body)=>__requestOverLoopback(port2,method,url2,headers,typeof body==="string"?Buffer$9.from(body):body)}}var __substrateUpgradeSockets=new Map;function __substrateFrame(opcode,payload,masked){const length=payload.length;const header=[128|opcode];if(length<126)header.push(128|length);else if(length<65536)header.push(128|126,length>>8,length&255);else header.push(128|127,0,0,0,0,length>>>24&255,length>>>16&255,length>>>8&255,length&255);const mask=[Math.random()*256|0,Math.random()*256|0,Math.random()*256|0,Math.random()*256|0];const out=new Uint8Array(header.length+mask.length+length);out.set(header,0);out.set(mask,header.length);for(let index2=0;index2<length;index2+=1)out[header.length+mask.length+index2]=payload[index2]^mask[index2&3];return out}function __substrateParseFrames(state,chunk,onFrame){const joined=state.pending.length?new Uint8Array([...state.pending,...chunk]):chunk;let offset2=0;for(;;){if(joined.length-offset2<2)break;const b02=joined[offset2],b12=joined[offset2+1];const fin=(b02&128)!==0,opcode=b02&15,masked=(b12&128)!==0;let length=b12&127,at22=offset2+2;if(length===126){if(joined.length-at22<2)break;length=joined[at22]<<8|joined[at22+1];at22+=2}else if(length===127){if(joined.length-at22<8)break;length=0;for(let index2=0;index2<8;index2+=1)length=length*256+joined[at22+index2];at22+=8}let mask;if(masked){if(joined.length-at22<4)break;mask=joined.subarray(at22,at22+4);at22+=4}if(joined.length-at22<length)break;const payload=joined.slice(at22,at22+length);if(mask)for(let index2=0;index2<length;index2+=1)payload[index2]^=mask[index2&3];offset2=at22+length;if(opcode===0&&state.fragments){state.fragments.parts.push(payload);if(fin){const parts=state.fragments.parts;const total=parts.reduce((sum,part)=>sum+part.length,0);const whole=new Uint8Array(total);let cursor=0;for(const part of parts){whole.set(part,cursor);cursor+=part.length}const op2=state.fragments.opcode;state.fragments=null;onFrame(op2,whole)}}else if(!fin&&(opcode===1||opcode===2))state.fragments={opcode,parts:[payload]};else onFrame(opcode,payload)}state.pending=joined.slice(offset2)}function __substrateUpgradeSocket(entry,socket){const end=socket;const bridge={push:frame=>{socket.write(frame)},destroy:()=>{socket.destroy()},get destroyed(){return socket.destroyed},onData:listener=>{socket.on("data",listener)}};let closed=false;const state={pending:new Uint8Array(0),fragments:null};const decoder22=new TextDecoder;const finish=(code22,reason)=>{if(closed)return;closed=true;__substrateUpgradeSockets.delete(entry.clientId);entry.channel.postMessage({type:"close",targetClient:entry.clientId,code:code22,reason})};const receive2=frame=>{if(!bridge.destroyed)bridge.push(frame)};bridge.onData(chunk=>{const bytes2=chunk;__substrateParseFrames(state,bytes2,(opcode,payload)=>{if(opcode===1)entry.channel.postMessage({type:"message",targetClient:entry.clientId,payload:decoder22.decode(payload)});else if(opcode===2)entry.channel.postMessage({type:"message",targetClient:entry.clientId,payload:payload.buffer.slice(payload.byteOffset,payload.byteOffset+payload.byteLength)});else if(opcode===8){const code22=payload.length>=2?payload[0]<<8|payload[1]:1005;finish(code22===1005?1e3:code22,payload.length>2?decoder22.decode(payload.subarray(2)):"");end.destroy()}else if(opcode===9)receive2(__substrateFrame(10,payload))})});end.on("close",()=>{finish(1e3,"");bridge.destroy()});end.deliver=payload=>{if(closed||end.destroyed)return;const bytes2=typeof payload==="string"?_encoder2.encode(payload):new Uint8Array(payload);receive2(__substrateFrame(typeof payload==="string"?1:2,bytes2))};end.disconnect=(code22,reason)=>{if(closed||end.destroyed)return;const text=_encoder2.encode(reason||"");const payload=new Uint8Array(2+text.length);payload[0]=code22>>8;payload[1]=code22&255;payload.set(text,2);receive2(__substrateFrame(8,payload));setTimeout(()=>{finish(code22,reason||"");end.destroy()},50)};return end}function __substrateRawUpgradeSocket(entry,socket){const end=socket;const bridge={push:data2=>{socket.write(data2)},destroy:()=>{socket.destroy()},end:()=>{socket.end()},get destroyed(){return socket.destroyed},onData:listener=>{socket.on("data",listener)}};let closed=false;const finish=(code22,reason)=>{if(closed)return;closed=true;__substrateUpgradeSockets.delete(entry.clientId);entry.channel.postMessage({type:"close",targetClient:entry.clientId,code:code22,reason})};bridge.onData(chunk=>{if(closed)return;entry.channel.postMessage({type:"message",targetClient:entry.clientId,payload:chunk.buffer.slice(chunk.byteOffset,chunk.byteOffset+chunk.byteLength)})});end.on("close",()=>{finish(1e3,"");bridge.destroy()});end.deliver=payload=>{if(closed||end.destroyed||bridge.destroyed)return;bridge.push(typeof payload==="string"?_encoder2.encode(payload):new Uint8Array(payload))};end.disconnect=(code22,reason)=>{if(closed||end.destroyed)return;bridge.end();finish(code22,reason||"");end.destroy()};return end}function __substrateListenForUpgrades(bridge){var _a22;if(typeof BroadcastChannel==="undefined")return null;const channel=new BroadcastChannel("vite-ws-channel");(_a22=channel.unref)==null?void 0:_a22.call(channel);channel.addEventListener("message",event=>{const data2=event.data;if(!data2||typeof data2!=="object")return;if(data2.type==="connect"){let url2;try{url2=new URL(data2.url)}catch{return}const port2=Number(url2.port);if(!__listening(port2))return;const record={clientId:data2.clientId,channel};const raw=data2.framing==="none";const key=uint8ToBase64(crypto.getRandomValues(new Uint8Array(16)));const protocols=Array.isArray(data2.protocols)?data2.protocols:[];void __upgradeOverLoopback(port2,"GET",url2.pathname+url2.search,{Host:typeof data2.host==="string"&&/^(?:\[[0-9a-f:.]+\]|[a-z0-9.-]+)(?::[0-9]{1,5})?$/iu.test(data2.host)?data2.host:url2.host,Upgrade:"websocket","Sec-WebSocket-Version":"13","Sec-WebSocket-Key":key,...protocols.length?{"Sec-WebSocket-Protocol":protocols.join(", ")}:{},...typeof data2.origin==="string"&&/^https?:\/\/[^/]+$/u.test(data2.origin)?{Origin:data2.origin}:{}}).then(result=>{if(result.statusCode!==101||!result.socket){channel.postMessage({type:"close",targetClient:data2.clientId,code:1006,reason:"upgrade refused"});return}const socket=raw?__substrateRawUpgradeSocket(record,result.socket):__substrateUpgradeSocket(record,result.socket);__substrateUpgradeSockets.set(data2.clientId,socket);channel.postMessage({type:"connected",targetClient:data2.clientId,protocol:result.headers["sec-websocket-protocol"]??(raw?protocols[0]??"":"")})})}else if(data2.type==="message"){const socket=__substrateUpgradeSockets.get(data2.clientId);if(socket)socket.deliver(data2.payload)}else if(data2.type==="disconnect"){const socket=__substrateUpgradeSockets.get(data2.clientId);if(socket)socket.disconnect(typeof data2.code==="number"?data2.code:1e3,typeof data2.reason==="string"?data2.reason:"")}});return channel}var ServerBridge=class extends PortBridge{constructor(options={}){super(options);__publicField2(this,"upgradeChannel",null);__publicField2(this,"guestServers",new WeakSet);this.watchGuestPorts();this.upgradeChannel=__substrateListenForUpgrades()}watchGuestPorts(){setPortWatchers((port2,address)=>{if(this.servers.has(port2))return;const hostname2=address||"0.0.0.0";const server=guestListeningServer(port2,hostname2);this.guestServers.add(server);this.registerServer(server,port2,hostname2)},port2=>{const entry=this.servers.get(port2);if(entry&&(entry.server===null||this.guestServers.has(entry.server))){if(entry.server)entry.server.listening=false;this.unregisterServer(port2)}})}close(){if(this.upgradeChannel){try{this.upgradeChannel.close()}catch{}this.upgradeChannel=null}super.close()}isGuest(entry){return entry.server===null||this.guestServers.has(entry.server)}requestGuest(port2,method,url2,headers,body){return __requestOverLoopback(port2,method,url2,headers,body)}streamGuest(port2,method,url2,headers,body,onStart,onChunk,onEnd,flow){return __streamOverLoopback(port2,method,url2,headers,body,onStart,onChunk,onEnd,flow)}bodyOf(bytes2){return Buffer$9.from(bytes2)}};var globalBridge=null;function getServerBridge(options){if(!globalBridge){globalBridge=new ServerBridge(options)}return globalBridge}function resetServerBridge(){globalBridge=null}var scopes=new WeakMap;var liveScopes=new Set;var NativeStreamScope=class{constructor(limits,emit2,ownerPid){__publicField2(this,"entries",new Map);__publicField2(this,"descriptors",new Map);__publicField2(this,"writes",new Map);__publicField2(this,"connects",new Map);__publicField2(this,"nextId",1);__publicField2(this,"pendingWriteBytes",0);__publicField2(this,"disposed",false);__publicField2(this,"limits");this.emit=emit2;this.ownerPid=ownerPid;if([limits.maxHandles,limits.maxReadChunkBytes,limits.maxQueuedBytes,limits.maxQueuedHandles,limits.maxPendingWriteBytes].some(value=>!Number.isSafeInteger(value)||value<1)||limits.maxReadChunkBytes>2147483647||limits.maxReadChunkBytes>limits.maxQueuedBytes||limits.maxReadChunkBytes>limits.maxPendingWriteBytes)throw new Error("Invalid native stream resource limits.");this.limits=Object.freeze({...limits});liveScopes.add(this)}handles(){var _a22;if(this.disposed)return[];const pid=(_a22=this.ownerPid)==null?void 0:_a22.call(this);return[...this.entries.values()].map(({handle,descriptor})=>({...pid!==void 0?{pid}:{},id:descriptor.id,kind:descriptor.kind,listening:!!handle.listening}))}entry(id2){return this.disposed?void 0:this.entries.get(id2)}publish(event){if(this.disposed)return;try{this.emit(event)}catch(cause){try{this.dispose()}catch(cleanup){throw new AggregateError([cause,cleanup],"Native stream event delivery and cleanup failed.")}throw cause}}claim(handle){if(this.disposed||!Number.isSafeInteger(this.nextId)||this.entries.size>=this.limits.maxHandles||scopes.has(handle))return void 0;const descriptor={id:this.nextId++,kind:handle instanceof TCP?"tcp":"pipe",type:handle.type};const entry={handle,descriptor};this.entries.set(descriptor.id,entry);scopes.set(handle,this);__adoptHandle(handle,null);handle.onconnection=(status,accepted)=>{const incoming2=status===0?this.claim(accepted):void 0;if(status===0&&!incoming2)accepted.close();this.publish({type:"connection",id:descriptor.id,status:status||(incoming2?0:UV_EMFILE),...incoming2?{handle:incoming2}:{}})};handle.onread=buffer2=>{const count=streamBaseState[kReadBytesOrError];const offset2=streamBaseState[kArrayBufferOffset];handle.readStop();const sent=handle.pendingHandle;handle.pendingHandle=null;let incoming2;if(sent!=null){if((sent instanceof TCP||sent instanceof Pipe)&&!sent.listening)incoming2=this.claim(sent);if(!incoming2){if(sent instanceof LibuvStreamWrap&&!scopes.has(sent)&&!sent.listening)sent.close();this.publish({type:"read",id:descriptor.id,status:UV_ENOTSUP});this.close(descriptor.id);return}}const bytes2=count>0?(buffer2?new Uint8Array(buffer2,offset2,count):entry.buffer.subarray(0,count)).slice():void 0;this.publish({type:"read",id:descriptor.id,status:count,...bytes2?{bytes:bytes2}:{},...incoming2?{handle:incoming2}:{}})};return{...descriptor}}call(operation){var _a22,_b22;if(this.disposed)return{status:UV_EBADF};if(operation.operation==="fdType"){if(!Number.isInteger(operation.fd)||operation.fd<0)return{status:UV_EINVAL};const id2=this.descriptors.get(operation.fd);const entry2=id2===void 0?void 0:this.entry(id2);return entry2?{status:0,handleType:entry2.descriptor.kind==="tcp"?"TCP":"PIPE"}:{status:UV_EBADF}}if(operation.operation==="create"){if(this.entries.size>=this.limits.maxHandles)return{status:UV_EMFILE};if(operation.kind!=="tcp"&&operation.kind!=="pipe"||!Number.isInteger(operation.type)||operation.type<0||operation.type>(operation.kind==="pipe"?2:1))return{status:UV_EINVAL};const handle2=operation.kind==="tcp"?new TCP(operation.type):new Pipe(operation.type);const descriptor=this.claim(handle2);if(!descriptor){handle2.close();return{status:UV_EMFILE}}return{status:0,handle:descriptor}}const entry=this.entry(operation.id);if(!entry)return{status:UV_EBADF};const handle=entry.handle;switch(operation.operation){case"duplicate":{if(handle.listening)return{status:UV_ENOTSUP};if(this.entries.size>=this.limits.maxHandles)return{status:UV_EMFILE};const copy2=handle.duplicate();const descriptor=this.claim(copy2);if(!descriptor){copy2.close();return{status:UV_EMFILE}}return{status:0,handle:descriptor}}case"pair":{const other=(_a22=this.entry(operation.peer))==null?void 0:_a22.handle;if(!other||handle.peer||other.peer||handle.listening||other.listening||other===handle)return{status:UV_EINVAL};LibuvStreamWrap.pair(handle,other);return{status:0}}case"bind":{if(typeof operation.address!=="string")return{status:UV_EINVAL};if(handle instanceof Pipe)return{status:handle.bind(operation.address)};if(!Number.isInteger(operation.port)||operation.port<0||operation.port>65535)return{status:UV_EINVAL};return{status:operation.ipv6?handle.bind6(operation.address,operation.port,operation.flags):handle.bind(operation.address,operation.port,operation.flags)}}case"listen":return{status:Number.isInteger(operation.backlog)&&operation.backlog>=0?handle.listen(operation.backlog):UV_EINVAL};case"connect":{if(this.connects.has(operation.id))return{status:UV_EALREADY};if(typeof operation.address!=="string"||!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};if(handle instanceof TCP&&(!Number.isInteger(operation.port)||operation.port<1||operation.port>65535))return{status:UV_EINVAL};this.connects.set(operation.id,operation.request);const request=handle instanceof TCP?new TCPConnectWrap:new PipeConnectWrap;request.oncomplete=status2=>{if(this.connects.get(operation.id)!==operation.request)return;this.connects.delete(operation.id);this.publish({type:"connect",id:operation.id,request:operation.request,status:status2})};const status=handle instanceof TCP?operation.ipv6?handle.connect6(request,operation.address,operation.port):handle.connect(request,operation.address,operation.port):handle.connect(request,operation.address);if(status!==0)this.connects.delete(operation.id);return{status}}case"open":{const inherited=this.descriptors.get(operation.fd);const held=inherited===void 0?void 0:this.entry(inherited);if(!held||held.descriptor.kind!==entry.descriptor.kind||handle.peer||handle.listening)return{status:UV_EBADF};if(held!==entry){if(handle instanceof TCP&&held.handle instanceof TCP){const local2={},remote={};if(held.handle.getsockname(local2)===0&&held.handle.getpeername(remote)===0)handle.adoptNames(local2,remote)}handle.takeOverFrom(held.handle);this.entries.delete(inherited);scopes.delete(held.handle);held.handle.close();this.descriptors.set(operation.fd,operation.id)}return{status:0}}case"readStart":entry.buffer??(entry.buffer=new Uint8Array(this.limits.maxReadChunkBytes));handle.useUserBuffer(entry.buffer);return{status:handle.readStart()};case"readStop":return{status:handle.readStop()};case"ref":handle.ref();return{status:0};case"unref":handle.unref();return{status:0};case"getsockname":case"getpeername":{if(!(handle instanceof TCP))return{status:UV_ENOTSUP};const address={};const status=handle[operation.operation](address);return{status,...status===0?{address}:{}}}case"shutdown":{if(!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};if(this.writes.has(operation.id))return{status:UV_EBUSY};const request=new ShutdownWrap;request.oncomplete=status=>this.publish({type:"shutdown",id:operation.id,request:operation.request,status});return{status:handle.shutdown(request)}}case"reset":if(!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};if(!(handle instanceof TCP))return{status:UV_ENOTSUP};(_b22=this.writes.get(operation.id))==null?void 0:_b22(UV_ECANCELED);return this.close(operation.id,operation.request,true);case"close":if(!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};return this.close(operation.id,operation.request)}}write(id2,bytes2,sentId){var _a22,_b22;const handle=(_a22=this.entry(id2))==null?void 0:_a22.handle;if(!handle)return Promise.resolve(UV_EBADF);if(this.writes.has(id2))return Promise.resolve(UV_EBUSY);if(bytes2.byteLength>this.limits.maxReadChunkBytes||this.pendingWriteBytes+bytes2.byteLength>this.limits.maxPendingWriteBytes)return Promise.resolve(UV_ENOBUFS);const sent=sentId===void 0?void 0:(_b22=this.entry(sentId))==null?void 0:_b22.handle;if(sentId!==void 0&&!sent)return Promise.resolve(UV_EBADF);if(sent&&(!(handle instanceof Pipe)||sent.listening||bytes2.byteLength===0))return Promise.resolve(UV_ENOTSUP);const owned2=new Uint8Array(bytes2.byteLength);owned2.set(bytes2);const retained=sent==null?void 0:sent.duplicate();if(retained)__adoptHandle(retained,null);this.pendingWriteBytes+=owned2.byteLength;return new Promise((resolve2,reject)=>{let ended2=false;let unsubscribe=()=>{};const finish=(status,failure)=>{if(ended2)return;ended2=true;unsubscribe();this.writes.delete(id2);this.pendingWriteBytes-=owned2.byteLength;try{retained==null?void 0:retained.close()}catch(cause){reject(cause);return}if(failure!==void 0)reject(failure);else resolve2(status)};const attempt=()=>{if(ended2)return;if(handle.closed||this.disposed){finish(UV_ECANCELED);return}if(!handle.peer){finish(UV_EPIPE);return}if(handle.peerQueuedBytes+owned2.byteLength>this.limits.maxQueuedBytes)return;if(retained&&handle.peerQueuedHandles>=this.limits.maxQueuedHandles)return;try{finish(handle.writeBuffer(new WriteWrap,owned2,retained))}catch(cause){finish(UV_ECANCELED,cause)}};this.writes.set(id2,finish);unsubscribe=handle.onPeerReadCapacity(attempt);attempt()})}inherit(fd2,source,id2){var _a22;if(this.disposed||!Number.isInteger(fd2)||fd2<0||this.descriptors.has(fd2))return{status:UV_EINVAL};if(this.entries.size>=this.limits.maxHandles)return{status:UV_EMFILE};const handle=(_a22=source.entry(id2))==null?void 0:_a22.handle;if(!handle)return{status:UV_EBADF};if(handle.listening)return{status:UV_ENOTSUP};const copy2=handle.duplicate();const descriptor=this.claim(copy2);if(!descriptor){copy2.close();return{status:UV_EMFILE}}this.descriptors.set(fd2,descriptor.id);return{status:0,handle:descriptor}}close(id2,request,reset2=false){var _a22;const entry=this.entries.get(id2);if(!entry)return{status:UV_EBADF};(_a22=this.writes.get(id2))==null?void 0:_a22(UV_ECANCELED);const connecting=this.connects.get(id2);this.connects.delete(id2);if(connecting!==void 0)this.publish({type:"connect",id:id2,request:connecting,status:UV_ECANCELED});this.entries.delete(id2);scopes.delete(entry.handle);for(const[fd2,held]of this.descriptors)if(held===id2)this.descriptors.delete(fd2);const complete=request===void 0?void 0:()=>this.publish({type:"close",id:id2,request,status:0});if(reset2)entry.handle.reset(complete);else entry.handle.close(complete);return{status:0}}dispose(){if(this.disposed)return;this.disposed=true;liveScopes.delete(this);const failures=[];for(const id2 of[...this.entries.keys()]){try{this.close(id2)}catch(cause){failures.push(cause)}}if(failures.length)throw new AggregateError(failures,"Native stream scope cleanup failed.")}};function nativeStreamOwnerPid(handle){var _a22,_b22;return(_b22=(_a22=scopes.get(handle))==null?void 0:_a22.ownerPid)==null?void 0:_b22.call(_a22)}function nativeStreamHandles(){return[...liveScopes].flatMap(scope4=>scope4.handles())}var __nextRunName=1;function createContainer(options){const vfs2=options&&options.vfs||new VirtualFS;const runtime=new Runtime(vfs2,options);const npmManager=new PackageManager(vfs2);const serverBridge=new ServerBridge({baseUrl:options==null?void 0:options.baseUrl,onServerReady:options==null?void 0:options.onServerReady});return{vfs:vfs2,runtime,npm:npmManager,serverBridge,execute:(code22,filename)=>runtime.execute(code22,filename),runFile:filename=>runtime.runFile(filename),run:(command,runOptions)=>{var _a22;if((_a22=runOptions==null?void 0:runOptions.signal)==null?void 0:_a22.aborted){return Promise.resolve({stdout:"",stderr:"",exitCode:130})}const processToken=typeof(runOptions==null?void 0:runOptions.processToken)==="string"&&runOptions.processToken.length>0?runOptions.processToken:`run-${__nextRunName++}`;registerRunStreams(processToken,{onStdout:runOptions==null?void 0:runOptions.onStdout,onStderr:runOptions==null?void 0:runOptions.onStderr,signal:runOptions==null?void 0:runOptions.signal,held:(runOptions==null?void 0:runOptions.held)===true,stdinStream:runOptions==null?void 0:runOptions.stdinStream,stdinOpen:(runOptions==null?void 0:runOptions.stdinStream)!==void 0,terminal:runOptions==null?void 0:runOptions.terminal});return new Promise(resolve2=>{runCommand(command,{cwd:runOptions==null?void 0:runOptions.cwd,env:runOptions==null?void 0:runOptions.env,stdin:typeof(runOptions==null?void 0:runOptions.stdin)==="string"?runOptions.stdin:void 0,processToken,vfs:vfs2},(error,stdout,stderr)=>{var _a32;releaseRunStreams(processToken);const terminatedBy=__takeTermination(processToken);resolve2({stdout:String(stdout),stderr:String(stderr),exitCode:((_a32=runOptions==null?void 0:runOptions.signal)==null?void 0:_a32.aborted)?143:error?error.code??1:0,...terminatedBy?{signal:terminatedBy}:{}})})})},pendingTimers:token=>{var _a22;return((_a22=__runFor(token))==null?void 0:_a22.pendingTimers())??0},processPorts:token=>__ownedServerPorts(token),portPid:port2=>{var _a22;const listener=listenerOnPort(port2);if(!listener)return void 0;return((_a22=runPid(ownerOf(listener)))==null?void 0:_a22.pid)??nativeStreamOwnerPid(listener)},streamHandles:()=>nativeStreamHandles(),signalProcess:(token,signal)=>__signalOwnedProcess(token,signal),stopProcess:token=>{const known=__runFor(token)!==void 0||__ownedServerPorts(token).length>0;__releaseOwnedServers(token,false);__releaseOwnedHandles(token);__stopOwnedProcess(token);return known},sendInput:(data2,token)=>sendStdin(data2,token),currentProcessToken:()=>__currentProcessToken(),runPid:token=>runPid(token===void 0?__currentProcessToken():token),processByPid,listenNet:(port2,onConnection)=>{const server=new Server(onConnection);server.listen(port2);__adoptHandle(server._handle,null);return()=>{server.close()}},createREPL:()=>runtime.createREPL(),on:(event,listener)=>{serverBridge.on(event,listener)}}}if(!Object.getOwnPropertyDescriptor(globalThis,"Buffer")){Object.defineProperty(globalThis,"Buffer",{configurable:true,enumerable:false,get:()=>bufferModule.Buffer})}function normalizeProcessFilesystemPolicy(value){if(!value||typeof value!=="object"||Object.keys(value).some(key=>key!=="writableRoots")||!Array.isArray(value.writableRoots)||value.writableRoots.length>128){throw new TypeError("Invalid process filesystem policy: expected up to 128 writableRoots.")}const roots=[...new Set(Array.from(value.writableRoots,absolutePolicyPath))].sort();return Object.freeze({writableRoots:Object.freeze(roots.filter(root2=>!roots.some(other=>other!==root2&&within(root2,other))))})}function intersectProcessFilesystemPolicies(parent2,child){const inherited=normalizeProcessFilesystemPolicy(parent2);if(child===void 0)return inherited;const requested=normalizeProcessFilesystemPolicy(child);return normalizeProcessFilesystemPolicy({writableRoots:inherited.writableRoots.flatMap(left=>requested.writableRoots.flatMap(right=>within(left,right)?[left]:within(right,left)?[right]:[]))})}function createProcessFilesystemMutationGuard(filesystem,requested){const policy=normalizeProcessFilesystemPolicy(requested);const permitted=path3=>policy.writableRoots.some(root2=>within(path3,root2));return input=>{const path3=absolutePolicyPath(input);if(!permitted(path3))deny(path3);let current3="";for(const part of path3.split("/").filter(Boolean)){current3+=`/${part}`;try{if(filesystem.lstatSync(current3).isSymbolicLink())deny(path3)}catch(error){if(error.code!=="ENOENT")throw error;if(!permitted(current3))deny(current3)}}return path3}}function absolutePolicyPath(path3){if(typeof path3!=="string"||!path3.startsWith("/")||path3.includes("\0")||path3.length>8192){throw new TypeError("Filesystem policy paths must be absolute paths without NUL bytes.")}const parts=[];for(const part of path3.split("/")){if(part==="..")parts.pop();else if(part&&part!==".")parts.push(part)}return`/${parts.join("/")}`}function within(path3,root2){return root2==="/"||path3===root2||path3.startsWith(`${root2}/`)}function deny(path3){throw Object.assign(new Error(`EACCES: process filesystem policy denies mutation of '${path3}'`),{code:"EACCES",path:path3})}async function forwardBrowserProcessInput(input,receive2,signal){signal.throwIfAborted();const iterator=input[Symbol.asyncIterator]();let finished=false;let rejectCancellation;const cancellation=new Promise((_resolve,reject)=>{rejectCancellation=reject});void cancellation.catch(()=>void 0);const abort=()=>rejectCancellation(signal.reason??new DOMException("Process input was cancelled.","AbortError"));signal.addEventListener("abort",abort,{once:true});try{for(;;){signal.throwIfAborted();const next2=await Promise.race([iterator.next(),cancellation]);signal.throwIfAborted();if(next2.done){finished=true;return}await Promise.race([Promise.resolve(receive2(next2.value)),cancellation])}}finally{signal.removeEventListener("abort",abort);if(!finished)void Promise.resolve().then(()=>iterator.return?.()).catch(()=>void 0)}}var BrowserProcessInputPipe=class{queued;ended=false;reading=false;failure;wake;write(bytes2){if(this.ended)return Promise.reject(this.failure??new Error("Process input is closed."));if(this.queued)return Promise.reject(new Error("Wait for the previous process input chunk to be consumed."));const consumed=new Promise((resolve2,reject)=>{this.queued={bytes:Uint8Array.from(bytes2),resolve:resolve2,reject}});this.notify();return consumed}end(){this.ended=true;this.notify()}cancel(cause=new DOMException("Process input was cancelled.","AbortError")){this.failure=cause;this.ended=true;this.queued?.reject(cause);this.queued=void 0;this.notify()}notify(){const wake=this.wake;this.wake=void 0;wake?.()}async*[Symbol.asyncIterator](){if(this.reading)throw new Error("Process input already has a reader.");this.reading=true;try{for(;;){if(this.failure!==void 0)throw this.failure;const next2=this.queued;if(next2){this.queued=void 0;next2.resolve();yield next2.bytes}else if(this.ended)return;else await new Promise(resolve2=>{this.wake=resolve2})}}finally{this.cancel()}}};function parseCommandWords(command){const words=[];let word="";let quote2="";let escaped=false;for(const character of command.trim()){if(escaped){word+=character;escaped=false;continue}if(character==="\\"&"e2!=="'"){escaped=true;continue}if(quote2){if(character===quote2)quote2="";else word+=character;continue}if(character==="'"||character==='"'){quote2=character;continue}if(/\s/u.test(character)){if(word){words.push(word);word=""}continue}if(/[|&;<>]/u.test(character))throw new Error("Shell operators require the shell runtime.");word+=character}if(escaped||quote2)throw new Error("Unterminated command quoting.");if(word)words.push(word);return words}function renderCommand(argv){return argv.map(value=>/^[A-Za-z0-9_./:@%+=,-]+$/u.test(value)?value:`'${value.replaceAll("'",`'\\''`)}'`).join(" ")}var PageNetSocketImpl=class{constructor(id2,post,onClosed){this.id=id2;this.post=post;this.onClosed=onClosed}id;post;onClosed;listeners=new Map;ended=false;outstanding=0;drainWaiters=[];on(event,listener){const list2=this.listeners.get(event)??[];list2.push(listener);this.listeners.set(event,list2);return this}write(chunk,done){if(this.ended)return false;const buffer2=Uint8Array.from(chunk).buffer;this.outstanding+=1;this.post({type:"net-data",socket:this.id,chunk:buffer2},[buffer2]);done?.();return true}taken(){this.outstanding=Math.max(0,this.outstanding-1);for(const waiter of[...this.drainWaiters]){if(this.outstanding>=waiter.below)continue;this.drainWaiters.splice(this.drainWaiters.indexOf(waiter),1);waiter.resume()}}drained(below){if(this.ended||this.outstanding<below)return Promise.resolve();return new Promise(resume=>this.drainWaiters.push({below,resume}))}end(){if(!this.ended){this.post({type:"net-end",socket:this.id});this.finish()}return this}destroy(){return this.end()}receive(chunk){if(this.ended)return;for(const listener of this.listeners.get("data")??[])listener(chunk)}finish(){if(this.ended)return;this.ended=true;this.onClosed();for(const waiter of this.drainWaiters.splice(0))waiter.resume();const listeners=[...this.listeners.get("end")??[],...this.listeners.get("close")??[]];this.listeners.clear();for(const listener of listeners)listener(void 0)}};var STATE=0;var STATUS=1;var PID=2;var PPID=3;var PGID=4;var IDLE=0;var REQUEST=1;var WRITING=2;var DONE3=3;var CLOSED=4;var TIMEOUT_MS=3e4;var STREAM_REPLY_BYTES=4096;function serveNodeProcessRegistry(limits,ownerPid){if(limits)limits=Object.freeze({...limits});const streams2=limits?new NativeStreamScope(limits,event=>{const transfer2=event.type==="read"&&event.bytes?[event.bytes.buffer]:[];port1.postMessage({operation:"stream-event",event},transfer2)},ownerPid):void 0;const registry=createProcessRegistryScope();const{port1,port2}=new MessageChannel;const shared=new SharedArrayBuffer(5*Int32Array.BYTES_PER_ELEMENT);const control=new Int32Array(shared);const reply=limits?new SharedArrayBuffer(STREAM_REPLY_BYTES):void 0;const encoder11=new TextEncoder;let disposed=false;const dispose=()=>{if(disposed)return;disposed=true;Atomics.store(control,STATE,CLOSED);Atomics.notify(control,STATE);try{port1.postMessage({operation:"closed"})}finally{try{streams2?.dispose()}finally{registry.dispose();port1.onmessage=null;port1.onmessageerror=null;port1.close();port2.close()}}};port1.onmessage=({data:data2})=>{if(disposed)return;if(!data2||typeof data2!=="object"){dispose();return}if(data2.operation==="close"){dispose();return}if(data2.operation==="stream-write"){if(!streams2||!limits||!Number.isSafeInteger(data2.request)||data2.request<1||!Number.isSafeInteger(data2.id)||data2.id<1||data2.handle!==void 0&&(!Number.isSafeInteger(data2.handle)||data2.handle<1)||!(data2.bytes instanceof Uint8Array)||data2.bytes.byteLength>limits.maxReadChunkBytes){dispose();return}try{void streams2.write(data2.id,data2.bytes,data2.handle).then(status2=>{if(!disposed)port1.postMessage({operation:"stream-written",request:data2.request,status:status2})}).catch(()=>dispose())}catch{dispose()}return}if(data2.operation==="stream-post"){const call=data2.call;const closing=call?.operation==="close"||call?.operation==="reset"||call?.operation==="shutdown";if(!streams2||call?.operation!=="readStart"&&!closing||!Number.isSafeInteger(call.id)||call.id<1||closing&&(!Number.isSafeInteger(call.request)||call.request<1)){dispose();return}try{const{status:status2}=streams2.call(call);if(status2!==0){port1.postMessage({operation:"stream-event",event:closing?{type:call.operation==="shutdown"?"shutdown":"close",id:call.id,request:call.request,status:status2}:{type:"read",id:call.id,status:status2}})}}catch{dispose()}return}if(Atomics.compareExchange(control,STATE,REQUEST,WRITING)!==REQUEST)return;let identity;let replyLength=0;let status=0;try{switch(data2.operation){case"allocate":identity={pid:registry.allocate(),ppid:0};break;case"publish":if(typeof data2.token!=="string")throw new Error("Invalid process token.");registry.publish(data2.token,{pid:data2.pid,ppid:data2.ppid,...data2.pgid!==void 0?{pgid:data2.pgid}:{},...data2.argv!==void 0?{argv:data2.argv}:{},...data2.cwd!==void 0?{cwd:data2.cwd}:{},...data2.startedAt!==void 0?{startedAt:data2.startedAt}:{}});break;case"forget":if(typeof data2.token!=="string")throw new Error("Invalid process token.");registry.forget(data2.token);break;case"lookup":identity=registry.lookup(data2.pid);break;case"signal":if(!Number.isSafeInteger(data2.pid)||typeof data2.signal!=="string"||!/^SIG[A-Z0-9]{1,12}$/u.test(data2.signal)){throw new Error("Invalid process signal.")}identity=registry.signal(data2.pid,data2.signal)?{pid:data2.pid,ppid:0}:void 0;break;case"lookup-group":case"signal-group":if(!Number.isSafeInteger(data2.pgid)||data2.pgid<1||data2.pgid>2147483647||data2.operation==="signal-group"&&(typeof data2.signal!=="string"||!/^SIG[A-Z0-9]{1,12}$/u.test(data2.signal))){throw new Error("Invalid process group operation.")}identity=(data2.operation==="lookup-group"?registry.lookupGroup?.(data2.pgid):registry.signalGroup?.(data2.pgid,data2.signal))?{pid:data2.pgid,ppid:0}:void 0;break;case"stream-call":{if(!streams2||!reply)throw new Error("Native stream transport was not granted.");const result=streams2.call(data2.call);const bytes2=encoder11.encode(JSON.stringify(result));if(bytes2.byteLength>reply.byteLength)throw new Error("Native stream reply exceeds its bound.");new Uint8Array(reply).set(bytes2);replyLength=bytes2.byteLength;break}default:throw new Error("Unknown process registry operation.")}}catch{if(data2.operation==="stream-call"){dispose();return}status=1}Atomics.store(control,STATUS,status);Atomics.store(control,PID,data2.operation==="stream-call"?replyLength:identity?.pid??0);Atomics.store(control,PPID,identity?.ppid??0);Atomics.store(control,PGID,identity?.pgid??0);if(Atomics.compareExchange(control,STATE,WRITING,DONE3)===WRITING)Atomics.notify(control,STATE);else dispose()};port1.onmessageerror=dispose;port1.start();return{registry,channel:{port:port2,control:shared,...registry.lookupGroup&®istry.signalGroup?{groups:true}:{},...reply&&limits?{streams:{reply,limits}}:{}},...streams2?{streams:streams2}:{},dispose}}function exchange(channel,request,read){const control=new Int32Array(channel.control);if(Atomics.compareExchange(control,STATE,IDLE,REQUEST)!==IDLE)throw new Error("Process owner channel is unavailable.");let result;let status;try{channel.port.postMessage(request);const deadline=performance.now()+TIMEOUT_MS;for(;;){const state=Atomics.load(control,STATE);if(state===DONE3)break;if(state===CLOSED)throw new Error("Process owner stopped.");const remaining=deadline-performance.now();if(remaining<=0)throw new Error("Process owner did not answer within 30 seconds.");Atomics.wait(control,STATE,state,remaining)}status=Atomics.load(control,STATUS);result=read(control);if(Atomics.compareExchange(control,STATE,DONE3,IDLE)!==DONE3)throw new Error("Process owner stopped.")}catch(cause){Atomics.store(control,STATE,CLOSED);try{channel.port.postMessage({operation:"close"})}finally{channel.port.close()}throw cause}if(status!==0)throw new Error("Process owner refused an invalid or unowned identity.");return result}var NodeProcessRegistryClient=class{constructor(channel){this.channel=channel;if(channel.streams)this.streams=this.native=new NodeNativeStreamClient(channel);if(channel.groups&&channel.control.byteLength>=5*Int32Array.BYTES_PER_ELEMENT){this.lookupGroup=pgid=>this.call({operation:"lookup-group",pgid})!==void 0;this.signalGroup=(pgid,signal)=>this.call({operation:"signal-group",pgid,signal})!==void 0}}channel;streams;lookupGroup;signalGroup;native;allocate(){return this.call({operation:"allocate"}).pid}publish(token,identity){this.call({operation:"publish",token,...identity})}forget(token){this.call({operation:"forget",token})}lookup(pid){return this.call({operation:"lookup",pid})}signal(pid,signal){return this.call({operation:"signal",pid,signal})!==void 0}call(request){try{return exchange(this.channel,request,control=>{const pid=Atomics.load(control,PID);const pgid=this.channel.groups?Atomics.load(control,PGID):0;return pid===0?void 0:{pid,ppid:Atomics.load(control,PPID),...pgid?{pgid}:{}}})}catch(cause){if(Atomics.load(new Int32Array(this.channel.control),STATE)===CLOSED)this.native?.dispose();throw cause}}};var NodeNativeStreamClient=class{constructor(channel){this.channel=channel;if(!channel.streams)throw new Error("Native stream transport was not granted.");this.metadata=channel.streams;this.limits=Object.freeze({...channel.streams.limits});channel.port.addEventListener("message",this.receive);channel.port.addEventListener("messageerror",this.failed);channel.port.start()}channel;limits;listeners=new Set;pending=new Map;writing=new Set;queued=[];pendingBytes=0;nextRequest=1;stopped=false;metadata;call(operation){try{return exchange(this.channel,{operation:"stream-call",call:operation},control=>{const length=Atomics.load(control,PID);if(length<1||length>this.metadata.reply.byteLength)throw new Error("Invalid native stream reply length.");const bytes2=new Uint8Array(this.metadata.reply,0,length).slice();return JSON.parse(new TextDecoder().decode(bytes2))})}catch(cause){this.dispose();throw cause}}post(operation){if(this.stopped||Atomics.load(new Int32Array(this.channel.control),STATE)===CLOSED){this.dispose();throw new Error("Native stream owner stopped.")}this.channel.port.postMessage({operation:"stream-post",call:operation})}write(id2,bytes2,handle){if(this.stopped||Atomics.load(new Int32Array(this.channel.control),STATE)===CLOSED){this.dispose();return Promise.reject(new Error("Native stream owner stopped."))}if(this.writing.has(id2)||this.pending.size>=this.limits.maxHandles||bytes2.byteLength>this.limits.maxReadChunkBytes||!Number.isSafeInteger(this.nextRequest))return Promise.reject(new Error("Native stream write exceeds its transport limits."));const request=this.nextRequest++;return new Promise((resolve2,reject)=>{this.pending.set(request,{id:id2,bytes:bytes2.byteLength,resolve:resolve2,reject});this.writing.add(id2);this.queued.push({request,id:id2,bytes:bytes2,...handle===void 0?{}:{handle}});this.flushWrites()})}flushWrites(){while(!this.stopped&&this.queued.length){const next2=this.queued[0];if(this.pendingBytes+next2.bytes.byteLength>this.limits.maxPendingWriteBytes)return;this.queued.shift();const owned2=new Uint8Array(next2.bytes.byteLength);owned2.set(next2.bytes);this.pendingBytes+=owned2.byteLength;try{this.channel.port.postMessage({operation:"stream-write",request:next2.request,id:next2.id,bytes:owned2,...next2.handle===void 0?{}:{handle:next2.handle}},[owned2.buffer])}catch{this.dispose()}}}onEvent(listener){if(this.stopped)throw new Error("Native stream owner stopped.");this.listeners.add(listener);return()=>{this.listeners.delete(listener)}}receive=({data:data2})=>{if(data2.operation==="closed"){this.dispose();return}if(data2.operation==="stream-event"){for(const listener of[...this.listeners])listener(data2.event)}else if(data2.operation==="stream-written"){const write=this.pending.get(data2.request);if(!write){this.dispose();return}this.pending.delete(data2.request);this.writing.delete(write.id);this.pendingBytes-=write.bytes;this.flushWrites();write.resolve(data2.status)}};failed=()=>{this.dispose()};dispose(){if(this.stopped)return;this.stopped=true;Atomics.store(new Int32Array(this.channel.control),STATE,CLOSED);try{this.channel.port.postMessage({operation:"close"})}finally{this.channel.port.removeEventListener("message",this.receive);this.channel.port.removeEventListener("messageerror",this.failed);this.channel.port.close();const cause=new Error("Native stream owner stopped.");for(const write of this.pending.values())write.reject(cause);this.pending.clear();this.queued.length=0;this.writing.clear();this.pendingBytes=0;const listeners=[...this.listeners];this.listeners.clear();const failures=[];for(const listener of listeners){try{listener({type:"closed"})}catch(error){failures.push(error)}}if(failures.length)throw new AggregateError(failures,"Native stream close delivery failed.")}}};var maximumChunk=64*1024;function validDescriptorNumber(fd2){return typeof fd2==="number"&&Number.isInteger(fd2)&&fd2>=3&&fd2<=63}var CrossOriginChildProcesses=class{constructor(run,send2){this.run=run;this.send=send2}run;send;children=new Map;disposed=false;receive(message){if(!["child-run","child-abort","child-stdin","child-stdin-end","child-resize","child-fd","child-fd-end"].includes(message.type))return false;if(this.disposed)return true;if(message.type==="child-run"){if(!Number.isSafeInteger(message.id)||message.id<1||this.children.has(message.id)){throw new Error("Invalid or duplicate child process identity.")}if(message.descriptors!==void 0&&(!Array.isArray(message.descriptors)||!message.descriptors.every(validDescriptorNumber)||new Set(message.descriptors).size!==message.descriptors.length)){throw new Error("Child process descriptors must be distinct integers from 3 through 63.")}void this.start(message).catch(cause=>console.error("Child process transport failed.",cause));return true}if(!("id"in message)||typeof message.id!=="number")return true;const child=this.children.get(message.id);if(!child)return true;if(message.type==="child-abort"){child.controller.abort();child.input?.cancel();for(const input of child.descriptors.values())input.cancel()}else if(message.type==="child-fd"||message.type==="child-fd-end"){const input=validDescriptorNumber(message.fd)?child.descriptors.get(message.fd):void 0;if(!input){child.controller.abort(new Error("Child process has no such descriptor."));return true}if(message.type==="child-fd-end"){input.end();return true}if(!(message.bytes instanceof ArrayBuffer)||message.bytes.byteLength>maximumChunk){const cause=new Error("Child process descriptor chunks must be at most 64 KiB.");child.controller.abort(cause);input.cancel(cause);return true}const fd2=message.fd;void input.write(new Uint8Array(message.bytes)).then(()=>{if(!this.disposed&&this.children.get(message.id)===child)this.send({type:"child-fd-consumed",id:message.id,fd:fd2})}).catch(cause=>{child.controller.abort(cause)})}else if(message.type==="child-stdin"){if(!child.input){child.controller.abort(new Error("Child process has no live input."));return true}if(message.bytes.byteLength>64*1024){const cause=new Error("Child process input chunks must be at most 64 KiB.");child.controller.abort(cause);child.input.cancel(cause);return true}void child.input.write(new Uint8Array(message.bytes)).then(()=>{if(!this.disposed&&this.children.get(message.id)===child)this.send({type:"child-input-consumed",id:message.id})}).catch(cause=>{if(!this.disposed&&this.children.get(message.id)===child)child.controller.abort(cause)})}else if(message.type==="child-stdin-end")child.input?.end();else if(message.type==="child-resize"&&child.terminal){child.terminal.columns=message.columns;child.terminal.rows=message.rows;for(const resize of[...child.resizes]){try{resize(message.columns,message.rows)}catch(cause){child.controller.abort(cause)}}}return true}detach(){this.close(false)}dispose(){this.close(true)}close(abort){if(this.disposed)return;this.disposed=true;for(const child of this.children.values()){if(abort){child.controller.abort();child.input?.cancel();for(const input of child.descriptors.values())input.cancel()}else{child.input?.end();for(const input of child.descriptors.values())input.end()}child.resizes.clear()}this.children.clear()}async start(message){const child={controller:new AbortController,resizes:new Set,descriptors:new Map((message.descriptors??[]).map(fd2=>[fd2,new BrowserProcessInputPipe])),...message.liveStdin?{input:new BrowserProcessInputPipe}:{}};if(message.terminal)child.terminal={...message.terminal,onResize:listener=>{child.resizes.add(listener);return()=>{child.resizes.delete(listener)}}};this.children.set(message.id,child);const descriptors={};for(const[fd2,input]of child.descriptors)descriptors[fd2]=this.descriptor(message.id,fd2,input,child);try{const result=await this.run(message,{...message.cwd!==void 0?{cwd:message.cwd}:{},...message.env!==void 0?{env:message.env}:{},...message.executablePath!==void 0?{executablePath:message.executablePath}:{},...message.filesystemPolicy!==void 0?{filesystemPolicy:message.filesystemPolicy}:{},...message.stdin!==void 0?{stdin:message.stdin}:{},...child.input?{stdinStream:child.input}:{},...child.terminal?{terminal:child.terminal}:{},...child.descriptors.size>0?{descriptors}:{},signal:child.controller.signal,onStdout:chunk=>{if(!this.disposed)this.send({type:"child-output",id:message.id,stream:"stdout",chunk})},onStderr:chunk=>{if(!this.disposed)this.send({type:"child-output",id:message.id,stream:"stderr",chunk})}});if(!this.disposed)this.send({type:"child-result",id:message.id,stdout:result.stdout,stderr:result.stderr,exitCode:result.exitCode,...result.signal?{signal:result.signal}:{}})}catch(cause){if(!this.disposed){try{this.send({type:"child-error",id:message.id,error:cause instanceof Error?cause.message:String(cause)})}catch(failure){console.error("Child process result transport failed.",failure)}}}finally{child.input?.cancel();for(const input of child.descriptors.values())input.cancel();child.resizes.clear();this.children.delete(message.id)}}descriptor(id2,fd2,input,child){let closed=false;const live2=()=>!closed&&!this.disposed&&this.children.get(id2)===child;return{input,write:bytes2=>{for(let offset2=0;offset2<bytes2.byteLength&&live2();offset2+=maximumChunk){const chunk=Uint8Array.from(bytes2.subarray(offset2,offset2+maximumChunk)).buffer;this.send({type:"child-fd-output",id:id2,fd:fd2,bytes:chunk},[chunk])}},end:()=>{if(!live2())return;closed=true;this.send({type:"child-fd-close",id:id2,fd:fd2})}}}};var STAT_FIELDS=["mode","mtimeMs","atimeMs","ctimeMs","birthtimeMs","nlink","uid","gid","dev","ino","rdev","blksize","blocks"];var STATE2=0;var OPERATION=1;var STATUS2=2;var INPUT_LENGTH=3;var OUTPUT_LENGTH=4;var TOTAL_LENGTH=5;var CONTROL_WORDS=8;var DEFAULT_PAYLOAD_BYTES=4*1024*1024;var REQUEST_TIMEOUT_MS=3e4;var encoder2=new TextEncoder;var decoder3=new TextDecoder;function createBrowserFilesystemChannel(payloadBytes=DEFAULT_PAYLOAD_BYTES){const{port1,port2}=new MessageChannel;const control=new SharedArrayBuffer(CONTROL_WORDS*Int32Array.BYTES_PER_ELEMENT);const payload=new SharedArrayBuffer(payloadBytes);return{holder:{port:port1,control,payload},reader:{port:port2,control,payload}}}function serveBrowserFilesystemChannel(filesystem,channel){const control=new Int32Array(channel.control);const payload=new Uint8Array(channel.payload);let staged=null;channel.port.onmessage=event=>{const requestId2=event.data;if(Atomics.load(control,STATE2)!==requestId2)return;let status=0;let output=new Uint8Array;let total=0;try{const operation=Atomics.load(control,OPERATION);const inputLength=Atomics.load(control,INPUT_LENGTH);const input=JSON.parse(decoder3.decode(payload.slice(0,inputLength)));if(operation===1){output=encoder2.encode(JSON.stringify(filesystem.existsSync(input.path)))}else if(operation===2||operation===13){if(operation===13&&!filesystem.lstatSync){throw Object.assign(new Error("The filesystem holder does not support lstat."),{code:"ENOTSUP"})}const stat2=input.throwIfNoEntry===false?operation===13?filesystem.lstatSync(input.path,{throwIfNoEntry:false}):filesystem.statSync(input.path,{throwIfNoEntry:false}):operation===13?filesystem.lstatSync(input.path):filesystem.statSync(input.path);if(stat2===void 0)output=encoder2.encode("null");else{const metadata=Object.fromEntries(STAT_FIELDS.filter(key=>stat2[key]!==void 0).map(key=>[key,stat2[key]]));output=encoder2.encode(JSON.stringify({...metadata,file:stat2.isFile(),directory:stat2.isDirectory(),symlink:stat2.isSymbolicLink?.()??false,size:stat2.size,mode:stat2.mode??420,mtimeMs:stat2.mtimeMs??0}))}}else if(operation===14&&filesystem.readlinkSync){output=encoder2.encode(JSON.stringify(filesystem.readlinkSync(input.path)))}else if(operation===15&&filesystem.symlinkSync&&typeof input.target==="string"){filesystem.symlinkSync(input.target,input.path)}else if(operation===4){output=encoder2.encode(JSON.stringify(filesystem.readdirSync(input.path)))}else if(operation===3){const bytes2=filesystem.readFileSync(input.path);total=bytes2.byteLength;const offset2=input.offset??0;output=bytes2.subarray(offset2,Math.min(total,offset2+payload.byteLength))}else if(operation===5){output=encoder2.encode(JSON.stringify(filesystem.realpathSync?.(input.path)??input.path))}else if(operation===6&&filesystem.writeFileSync){if(!Number.isSafeInteger(input.bytes)||input.bytes<0||inputLength+input.bytes>payload.byteLength)throw new Error("Invalid filesystem write length.");const piece=payload.slice(inputLength,inputLength+input.bytes);if(input.total===void 0){filesystem.writeFileSync(input.path,piece)}else{const offset2=input.offset??0;if(!Number.isSafeInteger(input.total)||input.total<0||offset2+piece.byteLength>input.total)throw new Error("Invalid filesystem write piece.");if(offset2===0)staged={path:input.path,bytes:new Uint8Array(input.total),received:0};if(!staged||staged.path!==input.path||staged.bytes.byteLength!==input.total||staged.received!==offset2){staged=null;throw new Error(`The filesystem channel received a write piece of ${input.path} out of order.`)}staged.bytes.set(piece,offset2);staged.received+=piece.byteLength;if(staged.received===input.total){const whole=staged.bytes;staged=null;filesystem.writeFileSync(input.path,whole)}}}else if(operation===16&&(filesystem.appendFileSync||filesystem.writeFileSync)){if(!Number.isSafeInteger(input.bytes)||input.bytes<0||inputLength+input.bytes>payload.byteLength)throw new Error("Invalid filesystem append length.");const piece=payload.slice(inputLength,inputLength+input.bytes);if(filesystem.appendFileSync)filesystem.appendFileSync(input.path,piece);else{const existing=filesystem.existsSync(input.path)?filesystem.readFileSync(input.path):new Uint8Array(0);const whole=new Uint8Array(existing.byteLength+piece.byteLength);whole.set(existing,0);whole.set(piece,existing.byteLength);filesystem.writeFileSync(input.path,whole)}}else if(operation===17&&(filesystem.writeAtSync||filesystem.writeFileSync)){if(!Number.isSafeInteger(input.bytes)||input.bytes<0||inputLength+input.bytes>payload.byteLength)throw new Error("Invalid filesystem write length.");if(!Number.isSafeInteger(input.position)||input.position<0)throw new Error("Invalid filesystem write position.");const piece=payload.slice(inputLength,inputLength+input.bytes);if(filesystem.writeAtSync)filesystem.writeAtSync(input.path,piece,input.position);else if(piece.byteLength===0&&filesystem.existsSync(input.path)){}else{const existing=filesystem.existsSync(input.path)?filesystem.readFileSync(input.path):new Uint8Array(0);const whole=new Uint8Array(Math.max(existing.byteLength,input.position+piece.byteLength));whole.set(existing,0);whole.set(piece,input.position);filesystem.writeFileSync(input.path,whole)}}else if(operation===7&&filesystem.mkdirSync){filesystem.mkdirSync(input.path,{recursive:input.recursive===true})}else if(operation===8&&filesystem.unlinkSync){filesystem.unlinkSync(input.path)}else if(operation===9&&filesystem.rmdirSync){filesystem.rmdirSync(input.path)}else if(operation===10&&filesystem.renameSync&&typeof input.to==="string"){filesystem.renameSync(input.path,input.to)}else if(operation===11&&filesystem.chmodSync&&Number.isInteger(input.mode)){filesystem.chmodSync(input.path,input.mode)}else if(operation===12&&filesystem.utimesSync&&Number.isFinite(input.atime)&&Number.isFinite(input.mtime)){filesystem.utimesSync(input.path,input.atimeDate?new Date(input.atime):input.atime,input.mtimeDate?new Date(input.mtime):input.mtime)}else{throw new Error(`Unsupported filesystem channel operation ${operation}.`)}if(output.byteLength>payload.byteLength)throw new Error("The filesystem channel answer exceeds its buffer.")}catch(cause){const error=cause;const message=cause instanceof Error?cause.message:String(cause);status=2;output=encoder2.encode(JSON.stringify({message,...typeof error?.code==="string"?{code:error.code}:{},...typeof error?.path==="string"?{path:error.path}:{}}));if(output.byteLength>payload.byteLength){status=1;output=encoder2.encode(message).subarray(0,payload.byteLength)}}if(Atomics.compareExchange(control,STATE2,requestId2,-requestId2)!==requestId2)return;payload.set(output);Atomics.store(control,STATUS2,status);Atomics.store(control,OUTPUT_LENGTH,output.byteLength);Atomics.store(control,TOTAL_LENGTH,total);Atomics.store(control,STATE2,requestId2+1);Atomics.notify(control,STATE2)};channel.port.start();return()=>{channel.port.onmessage=null;channel.port.close()}}var BrowserFilesystemChannelClient=class{constructor(channel){this.channel=channel;this.control=new Int32Array(channel.control);this.payload=new Uint8Array(channel.payload)}channel;control;payload;nextRequestId=1;existsSync(path3){return JSON.parse(decoder3.decode(this.call(1,{path:path3}).output))}statSync(path3,options){return this.stat(path3,2,options?.throwIfNoEntry!==false)}lstatSync(path3,options){return this.stat(path3,13,options?.throwIfNoEntry!==false)}stat(path3,operation,throwIfNoEntry){let bytes2;try{bytes2=this.call(operation,{path:path3,...throwIfNoEntry?{}:{throwIfNoEntry:false}}).output}catch(cause){if(!throwIfNoEntry&&cause.code==="ENOENT")return void 0;throw cause}const stat2=JSON.parse(decoder3.decode(bytes2));if(stat2===null){if(!throwIfNoEntry)return void 0;throw new Error("The filesystem holder returned absence for a throwing stat.")}return{...Object.fromEntries(STAT_FIELDS.filter(key=>stat2[key]!==void 0).map(key=>[key,stat2[key]])),isFile:()=>stat2.file,isDirectory:()=>stat2.directory,isSymbolicLink:()=>stat2.symlink===true,size:stat2.size,mode:stat2.mode,mtimeMs:stat2.mtimeMs,mtime:new Date(stat2.mtimeMs)}}readlinkSync(path3){return JSON.parse(decoder3.decode(this.call(14,{path:path3}).output))}symlinkSync(target,path3){this.call(15,{path:path3,target})}readdirSync(path3){return JSON.parse(decoder3.decode(this.call(4,{path:path3}).output))}realpathSync(path3){return JSON.parse(decoder3.decode(this.call(5,{path:path3}).output))}writeFileSync(path3,value){const bytes2=typeof value==="string"?encoder2.encode(value):value;const room=this.payload.byteLength-encoder2.encode(JSON.stringify({path:path3,bytes:bytes2.byteLength,offset:bytes2.byteLength,total:bytes2.byteLength})).byteLength;if(bytes2.byteLength<=room){this.call(6,{path:path3,bytes:bytes2.byteLength},bytes2);return}for(let offset2=0;offset2<bytes2.byteLength;offset2+=room){const piece=bytes2.subarray(offset2,Math.min(bytes2.byteLength,offset2+room));this.call(6,{path:path3,bytes:piece.byteLength,offset:offset2,total:bytes2.byteLength},piece)}}appendFileSync(path3,value){const bytes2=typeof value==="string"?encoder2.encode(value):value;const room=this.payload.byteLength-encoder2.encode(JSON.stringify({path:path3,bytes:bytes2.byteLength})).byteLength;if(bytes2.byteLength===0){this.call(16,{path:path3,bytes:0},bytes2);return}for(let offset2=0;offset2<bytes2.byteLength;offset2+=room){const piece=bytes2.subarray(offset2,Math.min(bytes2.byteLength,offset2+room));this.call(16,{path:path3,bytes:piece.byteLength},piece)}}writeAtSync(path3,value,position){const room=this.payload.byteLength-encoder2.encode(JSON.stringify({path:path3,position:position+value.byteLength,bytes:value.byteLength})).byteLength;if(value.byteLength===0){this.call(17,{path:path3,position,bytes:0},value);return}for(let offset2=0;offset2<value.byteLength;offset2+=room){const piece=value.subarray(offset2,Math.min(value.byteLength,offset2+room));this.call(17,{path:path3,position:position+offset2,bytes:piece.byteLength},piece)}}mkdirSync(path3,options){this.call(7,{path:path3,recursive:options?.recursive===true})}unlinkSync(path3){this.call(8,{path:path3})}rmdirSync(path3){this.call(9,{path:path3})}renameSync(path3,to2){this.call(10,{path:path3,to:to2})}chmodSync(path3,mode){this.call(11,{path:path3,mode})}utimesSync(path3,atime,mtime){this.call(12,{path:path3,atime:typeof atime==="number"?atime:Number(atime),mtime:typeof mtime==="number"?mtime:Number(mtime),atimeDate:typeof atime!=="number",mtimeDate:typeof mtime!=="number"})}readFileSync(path3,encoding){const first=this.call(3,{path:path3});let bytes2;if(first.output.byteLength>=first.total){bytes2=first.output}else{bytes2=new Uint8Array(first.total);bytes2.set(first.output,0);for(let offset2=first.output.byteLength;offset2<first.total;){const piece=this.call(3,{path:path3,offset:offset2});if(piece.output.byteLength===0)throw new Error(`The filesystem channel returned a short read of ${path3}.`);bytes2.set(piece.output,offset2);offset2+=piece.output.byteLength}}return encoding?decoder3.decode(bytes2):bytes2}call(operation,input,bytes2){const encoded=encoder2.encode(JSON.stringify(input));if(encoded.byteLength+(bytes2?.byteLength??0)>this.payload.byteLength)throw new Error("The filesystem channel request exceeds its buffer.");if(Atomics.load(this.control,STATE2)!==0)throw new Error("The filesystem channel is answering another request.");const requestId2=this.nextRequestId;this.nextRequestId=requestId2>=1073741821?1:requestId2+2;this.payload.set(encoded);if(bytes2)this.payload.set(bytes2,encoded.byteLength);Atomics.store(this.control,OPERATION,operation);Atomics.store(this.control,INPUT_LENGTH,encoded.byteLength);Atomics.store(this.control,STATE2,requestId2);this.channel.port.postMessage(requestId2);const deadline=Date.now()+REQUEST_TIMEOUT_MS;for(;;){const state=Atomics.load(this.control,STATE2);if(state===requestId2+1)break;if(state!==requestId2&&state!==-requestId2)throw new Error(`The filesystem channel is in state ${state} for request ${requestId2}.`);const remaining=Math.max(0,deadline-Date.now());if(remaining===0&&state===requestId2&&Atomics.compareExchange(this.control,STATE2,requestId2,0)===requestId2){throw new Error(`The filesystem holder did not answer within ${REQUEST_TIMEOUT_MS} ms.`)}Atomics.wait(this.control,STATE2,state,state===-requestId2?void 0:remaining)}const status=Atomics.load(this.control,STATUS2);const length=Atomics.load(this.control,OUTPUT_LENGTH);const total=Atomics.load(this.control,TOTAL_LENGTH);const output=this.payload.slice(0,length);Atomics.store(this.control,STATE2,0);if(status===2){const error=JSON.parse(decoder3.decode(output));throw Object.assign(new Error(error.message),error)}if(status!==0)throw new Error(decoder3.decode(output));return{output,total}}};function createConfinedNodeFilesystem(filesystem,policy){const writable=createProcessFilesystemMutationGuard(filesystem,policy);const view=new VirtualFS;Object.defineProperty(view,Symbol.for("@volter/browser-node/assert-filesystem-mutation"),{value:writable});const descriptors={existsSync:path3=>filesystem.existsSync(path3),statSync:(path3,options)=>filesystem.statSync(path3,options),lstatSync:(path3,options)=>filesystem.lstatSync(path3,options),readdirSync:path3=>filesystem.readdirSync(path3),realpathSync:path3=>filesystem.realpathSync(path3),readlinkSync:path3=>filesystem.readlinkSync(path3),accessSync:(path3,mode)=>filesystem.accessSync((mode??0)&2?writable(path3):path3,mode),readFileSync:(path3,encoding)=>{const bytes2=new Uint8Array(filesystem.readFileSync(path3));return encoding?new TextDecoder().decode(bytes2):bytes2},writeFileSync:(path3,bytes2)=>filesystem.writeFileSync(writable(path3),typeof bytes2==="string"?bytes2:new Uint8Array(bytes2)),appendFileSync:(path3,bytes2)=>filesystem.appendFileSync(writable(path3),typeof bytes2==="string"?bytes2:new Uint8Array(bytes2)),writeAtSync:(path3,bytes2,position)=>filesystem.writeAtSync(writable(path3),new Uint8Array(bytes2),position),mkdirSync:(path3,options)=>{if(options?.recursive&&filesystem.existsSync(path3)&&filesystem.lstatSync(path3).isDirectory()&&!filesystem.lstatSync(path3).isSymbolicLink())return;filesystem.mkdirSync(writable(path3),options)},unlinkSync:path3=>filesystem.unlinkSync(writable(path3)),rmdirSync:path3=>filesystem.rmdirSync(writable(path3)),renameSync:(from,to2)=>{const source=writable(from);const destination=writable(to2);filesystem.renameSync(source,destination)},chmodSync:(path3,mode)=>{const target=writable(path3);const change=Reflect.get(filesystem,"chmodSync");if(!change)unsupported2("chmod");change.call(filesystem,target,mode)},utimesSync:(path3,atime,mtime)=>{const target=writable(path3);const change=Reflect.get(filesystem,"utimesSync");if(!change)unsupported2("utimes");change.call(filesystem,target,atime,mtime)},symlinkSync:()=>unsupported2("symlink"),linkSync:()=>unsupported2("link"),toSnapshot:()=>structuredClone(filesystem.toSnapshot()),watch:filesystem.watch.bind(filesystem),on:(event,listener)=>{filesystem.on(event,listener);return view},off:(event,listener)=>{filesystem.off(event,listener);return view}};for(const[name,value]of Object.entries(descriptors)){Object.defineProperty(view,name,{value,configurable:false,writable:false})}return view}function unsupported2(operation){throw Object.assign(new Error(`Node filesystem does not support ${operation}.`),{code:"ENOTSUP"})}var MAGIC=2019846480;var HEADER_WORDS=6;var RECORD_WORDS=6;var RECORD_NUMBERS=3;var PATH_OFFSET=0;var PATH_LENGTH=1;var FLAGS3=2;var MODE=3;var CHILD_START=4;var CHILD_COUNT=5;var MTIME=0;var OFFSET=1;var LENGTH3=2;var HAS_ENTRY=1;var HAS_CHILDREN=2;var PACKED=4;var ASCII2=32;var TYPE_SHIFT=3;var TYPES=["file","directory","symlink"];var LONE_SURROGATE=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;var encoder3=new TextEncoder;var decoder4=new TextDecoder;function hashPath(path3){let hash2=2166136261;for(let index2=0;index2<path3.length;index2+=1){hash2^=path3.charCodeAt(index2);hash2=Math.imul(hash2,16777619)}return hash2>>>0}function encodeSharedIndex(entries,children){const paths=[...entries.keys()];for(const path3 of paths)if(LONE_SURROGATE.test(path3))throw new Error("A path in the store is not well-formed UTF-16.");const at3=new Map;for(let index2=0;index2<paths.length;index2+=1)at3.set(paths[index2],index2);for(const parent2 of children.keys())if(!at3.has(parent2)){at3.set(parent2,paths.length);paths.push(parent2)}const count=paths.length;const encoded=new Map;const byteLengths=new Uint32Array(count);let stringBytes=0;for(let index2=0;index2<count;index2+=1){const path3=paths[index2];let ascii=true;for(let unit=0;unit<path3.length;unit+=1)if(path3.charCodeAt(unit)>=128){ascii=false;break}if(!ascii)encoded.set(index2,encoder3.encode(path3));byteLengths[index2]=ascii?path3.length:encoded.get(index2).length;stringBytes+=byteLengths[index2]}let childTotal=0;for(const names2 of children.values())childTotal+=names2.size;let tableSize=1;while(tableSize<count*2)tableSize<<=1;const recordsAt=HEADER_WORDS*4;const numbersAt=align(recordsAt+count*RECORD_WORDS*4,8);const tableAt=numbersAt+count*RECORD_NUMBERS*8;const childListAt=tableAt+tableSize*4;const stringsAt=childListAt+childTotal*4;const buffer2=new SharedArrayBuffer(align(stringsAt+stringBytes,8));const header=new Uint32Array(buffer2,0,HEADER_WORDS);header.set([MAGIC,count,tableSize,childTotal,stringBytes,entries.size]);const records=new Uint32Array(buffer2,recordsAt,count*RECORD_WORDS);const numbers=new Float64Array(buffer2,numbersAt,count*RECORD_NUMBERS);const table=new Uint32Array(buffer2,tableAt,tableSize);const childList=new Uint32Array(buffer2,childListAt,childTotal);const strings2=new Uint8Array(buffer2,stringsAt,stringBytes);let stringCursor=0;let childCursor=0;for(let index2=0;index2<count;index2+=1){const path3=paths[index2];const word=index2*RECORD_WORDS;const other=encoded.get(index2);if(other)strings2.set(other,stringCursor);else for(let unit=0;unit<path3.length;unit+=1)strings2[stringCursor+unit]=path3.charCodeAt(unit);const length=byteLengths[index2];records[word+PATH_OFFSET]=stringCursor;records[word+PATH_LENGTH]=length;stringCursor+=length;let flags=other?0:ASCII2;const entry=entries.get(path3);if(entry){flags|=HAS_ENTRY|TYPES.indexOf(entry.type)<<TYPE_SHIFT;if(entry.pack)flags|=PACKED;records[word+MODE]=entry.mode;const number=index2*RECORD_NUMBERS;numbers[number+MTIME]=entry.mtimeMs;numbers[number+OFFSET]=entry.offset;numbers[number+LENGTH3]=entry.length}const names2=children.get(path3);if(names2){flags|=HAS_CHILDREN;records[word+CHILD_START]=childCursor;records[word+CHILD_COUNT]=names2.size;for(const name of names2){const child=at3.get(`${path3}/${name}`);if(child===void 0)throw new Error(`The store's children name ${path3}/${name}, which its index does not hold.`);childList[childCursor++]=child}}records[word+FLAGS3]=flags;let slot=hashPath(path3)&tableSize-1;while(table[slot]!==0)slot=slot+1&tableSize-1;table[slot]=index2+1}if(childCursor!==childTotal)throw new Error("The shared index's children did not add up.");return buffer2}function align(value,to2){return Math.ceil(value/to2)*to2}var SharedIndex=class{buffer;count;entryCount;records;numbers;table;childList;strings;mask;constructor(buffer2){const header=new Uint32Array(buffer2,0,HEADER_WORDS);if(header[0]!==MAGIC)throw new Error("Not a shared store index.");const[,count,tableSize,childTotal,stringBytes,entryCount]=header;this.buffer=buffer2;this.count=count;this.entryCount=entryCount;const recordsAt=HEADER_WORDS*4;const numbersAt=align(recordsAt+count*RECORD_WORDS*4,8);const tableAt=numbersAt+count*RECORD_NUMBERS*8;const childListAt=tableAt+tableSize*4;const stringsAt=childListAt+childTotal*4;this.records=new Uint32Array(buffer2,recordsAt,count*RECORD_WORDS);this.numbers=new Float64Array(buffer2,numbersAt,count*RECORD_NUMBERS);this.table=new Uint32Array(buffer2,tableAt,tableSize);this.childList=new Uint32Array(buffer2,childListAt,childTotal);this.strings=new Uint8Array(buffer2,stringsAt,stringBytes);this.mask=tableSize-1}find(path3){let slot=hashPath(path3)&this.mask;for(;;){const held=this.table[slot];if(held===0)return-1;if(this.pathIs(held-1,path3))return held-1;slot=slot+1&this.mask}}entry(record){const word=record*RECORD_WORDS;const flags=this.records[word+FLAGS3];if(!(flags&HAS_ENTRY))return void 0;const number=record*RECORD_NUMBERS;const entry={type:TYPES[flags>>>TYPE_SHIFT&3],mode:this.records[word+MODE],mtimeMs:this.numbers[number+MTIME],offset:this.numbers[number+OFFSET],length:this.numbers[number+LENGTH3]};if(flags&PACKED)entry.pack="packages";return entry}typeAt(record){const flags=this.records[record*RECORD_WORDS+FLAGS3];return flags&HAS_ENTRY?TYPES[flags>>>TYPE_SHIFT&3]:void 0}hasEntry(record){return(this.records[record*RECORD_WORDS+FLAGS3]&HAS_ENTRY)!==0}childNames(record){const word=record*RECORD_WORDS;if(!(this.records[word+FLAGS3]&HAS_CHILDREN))return void 0;const start=this.records[word+CHILD_START];const skip=this.records[word+PATH_LENGTH]+1;const names2=[];for(let index2=0;index2<this.records[word+CHILD_COUNT];index2+=1){const child=this.childList[start+index2]*RECORD_WORDS;names2.push(this.decode(this.records[child+PATH_OFFSET]+skip,this.records[child+PATH_LENGTH]-skip,(this.records[child+FLAGS3]&ASCII2)!==0))}return names2}path(record){const word=record*RECORD_WORDS;return this.decode(this.records[word+PATH_OFFSET],this.records[word+PATH_LENGTH],(this.records[word+FLAGS3]&ASCII2)!==0)}decode(start,length,ascii){if(!ascii)return decoder4.decode(this.strings.slice(start,start+length));let text="";for(let at3=start,end=start+length;at3<end;at3+=4096){text+=String.fromCharCode.apply(null,this.strings.subarray(at3,Math.min(end,at3+4096)))}return text}pathIs(record,path3){const word=record*RECORD_WORDS;const start=this.records[word+PATH_OFFSET];const length=this.records[word+PATH_LENGTH];if(!(this.records[word+FLAGS3]&ASCII2))return this.path(record)===path3;if(length!==path3.length)return false;for(let index2=0;index2<length;index2+=1)if(this.strings[start+index2]!==path3.charCodeAt(index2))return false;return true}};var DELETED=Symbol("deleted");function sameIndexEntry(left,right){return left===right||!!left&&!!right&&left.type===right.type&&left.offset===right.offset&&left.length===right.length&&left.pack===right.pack&&left.mode===right.mode&&left.mtimeMs===right.mtimeMs&&left.capacity===right.capacity}var OverlaidIndex=class{constructor(base){this.base=base}base;overlay=new Map;delta=0;get[Symbol.toStringTag](){return"Map"}get size(){return this.base.entryCount+this.delta}get(path3){const over=this.overlay.get(path3);if(over!==void 0)return over===DELETED?void 0:over;const record=this.base.find(path3);return record<0?void 0:this.base.entry(record)}typeOf(path3){const over=this.overlay.get(path3);if(over!==void 0)return over===DELETED?void 0:over.type;const record=this.base.find(path3);return record<0?void 0:this.base.typeAt(record)}has(path3){const over=this.overlay.get(path3);if(over!==void 0)return over!==DELETED;const record=this.base.find(path3);return record>=0&&this.base.hasEntry(record)}set(path3,entry){if(!this.has(path3))this.delta+=1;const record=this.base.find(path3);if(record>=0&&sameIndexEntry(this.base.entry(record),entry))this.overlay.delete(path3);else this.overlay.set(path3,entry);return this}delete(path3){if(!this.has(path3))return false;const record=this.base.find(path3);if(record>=0&&this.base.hasEntry(record))this.overlay.set(path3,DELETED);else this.overlay.delete(path3);this.delta-=1;return true}clear(){throw new Error("A reader's index is not cleared; it is replaced.")}*entries(){for(const[path3,entry]of this.overlay)if(entry!==DELETED)yield[path3,entry];for(let record=0;record<this.base.count;record+=1){if(!this.base.hasEntry(record))continue;const path3=this.base.path(record);if(this.overlay.has(path3))continue;yield[path3,this.base.entry(record)]}}*keys(){for(const[path3]of this.entries())yield path3}*values(){for(const[,entry]of this.entries())yield entry}[Symbol.iterator](){return this.entries()}forEach(callback,thisArg){for(const[path3,entry]of this.entries())callback.call(thisArg,entry,path3,this)}*changed(){for(const[path3,entry]of this.overlay)if(entry!==DELETED)yield[path3,entry]}*changes(){for(const[path3,entry]of this.overlay)yield[path3,entry===DELETED?null:entry]}get overlaid(){return this.overlay.size}boundedChanges(){if(this.overlay.size>65536)return void 0;const changes=[];let bytes2=0;for(const[path3,entry]of this.changes()){bytes2+=path3.length*2+128;if(bytes2>8*1024*1024)return void 0;changes.push([path3,entry])}return changes}};var OverlaidChildren=class{constructor(base){this.base=base}base;overlay=new Map;get(path3){const over=this.overlay.get(path3);if(over!==void 0)return over===DELETED?void 0:over;const record=this.base.find(path3);const names2=record<0?void 0:this.base.childNames(record);return names2?new Set(names2):void 0}mutable(path3){const over=this.overlay.get(path3);if(over!==void 0&&over!==DELETED)return over;const names2=new Set(over===DELETED?[]:this.get(path3)??[]);this.overlay.set(path3,names2);return names2}delete(path3){this.overlay.set(path3,DELETED)}};var STORE_BASE_DIRECTORY="supercode-browser-filesystems";var PACKAGES_STORE="packages";var STORE_STATE_FILE="state.json";var PACKAGES_ROOT="/packages";var BROWSER_PACK_RETENTION_ROOT="/opt/.browser-packs";var PACKAGES_LOCK="supercode-browser-packages";var PACKAGES_OPEN_LOCK="supercode-browser-packages-open";var encoder4=new TextEncoder;var decoder5=new TextDecoder("utf-8",{fatal:true});var BASE_DIRECTORY=STORE_BASE_DIRECTORY;var TREE_STORE_PREFIX="host-tree.";var GENERATIONS_DIRECTORY="generations";var STAGING_DIRECTORY="atomic-staging";var STATE_FILE=STORE_STATE_FILE;var INDEX_FILE="index.json";var LOG_FILE="index-log.bin";var PACK_FILE="pack.bin";var RECORD_HEADER_BYTES=8;var MAX_RECORD_BYTES=64*1024*1024;var MAX_FILE_BYTES=1024*1024*1024;var ORIGIN_QUOTA_SHARE=.95;var PROJECT_ROOTS=["/workspace","/home","/opt"];var STORE_CLOCK_EPOCH=0;var STORE_CLOCK_LOG=1;var MAX_ENTRIES=1e6;var MAX_LOG_BYTES=8*1024*1024;var FLUSH_WINDOW_MS=250;var COMPACTION_FLOOR_BYTES=64*1024*1024;var SESSION_COMPACTION_BYTES=256*1024*1024;var COPY_BUFFER_BYTES=4*1024*1024;var DIRECTORY_MODE=493;var FILE_MODE=420;function createPackStore(environment,options={}){const explicitBytes=options.limits?.maxBytes;const maximumEntries=options.limits?.maxEntries??MAX_ENTRIES;if(explicitBytes!==void 0&&(!Number.isSafeInteger(explicitBytes)||explicitBytes<1)||!Number.isSafeInteger(maximumEntries)||maximumEntries<1||maximumEntries>MAX_ENTRIES){throw new Error("Invalid OPFS workspace limits.")}let originRoom=Number.MAX_SAFE_INTEGER;let heldAtOpen;let project;let shared=false;let readOnly=false;let extentsOnly=false;let generationHandle;let linked=0;let linkedBytes=0;let releaseLock;let projectId;let generation;let entries=new Map;let children=new LocalChildren;let packAccess;let imageRangesDigest;let imageReader;let deferredImage;let receivedImageCompletion;let receivedImageLine;let generationInitializedAt=0;let logAccess;let immutableReadEnd=0;const readAhead=new Map;const READ_AHEAD_BYTES=256*1024;const READ_AHEAD_BLOCKS=32;let packBytes=0;let flushTimer;let lastFlushAt=-Infinity;let flushes=0;let flushMs=0;let logBytes=0;let liveBytes=0;let deadBytes=0;let rewrites=0;let rewrittenBytes=0;let mutationUndo;let bytesUndo;let mutationFailure;let initializing=false;let openingController;let checkpointTail=Promise.resolve();let activeStorageOperations=0;let closing=false;let rewritingGeneration=false;let clockView;let transitions=0;let clockClosed=false;function publishLog(){if(!clockView||clockClosed)return;if(logBytes>2147483647){retireClock();return}Atomics.store(clockView,STORE_CLOCK_LOG,logBytes)}function retireClock(){if(!clockView||clockClosed)return;clockClosed=true;if((Atomics.load(clockView,STORE_CLOCK_EPOCH)&1)===0)Atomics.add(clockView,STORE_CLOCK_EPOCH,1)}function beginTransition(){transitions+=1;if(transitions===1&&clockView&&!clockClosed)Atomics.add(clockView,STORE_CLOCK_EPOCH,1)}function endTransition(){transitions-=1;if(transitions>0||!clockView||clockClosed)return;publishLog();if(!clockClosed)Atomics.add(clockView,STORE_CLOCK_EPOCH,1)}function clock(){if(readOnly)throw new Error("A store open for reading follows its owner's clock; it has none of its own.");if(!clockView){clockView=new Int32Array(new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT));clockView[STORE_CLOCK_EPOCH]=transitions>0||clockClosed?1:0;publishLog()}return clockView.buffer}let seedCache;const SEED_REPLAY_BYTES=8*1024*1024;let startedFromSeed=false;function readerSeed(options2){if(readOnly||!clockView||!generation||initializing||transitions>0||clockClosed||closing)return void 0;const epoch=Atomics.load(clockView,STORE_CLOCK_EPOCH);if(epoch&1)return void 0;if(options2?.overlays&&entries instanceof OverlaidIndex){const changes=entries.boundedChanges();if(changes){return withImageCompletion({generation,index:entries.base.buffer,changes,packBytes,logBytes,epoch,liveBytes,linked,linkedBytes})}}if(seedCache&&seedCache.generation===generation&&seedCache.epoch===epoch&&logBytes>=seedCache.logBytes&&logBytes-seedCache.logBytes<=(options2?.current?0:SEED_REPLAY_BYTES))return withImageCompletion(seedCache);let index2;try{index2=encodeSharedIndex(entries,childrenMap())}catch(cause){console.warn(`[pack-store] no reader seed: ${cause instanceof Error?cause.message:String(cause)}`);return void 0}seedCache={generation,index:index2,packBytes,logBytes,epoch,liveBytes,linked,linkedBytes};standOnSeed(index2);return withImageCompletion(seedCache)}function withImageCompletion(seed){const packagesImage=options.packages?.imageCompletionSeed();return packagesImage?{...seed,packagesImage}:seed}function imageCompletionSeed(){if(!imageReader||!imageRangesDigest||!generation||initializing||transitions>0||closing)return void 0;return{generation,rangesDigest:imageRangesDigest,completed:imageReader.completionBuffer,...imageReader.receiptKey?{metadata:{ranges:imageReader.verifiedRanges,receiptKey:imageReader.receiptKey}}:{}}}function standOnSeed(index2){const roomy=[];if(entries instanceof OverlaidIndex){for(const[path3,entry]of entries.changed())if(entry.capacity!==void 0)roomy.push([path3,entry])}else{for(const[path3,entry]of entries)if(entry.capacity!==void 0)roomy.push([path3,entry])}const base=new SharedIndex(index2);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);for(const[path3,entry]of roomy)entries.set(path3,entry)}function childrenMap(){if(children instanceof LocalChildren)return children.map;const derived=new Map;for(const path3 of entries.keys()){const parent2=parentPath(path3);if(parent2===path3)continue;let names2=derived.get(parent2);if(!names2){names2=new Set;derived.set(parent2,names2)}names2.add(path3.slice(parent2.length+1))}return derived}function follow(){if(!readOnly||extentsOnly||closing||!logAccess)return;replayLog(logBytes)}async function ownStorageOperation(operation){if(closing)throw new Error("This OPFS workspace is closing.");activeStorageOperations+=1;let failure;let failed=false;try{return await operation()}catch(cause){failed=true;failure=cause;throw cause}finally{activeStorageOperations-=1;if(closing&&activeStorageOperations===0){try{closeStorage()}catch(cause){if(failed)throw new AggregateError([failure,cause],"OPFS operation and deferred close both failed.");throw cause}}}}async function rewriteGeneration(operation){assertWritable();if(activeStorageOperations!==0)return Promise.reject(new Error("Wait for the current OPFS storage operation before replacing its generation."));rewritingGeneration=true;return ownStorageOperation(async()=>{try{return await operation()}finally{rewritingGeneration=false}})}function read(path3){if(closing)throw new Error("This OPFS workspace is closing.");const entry=entries.get(path3);if(!entry||entry.type==="directory")throw new Error(`OPFS workspace file does not exist: ${path3}`);return readEntry(entry)}function readRange(path3,offset2,length){if(closing)throw new Error("This OPFS workspace is closing.");const entry=entries.get(path3);if(!entry||entry.type==="directory")throw new Error(`OPFS workspace file does not exist: ${path3}`);const start=Math.min(Math.max(0,offset2),entry.length);const count=Math.min(Math.max(0,length),entry.length-start);if(entry.pack){const packages2=options.packages;if(!packages2)throw new Error("This store has no shared package store to read from.");return packages2.readExtent(entry.offset+start,count)}return readExtent(entry.offset+start,count)}function readEntry(entry){if(entry.pack){const packages2=options.packages;if(!packages2)throw new Error("This store has no shared package store to read from.");return packages2.readExtent(entry.offset,entry.length)}return readExtent(entry.offset,entry.length)}function readExtent(offset2,length){if(closing)throw new Error("This OPFS workspace is closing.");const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");const value=new Uint8Array(length);if(length>0&&length<=READ_AHEAD_BYTES&&offset2>=0&&offset2+length<=immutableReadEnd){let copied=0;while(copied<length){const position=offset2+copied;const start=Math.floor(position/READ_AHEAD_BYTES)*READ_AHEAD_BYTES;let block=readAhead.get(start);if(!block){block=new Uint8Array(Math.min(READ_AHEAD_BYTES,immutableReadEnd-start));imageReader?.ensure(start,block.byteLength);if(access.read(block,{at:start})!==block.byteLength)throw new Error("An OPFS package range could not be read completely.")}readAhead.delete(start);readAhead.set(start,block);if(readAhead.size>READ_AHEAD_BLOCKS)readAhead.delete(readAhead.keys().next().value);const from=position-start;const count=Math.min(length-copied,block.byteLength-from);value.set(block.subarray(from,from+count),copied);copied+=count}return value}imageReader?.ensure(offset2,length);if(length>0&&access.read(value,{at:offset2})!==length){throw new Error("An OPFS workspace file could not be read completely.")}return value}async function initialize2(requestedProjectId,openOptions={}){if(closing&&project||!project&&activeStorageOperations!==0)throw new Error("Wait for this OPFS workspace to finish closing before opening it again.");if(initializing)throw new Error("This OPFS store is already opening a workspace.");if(project){if(projectId!==validProjectId(requestedProjectId))throw new Error("Close this OPFS store before opening another workspace.");return entries.size>0}initializing=true;closing=false;const opening=new AbortController;openingController=opening;try{entries=new Map;children=new LocalChildren;generation=void 0;imageRangesDigest=void 0;generationHandle=void 0;mutationUndo=void 0;mutationFailure=void 0;packBytes=logBytes=liveBytes=deadBytes=linked=linkedBytes=0;checkpointPrefix=void 0;rewrites=rewrittenBytes=flushes=flushMs=0;lastFlushAt=-Infinity;projectId=validProjectId(requestedProjectId);readOnly=openOptions.readOnly===true;receivedImageCompletion=readOnly?openOptions.imageCompletion:void 0;receivedImageLine=readOnly?openOptions.imageLine:void 0;extentsOnly=readOnly&&openOptions.extentsOnly===true;shared=openOptions.shared===true||readOnly;heldAtOpen=void 0;try{const estimate=await environment.navigator.storage.estimate?.();if(estimate?.quota)originRoom=Math.max(0,Math.floor(estimate.quota*ORIGIN_QUOTA_SHARE)-(estimate.usage??0))}catch{}if(!shared)await acquireSessionLock(opening.signal);opening.signal.throwIfAborted();const root2=await storageRoot();opening.signal.throwIfAborted();try{const base=await root2.getDirectoryHandle(BASE_DIRECTORY,{create:!readOnly});opening.signal.throwIfAborted();project=await base.getDirectoryHandle(projectId,{create:!readOnly})}catch(cause){opening.signal.throwIfAborted();if(readOnly&¬Found2(cause))return false;throw cause}opening.signal.throwIfAborted();let state=readStorageState(await readJson(project,STATE_FILE));opening.signal.throwIfAborted();if(!state&&readOnly){await assertNoUncommittedGenerations();return false}if(!state&&shared){await environment.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive",signal:opening.signal},async()=>{opening.signal.throwIfAborted();state=readStorageState(await readJson(project,STATE_FILE));opening.signal.throwIfAborted();if(!state){await assertNoUncommittedGenerations();await writeGeneration({files:[],pack:new ArrayBuffer(0)});await writeSweepMark(project)}});opening.signal.throwIfAborted();if(!state){generationHandle=await generationDirectory(generation,false);opening.signal.throwIfAborted();return false}}if(!state){await assertNoUncommittedGenerations();opening.signal.throwIfAborted();return false}const openCommitted=async state2=>{let directory2;try{directory2=await generationDirectory(state2.generation,false)}catch(cause){opening.signal.throwIfAborted();if(!notFound2(cause))throw cause;throw new Error("The committed OPFS workspace generation is missing. Stored generations were retained.",{cause})}opening.signal.throwIfAborted();generation=state2.generation;generationInitializedAt=state2.initializedAt;imageRangesDigest=state2.imageRanges;generationHandle=directory2;if(extentsOnly){if(projectId===PACKAGES_STORE&&environment.navigator.locks){await environment.navigator.locks.request(PACKAGES_LOCK,{mode:"shared",signal:opening.signal},async()=>{await openGenerationHandles(directory2);immutableReadEnd=packAccess.getSize()})}else await openGenerationHandles(directory2);opening.signal.throwIfAborted();return true}const seed=readOnly?openOptions.seed:void 0;if(seed&&seed.generation===state2.generation){const base=new SharedIndex(seed.index);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);packBytes=seed.packBytes;if(seed.changes)applyIndexRecord({packBytes:seed.packBytes,changes:seed.changes});await openGenerationHandles(directory2);opening.signal.throwIfAborted();logBytes=seed.logBytes;({liveBytes,linked,linkedBytes}=seed);deadBytes=Math.max(0,packBytes-liveBytes);startedFromSeed=true;return entries.size>0}const retained=!readOnly?await readRetainedIndex(directory2):void 0;opening.signal.throwIfAborted();if(retained){const base=new SharedIndex(retained.index);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);({packBytes,liveBytes,linked,linkedBytes}=retained);const epoch=Atomics.load(new Int32Array(clock()),STORE_CLOCK_EPOCH);seedCache={generation,index:retained.index,packBytes,liveBytes,linked,linkedBytes,logBytes:0,epoch}}else{entries=readIndex(await readJson(directory2,INDEX_FILE));opening.signal.throwIfAborted();rebuildChildren();packBytes=indexPackBytes(entries)}await openGenerationHandles(directory2);opening.signal.throwIfAborted();const represented=retained?await verifiedJournalPrefix(retained):0;opening.signal.throwIfAborted();if(represented){checkpointPrefix={generation,bytes:represented};if(seedCache)seedCache.logBytes=represented}replayLog(represented,!!retained);if(retained)deadBytes=Math.max(0,packBytes-liveBytes);else measureBytes();assertWorkspaceQuota();if(shared&&!readOnly&&!retained&&entries.size>=1e4){flushStorage();await writeIndexAtomically(directory2,entries,{access:logAccess,bytes:logBytes,packBytes})}if(!shared){packAccess.truncate(packBytes);await removeEntry(project,STAGING_DIRECTORY,true);await discardGenerations(generation);opening.signal.throwIfAborted();if(deadBytes>COMPACTION_FLOOR_BYTES&&deadBytes>liveBytes)await compact()}opening.signal.throwIfAborted();return entries.size>0};if(shared&&!readOnly){return await environment.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive",signal:opening.signal},async()=>{state=readStorageState(await readJson(project,STATE_FILE));if(!state)throw new Error("The committed package store state is missing. Stored data was retained.");return openCommitted(state)})}return await openCommitted(state)}catch(cause){const failures=[cause];try{closeGenerationHandles()}catch(error){failures.push(error)}try{releaseLock?.()}catch(error){failures.push(error)}releaseLock=void 0;project=void 0;if(failures.length>1)throw new AggregateError(failures,"OPFS workspace open and cleanup failed.");throw cause}finally{initializing=false;openingController=void 0}}function refresh(options2){return ownStorageOperation(()=>refreshStorage(options2?.whole===true))}async function refreshStorage(whole=false){if(extentsOnly)throw new Error("A store opened for its extents alone has no index to follow.");if(readOnly&&project){const state=readStorageState(await readJson(project,STATE_FILE));if(!state)throw new Error("The committed OPFS workspace state is missing. Stored data was retained.");if(state.generation!==generation||whole){const directory2=await generationDirectory(state.generation,false);const index2=readIndex(await readJson(directory2,INDEX_FILE));packBytes=indexPackBytes(index2);if(state.generation!==generation){generation=state.generation;generationInitializedAt=state.initializedAt;imageRangesDigest=state.imageRanges;await openGenerationHandles(directory2)}generation=state.generation;generationHandle=directory2;entries=index2;rebuildChildren();replayLog();measureBytes();return}}const access=logAccess;if(!access||!generationHandle)return;const size=access.getSize();let reread=false;if(size<logBytes){entries=readIndex(await readJson(generationHandle,INDEX_FILE));rebuildChildren();packBytes=indexPackBytes(entries);logBytes=0;reread=true}const before=logBytes;replayLog(logBytes);if(reread||logBytes!==before)measureBytes()}async function storageRoot(){let last;for(let attempt=0;attempt<10;attempt+=1){openingController?.signal.throwIfAborted();try{return await environment.navigator.storage.getDirectory()}catch(cause){last=cause;await new Promise(resolve2=>setTimeout(resolve2,200))}}throw last instanceof Error?last:new Error("This browser workspace's storage is unavailable.")}const OPEN_ATTEMPT_MS=1e4;async function openSyncAccess(handle,name){let refusal;const signal=openingController?.signal;for(let attempt=0;attempt<2;attempt+=1){signal?.throwIfAborted();const pending=handle.createSyncAccessHandle({mode:"readwrite-unsafe"});let timer;let abort;let claimed=false;try{const cancelled2=new Promise((_resolve,reject)=>{abort=()=>reject(signal?.reason??new DOMException("Workspace open was cancelled.","AbortError"));signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted)abort()});const opened=await Promise.race([pending.then(access=>({access})).catch(cause=>{refusal=cause;return void 0}),new Promise(resolve2=>{timer=setTimeout(()=>resolve2(void 0),OPEN_ATTEMPT_MS)}),cancelled2]);signal?.throwIfAborted();if(opened){claimed=true;return opened.access}}finally{if(timer!==void 0)clearTimeout(timer);if(abort)signal?.removeEventListener("abort",abort);if(!claimed)void pending.then(access=>access.close(),()=>void 0).catch(cause=>console.error("Late workspace handle cleanup failed.",cause))}if(refusal 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). ${refusal.message}`)}await new Promise(resolve2=>setTimeout(resolve2,500))}const reason=refusal instanceof Error?` (${refusal.message})`:"";throw new Error(`This browser workspace's ${name} is held by another page${reason}.`)}async function openGenerationHandles(directory2){closeGenerationHandles();const pack=await directory2.getFileHandle(PACK_FILE);packAccess=await openSyncAccess(pack,"store");try{if(packAccess.getSize()<packBytes)throw new Error("The committed OPFS workspace pack is incomplete. Stored data was retained.");const log=await directory2.getFileHandle(LOG_FILE);logAccess=await openSyncAccess(log,"record of changes");logBytes=logAccess.getSize();if(imageRangesDigest){const supplied=receivedImageCompletion;const completion=supplied&&supplied.generation===generation&&supplied.rangesDigest===imageRangesDigest?supplied:void 0;let ranges;let receiptKey;if(completion?.metadata){ranges=validateImageRanges(completion.metadata.ranges);receiptKey=completion.metadata.receiptKey;if(!/^[a-f0-9]{64}$/u.test(receiptKey))throw new Error("The owner's immutable receipt key is invalid.")}else{const file2=await(await directory2.getFileHandle(IMAGE_RANGES_FILE)).getFile();const bytes2=new Uint8Array(await file2.arrayBuffer());if(await indexDigest(bytes2)!==imageRangesDigest)throw new Error("The committed immutable image ranges have changed. Stored data was retained.");ranges=validateImageRanges(JSON.parse(decoder5.decode(bytes2)));receiptKey=await indexDigest(encoder4.encode(JSON.stringify(ranges)))}if(ranges.bytes>packAccess.getSize())throw new Error("The immutable image reservation is incomplete. Stored data was retained.");const line=completion?receivedImageLine:void 0;if(!line)receivedImageLine?.port.close();receivedImageLine=void 0;imageReader=new ImageRangeReader(ranges,directory2,`${projectId}.${generation}`,completion?.completed,receiptKey,line);console.log(`[boot-trace] ${JSON.stringify({event:"image-reader-open",at:Date.now(),reader:`${projectId}.${generation}`,offered:supplied!==void 0,shared:completion!==void 0,...supplied&&!completion?{offeredGeneration:supplied.generation,generation,rangesMatch:supplied.rangesDigest===imageRangesDigest}:{}})}`);await imageReader.initialize();deferredImage=ranges.image}}catch(cause){closeGenerationHandles();throw cause}}function closeGenerationHandles(){imageReader?.close();imageReader=void 0;deferredImage=void 0;const pack=packAccess,log=logAccess;packAccess=void 0;logAccess=void 0;logBytes=0;immutableReadEnd=0;readAhead.clear();try{pack?.close()}finally{log?.close()}}function replayLog(from=0,measureChanges=false){const access=logAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");const size=access.getSize();if(size<=from){logBytes=size;return}const buffer2=new Uint8Array(size-from);if(access.read(buffer2,{at:from})!==buffer2.byteLength)throw new Error("The OPFS workspace index log could not be read.");const packSize=packAccess?.getSize()??Infinity;const view=new DataView(buffer2.buffer);let offset2=0;const end=buffer2.byteLength;while(offset2+RECORD_HEADER_BYTES<=end){const length=view.getUint32(offset2,true);const checksum=view.getUint32(offset2+4,true);const start=offset2+RECORD_HEADER_BYTES;if(length===0||length>MAX_RECORD_BYTES||start+length>end)break;const body=buffer2.subarray(start,start+length);if(fingerprint2(body)!==checksum)break;let record;try{record=readIndexRecord(JSON.parse(decoder5.decode(body)))}catch{break}if(record.packBytes>packSize)break;applyIndexRecord(record,measureChanges);offset2=start+length}if(offset2!==end&&!shared)access.truncate(from+offset2);logBytes=from+offset2}function applyIndexRecord(record,measureChanges=false){for(const[path3,entry]of record.changes){const previous=entries.get(path3);if(entry&&sameIndexEntry(previous,entry)){attach(path3);continue}if(measureChanges){if(previous?.pack){linked-=1;linkedBytes-=previous.length}else if(previous)liveBytes-=previous.length;if(entry?.pack){linked+=1;linkedBytes+=entry.length}else if(entry)liveBytes+=entry.length}if(entry===null){entries.delete(path3);detach(path3)}else{entries.set(path3,entry);attach(path3)}}packBytes=Math.max(packBytes,record.packBytes)}function measureBytes(){liveBytes=0;linked=0;linkedBytes=0;for(const entry of entries.values()){if(entry.pack){linked+=1;linkedBytes+=entry.length}else liveBytes+=entry.length}deadBytes=Math.max(0,packBytes-liveBytes)}function indexPackBytes(index2){let end=0;for(const entry of index2.values())if(!entry.pack)end=Math.max(end,entry.offset+entry.length);return end}const SESSION_LOCK_WAIT_MS=5e3;async function acquireSessionLock(signal){if(!environment.navigator.locks)return;if(!projectId)throw new Error("OPFS filesystem project is not initialized.");const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),SESSION_LOCK_WAIT_MS);try{await new Promise((resolve2,reject)=>{void environment.navigator.locks.request(`supercode-browser-filesystem-${projectId}`,{mode:"exclusive",signal:signal?AbortSignal.any([signal,controller.signal]):controller.signal},async()=>{clearTimeout(timer);resolve2();await new Promise(release2=>{releaseLock=release2})}).catch(()=>reject(signal?.aborted?signal.reason:new Error("This browser workspace is already open in another tab.")))})}finally{clearTimeout(timer)}}function validProjectId(value){if(typeof value!=="string"||!/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/u.test(value)){throw new Error("OPFS filesystem projectId is invalid.")}return value}async function projectDirectory(){if(!project)throw new Error("OPFS filesystem worker is not initialized.");return project}async function generationDirectory(name,create2){const root2=await(await projectDirectory()).getDirectoryHandle(GENERATIONS_DIRECTORY,{create:create2});return root2.getDirectoryHandle(name,{create:create2})}async function assertNoUncommittedGenerations(){let directory2;try{directory2=await(await projectDirectory()).getDirectoryHandle(GENERATIONS_DIRECTORY)}catch(cause){if(notFound2(cause))return;throw cause}for await(const _entry of directory2.entries()){throw new Error("OPFS workspace state is missing but stored generations exist. Stored data was retained.")}}async function discardGenerations(retain2){const directory2=await projectDirectory();let root2;try{root2=await directory2.getDirectoryHandle(GENERATIONS_DIRECTORY)}catch(cause){if(notFound2(cause))return;throw cause}for await(const[name]of root2.entries()){if(name!==retain2)await removeGenerationQuietly(root2,name)}}function assertWritable(){if(closing)throw new Error("This OPFS workspace is closing.");if(rewritingGeneration)throw new Error("This OPFS workspace is replacing its generation; wait for that operation before writing.");if(readOnly)throw new Error("This store is open for reading; its owner writes it.");if(mutationFailure)throw mutationFailure}async function applyMutations(mutations){applyNow(mutations)}let checkpointPending=false;let maintenanceDeferrals=0;let checkpointPrefix;let compactingLive=false;function maintain(){if(maintenanceDeferrals>0)return;const represented=checkpointPrefix&&checkpointPrefix.generation===generation&&checkpointPrefix.bytes<=logBytes?checkpointPrefix.bytes:0;if(logBytes-represented>MAX_LOG_BYTES&&!checkpointPending){checkpointPending=true;const operation=shared?environment.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive"},async()=>{if(!project||closing)return;await refreshStorage();const prefix2=checkpointPrefix;const represented2=prefix2&&prefix2.generation===generation&&prefix2.bytes<=logBytes?prefix2.bytes:0;if(logBytes-represented2>MAX_LOG_BYTES)await checkpoint()}):checkpoint();void operation.catch(cause=>console.error("The workspace's log could not be checkpointed; it is replayed at the next open.",cause)).finally(()=>{checkpointPending=false})}if(!shared&&!compactingLive&&deadBytes>SESSION_COMPACTION_BYTES&&deadBytes>liveBytes){compactingLive=true;void ownStorageOperation(compactWhileWriting).catch(cause=>console.error("The workspace could not be compacted; it keeps its generation.",cause)).finally(()=>{compactingLive=false})}}async function deferMaintenance(operation){assertWritable();maintenanceDeferrals+=1;try{return await operation()}finally{maintenanceDeferrals-=1;if(maintenanceDeferrals===0&&!closing&&project)maintain()}}function applyMutation(mutation,changes){const path3=requiredPath2(mutation.path);if(mutation.operation==="write"){if(entries.get(path3)?.type==="directory")throw new Error(`OPFS write target is a directory: ${path3}`);if(!(mutation.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const value=mutation.content;if(value.byteLength>MAX_FILE_BYTES)throw new Error(`${path3} is ${value.byteLength} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`);assertBounds(path3,value.byteLength);createParents(path3,changes);const offset2=appendPack(value);setEntry(path3,{type:mutation.symlink?"symlink":"file",mode:mutation.mode??entries.get(path3)?.mode??FILE_MODE,mtimeMs:mutation.mtimeMs??Date.now(),offset:offset2,length:value.byteLength},changes);return}if(mutation.operation==="append"){const previous=entries.get(path3);if(previous&&previous.type!=="file")throw new Error(`OPFS append target is not a file: ${path3}`);if(!(mutation.content instanceof Uint8Array))throw new Error("OPFS append requires file content.");const added=mutation.content;const length=(previous?.length??0)+added.byteLength;if(length>MAX_FILE_BYTES)throw new Error(`${path3} is ${length} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`);assertBounds(path3,length);createParents(path3,changes);const mode=mutation.mode??previous?.mode??FILE_MODE;const mtimeMs=mutation.mtimeMs??Date.now();const room=previous&&!previous.pack?previous.capacity??previous.length:0;if(projectId!==PACKAGES_STORE&&previous&&!previous.pack&&previous.length>0&&(length<=room||previous.offset+room===packBytes)){writePackAt(previous.offset+previous.length,added);setEntry(path3,{...previous,mode,mtimeMs,length,capacity:Math.max(room,length)},changes);deadBytes-=Math.max(previous.length,previous.capacity??0);rewrites-=1;rewrittenBytes-=previous.length;return}const whole=new Uint8Array(length);if(previous&&previous.length>0)whole.set(readEntry(previous),0);whole.set(added,length-added.byteLength);const offset2=appendPack(whole);const capacity=Math.min(MAX_FILE_BYTES,Math.max(length,length*2,64*1024));if(capacity>length)reservePack(offset2+capacity);setEntry(path3,{type:"file",mode,mtimeMs,offset:offset2,length,capacity},changes);return}if(mutation.operation==="write-at"){const previous=entries.get(path3);if(previous&&previous.type!=="file")throw new Error(`OPFS write target is not a file: ${path3}`);if(!(mutation.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const bytes2=mutation.content;const position=mutation.position;const held=previous?.length??0;if(bytes2.byteLength===0&&previous)return;const length=bytes2.byteLength===0?held:Math.max(held,position+bytes2.byteLength);if(length>MAX_FILE_BYTES)throw new Error(`${path3} is ${length} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`);assertBounds(path3,length);createParents(path3,changes);const mode=mutation.mode??previous?.mode??FILE_MODE;const mtimeMs=mutation.mtimeMs??Date.now();const room=previous&&!previous.pack?previous.capacity??previous.length:0;if(projectId!==PACKAGES_STORE&&previous&&!previous.pack&&held>0&&(length<=room||previous.offset+room===packBytes)){if(position>held)writePackAt(previous.offset+held,new Uint8Array(position-held));if(bytesUndo&&position<held){const end=Math.min(held,position+bytes2.byteLength);bytesUndo.push([previous.offset+position,readExtent(previous.offset+position,end-position)])}writePackAt(previous.offset+position,bytes2);setEntry(path3,{...previous,mode,mtimeMs,length,capacity:Math.max(room,length)},changes);if(length!==held){deadBytes-=Math.max(previous.length,previous.capacity??0);rewrites-=1;rewrittenBytes-=previous.length}return}const whole=new Uint8Array(length);if(previous&&held>0)whole.set(readEntry(previous),0);if(bytes2.byteLength>0)whole.set(bytes2,position);const offset2=appendPack(whole);const capacity=Math.min(MAX_FILE_BYTES,Math.max(length,length*2,64*1024));if(capacity>length)reservePack(offset2+capacity);setEntry(path3,{type:"file",mode,mtimeMs,offset:offset2,length,capacity},changes);return}if(mutation.operation==="mkdir"){createParents(path3,changes);const existing=entries.get(path3);if(existing&&existing.type!=="directory")throw new Error(`OPFS path is a file: ${path3}`);setEntry(path3,{type:"directory",mode:mutation.mode??existing?.mode??DIRECTORY_MODE,mtimeMs:mutation.mtimeMs??existing?.mtimeMs??Date.now(),offset:0,length:0},changes);return}if(mutation.operation==="remove"){removeTree3(path3,changes);if(storeRoots().includes(path3)){setEntry(path3,{type:"directory",mode:DIRECTORY_MODE,mtimeMs:Date.now(),offset:0,length:0},changes)}return}if(mutation.operation==="link"){linkShared(path3,sharedPath(mutation.source),changes);return}if(mutation.operation==="rename"){renameTree(path3,requiredPath2(mutation.destination),changes);return}const entry=entries.get(path3);if(!entry)throw new Error(`OPFS metadata target does not exist: ${path3}`);setEntry(path3,{...entry,mode:mutation.mode??entry.mode,mtimeMs:mutation.mtimeMs??entry.mtimeMs},changes)}function setEntry(path3,entry,changes){const previous=entries.get(path3);if(mutationUndo&&!mutationUndo.has(path3))mutationUndo.set(path3,previous);const sameExtent=previous!==void 0&&previous.type===entry.type&&previous.offset===entry.offset&&previous.length===entry.length&&previous.pack===entry.pack;if(previous&&!sameExtent){forget(previous,path3);if(previous.type!=="directory"&&entry.type!=="directory"&&previous.length>0&&!previous.pack){rewrites+=1;rewrittenBytes+=previous.length}}entries.set(path3,entry);attach(path3);if(!sameExtent){if(entry.pack){linked+=1;linkedBytes+=entry.length}else liveBytes+=entry.length}changes.push([path3,entry])}function attach(path3){const parent2=parentPath(path3);if(parent2===path3)return;children.mutable(parent2).add(path3.slice(parent2.length+1))}function detach(path3){const parent2=parentPath(path3);if(children.get(parent2)?.has(path3.slice(parent2.length+1)))children.mutable(parent2).delete(path3.slice(parent2.length+1));children.delete(path3)}function rebuildChildren(){children=new LocalChildren;for(const path3 of entries.keys())attach(path3)}function descendants(prefix2){const found=[];const visit=path3=>{const entry=entries.get(path3);if(!entry)return;found.push([path3,entry]);const names2=children.get(path3);if(names2)for(const name of names2)visit(`${path3}/${name}`)};visit(prefix2);return found}function forget(previous,path3){if(previous.pack){linked-=1;linkedBytes-=previous.length;return}liveBytes-=previous.length;deadBytes+=Math.max(previous.length,previous.capacity??0)}function deleteEntry(path3,changes){const previous=entries.get(path3);if(!previous)return;if(mutationUndo&&!mutationUndo.has(path3))mutationUndo.set(path3,previous);entries.delete(path3);detach(path3);forget(previous,path3);changes.push([path3,null])}function linkShared(path3,source,changes){const packages2=options.packages;if(!packages2)throw new Error("This store has no shared package store to link from.");const prefix2=sharedPath(source);const files=packages2.descendants(prefix2);if(files.length===0)throw new Error(`The shared package store does not hold ${source}.`);createParents(path3,changes);removeTree3(path3,changes);assertEntryCount(entries.size+files.length);for(const[candidate,entry]of files){const target=candidate===prefix2?path3:`${path3}${candidate.slice(prefix2.length)}`;setEntry(target,entry.type==="directory"?{type:"directory",mode:entry.mode,mtimeMs:entry.mtimeMs,offset:0,length:0}:{type:entry.type,mode:entry.mode,mtimeMs:entry.mtimeMs,offset:entry.offset,length:entry.length,pack:PACKAGES_STORE},changes)}}function createParents(path3,changes){const above=parentPath(path3);if(above!==path3&&entries.get(above)?.type==="directory"){assertEntryCount(entries.size+(entries.has(path3)?0:1));return}const missing=[];let current3=rootOf(path3)??storeRoots()[0];if(!entries.has(current3))missing.push(current3);if(path3!==current3){for(const segment of segmentsOf(relativePath3(parentPath(path3)))){current3=`${current3}/${segment}`;const existing=entries.get(current3);if(existing&&existing.type!=="directory")throw new Error(`OPFS path parent is a file: ${current3}`);if(!existing)missing.push(current3)}}assertEntryCount(entries.size+missing.length+(entries.has(path3)?0:1));const now=Date.now();for(const directory2 of missing){setEntry(directory2,{type:"directory",mode:DIRECTORY_MODE,mtimeMs:now,offset:0,length:0},changes)}}function removeTree3(path3,changes){for(const[candidate]of descendants(path3))deleteEntry(candidate,changes)}function renameTree(source,destination,changes){if(source===destination)return;if(destination.startsWith(`${source}/`))throw new Error("An OPFS rename cannot move a directory into itself.");const moved=descendants(source);if(moved.length===0){if(entries.has(destination))return;throw new Error(`OPFS rename source does not exist: ${source}`)}createParents(destination,changes);removeTree3(destination,changes);for(const[path3]of moved)deleteEntry(path3,changes);for(const[path3,entry]of moved)setEntry(`${destination}${path3.slice(source.length)}`,entry,changes);assertEntryCount(entries.size)}function sharedPath(value){if(typeof value!=="string"||!value.startsWith(`${PACKAGES_ROOT}/`)||value.includes("\0")||value.length>4096){throw new Error("Invalid shared store path.")}segmentsOf(value.slice(PACKAGES_ROOT.length+1));return value}function storeRoots(){return projectId===PACKAGES_STORE?[PACKAGES_ROOT]:PROJECT_ROOTS}function rootOf(path3){return storeRoots().find(root2=>path3===root2||path3.startsWith(`${root2}/`))}function maximumBytes(){if(explicitBytes!==void 0)return explicitBytes;heldAtOpen??=liveBytes;return Math.min(Number.MAX_SAFE_INTEGER,heldAtOpen+originRoom)}function boundSource(){return explicitBytes!==void 0?"its configured limit":"the origin's storage quota"}function assertBounds(path3,bytes2){const previous=entries.get(path3);const replaced=previous&&!previous.pack?previous.length:0;const limit=maximumBytes();if(liveBytes-replaced+bytes2>limit){const holder=shared?"the origin's shared packages":"the project's own files";throw new Error(`OPFS workspace exceeds ${boundSource()}: writing ${path3} (${bytes2} bytes) would take ${holder} past ${limit} bytes (${liveBytes} bytes held, ${replaced} replaced).`)}}function assertEntryCount(count){if(count>maximumEntries)throw new Error("OPFS workspace exceeds its entry limit.")}function assertWorkspaceQuota(){assertEntryCount(entries.size);const limit=maximumBytes();if(liveBytes>limit)throw new Error(`OPFS workspace exceeds ${boundSource()}: ${shared?"the origin's shared packages":"the project's own files"} hold ${liveBytes} bytes, past ${limit}.`)}function writePackAt(offset2,value){const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");let written=0;while(written<value.byteLength){const count=access.write(value.subarray(written),{at:offset2+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}packBytes=Math.max(packBytes,offset2+value.byteLength)}function reservePack(end){const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");if(end<=packBytes)return;access.truncate(end);packBytes=end}function appendPack(value){const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");const offset2=packBytes;let written=0;while(written<value.byteLength){const count=access.write(value.subarray(written),{at:offset2+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}packBytes=offset2+value.byteLength;return offset2}function assertStored(log){const pack=packAccess;if(pack.getSize()>=packBytes&&log.getSize()>=logBytes)return;pack.flush();log.flush();const packSize=pack.getSize(),logSize=log.getSize();if(packSize>=packBytes&&logSize>=logBytes)return;throw Object.assign(new Error(`This browser is keeping less than the tab wrote (the store's pack holds ${packSize} of ${packBytes} bytes, its log ${logSize} of ${logBytes}): its storage is full, as a private window's is well below its quota.`),{name:"QuotaExceededError",code:"ENOSPC"})}function commit(changes,options2={}){const access=logAccess;if(!access||!packAccess)throw new Error("OPFS filesystem worker is not initialized.");if(changes.length===0)return;const body=encoder4.encode(JSON.stringify({packBytes,changes}));if(body.byteLength>MAX_RECORD_BYTES)throw new Error("An OPFS workspace index record exceeds its size limit.");const record=new Uint8Array(RECORD_HEADER_BYTES+body.byteLength);const view=new DataView(record.buffer);view.setUint32(0,body.byteLength,true);view.setUint32(4,fingerprint2(body),true);record.set(body,RECORD_HEADER_BYTES);let written=0;while(written<record.byteLength){const count=access.write(record.subarray(written),{at:logBytes+written});if(count<=0)throw new Error("The OPFS workspace index log could not be written completely.");written+=count}logBytes+=record.byteLength;assertStored(access);if(options2.publish!==false)publishLog();if(performance.now()-lastFlushAt>=FLUSH_WINDOW_MS)flushStorage();else if(flushTimer===void 0)flushTimer=setTimeout(flushStorage,FLUSH_WINDOW_MS)}function flushStorage(){if(flushTimer!==void 0){clearTimeout(flushTimer);flushTimer=void 0}if(mutationFailure)throw mutationFailure;const startedAt=performance.now();packAccess?.flush();logAccess?.flush();lastFlushAt=performance.now();flushes+=1;flushMs+=lastFlushAt-startedAt}function checkpoint(){const previous=checkpointTail;const operation=ownStorageOperation(()=>previous.catch(()=>void 0).then(checkpointStorage));checkpointTail=operation;return operation}async function checkpointStorage(){assertWritable();if(!generation)return;const checkpointGeneration=generation;const access=logAccess;const directory2=await generationDirectory(checkpointGeneration,false);if(!access||access!==logAccess||checkpointGeneration!==generation){throw new Error("OPFS workspace changed generations before its checkpoint could start.")}flushStorage();const checkpointBytes=logBytes;await writeIndexAtomically(directory2,entries,{access,bytes:checkpointBytes,packBytes});if(checkpointGeneration===generation)checkpointPrefix={generation:checkpointGeneration,bytes:checkpointBytes};if(access===logAccess&&checkpointGeneration===generation&&checkpointBytes===logBytes){beginTransition();try{access.truncate(0);access.flush();logBytes=0;checkpointPrefix={generation:checkpointGeneration,bytes:0}}finally{endTransition()}}}function writeGeneration(snapshot){return rewriteGeneration(()=>writeGenerationContents(validateSnapshot(snapshot)))}async function writeGenerationContents(snapshot){const next2=crypto.randomUUID();const directory2=await generationDirectory(next2,true);const handle=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(handle,"store");const index2=new Map;let cursor=0;try{for(const entry of snapshot.files){let offset2=0;let length=0;if(entry.type!=="directory"){const value=new Uint8Array(snapshot.pack,entry.offset??0,entry.length??0);offset2=cursor;length=value.byteLength;let written=0;while(written<length){const count=access.write(value.subarray(written),{at:offset2+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}cursor+=length}index2.set(entry.path,{type:entry.type,mode:entry.mode??(entry.type==="directory"?DIRECTORY_MODE:FILE_MODE),mtimeMs:entry.mtimeMs??Date.now(),offset:offset2,length})}for(const root2 of storeRoots()){if(!index2.has(root2))index2.set(root2,{type:"directory",mode:DIRECTORY_MODE,mtimeMs:Date.now(),offset:0,length:0})}assertEntryCount(index2.size);access.truncate(cursor);access.flush()}finally{access.close()}const prepared=await writeIndexAtomically(directory2,index2);await commitGeneration(next2,directory2,index2,cursor,prepared)}async function compact(){await retain(()=>true)}async function compactWhileWriting(){let transitioning=false;let named=false;let stayed=false;try{await compactWhileWritingIn(()=>{transitioning=true},()=>{named=true},()=>{stayed=true})}finally{if(transitioning&&(named||stayed))endTransition();else if(transitioning)retireClock()}}async function compactWhileWritingIn(began,named,stayed){const next2=crypto.randomUUID();const directory2=await generationDirectory(next2,true);const pack=await openSyncAccess(await directory2.getFileHandle(PACK_FILE,{create:true}),"store");let log;let switched=false;try{log=await openSyncAccess(await directory2.getFileHandle(LOG_FILE,{create:true}),"record of changes");log.truncate(0);const buffer2=new Uint8Array(COPY_BUFFER_BYTES);let cursor=0;const copy2=entry=>{if(entry.pack)return{...entry};if(entry.type==="directory"||entry.length===0)return{...entry,offset:0,length:0};const source=packAccess;if(!source)throw new Error("OPFS filesystem worker is not initialized.");const offset2=cursor;let copied=0;while(copied<entry.length){const span=Math.min(buffer2.byteLength,entry.length-copied);const chunk=buffer2.subarray(0,span);imageReader?.ensure(entry.offset+copied,span);if(source.read(chunk,{at:entry.offset+copied})!==span)throw new Error("An OPFS workspace file could not be read completely.");let written=0;while(written<span){const count=pack.write(chunk.subarray(written),{at:offset2+copied+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}copied+=span}cursor+=entry.length;const{capacity:_room,...extent}=entry;return{...extent,offset:offset2}};const copies=new Map;let sliceStart=performance.now();for(const[path3,entry]of[...entries]){if(closing||rewritingGeneration)return;if(entries.get(path3)!==entry)continue;copies.set(entry,copy2(entry));if(performance.now()-sliceStart>8){await new Promise(resolve2=>setTimeout(resolve2,0));sliceStart=performance.now()}}if(closing||rewritingGeneration||!packAccess||!logAccess)return;beginTransition();began();const index2=new Map;for(const[path3,entry]of entries)index2.set(path3,copies.get(entry)??copy2(entry));pack.truncate(cursor);pack.flush();log.flush();flushStorage();const previous={pack:packAccess,log:logAccess};packAccess=pack;logAccess=log;logBytes=0;entries=index2;rebuildChildren();packBytes=cursor;generation=next2;generationHandle=directory2;measureBytes();switched=true;const document2=new Map(index2);try{previous.pack.close()}finally{previous.log.close()}try{await writeIndexAtomically(directory2,document2);const state={storageVersion:4,generation:next2,initializedAt:Date.now()};await writeJsonAtomically(await projectDirectory(),STATE_FILE,state)}catch(cause){mutationFailure=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});throw mutationFailure}named();await discardGenerations(next2)}finally{if(!switched){stayed();try{pack.close()}finally{log?.close()}await removeGenerationQuietly(await(await projectDirectory()).getDirectoryHandle(GENERATIONS_DIRECTORY),next2)}}}async function remapLinks(moved){assertWritable();beginTransition();try{await remapLinksIn(moved)}finally{endTransition()}}async function remapLinksIn(moved){let changed=false;for(const[path3,entry]of entries){if(!entry.pack||entry.length===0)continue;const offset2=moved.get(entry.offset);if(offset2===void 0)throw new Error(`The shared store no longer holds the bytes of ${path3}.`);if(offset2===entry.offset)continue;entries.set(path3,{...entry,offset:offset2});changed=true}if(changed)await checkpoint()}function retain(keep){return rewriteGeneration(()=>retainGeneration(keep))}async function retainGeneration(keep){const source=packAccess;if(!source)throw new Error("OPFS filesystem worker is not initialized.");const moved=new Map;const next2=crypto.randomUUID();const directory2=await generationDirectory(next2,true);const handle=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(handle,"store");const index2=new Map;const buffer2=new Uint8Array(COPY_BUFFER_BYTES);let cursor=0;try{for(const[path3,entry]of entries){if(!keep(path3,entry))continue;if(entry.pack){index2.set(path3,{...entry});continue}if(entry.type==="directory"||entry.length===0){index2.set(path3,{...entry,offset:0,length:0});continue}const offset2=cursor;moved.set(entry.offset,offset2);let copied=0;while(copied<entry.length){const span=Math.min(buffer2.byteLength,entry.length-copied);const chunk=buffer2.subarray(0,span);imageReader?.ensure(entry.offset+copied,span);if(source.read(chunk,{at:entry.offset+copied})!==span){throw new Error("An OPFS workspace file could not be read completely.")}let written=0;while(written<span){const count=access.write(chunk.subarray(written),{at:offset2+copied+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}copied+=span}cursor+=entry.length;const{capacity:_room,...extent}=entry;index2.set(path3,{...extent,offset:offset2,length:entry.length})}access.truncate(cursor);access.flush()}finally{access.close()}const prepared=await writeIndexAtomically(directory2,index2);await commitGeneration(next2,directory2,index2,cursor,prepared);return moved}async function commitGeneration(name,directory2,index2,bytes2,prepared,rangesDigest){beginTransition();try{await commitGenerationIn(name,directory2,index2,bytes2,prepared,rangesDigest)}finally{endTransition()}}async function commitGenerationIn(name,directory2,index2,bytes2,prepared,rangesDigest){const journal=await directory2.getFileHandle(LOG_FILE,{create:true});const journalAccess=await openSyncAccess(journal,"record of changes");try{journalAccess.truncate(0);journalAccess.flush()}finally{journalAccess.close()}const state={storageVersion:rangesDigest?5:4,generation:name,initializedAt:Date.now(),...rangesDigest?{imageRanges:rangesDigest}:{}};await writeJsonAtomically(await projectDirectory(),STATE_FILE,state);closeGenerationHandles();generation=name;generationInitializedAt=state.initializedAt;imageRangesDigest=rangesDigest;if(prepared){const base=new SharedIndex(prepared.index);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);seedCache=void 0}else{entries=index2;rebuildChildren()}packBytes=bytes2;generationHandle=directory2;await openGenerationHandles(directory2);if(prepared){({liveBytes,linked,linkedBytes}=prepared);deadBytes=Math.max(0,packBytes-liveBytes)}else measureBytes();if(!shared)await discardGenerations(name)}async function installPreparedImage(prepared,json,binary,suppliedRanges,verified=false){assertWritable();if(!shared||projectId!==PACKAGES_STORE)throw new Error("Only the shared package store can reserve immutable image extents.");if(packBytes!==0||[...entries.values()].some(entry=>entry.type!=="directory"))return false;const ranges=validateImageRanges(suppliedRanges);if(ranges.bytes!==prepared.packBytes||prepared.entries>MAX_ENTRIES||prepared.liveBytes>prepared.packBytes||json.byteLength!==prepared.json.raw||binary.byteLength!==prepared.binary.raw||!await matchesDigest(json,prepared.json.sha256,verified)||!await matchesDigest(binary,prepared.binary.sha256,verified)){throw new Error("The image's prepared metadata does not match its document.")}const newline=json.subarray(0,4096).indexOf(10);if(newline<0)throw new Error("The prepared index has no bounded retained header.");const retained=JSON.parse(`${decoder5.decode(json.subarray(0,newline-1))}}`);const measures={packBytes:prepared.packBytes,liveBytes:prepared.liveBytes,linked:0,linkedBytes:0};const header=retained.retainedIndex;if(header.version!==1||header.digest!==await retainedIndexDigestOf(prepared.binary.sha256,measures)||header.packBytes!==measures.packBytes||header.liveBytes!==measures.liveBytes||header.linked!==0||header.linkedBytes!==0){throw new Error("The prepared index's retained measures are inconsistent.")}const index2=new SharedArrayBuffer(binary.byteLength);new Uint8Array(index2).set(binary);if(new SharedIndex(index2).entryCount!==prepared.entries)throw new Error("The prepared index has the wrong number of entries.");return rewriteGeneration(async()=>{const name=crypto.randomUUID();const directory2=await generationDirectory(name,true);const pack=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(pack,"immutable image reservation");try{access.truncate(prepared.packBytes);access.flush()}finally{access.close()}const rangeBytes=encoder4.encode(JSON.stringify(ranges));await writeBytesAtomically(directory2,IMAGE_RANGES_FILE,rangeBytes);await writeBytesAtomically(directory2,RETAINED_INDEX_FILE,binary);await writeBytesAtomically(directory2,INDEX_FILE,json);await commitGeneration(name,directory2,new Map,prepared.packBytes,{index:index2,...measures},await indexDigest(rangeBytes));return true})}async function installPreparedProject(prepared,json,binary,verified=false,imageInstalled){assertWritable();if(shared||!options.packages||!imageInstalled&&!options.packages.deferredImage)throw new Error("Prepared project paths require a verified shared image.");if(packBytes!==0||[...entries.values()].some(entry=>entry.type!=="directory"))return false;if(json.byteLength!==prepared.json.raw||binary.byteLength!==prepared.binary.raw||!await matchesDigest(json,prepared.json.sha256,verified)||!await matchesDigest(binary,prepared.binary.sha256,verified)){throw new Error("The image's prepared project does not match its descriptor.")}const newline=json.subarray(0,4096).indexOf(10);if(newline<0)throw new Error("The prepared project has no bounded retained header.");const header=JSON.parse(`${decoder5.decode(json.subarray(0,newline-1))}}`).retainedIndex;const measures={packBytes:0,liveBytes:0,linked:prepared.linked,linkedBytes:prepared.linkedBytes};if(header.version!==1||header.digest!==await retainedIndexDigestOf(prepared.binary.sha256,measures)||header.packBytes!==0||header.liveBytes!==0||header.linked!==prepared.linked||header.linkedBytes!==prepared.linkedBytes){throw new Error("The prepared project's retained measures are inconsistent.")}const index2=new SharedArrayBuffer(binary.byteLength);new Uint8Array(index2).set(binary);if(new SharedIndex(index2).entryCount!==prepared.entries||prepared.entries>maximumEntries)throw new Error("The prepared project has invalid entry bounds.");return rewriteGeneration(async()=>{const name=crypto.randomUUID();const directory2=await generationDirectory(name,true);const pack=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(pack,"prepared project");try{access.truncate(0);access.flush()}finally{access.close()}await writeBytesAtomically(directory2,RETAINED_INDEX_FILE,binary);await writeBytesAtomically(directory2,INDEX_FILE,json);if(imageInstalled&&!await imageInstalled)return false;if(!options.packages?.deferredImage)throw new Error("Prepared project paths require a verified shared image.");await commitGeneration(name,directory2,new Map,0,{index:index2,...measures});return true})}async function readSnapshot(){if(closing)throw new Error("This OPFS workspace is closing.");if(!packAccess)throw new Error("OPFS filesystem worker is not initialized.");const files=[];const paths=[...entries.keys()].sort((left,right)=>depth4(left)-depth4(right)||(left<right?-1:1));let total=0;for(const entry of entries.values())if(entry.type!=="directory")total+=entry.length;const pack=new ArrayBuffer(total);const view=new Uint8Array(pack);let cursor=0;for(const path3 of paths){const entry=entries.get(path3);if(entry.type==="directory"){files.push({path:path3,type:"directory",mode:entry.mode,mtimeMs:entry.mtimeMs});continue}if(entry.length>0)view.set(readEntry(entry),cursor);files.push({path:path3,type:entry.type,offset:cursor,length:entry.length,mode:entry.mode,mtimeMs:entry.mtimeMs});cursor+=entry.length}for(const root2 of[...storeRoots()].reverse()){if(!entries.has(root2))files.unshift({path:root2,type:"directory",mode:DIRECTORY_MODE,mtimeMs:Date.now()})}return validateSnapshot({files,pack})}async function writeJsonAtomically(directory2,name,value){await writeBytesAtomically(directory2,name,encoder4.encode(JSON.stringify(value)))}async function writeBytesAtomically(directory2,name,bytes2){const staging=await(await projectDirectory()).getDirectoryHandle(STAGING_DIRECTORY,{create:true});const temporaryName=crypto.randomUUID();const handle=await staging.getFileHandle(temporaryName,{create:true});const access=await openSyncAccess(handle,"index");try{let written=0;while(written<bytes2.byteLength){const count=access.write(bytes2.subarray(written),{at:written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}access.truncate(bytes2.byteLength);access.flush()}finally{access.close()}try{await handle.move(directory2,name)}finally{await removeEntry(staging,temporaryName,false)}}const RETAINED_INDEX_FILE="index.shared";async function indexDigest(bytes2){const hash2=await crypto.subtle.digest("SHA-256",bytes2);return Array.from(new Uint8Array(hash2),byte=>byte.toString(16).padStart(2,"0")).join("")}async function matchesDigest(bytes2,digest,verified){return verified||await indexDigest(bytes2)===digest}function retainedIndexDigestOf(binaryDigest,measures){const{packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,journalPrefix}=measures;return indexDigest(encoder4.encode(`${JSON.stringify({packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,...journalPrefix?{journalPrefix}:{}})}:${binaryDigest}`))}async function retainedIndexDigest(bytes2,measures){const{packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,journalPrefix}=measures;return indexDigest(encoder4.encode(`${JSON.stringify({packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,...journalPrefix?{journalPrefix}:{}})}:${await indexDigest(bytes2)}`))}async function writeIndexAtomically(directory2,index2,journal){const document2=indexDocument(index2);if(typeof SharedArrayBuffer==="undefined"||index2.size<1e4){await writeJsonAtomically(directory2,INDEX_FILE,document2);return}const snapshot=new Map(document2.entries);const names2=new Map;const measure={packBytes:journal?.packBytes??0,liveBytes:0,linked:0,linkedBytes:0};for(const[path3,entry]of snapshot){const parent2=parentPath(path3);if(parent2!==path3){let children2=names2.get(parent2);if(!children2){children2=new Set;names2.set(parent2,children2)}children2.add(path3.slice(parent2.length+1))}if(entry.pack){measure.linked+=1;measure.linkedBytes+=entry.length}else{measure.liveBytes+=entry.length;measure.packBytes=Math.max(measure.packBytes,entry.offset+entry.length)}}let encoded;try{encoded=encodeSharedIndex(snapshot,names2)}catch{await writeJsonAtomically(directory2,INDEX_FILE,document2);return}const json=JSON.stringify(document2.entries);const prefixBytes=journal?new Uint8Array(journal.bytes):void 0;if(prefixBytes&&journal.access.read(prefixBytes,{at:0})!==prefixBytes.byteLength){throw new Error("The checkpoint's journal prefix could not be read completely.")}const journalPrefix=prefixBytes?{bytes:prefixBytes.byteLength,digest:await indexDigest(prefixBytes)}:void 0;const bytes2=new Uint8Array(encoded).slice();const retained={version:journalPrefix?2:1,digest:await retainedIndexDigest(bytes2,{...measure,...journalPrefix?{journalPrefix}:{}}),...measure,...journalPrefix?{journalPrefix}:{}};try{await writeBytesAtomically(directory2,RETAINED_INDEX_FILE,bytes2)}catch{await writeJsonAtomically(directory2,INDEX_FILE,{entries:JSON.parse(json)});return}await writeBytesAtomically(directory2,INDEX_FILE,encoder4.encode(`{"retainedIndex":${JSON.stringify(retained)},
|
|
5893
5893
|
"entries":${json}}`));return{index:encoded,...measure}}async function readRetainedIndex(directory2){if(typeof SharedArrayBuffer==="undefined")return void 0;try{const handle=await directory2.getFileHandle(INDEX_FILE);const access=await openSyncAccess(handle,"index");let prefix2;try{const bytes3=new Uint8Array(Math.min(512,access.getSize()));const count=access.read(bytes3,{at:0});prefix2=decoder5.decode(bytes3.subarray(0,count))}finally{access.close()}const firstLine=prefix2.split("\n",1)[0];if(!firstLine.startsWith('{"retainedIndex":')||!firstLine.endsWith(","))return void 0;const retained=JSON.parse(firstLine.slice(0,-1)+"}").retainedIndex;if(retained.version!==1&&retained.version!==2||!/^[a-f0-9]{64}$/u.test(retained.digest)||![retained.packBytes,retained.liveBytes,retained.linked,retained.linkedBytes].every(n8=>Number.isSafeInteger(n8)&&n8>=0))return void 0;if(retained.version===1&&retained.journalPrefix!==void 0)return void 0;if(retained.version===2&&(!retained.journalPrefix||!Number.isSafeInteger(retained.journalPrefix.bytes)||retained.journalPrefix.bytes<0||!/^[a-f0-9]{64}$/u.test(retained.journalPrefix.digest)))return void 0;const binary=await directory2.getFileHandle(RETAINED_INDEX_FILE);const reader=await openSyncAccess(binary,"index");let bytes2;try{const size=reader.getSize();if(size>256*1024*1024)return void 0;bytes2=new Uint8Array(size);if(reader.read(bytes2,{at:0})!==size)return void 0}finally{reader.close()}if(await retainedIndexDigest(bytes2,retained)!==retained.digest)return void 0;const index2=new SharedArrayBuffer(bytes2.byteLength);new Uint8Array(index2).set(bytes2);const base=new SharedIndex(index2);assertEntryCount(base.entryCount);return{...retained,index:index2}}catch{return void 0}}async function verifiedJournalPrefix(retained){const prefix2=retained.journalPrefix;if(!prefix2||!logAccess||!packAccess||prefix2.bytes>logAccess.getSize()||retained.packBytes>packAccess.getSize())return 0;const bytes2=new Uint8Array(prefix2.bytes);if(logAccess.read(bytes2,{at:0})!==bytes2.byteLength)return 0;return await indexDigest(bytes2)===prefix2.digest?prefix2.bytes:0}async function readJson(directory2,name){let handle;try{handle=await directory2.getFileHandle(name)}catch(cause){if(notFound2(cause))return;throw cause}let text;if(readOnly){text=await(await handle.getFile()).text();try{return JSON.parse(text)}catch(cause){throw new Error(`Invalid OPFS workspace metadata (${name}). Stored data was retained.`,{cause})}}const access=await openSyncAccess(handle,"index");try{const size=access.getSize();const value=new Uint8Array(size);if(size>0&&access.read(value,{at:0})!==size){throw new Error("An OPFS workspace file could not be read completely.")}text=decoder5.decode(value)}finally{access.close()}try{return JSON.parse(text)}catch(cause){throw new Error(`Invalid OPFS workspace metadata (${name}). Stored data was retained.`,{cause})}}async function removeEntry(directory2,name,recursive){try{await directory2.removeEntry(name,{recursive})}catch(cause){if(!notFound2(cause))throw cause}}async function removeGenerationQuietly(root2,name){try{await root2.removeEntry(name,{recursive:true})}catch{}}function validateMutation(candidate){if(!candidate||typeof candidate!=="object"||Array.isArray(candidate))throw new Error("Invalid OPFS filesystem mutation.");if(candidate.operation!=="write"&&candidate.operation!=="append"&&candidate.operation!=="write-at"&&candidate.operation!=="mkdir"&&candidate.operation!=="remove"&&candidate.operation!=="rename"&&candidate.operation!=="metadata"&&candidate.operation!=="link"){throw new Error("Invalid OPFS filesystem mutation.")}requiredPath2(candidate.path);if(candidate.operation==="rename")requiredPath2(candidate.destination);if((candidate.operation==="write"||candidate.operation==="append"||candidate.operation==="write-at")&&!(candidate.content instanceof Uint8Array)){throw new Error("Invalid OPFS file content.")}if(candidate.operation==="write-at"&&(!Number.isSafeInteger(candidate.position)||candidate.position<0)){throw new Error("Invalid OPFS write position.")}validateEntryMetadata(candidate);return candidate}function validateMutationBatch(candidate){if(!Array.isArray(candidate)||candidate.length===0||candidate.length>128){throw new Error("Invalid OPFS filesystem mutation batch.")}return candidate.map(mutation=>validateMutation(mutation))}function validateSnapshot(candidate){if(!candidate||!Array.isArray(candidate.files)||candidate.files.length>maximumEntries||!(candidate.pack instanceof ArrayBuffer)){throw new Error("Invalid OPFS workspace snapshot.")}const paths=new Set;const types3=new Map(storeRoots().map(root2=>[root2,"directory"]));let bytes2=0;for(const entry of candidate.files){if(!entry||typeof entry!=="object")throw new Error("Invalid OPFS workspace snapshot entry.");requiredPath2(entry.path);if(entry.type!=="file"&&entry.type!=="directory"&&entry.type!=="symlink"||paths.has(entry.path)){throw new Error("Invalid or duplicate OPFS workspace entry.")}paths.add(entry.path);types3.set(entry.path,entry.type);if(storeRoots().includes(entry.path)&&entry.type!=="directory")throw new Error("The OPFS workspace root must be a directory.");if(entry.type!=="directory"){const offset2=entry.offset??0;const length=entry.length??0;if(!Number.isSafeInteger(offset2)||!Number.isSafeInteger(length)||offset2<0||length<0||length>MAX_FILE_BYTES||offset2+length>candidate.pack.byteLength){throw new Error("Invalid OPFS workspace file.")}bytes2+=length;if(bytes2>maximumBytes())throw new Error(`OPFS workspace exceeds ${boundSource()}.`)}else if((entry.offset??0)!==0||(entry.length??0)!==0){throw new Error("An OPFS workspace directory cannot contain file bytes.")}validateEntryMetadata(entry)}assertEntryCount(types3.size);for(const entry of candidate.files){if(!storeRoots().includes(entry.path)&&types3.get(parentPath(entry.path))!=="directory"){throw new Error(`An OPFS workspace snapshot has no directory parent for ${entry.path}.`)}}return candidate}function validateEntryMetadata(value){if(value.mode!==void 0&&(!Number.isSafeInteger(value.mode)||value.mode<0||value.mode>4095)){throw new Error("Invalid OPFS file mode.")}if(value.mtimeMs!==void 0&&(typeof value.mtimeMs!=="number"||!Number.isFinite(value.mtimeMs)||value.mtimeMs<0)){throw new Error("Invalid OPFS modification time.")}}function indexDocument(index2){return{entries:[...index2]}}function readIndex(value){const index2=new Map;if(value===void 0)throw new Error("The committed OPFS workspace index is missing. Stored data was retained.");if(!value||typeof value!=="object"||!Array.isArray(value.entries)){throw new Error("Invalid OPFS workspace index.")}const rows=value.entries;assertEntryCount(rows.length);for(const row of rows){if(!Array.isArray(row)||row.length!==2)throw new Error("Invalid OPFS workspace index entry.");const path3=requiredPath2(row[0]);if(index2.has(path3))throw new Error("Duplicate OPFS workspace index entry.");index2.set(path3,readIndexEntry(row[1]))}return index2}function readIndexEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid OPFS workspace index entry.");const candidate=value;if(candidate.type!=="file"&&candidate.type!=="directory"&&candidate.type!=="symlink")throw new Error("Invalid OPFS workspace index entry.");validateEntryMetadata(candidate);if(candidate.mode===void 0||candidate.mtimeMs===void 0)throw new Error("Invalid OPFS workspace index entry.");if(!Number.isSafeInteger(candidate.offset)||candidate.offset<0||!Number.isSafeInteger(candidate.length)||candidate.length<0||candidate.length>MAX_FILE_BYTES){throw new Error("Invalid OPFS workspace index extent.")}if(candidate.pack!==void 0&&candidate.pack!==PACKAGES_STORE)throw new Error("Invalid OPFS workspace index entry.");return{type:candidate.type,mode:candidate.mode,mtimeMs:candidate.mtimeMs,offset:candidate.offset,length:candidate.length,...candidate.pack?{pack:candidate.pack}:{}}}function readIndexRecord(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid OPFS workspace index record.");const candidate=value;if(!Number.isSafeInteger(candidate.packBytes)||candidate.packBytes<0||!Array.isArray(candidate.changes)){throw new Error("Invalid OPFS workspace index record.")}const changes=[];for(const row of candidate.changes){if(!Array.isArray(row)||row.length!==2)throw new Error("Invalid OPFS workspace index record.");changes.push([requiredPath2(row[0]),row[1]===null?null:readIndexEntry(row[1])])}return{packBytes:candidate.packBytes,changes}}function readStorageState(value){if(value===void 0)return;if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid OPFS workspace state. Stored data was retained.");const candidate=value;if(candidate.storageVersion!==4&&candidate.storageVersion!==5||candidate.storageVersion===5&&(typeof candidate.imageRanges!=="string"||!/^[a-f0-9]{64}$/u.test(candidate.imageRanges))||candidate.storageVersion===4&&candidate.imageRanges!==void 0||typeof candidate.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(candidate.generation)||typeof candidate.initializedAt!=="number"||!Number.isFinite(candidate.initializedAt)){throw new Error("Invalid or unsupported OPFS workspace state. Stored data was retained.")}return candidate}function requiredPath2(value){if(typeof value!=="string"||rootOf(value)===void 0||value.includes("\0")||value.length>4096){throw new Error("Invalid OPFS workspace path.")}relativePath3(value);return value}function relativePath3(path3){const root2=rootOf(path3);if(root2===void 0)throw new Error("Invalid OPFS workspace path.");const relative2=path3===root2?"":path3.slice(root2.length+1);segmentsOf(relative2);return relative2}function segmentsOf(relative2){const segments=relative2===""?[]:relative2.split("/");if(segments.some(segment=>!segment||segment==="."||segment===".."||segment.includes("\0"))){throw new Error("Invalid OPFS workspace path segment.")}return segments}function parentPath(path3){const parent2=path3.slice(0,path3.lastIndexOf("/"));return parent2===""||rootOf(parent2)===void 0?rootOf(path3)??path3:parent2}function depth4(path3){let segments=1;for(let index2=0;index2<path3.length;index2+=1)if(path3.charCodeAt(index2)===47)segments+=1;return segments}function notFound2(cause){return cause instanceof DOMException&&cause.name==="NotFoundError"}function fingerprint2(value){let hash2=2166136261;for(let index2=0;index2<value.byteLength;index2+=1){hash2^=value[index2];hash2=Math.imul(hash2,16777619)}return hash2>>>0}if(typeof addEventListener==="function")addEventListener("close",()=>{packAccess?.flush();logAccess?.flush();closeGenerationHandles();releaseLock?.()});function applyNow(mutations,options2={}){assertWritable();if(mutationUndo)throw new Error("An OPFS mutation batch cannot be nested.");for(const mutation of mutations)validateMutation(mutation);if(!mutations.length)return[];return runBatch(changes=>{for(const mutation of mutations)applyMutation(mutation,changes)},options2)}function applyExtentsNow(bytes2,files,options2={}){assertWritable();if(mutationUndo)throw new Error("An OPFS mutation batch cannot be nested.");for(const file2 of files){requiredPath2(file2.path);if(file2.type!=="file"&&file2.type!=="directory"&&file2.type!=="symlink")throw new Error(`OPFS extent ${file2.path} has no valid type.`);if(file2.type==="directory")continue;const{offset:offset2,length}=file2;if(offset2===void 0||length===void 0||!Number.isSafeInteger(offset2)||!Number.isSafeInteger(length)||offset2<0||length<0||offset2+length>bytes2.byteLength)throw new Error(`OPFS extent ${file2.path} lies outside its bytes.`);if(length>MAX_FILE_BYTES)throw new Error(`${file2.path} is ${length} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`)}if(!files.length)return[];return runBatch(changes=>{const base=bytes2.byteLength>0?appendPack(bytes2):packBytes;for(const file2 of files){const path3=requiredPath2(file2.path);createParents(path3,changes);const existing=entries.get(path3);if(file2.type==="directory"){if(existing&&existing.type!=="directory")throw new Error(`OPFS path is a file: ${path3}`);setEntry(path3,{type:"directory",mode:file2.mode,mtimeMs:file2.mtimeMs,offset:0,length:0},changes);continue}if(existing?.type==="directory")throw new Error(`OPFS write target is a directory: ${path3}`);assertBounds(path3,file2.length);setEntry(path3,{type:file2.type,mode:file2.mode,mtimeMs:file2.mtimeMs,offset:base+file2.offset,length:file2.length},changes)}},options2)}function runBatch(apply,options2){if(!packAccess||!logAccess)throw new Error("OPFS filesystem worker is not initialized.");const before={packBytes,logBytes,liveBytes,deadBytes,rewrites,rewrittenBytes,linked,linkedBytes};const undo=new Map;mutationUndo=undo;const overwritten=[];bytesUndo=overwritten;const changes=[];try{apply(changes);assertWorkspaceQuota();commit(changes,{publish:!options2.durable});if(options2.durable){flushStorage();publishLog()}maintain();return changes}catch(cause){const published=clockView!==void 0&&!clockClosed&&Atomics.load(clockView,STORE_CLOCK_LOG)!==before.logBytes;if(published)beginTransition();for(const[path3,entry]of undo){if(entry===void 0)entries.delete(path3);else entries.set(path3,entry)}rebuildChildren();try{for(let index2=overwritten.length-1;index2>=0;index2-=1)writePackAt(overwritten[index2][0],overwritten[index2][1])}catch(restoreCause){cause=new AggregateError([cause,restoreCause],"OPFS could not restore bytes a failed batch wrote over.")}({packBytes,logBytes,liveBytes,deadBytes,rewrites,rewrittenBytes,linked,linkedBytes}=before);if(flushTimer!==void 0){clearTimeout(flushTimer);flushTimer=void 0}try{logAccess.truncate(logBytes);logAccess.flush();packAccess.truncate(packBytes);packAccess.flush()}catch(rollbackCause){retireClock();mutationFailure=new AggregateError([cause,rollbackCause],"OPFS could not roll back a failed batch; reopen this workspace before writing again.");throw mutationFailure}if(published)endTransition();throw cause}finally{mutationUndo=void 0;bytesUndo=void 0}}function close2(){if(initializing){openingController?.abort(new DOMException("The workspace was closed while opening.","AbortError"));return}if(closing)return;closing=true;if(activeStorageOperations!==0)return;closeStorage()}function closeStorage(){retireClock();try{flushStorage()}finally{try{closeGenerationHandles()}finally{const release2=releaseLock;releaseLock=void 0;project=void 0;try{release2?.()}finally{if(options.ownsPackages)options.packages?.close()}}}}return{initialize:initialize2,opened:()=>project!==void 0&&!closing,stats:()=>({entries:entries.size,liveBytes,deadBytes,packBytes,rewrites,rewrittenBytes,linked,linkedBytes,flushes,flushMs}),applyNow,applyExtentsNow,close:close2,readExtent,descendants,retain,remapLinks,childrenOf:path3=>[...children.get(path3)??[]].sort(),refresh,follow,clock,readerSeed,imageCompletionSeed,imageLine:()=>imageReader?.lineForReader()??options.packages?.imageLine(),imageStartupSet:()=>imageReader?.readDigests()??imageReader?.completedDigests()??[],prefetchImage:(digests,streams2)=>imageReader?.prefetch(digests,streams2)??{queued:0,done:Promise.resolve()},seeded:()=>startedFromSeed,get logBytes(){return logBytes},checkpoint,deferMaintenance,installPreparedImage,installPreparedProject,get deferredImage(){return deferredImage},get imagePlacedAt(){return project&&imageRangesDigest?generationInitializedAt:void 0},get entries(){return entries},get packBytes(){return packBytes},read,readRange,snapshot:readSnapshot,replace:writeGeneration,apply:applyMutations,flush:()=>{if(closing||!project)throw new Error("This OPFS workspace is not open.");if(rewritingGeneration)throw new Error("Wait for the OPFS generation replacement before flushing it.");flushStorage()},validateSnapshot,validateMutationBatch}}async function openPackReader(environment,projectId,seed,imageLine){const packages2=createPackStore(environment);await packages2.initialize(PACKAGES_STORE,{readOnly:true,extentsOnly:true,...seed?.packagesImage?{imageCompletion:seed.packagesImage,...imageLine?{imageLine}:{}}:{}});const project=createPackStore(environment,{packages:packages2,ownsPackages:true});let opened;try{opened=await project.initialize(projectId,{readOnly:true,...seed?{seed}:{}})}catch(cause){project.close();packages2.close();throw cause}if(!opened&&!project.opened()){packages2.close();return void 0}return project}var SWEEP_COMPACTION_BYTES=64*1024*1024;var SWEEP_INTERVAL_MS=24*60*60*1e3;var SWEEP_MARK_FILE="sweep.json";var SWEEP_GRACE_MS=14*24*60*60*1e3;async function sweepSharedPackages(environment,progress){const locks=environment.navigator.locks;if(!locks)return void 0;return locks.request(PACKAGES_OPEN_LOCK,{mode:"exclusive",ifAvailable:true},async lock=>{if(!lock)return void 0;const root2=await environment.navigator.storage.getDirectory();let base;try{base=await root2.getDirectoryHandle(BASE_DIRECTORY)}catch{return void 0}let packagesDirectory;try{packagesDirectory=await base.getDirectoryHandle(PACKAGES_STORE)}catch{return void 0}const lastSweep=await readSweepMark(packagesDirectory);if(lastSweep!==void 0&&Date.now()-lastSweep<SWEEP_INTERVAL_MS)return void 0;const projectIds=[];for await(const[name,handle]of base.entries()){if(handle.kind==="directory"&&name!==PACKAGES_STORE&&name!==STAGING_DIRECTORY&&!name.startsWith(TREE_STORE_PREFIX))projectIds.push(name)}const shared=createPackStore(environment);if(!await shared.initialize(PACKAGES_STORE,{shared:true})){shared.close();return void 0}const projects=[];const referenced=new Set;try{for(const[index2,id2]of projectIds.entries()){progress?.(`sweeping the origin's packages, project ${index2+1} of ${projectIds.length}`);const project=createPackStore(environment,{packages:shared});try{const opened=await project.initialize(id2);if(!opened&&!project.opened()){project.close();continue}}catch{project.close();continue}for(const entry of project.entries.values())if(entry.pack&&entry.length>0)referenced.add(entry.offset);projects.push(project)}const kept=new Set;const now=Date.now();for(const[path3,entry]of shared.entries){const unit=unitOf(path3);if(unit===void 0)continue;const linked=entry.type!=="directory"&&entry.length>0&&referenced.has(entry.offset);const recent=path3===`${PACKAGES_ROOT}/${unit}`&&now-Math.max(entry.mtimeMs,shared.imagePlacedAt??0)<SWEEP_GRACE_MS;if(linked||recent)kept.add(unit)}let packagesDropped=0;let bytesDropped=0;const units=new Set;for(const[path3,entry]of shared.entries){const unit=unitOf(path3);if(unit===void 0)continue;units.add(unit);if(!kept.has(unit)&&entry.type!=="directory")bytesDropped+=entry.length}if([...units].some(unit=>!kept.has(unit)&&unit!==".layers"&&unit!==".layers-deferred")){kept.delete(".layers");kept.delete(".layers-deferred")}for(const unit of units)if(!kept.has(unit))packagesDropped+=1;const keep=path3=>{const unit=unitOf(path3);return unit===void 0||kept.has(unit)};let compacted=false;if(packagesDropped>0){if(bytesDropped>=SWEEP_COMPACTION_BYTES||bytesDropped*4>=shared.packBytes){progress?.("sweeping the origin's packages, compacting");const moved=await shared.retain(keep);for(const project of projects)await project.remapLinks(moved);compacted=true}else{const removals=[];for(const unit of units)if(!kept.has(unit))removals.push({operation:"remove",path:`${PACKAGES_ROOT}/${unit}`});for(let offset2=0;offset2<removals.length;offset2+=128)await shared.apply(removals.slice(offset2,offset2+128))}}await writeSweepMark(packagesDirectory);return{projects:projects.length,packagesKept:kept.size,packagesDropped,bytesDropped,compacted}}finally{for(const project of projects)project.close();shared.close()}})}async function readSweepMark(directory2){try{const file2=await(await directory2.getFileHandle(SWEEP_MARK_FILE)).getFile();const mark=JSON.parse(await file2.text());return typeof mark.at==="number"&&Number.isFinite(mark.at)?mark.at:void 0}catch{return void 0}}async function writeSweepMark(directory2){const handle=await directory2.getFileHandle(SWEEP_MARK_FILE,{create:true});const writable=await handle.createWritable();await writable.write(JSON.stringify({at:Date.now()}));await writable.close()}function unitOf(path3){if(!path3.startsWith(`${PACKAGES_ROOT}/`))return void 0;const parts=path3.slice(PACKAGES_ROOT.length+1).split("/");if(parts[0]===".modules")return parts.length>=4?parts.slice(0,4).join("/"):void 0;if(parts[0]===".programs")return parts.length>=2?parts.slice(0,2).join("/"):void 0;if(parts[0]===".browser-packs"){if(parts[1]==="objects"&&parts.length>=3)return parts.slice(0,3).join("/");if(parts[1]==="locks"&&parts.length>=3)return parts.slice(0,3).join("/");return void 0}const packageLength=parts[0]?.startsWith("@")?2:1;return parts.length>=packageLength?parts.slice(0,packageLength).join("/"):void 0}var LocalChildren=class{map=new Map;get(path3){return this.map.get(path3)}mutable(path3){let names2=this.map.get(path3);if(!names2){names2=new Set;this.map.set(path3,names2)}return names2}delete(path3){this.map.delete(path3)}};function storeImportMutations(store,tree2,inside){const root2=normalize2(tree2.root);if(root2!==tree2.root||root2.includes("\0")||root2.includes("\\")||root2.length>4096)throw new Error("Invalid workspace import root.");if(!inside(root2))return false;if(!Array.isArray(tree2.entries)||!tree2.entries.length||tree2.entries.length>5e4)throw new Error("Invalid workspace import entry count.");const incoming2=new Map;let bytes2=0;for(const entry of tree2.entries){if(!entry||typeof entry.path!=="string"||normalize2(entry.path)!==entry.path||entry.path.includes("\0")||entry.path.includes("\\")||entry.path.length>4096||entry.path!==root2&&!entry.path.startsWith(`${root2}/`)||incoming2.has(entry.path)||entry.type!=="file"&&entry.type!=="directory"||!Number.isInteger(entry.mode)||entry.mode<0||entry.mode>4095||!Number.isFinite(entry.mtimeMs)||entry.mtimeMs<0)throw new Error("Invalid workspace import entry.");if(entry.type==="file"){if(!(entry.bytes instanceof Uint8Array))throw new Error("Workspace import file has no bytes.");bytes2+=entry.bytes.byteLength;if(bytes2>128*1024*1024)throw new Error("Workspace import exceeds its byte limit.")}incoming2.set(entry.path,entry)}if(incoming2.get(root2)?.type!=="directory")throw new Error("Workspace import has no root directory.");for(const entry of incoming2.values()){if(entry.path!==root2&&incoming2.get(parentOf(entry.path))?.type!=="directory"){throw new Error(`Workspace import has no parent directory for ${entry.path}.`)}const current3=store.entries.get(entry.path);if(!tree2.replace&¤t3&¤t3.type!==entry.type)throw new Error(`Workspace import conflicts with ${entry.path}.`)}const heldRoot=store.entries.get(root2);if(tree2.requireEmpty&&heldRoot&&(heldRoot.type!=="directory"||store.childrenOf(root2).length>0)){throw new Error(`Workspace import target is not empty: ${root2}`)}const mutations=tree2.replace?[{operation:"remove",path:root2}]:[];for(const entry of[...incoming2.values()].sort((left,right)=>depth(left.path)-depth(right.path))){mutations.push(entry.type==="directory"?{operation:"mkdir",path:entry.path,mode:entry.mode,mtimeMs:entry.mtimeMs}:{operation:"write",path:entry.path,content:entry.bytes,mode:entry.mode,mtimeMs:entry.mtimeMs})}return mutations}function normalize2(path3){if(path3.startsWith("/")&&(path3.length===1||!path3.endsWith("/"))&&!path3.includes("//")&&!path3.includes("/./")&&!path3.includes("/../")&&!path3.endsWith("/.")&&!path3.endsWith("/.."))return path3;const parts=[];for(const part of`/${path3}`.split("/")){if(!part||part===".")continue;if(part==="..")parts.pop();else parts.push(part)}return`/${parts.join("/")}`}function parentOf(path3){const at3=path3.lastIndexOf("/");return at3<=0?"/":path3.slice(0,at3)}function depth(path3){let segments=1;for(let index2=0;index2<path3.length;index2+=1)if(path3.charCodeAt(index2)===47)segments+=1;return segments}var DIRECTORY_MODE2=493;var FILE_MODE2=420;var PackedVirtualFS=class extends VirtualFS{storeRoots;store;changeListeners=new Set;deleteListeners=new Set;storeWatchers=new Map;textDecoder=new TextDecoder;textEncoder=new TextEncoder;constructor(store,roots=PROJECT_ROOTS,options={}){super();this.store=store;this.storeRoots=typeof roots==="string"?[roots]:roots;if(options.reader===true)return;for(const root2 of this.storeRoots){if(store.entries.has(root2))continue;try{store.applyNow([{operation:"mkdir",path:root2,mode:DIRECTORY_MODE2,mtimeMs:Date.now()}])}catch{}}}on(event,listener){if(event==="change")this.changeListeners.add(listener);else if(event==="delete")this.deleteListeners.add(listener);super.on(event,listener);return this}off(event,listener){if(event==="change")this.changeListeners.delete(listener);else if(event==="delete")this.deleteListeners.delete(listener);super.off(event,listener);return this}existsSync(path3){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return super.existsSync(normalized);return this.store.entries.has(normalized)}statSync(path3,options){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return super.statSync(normalized,options);const entry=this.store.entries.get(normalized);if(!entry){if(options?.throwIfNoEntry===false)return void 0;throw nodeError("ENOENT","stat",normalized)}return statsOf(entry)}lstatSync(path3,options){const normalized=normalize3(path3);const resolved=this.packedResolve(normalized,true);if(!this.packedInside(resolved))return super.lstatSync(resolved,options);const entry=this.store.entries.get(resolved);if(!entry){if(options?.throwIfNoEntry===false)return void 0;throw nodeError("ENOENT","lstat",resolved)}return statsOf(entry)}readFileSync(path3,encoding){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return encoding?super.readFileSync(normalized,encoding):super.readFileSync(normalized);const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","open",normalized);if(entry.type!=="file")throw nodeError("EISDIR","read",normalized);const bytes2=this.store.read(normalized);return encoding?this.textDecoder.decode(bytes2):bytes2}readdirSync(path3){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return super.readdirSync(normalized);const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","scandir",normalized);if(entry.type!=="directory")throw nodeError("ENOTDIR","scandir",normalized);return this.store.childrenOf(normalized)}holds(path3,keepLast=false){return this.packedInside(this.packedResolve(normalize3(path3),keepLast))}realpathSync(path3){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return super.realpathSync(normalized);if(!this.store.entries.has(normalized))throw nodeError("ENOENT","realpath",normalized);return normalized}accessSync(path3,mode){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized)){super.accessSync(normalized,mode);return}if(!this.store.entries.has(normalized))throw nodeError("ENOENT","access",normalized)}symlinkSync(target,path3){const normalized=this.packedResolve(normalize3(path3),true);if(!this.packedInside(normalized)){super.symlinkSync(target,normalized);return}const parent2=this.store.entries.get(parentOf2(normalized));if(!parent2||parent2.type!=="directory")throw nodeError("ENOENT","symlink",normalized);if(this.store.entries.has(normalized))throw nodeError("EEXIST","symlink",normalized);this.packedApply([{operation:"write",path:normalized,content:this.textEncoder.encode(String(target)),symlink:true,mode:511,mtimeMs:Date.now()}])}readlinkSync(path3){const normalized=this.packedResolve(normalize3(path3),true);if(!this.packedInside(normalized))return super.readlinkSync(normalized);const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","readlink",normalized);if(entry.type!=="symlink")throw nodeError("EINVAL","readlink",normalized);return this.textDecoder.decode(this.store.read(normalized))}writeFileSync(path3,data2){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized)){super.writeFileSync(path3,data2);return}const existing=this.store.entries.get(normalized);if(existing?.type==="directory")throw nodeError("EISDIR","open",normalized);const content=typeof data2==="string"?this.textEncoder.encode(data2):data2;this.packedAppeared(this.packedApply([{operation:"write",path:normalized,content,mode:existing?.mode??FILE_MODE2,mtimeMs:Date.now()}]));this.packedChanged(normalized,typeof data2==="string"?data2:void 0,existing===void 0?"rename":"change")}appendFileSync(path3,data2){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized)){super.appendFileSync(path3,data2);return}const existing=this.store.entries.get(normalized);if(existing?.type==="directory")throw nodeError("EISDIR","open",normalized);const content=typeof data2==="string"?this.textEncoder.encode(data2):data2;this.packedAppeared(this.packedApply([{operation:"append",path:normalized,content,mode:existing?.mode??FILE_MODE2,mtimeMs:Date.now()}]));this.packedChanged(normalized,void 0,existing===void 0?"rename":"change")}writeAtSync(path3,data2,position){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized)){super.writeAtSync(path3,data2,position);return}const existing=this.store.entries.get(normalized);if(existing?.type==="directory")throw nodeError("EISDIR","open",normalized);this.packedAppeared(this.packedApply([{operation:"write-at",path:normalized,content:data2,position,mode:existing?.mode??FILE_MODE2,mtimeMs:Date.now()}]));this.packedChanged(normalized,void 0,existing===void 0?"rename":"change")}mkdirSync(path3,options){const normalized=this.packedResolve(normalize3(path3),true);if(!this.packedInside(normalized)){super.mkdirSync(path3,options);return}const existing=this.store.entries.get(normalized);if(existing){if(options?.recursive&&existing.type==="directory")return;throw nodeError("EEXIST","mkdir",normalized)}if(!options?.recursive){const parent2=parentOf2(normalized);const above=this.store.entries.get(parent2);if(!above&&this.packedInside(parent2))throw nodeError("ENOENT","mkdir",normalized);if(above&&above.type!=="directory")throw nodeError("ENOTDIR","mkdir",normalized)}this.packedAppeared(this.packedApply([{operation:"mkdir",path:normalized,mode:DIRECTORY_MODE2,mtimeMs:Date.now()}]))}unlinkSync(path3){const normalized=this.packedResolve(normalize3(path3),true);if(!this.packedInside(normalized)){super.unlinkSync(path3);return}const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","unlink",normalized);if(entry.type==="directory")throw nodeError("EISDIR","unlink",normalized);this.packedApply([{operation:"remove",path:normalized,recursive:false}]);this.packedDeleted(normalized)}rmdirSync(path3){const normalized=normalize3(path3);if(!this.packedInside(normalized)){super.rmdirSync(path3);return}const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","rmdir",normalized);if(entry.type!=="directory")throw nodeError("ENOTDIR","rmdir",normalized);if(this.store.childrenOf(normalized).length>0)throw nodeError("ENOTEMPTY","rmdir",normalized);this.packedApply([{operation:"remove",path:normalized,recursive:true}]);this.packedDeleted(normalized)}linkShared(source,path3){this.linkSharedBatch([{source,path:path3}])}linkSharedBatch(links){const mutations=links.map(({source,path:path3})=>{const normalized=normalize3(path3);if(!this.packedInside(normalized))throw new Error(`A shared path can only be linked inside ${this.storeRoots.join(" or ")}.`);return{operation:"link",path:normalized,source}});const startedAt=performance.now();const changes=this.store.applyNow(mutations);const indexedAt=performance.now();this.linkTiming.indexMs+=indexedAt-startedAt;for(const[changed,entry]of changes){if(entry===null){this.packedDeleted(changed);continue}if(entry.type==="file")this.packedChanged(changed,void 0)}this.linkTiming.announceMs+=performance.now()-indexedAt}linkTiming={indexMs:0,announceMs:0};chmodSync(path3,mode){const normalized=normalize3(path3);if(!this.packedInside(normalized))return;if(!this.store.entries.has(normalized))throw nodeError("ENOENT","chmod",normalized);this.packedApply([{operation:"metadata",path:normalized,mode:mode&4095}])}utimesSync(path3,_atime,mtime){const normalized=normalize3(path3);if(!this.packedInside(normalized))return;if(!this.store.entries.has(normalized))throw nodeError("ENOENT","utimes",normalized);this.packedApply([{operation:"metadata",path:normalized,mtimeMs:typeof mtime==="number"?mtime:mtime.getTime()}])}renameSync(oldPath,newPath){const source=normalize3(oldPath);const destination=normalize3(newPath);const sourceInside=this.packedInside(source);const destinationInside=this.packedInside(destination);if(!sourceInside&&!destinationInside){super.renameSync(oldPath,newPath);return}if(sourceInside&&destinationInside){if(!this.store.entries.has(source))throw nodeError("ENOENT","rename",source);const moved=[source];for(let index2=0;index2<moved.length;index2+=1){const path3=moved[index2];if(this.store.entries.get(path3)?.type!=="directory")continue;for(const name of this.store.childrenOf(path3))moved.push(`${path3}/${name}`)}this.packedApply([{operation:"rename",path:source,destination}]);for(const path3 of moved)this.packedDeleted(path3);for(const path3 of moved)this.packedChanged(`${destination}${path3.slice(source.length)}`,void 0);return}this.packedCopyTree(source,destination);this.packedRemoveTree(source)}copyFileSync(src,dest){this.writeFileSync(dest,this.readFileSync(src))}watchedPaths(){const paths=[];for(const[path3,set]of this.storeWatchers)if(set.size>0)paths.push({path:path3,recursive:[...set].some(entry=>entry.recursive)});const overlay=this.watchers;for(const[path3,set]of overlay??[]){const live2=[...set].filter(entry=>!entry.closed);if(live2.length>0)paths.push({path:path3,recursive:live2.some(entry=>entry.recursive===true)})}return paths}watch(filename,optionsOrListener,listener){const normalized=normalize3(filename);const inside=this.packedInside(normalized);const above=this.storeRoots.some(root2=>normalized==="/"||root2.startsWith(normalized+"/"));if(!inside&&!above)return super.watch(filename,optionsOrListener,listener);const overlay=inside?void 0:super.watch(filename,optionsOrListener,listener);const options=typeof optionsOrListener==="function"?{}:optionsOrListener??{};const actual=typeof optionsOrListener==="function"?optionsOrListener:listener;const entry={listener:actual??(()=>void 0),recursive:options.recursive??false};let set=this.storeWatchers.get(normalized);if(!set){set=new Set;this.storeWatchers.set(normalized,set)}set.add(entry);const watcher={close:()=>{set.delete(entry);overlay?.close()},ref(){overlay?.ref();return this},unref(){overlay?.unref();return this}};return watcher}toSnapshot(){const base=super.toSnapshot();const files=base.files.filter(entry=>!this.packedInside(entry.path));const paths=[...this.store.entries.keys()].sort((left,right)=>depth2(left)-depth2(right)||(left<right?-1:1));for(const path3 of paths){const entry=this.store.entries.get(path3);const metadata={mode:entry.mode&4095,mtimeMs:entry.mtimeMs};if(entry.type==="directory")files.push({path:path3,type:"directory",...metadata});else if(entry.type==="symlink")files.push({path:path3,type:"symlink",target:this.textDecoder.decode(this.store.read(path3)),...metadata});else files.push({path:path3,type:"file",content:base642(this.store.read(path3)),...metadata})}return{...base,files}}packedInside(path3){return this.storeRoots.some(root2=>path3===root2||path3.startsWith(`${root2}/`))}typeOf(path3){const entries=this.store.entries;return entries.typeOf?entries.typeOf(path3):entries.get(path3)?.type}packedResolve(path3,keepLast=false){if(!this.packedInside(path3))return path3;const direct=this.typeOf(path3);if(direct?direct!=="symlink"||keepLast:this.typeOf(parentOf2(path3))==="directory")return path3;let current3=path3;for(let hops=0;hops<40;hops+=1){const parts=current3.split("/").filter(Boolean);let prefix2="";let followed=false;for(let index2=0;index2<parts.length;index2+=1){prefix2=`${prefix2}/${parts[index2]}`;if(!this.packedInside(prefix2))return current3;if(keepLast&&index2===parts.length-1)break;const type2=this.typeOf(prefix2);if(!type2)return current3;if(type2!=="symlink")continue;const target=this.textDecoder.decode(this.store.read(prefix2));const base=target.startsWith("/")?target:`${parentOf2(prefix2)}/${target}`;current3=normalize3(`${base}/${parts.slice(index2+1).join("/")}`.replace(/\/$/u,""));followed=true;break}if(!followed)return current3}throw nodeError("ELOOP","stat",path3)}packedApply(mutations,options){return this.store.applyNow(mutations,options)}applyBatch(mutations){for(const mutation of mutations){if(typeof mutation.path!=="string"||!this.packedInside(normalize3(mutation.path))){throw new Error(`A batch can only be applied inside ${this.storeRoots.join(" or ")}.`)}}const changes=this.packedApply(mutations);for(const[path3,entry]of changes){if(entry===null)this.packedDeleted(path3);else if(entry.type==="file")this.packedChanged(path3,void 0)}}importTree(tree2){const mutations=storeImportMutations(this.store,tree2,path3=>this.packedInside(path3));if(!mutations)return false;const changes=this.packedApply(mutations,{durable:true});for(const[path3,entry]of changes){try{if(entry===null)this.packedDeleted(path3);else if(entry.type==="file")this.packedChanged(path3,void 0)}catch(cause){console.error("Workspace import observer failed.",cause)}}return true}packedAppeared(changes){for(const[path3,entry]of changes)if(entry!==null&&entry.type==="directory")this.packedNotifyWatchers(path3,"rename")}packedChanged(path3,text,event="change"){for(const listener of this.changeListeners)listener(path3,text??"");this.packedNotifyWatchers(path3,event)}packedDeleted(path3){for(const listener of this.deleteListeners)listener(path3);this.packedNotifyWatchers(path3,"rename")}packedNotifyWatchers(path3,event){for(const[watched,set]of this.storeWatchers){if(path3!==watched&&watched!=="/"&&!path3.startsWith(`${watched}/`))continue;const relative2=path3===watched?path3.slice(path3.lastIndexOf("/")+1):path3.slice(watched==="/"?1:watched.length+1);for(const entry of set){if(path3!==watched&&!entry.recursive&&relative2.includes("/"))continue;entry.listener(event,relative2)}}}packedCopyTree(source,destination){const stat2=this.statSync(source);if(stat2.isDirectory()){this.mkdirSync(destination,{recursive:true});for(const name of this.readdirSync(source))this.packedCopyTree(`${source}/${name}`,`${destination}/${name}`);return}this.writeFileSync(destination,this.readFileSync(source))}packedRemoveTree(path3){const stat2=this.statSync(path3);if(stat2.isDirectory()){for(const name of this.readdirSync(path3))this.packedRemoveTree(`${path3}/${name}`);this.rmdirSync(path3);return}this.unlinkSync(path3)}};function statsOf(entry){const isFile2=entry.type==="file";const isLink=entry.type==="symlink";const when=new Date(entry.mtimeMs);return{isFile:()=>isFile2,isDirectory:()=>entry.type==="directory",isSymbolicLink:()=>isLink,isBlockDevice:()=>false,isCharacterDevice:()=>false,isFIFO:()=>false,isSocket:()=>false,size:entry.type==="directory"?0:entry.length,mode:(isFile2?32768:isLink?40960:16384)|entry.mode,mtime:when,atime:when,ctime:when,birthtime:when,mtimeMs:entry.mtimeMs,atimeMs:entry.mtimeMs,ctimeMs:entry.mtimeMs,birthtimeMs:entry.mtimeMs,nlink:1,uid:0,gid:0,dev:0,ino:0,rdev:0,blksize:4096,blocks:Math.ceil((isFile2?entry.length:0)/512)}}function nodeError(code3,syscall,path3){const messages3={ENOENT:"no such file or directory",ENOTDIR:"not a directory",EISDIR:"is a directory",EEXIST:"file already exists",ENOTEMPTY:"directory not empty",EINVAL:"invalid argument",ELOOP:"too many symbolic links encountered"};const errno2={ENOENT:-2,ENOTDIR:-20,EISDIR:-21,EEXIST:-17,ENOTEMPTY:-39,EINVAL:-22,ELOOP:-40};return Object.assign(new Error(`${code3}: ${messages3[code3]}, ${syscall} '${path3}'`),{code:code3,errno:errno2[code3],syscall,path:path3})}function normalize3(path3){if(path3.startsWith("/")&&(path3.length===1||!path3.endsWith("/"))&&!path3.includes("//")&&!path3.includes("/./")&&!path3.includes("/../")&&!path3.endsWith("/.")&&!path3.endsWith("/.."))return path3;const parts=[];for(const part of`/${path3}`.split("/")){if(!part||part===".")continue;if(part==="..")parts.pop();else parts.push(part)}return`/${parts.join("/")}`}function parentOf2(path3){const at3=path3.lastIndexOf("/");return at3<=0?"/":path3.slice(0,at3)}function base642(value){let binary="";for(let offset2=0;offset2<value.byteLength;offset2+=32768){binary+=String.fromCharCode(...value.subarray(offset2,Math.min(value.byteLength,offset2+32768)))}return btoa(binary)}function depth2(path3){let segments=1;for(let index2=0;index2<path3.length;index2+=1)if(path3.charCodeAt(index2)===47)segments+=1;return segments}function storeReads(grant){const{opening,clock:buffer2}=grant;const clock=new Int32Array(buffer2);let reader;let local2;let synced=-1;void opening.then(opened=>{if(!opened)return;reader=opened;local2=new PackedVirtualFS(opened,PROJECT_ROOTS,{reader:true});const openedAt=grant.openedAt;if((openedAt&1)===0&&Atomics.load(clock,STORE_CLOCK_EPOCH)===openedAt)synced=openedAt},()=>void 0);let resyncing=false;let retryAt=0;const resync=epoch=>{if(resyncing||!reader||performance.now()<retryAt)return;resyncing=true;reader.refresh({whole:true}).then(()=>{if(Atomics.load(clock,STORE_CLOCK_EPOCH)===epoch)synced=epoch},()=>{retryAt=performance.now()+1e3}).finally(()=>{resyncing=false})};return(path3,keepLast,read)=>{if(!reader||!local2)return void 0;const epoch=Atomics.load(clock,STORE_CLOCK_EPOCH);if(resyncing)return void 0;if(epoch!==synced){if((epoch&1)===0)resync(epoch);return void 0}const published=Atomics.load(clock,STORE_CLOCK_LOG);if(reader.logBytes<published){try{reader.follow()}catch{return void 0}if(reader.logBytes<published)return void 0}let value;try{if(!local2.holds(path3,keepLast))return void 0;value=read(local2)}catch(cause){if(Atomics.load(clock,STORE_CLOCK_EPOCH)!==epoch||typeof cause?.code!=="string")return void 0;throw cause}if(Atomics.load(clock,STORE_CLOCK_EPOCH)!==epoch)return void 0;return{value}}}function validateNodePreparedFiles(files,limits){if(!Number.isSafeInteger(limits.maxBytes)||limits.maxBytes<1||!Number.isSafeInteger(limits.maxEntries)||limits.maxEntries<1||!Array.isArray(files)||files.length>limits.maxEntries)throw new Error("Invalid Node prepared-file limits or count.");const paths=new Map([["/","directory"]]);const encoder11=new TextEncoder;let bytes2=1;for(const file2 of files){if(!file2||typeof file2.path!=="string"||file2.path.length>limits.maxBytes||!file2.path.startsWith("/")||file2.path.endsWith("/")||file2.path.includes("\0")||file2.path.slice(1).split("/").some(part=>!part||part==="."||part==="..")||!(file2.bytes instanceof Uint8Array)||paths.has(file2.path))throw new Error("Invalid Node prepared file.");let parent2="";for(const part of file2.path.slice(1).split("/").slice(0,-1)){parent2+=`/${part}`;if(paths.get(parent2)==="file")throw new Error("Node prepared file conflicts with a directory.");if(!paths.has(parent2)){paths.set(parent2,"directory");bytes2+=encoder11.encode(parent2).byteLength}}paths.set(file2.path,"file");bytes2+=encoder11.encode(file2.path).byteLength+file2.bytes.byteLength;if(paths.size>limits.maxEntries)throw new Error("Node prepared files exceed their entry limit.");if(bytes2>limits.maxBytes)throw new Error("Node prepared files exceed their byte limit.")}}function captureNodePreparedFiles(filesystem,limits){validateNodePreparedFiles([],limits);const paths=["/"];const files=[];const encoder11=new TextEncoder;let entries=0,bytes2=0;while(paths.length){const path3=paths.pop();if(++entries>limits.maxEntries)throw new Error("Node prepared files exceed their entry limit.");const stat2=filesystem.lstatSync(path3);bytes2+=encoder11.encode(path3).byteLength;if(stat2.isFile()){bytes2+=stat2.size;files.push(path3)}else if(stat2.isDirectory()){const names2=filesystem.readdirSync(path3);if(entries+paths.length+names2.length>limits.maxEntries)throw new Error("Node prepared files exceed their entry limit.");for(const name of names2)paths.push(`${path3==="/"?"":path3}/${name}`)}else throw new Error("Node prepared files cannot contain symbolic links.");if(bytes2>limits.maxBytes)throw new Error("Node prepared files exceed their byte limit.")}return files.map(path3=>({path:path3,bytes:Uint8Array.from(filesystem.readFileSync(path3))}))}function nodeInvocationFilesystem(channel,policy,prepared,store){const client=new BrowserFilesystemChannelClient(channel);const shared=new VirtualFS;for(const method of["existsSync","statSync","lstatSync","readFileSync","readdirSync","realpathSync","readlinkSync","symlinkSync","writeFileSync","appendFileSync","writeAtSync","mkdirSync","unlinkSync","rmdirSync","renameSync","chmodSync","utimesSync"]){Reflect.set(shared,method,client[method].bind(client))}Reflect.set(shared,"accessSync",path3=>{client.statSync(path3)});if(store){const attempt=storeReads(store);for(const method of["existsSync","statSync","lstatSync","readFileSync","readdirSync","realpathSync","readlinkSync","accessSync"]){const owner2=Reflect.get(shared,method);const keepLast=method==="lstatSync"||method==="readlinkSync";Reflect.set(shared,method,(path3,...args)=>{const answer2=attempt(path3,keepLast,local2=>Reflect.get(local2,method).call(local2,path3,...args));return answer2?answer2.value:owner2(path3,...args)})}}const runtimeFiles=new VirtualFS;if(prepared){validateNodePreparedFiles(prepared.files,prepared.limits);for(const{path:path3,bytes:bytes2}of prepared.files){runtimeFiles.mkdirSync(path3.slice(0,path3.lastIndexOf("/"))||"/",{recursive:true});runtimeFiles.writeFileSync(path3,bytes2)}}const merged=new VirtualFS;const owner=path3=>{if(!runtimeFiles.existsSync(path3))return shared;if(runtimeFiles.statSync(path3).isDirectory()&&shared.existsSync(path3))return shared;return runtimeFiles};const mutationOwner=path3=>{const filesystem=owner(path3);if(filesystem===runtimeFiles)throw Object.assign(new Error(`EACCES: private runtime file '${path3}' is read-only`),{code:"EACCES"});return filesystem};for(const method of["statSync","lstatSync","readFileSync","realpathSync","readlinkSync","accessSync","writeFileSync","appendFileSync","writeAtSync","mkdirSync","unlinkSync","rmdirSync","chmodSync","utimesSync"]){Reflect.set(merged,method,(path3,...args)=>{const mutating=["writeFileSync","appendFileSync","writeAtSync","mkdirSync","unlinkSync","rmdirSync","chmodSync","utimesSync"].includes(method)||method==="accessSync"&&(Number(args[0]??0)&2)!==0;const filesystem=mutating?mutationOwner(path3):owner(path3);const action=Reflect.get(filesystem,method);if(!action)throw Object.assign(new Error(`Unsupported filesystem operation ${method}.`),{code:"ENOTSUP"});return action.call(filesystem,path3,...args)})}Reflect.set(merged,"existsSync",path3=>runtimeFiles.existsSync(path3)||shared.existsSync(path3));Reflect.set(merged,"readdirSync",path3=>[...new Set([...runtimeFiles.existsSync(path3)?runtimeFiles.readdirSync(path3):[],...shared.existsSync(path3)?shared.readdirSync(path3):[]])].sort());Reflect.set(merged,"renameSync",(from,to2)=>{const filesystem=mutationOwner(from);if(filesystem!==mutationOwner(to2))throw Object.assign(new Error("Cannot rename across runtime and project files."),{code:"EXDEV"});filesystem.renameSync(from,to2)});Reflect.set(merged,"symlinkSync",(target,path3)=>mutationOwner(path3).symlinkSync(target,path3));const listeners={change:new Set,delete:new Set};const watchers=new Set;const normalize4=path3=>{const parts=[];for(const part of path3.split("/")){if(part==="..")parts.pop();else if(part&&part!==".")parts.push(part)}return"/"+parts.join("/")};Reflect.set(merged,"on",(event,listener)=>{listeners[event].add(listener);return merged});Reflect.set(merged,"off",(event,listener)=>{listeners[event].delete(listener);return merged});Reflect.set(merged,"watch",((path3,optionsOrListener,listener)=>{const options=typeof optionsOrListener==="object"?optionsOrListener:{};const entry={path:normalize4(path3),directory:merged.statSync(path3).isDirectory(),recursive:options?.recursive===true,persistent:options?.persistent!==false,listener:typeof optionsOrListener==="function"?optionsOrListener:listener};watchers.add(entry);return{close(){watchers.delete(entry)},ref(){entry.persistent=true;return this},unref(){entry.persistent=false;return this}}}));return{guest:policy?createConfinedNodeFilesystem(merged,policy):merged,runtimeFiles,notify(event,changedPath){const path3=normalize4(changedPath);let content="";if(event==="change"&&listeners.change.size&&merged.existsSync(path3)&&merged.statSync(path3).isFile())content=merged.readFileSync(path3,"utf8");for(const listener of listeners[event])listener(path3,content)},notifyWatch(event,changedPath){const path3=normalize4(changedPath);for(const watcher of watchers){const relative2=path3.slice(watcher.path==="/"?1:watcher.path.length+1);const inside=watcher.directory&&(watcher.path==="/"||path3.startsWith(watcher.path+"/"));if(path3===watcher.path||inside&&(watcher.recursive||!relative2.includes("/"))){watcher.listener?.(event,inside?relative2:path3.split("/").pop())}}}}}var observedBridges=new WeakMap;function browserServerRegistration(bridge,port2,server){const registration=observedBridges.get(bridge)?.registrations.get(port2);return server===void 0||registration?.server===server?registration:void 0}function releaseBrowserServerRegistration(bridge,port2,registration){if(browserServerRegistration(bridge,port2)===registration)bridge.unregisterServer(port2)}function observeBrowserServerPorts(bridge,listener){let observed=observedBridges.get(bridge);if(!observed){observed={listeners:new Set,registrations:new Map};observedBridges.set(bridge,observed);const register=bridge.registerServer.bind(bridge);const unregister=bridge.unregisterServer.bind(bridge);bridge.registerServer=(server,port2,hostname2)=>{const existed=bridge.getServerPorts().includes(port2);const handle=server.handleRequest.bind(server);server.handleRequest=(method,url2,headers,body)=>{const named=Object.keys(headers).some(name=>name.toLowerCase()==="host");return handle(method,url2,named?headers:{...headers,host:`${hostname2&&hostname2!=="0.0.0.0"&&hostname2!=="::"?hostname2:"127.0.0.1"}:${port2}`},body)};register(server,port2,hostname2);observed.registrations.set(port2,{server});if(!existed){const event={port:port2,type:"open",...bridge.getServerUrl?{url:bridge.getServerUrl(port2)}:{}};for(const accept of observed.listeners){try{accept(event)}catch(cause){console.error("Port registration observer failed.",cause)}}}};bridge.unregisterServer=port2=>{const existed=bridge.getServerPorts().includes(port2);unregister(port2);observed.registrations.delete(port2);if(existed){const event={port:port2,type:"close"};for(const accept of observed.listeners){try{accept(event)}catch(cause){console.error("Port release observer failed.",cause)}}}}}observed.listeners.add(listener);return()=>observed.listeners.delete(listener)}function requestNodeThread(launcher){const channel=new MessageChannel;let closed=false;const transport2={onmessage:null,onerror:null,postMessage(value,transfer2=[]){if(!closed)channel.port1.postMessage({type:"post",value,transfer:transfer2},transfer2)},terminate(){if(closed)return;closed=true;channel.port1.postMessage({type:"stop"});channel.port1.close()}};channel.port1.onmessage=event=>{if(!closed)transport2.onmessage?.(event)};channel.port1.onmessageerror=()=>transport2.onerror?.(new ErrorEvent("error",{message:"Node thread transport could not receive a message."}));launcher.postMessage({type:"launch",port:channel.port2},[channel.port2]);return transport2}function serveNodeThreadLauncher(host2){const channel=new MessageChannel;const live2=new Set;let disposed=false;channel.port1.onmessage=({data:data2})=>{const port2=data2?.port;if(data2?.type!=="launch"||!(port2 instanceof MessagePort))return;if(disposed||live2.size>=8){port2.postMessage({type:"node-thread-error",message:disposed?"The parent process has ended.":"The Node pack's eight-thread limit was reached."});port2.close();return}let worker2;let stopFilesystem;let initialized2=false;const stop2=()=>{live2.delete(stop2);worker2?.terminate();worker2=void 0;stopFilesystem?.();stopFilesystem=void 0;port2.close()};const failed=cause=>{port2.postMessage({type:"node-thread-error",message:cause instanceof Error?cause.stack??cause.message:String(cause)});stop2()};live2.add(stop2);try{worker2=new Worker(host2.workerUrl,{type:"module",name:"owned-node-thread"});worker2.onmessage=event=>{port2.postMessage(event.data);if(event.data?.type==="node-thread-exit")stop2()};worker2.onerror=event=>{event.preventDefault();failed(new Error(event.message))};port2.onmessage=({data:data3})=>{try{if(data3?.type==="stop"){stop2();return}if(data3?.type!=="post"||!worker2)throw new Error("Invalid owned Node thread message.");const value=data3.value;const transfer2=data3.transfer??[];if(!initialized2){if(value?.type!=="node-thread-init"||value.channel!==void 0)throw new Error("Invalid owned Node thread initialization.");initialized2=true;const files=createBrowserFilesystemChannel();stopFilesystem=serveBrowserFilesystemChannel(host2.filesystem,files.holder);const reads=host2.storeReads?.();worker2.postMessage({...value,channel:files.reader,filesystemPolicy:host2.policy,...reads?{storeReads:reads}:{}},[...transfer2,files.reader.port,...reads?.imageLine?[reads.imageLine.port]:[]])}else{if(value?.type!=="node-thread-message")throw new Error("Invalid owned Node thread request.");worker2.postMessage(value,transfer2)}}catch(cause){failed(cause)}};port2.onmessageerror=()=>failed(new Error("Owned Node thread transport could not receive a message."))}catch(cause){failed(cause)}};return{port:channel.port2,dispose(){if(disposed)return;disposed=true;for(const stop2 of[...live2])stop2();channel.port1.close();channel.port2.close()}}}var live=new Set;var ended=false;var installed2=false;function install2(){installed2=true;addEventListener("pagehide",()=>{ended=live.size>0||ended;for(const worker2 of[...live])worker2.terminate()});addEventListener("pageshow",event=>{if(event.persisted&&ended)location.reload()})}function pageWorker(worker2){if(typeof document==="undefined")return worker2;if(!installed2)install2();const terminate=worker2.terminate.bind(worker2);worker2.terminate=()=>{live.delete(worker2);terminate()};live.add(worker2);return worker2}var SIGNAL_NUMBERS={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGBUS:7,SIGFPE:8,SIGKILL:9,SIGUSR1:10,SIGSEGV:11,SIGUSR2:12,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGSTKFLT:16,SIGCHLD:17,SIGCONT:18,SIGSTOP:19,SIGTSTP:20,SIGTTIN:21,SIGTTOU:22,SIGURG:23,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:29,SIGPWR:30,SIGSYS:31};var IGNORED_BY_DEFAULT2=new Set(["SIGCHLD","SIGCONT","SIGURG","SIGWINCH"]);function runConfinedNodeRealm(command,options,host2){options={...options,...options.env!==void 0?{env:{...options.env}}:{},...options.terminal!==void 0?{terminal:{...options.terminal}}:{}};host2={...host2,configuration:structuredClone(host2.configuration)};if(host2.nodeProcess&&(!host2.processAdmission||!host2.nativeStreams)){throw new Error("Node process execution requires admitted identity and native stream ownership.")}if(host2.preparedFiles&&!host2.nodeProcess)throw new Error("Prepared entries require Node process admission.");if(host2.nodeProcess){validateNodePreparedFiles(host2.preparedFiles??[],host2.nodeProcess.preparedLimits);host2={...host2,nodeProcess:{...host2.nodeProcess,preparedLimits:{...host2.nodeProcess.preparedLimits}},preparedFiles:(host2.preparedFiles??[]).map(file2=>({path:file2.path,bytes:Uint8Array.from(file2.bytes)}))}}if(host2.policy===void 0&&!host2.nodeProcess)throw new Error("An ordinary Node realm requires process admission.");const policy=host2.policy===void 0?void 0:normalizeProcessFilesystemPolicy(host2.policy);const guarded=policy?createConfinedNodeFilesystem(host2.filesystem,policy):host2.filesystem;if(options.signal?.aborted)return Promise.resolve({stdout:"",stderr:"",exitCode:130});const channel=createBrowserFilesystemChannel();const stopFilesystem=serveBrowserFilesystemChannel(guarded,channel.holder);let initialProcess;const processRegistry2=(()=>{try{return serveNodeProcessRegistry(host2.nativeStreams?.limits,()=>initialProcess?.identity.pid)}catch(error){stopFilesystem();channel.reader.port.close();throw error}})();const messages3=new MessageChannel;let worker2;try{if(host2.nativeStreams){for(const inherited of host2.nativeStreams.inherited){const result=processRegistry2.streams.inherit(inherited.fd,inherited.source,inherited.id);if(result.status!==0)throw new Error(`Node descriptor ${inherited.fd} inheritance failed (${result.status}).`)}}if(host2.processAdmission){initialProcess={token:"1",identity:processRegistry2.registry.adoptRun(host2.processAdmission.source,host2.processAdmission.token,"1",host2.processAdmission.parentPid)}}worker2=host2.createWorker?.()??pageWorker(new Worker(host2.workerUrl,{type:"module",name:"confined-node-command"}))}catch(error){processRegistry2.dispose();stopFilesystem();messages3.port1.close();messages3.port2.close();channel.reader.port.close();throw error}return new Promise((resolve2,reject)=>{const threadLauncher=serveNodeThreadLauncher({workerUrl:host2.workerUrl,filesystem:guarded,...policy?{policy}:{},...host2.storeReads?{storeReads:host2.storeReads}:{}});let ended2=false;let started2=false;let workerSignals=false;const network=new AbortController;const fetches=new Map;const pulls=new Map;const credits=new Set;const waitForPull=(id2,signal)=>{signal.throwIfAborted();if(credits.delete(id2))return Promise.resolve();return new Promise((resolve3,reject2)=>{const abort2=()=>{pulls.delete(id2);reject2(signal.reason)};pulls.set(id2,()=>{signal.removeEventListener("abort",abort2);resolve3()});signal.addEventListener("abort",abort2,{once:true});if(signal.aborted)abort2()})};const ownedPorts=new Set;const portRegistrations=new Map;const stopObservingPorts=host2.serverBridge?observeBrowserServerPorts(host2.serverBridge,()=>void 0):void 0;const sockets=new Map;let stopNetListeners;let stopHostPorts;const requests=new Map;let nextRequest2=2;const send2=(message,transfer2=[])=>{if(!ended2)messages3.port1.postMessage(message,transfer2)};const children=new CrossOriginChildProcesses((message,childOptions)=>{const childPolicy=policy?intersectProcessFilesystemPolicies(policy,childOptions.filesystemPolicy):childOptions.filesystemPolicy===void 0?void 0:normalizeProcessFilesystemPolicy(childOptions.filesystemPolicy);const inheritedOptions={...childOptions,cwd:childOptions.cwd??options.cwd??"/",...childOptions.env??options.env?{env:childOptions.env??options.env}:{},...childPolicy?{filesystemPolicy:childPolicy}:{}};if(!message.nodeProcess)return host2.runChild(message.command,inheritedOptions,message.argv);if(!host2.nodeProcess||!initialProcess||!processRegistry2.streams)throw new Error("Node process dispatch was not negotiated.");const{token,inherited}=message.nodeProcess;if(typeof token!=="string"||!token||token===initialProcess.token||!Array.isArray(inherited)||inherited.length>host2.nativeStreams.limits.maxHandles||inherited.some(entry=>!entry||!Number.isSafeInteger(entry.fd)||entry.fd<0||!Number.isSafeInteger(entry.id)||entry.id<1)||!Array.isArray(message.argv)||message.argv[0]!=="node"||!message.argv.every(word=>typeof word==="string")){throw new Error("Invalid Node child admission.")}const preparedFiles=message.nodeProcess.preparedFiles??[];validateNodePreparedFiles(preparedFiles,host2.nodeProcess.preparedLimits);return host2.nodeProcess.runChild([...message.argv],inheritedOptions,{process:{source:processRegistry2.registry,token,parentPid:initialProcess.identity.pid},streams:{source:processRegistry2.streams,inherited:inherited.map(entry=>({...entry}))},preparedFiles})},send2);const changed=path3=>send2({type:"fs-event",event:"change",path:path3});const deleted=path3=>send2({type:"fs-event",event:"delete",path:path3});let filesystemWatcher;let removeResize;let pendingInput;let loading=false;let startup=setTimeout(()=>finish(new Error("Confined Node worker was not scheduled within 180 seconds.")),18e4);const finish=(error,result)=>{if(ended2)return;ended2=true;const failures=error===void 0?[]:[error];const release2=action=>{try{action()}catch(cause){failures.push(cause)}};clearTimeout(startup);options.signal?.removeEventListener("abort",abort);release2(()=>removeResize?.());release2(()=>stopNetListeners?.());release2(()=>stopHostPorts?.());for(const socket of sockets.values())release2(()=>socket.destroy());sockets.clear();release2(()=>network.abort());pendingInput?.reject(new DOMException("The process stopped.","AbortError"));pendingInput=void 0;for(const request of fetches.values())release2(()=>request.abort());fetches.clear();release2(()=>{if(host2.nodeProcess&&error===void 0&&!options.signal?.aborted)children.detach();else children.dispose()});release2(()=>filesystemWatcher?.close());release2(()=>{guarded.off("change",changed)});release2(()=>{guarded.off("delete",deleted)});for(const pending of requests.values())pending.reject(new Error("Confined Node command stopped."));requests.clear();for(const[port2,registration]of portRegistrations)release2(()=>{if(host2.serverBridge)releaseBrowserServerRegistration(host2.serverBridge,port2,registration)});portRegistrations.clear();ownedPorts.clear();release2(()=>stopObservingPorts?.());release2(()=>messages3.port1.close());release2(()=>threadLauncher.dispose());release2(()=>worker2.terminate());release2(()=>processRegistry2.dispose());release2(stopFilesystem);if(failures.length>1)reject(new AggregateError(failures,"Confined Node execution and cleanup failed."));else if(failures.length)reject(failures[0]);else resolve2(result)};const abort=()=>finish(void 0,{stdout:"",stderr:"",exitCode:130});options.signal?.addEventListener("abort",abort,{once:true});if(initialProcess){const own=initialProcess.identity.pid;processRegistry2.registry.receiveSignals((pid,signal)=>{if(pid!==own||ended2||SIGNAL_NUMBERS[signal]===void 0)return false;if(workerSignals&&signal!=="SIGKILL"&&signal!=="SIGSTOP"){send2({type:"signal",id:1,signal});return true}if(IGNORED_BY_DEFAULT2.has(signal))return true;queueMicrotask(()=>finish(void 0,{stdout:"",stderr:"",exitCode:128+SIGNAL_NUMBERS[signal]}));return true})}worker2.onerror=event=>{event.preventDefault();finish(new Error(event.message))};messages3.port1.onmessage=async({data:data2})=>{if(ended2)return;try{if(children.receive(data2))return;if(data2.type==="stdin-consumed"){if(data2.id===1){const input=pendingInput;pendingInput=void 0;input?.resolve()}return}if(data2.type==="attach-error"){finish(new Error(data2.error))}else if(data2.type==="attaching"&&!loading){loading=true;clearTimeout(startup);startup=setTimeout(()=>finish(new Error(`Confined Node worker timed out while ${data2.work}.`)),18e4)}else if(data2.type==="attached"){clearTimeout(startup);startup=setTimeout(()=>finish(new Error("Confined Node worker did not initialize within 180 seconds.")),18e4);const grant=host2.storeReads?.();send2({type:"init-confined",id:0,...host2.configuration,childInputVersion:1,filesystem:channel.reader,threadLauncher:threadLauncher.port,...grant?{storeReads:grant}:{},...policy?{filesystemPolicy:policy}:{},processRegistry:processRegistry2.channel,...initialProcess?{initialProcess}:{},...host2.nodeProcess?{nodeProcess:host2.nodeProcess.preparedLimits,preparedFiles:[...host2.preparedFiles??[]]}:{}},[channel.reader.port,threadLauncher.port,processRegistry2.channel.port,...grant?.imageLine?[grant.imageLine.port]:[]])}else if(data2.type==="initialized"){if(data2.filesystemPolicyVersion!==1)throw new Error("The Node worker did not negotiate filesystem confinement.");if(data2.processRegistryVersion!==1)throw new Error("The Node worker did not negotiate shared process identity.");if(processRegistry2.channel.streams&&data2.nativeStreamVersion!==1)throw new Error("The Node worker did not negotiate native stream ownership.");if(host2.nodeProcess&&data2.nodeProcessVersion!==1)throw new Error("The Node worker did not negotiate process dispatch.");if(started2)throw new Error("Confined Node worker initialized twice.");started2=true;workerSignals=data2.signalVersion===1;clearTimeout(startup);guarded.on("change",changed);guarded.on("delete",deleted);filesystemWatcher=guarded.watch("/",{recursive:true,persistent:false},(event,filename)=>{if(filename!==null)send2({type:"fs-watch-event",event,path:"/"+filename})});if(host2.net&&!(processRegistry2.channel.streams&&data2.nativeStreamVersion===1)){for(const port2 of host2.net.ports())send2({type:"listen-net",port:port2});stopNetListeners=host2.net.subscribe((port2,listening)=>send2({type:listening?"listen-net":"unlisten-net",port:port2}))}if(host2.hostPorts){send2({type:"host-ports",ports:[...host2.hostPorts.current()]});stopHostPorts=host2.hostPorts.subscribe(ports2=>send2({type:"host-ports",ports:[...ports2]}))}send2({type:"run",id:1,command,...options.cwd?{cwd:options.cwd}:{},...options.env?{env:{...options.env}}:{},interactive:!host2.nodeProcess,...options.stdin!==void 0?{stdin:options.stdin}:{},liveStdin:Boolean(options.stdinStream),...options.terminal?{terminal:{columns:options.terminal.columns,rows:options.terminal.rows}}:{}});if(options.stdinStream){const decoder11=new TextDecoder("utf-8",{fatal:true});const bytesSupported=data2.inputBytesVersion===1;void forwardBrowserProcessInput(options.stdinStream,async chunk=>{if(!bytesSupported){send2({type:"stdin",id:1,data:decoder11.decode(chunk,{stream:true})});return}for(let offset2=0;offset2<chunk.byteLength;offset2+=64*1024){network.signal.throwIfAborted();const bytes2=Uint8Array.from(chunk.subarray(offset2,offset2+64*1024)).buffer;await new Promise((resolve3,reject2)=>{pendingInput={resolve:resolve3,reject:reject2};try{send2({type:"stdin",id:1,data:"",bytes:bytes2},[bytes2])}catch(cause){pendingInput=void 0;reject2(cause)}})}},network.signal).then(()=>{if(ended2)return;const tail=decoder11.decode();if(tail)send2({type:"stdin",id:1,data:tail});send2({type:"stdin-end",id:1})}).catch(cause=>{if(!ended2)finish(cause)})}removeResize=options.terminal?.onResize?.((columns,rows)=>send2({type:"resize",id:1,columns,rows}))}else if(data2.type==="output"){(data2.stream==="stdout"?options.onStdout:options.onStderr)?.(data2.chunk)}else if(data2.type==="result"){finish(void 0,{stdout:data2.stdout,stderr:data2.stderr,exitCode:data2.exitCode,...data2.signal?{signal:data2.signal}:{}})}else if(data2.type==="error"){const pending=requests.get(data2.id);if(pending){requests.delete(data2.id);pending.reject(new Error(data2.error))}else if(data2.id===void 0||data2.id<=1)finish(new Error(data2.error))}else if(data2.type==="response"){const pending=requests.get(data2.id);requests.delete(data2.id);pending?.resolve({statusCode:data2.statusCode,statusMessage:data2.statusMessage,headers:data2.headers,body:new Uint8Array(data2.body)})}else if(data2.type==="port"){const bridge=host2.serverBridge;if(!bridge)throw new Error("Confined Node server forwarding is not configured.");if(data2.action==="open"){if(!Number.isInteger(data2.port)||data2.port<1||data2.port>65535)throw new Error("Invalid confined Node server port.");if(bridge.getServerPorts().includes(data2.port))throw Object.assign(new Error(`Port ${data2.port} is already in use.`),{code:"EADDRINUSE"});ownedPorts.add(data2.port);const server={listening:true,address:()=>({port:data2.port,address:"127.0.0.1",family:"IPv4"}),handleRequest:(method,url2,headers,body)=>new Promise((resolve3,reject2)=>{if(ended2||!ownedPorts.has(data2.port)){reject2(new Error("Confined Node server is closed."));return}if(requests.size>=128){reject2(new Error("Confined Node server has reached its 128 pending-request limit."));return}const id2=nextRequest2++;requests.set(id2,{port:data2.port,resolve:resolve3,reject:reject2});const bytes2=body===void 0?void 0:typeof body==="string"?new TextEncoder().encode(body):Uint8Array.from(body);try{send2({type:"request",id:id2,port:data2.port,method,url:url2,headers,...bytes2?{body:bytes2.buffer}:{}})}catch(cause){requests.delete(id2);reject2(cause)}})};bridge.registerServer(server,data2.port);const registration=browserServerRegistration(bridge,data2.port,server);if(registration)portRegistrations.set(data2.port,registration)}else if(ownedPorts.delete(data2.port)){const registration=portRegistrations.get(data2.port);portRegistrations.delete(data2.port);if(registration)releaseBrowserServerRegistration(bridge,data2.port,registration);for(const[id2,pending]of requests)if(pending.port===data2.port){requests.delete(id2);pending.reject(new Error("Confined Node server is closed."))}}}else if(data2.type==="fetch"){const controller=new AbortController;fetches.set(data2.id,controller);try{const signal=AbortSignal.any([network.signal,controller.signal]);const body=data2.body instanceof ArrayBuffer?new ReadableStream({start(controller2){controller2.enqueue(new Uint8Array(data2.body));controller2.close()}}):data2.body;const response=await host2.http({url:data2.url,method:data2.method,headers:data2.headers,...body?{body}:{},signal,...data2.profile?{profile:data2.profile}:{}});if(signal.aborted){await response.body?.cancel(signal.reason);signal.throwIfAborted()}send2({type:"fetch-response-start",id:data2.id,status:response.status,statusText:response.statusText,headers:response.headers});const reader=response.body?.getReader();try{for(;;){await waitForPull(data2.id,signal);const next2=reader?await reader.read():{done:true,value:void 0};if(next2.done){send2({type:"fetch-response-end",id:data2.id});break}const bytes2=Uint8Array.from(next2.value).buffer;send2({type:"fetch-response-chunk",id:data2.id,body:bytes2},[bytes2])}}catch(cause){await reader?.cancel(cause).catch(()=>void 0);throw cause}finally{reader?.releaseLock()}}finally{fetches.delete(data2.id);pulls.delete(data2.id);credits.delete(data2.id)}}else if(data2.type==="module-cache-link"||data2.type==="module-cache-keep"){const cache2=host2.moduleCache;const answer2=(linked,error)=>send2({type:"module-cache-answer",id:data2.id,linked,...error?{error}:{}});if(!cache2){answer2(false);return}try{if(data2.type==="module-cache-link"){const linked=await cache2.link(data2.key,data2.target);if(linked&&!host2.filesystem.existsSync(data2.target))console.warn(`[modules] ${data2.key} was linked for a child at ${data2.target}, and the filesystem served to that child does not have it`);answer2(linked)}else{await cache2.keep(data2.key,data2.code,data2.target);answer2(true)}}catch(cause){answer2(false,cause instanceof Error?cause.message:String(cause))}}else if(data2.type==="fetch-pull"){if(!fetches.has(data2.id))return;const resume=pulls.get(data2.id);if(resume){pulls.delete(data2.id);resume()}else credits.add(data2.id)}else if(data2.type==="fetch-abort"){fetches.get(data2.id)?.abort(new DOMException("The request was cancelled.","AbortError"))}else if(data2.type==="net-connect"){if(!Number.isSafeInteger(data2.socket)||data2.socket<1||sockets.has(data2.socket))throw new Error("Invalid confined loopback socket identity.");if(!host2.net||![...host2.net.ports()].includes(data2.port)||sockets.size>=128){send2({type:"net-end",socket:data2.socket});return}const socket=new PageNetSocketImpl(data2.socket,send2,()=>sockets.delete(data2.socket));sockets.set(data2.socket,socket);host2.net.connect(data2.port,socket)}else if(data2.type==="net-guest-data"){sockets.get(data2.socket)?.receive(new Uint8Array(data2.chunk))}else if(data2.type==="net-guest-end"){sockets.get(data2.socket)?.finish()}}catch(error){if(data2.type==="fetch")send2({type:"fetch-error",id:data2.id,error:error instanceof Error?error.message:String(error)});else finish(error)}};messages3.port1.start();worker2.postMessage({type:"attach",port:messages3.port2},[messages3.port2])})}var NodeProcessSupervisor=class{maxWorkers=16;workers=0;disposed=false;roots=new Set;pending=new Set;workerUrl;unassigned=[];prepareWorkers(workerUrl){if(this.disposed)return;if(this.workerUrl!==void 0&&this.workerUrl!==workerUrl)return;this.workerUrl=workerUrl;while(this.unassigned.length<2&&this.workers+this.unassigned.length<this.maxWorkers){let worker2;try{worker2=pageWorker(new Worker(workerUrl,{type:"module",name:"unassigned-node-command"}))}catch{return}const entry={worker:worker2,failed:event=>{event.preventDefault();const index2=this.unassigned.indexOf(entry);if(index2<0)return;this.unassigned.splice(index2,1);worker2.removeEventListener("error",entry.failed);worker2.terminate()}};worker2.addEventListener("error",entry.failed);this.unassigned.push(entry);try{worker2.postMessage({type:"warm-engine"})}catch{this.unassigned.pop();worker2.removeEventListener("error",entry.failed);worker2.terminate();return}}}takeWorker(workerUrl){if(this.workerUrl!==workerUrl){for(const idle of this.unassigned.splice(0)){idle.worker.removeEventListener("error",idle.failed);idle.worker.terminate()}this.workerUrl=workerUrl}const entry=this.workerUrl===workerUrl?this.unassigned.shift():void 0;if(entry)entry.worker.removeEventListener("error",entry.failed);const worker2=entry?.worker??pageWorker(new Worker(workerUrl,{type:"module",name:"confined-node-command"}));this.prepareWorkers(workerUrl);return worker2}run(command,options,host2){return this.launch(command,options,host2)}async dispose(){this.disposed=true;for(const entry of this.unassigned.splice(0)){entry.worker.removeEventListener("error",entry.failed);entry.worker.terminate()}for(const root2 of[...this.roots])this.cancel(root2,new DOMException("The container stopped.","AbortError"));await Promise.all([...this.pending])}launch(command,options,host2,parent2){return this.own(command,parent2,options.signal,true,(run,signal)=>{const{nodeProcess,...shared}=host2;return runConfinedNodeRealm(command,{...options,signal},{...shared,createWorker:()=>this.takeWorker(host2.workerUrl),runChild:(childCommand,childOptions,argv)=>this.own(childCommand,run,childOptions.signal,false,(_child,signal2)=>host2.runChild(childCommand,{...childOptions,signal:signal2},argv)),...nodeProcess?{nodeProcess:{preparedLimits:nodeProcess.preparedLimits,runChild:(argv,childOptions,admission)=>this.launch(renderCommand(argv),childOptions,{...host2,...childOptions.filesystemPolicy?{policy:childOptions.filesystemPolicy}:{},processAdmission:admission.process,nativeStreams:{limits:host2.nativeStreams.limits,inherited:admission.streams.inherited.map(entry=>({...entry,source:admission.streams.source}))},preparedFiles:admission.preparedFiles},run)}}:{}})})}async own(label,parent2,signal,worker2,start){if(this.disposed)throw new Error("The Node process supervisor is disposed.");signal?.throwIfAborted();if(parent2){parent2.controller.signal.throwIfAborted();if(parent2.finished)throw new Error("The parent process has already exited.")}if(worker2&&this.workers>=this.maxWorkers){throw new Error(`The Node execution worker's ${this.maxWorkers} process realms are all running: ${this.holders()}.`)}if(worker2)this.workers+=1;let settle;const completion=new Promise(resolve2=>{settle=resolve2});this.pending.add(completion);const run={label,worker:worker2,controller:new AbortController,parent:parent2,children:new Set,finished:false,removeAbort:()=>signal?.removeEventListener("abort",abort)};const abort=()=>this.cancel(run,signal?.reason);(parent2?.children??this.roots).add(run);signal?.addEventListener("abort",abort,{once:true});try{if(signal?.aborted)abort();run.controller.signal.throwIfAborted();return await start(run,run.controller.signal)}catch(cause){this.cancel(run,cause);throw cause}finally{if(worker2)this.workers-=1;run.finished=true;this.release(run);this.pending.delete(completion);settle()}}holders(){const counted=new Map;const visit=run=>{if(run.worker&&!run.finished){const label=run.label.length>80?`${run.label.slice(0,77)}...`:run.label;counted.set(label,(counted.get(label)??0)+1)}for(const child of run.children)visit(child)};for(const root2 of this.roots)visit(root2);return[...counted].map(([label,count])=>count>1?`${label} (${count})`:label).join("; ")||"unnamed"}cancel(run,reason){run.controller.abort(reason);for(const child of[...run.children])this.cancel(child,reason)}release(run){run.removeAbort();const siblings=run.parent?.children??this.roots;siblings.delete(run);for(const child of run.children){child.parent=run.parent;siblings.add(child)}run.children.clear();run.parent=void 0}};function restrictNodeWorkerAuthority(){const navigator2=globalThis.navigator;Object.defineProperty(globalThis,"navigator",{value:Object.freeze({hardwareConcurrency:navigator2?.hardwareConcurrency??1,userAgent:navigator2?.userAgent??"",platform:navigator2?.platform??""}),configurable:false,writable:false});for(const name of["indexedDB","caches","localStorage","sessionStorage","Worker","SharedWorker","BroadcastChannel","importScripts"]){const existing=Object.getOwnPropertyDescriptor(globalThis,name);if(existing?.configurable===false&&existing.value===void 0)continue;Object.defineProperty(globalThis,name,{value:void 0,configurable:false,writable:false})}}var scope=self;var PROJECT_HOLD_WAIT_MS=5e3;async function holdProject(projectId){const name=`supercode-browser-project:${projectId}`;const giveUp=new AbortController;const timer=setTimeout(()=>giveUp.abort(),PROJECT_HOLD_WAIT_MS);let release2;try{await new Promise((settle,fail3)=>{void scope.navigator.locks.request(name,{mode:"exclusive",signal:giveUp.signal},()=>new Promise(letGo=>{release2=letGo;settle()})).catch(cause=>fail3(cause))})}catch{throw new Error("This project is already open in another tab of this origin. Close that tab, or serve the project on a port of its own; one page at a time works a project's files.")}finally{clearTimeout(timer)}return release2}function holdPackagesOpen(){return new Promise(resolve2=>{void scope.navigator.locks.request(PACKAGES_OPEN_LOCK,{mode:"shared"},()=>new Promise(release2=>resolve2(release2)))})}async function holdProjectStores(options){const environment={navigator:scope.navigator};const ended2=()=>new Error("Browser Node host is disposed.");const releaseProject2=await holdProject(options.projectId);const open2={};const abandon=()=>{open2.store?.close();open2.shared?.close();open2.releasePackagesOpen?.();releaseProject2();throw ended2()};if(options.disposing())abandon();options.report("sweeping the origin's packages");const startedAt=performance.now();const phases=[];const phase=(name,since)=>{phases.push(`${name} ${Math.round(performance.now()-since)} ms`);return performance.now()};const swept=await sweepSharedPackages(environment,options.report).catch(()=>void 0);if(options.disposing())abandon();if(swept&&swept.packagesDropped>0)console.log(`[packages] swept ${swept.packagesDropped} unlinked of ${swept.packagesDropped+swept.packagesKept}, ${Math.round(swept.bytesDropped/1048576)} MiB${swept.compacted?", compacted":""}`);let at3=phase(swept?`sweep of ${swept.packagesKept+swept.packagesDropped} packages`:"no sweep",startedAt);const releasePackagesOpen2=await holdPackagesOpen();open2.releasePackagesOpen=releasePackagesOpen2;if(options.disposing())abandon();const shared=createPackStore(environment);open2.shared=shared;await shared.initialize(PACKAGES_STORE,{shared:true});if(options.disposing())abandon();at3=phase(`shared store of ${shared.entries.size} entries`,at3);const store=createPackStore(environment,{packages:shared,...options.limits?{limits:options.limits}:{}});open2.store=store;const opened=await store.initialize(options.projectId);if(options.disposing())abandon();if(!opened)await store.replace({files:[],pack:new ArrayBuffer(0)});if(options.disposing())abandon();phase(`project store of ${store.entries.size} entries`,at3);return{shared,store,opened,releaseProject:releaseProject2,releasePackagesOpen:releasePackagesOpen2,phases,startedAt}}var HANDOFF=Symbol.for("browser-substrate.execution-worker.store-handoff");var INITIALIZED=Symbol.for("browser-substrate.execution-worker.engine-initialized");function publishEngineInitialized(initialized2){globalThis[INITIALIZED]=initialized2}function takeStoreHandoff(){const holder=globalThis;const handoff2=holder[HANDOFF];delete holder[HANDOFF];return handoff2}var scope2=self;function livePackStore(packages2){if(!packages2)throw new Error("The origin's package store is not open.");const storage=scope2.navigator.storage;const locks=scope2.navigator.locks;return new PackedBrowserPackInstallStore(packages2,async()=>{const estimate=await storage?.estimate?.();return estimate?.quota===void 0||estimate.usage===void 0?void 0:Math.max(0,estimate.quota-estimate.usage)},work=>locks.request(PACKAGES_LOCK,{mode:"exclusive"},work))}async function answerPackStore(message,signal,context2){const{send:send2}=context2;try{const store=livePackStore(context2.packages);const packages2=context2.packages;if(message.action==="has")send2({type:"pack-store-result",id:message.id,present:await store.has(message.digest)});else if(message.action==="read-artifact"){const bytes2=await store.readArtifact(message.digest);const body=bytes2.buffer;send2({type:"pack-store-result",id:message.id,bytes:body},[body])}else if(message.action==="link-archive"){if(!packages2)throw new Error("The origin's package store is not open.");const target=normalizeStorePath(message.target);if(!target.startsWith("/opt/"))throw new Error("Live-pack archives may only mount below /opt.");await scope2.navigator.locks.request(PACKAGES_LOCK,{mode:"shared"},async()=>{await packages2.refresh();const current3=packages2.entries.has(browserPackCompletePath(message.digest));const flat=packages2.entries.has(flatBrowserPackCompletePath(message.digest));if(!current3&&!flat)throw new Error(`Pack archive ${message.digest} is not completely staged.`);const source=current3?browserPackExpandedPath(message.digest):flatBrowserPackExpandedPath(message.digest);if(!packages2.entries.has(source))throw new Error(`Pack artifact ${message.digest} is not an expanded archive.`);const project=context2.project;if(!project)throw new Error("The live pack needs the worker's packed filesystem.");const existing=project.descendants(target);if(existing.length>0){const staged=packages2.descendants(source);const same=existing.length===staged.length&&staged.every(([path3,entry])=>{const held=project.entries.get(`${target}${path3.slice(source.length)}`);return held?.type===entry.type&&held.mode===entry.mode&&held.length===entry.length&&(entry.type==="directory"||held.pack===PACKAGES_STORE&&held.offset===entry.offset)});if(!same)throw new Error(`Live-pack mount ${target} already belongs to different bytes; activation requires a content-specific root or an explicit safe restart.`);return}context2.linkShared(source,target)});send2({type:"pack-store-result",id:message.id})}else if(message.action==="available"){const availableBytes=await store.availableBytes();send2({type:"pack-store-result",id:message.id,...availableBytes===void 0?{}:{availableBytes}})}else if(message.action==="stage-artifact"){await store.stageArtifact(message.digest,new Uint8Array(message.bytes),message.artifact,signal);send2({type:"pack-store-result",id:message.id})}else if(message.action==="stage-environment"){await store.stageEnvironment(message.digest,message.lock);send2({type:"pack-store-result",id:message.id})}else{if(!context2.project||!packages2)throw new Error("Live-pack retention needs the worker's packed filesystem and shared store.");const root2=`${BROWSER_PACK_RETENTION_ROOT}/revisions/${message.digest.slice("sha256:".length)}`;await scope2.navigator.locks.request(PACKAGES_LOCK,{mode:"shared"},async()=>{await packages2.refresh();if(!packages2.entries.has(browserPackLockPath(message.digest)))throw new Error(`Pack lock ${message.digest} is not staged.`);context2.linkShared(browserPackLockPath(message.digest),`${root2}/lock.json`);for(const artifact of message.artifacts){if(!packages2.entries.has(browserPackCompletePath(artifact.digest)))throw new Error(`Pack artifact ${artifact.digest} is not completely staged.`);context2.linkShared(browserPackArtifactPath(artifact.digest),`${root2}/artifacts/${artifact.digest.slice("sha256:".length)}`)}});send2({type:"pack-store-result",id:message.id})}}catch(cause){const error=cause;send2({type:"pack-store-result",id:message.id,error:{...typeof error?.category==="string"?{category:error.category}:{},message:typeof error?.message==="string"?error.message:String(cause)}})}}function normalizeStorePath(path3){const parts=[];for(const part of path3.split("/")){if(!part||part===".")continue;if(part==="..")parts.pop();else parts.push(part)}return`/${parts.join("/")}`}var ComposeFileError=class extends Error{constructor(line,message){super(`line ${line}: ${message}`);this.line=line;this.name="ComposeFileError"}line};function parseYamlSubset(text){const lines=[];text.split(/\r?\n/).forEach((rawLine,index2)=>{const line=index2+1;if(/^\s*$/.test(rawLine)||/^\s*#/.test(rawLine))return;if(/^---\s*$/.test(rawLine)||/^\.\.\.\s*$/.test(rawLine)){if(lines.length>0)throw new ComposeFileError(line,"multiple documents are not supported.");return}if(/^\s*\t/.test(rawLine))throw new ComposeFileError(line,"tabs are not allowed for indentation.");const indent=rawLine.length-rawLine.trimStart().length;lines.push({line,indent,text:stripComment(rawLine.trim())})});if(lines.length===0)return{};const[value,next2]=parseBlock(lines,0,lines[0].indent);if(next2<lines.length)throw new ComposeFileError(lines[next2].line,"unexpected content.");return value}function stripComment(text){let quote2;for(let index2=0;index2<text.length;index2+=1){const char=text[index2];if(quote2){if(char===quote2)quote2=void 0;continue}if(char==='"'||char==="'"){quote2=char;continue}if(char==="#"&&(index2===0||/\s/.test(text[index2-1])))return text.slice(0,index2).trimEnd()}return text}function parseBlock(lines,start,indent){const first=lines[start];if(first.text.startsWith("- ")||first.text==="-")return parseSequence(lines,start,indent);return parseMapping(lines,start,indent)}function parseSequence(lines,start,indent){const items=[];let index2=start;while(index2<lines.length){const current3=lines[index2];if(current3.indent<indent)break;if(current3.indent>indent)throw new ComposeFileError(current3.line,"unexpected indentation.");if(!(current3.text.startsWith("- ")||current3.text==="-"))break;const rest=current3.text==="-"?"":current3.text.slice(2).trim();if(rest===""){const nextLine=lines[index2+1];if(nextLine&&nextLine.indent>indent){const[value,next2]=parseBlock(lines,index2+1,nextLine.indent);items.push(value);index2=next2}else{items.push(null);index2+=1}continue}if(isMappingEntry(rest)){const virtualIndent=indent+2;const inline={line:current3.line,indent:virtualIndent,text:rest};const spliced=[inline,...lines.slice(index2+1)];const[value,consumed2]=parseMapping(spliced,0,virtualIndent);items.push(value);index2=index2+consumed2;continue}const[scalar,consumed]=parseScalarOrBlock(rest,lines,index2,indent);items.push(scalar);index2=index2+1+consumed}return[items,index2]}function parseMapping(lines,start,indent){const map={};let index2=start;while(index2<lines.length){const current3=lines[index2];if(current3.indent<indent)break;if(current3.indent>indent)throw new ComposeFileError(current3.line,"unexpected indentation.");if(current3.text.startsWith("- ")||current3.text==="-")break;const entry=splitMappingEntry(current3.text,current3.line);const{key,rest}=entry;if(key in map)throw new ComposeFileError(current3.line,`duplicate key ${key}.`);if(rest===""){const nextLine=lines[index2+1];if(nextLine&&(nextLine.indent>indent||nextLine.indent===indent&&(nextLine.text.startsWith("- ")||nextLine.text==="-"))){const[value,next2]=parseBlock(lines,index2+1,nextLine.indent);map[key]=value;index2=next2}else{map[key]=null;index2+=1}continue}const[scalar,consumed]=parseScalarOrBlock(rest,lines,index2,indent);map[key]=scalar;index2=index2+1+consumed}return[map,index2]}function isMappingEntry(text){try{splitMappingEntry(text,0);return true}catch{return false}}function splitMappingEntry(text,line){if(text.startsWith("[")||text.startsWith("{")||text.startsWith('"')&&!/^"[^"]*"\s*:/.test(text)){throw new ComposeFileError(line,`expected a key: ${text}`)}const quoted=/^(?:"([^"]*)"|'([^']*)')\s*:(?:\s+(.*))?$/.exec(text);if(quoted)return{key:quoted[1]??quoted[2]??"",rest:(quoted[3]??"").trim()};const plain=/^([^\s:#][^:]*?)\s*:(?:\s+(.*))?$/.exec(text);if(!plain)throw new ComposeFileError(line,`expected a key: ${text}`);return{key:plain[1],rest:(plain[2]??"").trim()}}function parseScalarOrBlock(text,lines,index2,indent){if(text==="|"||text===">"||text==="|-"||text===">-"){const folded=text.startsWith(">");const chomp=text.endsWith("-");const parts=[];let cursor=index2+1;while(cursor<lines.length&&lines[cursor].indent>indent){parts.push(lines[cursor].text);cursor+=1}const joined=folded?parts.join(" "):parts.join("\n");return[chomp?joined:`${joined}
|
|
5894
5894
|
`,cursor-index2-1]}return[parseFlowScalar(text,lines[index2].line),0]}function parseFlowScalar(text,line){if(text.startsWith("&")||text.startsWith("*")||text.startsWith("!"))throw new ComposeFileError(line,"anchors, aliases, and tags are not supported.");if(text.startsWith("["))return parseFlowSequence(text,line);if(text.startsWith("{"))return parseFlowMapping(text,line);if(text==="null"||text==="~")return null;if(text.startsWith('"')&&text.endsWith('"')&&text.length>=2)return JSON.parse(text);if(text.startsWith("'")&&text.endsWith("'")&&text.length>=2)return text.slice(1,-1).replace(/''/g,"'");return text}function parseFlowSequence(text,line){if(!text.endsWith("]"))throw new ComposeFileError(line,"unterminated flow sequence.");return splitFlow(text.slice(1,-1),line).map(item=>parseFlowScalar(item,line))}function parseFlowMapping(text,line){if(!text.endsWith("}"))throw new ComposeFileError(line,"unterminated flow mapping.");const map={};for(const item of splitFlow(text.slice(1,-1),line)){const entry=splitMappingEntry(item,line);map[entry.key]=parseFlowScalar(entry.rest,line)}return map}function splitFlow(text,line){const items=[];let current3="";let quote2;let depth4=0;for(const char of text){if(quote2){current3+=char;if(char===quote2)quote2=void 0;continue}if(char==='"'||char==="'"){quote2=char;current3+=char;continue}if(char==="["||char==="{")depth4+=1;if(char==="]"||char==="}")depth4-=1;if(char===","&&depth4===0){items.push(current3.trim());current3="";continue}current3+=char}if(quote2)throw new ComposeFileError(line,"unterminated quote.");if(current3.trim()!=="")items.push(current3.trim());return items.filter(item=>item!=="")}function encodeBase64(value){const native=value.toBase64;if(typeof native==="function")return native.call(value);let binary="";for(let offset2=0;offset2<value.byteLength;offset2+=32768){binary+=String.fromCharCode(...value.subarray(offset2,offset2+32768))}return btoa(binary)}function decodeBase64(value){const native=Uint8Array.fromBase64;if(typeof native==="function")return native(value);const binary=atob(value);const out=new Uint8Array(binary.length);for(let index2=0;index2<binary.length;index2+=1)out[index2]=binary.charCodeAt(index2);return out}var SUBSTRATE_CONTROL_PLANE_ROUTES=Object.freeze([{method:"GET",path:"/health",summary:"liveness, provider, sandbox count",safe:true},{method:"GET",path:"/sandboxes",summary:"manager.list()",safe:true},{method:"POST",path:"/sandboxes",summary:"manager.create(options)",safe:false},{method:"GET",path:"/sandboxes/{id}",summary:"one sandbox by id, for a page reattaching after a reload",safe:true},{method:"POST",path:"/sandboxes/{id}/pause",summary:"pause the provider workload with declared process semantics",safe:false},{method:"POST",path:"/sandboxes/{id}/resume",summary:"resume the provider workload and reconnect its agent",safe:false},{method:"GET",path:"/sandboxes/{id}/snapshot",summary:"portable integrity-checked workspace ZIP; process state excluded",safe:true},{method:"POST",path:"/sandboxes/{id}/fork",summary:"create an independent sandbox from a workspace snapshot",safe:false},{method:"DELETE",path:"/sandboxes/{id}",summary:"sandbox.kill()",safe:false},{method:"GET",path:"/sandboxes/{id}/agent/*",summary:"the sandbox's agent, token added server-side",safe:true}]);var MAX_LIFETIME_MS=400*24*60*60*1e3;var HOST_FETCH_DEFAULT_MAX_REQUEST_BYTES=16*1024*1024;var MAX_PROJECT_BYTES=1024*1024*1024;var writeTail=Promise.resolve();var MAX_FILE_BYTES2=128*1024*1024;var MAX_ARCHIVE_BYTES=192*1024*1024;var CRC_TABLES=(()=>{const tables=new Uint32Array(8*256);for(let index2=0;index2<256;index2+=1){let crc=index2;for(let bit=0;bit<8;bit+=1)crc=crc>>>1^3988292384&-(crc&1);tables[index2]=crc>>>0}for(let index2=0;index2<256;index2+=1){for(let slice=1;slice<8;slice+=1){const previous=tables[(slice-1)*256+index2];tables[slice*256+index2]=previous>>>8^tables[previous&255]}}return tables})();var PAYLOAD_BYTES=1024*1024;var CHUNK_BYTES=512*1024;var MAXIMUM_FILE_BYTES=256*1024*1024;var CLOSED_SLOT=5;var ECANCELED=-125;var encoder5=new TextEncoder;var decoder6=new TextDecoder("utf-8",{fatal:true});var BrowserFileCoherenceCoordinator=class{filesystems=new WeakMap;attach(channel,filesystem,onCommit,onApplied){const control=new Int32Array(channel.control);const payload=new Uint8Array(channel.payload);const state=this.state(filesystem);let pending;let reading;let closed=false;let activeRequest;const assertOpen=()=>{if(closed)throw Object.assign(new Error("File-coherence channel was closed."),{errno:-ECANCELED})};channel.port.onmessage=event=>{const requestId2=event.data;if(closed||activeRequest!==void 0||!Number.isSafeInteger(requestId2)||requestId2<1||requestId2>1073741821||requestId2%2!==1||Atomics.load(control,0)!==requestId2)return;activeRequest=requestId2;void(async()=>{try{const operation=Atomics.load(control,1);const inputLength=requiredInteger(Atomics.load(control,3),0,payload.byteLength);const input=inputLength===0?{}:JSON.parse(decoder6.decode(payload.slice(0,inputLength)));if(!input||typeof input!=="object"||Array.isArray(input))throw invalid("Invalid coherent file request.");let output;if(operation===1){reading=void 0;await state.tail;assertOpen();const path3=requiredPath(input.path);if(!filesystem.existsSync(path3))output={exists:false};else{const stat2=filesystem.statSync(path3);if(stat2.isDirectory())throw invalid("A coherent file cannot be a directory.");if(stat2.size!==void 0&&stat2.size>MAXIMUM_FILE_BYTES)throw invalid("Coherent file exceeds 256 MiB.");const bytes2=await filesystem.readFile(path3);assertOpen();if(bytes2.byteLength>MAXIMUM_FILE_BYTES)throw invalid("Coherent file exceeds 256 MiB.");if(bytes2.byteLength)reading={path:path3,bytes:Uint8Array.from(bytes2)};output={exists:true,length:bytes2.byteLength,...stat2.mode===void 0?{}:{mode:stat2.mode},...stat2.mtimeMs===void 0?{}:{mtimeMs:stat2.mtimeMs},parents:coherentFileParents(filesystem,path3)}}}else if(operation===2){const path3=requiredPath(input.path);const offset2=requiredInteger(input.offset,0,MAXIMUM_FILE_BYTES);const length=requiredInteger(input.length,0,CHUNK_BYTES);if(!reading||reading.path!==path3)throw invalid("Inspect the coherent file before reading its chunks.");const bytes2=reading.bytes;if(offset2+length>bytes2.byteLength)throw invalid("Invalid coherent file range.");output={content:encodeBase64(bytes2.subarray(offset2,offset2+length))};if(offset2+length===bytes2.byteLength)reading=void 0}else if(operation===3){reading=void 0;const path3=requiredPath(input.path);const length=requiredInteger(input.length,0,MAXIMUM_FILE_BYTES);pending={path:path3,bytes:new Uint8Array(length),offset:0,...optionalMetadata(input),parents:validatedParents(path3,input.parents)}}else if(operation===4){const offset2=requiredInteger(input.offset,0,MAXIMUM_FILE_BYTES);const chunk=decodeBase64(requiredString(input.content));if(!pending||offset2!==pending.offset||chunk.byteLength>CHUNK_BYTES||offset2+chunk.byteLength>pending.bytes.byteLength){throw invalid("Invalid coherent file chunk.")}pending.bytes.set(chunk,offset2);pending.offset+=chunk.byteLength}else if(operation===5){if(!pending||pending.offset!==pending.bytes.byteLength)throw invalid("Incomplete coherent file write.");const write=pending;pending=void 0;await this.enqueue(state,async()=>{assertOpen();ensureCoherentFileParents(filesystem,write.path,write.parents);filesystem.writeFileSync(write.path,write.bytes);if(write.mode!==void 0)filesystem.chmodSync?.(write.path,write.mode);if(write.mtimeMs!==void 0)filesystem.utimesSync?.(write.path,new Date(write.mtimeMs),new Date(write.mtimeMs));onApplied?.(write.path);await onCommit?.(filesystem)})}else if(operation===6){const path3=requiredPath(input.path);await this.enqueue(state,async()=>{assertOpen();if(filesystem.existsSync(path3)){if(filesystem.statSync(path3).isDirectory())throw invalid("A coherent file cannot be a directory.");filesystem.unlinkSync(path3)}onApplied?.(path3);await onCommit?.(filesystem)})}else throw invalid("Unknown file-coherence operation.");assertOpen();respond(control,payload,requestId2,0,output)}catch(error){pending=void 0;reading=void 0;respond(control,payload,requestId2,errno(error))}finally{activeRequest=void 0}})()};channel.port.start();return()=>{if(closed)return;closed=true;pending=void 0;reading=void 0;channel.port.onmessage=null;Atomics.store(control,CLOSED_SLOT,1);const requestId2=Atomics.load(control,0);if(requestId2>0&&requestId2%2===1)respond(control,payload,requestId2,ECANCELED);Atomics.notify(control,0);channel.port.close()}}state(filesystem){const key=filesystem;let state=this.filesystems.get(key);if(!state){state={tail:Promise.resolve()};this.filesystems.set(key,state)}return state}async enqueue(state,action){const operation=state.tail.then(action);state.tail=operation.catch(()=>void 0);await operation}};var sharedBrowserFileCoherenceCoordinator=new BrowserFileCoherenceCoordinator;function coherentFileParents(filesystem,path3){return ancestorPaths(path3).flatMap(parent2=>{if(!filesystem.existsSync(parent2))return[];const stat2=filesystem.statSync(parent2);if(!stat2.isDirectory())throw invalid("A coherent file parent must be a directory.");return[{path:parent2,...optionalMetadata({mode:stat2.mode,mtimeMs:stat2.mtimeMs})}]})}function ensureCoherentFileParents(filesystem,path3,parents){const metadata=new Map(validatedParents(path3,parents).map(entry=>[entry.path,entry]));for(const parent2 of ancestorPaths(path3)){if(filesystem.existsSync(parent2)){if(!filesystem.statSync(parent2).isDirectory())throw invalid("A coherent file parent must be a directory.");continue}filesystem.mkdirSync(parent2);const entry=metadata.get(parent2);if(entry?.mode!==void 0)filesystem.chmodSync?.(parent2,entry.mode);if(entry?.mtimeMs!==void 0)filesystem.utimesSync?.(parent2,new Date(entry.mtimeMs),new Date(entry.mtimeMs))}}function validatedParents(path3,value){if(value===void 0)return[];const ancestors=new Set(ancestorPaths(path3));if(!Array.isArray(value)||value.length>ancestors.size)throw invalid("Invalid coherent file parents.");return value.map(entry=>{if(typeof entry!=="object"||entry===null)throw invalid("Invalid coherent file parent.");const record=entry;const parent2=requiredPath(record.path);if(!ancestors.delete(parent2))throw invalid("Coherent metadata must name distinct ancestors of its file.");return{path:parent2,...optionalMetadata(record)}})}function ancestorPaths(path3){const parts=[];for(const part of requiredPath(path3).split("/")){if(!part||part===".")continue;if(part==="..")parts.pop();else parts.push(part)}return parts.slice(0,-1).map((_,index2)=>`/${parts.slice(0,index2+1).join("/")}`)}function optionalMetadata(input){const mode=input.mode===void 0?void 0:requiredInteger(input.mode,0,65535);const mtimeMs=input.mtimeMs===void 0?void 0:requiredFinite(input.mtimeMs);return{...mode===void 0?{}:{mode},...mtimeMs===void 0?{}:{mtimeMs}}}function requiredPath(value){const path3=requiredString(value);if(!path3.startsWith("/")||path3.length>4096||path3.includes("\0"))throw invalid("Invalid coherent file path.");return path3}function requiredString(value){if(typeof value!=="string")throw invalid("Expected a string.");return value}function requiredInteger(value,minimum,maximum){if(!Number.isSafeInteger(value)||value<minimum||value>maximum){throw invalid("Expected a bounded integer.")}return value}function requiredFinite(value){if(typeof value!=="number"||!Number.isFinite(value))throw invalid("Expected a finite number.");return value}function invalid(message){return Object.assign(new Error(message),{errno:22})}function errno(error){const value=typeof error==="object"&&error!==null&&"errno"in error?Number(error.errno):5;return-(Number.isSafeInteger(value)&&value>0?value:5)}function respond(control,payload,requestId2,result,output){let encoded;try{encoded=output===void 0?new Uint8Array:encoder5.encode(JSON.stringify(output))}catch{encoded=new Uint8Array;result=-5}if(Atomics.compareExchange(control,0,requestId2,-requestId2)!==requestId2)return;if(encoded.byteLength>payload.byteLength){Atomics.store(control,2,-90);Atomics.store(control,4,0)}else{if(encoded.byteLength>0)payload.set(encoded);Atomics.store(control,2,result);Atomics.store(control,4,encoded.byteLength)}Atomics.store(control,0,requestId2+1);Atomics.notify(control,0)}var PAYLOAD_BYTES2=64*1024;var EAGAIN=-11;var EINTR=-4;var CLOSED_SLOT2=3;var BrowserFileLockCoordinator=class{locks=[];pending=[];attach(channel,ownerPrefix){if(typeof ownerPrefix!=="string"||!ownerPrefix||ownerPrefix.includes("\0"))throw new Error("Invalid file-lock owner prefix.");const control=new Int32Array(channel.control);const payload=new Uint8Array(channel.payload);const decoder11=new TextDecoder("utf-8",{fatal:true});let closed=false;let activeRequest;channel.port.onmessage=event=>{const requestId2=event.data;if(closed||activeRequest!==void 0||!Number.isSafeInteger(requestId2)||requestId2<1||requestId2>1073741821||requestId2%2!==1||Atomics.load(control,0)!==requestId2)return;let request;try{const length=Atomics.load(control,1);if(length<1||length>payload.byteLength)throw new Error("Invalid file-lock request length.");request=JSON.parse(decoder11.decode(payload.slice(0,length)));validateRequest(request,ownerPrefix)}catch{respond2(control,payload,requestId2,{result:-22});return}activeRequest=requestId2;this.dispatch(request,response=>{if(activeRequest===requestId2)activeRequest=void 0;respond2(control,payload,requestId2,response)})};channel.port.start();return()=>{if(closed)return;closed=true;channel.port.onmessage=null;Atomics.store(control,CLOSED_SLOT2,1);this.releasePrefix(ownerPrefix);const requestId2=Atomics.load(control,0);if(requestId2>0&&requestId2%2===1)respond2(control,payload,requestId2,{result:EINTR});Atomics.notify(control,0);channel.port.close()}}dispatch(request,complete){if(request.operation==="release-owner"){this.releaseOwner(request.owner);complete({result:0});return}if(request.operation==="unlock"){this.removeRange(request.owner,request.namespace,request.path,request.range);this.drain();complete({result:0});return}const conflict=this.conflict(request);if(request.operation==="query"){complete({result:0,...conflict?{conflict:publicConflict(conflict)}:{}});return}if(conflict){if(!request.blocking)complete({result:EAGAIN});else this.pending.push({request,complete});return}this.install(request);complete({result:0})}conflict(request){return this.locks.find(lock=>lock.namespace===request.namespace&&lock.path===request.path&&lock.owner!==request.owner&&overlaps(lock,request.range)&&(lock.mode==="write"||request.mode==="write"))}install(request){this.removeRange(request.owner,request.namespace,request.path,request.range);this.locks.push({owner:request.owner,namespace:request.namespace,path:request.path,mode:request.mode,pid:request.pid,...request.range})}removeRange(owner,namespace,path3,range3){for(let index2=this.locks.length-1;index2>=0;index2-=1){const lock=this.locks[index2];if(lock.owner!==owner||lock.namespace!==namespace||lock.path!==path3||!overlaps(lock,range3))continue;this.locks.splice(index2,1,...subtract(lock,range3))}}releaseOwner(owner){for(let index2=this.locks.length-1;index2>=0;index2-=1){if(this.locks[index2].owner===owner)this.locks.splice(index2,1)}for(let index2=this.pending.length-1;index2>=0;index2-=1){if(this.pending[index2].request.owner===owner){const[removed]=this.pending.splice(index2,1);removed.complete({result:EINTR})}}this.drain()}releasePrefix(prefix2){const owns2=owner=>owner===prefix2||owner.startsWith(`${prefix2}:`);for(let index2=this.locks.length-1;index2>=0;index2-=1){if(owns2(this.locks[index2].owner))this.locks.splice(index2,1)}for(let index2=this.pending.length-1;index2>=0;index2-=1){if(owns2(this.pending[index2].request.owner)){const[removed]=this.pending.splice(index2,1);removed.complete({result:EINTR})}}this.drain()}drain(){for(let index2=0;index2<this.pending.length;){const pending=this.pending[index2];if(this.conflict(pending.request)){index2+=1;continue}this.pending.splice(index2,1);this.install(pending.request);pending.complete({result:0})}}};var sharedBrowserFileLockCoordinator=new BrowserFileLockCoordinator;function validateRequest(request,ownerPrefix){if(!request||typeof request!=="object"||!owns(ownerPrefix,request.owner))throw new Error("Invalid lock owner.");if(!["query","set","unlock","release-owner"].includes(request.operation))throw new Error("Invalid file lock operation.");if(request.operation==="release-owner")return;if(!["posix","ofd","flock"].includes(request.namespace)||typeof request.path!=="string"||!request.path.startsWith("/")||request.path.length>4096||request.path.includes("\0")||!validRange(request.range))throw new Error("Invalid file lock request.");const parts=[];for(const part of request.path.split("/")){if(!part||part===".")continue;if(part==="..")parts.pop();else parts.push(part)}request.path=`/${parts.join("/")}`;if(request.operation==="set"&&request.blocking!==void 0&&typeof request.blocking!=="boolean"){throw new Error("Invalid file lock blocking option.")}if(request.operation!=="unlock"&&(!["read","write"].includes(request.mode)||!Number.isSafeInteger(request.pid)||request.pid<0)){throw new Error("Invalid file lock request.")}}function validRange(range3){return!!range3&&typeof range3==="object"&&Number.isSafeInteger(range3.start)&&range3.start>=0&&(range3.end===void 0||Number.isSafeInteger(range3.end)&&range3.end>range3.start)}function owns(prefix2,owner){return typeof owner==="string"&&(owner===prefix2||owner.startsWith(`${prefix2}:`))}function publicConflict(lock){return{mode:lock.mode,start:lock.start,...lock.end===void 0?{}:{end:lock.end},pid:lock.pid}}function overlaps(left,right){return left.start<(right.end??Number.POSITIVE_INFINITY)&&right.start<(left.end??Number.POSITIVE_INFINITY)}function subtract(lock,range3){const result=[];if(lock.start<range3.start)result.push({...lock,end:range3.start});const lockEnd=lock.end??Number.POSITIVE_INFINITY;const rangeEnd=range3.end??Number.POSITIVE_INFINITY;if(rangeEnd<lockEnd)result.push({...lock,start:rangeEnd,...lock.end===void 0?{}:{end:lock.end}});return result}function respond2(control,payload,requestId2,response){let encoded=new TextEncoder().encode(JSON.stringify(response));if(encoded.byteLength>payload.byteLength)encoded=new TextEncoder().encode('{"result":-90}');if(Atomics.compareExchange(control,0,requestId2,-requestId2)!==requestId2)return;payload.set(encoded);Atomics.store(control,2,encoded.byteLength);Atomics.store(control,0,requestId2+1);Atomics.notify(control,0)}var IMAGE_LAYERS_KIND="browser-substrate-image-layers";var IMAGE_LAYERS_VERSION=1;function validPreparedRoot(root2){return typeof root2==="string"&&root2.startsWith("/workspace/")&&!root2.split("/").some(segment=>segment==="."||segment==="..")}function validatePreparedImageIndex(prepared){if(!prepared||![prepared.packBytes,prepared.liveBytes,prepared.entries].every(n8=>Number.isSafeInteger(n8)&&n8>=0)||prepared.liveBytes>prepared.packBytes||prepared.entries>1e6)throw new Error("Invalid prepared image bounds.");if(prepared.project){const project=prepared.project;if(![project.entries,project.linked,project.linkedBytes].every(n8=>Number.isSafeInteger(n8)&&n8>=0)||project.entries>1e6||project.linked>project.entries||!Array.isArray(project.plans)||project.plans.some(plan=>!plan||!validPreparedRoot(plan.root)||typeof plan.key!=="string"||!plan.key)||project.trees!==void 0&&(!Array.isArray(project.trees)||project.trees.length>16||project.trees.some(tree2=>!tree2||!validPreparedRoot(tree2.root)||typeof tree2.integrity!=="string"||!tree2.integrity||tree2.integrity.length>256)||new Set(project.trees.map(tree2=>tree2.root)).size!==project.trees.length)){throw new Error("Invalid prepared project metadata.")}}for(const file2 of[prepared.json,prepared.binary,...prepared.project?[prepared.project.json,prepared.project.binary]:[]]){if(!file2||typeof file2.url!=="string"||!/^\/substrate\/[A-Za-z0-9._/-]+$/u.test(file2.url)||file2.url.split("/").some(segment=>segment==="."||segment==="..")||!Number.isSafeInteger(file2.bytes)||file2.bytes<0||!Number.isSafeInteger(file2.raw)||file2.raw<0||file2.raw>1024*1024*1024||typeof file2.sha256!=="string"||!/^[a-f0-9]{64}$/u.test(file2.sha256))throw new Error("Invalid prepared image metadata file.")}if(validateImageRanges(prepared.ranges).bytes!==prepared.packBytes)throw new Error("Prepared image ranges do not cover its pack.");return prepared}function validateImageLayers(candidate){const fail3=what=>{throw new Error(`The image's layers are malformed: ${what}.`)};if(!candidate||typeof candidate!=="object")fail3("not an object");const document2=candidate;if(document2.kind!==IMAGE_LAYERS_KIND||document2.version!==IMAGE_LAYERS_VERSION)fail3("an unknown kind or version");if(!Number.isFinite(document2.mtimeMs)||!Array.isArray(document2.parts))fail3("no time or parts");for(const part of document2.parts){if(!part||typeof part.url!=="string"||!Number.isSafeInteger(part.bytes)||!Number.isSafeInteger(part.raw)||part.raw<0||typeof part.sha256!=="string"||!/^[0-9a-f]{64}$/u.test(part.sha256)||!Array.isArray(part.units))fail3("a part without its url, sizes, digest or units");for(const unit of part.units){if(!unit||unit.kind!=="package"&&unit.kind!=="body"&&unit.kind!=="module"&&unit.kind!=="program"&&unit.kind!=="tree"||typeof unit.id!=="string"||typeof unit.root!=="string"||!unit.root.startsWith("/packages/")||typeof unit.marker!=="string"||!unit.marker.startsWith("/packages/")||!Array.isArray(unit.files))fail3(`a unit of ${part.url} without its kind, root, marker or files`);for(const file2 of unit.files){if(!Array.isArray(file2)||file2.length!==5||typeof file2[0]!=="string"||file2[1]!=="f"&&file2[1]!=="d"&&file2[1]!=="l"||!Number.isSafeInteger(file2[2])||!Number.isSafeInteger(file2[3])||!Number.isSafeInteger(file2[4])||file2[3]<0||file2[4]<0||file2[3]+file2[4]>part.raw||file2[0].split("/").some(segment=>segment===".."||segment==="."))fail3(`a file of ${unit.id} outside its part or its root`)}}}if(document2.prepared){const prepared=validatePreparedImageIndex(document2.prepared);if(document2.parts.reduce((total,part)=>total+part.raw,0)!==prepared.packBytes)fail3("prepared metadata does not fit its parts")}return document2}function imageLayerPath(unit,relative2){return relative2===""?unit.root:`${unit.root}/${relative2}`}function imageLayersAppliedPath(digest){return`/packages/.layers/${digest}`}function imageLayersDeferredPath(digest){return`/packages/.layers-deferred/${digest}`}var PROGRAM_ARCHIVE_RECEIPT=".browser-program-archives";function splitShellChain(command){const whole=[{operator:void 0,command}];if(/[|<>()]/u.test(unquoted(command).replace(/\|\|/gu,""))||/[`$]/u.test(unquoted(command,"'"))||/(^|[;&|]\s*)cd\s/u.test(command))return whole;const links=[];let current3="";let operator;let quote2;for(let index2=0;index2<command.length;index2+=1){const character=command[index2];if(quote2){current3+=character;if(character===quote2)quote2=void 0;continue}if(character==='"'||character==="'"){quote2=character;current3+=character;continue}const pair=command.slice(index2,index2+2);if(pair==="&&"||pair==="||"||character===";"){if(current3.trim()==="")return whole;links.push({operator,command:current3.trim()});operator=character===";"?";":pair;current3="";if(pair==="&&"||pair==="||")index2+=1;continue}current3+=character}if(quote2||current3.trim()==="")return whole;links.push({operator,command:current3.trim()});return links.length>1?links:whole}function splitTrailing(trailing2){let quote2;for(let index2=0;index2<trailing2.length;index2+=1){const character=trailing2[index2];if(quote2){if(character===quote2)quote2=void 0;continue}if(character==="\\"){index2+=1;continue}if(character==="'"||character==='"'){quote2=character;continue}if(/[;&|<>]/u.test(character))return{words:trailing2.slice(0,index2).trim(),rest:trailing2.slice(index2).trim()}}return{words:trailing2.trim(),rest:""}}function unquoted(command,drop2=`"'`){let out="";let quote2;for(const character of command){if(quote2){if(character===quote2)quote2=void 0;else if(!drop2.includes(quote2))out+=character;continue}if(character==='"'||character==="'"){quote2=character;continue}out+=character}return out}function chainContinues(operator,exitCode){if(operator==="&&")return exitCode===0;if(operator==="||")return exitCode!==0;return true}function shellCommandLine(command){const match2=/^\s*(?:\/usr\/bin\/env\s+)?(?:\/(?:usr\/)?bin\/)?(?:sh|bash|zsh|dash)\s+-[a-zA-Z]*c[a-zA-Z]*\s+(.+?)\s*$/su.exec(command);if(!match2)return void 0;const rest=match2[1];const withPositionals=(line2,trailing2)=>{const{words,rest:rest2}=splitTrailing(trailing2);const body=words&&line2.includes("$")?`set -- ${words}; shift; ${line2}`:line2;return rest2?`{ ${body}
|
|
5895
5895
|
} ${rest2}`:body};let line="";let quote2;let index2=0;for(;index2<rest.length;index2+=1){const character=rest[index2];if(quote2==="'"){if(character==="'")quote2=void 0;else line+=character;continue}if(character==="\\"&&index2+1<rest.length&&(quote2===void 0||/["\\$`]/u.test(rest[index2+1]))){line+=rest[index2+1];index2+=1;continue}if(quote2==='"'){if(character==='"')quote2=void 0;else line+=character;continue}if(character==="'"||character==='"'){quote2=character;continue}if(/\s/u.test(character))break;line+=character}if(quote2)return void 0;return withPositionals(line,rest.slice(index2))}var MAX_VIRTUAL_WEBSOCKET_FRAME_BYTES=32*1024*1024;var MAX_HTTP_TRANSPORT_POLICY_BYTES=1024*1024;var DEFAULT_BROWSER_RUNTIME_LIMITS=Object.freeze({maxConcurrentProcesses:64,maxProcessOutputBytes:16*1024*1024,maxProcessRuntimeMs:0,maxVirtualPorts:64,maxFilesystemEntries:1e6,maxFilesystemBytes:1024*1024*1024,maxVirtualRequests:32,maxVirtualWebSockets:32,maxVirtualRequestBytes:16*1024*1024,maxVirtualResponseBytes:32*1024*1024,maxPreviewCommands:16,maxPreviewObservations:1e3,maxEgressConnections:16,maxEgressBytes:64*1024*1024});var encoder6=new TextEncoder;var decoder7=new TextDecoder;var MAX_PUBLISH_BYTES=16*1024*1024;var MAX_TUNNEL_BUFFERED_BYTES=4*1024*1024;var TUNNEL_PAUSE_BYTES=1024*1024;var TUNNEL_RESUME_BYTES=256*1024;var TUNNEL_HELD_CEILING_BYTES=16*1024*1024;var TUNNEL_SOCKET_PART_BYTES=512*1024;var TUNNEL_SOCKET_PART_CHARS=256*1024;var RETAINED_OUTPUT_BYTES=64*1024;var encoder7=new TextEncoder;var decoder8=new TextDecoder;var DOCKER_ENGINE_API_VERSION="1.51";var DOCKER_ENGINE_BASE_PATH=`/v${DOCKER_ENGINE_API_VERSION}`;var encoder8=new TextEncoder;var decoder9=new TextDecoder;var CROSS_ORIGIN_ISOLATION_WORKER_SOURCE=['"use strict";',`if (!self.__dockerEngineHandles) try { importScripts("/docker-engine-sw.js"); } catch (error) { console.warn("[SW] the container's wire is not carried:", error); }`,'if (!self.__packFilesHandles) try { importScripts("/pack-files-sw.js"); } catch (error) { console.warn("[SW] the pack files are not carried:", error); }','self.addEventListener("install", () => self.skipWaiting());','self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim()));','self.addEventListener("fetch", (event) => {'," const request = event.request;"," if (self.__dockerEngineHandles && self.__dockerEngineHandles(request)) return;"," if (self.__packFilesHandles && self.__packFilesHandles(request)) return;",' if (request.cache === "only-if-cached" && request.mode !== "same-origin") return;'," event.respondWith(fetch(request).then((response) => {",' if (response.status === 0 || response.type === "opaque") return response;'," const headers = new Headers(response.headers);",' headers.set("Cross-Origin-Opener-Policy", "same-origin");',' headers.set("Cross-Origin-Embedder-Policy", "credentialless");',' if (!headers.has("Cross-Origin-Resource-Policy")) headers.set("Cross-Origin-Resource-Policy", "cross-origin");'," return new Response(response.body, { status: response.status, statusText: response.statusText, headers });"," }));","});",""].join("\n");var HTTP_RELAY_MAX_METADATA_BYTES=32*1024;var HTTP_RELAY_MAX_FRAME_BYTES=64*1024;var HTTP_RELAY_MAX_ERROR_BYTES=4*1024;var HTTP_RELAY_MAX_BUFFERED_REQUEST_BYTES=32*1024;var BUN_RUNTIME_DIRECTORY="/tmp/browser-runtime-bun";var BUN_GLOBALS_PATH=`${BUN_RUNTIME_DIRECTORY}/bun.cjs`;var BUN_BUILD_PATH=`${BUN_RUNTIME_DIRECTORY}/build.cjs`;var BUN_ENVIRONMENT_FLAG="BROWSER_RUNTIME_BUN";var BUN_VERSION="1.1.0";var BUN_GLOBALS_SOURCE=String.raw`"use strict";
|
|
@@ -6048,7 +6048,7 @@ esbuild.build({ ...options, entryPoints, write: false, absWorkingDir: process.cw
|
|
|
6048
6048
|
`;function translatePackageManagerCommand(argv){const[manager,...rest]=argv;const flags=rest.filter(arg=>arg.startsWith("-"));const separator=rest.indexOf("--");const words=(separator<0?rest:rest.slice(0,separator)).filter(arg=>!arg.startsWith("-"));const dev=flags.some(flag=>["-D","--save-dev","--dev","-d"].includes(flag))?["--save-dev"]:[];const command=words[0];const passthrough=from=>words.slice(from);const installFlags=production=>[...flags.some(flag=>production.includes(flag))?["--omit=dev"]:[],...flags.includes("--ignore-scripts")?["--ignore-scripts"]:[]];switch(manager){case"pnpm":{if(command===void 0||command==="install"||command==="i")return{argv:["npm","install",...installFlags(["--prod","-P","--production"])]};if(command==="add")return{argv:["npm","install",...dev,...passthrough(1)]};if(command==="remove"||command==="rm"||command==="uninstall")return{argv:["npm","uninstall",...passthrough(1)]};if(command==="run"||command==="run-script")return{argv:["npm","run",...passthrough(1),...trailing(rest)]};if(command==="exec")return{argv:["npx",...passthrough(1)]};if(command==="dlx")return{argv:["npx",...passthrough(1)]};if(command==="start"||command==="test")return{argv:["npm",command,...trailing(rest)]};return{argv:["npm","run",command,...passthrough(1),...trailing(rest)]}}case"yarn":{if(command===void 0||command==="install")return{argv:["npm","install",...installFlags(["--production","--prod"])]};if(command==="add")return{argv:["npm","install",...dev,...passthrough(1)]};if(command==="remove")return{argv:["npm","uninstall",...passthrough(1)]};if(command==="run")return{argv:["npm","run",...passthrough(1),...trailing(rest)]};if(command==="dlx"||command==="exec")return{argv:["npx",...passthrough(1)]};if(command==="start"||command==="test")return{argv:["npm",command,...trailing(rest)]};return{argv:["npm","run",command,...passthrough(1),...trailing(rest)]}}case"bun":{if(flags.includes("--version")||flags.includes("-v"))return{argv:["node","-e",`process.stdout.write(${JSON.stringify(`${BUN_VERSION}
|
|
6049
6049
|
`)})`]};if(command===void 0||command==="install"||command==="i")return{argv:["npm","install",...installFlags(["--production","-p"])]};if(command==="add")return{argv:["npm","install",...dev,...passthrough(1)]};if(command==="remove"||command==="rm")return{argv:["npm","uninstall",...passthrough(1)]};if(command==="run"){const target=words[1];if(target&&/\.(m?js|cjs|ts|mts|cts|jsx|tsx)$/u.test(target))return{argv:["node",...passthrough(1)],bun:true};return{argv:["npm","run",...passthrough(1),...trailing(rest)]}}if(command==="build")return{argv:["node",BUN_BUILD_PATH,...rest.filter(arg=>arg!=="build")],bun:true};if(command==="x")return{argv:["npx",...passthrough(1)]};if(command==="start"||command==="test")return{argv:["npm",command,...trailing(rest)]};if(/\.(m?js|cjs|ts|mts|cts|jsx|tsx)$/u.test(command))return{argv:["node",...words],bun:true};return{argv:["npm","run",command,...passthrough(1),...trailing(rest)]}}case"corepack":return{argv:[],note:"corepack: the tab's package managers are provided by the page; there is nothing to enable.\n"};case"uv":{if(command==="pip")return{argv:["pip",...passthrough(1),...flags.filter(flag=>flag!=="--system")]};if(command==="sync"||command==="lock")return{argv:["pip","install","."]};if(command==="add")return{argv:["pip","install",...passthrough(1)]};if(command==="run")return{argv:words[1]==="python"?["python",...passthrough(2)]:["python",...passthrough(1)]};if(command==="venv")return{argv:[],note:"uv venv: the tab runs one Python; no virtual environment is created.\n"};return void 0}default:return void 0}}function trailing(rest){const separator=rest.indexOf("--");return separator>=0?["--",...rest.slice(separator+1)]:[]}function packageManagerAliasRunner(manager,run){return async(argv,options)=>{const translation=translatePackageManagerCommand(argv);if(!translation){const message=`${manager}: ${argv.slice(1).join(" ")||"(no command)"} has no equivalent in the tab; its scripts run through \`${manager} run\`, and its dependencies are prepared on a machine by \`npx @volter/browser-substrate dev\`.
|
|
6050
6050
|
`;options.onStderr?.(message);return{stdout:"",stderr:message,exitCode:2}}if(translation.note)options.onStderr?.(translation.note);if(translation.argv.length===0)return{stdout:"",stderr:"",exitCode:0};const runOptions=translation.bun?{...options,env:{...options.env??{},[BUN_ENVIRONMENT_FLAG]:"1"}}:options;return run(translation.argv.map(shellQuote2).join(" "),runOptions)}}function shellQuote2(word){return/^[A-Za-z0-9_@%+=:,./-]+$/u.test(word)?word:`'${word.replace(/'/gu,"'\\''")}'`}function rollupFsOver(vfs2){const fs2=vfs2;const stats=path3=>{const stat2=fs2.statSync(path3);return{isFile:()=>stat2.isFile(),isDirectory:()=>stat2.isDirectory(),isSymbolicLink:()=>false,size:stat2.size,mtime:stat2.mtime??new Date(stat2.mtimeMs??0),mtimeMs:stat2.mtimeMs??0}};const removeTree3=path3=>{const stat2=fs2.statSync(path3);if(stat2.isDirectory()){for(const name of fs2.readdirSync(path3))removeTree3(`${path3}/${name}`);fs2.rmdirSync(path3)}else{fs2.unlinkSync(path3)}};let temporaries=0;return{appendFile:async(path3,data2)=>{const existing=fs2.existsSync(path3)?fs2.readFileSync(path3):new Uint8Array;const bytes2=typeof data2==="string"?new TextEncoder().encode(data2):data2;const joined=new Uint8Array(existing.byteLength+bytes2.byteLength);joined.set(existing,0);joined.set(bytes2,existing.byteLength);fs2.writeFileSync(path3,joined)},copyFile:async(source,destination)=>{fs2.writeFileSync(destination,fs2.readFileSync(source))},mkdir:async(path3,options)=>{fs2.mkdirSync(path3,{recursive:options?.recursive??false})},mkdtemp:async prefix2=>{const path3=`${prefix2}${Date.now().toString(36)}${(temporaries+=1).toString(36)}`;fs2.mkdirSync(path3,{recursive:true});return path3},readdir:async(path3,options)=>{const names2=fs2.readdirSync(path3);if(!options?.withFileTypes)return names2;return names2.map(name=>{const stat2=stats(`${path3.replace(/\/$/u,"")}/${name}`);return{name,isFile:()=>stat2.isFile(),isDirectory:()=>stat2.isDirectory(),isSymbolicLink:()=>false}})},readFile:async(path3,options)=>{const encoding=typeof options==="string"?options:options?.encoding??null;const bytes2=fs2.readFileSync(path3);if(encoding)return typeof bytes2==="string"?bytes2:new TextDecoder().decode(bytes2);return typeof bytes2==="string"?new TextEncoder().encode(bytes2):bytes2},realpath:async path3=>fs2.realpathSync?fs2.realpathSync(path3):path3,rename:async(oldPath,newPath)=>{fs2.renameSync(oldPath,newPath)},rmdir:async(path3,options)=>{if(options?.recursive)removeTree3(path3);else fs2.rmdirSync(path3)},rm:async(path3,options)=>{if(!fs2.existsSync(path3)){if(options?.force)return;throw Object.assign(new Error(`ENOENT: no such file or directory, rm '${path3}'`),{code:"ENOENT"})}if(options?.recursive)removeTree3(path3);else if(fs2.statSync(path3).isDirectory())fs2.rmdirSync(path3);else fs2.unlinkSync(path3)},stat:async path3=>stats(path3),lstat:async path3=>stats(path3),unlink:async path3=>{fs2.unlinkSync(path3)},writeFile:async(path3,data2)=>{fs2.writeFileSync(path3,data2)},access:async path3=>{if(!fs2.existsSync(path3))throw Object.assign(new Error(`ENOENT: no such file or directory, access '${path3}'`),{code:"ENOENT"})}}}var encoder9=new TextEncoder;var CLOCK_TICKS=100;var SOCKET_INODE_BASE=1e5;var STREAM_INODE_BASE=2e5;function file(text,now){return{type:"file",content:encoder9.encode(text),mtime:now,mode:292}}function directory(entries,now){return{type:"directory",children:new Map(Object.entries(entries)),mtime:now,mode:365}}function link(target,now){return{type:"symlink",target,mtime:now,mode:511}}function tcpTable(ports2){const rows=ports2.map((p,index2)=>{const port2=p.port.toString(16).toUpperCase().padStart(4,"0");return`${String(index2).padStart(4)}: 00000000:${port2} 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 ${SOCKET_INODE_BASE+p.port} 1 0000000000000000 100 0 0 10 0
|
|
6051
|
-
`});return" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n"+rows.join("")}var TCP6_HEADER=" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n";function commOf(identity){const first=identity.argv?.[0]??"node";return(first.slice(first.lastIndexOf("/")+1)||first).slice(0,15)}function stat(identity,bootAt){const started2=identity.startedAt===void 0?0:Math.max(0,Math.round((identity.startedAt-bootAt)*CLOCK_TICKS/1e3));const fields=["S",identity.ppid,identity.pid,identity.pid,0,-1,0,0,0,0,0,0,0,0,0,20,0,1,0,started2];while(fields.length<50)fields.push(0);return`${identity.pid} (${commOf(identity)}) ${fields.join(" ")}
|
|
6051
|
+
`});return" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n"+rows.join("")}var TCP6_HEADER=" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n";function commOf(identity){const first=identity.argv?.[0]??"node";return(first.slice(first.lastIndexOf("/")+1)||first).slice(0,15)}function stat(identity,bootAt){const started2=identity.startedAt===void 0?0:Math.max(0,Math.round((identity.startedAt-bootAt)*CLOCK_TICKS/1e3));const fields=["S",identity.ppid,identity.pgid??identity.pid,identity.pid,0,-1,0,0,0,0,0,0,0,0,0,20,0,1,0,started2];while(fields.length<50)fields.push(0);return`${identity.pid} (${commOf(identity)}) ${fields.join(" ")}
|
|
6052
6052
|
`}function fdDirectory(owned2,streams2,now){const fds={};const targets=[...owned2.map(p=>`socket:[${SOCKET_INODE_BASE+p.port}]`),...streams2.filter(h=>!h.listening).map(h=>`${h.kind==="tcp"?"socket":"pipe"}:[${STREAM_INODE_BASE+h.id}]`)];targets.forEach((target,index2)=>{fds[String(3+index2)]=link(target,now)});return directory(fds,now)}function processDirectory(identity,bootAt,now){return directory({cmdline:file(identity.argv?identity.argv.join("\0")+"\0":"",now),comm:file(`${commOf(identity)}
|
|
6053
6053
|
`,now),...identity.cwd?{cwd:link(identity.cwd,now)}:{},fd:directory({},now),stat:file(stat(identity,bootAt),now)},now)}function containerProc(processes,ports2,streams2=()=>[]){const bootAt=Date.now();return{node(path3){const now=Date.now();const segments=path3.split("/").filter(Boolean);if(segments[0]==="net"){const net={tcp:()=>file(tcpTable(ports2()),now),tcp6:()=>file(TCP6_HEADER,now)};if(segments.length===1)return directory({tcp:net.tcp(),tcp6:net.tcp6()},now);const table2=segments.length===2?net[segments[1]]:void 0;return table2?.()}const table=processes();if(segments.length===0){const entries={};for(const identity2 of table)entries[String(identity2.pid)]=directory({},now);entries.net=directory({},now);return directory(entries,now)}const identity=/^\d+$/.test(segments[0])?table.find(entry=>entry.pid===Number(segments[0])):void 0;if(!identity)return void 0;let node=segments[1]==="fd"?fdDirectory(ports2().filter(p=>p.pid===identity.pid),streams2().filter(h=>h.pid===identity.pid),now):processDirectory(identity,bootAt,now);for(const segment of segments.slice(segments[1]==="fd"?2:1))node=node?.type==="directory"?node.children?.get(segment):void 0;return node}}}function mountContainerProc(filesystem,processes,ports2,streams2){return filesystem.mount("/proc",containerProc(processes,ports2,streams2))}var groups=["dependencies","devDependencies","optionalDependencies"];var ignored=new Set(["node_modules",".git","dist","build",".substrate"]);function normalizeWorkspacePath(path3){const parts=[];for(const part of path3.split("/")){if(part==="..")parts.pop();else if(part&&part!==".")parts.push(part)}return"/"+parts.join("/")}function workspaceGlob(pattern,value){if(/[\[\]{}()\\]/u.test(pattern))throw new Error(`Unsupported workspace glob: ${pattern}`);let source="";for(let i10=0;i10<pattern.length;i10++){const char=pattern[i10];if(char==="*"&&pattern[i10+1]==="*"){i10++;if(pattern[i10+1]==="/"){i10++;source+="(?:.*/)?"}else source+=".*"}else if(char==="*")source+="[^/]*";else if(char==="?")source+="[^/]";else source+=char.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}return new RegExp(`^${source}$`,"u").test(value)}function discoverPnpmWorkspace(fs2,cwd){let root2=normalizeWorkspacePath(cwd);while(!fs2.existsSync(normalizeWorkspacePath(`${root2}/pnpm-workspace.yaml`))){if(root2==="/")return;root2=root2.slice(0,root2.lastIndexOf("/"))||"/"}root2=root2==="/"?"":root2;const declaration=parseYamlSubset(fs2.readFileSync(`${root2}/pnpm-workspace.yaml`,"utf8"));if(declaration?.packages===void 0)return;if(!Array.isArray(declaration.packages)||!declaration.packages.every(p=>typeof p==="string"))throw new Error("pnpm-workspace.yaml must declare package patterns.");const patterns=declaration.packages;if(patterns.every(pattern=>/^\.\/?$/u.test(pattern)))return;const packages2=[];const skipped=new Set;const visit=(path3,relative2)=>{const included=relative2==="."||patterns.filter(p=>!p.startsWith("!")).some(p=>workspaceGlob(p,relative2))&&!patterns.filter(p=>p.startsWith("!")).some(p=>workspaceGlob(p.slice(1),relative2));const manifestPath=normalizeWorkspacePath(`${path3}/package.json`);if(included&&fs2.existsSync(manifestPath)){const manifest=JSON.parse(fs2.readFileSync(manifestPath,"utf8"));if(typeof manifest.name!=="string"||!manifest.name)throw new Error(`Workspace package at ${relative2} needs a name.`);packages2.push({name:manifest.name,path:path3,relative:relative2,manifest,dependencies:[]})}for(const name of fs2.readdirSync(path3).sort()){if(ignored.has(name)||name.startsWith("."))continue;const child=`${path3}/${name}`;let entry;try{entry=fs2.lstatSync(child)}catch{continue}if(entry.isSymbolicLink()){skipped.add(child);continue}if(entry.isDirectory())visit(child,relative2==="."?name:`${relative2}/${name}`)}};visit(root2||"/",".");for(const path3 of skipped)console.error(`${path3}: link skipped; workspace members are directories, not links.`);const names2=new Map(packages2.map(pkg=>[pkg.name,pkg]));if(names2.size!==packages2.length)throw new Error("Workspace package names must be unique.");for(const pkg of packages2){for(const group of[...groups,"peerDependencies"])for(const[name,spec]of Object.entries(pkg.manifest[group]??{})){if(typeof spec!=="string"||!spec.startsWith("workspace:"))continue;const target=names2.get(name);if(!target)throw new Error(`${pkg.name}: workspace dependency ${name} is missing; refusing registry fallback.`);const range3=spec.slice("workspace:".length);if(!["*","^","~",target.manifest.version].includes(range3))throw new Error(`${pkg.name}: workspace range ${spec} for ${name} requires explicit range support.`);if(group!=="peerDependencies"&&!pkg.dependencies.includes(name))pkg.dependencies.push(name)}}return{root:root2||"/",packages:packages2}}function orderWorkspacePackages(packages2){const selected=new Map(packages2.map(pkg=>[pkg.name,pkg]));const pending=new Set,visited=new Set,ordered=[];const visit=pkg=>{if(visited.has(pkg.name))return;if(pending.has(pkg.name))throw new Error(`Workspace dependency cycle at ${pkg.name}.`);pending.add(pkg.name);for(const name of pkg.dependencies){const dependency=selected.get(name);if(dependency)visit(dependency)}pending.delete(pkg.name);visited.add(pkg.name);ordered.push(pkg)};packages2.forEach(visit);return ordered}var attached=new WeakMap;function configureWorkspaceLinks(fs2,workspace){let links=attached.get(fs2);if(!links){links=[];attached.set(fs2,links)}links.splice(0,links.length,...links.filter(link2=>link2.root!==workspace.root));const next2=[];for(const pkg of workspace.packages){for(const name of new Set([...pkg.dependencies,...Object.keys(pkg.manifest.peerDependencies??{}).filter(name2=>String(pkg.manifest.peerDependencies[name2]).startsWith("workspace:"))])){const dependency=workspace.packages.find(candidate=>candidate.name===name);const path3=`${pkg.path}/node_modules/${name}`;placeLink(fs2,path3,relativePath(`${pkg.path}/node_modules/${name.includes("/")?name.split("/")[0]:""}`.replace(/\/$/u,""),dependency.path));next2.push({path:path3,target:dependency.path,root:workspace.root})}}links.push(...next2);links.sort((a,b)=>b.path.length-a.path.length);const members=Reflect.get(globalThis,WORKSPACE_MEMBERS)??new Set;for(const pkg of workspace.packages)members.add(pkg.path);for(const link2 of links){members.add(link2.path);members.add(link2.target)}Reflect.set(globalThis,WORKSPACE_MEMBERS,members)}function configurePlanAliases(fs2,root2,aliases){const at3=relative2=>`${root2==="/"?"":root2}/${relative2}`;const members=Reflect.get(globalThis,WORKSPACE_MEMBERS)??new Set;for(const alias of aliases){const path3=at3(alias.path);const target=at3(alias.target);placeLink(fs2,path3,relativePath(path3.slice(0,path3.lastIndexOf("/")),target));members.add(path3);members.add(target)}Reflect.set(globalThis,WORKSPACE_MEMBERS,members)}function placeLink(fs2,path3,target){const parent2=path3.slice(0,path3.lastIndexOf("/"));fs2.mkdirSync(parent2,{recursive:true});const linkFs=fs2;if(typeof linkFs.symlinkSync!=="function")throw new Error("The engine filesystem has no symbolic links; a workspace dependency cannot be linked.");let existing;try{existing=linkFs.lstatSync(path3)}catch{existing=void 0}if(existing?.isSymbolicLink()){if(linkFs.readlinkSync(path3)===target)return;linkFs.unlinkSync(path3)}else if(existing?.isDirectory()){if(linkFs.readdirSync(path3).length>0)return;linkFs.rmdirSync(path3)}else if(existing){linkFs.unlinkSync(path3)}linkFs.symlinkSync(target,path3)}function relativePath(from,to2){const a=from.split("/").filter(Boolean);const b=to2.split("/").filter(Boolean);let common2=0;while(common2<a.length&&common2<b.length&&a[common2]===b[common2])common2+=1;const up2=a.length-common2;const rest=b.slice(common2);return[...Array(up2).fill(".."),...rest].join("/")||"."}var WORKSPACE_MEMBERS="__browserRuntimeWorkspaceMembers";function workspaceDependencyPath(fs2,consumer,source){const pending=[{root:consumer,alias:consumer}];const seen=new Set;for(const{root:root2,alias}of pending){if(seen.has(root2))continue;seen.add(root2);for(const link2 of attached.get(fs2)??[]){if(!link2.path.startsWith(`${root2}/node_modules/`))continue;const dependency=alias+link2.path.slice(root2.length);if(source===link2.target||source.startsWith(`${link2.target}/`))return dependency+source.slice(link2.target.length);pending.push({root:link2.target,alias:dependency})}}return void 0}function isWorkspaceDependency(fs2,path3){return attached.get(fs2)?.some(link2=>path3===link2.path||path3.startsWith(`${link2.path}/`)||path3===link2.target||path3.startsWith(`${link2.target}/`))??false}function workspaceDependencySources(fs2,consumer){const roots=new Set([consumer]);for(const root2 of roots){for(const link2 of attached.get(fs2)??[]){if(link2.path.startsWith(`${root2}/node_modules/`))roots.add(link2.target)}}roots.delete(consumer);return[...roots]}var HEADER_INTS=8;var READ=0;var WRITE=1;var COUNT=2;var CLOSED2=3;var LOCK=4;var RING_BYTES=4*1024*1024;var HANDLE="__substrateThreadPort";var SharedRing=class _SharedRing{constructor(buffer2){this.buffer=buffer2;this.header=new Int32Array(buffer2,0,HEADER_INTS);this.bytes=new Uint8Array(buffer2,HEADER_INTS*4);this.capacity=this.bytes.byteLength}buffer;header;bytes;capacity;static create(){return new _SharedRing(new SharedArrayBuffer(HEADER_INTS*4+RING_BYTES))}lock(){while(Atomics.compareExchange(this.header,LOCK,0,1)!==0){}}unlock(){Atomics.store(this.header,LOCK,0)}get closed(){return Atomics.load(this.header,CLOSED2)!==0}close(){Atomics.store(this.header,CLOSED2,1);Atomics.add(this.header,COUNT,1);Atomics.notify(this.header,COUNT)}write(data2){if(data2.byteLength+4>this.capacity)throw new Error(`A thread message of ${data2.byteLength} bytes exceeds the ${this.capacity}-byte port buffer.`);this.lock();try{const read=Atomics.load(this.header,READ);let write=Atomics.load(this.header,WRITE);const used=(write-read+this.capacity)%this.capacity;if(used+data2.byteLength+4>=this.capacity)throw new Error(`The port buffer is full: ${used} bytes unread and a ${data2.byteLength}-byte message waiting.`);const length=new Uint8Array(new Uint32Array([data2.byteLength]).buffer);for(const chunk of[length,data2]){const first=Math.min(chunk.byteLength,this.capacity-write);this.bytes.set(chunk.subarray(0,first),write);if(first<chunk.byteLength)this.bytes.set(chunk.subarray(first),0);write=(write+chunk.byteLength)%this.capacity}Atomics.store(this.header,WRITE,write)}finally{this.unlock()}Atomics.add(this.header,COUNT,1);Atomics.notify(this.header,COUNT)}read(){this.lock();try{let read=Atomics.load(this.header,READ);const write=Atomics.load(this.header,WRITE);if(read===write)return void 0;const take=count=>{const out=new Uint8Array(count);const first=Math.min(count,this.capacity-read);out.set(this.bytes.subarray(read,read+first));if(first<count)out.set(this.bytes.subarray(0,count-first),first);read=(read+count)%this.capacity;return out};const length=new Uint32Array(take(4).buffer)[0];const data2=take(length);Atomics.store(this.header,READ,read);return data2}finally{this.unlock()}}};var encoder10=new TextEncoder;var decoder10=new TextDecoder;function encode(value){const seen=new Set;const walk=input=>{if(input===void 0)return{$t:"undefined"};if(typeof input==="bigint")return{$t:"bigint",v:input.toString()};if(typeof input==="function"||typeof input==="symbol")throw new TypeError(`A thread message cannot carry a ${typeof input}.`);if(input===null||typeof input!=="object")return input;if(isPort(input))throw new TypeError("A message port inside a thread message is not supported; hand it to the thread in workerData.");if(seen.has(input))throw new TypeError("A thread message with a cycle is not supported.");seen.add(input);try{if(input instanceof Date)return{$t:"date",v:input.getTime()};if(input instanceof RegExp)return{$t:"regexp",s:input.source,f:input.flags};if(input instanceof Map)return{$t:"map",v:[...input].map(([k10,v2])=>[walk(k10),walk(v2)])};if(input instanceof Set)return{$t:"set",v:[...input].map(walk)};if(input instanceof ArrayBuffer)return{$t:"bytes",k:"ArrayBuffer",v:base643(new Uint8Array(input))};if(ArrayBuffer.isView(input))return{$t:"bytes",k:input.constructor.name,v:base643(new Uint8Array(input.buffer,input.byteOffset,input.byteLength))};if(input instanceof Error){const own={};for(const key of Object.keys(input))own[key]=walk(input[key]);return{$t:"error",name:input.name,message:input.message,stack:input.stack,own}}if(Array.isArray(input))return input.map(walk);const out={};for(const[key,item]of Object.entries(input))out[key]=walk(item);return out}finally{seen.delete(input)}};return encoder10.encode(JSON.stringify(walk(value)))}function decode2(data2){const revive=input=>{if(input===null||typeof input!=="object")return input;if(Array.isArray(input))return input.map(revive);const tagged=input;switch(tagged.$t){case"undefined":return void 0;case"bigint":return BigInt(tagged.v);case"date":return new Date(tagged.v);case"regexp":return new RegExp(tagged.s,tagged.f);case"map":return new Map(tagged.v.map(([k10,v2])=>[revive(k10),revive(v2)]));case"set":return new Set(tagged.v.map(revive));case"bytes":{const bytes2=fromBase64(tagged.v);const kind=tagged.k;if(kind==="ArrayBuffer")return bytes2.buffer;const View=globalThis[kind];return View?new View(bytes2.buffer):bytes2}case"error":{const Kind=globalThis[tagged.name]??Error;const error=new Kind(tagged.message);error.name=tagged.name;if(typeof tagged.stack==="string")error.stack=tagged.stack;for(const[key,item]of Object.entries(tagged.own))error[key]=revive(item);return error}default:{const out={};for(const[key,item]of Object.entries(tagged))out[key]=revive(item);return out}}};return revive(JSON.parse(decoder10.decode(data2)))}function base643(bytes2){let s10="";for(let i10=0;i10<bytes2.length;i10+=1)s10+=String.fromCharCode(bytes2[i10]);return btoa(s10)}function fromBase64(text){const s10=atob(text);const out=new Uint8Array(s10.length);for(let i10=0;i10<s10.length;i10+=1)out[i10]=s10.charCodeAt(i10);return out}var ports=new WeakSet;function isPort(value){return typeof value==="object"&&value!==null&&ports.has(value)}var ThreadMessagePort=class extends eventsModule.EventEmitter{constructor(incoming2,outgoing,handle){super();this.incoming=incoming2;this.outgoing=outgoing;this.handle=handle;ports.add(this);this.on("newListener",event=>{if(event==="message")this.start()})}incoming;outgoing;handle;#referenced=true;#pumping=false;#closed=false;get referenced(){return this.#referenced&&!this.#closed&&this.listenerCount("message")>0}postMessage(value,transfer2=[]){if(this.#closed)return;if(transfer2.some(item=>!(item instanceof ArrayBuffer)))throw new TypeError("Only ArrayBuffers transfer through a thread message port here.");if(this.outgoing.closed)return;this.outgoing.write(encode(value))}receive(){const data2=this.incoming.read();return data2===void 0?void 0:{message:decode2(data2)}}start(){if(this.#pumping||this.#closed)return;this.#pumping=true;void this.pump()}async pump(){const header=this.incoming.header;while(!this.#closed){const seen=Atomics.load(header,COUNT);for(let next2=this.receive();next2!==void 0;next2=this.receive()){if(this.#closed)return;this.emit("message",next2.message)}if(this.incoming.closed){this.close();return}const waited=Atomics.waitAsync(header,COUNT,seen);if(waited.async)await waited.value}}close(){if(this.#closed)return;this.#closed=true;this.outgoing.close();queueMicrotask(()=>this.emit("close"))}ref(){this.#referenced=true;return this}unref(){this.#referenced=false;return this}toHandle(){return this.handle}};var ThreadMessageChannel=class{port1;port2;constructor(){const ab2=SharedRing.create();const ba2=SharedRing.create();this.port1=new ThreadMessagePort(ba2,ab2,{[HANDLE]:true,ab:ab2.buffer,ba:ba2.buffer,side:1});this.port2=new ThreadMessagePort(ab2,ba2,{[HANDLE]:true,ab:ab2.buffer,ba:ba2.buffer,side:2})}};function receiveMessageOnPort2(port2){if(!isPort(port2))throw new TypeError("receiveMessageOnPort needs a MessagePort.");return port2.receive()}function isHandle(value){return typeof value==="object"&&value!==null&&value[HANDLE]===true}function detachPorts(value){const walk=input=>{if(isPort(input))return input.toHandle();if(input===null||typeof input!=="object")return input;if(Array.isArray(input))return input.map(walk);if(input instanceof ArrayBuffer||ArrayBuffer.isView(input)||input instanceof SharedArrayBuffer||input instanceof Date||input instanceof RegExp||input instanceof Map||input instanceof Set||input instanceof Error)return input;const out={};for(const[key,item]of Object.entries(input))out[key]=walk(item);return out};return walk(value)}function attachPorts(value){const walk=input=>{if(isHandle(input)){const ab2=new SharedRing(input.ab);const ba2=new SharedRing(input.ba);return input.side===1?new ThreadMessagePort(ba2,ab2,input):new ThreadMessagePort(ab2,ba2,input)}if(input===null||typeof input!=="object")return input;if(Array.isArray(input))return input.map(walk);if(input instanceof ArrayBuffer||ArrayBuffer.isView(input)||input instanceof SharedArrayBuffer||input instanceof Date||input instanceof RegExp||input instanceof Map||input instanceof Set||input instanceof Error)return input;const out={};for(const[key,item]of Object.entries(input))out[key]=walk(item);return out};return walk(value)}var bridgeKey=Symbol.for("@volter/browser-node/threads");var ownerKey="__substrateThreadOwner";var UnsupportedBroadcastChannel=class{constructor(){unsupported3("thread broadcast channels")}};var unsupported3=detail=>{throw Object.assign(new Error(`Node thread operation is unsupported: ${detail}`),{code:"ERR_WORKER_UNSUPPORTED"})};var unsupportedOperations=Object.fromEntries(["moveMessagePortToContext","markAsUntransferable","getEnvironmentData","setEnvironmentData"].map(name=>[name,()=>unsupported3(name)]));var absolute=(cwd,path3)=>{const parts=[];for(const part of(path3.startsWith("/")?path3:`${cwd}/${path3}`).split("/")){if(part==="..")parts.pop();else if(part&&part!==".")parts.push(part)}return"/"+parts.join("/")};function installNodeThreadHost(filesystem,bundler2,store,owner){const NativeWorker=globalThis.Worker;const workers2=new Set;const modules2=new WeakMap;let nextId=0;let disposed=false;const bridge={module(fs2,process3,original){if(fs2!==filesystem||disposed)return void 0;const cached=modules2.get(process3);if(cached)return cached;class NodeWorker extends eventsModule.EventEmitter{threadId;resourceLimits={};referenced=true;#worker;#stopServing;constructor(filename,options={}){super();if(disposed||process3[ownerKey]?.stopped)throw new Error("The parent process has ended.");if(workers2.size>=8)throw Object.assign(new Error("The Node pack's eight-thread limit was reached."),{code:"ERR_WORKER_LIMIT"});if(options.eval)unsupported3("eval");if(options.argv?.length)unsupported3("argv");if(options.stdin||options.stdout||options.stderr)unsupported3("redirected stdio");if(options.resourceLimits&&Object.keys(options.resourceLimits).length>0)unsupported3("custom resource limits");const execArgv=(options.execArgv??[]).filter(flag=>flag!=="");if(execArgv.length>0)throw Object.assign(new Error(`Initiated Worker with invalid execArgv flags: ${execArgv.join(", ")}`),{code:"ERR_WORKER_INVALID_EXEC_ARGV"});if(options.env!==void 0&&(typeof options.env!=="object"||options.env===null))unsupported3("shared environment");const path3=filename instanceof URL?filename.protocol==="file:"?decodeURIComponent(filename.pathname):unsupported3("non-file worker URL"):filename;if(typeof path3!=="string"||!path3.startsWith("/")&&!path3.startsWith("./")&&!path3.startsWith("../"))throw new TypeError("A worker filename must be an absolute or explicit relative path.");const target=absolute(process3.cwd(),path3);if(!filesystem.existsSync(target))throw new Error(`Worker entry does not exist: ${target}`);if(options.transferList?.some(item=>!(item instanceof ArrayBuffer)&&!isPort(item)))unsupported3("transferring anything but bytes and message ports");const workerData2=structuredClone(detachPorts(options.workerData));this.threadId=++nextId;const channel=owner?void 0:createBrowserFilesystemChannel();if(channel)this.#stopServing=serveBrowserFilesystemChannel(filesystem,channel.holder);try{this.#worker=owner?requestNodeThread(owner.launcher):new NativeWorker(location.href,{type:"module",name:`node-thread-${this.threadId}`});this.#worker.onmessage=({data:data2})=>{if(!this.#worker)return;if(data2.type==="node-thread-message")this.emit("message",data2.value);else if(data2.type==="node-thread-online")this.emit("online");else if(data2.type==="node-thread-output")(data2.stream==="stderr"?process3.stderr:process3.stdout).write(data2.text);else if(data2.type==="node-thread-error")this.fail(new Error(data2.message));else if(data2.type==="node-thread-exit")this.finish(data2.code)};this.#worker.onerror=event=>{event.preventDefault();this.fail(new Error(event.message))};workers2.add(this);if(process3[ownerKey])(process3[ownerKey].threads??=new Set).add(this);store?.flush();const prepared=owner?.prepared?.();this.#worker.postMessage({type:"node-thread-init",filename:target,cwd:process3.cwd(),env:{...options.env??process3.env},workerData:workerData2,id:this.threadId,...channel?{channel:channel.reader}:{},bundler:bundler2,...prepared?{preparedFiles:prepared.files,preparedLimits:prepared.limits}:{},...store?{store:{projectId:store.projectId}}:{}},channel?[channel.reader.port]:[])}catch(cause){this.finish(1);throw cause}}emit(event,...args){if(process3[ownerKey]?.stopped)return false;const invoke=()=>super.emit(event,...args);return process3.__substrateRunOwnedCallback?process3.__substrateRunOwnedCallback(invoke):invoke()}postMessage(value,transfer2=[]){if(!this.#worker)return;if(transfer2.some(value2=>!(value2 instanceof ArrayBuffer)))unsupported3("transferring thread ports");this.#worker.postMessage({type:"node-thread-message",value},transfer2)}ref(){this.referenced=true;return this}unref(){this.referenced=false;return this}terminate(){this.finish(1);return Promise.resolve(1)}fail(error){this.finish(1);if(this.listenerCount("error"))this.emit("error",error);else{process3.exitCode=1;process3.stderr.write(`${error.stack??error.message}
|
|
6054
6054
|
`)}}finish(code3){if(!this.#worker&&!this.#stopServing)return;this.#worker?.terminate();this.#worker=void 0;this.#stopServing?.();this.#stopServing=void 0;workers2.delete(this);process3[ownerKey]?.threads?.delete(this);queueMicrotask(()=>this.emit("exit",code3))}}const module={...original,...unsupportedOperations,Worker:NodeWorker,MessageChannel:ThreadMessageChannel,MessagePort:ThreadMessagePort,receiveMessageOnPort:receiveMessageOnPort2,BroadcastChannel:UnsupportedBroadcastChannel,default:void 0};module.default=module;modules2.set(process3,module);return module}};Reflect.set(globalThis,bridgeKey,bridge);return{dispose(){disposed=true;for(const worker2 of[...workers2])void worker2.terminate();owner?.launcher.close();if(Reflect.get(globalThis,bridgeKey)===bridge)Reflect.deleteProperty(globalThis,bridgeKey)}}}function receiveNodeThread(event){if(event.data?.type!=="node-thread-init")return false;const message=event.data;const scope4=self;const postToOwner=scope4.postMessage.bind(scope4);const closeThread=scope4.close.bind(scope4);const send2=(data2,transfer2=[])=>postToOwner(data2,transfer2);if(!message.channel)throw new Error("Node thread has no admitted filesystem channel.");const client=new BrowserFilesystemChannelClient(message.channel);const storeEnvironment={navigator:scope4.navigator};const openFilesystem=async()=>{if(message.storeReads||message.preparedLimits||message.filesystemPolicy){let reads2;if(message.storeReads){const grant=message.storeReads;const before=Atomics.load(new Int32Array(grant.clock),STORE_CLOCK_EPOCH);const reader=await openPackReader(storeEnvironment,grant.projectId,grant.seed,grant.imageLine);if(!reader)throw new Error(`The project's store is not there for this thread to read: ${grant.projectId}.`);reads2={opening:Promise.resolve(reader),clock:grant.clock,openedAt:reader.seeded()&&grant.seed?grant.seed.epoch:before}}const files=nodeInvocationFilesystem(message.channel,message.filesystemPolicy,message.preparedLimits?{files:message.preparedFiles??[],limits:message.preparedLimits}:void 0,reads2);await Promise.resolve();return files.guest}const fs2=new VirtualFS;for(const method of["writeFileSync","appendFileSync","writeAtSync","mkdirSync","unlinkSync","rmdirSync","renameSync"]){Reflect.set(fs2,method,client[method].bind(client))}const reads=["existsSync","statSync","lstatSync","readFileSync","readdirSync","realpathSync"];if(message.store){const reader=await openPackReader(storeEnvironment,message.store.projectId);if(!reader)throw new Error(`The project's store is not there for this thread to read: ${message.store.projectId}.`);const backing=new PackedVirtualFS(reader);for(const method of reads){const read=Reflect.get(backing,method);Reflect.set(fs2,method,read.bind(backing))}}else{for(const method of reads)Reflect.set(fs2,method,client[method].bind(client))}for(const method of["watch","symlinkSync","readlinkSync","chmodSync","utimesSync"])Reflect.set(fs2,method,()=>unsupported3(`filesystem ${method}`));return fs2};const workerData2=attachPorts(message.workerData);const heldPorts=[];const collect=value=>{if(isPort(value)){heldPorts.push(value);return}if(value&&typeof value==="object"&&!(value instanceof ArrayBuffer)&&!ArrayBuffer.isView(value))for(const item of Object.values(value))collect(item)};collect(workerData2);const parentPort2=new eventsModule.EventEmitter;const incomingMessages=[];let guestEntryReady=false;const deliverMessages=()=>{if(!guestEntryReady||ended2)return;try{while(incomingMessages.length&&parentPort2.listenerCount("message")>0&&!ended2){const value=incomingMessages.shift();parentPort2.emit("message",value)}}catch(cause){failed(cause)}};parentPort2.on("newListener",event2=>{if(event2==="message")queueMicrotask(deliverMessages)});let ended2=false;const exit=code3=>{if(!ended2){ended2=true;send2({type:"node-thread-exit",code:code3});closeThread()}};parentPort2.postMessage=(value,transfer2=[])=>{if(transfer2.some(value2=>!(value2 instanceof ArrayBuffer)))unsupported3("transferring thread ports");send2({type:"node-thread-message",value},transfer2)};parentPort2.close=()=>exit(0);parentPort2.start=()=>{};let portReferenced=true;parentPort2.ref=()=>{portReferenced=true;return parentPort2};parentPort2.unref=()=>{portReferenced=false;return parentPort2};Reflect.set(globalThis,bridgeKey,{module(_fs,_process,original){const module={...original,...unsupportedOperations,MessageChannel:ThreadMessageChannel,MessagePort:ThreadMessagePort,receiveMessageOnPort:receiveMessageOnPort2,BroadcastChannel:UnsupportedBroadcastChannel,isMainThread:false,threadId:message.id,workerData:workerData2,parentPort:parentPort2,default:void 0};module.default=module;return module}});scope4.addEventListener("message",event2=>{if(event2.data.type==="node-thread-message"){incomingMessages.push(event2.data.value);deliverMessages()}});const failed=cause=>{send2({type:"node-thread-error",message:cause instanceof Error?cause.stack??cause.message:String(cause)});exit(1)};scope4.addEventListener("error",event2=>{event2.preventDefault();failed(event2.error??event2.message)});scope4.addEventListener("unhandledrejection",event2=>{event2.preventDefault();failed(event2.reason)});const originalFetch=globalThis.fetch.bind(globalThis);restrictNodeWorkerAuthority();const assets=new Set([message.bundler?.esbuildWasmUrl,message.bundler?.rollupModuleUrl?.replace(/[^/]+$/u,"bindings_wasm_bg.wasm")].filter(value=>Boolean(value)).map(value=>new URL(value,location.href).href));Object.defineProperty(globalThis,"fetch",{configurable:false,writable:false,value:(input,options)=>{const request=new Request(input,options);if(request.method!=="GET"||!assets.has(request.url)||[...request.headers].length)return Promise.reject(new Error("Node thread network authority is not delegated."));return originalFetch(new Request(request,{credentials:"omit",redirect:"error"}))}});for(const name of["XMLHttpRequest","WebSocket","EventSource","BroadcastChannel","SharedWorker","Worker"]){if(Object.getOwnPropertyDescriptor(globalThis,name)?.configurable===false&&Reflect.get(globalThis,name)===void 0)continue;Object.defineProperty(globalThis,name,{configurable:false,writable:false,value:class{constructor(){unsupported3(`${name} authority`)}}})}const schedule=globalThis.setTimeout.bind(globalThis);const repeat2=globalThis.setInterval.bind(globalThis);const clearTimeout2=globalThis.clearTimeout.bind(globalThis);const clearInterval2=globalThis.clearInterval.bind(globalThis);const timeouts=new Set;const intervals=new Set;globalThis.setTimeout=((callback,delay2,...args)=>{const timer=schedule(()=>{timeouts.delete(timer);callback(...args)},delay2);timeouts.add(timer);return timer});globalThis.setInterval=((callback,delay2,...args)=>{const timer=repeat2(callback,delay2,...args);intervals.add(timer);return timer});globalThis.clearTimeout=(timer=>{timeouts.delete(timer);clearTimeout2(timer)});globalThis.clearInterval=(timer=>{intervals.delete(timer);clearInterval2(timer)});void(async()=>{try{const fs2=await openFilesystem();const runtime=new Runtime(fs2,{cwd:message.cwd,env:message.env,onStdout:text=>send2({type:"node-thread-output",stream:"stdout",text}),onStderr:text=>send2({type:"node-thread-output",stream:"stderr",text}),onConsole:(method,args)=>send2({type:"node-thread-output",stream:method==="error"||method==="warn"?"stderr":"stdout",text:args.map(String).join(" ")+"\n"})});Reflect.set(runtime.process,"exit",exit);if(message.bundler){const shim=esbuildShim;shim.setModuleURL(new URL(message.bundler.esbuildModuleUrl,location.href).href);shim.setWasmURL(new URL(message.bundler.esbuildWasmUrl,location.href).href);if(message.bundler.rollupModuleUrl)Reflect.set(globalThis,"__browserRuntimeRollupUrl",new URL(message.bundler.rollupModuleUrl,location.href).href);Reflect.set(globalThis,"__browserRuntimeRollupFs",rollupFsOver(fs2))}send2({type:"node-thread-online"});await runtime.runFileAsync(message.filename);guestEntryReady=true;deliverMessages();repeat2(()=>{if(!ended2&&!(portReferenced&&parentPort2.listenerCount("message")>0)&&!heldPorts.some(port2=>port2.referenced)&&timeouts.size===0&&intervals.size===0){exit(runtime.process.exitCode??0)}},25)}catch(cause){failed(cause)}})();return true}var BrowserBundler=class{constructor(filesystem,options){this.filesystem=filesystem;this.options=options}filesystem;options;WorkerConstructor=globalThis.Worker;worker;stopServing;pending=new Map;sequence=0;idleTimer;disposed=false;prebundle;neighbors=true;async build(options){const{plugins,...rest}=options;for(const plugin of plugins??[]){if(plugin?.name!=="vfs-loader"&&plugin?.name!=="neighbors")throw new Error(`The bundler worker cannot run the esbuild plugin '${plugin?.name??"?"}'.`)}const result=await this.request({type:"build",id:0,options:rest});for(const file2 of result.outputFiles){Object.defineProperty(file2,"contents",{get:()=>new TextEncoder().encode(file2.text),enumerable:false})}return result}transform(code3,options){return this.request({type:"transform",id:0,code:code3,options:options??{}})}stop(){if(this.idleTimer!==void 0)clearTimeout(this.idleTimer);this.idleTimer=void 0;const stopServing=this.stopServing,worker2=this.worker;this.stopServing=void 0;this.worker=void 0;for(const[,waiter]of this.pending)waiter.reject(new Error("The bundler worker was ended."));this.pending.clear();try{stopServing?.()}finally{worker2?.terminate()}}dispose(){this.disposed=true;this.stop()}request(message){if(this.disposed)return Promise.reject(new Error("The bundler is disposed."));if(this.idleTimer!==void 0)clearTimeout(this.idleTimer);this.idleTimer=void 0;const worker2=this.worker??this.start();const id2=++this.sequence;return new Promise((resolve2,reject)=>{this.pending.set(id2,{resolve:resolve2,reject});try{worker2.postMessage({...message,id:id2})}catch(cause){this.pending.delete(id2);reject(cause instanceof Error?cause:new Error(String(cause)))}}).finally(()=>this.settle())}settle(){if(this.pending.size>0||!this.worker)return;const nativeSetTimeout=globalThis.__browserRuntimeNativeSetTimeout??setTimeout;this.idleTimer=nativeSetTimeout.call(globalThis,()=>this.stop(),this.options.idleMs??1e4)}start(){const worker2=pageWorker(new this.WorkerConstructor(this.options.workerUrl,{type:"module",name:"browser-bundler"}));this.worker=worker2;try{const channel=createBrowserFilesystemChannel();this.stopServing=serveBrowserFilesystemChannel(this.filesystem,channel.holder);worker2.onmessage=event=>{const waiter=this.pending.get(event.data.id);if(!waiter)return;this.pending.delete(event.data.id);if(event.data.type==="error")waiter.reject(new Error(event.data.message));else waiter.resolve(event.data.result)};worker2.onerror=event=>{const cause=new Error(`The bundler worker failed: ${event.message}`);for(const[,waiter]of this.pending)waiter.reject(cause);this.pending.clear();this.stop()};worker2.onmessageerror=()=>{for(const waiter of this.pending.values())waiter.reject(new Error("The bundler worker returned an unreadable message."));this.stop()};worker2.postMessage({type:"attach",channel:channel.reader,esbuildModuleUrl:new URL(this.options.esbuildModuleUrl,location.href).href,esbuildWasmUrl:new URL(this.options.esbuildWasmUrl,location.href).href},[channel.reader.port]);return worker2}catch(cause){this.stop();throw cause}}};function stripJsonComments(text){let result="";let index2=0;let inString=false;while(index2<text.length){const character=text[index2];if(inString){result+=character;if(character==="\\"){result+=text[index2+1]??"";index2+=2;continue}if(character==='"')inString=false;index2+=1;continue}if(character==='"'){inString=true;result+=character;index2+=1;continue}if(character==="/"&&text[index2+1]==="/"){while(index2<text.length&&text[index2]!=="\n")index2+=1;continue}if(character==="/"&&text[index2+1]==="*"){index2+=2;while(index2<text.length&&!(text[index2]==="*"&&text[index2+1]==="/"))index2+=1;index2+=2;continue}result+=character;index2+=1}return result.replace(/,(\s*[}\]])/gu,"$1")}function workspaceCompilerOptions(vfs2,entry){const normalize4=path3=>{const parts=[];for(const part of path3.split("/")){if(part==="..")parts.pop();else if(part&&part!==".")parts.push(part)}return"/"+parts.join("/")};const read=(path3,seen=new Set)=>{if(seen.has(path3)||seen.size>20)throw new Error(`TypeScript config inheritance cycle: ${path3}`);seen.add(path3);const config=JSON.parse(stripJsonComments(vfs2.readFileSync(path3,"utf8")).replace(/,(\s*[}\]])/gu,"$1"));const directory3=path3.slice(0,path3.lastIndexOf("/"));let inherited={};const bases=Array.isArray(config.extends)?config.extends:config.extends?[config.extends]:[];for(const base of bases){if(typeof base!=="string")throw new Error(`${path3}: a TypeScript extends target must be a path.`);const parent2=resolveExtends(directory3,base);if(parent2===void 0)throw new Error(`${path3}: TypeScript config ${JSON.stringify(base)} was not found.`);const next2=read(parent2,seen);inherited={...inherited,...next2}}const own=config.compilerOptions??{};return{...inherited,...own,baseUrl:typeof own.baseUrl==="string"?normalize4(`${directory3}/${own.baseUrl}`):inherited.baseUrl??directory3}};const isFile2=candidate=>{try{return vfs2.existsSync(candidate)&&!vfs2.statSync(candidate).isDirectory()}catch{return false}};const configFile=candidate=>{if(isFile2(candidate))return candidate;if(!candidate.endsWith(".json")&&isFile2(`${candidate}.json`))return`${candidate}.json`;try{const manifest=JSON.parse(vfs2.readFileSync(`${candidate}/package.json`,"utf8"));if(typeof manifest.tsconfig==="string"&&isFile2(normalize4(`${candidate}/${manifest.tsconfig}`)))return normalize4(`${candidate}/${manifest.tsconfig}`)}catch{}return isFile2(`${candidate}/tsconfig.json`)?`${candidate}/tsconfig.json`:void 0};const resolveExtends=(from,base)=>{if(base.startsWith(".")||base.startsWith("/"))return configFile(base.startsWith("/")?normalize4(base):normalize4(`${from}/${base}`));let current3=from||"/";for(;;){const found=configFile(`${current3==="/"?"":current3}/node_modules/${base}`);if(found)return found;if(current3==="/"||current3==="")return void 0;current3=current3.slice(0,current3.lastIndexOf("/"))||"/"}};let directory2=vfs2.realpathSync(entry);directory2=directory2.slice(0,directory2.lastIndexOf("/"));while(directory2){const path3=`${directory2}/tsconfig.json`;if(vfs2.existsSync(path3))return read(path3);if(vfs2.existsSync(`${directory2}/package.json`))return;directory2=directory2.slice(0,directory2.lastIndexOf("/"))}return}function flattenSpecifier(specifier){const flat=specifier.replace(/[/:]/gu,"_").replace(/\./gu,"__").replace(/(\s*>\s*)/gu,"___").replace(/#/gu,"____");return flat.length>170?`${flat.slice(0,160)}_${shortHash(flat)}`:flat}function packFileName(specifier){return`pack_${flattenSpecifier(specifier)}.js`}function packageNameOf2(specifier){const parts=specifier.split("/");return specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0]}function chunkNamePattern(packageName){return`chunk_${flattenSpecifier(packageName)}_[hash]`}var CHUNK_FILE=/^chunk_[\w.@-]+\.js$/u;function isChunkFile(name){return CHUNK_FILE.test(name)}function chunkImports(code3){return[...new Set([...code3.matchAll(/(["'])\.\/(chunk_[\w.@-]+\.js)\1/gu)].map(match2=>match2[2]))]}var PACK_HEADER="// browser-substrate pack:";function formatPackHeader(header){const list2=values=>values.map(value=>encodeURIComponent(value)).join(",");return`${PACK_HEADER} neighbors=${list2(header.neighbors)} chunks=${list2(header.chunks)} exports=${list2(header.exports)} default=${header.hasDefault?1:0}`}function readPackHeader(code3){const line=code3.slice(0,code3.indexOf("\n")<0?code3.length:code3.indexOf("\n"));if(!line.startsWith(PACK_HEADER))return void 0;const field=name=>new RegExp(`\\b${name}=([^ ]*)`,"u").exec(line)?.[1]??"";const list2=value=>value.split(",").filter(Boolean).map(item=>decodeURIComponent(item));return{neighbors:list2(field("neighbors")),chunks:list2(field("chunks")),exports:list2(field("exports")),hasDefault:field("default")==="1"}}function shortHash(text){let hash2=0;for(let index2=0;index2<text.length;index2+=1)hash2=hash2*31+text.charCodeAt(index2)|0;return(hash2>>>0).toString(36)}var NPM_MODULE_PREFIX="/_npm/";var NPM_REQUIRE_PREFIX="/_npm-require/";var BUILT_MODULES_DIRECTORY=".browser-substrate/modules-13";var CHUNK_ROUTE="__chunks/";var MULTI_ENTRY_LIMIT=128;var BARREL_REEXPORTS=256;var BARREL_MARK="// browser-substrate barrel:";var SOURCE_FILE=/\.(?:[cm]?[jt]sx?|vue|svelte|astro|mdx?)$/u;var SKIPPED_DIRECTORIES=new Set(["node_modules",".git","dist","build",".browser-substrate",".substrate","coverage"]);var SOURCE_FILE_LIMIT=5e3;var BUILD_BATCH_WINDOW_MS=25;var BATCH_OUTPUT_DIRECTORY="/_browser-substrate-build";var RESERVED_WORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]);var CONDITION_PRIORITY=["browser","svelte","module","import","default","require"];var BrowserNpmModules=class{constructor(vfs2,workspaceRoot,moduleCache,options={}){this.vfs=vfs2;this.workspaceRoot=workspaceRoot;this.moduleCache=moduleCache;this.options=options;this.nodeModulesRoot=`${workspaceRoot==="/"?"":workspaceRoot}/node_modules`;this.builtRoot=`${this.nodeModulesRoot}/${BUILT_MODULES_DIRECTORY}`;this.vfs.on("change",this.changed);this.vfs.on("delete",this.changed)}vfs;workspaceRoot;moduleCache;options;nodeModulesRoot;builtRoot;reexportCounts=new Map;servedBarrels=new Map;stop(){this.vfs.off("change",this.changed);this.vfs.off("delete",this.changed);if(this.flushTimer!==void 0)clearTimeout(this.flushTimer);this.flushTimer=void 0;for(const items of this.queued.values())for(const item of items)item.reject(new Error("The module server stopped."));this.queued.clear()}imports(){const imports={};for(const name of this.installedPackageNames()){imports[name]=`${NPM_MODULE_PREFIX}${name}`;imports[`${name}/`]=`${NPM_MODULE_PREFIX}${name}/`}return imports}handles(pathname){return pathname.startsWith(NPM_MODULE_PREFIX)||pathname.startsWith(NPM_REQUIRE_PREFIX)}resolveStylesheet(specifier){if(!isPackageSpecifier(specifier))return void 0;const entry=this.resolveEntry(specifier);return entry&&/\.css$/u.test(entry)?entry:void 0}async serve(pathname,options={}){const requireEntry=pathname.startsWith(NPM_REQUIRE_PREFIX);const specifier=decodeURIComponent(pathname.slice((requireEntry?NPM_REQUIRE_PREFIX:NPM_MODULE_PREFIX).length));if(specifier.startsWith(CHUNK_ROUTE))return this.serveChunk(specifier.slice(CHUNK_ROUTE.length),options.whole===true);if(!isPackageSpecifier(specifier))return javascriptResponse(400,`Invalid npm module path: ${specifier}`);try{const built=`${this.builtRoot}/${requireEntry?"require":"npm"}/${encodeURIComponent(specifier)}.js`;let code3=this.vfs.existsSync(built)?this.vfs.readFileSync(built,"utf8"):void 0;if(code3!==void 0&&(readPackHeader(code3)?.chunks??[]).some(chunk=>!this.vfs.existsSync(`${this.builtRoot}/npm/${chunk}`))){this.vfs.unlinkSync(built);code3=void 0}const entry=this.resolveEntry(specifier,requireEntry);const imported=entry&&!options.whole&&this.isBarrel(specifier,entry)?this.importedNames(splitPackageSpecifier(specifier)[0],entry):void 0;const barrel=imported&&imported.size>0?imported:void 0;if(code3!==void 0&&(barrel?!barrelCovers(code3,barrel):hasBarrelMark(code3))){this.vfs.unlinkSync(built);code3=void 0}if(code3===void 0){const resolution=requireEntry?{skipped:"it is a require entry"}:!entry?{skipped:"its entry does not resolve"}:/\.css$/u.test(entry)?{skipped:"it is a stylesheet"}:this.packKey(specifier,barrel);const key="key"in resolution?resolution:void 0;let missed="skipped"in resolution?`there is no pack key: ${resolution.skipped}`:void 0;if(key){if(!await this.moduleCache?.link(key.key,built))missed=`neither this tab's store nor the image has a pack at ${key.key}`;else{const missingChunk=await this.linkChunks(key.prefix,built);if(missingChunk===void 0){try{code3=this.vfs.readFileSync(built,"utf8")}catch(cause){console.warn(`[modules] ${key.key} linked to ${built} but reading it failed (${cause instanceof Error?cause.message:String(cause)}): exists ${this.vfs.existsSync(built)}, its directory ${this.vfs.existsSync(built.slice(0,built.lastIndexOf("/")))}`);throw cause}}else missed=`the pack at ${key.key} linked but its chunk ${missingChunk} is in neither the store nor the image, so the pack was dropped`}}if(code3===void 0&&entry&&/\.css$/u.test(entry)){if(missed)console.log(`[modules] ${specifier}: ${missed}; serving it as a style module`);code3=this.styleModule(specifier,entry);this.keep(built,code3)}else if(code3===void 0){if(!entry){const[packageName]=splitPackageSpecifier(specifier);if(NODE_BUILTIN_NAMES.has(packageName))throw new Error(`'${specifier}' is a Node builtin; a browser module graph has no module for it, so the module that imported it belongs on the server.`);throw new Error(`The npm package '${specifier}' is not installed in ${this.workspaceRoot}.`)}if(!this.options.preparesImage){installTrap({door:"pack miss",subject:`${specifier}: ${missed??"no pack was linked"}`,detail:{specifier,root:this.workspaceRoot,...key?{key:key.key}:{},...requireEntry?{requireEntry:true}:{},...barrel?{names:[...barrel].join(",")}:{}}})}const started2=performance.now();code3=await this.bundle(specifier,barrel,requireEntry);console.log(`[modules] built ${specifier}${barrel?` to the ${barrel.size} names the project imports`:""} in ${((performance.now()-started2)/1e3).toFixed(1)} s, ${Math.round(code3.length/1024)} KiB`)}}if(barrel)this.servedBarrels.set(specifier,barrel);return javascriptResponse(200,options.whole?code3:absoluteChunkImports(code3))}catch(cause){const message=cause instanceof Error?cause.message:String(cause);return javascriptResponse(404,`throw new Error(${JSON.stringify(message)});`)}}bundle(specifier,barrel,requireEntry=false){const entry=this.resolveEntry(specifier,requireEntry);const[packageName,subpath]=splitPackageSpecifier(specifier);if(!entry&&NODE_BUILTIN_NAMES.has(packageName))throw new Error(`'${specifier}' is a Node builtin; a browser module graph has no module for it, so the module that imported it belongs on the server.`);if(!entry)throw new Error(`The npm package '${specifier}' is not installed in ${this.workspaceRoot}.`);let buildEntry=entry;if(barrel){buildEntry=`${this.builtRoot}/entries/${encodeURIComponent(specifier)}.js`;const entriesDirectory=buildEntry.slice(0,buildEntry.lastIndexOf("/"));const entryDirectory=entry.slice(0,entry.lastIndexOf("/"));const sources=barrelExportSources(this.vfs.readFileSync(entry,"utf8"));const lines=[];const fromBarrel=[];for(const name of[...barrel].sort()){const source=sources.get(name);const target=source?normalizePath2(`${entryDirectory}/${source.from}`):void 0;if(!source||!target){fromBarrel.push(name);continue}const from=relativePath2(entriesDirectory,target);lines.push(`export { ${source.imported===name?name:`${source.imported} as ${name}`} } from ${JSON.stringify(from)};`)}if(fromBarrel.length>0)lines.push(`export { ${fromBarrel.join(", ")} } from ${JSON.stringify(relativePath2(entriesDirectory,entry))};`);this.keep(buildEntry,`${lines.join("\n")}
|