@volter/browser-substrate 0.1.110 → 0.1.112

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 track=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;track(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-CTPA-1k9.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 owned=new Uint8Array(bytes2.byteLength);owned.set(bytes2);const retained=sent==null?void 0:sent.duplicate();if(retained)__adoptHandle(retained,null);this.pendingWriteBytes+=owned.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-=owned.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+owned.byteLength>this.limits.maxQueuedBytes)return;if(retained&&handle.peerQueuedHandles>=this.limits.maxQueuedHandles)return;try{finish(handle.writeBuffer(new WriteWrap,owned,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(parent,child){const inherited=normalizeProcessFilesystemPolicy(parent);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==="\\"&&quote2!=="'"){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 encoder7=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=encoder7.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 owned=new Uint8Array(next2.bytes.byteLength);owned.set(next2.bytes);this.pendingBytes+=owned.byteLength;try{this.channel.port.postMessage({operation:"stream-write",request:next2.request,id:next2.id,bytes:owned,...next2.handle===void 0?{}:{handle:next2.handle}},[owned.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 hash3=2166136261;for(let index2=0;index2<path3.length;index2+=1){hash3^=path3.charCodeAt(index2);hash3=Math.imul(hash3,16777619)}return hash3>>>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 parent of children.keys())if(!at3.has(parent)){at3.set(parent,paths.length);paths.push(parent)}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 MAX_WORKSPACE_BYTES=4*1024*1024*1024;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 maximumBytes=options.limits?.maxBytes??MAX_WORKSPACE_BYTES;const maximumEntries=options.limits?.maxEntries??MAX_ENTRIES;if(!Number.isSafeInteger(maximumBytes)||maximumBytes<1||maximumBytes>MAX_WORKSPACE_BYTES||!Number.isSafeInteger(maximumEntries)||maximumEntries<1||maximumEntries>MAX_ENTRIES){throw new Error("Invalid OPFS workspace limits.")}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 clockRetired=false;function publishLog(){if(!clockView||clockRetired)return;if(logBytes>2147483647){retireClock();return}Atomics.store(clockView,STORE_CLOCK_LOG,logBytes)}function retireClock(){if(!clockView||clockRetired)return;clockRetired=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&&!clockRetired)Atomics.add(clockView,STORE_CLOCK_EPOCH,1)}function endTransition(){transitions-=1;if(transitions>0||!clockView||clockRetired)return;publishLog();if(!clockRetired)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||clockRetired?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||clockRetired||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 parent=parentPath(path3);if(parent===path3)continue;let names2=derived.get(parent);if(!names2){names2=new Set;derived.set(parent,names2)}names2.add(path3.slice(parent.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;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&&notFound(cause))return false;throw cause}opening.signal.throwIfAborted();let state=readStorageState(await readJson2(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 readJson2(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(!notFound(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 readJson2(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 readJson2(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 readJson2(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 readJson2(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 readJson2(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._-]{0,62}[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(notFound(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(notFound(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=requiredPath(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,requiredPath(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 parent=parentPath(path3);if(parent===path3)return;children.mutable(parent).add(path3.slice(parent.length+1))}function detach(path3){const parent=parentPath(path3);if(children.get(parent)?.has(path3.slice(parent.length+1)))children.mutable(parent).delete(path3.slice(parent.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 assertBounds(path3,bytes2){const previous=entries.get(path3);const replaced=previous&&!previous.pack?previous.length:0;if(liveBytes-replaced+bytes2>maximumBytes){throw new Error(`OPFS workspace exceeds its byte limit: writing ${path3} (${bytes2} bytes) would take the project's own files past ${maximumBytes} 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);if(liveBytes>maximumBytes)throw new Error(`OPFS workspace exceeds its byte limit: the project's own files hold ${liveBytes} bytes, past ${maximumBytes}.`)}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 hash3=await crypto.subtle.digest("SHA-256",bytes2);return Array.from(new Uint8Array(hash3),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 parent=parentPath(path3);if(parent!==path3){let children2=names2.get(parent);if(!children2){children2=new Set;names2.set(parent,children2)}children2.add(path3.slice(parent.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 owned=new Uint8Array(bytes2.byteLength);owned.set(bytes2);const retained=sent==null?void 0:sent.duplicate();if(retained)__adoptHandle(retained,null);this.pendingWriteBytes+=owned.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-=owned.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+owned.byteLength>this.limits.maxQueuedBytes)return;if(retained&&handle.peerQueuedHandles>=this.limits.maxQueuedHandles)return;try{finish(handle.writeBuffer(new WriteWrap,owned,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(parent,child){const inherited=normalizeProcessFilesystemPolicy(parent);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==="\\"&&quote2!=="'"){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 encoder7=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=encoder7.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 owned=new Uint8Array(next2.bytes.byteLength);owned.set(next2.bytes);this.pendingBytes+=owned.byteLength;try{this.channel.port.postMessage({operation:"stream-write",request:next2.request,id:next2.id,bytes:owned,...next2.handle===void 0?{}:{handle:next2.handle}},[owned.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 hash3=2166136261;for(let index2=0;index2<path3.length;index2+=1){hash3^=path3.charCodeAt(index2);hash3=Math.imul(hash3,16777619)}return hash3>>>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 parent of children.keys())if(!at3.has(parent)){at3.set(parent,paths.length);paths.push(parent)}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 MAX_WORKSPACE_BYTES=10*1024*1024*1024;var MAX_SHARED_PACKAGES_BYTES=16*1024*1024*1024;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 maximumBytes=options.limits?.maxBytes??MAX_WORKSPACE_BYTES;const maximumEntries=options.limits?.maxEntries??MAX_ENTRIES;if(!Number.isSafeInteger(maximumBytes)||maximumBytes<1||maximumBytes>MAX_WORKSPACE_BYTES||!Number.isSafeInteger(maximumEntries)||maximumEntries<1||maximumEntries>MAX_ENTRIES){throw new Error("Invalid OPFS workspace limits.")}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 clockRetired=false;function publishLog(){if(!clockView||clockRetired)return;if(logBytes>2147483647){retireClock();return}Atomics.store(clockView,STORE_CLOCK_LOG,logBytes)}function retireClock(){if(!clockView||clockRetired)return;clockRetired=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&&!clockRetired)Atomics.add(clockView,STORE_CLOCK_EPOCH,1)}function endTransition(){transitions-=1;if(transitions>0||!clockView||clockRetired)return;publishLog();if(!clockRetired)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||clockRetired?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||clockRetired||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 parent=parentPath(path3);if(parent===path3)continue;let names2=derived.get(parent);if(!names2){names2=new Set;derived.set(parent,names2)}names2.add(path3.slice(parent.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;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&&notFound(cause))return false;throw cause}opening.signal.throwIfAborted();let state=readStorageState(await readJson2(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 readJson2(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(!notFound(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 readJson2(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 readJson2(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 readJson2(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 readJson2(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 readJson2(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._-]{0,62}[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(notFound(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(notFound(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=requiredPath(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,requiredPath(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 parent=parentPath(path3);if(parent===path3)return;children.mutable(parent).add(path3.slice(parent.length+1))}function detach(path3){const parent=parentPath(path3);if(children.get(parent)?.has(path3.slice(parent.length+1)))children.mutable(parent).delete(path3.slice(parent.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 assertBounds(path3,bytes2){const previous=entries.get(path3);const replaced=previous&&!previous.pack?previous.length:0;const limit=shared?MAX_SHARED_PACKAGES_BYTES: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 its byte limit: 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);if(liveBytes>maximumBytes)throw new Error(`OPFS workspace exceeds its byte limit: the project's own files hold ${liveBytes} bytes, past ${maximumBytes}.`)}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 hash3=await crypto.subtle.digest("SHA-256",bytes2);return Array.from(new Uint8Array(hash3),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 parent=parentPath(path3);if(parent!==path3){let children2=names2.get(parent);if(!children2){children2=new Set;names2.set(parent,children2)}children2.add(path3.slice(parent.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 readJson2(directory2,name){let handle;try{handle=await directory2.getFileHandle(name)}catch(cause){if(notFound(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(!notFound(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.")}requiredPath(candidate.path);if(candidate.operation==="rename")requiredPath(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.");requiredPath(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 its byte limit.")}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=requiredPath(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([requiredPath(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 requiredPath(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 relative3=path3===root2?"":path3.slice(root2.length+1);segmentsOf(relative3);return relative3}function segmentsOf(relative3){const segments=relative3===""?[]:relative3.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 parent=path3.slice(0,path3.lastIndexOf("/"));return parent===""||rootOf(parent)===void 0?rootOf(path3)??path3:parent}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 notFound(cause){return cause instanceof DOMException&&cause.name==="NotFoundError"}function fingerprint2(value){let hash3=2166136261;for(let index2=0;index2<value.byteLength;index2+=1){hash3^=value[index2];hash3=Math.imul(hash3,16777619)}return hash3>>>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){requiredPath(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=requiredPath(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&&!clockRetired&&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&&current3&&current3.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 parent=this.store.entries.get(parentOf2(normalized));if(!parent||parent.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 parent=parentOf2(normalized);const above=this.store.entries.get(parent);if(!above&&this.packedInside(parent))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 relative3=path3===watched?path3.slice(path3.lastIndexOf("/")+1):path3.slice(watched==="/"?1:watched.length+1);for(const entry of set){if(path3!==watched&&!entry.recursive&&relative3.includes("/"))continue;entry.listener(event,relative3)}}}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 errno={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:errno[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 encoder7=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 parent="";for(const part of file2.path.slice(1).split("/").slice(0,-1)){parent+=`/${part}`;if(paths.get(parent)==="file")throw new Error("Node prepared file conflicts with a directory.");if(!paths.has(parent)){paths.set(parent,"directory");bytes2+=encoder7.encode(parent).byteLength}}paths.set(file2.path,"file");bytes2+=encoder7.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 encoder7=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+=encoder7.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 relative3=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||!relative3.includes("/"))){watcher.listener?.(event,inside?relative3:path3.split("/").pop())}}}}}var TAILWIND_RUNTIME_DIRECTORY="/tmp/browser-runtime-tailwind";var TAILWIND_VITE_PATH=`${TAILWIND_RUNTIME_DIRECTORY}/vite.cjs`;var STAND_IN_PATHS={"@tailwindcss/vite":TAILWIND_VITE_PATH};function ensureTailwindStandIn(filesystem){if(filesystem.existsSync(TAILWIND_VITE_PATH))return;filesystem.mkdirSync(TAILWIND_RUNTIME_DIRECTORY,{recursive:true});filesystem.writeFileSync(TAILWIND_VITE_PATH,TAILWIND_VITE_SOURCE)}var TAILWIND_VITE_SOURCE=String.raw`"use strict";
5894
5894
  const fs = require("fs");
5895
5895
  const path = require("path");