@volter/browser-substrate 0.1.101 → 0.1.103
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/program-images.js +2 -2
- package/dist/program-images.js.map +1 -1
- package/dist/shell/assets/browser-sandbox-bridge-BJbQoc4f.js +237 -0
- package/dist/shell/assets/{filesystem-host-BT4CmP6I.js → filesystem-host-DJbFuokb.js} +1 -1
- package/dist/shell/assets/{filesystem-host-BBYqSE7n.js → filesystem-host-yMcJuvmT.js} +2 -2
- package/dist/shell/assets/{filesystem-worker-D88RPdU7.js → filesystem-worker-BbsBhZ9p.js} +3 -3
- package/dist/shell/assets/{fork-worker-CEQ37gcQ.js → fork-worker-BXY2kfdX.js} +1 -1
- package/dist/shell/assets/{node-execution-worker-7a2fc3cf9f082cbe.js → node-execution-worker-7e8e0c5321ca0d10.js} +1 -1
- package/dist/shell/assets/{sandbox-CLAYkibu.js → sandbox-bMeKqKBn.js} +1 -1
- package/dist/shell/assets/{shell-CzbWwVZ3.js → shell-DLIQ6jHu.js} +5 -5
- package/dist/shell/assets/{worker-CQmX_ncR.js → worker-Ce8bBwSJ.js} +16 -16
- package/dist/shell/assets/{worker-program-worker-CLXTQPjT.js → worker-program-worker-B4OcKVtV.js} +2 -2
- package/dist/shell/bundler-worker.js +1 -1
- package/dist/shell/index.html +2 -2
- package/dist/shell/node-execution-worker.js +1 -1
- package/dist/shell/python-execution-worker.js +4 -4
- package/dist/shell/python-runtime-snapshot.bin +0 -0
- package/dist/shell/python-runtime-snapshot.json +1 -1
- package/dist/shell/sandbox.html +2 -2
- package/package.json +1 -1
- package/dist/shell/assets/browser-sandbox-bridge-BRDWHeqY.js +0 -237
|
@@ -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="",file="",lineNo=0,colNo=0;const safariMatch=line.match(/^(.*)@(.*?):(\d+):(\d+)$/);if(safariMatch){fn2=safariMatch[1]||"";file=safariMatch[2];lineNo=parseInt(safariMatch[3],10);colNo=parseInt(safariMatch[4],10);frames.push({fn:fn2,file,line:lineNo,col:colNo});continue}const chromeMatch=line.match(/^at\s+(?:(.+?)\s+\()?(.*?):(\d+):(\d+)\)?$/);if(chromeMatch){fn2=chromeMatch[1]||"";file=chromeMatch[2];lineNo=parseInt(chromeMatch[3],10);colNo=parseInt(chromeMatch[4],10);frames.push({fn:fn2,file,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-CFd3N-Xm.js",{type:"module"});this.workerApi=wrap(this.worker);this.initialized=this.initWorker();this.setupVFSListeners()}async initWorker(){const snapshot=this.vfs.toSnapshot();const workerOptions={cwd:this.options.cwd,env:this.options.env};await this.workerApi.init(snapshot,workerOptions);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 installed2=new WeakMap;const live=new Set;const collected=new FinalizationRegistry(ref2=>live.delete(ref2));const install2=(Agent,protocol,require2)=>{const prototype=Agent.prototype;if(installed2.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;installed2.set(prototype,{original,connect:connect2});const ref2=new WeakRef(prototype);live.add(ref2);collected.register(prototype,ref2,ref2)};install2(httpModule.Agent,"http:");install2(httpsModule.Agent,"https:");const unsubscribe=onNodeLibLoaded((name,value,require2)=>{if(name==="_http_agent")install2(value.Agent,"http:",require2);if(name==="https")install2(value.Agent,"https:",require2)});return()=>{unsubscribe();for(const ref2 of live){const prototype=ref2.deref();const held=prototype&&installed2.get(prototype);if(prototype&&held&&prototype.createConnection===held.connect)prototype.createConnection=held.original;collected.unregister(ref2)}live.clear()}}function connection(origin,exchange,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 fail=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",fail);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 exchange({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(fail)});for(const name of["connect","upgrade","checkContinue","checkExpectation"])server.on(name,()=>fail(unsupported(name)));server.on("clientError",fail);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 scope2=packageName.startsWith("@")&&packageName.includes("/")?packageName.slice(0,packageName.indexOf("/")):packageName;const url2=scopes2[scope2]??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 decompress(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=decompress(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 stat=vfs2.statSync(fullPath);if(stat.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 packages={};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"));packages[`${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"));packages[entry]=pkgJson.version}}}return packages}};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(port){return listenerOnPort(port)!==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(port){return{statusCode:503,statusMessage:"Service Unavailable",headers:{"Content-Type":"text/plain"},body:ownedConcat([Buffer$9.from(`No server listening on port ${port}`)])}}function __requestOverLoopback(port,method,url2,headers,body){if(!__listening(port))return Promise.resolve(serviceUnavailable(port));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,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(port))});socket.write(requestHead(method,url2,headers,body));if(body&&body.length>0)socket.write(body)})}function __streamOverLoopback(port,method,url2,headers,body,onStart,onChunk,onEnd,flow){if(!__listening(port)){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 ended=false;const finish=()=>{if(ended)return;ended=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,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(ended)return;const read=parser.execute(chunk);if(read instanceof Error){socket.destroy();finish()}else if(collected.complete){socket.destroy();finish()}});socket.on("end",()=>{if(!ended){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(port,method,url2,headers){if(!__listening(port)){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,host:"127.0.0.1"});const fail=()=>{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();fail();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();fail()}});socket.on("error",fail);socket.on("close",fail);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(port,address){const hostname2=address;return{listening:true,address:()=>({port,address:hostname2,family:hostname2.includes(":")?"IPv6":"IPv4"}),handleRequest:(method,url2,headers,body)=>__requestOverLoopback(port,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 receive=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)receive(__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);receive(__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);receive(__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 port=Number(url2.port);if(!__listening(port))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(port,"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((port,address)=>{if(this.servers.has(port))return;const hostname2=address||"0.0.0.0";const server=guestListeningServer(port,hostname2);this.guestServers.add(server);this.registerServer(server,port,hostname2)},port=>{const entry=this.servers.get(port);if(entry&&(entry.server===null||this.guestServers.has(entry.server))){if(entry.server)entry.server.listening=false;this.unregisterServer(port)}})}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(port,method,url2,headers,body){return __requestOverLoopback(port,method,url2,headers,body)}streamGuest(port,method,url2,headers,body,onStart,onChunk,onEnd,flow){return __streamOverLoopback(port,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 ended=false;let unsubscribe=()=>{};const finish=(status,failure)=>{if(ended)return;ended=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(ended)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(scope2=>scope2.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:port=>{var _a22;const listener=listenerOnPort(port);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:(port,onConnection)=>{const server=new Server(onConnection);server.listen(port);__adoptHandle(server._handle,null);return()=>{server.close()}},createREPL:()=>runtime.createREPL(),on:(event,listener)=>{serverBridge.on(event,listener)}}}function flattenSpecifier(specifier){const flat=specifier.replace(/[/:]/gu,"_").replace(/\./gu,"__").replace(/(\s*>\s*)/gu,"___").replace(/#/gu,"____");return flat.length>170?`${flat.slice(0,160)}_${shortHash(flat)}`:flat}function packFileName(specifier){return`pack_${flattenSpecifier(specifier)}.js`}function packageNameOf2(specifier){const parts=specifier.split("/");return specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0]}function shortHash(text){let hash2=0;for(let index2=0;index2<text.length;index2+=1)hash2=hash2*31+text.charCodeAt(index2)|0;return(hash2>>>0).toString(36)}var STAT_FIELDS=["mode","mtimeMs","atimeMs","ctimeMs","birthtimeMs","nlink","uid","gid","dev","ino","rdev","blksize","blocks"];var STATE=0;var OPERATION=1;var STATUS=2;var INPUT_LENGTH=3;var OUTPUT_LENGTH=4;var TOTAL_LENGTH=5;var DEFAULT_PAYLOAD_BYTES=4*1024*1024;var REQUEST_TIMEOUT_MS=3e4;var encoder2=new TextEncoder;var decoder2=new TextDecoder;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(decoder2.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 stat=JSON.parse(decoder2.decode(bytes2));if(stat===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=>stat[key]!==void 0).map(key=>[key,stat[key]])),isFile:()=>stat.file,isDirectory:()=>stat.directory,isSymbolicLink:()=>stat.symlink===true,size:stat.size,mode:stat.mode,mtimeMs:stat.mtimeMs,mtime:new Date(stat.mtimeMs)}}readlinkSync(path3){return JSON.parse(decoder2.decode(this.call(14,{path:path3}).output))}symlinkSync(target,path3){this.call(15,{path:path3,target})}readdirSync(path3){return JSON.parse(decoder2.decode(this.call(4,{path:path3}).output))}realpathSync(path3){return JSON.parse(decoder2.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:atime instanceof Date?atime.getTime():atime,mtime:mtime instanceof Date?mtime.getTime():mtime,atimeDate:atime instanceof Date,mtimeDate:mtime instanceof Date})}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?decoder2.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,STATE)!==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,STATE,requestId2);this.channel.port.postMessage(requestId2);const deadline=Date.now()+REQUEST_TIMEOUT_MS;for(;;){const state=Atomics.load(this.control,STATE);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,STATE,requestId2,0)===requestId2){throw new Error(`The filesystem holder did not answer within ${REQUEST_TIMEOUT_MS} ms.`)}Atomics.wait(this.control,STATE,state,state===-requestId2?void 0:remaining)}const status=Atomics.load(this.control,STATUS);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,STATE,0);if(status===2){const error=JSON.parse(decoder2.decode(output));throw Object.assign(new Error(error.message),error)}if(status!==0)throw new Error(decoder2.decode(output));return{output,total}}};var scope=self;function packNeighborsPlugin(neighbors,seen){const names2=new Set(neighbors.names);const self2=new Set(neighbors.self??[]);return{name:"pack-neighbors",setup(build2){build2.onResolve({filter:/^[^./]/u},args=>{if(args.namespace==="pack-neighbor"||args.path.startsWith("node:")||args.path.includes(":"))return void 0;const name=packageNameOf2(args.path);if(!names2.has(name)||self2.has(args.path))return void 0;seen.add(args.path);if(args.kind==="require-call")return{path:args.path,namespace:"pack-neighbor"};return{path:`./${packFileName(args.path)}`,external:true}});build2.onResolve({filter:/^\.\/pack_.*\.js$/u},args=>({path:args.path,external:true}));build2.onLoad({filter:/.*/u,namespace:"pack-neighbor"},args=>({loader:"js",contents:`import * as neighbor from ${JSON.stringify(`./${packFileName(args.path)}`)};
|
|
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 packages={};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"));packages[`${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"));packages[entry]=pkgJson.version}}}return packages}};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(port){return listenerOnPort(port)!==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(port){return{statusCode:503,statusMessage:"Service Unavailable",headers:{"Content-Type":"text/plain"},body:ownedConcat([Buffer$9.from(`No server listening on port ${port}`)])}}function __requestOverLoopback(port,method,url2,headers,body){if(!__listening(port))return Promise.resolve(serviceUnavailable(port));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,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(port))});socket.write(requestHead(method,url2,headers,body));if(body&&body.length>0)socket.write(body)})}function __streamOverLoopback(port,method,url2,headers,body,onStart,onChunk,onEnd,flow){if(!__listening(port)){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 ended=false;const finish=()=>{if(ended)return;ended=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,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(ended)return;const read=parser.execute(chunk);if(read instanceof Error){socket.destroy();finish()}else if(collected.complete){socket.destroy();finish()}});socket.on("end",()=>{if(!ended){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(port,method,url2,headers){if(!__listening(port)){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,host:"127.0.0.1"});const fail=()=>{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();fail();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();fail()}});socket.on("error",fail);socket.on("close",fail);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(port,address){const hostname2=address;return{listening:true,address:()=>({port,address:hostname2,family:hostname2.includes(":")?"IPv6":"IPv4"}),handleRequest:(method,url2,headers,body)=>__requestOverLoopback(port,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 receive=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)receive(__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);receive(__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);receive(__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 port=Number(url2.port);if(!__listening(port))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(port,"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((port,address)=>{if(this.servers.has(port))return;const hostname2=address||"0.0.0.0";const server=guestListeningServer(port,hostname2);this.guestServers.add(server);this.registerServer(server,port,hostname2)},port=>{const entry=this.servers.get(port);if(entry&&(entry.server===null||this.guestServers.has(entry.server))){if(entry.server)entry.server.listening=false;this.unregisterServer(port)}})}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(port,method,url2,headers,body){return __requestOverLoopback(port,method,url2,headers,body)}streamGuest(port,method,url2,headers,body,onStart,onChunk,onEnd,flow){return __streamOverLoopback(port,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 ended=false;let unsubscribe=()=>{};const finish=(status,failure)=>{if(ended)return;ended=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(ended)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(scope2=>scope2.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:port=>{var _a22;const listener=listenerOnPort(port);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:(port,onConnection)=>{const server=new Server(onConnection);server.listen(port);__adoptHandle(server._handle,null);return()=>{server.close()}},createREPL:()=>runtime.createREPL(),on:(event,listener)=>{serverBridge.on(event,listener)}}}function flattenSpecifier(specifier){const flat=specifier.replace(/[/:]/gu,"_").replace(/\./gu,"__").replace(/(\s*>\s*)/gu,"___").replace(/#/gu,"____");return flat.length>170?`${flat.slice(0,160)}_${shortHash(flat)}`:flat}function packFileName(specifier){return`pack_${flattenSpecifier(specifier)}.js`}function packageNameOf2(specifier){const parts=specifier.split("/");return specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0]}function shortHash(text){let hash2=0;for(let index2=0;index2<text.length;index2+=1)hash2=hash2*31+text.charCodeAt(index2)|0;return(hash2>>>0).toString(36)}var STAT_FIELDS=["mode","mtimeMs","atimeMs","ctimeMs","birthtimeMs","nlink","uid","gid","dev","ino","rdev","blksize","blocks"];var STATE=0;var OPERATION=1;var STATUS=2;var INPUT_LENGTH=3;var OUTPUT_LENGTH=4;var TOTAL_LENGTH=5;var DEFAULT_PAYLOAD_BYTES=4*1024*1024;var REQUEST_TIMEOUT_MS=3e4;var encoder2=new TextEncoder;var decoder2=new TextDecoder;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(decoder2.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 stat=JSON.parse(decoder2.decode(bytes2));if(stat===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=>stat[key]!==void 0).map(key=>[key,stat[key]])),isFile:()=>stat.file,isDirectory:()=>stat.directory,isSymbolicLink:()=>stat.symlink===true,size:stat.size,mode:stat.mode,mtimeMs:stat.mtimeMs,mtime:new Date(stat.mtimeMs)}}readlinkSync(path3){return JSON.parse(decoder2.decode(this.call(14,{path:path3}).output))}symlinkSync(target,path3){this.call(15,{path:path3,target})}readdirSync(path3){return JSON.parse(decoder2.decode(this.call(4,{path:path3}).output))}realpathSync(path3){return JSON.parse(decoder2.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?decoder2.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,STATE)!==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,STATE,requestId2);this.channel.port.postMessage(requestId2);const deadline=Date.now()+REQUEST_TIMEOUT_MS;for(;;){const state=Atomics.load(this.control,STATE);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,STATE,requestId2,0)===requestId2){throw new Error(`The filesystem holder did not answer within ${REQUEST_TIMEOUT_MS} ms.`)}Atomics.wait(this.control,STATE,state,state===-requestId2?void 0:remaining)}const status=Atomics.load(this.control,STATUS);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,STATE,0);if(status===2){const error=JSON.parse(decoder2.decode(output));throw Object.assign(new Error(error.message),error)}if(status!==0)throw new Error(decoder2.decode(output));return{output,total}}};var scope=self;function packNeighborsPlugin(neighbors,seen){const names2=new Set(neighbors.names);const self2=new Set(neighbors.self??[]);return{name:"pack-neighbors",setup(build2){build2.onResolve({filter:/^[^./]/u},args=>{if(args.namespace==="pack-neighbor"||args.path.startsWith("node:")||args.path.includes(":"))return void 0;const name=packageNameOf2(args.path);if(!names2.has(name)||self2.has(args.path))return void 0;seen.add(args.path);if(args.kind==="require-call")return{path:args.path,namespace:"pack-neighbor"};return{path:`./${packFileName(args.path)}`,external:true}});build2.onResolve({filter:/^\.\/pack_.*\.js$/u},args=>({path:args.path,external:true}));build2.onLoad({filter:/.*/u,namespace:"pack-neighbor"},args=>({loader:"js",contents:`import * as neighbor from ${JSON.stringify(`./${packFileName(args.path)}`)};
|
|
5893
5893
|
module.exports = neighbor.__browser_commonjs ?? neighbor;
|
|
5894
5894
|
`}))}}}var shim=esbuildShim;var send=message=>scope.postMessage(message);scope.onmessage=async event=>{const message=event.data;if(message.type==="attach"){shim.setModuleURL(message.esbuildModuleUrl);shim.setWasmURL(message.esbuildWasmUrl);shim.setVFS(new BrowserFilesystemChannelClient(message.channel));return}try{if(message.type==="build"){const{neighbors,...options}=message.options;const seen=new Set;if(neighbors)options.plugins=[packNeighborsPlugin(neighbors,seen),...options.plugins??[]];const result=await shim.build(options);send({type:"result",id:message.id,result:{outputFiles:(result.outputFiles??[]).map(file=>({path:file.path,text:file.text})),...neighbors?{neighbors:[...seen].sort()}:{},warnings:result.warnings??[],errors:result.errors??[],...result.metafile!==void 0?{metafile:result.metafile}:{}}})}else if(message.type==="transform"){const result=await shim.transform(message.code,message.options);send({type:"result",id:message.id,result:{code:result.code,map:result.map,warnings:result.warnings??[]}})}}catch(cause){send({type:"error",id:message.id,message:cause instanceof Error?cause.message:String(cause)})}};
|
|
5895
5895
|
/*! Bundled license information:
|
package/dist/shell/index.html
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
<link rel="icon" type="image/svg+xml" href="https://brand.volter.ai/logo/browser-substrate/svg?size=64" />
|
|
9
9
|
<!-- Black glass from the first byte, before any script: the boot screen (boot-screen.js) comes on from here. Ready or failed, the page's own paper returns. -->
|
|
10
10
|
<style>html:not([data-ready]):not([data-error]), html:not([data-ready]):not([data-error]) body { background: #0b0b0c; color-scheme: dark; }</style>
|
|
11
|
-
<script type="module" crossorigin src="/assets/shell-
|
|
11
|
+
<script type="module" crossorigin src="/assets/shell-DLIQ6jHu.js"></script>
|
|
12
12
|
<link rel="modulepreload" crossorigin href="/assets/page-workers-BUcWBF51.js">
|
|
13
|
-
<link rel="modulepreload" crossorigin href="/assets/browser-sandbox-bridge-
|
|
13
|
+
<link rel="modulepreload" crossorigin href="/assets/browser-sandbox-bridge-BJbQoc4f.js">
|
|
14
14
|
<link rel="modulepreload" crossorigin href="/assets/cross-origin-container-protocol-hIp9vH-t.js">
|
|
15
15
|
<link rel="stylesheet" crossorigin href="/assets/shell-BEKXfRsE.css">
|
|
16
16
|
</head>
|
|
@@ -4319,4 +4319,4 @@ function serveStore(scope3, port, loadEngine) {
|
|
|
4319
4319
|
}
|
|
4320
4320
|
|
|
4321
4321
|
// <stdin>
|
|
4322
|
-
startExecutionFront(self, () => import("/assets/node-execution-worker-
|
|
4322
|
+
startExecutionFront(self, () => import("/assets/node-execution-worker-7e8e0c5321ca0d10.js"));
|
|
@@ -3181,7 +3181,7 @@ function applyPythonProcessPatch(fs, patch, base) {
|
|
|
3181
3181
|
applyProcessFilesystemPatch(pythonProcessFileSystem(fs), patch, base);
|
|
3182
3182
|
}
|
|
3183
3183
|
function msOf(time) {
|
|
3184
|
-
return time
|
|
3184
|
+
return typeof time === "number" ? time : Number(time);
|
|
3185
3185
|
}
|
|
3186
3186
|
function restorePythonSnapshot(fs, value) {
|
|
3187
3187
|
clearTree(fs, PYTHON_WORKSPACE);
|
|
@@ -3277,7 +3277,7 @@ function depth2(path) {
|
|
|
3277
3277
|
return segments;
|
|
3278
3278
|
}
|
|
3279
3279
|
function pythonMetadata(stat) {
|
|
3280
|
-
const mtimeMs = stat.mtime
|
|
3280
|
+
const mtimeMs = typeof stat.mtime === "number" ? stat.mtime : Number(stat.mtime);
|
|
3281
3281
|
return {
|
|
3282
3282
|
mode: stat.mode & 4095,
|
|
3283
3283
|
...typeof mtimeMs === "number" && Number.isFinite(mtimeMs) ? { mtimeMs } : {}
|
|
@@ -3497,7 +3497,7 @@ function snapshotPackWorkspace(filesystem, changes, original) {
|
|
|
3497
3497
|
const files = original.files.filter((entry) => entry.path !== PYTHON_WORKSPACE && !entry.path.startsWith(`${PYTHON_WORKSPACE}/`));
|
|
3498
3498
|
const walk2 = (path) => {
|
|
3499
3499
|
const stat = filesystem.stat(path);
|
|
3500
|
-
const mtimeMs = stat.mtime
|
|
3500
|
+
const mtimeMs = typeof stat.mtime === "number" ? stat.mtime : Number(stat.mtime);
|
|
3501
3501
|
const metadata2 = { mode: stat.mode & 4095, ...typeof mtimeMs === "number" && Number.isFinite(mtimeMs) ? { mtimeMs } : {} };
|
|
3502
3502
|
if ((stat.mode & 61440) === S_IFDIR2) {
|
|
3503
3503
|
files.push({ path, type: "directory", ...metadata2 });
|
|
@@ -5288,7 +5288,7 @@ var PythonSqliteCoherence = class {
|
|
|
5288
5288
|
const stat = this.filesystem.stat(path);
|
|
5289
5289
|
if ((stat.mode & 61440) === 16384)
|
|
5290
5290
|
return;
|
|
5291
|
-
const mtimeMs = stat.mtime
|
|
5291
|
+
const mtimeMs = typeof stat.mtime === "number" ? stat.mtime : Number(stat.mtime);
|
|
5292
5292
|
return {
|
|
5293
5293
|
bytes: this.filesystem.readFile(path),
|
|
5294
5294
|
mode: stat.mode & 4095,
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"format":1,"pyodide":"314.0.6","engine":"sha256-OgoA3+qjSKwg+e8JkEIz0y0z9kQzlmLUrzaPiiAQ83o=","preparation":"77987879a2949714bdec4de6bae2d0431adbc3549686414e4e13e051cf23bfae","integrity":"sha256-
|
|
1
|
+
{"format":1,"pyodide":"314.0.6","engine":"sha256-OgoA3+qjSKwg+e8JkEIz0y0z9kQzlmLUrzaPiiAQ83o=","preparation":"77987879a2949714bdec4de6bae2d0431adbc3549686414e4e13e051cf23bfae","integrity":"sha256-mvUmkLruetmW5mfg/qgs2grUYwbB86vpGJKPSIuYdtA=","bytes":6220153}
|
package/dist/shell/sandbox.html
CHANGED
|
@@ -7,9 +7,9 @@
|
|
|
7
7
|
<meta name="referrer" content="no-referrer" />
|
|
8
8
|
<title>Generated application sandbox</title>
|
|
9
9
|
<style>html,body,#generated-preview{border:0;height:100%;margin:0;padding:0;width:100%}body{overflow:hidden}</style>
|
|
10
|
-
<script type="module" crossorigin src="/assets/sandbox-
|
|
10
|
+
<script type="module" crossorigin src="/assets/sandbox-bMeKqKBn.js"></script>
|
|
11
11
|
<link rel="modulepreload" crossorigin href="/assets/page-workers-BUcWBF51.js">
|
|
12
|
-
<link rel="modulepreload" crossorigin href="/assets/browser-sandbox-bridge-
|
|
12
|
+
<link rel="modulepreload" crossorigin href="/assets/browser-sandbox-bridge-BJbQoc4f.js">
|
|
13
13
|
</head>
|
|
14
14
|
<body>
|
|
15
15
|
<!-- The containing page is already a dedicated, credential-free origin.
|