pi-namespace-patch 1.0.2-namespace.2 → 1.0.3-namespace.1
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/CHANGELOG.md +27 -0
- package/README.md +8 -8
- package/dist/bundle/chunks/{anthropic-messages-MVG2FL56.js → anthropic-messages-Y22YDKSW.js} +1 -1
- package/dist/bundle/chunks/azure-openai-responses-YJDJIIDQ.js +2 -0
- package/dist/bundle/chunks/chunk-22CYIUS4.js +2 -0
- package/dist/bundle/chunks/{chunk-SYF2TF6W.js → chunk-2VBQLN7Y.js} +3 -3
- package/dist/bundle/chunks/{chunk-ZSI3BL5Q.js → chunk-6DBOMCBS.js} +1 -1
- package/dist/bundle/chunks/{chunk-2KAZSACP.js → chunk-7TP2J6F2.js} +1 -1
- package/dist/bundle/chunks/{chunk-6FX7UEPL.js → chunk-AXOERKKW.js} +3 -3
- package/dist/bundle/chunks/{chunk-OSKPX3Z5.js → chunk-C47CLQZK.js} +1 -1
- package/dist/bundle/chunks/{chunk-DN3QEIXS.js → chunk-DEVCTHZR.js} +1 -1
- package/dist/bundle/chunks/{chunk-IKZJX7ZT.js → chunk-HQHD6PZI.js} +1 -1
- package/dist/bundle/chunks/{chunk-OLBCNJCL.js → chunk-ITAWMMSC.js} +30 -30
- package/dist/bundle/chunks/chunk-KJUDFE6Y.js +11 -0
- package/dist/bundle/chunks/{chunk-WCQZGZ6I.js → chunk-PSQJVYXD.js} +1 -1
- package/dist/bundle/chunks/{chunk-G7EDXK4D.js → chunk-TAOL3JFA.js} +1 -1
- package/dist/bundle/chunks/chunk-UBHCV62G.js +20 -0
- package/dist/bundle/chunks/{chunk-BYB6ZAAQ.js → chunk-WE4MXUQS.js} +1 -1
- package/dist/bundle/chunks/chunk-ZBURYEWF.js +2 -0
- package/dist/bundle/chunks/chunk-ZSQEXT6X.js +15 -0
- package/dist/bundle/chunks/{cli-KILDDGW3.js → cli-HTJP6F6Z.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-X5PVWWYJ.js → cloudflare-workers-ai-system-one-NM3JRRWQ.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +0 -1
- package/dist/bundle/chunks/{easter-egg-3d-T5FFWIBR.js → easter-egg-3d-6YCNESG3.js} +1 -1
- package/dist/bundle/chunks/{execute-RYVK27GT.js → execute-JRUOLYDA.js} +4 -4
- package/dist/bundle/chunks/{google-generative-ai-ZOK6CV7D.js → google-generative-ai-XMFHGQC5.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-VKWZQ3AY.js → google-vertex-4XRRNP74.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-7DAUEE4N.js → mistral-conversations-Q22M3IBG.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-TC3OK7B4.js → openai-codex-responses-4MYQSO5E.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-GWHGMQ3T.js → openai-completions-OSRCWAAA.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-EZ7FJ2KL.js → openai-responses-UHF3DHNG.js} +1 -1
- package/dist/bundle/chunks/{runtime-D5I2NTIF.js → runtime-NW7GPWKS.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-A4CZTQWZ.js → typesafe-system-one-PRR5K6CI.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-U4SEX4TD.js +2 -0
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/config.d.ts +18 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +44 -6
- package/dist/config.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +2 -7
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/keybindings.d.ts +4 -4
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +4 -10
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +49 -8
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/tool.js +1 -1
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +4 -9
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +7 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +42 -6
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/output-files.d.ts +15 -0
- package/dist/utils/output-files.d.ts.map +1 -0
- package/dist/utils/output-files.js +30 -0
- package/dist/utils/output-files.js.map +1 -0
- package/docs/codemode.md +3 -3
- package/docs/keybindings.md +4 -4
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +10 -10
- package/dist/bundle/chunks/azure-openai-responses-7AMFUIWJ.js +0 -2
- package/dist/bundle/chunks/chunk-7JGR3GZN.js +0 -11
- package/dist/bundle/chunks/chunk-OYBSLV7Y.js +0 -16
- package/dist/bundle/chunks/chunk-PDFMCAOZ.js +0 -19
- package/dist/bundle/chunks/chunk-VIV3CWXG.js +0 -2
- package/dist/bundle/chunks/virtual-modules-J2M3WAR2.js +0 -2
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{VisualLinePreview,formatSize,formatToolCallWithArgs,getShellConfig,getTextOutput,replaceTabs,truncateMiddle,writeOutputFile}from"./chunk-UBHCV62G.js";import{Container,Spacer,Text,getAgentDir,getFileRevision,keyHint,normalizePath,require_cross_spawn,stripBom}from"./chunk-AXOERKKW.js";import{__commonJS,__require,__toESM}from"./chunk-4L3WN2XY.js";var require_polyfills=__commonJS({"node_modules/graceful-fs/polyfills.js"(exports,module){var constants=__require("constants"),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return cwd||(cwd=origCwd.call(process)),cwd};try{process.cwd()}catch{}typeof process.chdir=="function"&&(chdir=process.chdir,process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,chdir));var chdir;module.exports=patch;function patch(fs){constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&patchLchmod(fs),fs.lutimes||patchLutimes(fs),fs.chown=chownFix(fs.chown),fs.fchown=chownFix(fs.fchown),fs.lchown=chownFix(fs.lchown),fs.chmod=chmodFix(fs.chmod),fs.fchmod=chmodFix(fs.fchmod),fs.lchmod=chmodFix(fs.lchmod),fs.chownSync=chownFixSync(fs.chownSync),fs.fchownSync=chownFixSync(fs.fchownSync),fs.lchownSync=chownFixSync(fs.lchownSync),fs.chmodSync=chmodFixSync(fs.chmodSync),fs.fchmodSync=chmodFixSync(fs.fchmodSync),fs.lchmodSync=chmodFixSync(fs.lchmodSync),fs.stat=statFix(fs.stat),fs.fstat=statFix(fs.fstat),fs.lstat=statFix(fs.lstat),fs.statSync=statFixSync(fs.statSync),fs.fstatSync=statFixSync(fs.fstatSync),fs.lstatSync=statFixSync(fs.lstatSync),fs.chmod&&!fs.lchmod&&(fs.lchmod=function(path,mode,cb){cb&&process.nextTick(cb)},fs.lchmodSync=function(){}),fs.chown&&!fs.lchown&&(fs.lchown=function(path,uid,gid,cb){cb&&process.nextTick(cb)},fs.lchownSync=function(){}),platform==="win32"&&(fs.rename=typeof fs.rename!="function"?fs.rename:(function(fs$rename){function rename(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&(er.code==="EACCES"||er.code==="EPERM"||er.code==="EBUSY")&&Date.now()-start<6e4){setTimeout(function(){fs.stat(to,function(stater,st){stater&&stater.code==="ENOENT"?fs$rename(from,to,CB):cb(er)})},backoff),backoff<100&&(backoff+=10);return}cb&&cb(er)})}return Object.setPrototypeOf&&Object.setPrototypeOf(rename,fs$rename),rename})(fs.rename)),fs.read=typeof fs.read!="function"?fs.read:(function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&typeof callback_=="function"){var eagCounter=0;callback=function(er,_,__){if(er&&er.code==="EAGAIN"&&eagCounter<10)return eagCounter++,fs$read.call(fs,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs,fd,buffer,offset,length,position,callback)}return Object.setPrototypeOf&&Object.setPrototypeOf(read,fs$read),read})(fs.read),fs.readSync=typeof fs.readSync!="function"?fs.readSync:(function(fs$readSync){return function(fd,buffer,offset,length,position){for(var eagCounter=0;;)try{return fs$readSync.call(fs,fd,buffer,offset,length,position)}catch(er){if(er.code==="EAGAIN"&&eagCounter<10){eagCounter++;continue}throw er}}})(fs.readSync);function patchLchmod(fs2){fs2.lchmod=function(path,mode,callback){fs2.open(path,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){if(err){callback&&callback(err);return}fs2.fchmod(fd,mode,function(err2){fs2.close(fd,function(err22){callback&&callback(err2||err22)})})})},fs2.lchmodSync=function(path,mode){var fd=fs2.openSync(path,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0,ret;try{ret=fs2.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs2.closeSync(fd)}catch{}else fs2.closeSync(fd)}return ret}}function patchLutimes(fs2){constants.hasOwnProperty("O_SYMLINK")&&fs2.futimes?(fs2.lutimes=function(path,at,mt,cb){fs2.open(path,constants.O_SYMLINK,function(er,fd){if(er){cb&&cb(er);return}fs2.futimes(fd,at,mt,function(er2){fs2.close(fd,function(er22){cb&&cb(er2||er22)})})})},fs2.lutimesSync=function(path,at,mt){var fd=fs2.openSync(path,constants.O_SYMLINK),ret,threw=!0;try{ret=fs2.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs2.closeSync(fd)}catch{}else fs2.closeSync(fd)}return ret}):fs2.futimes&&(fs2.lutimes=function(_a,_b,_c,cb){cb&&process.nextTick(cb)},fs2.lutimesSync=function(){})}function chmodFix(orig){return orig&&function(target,mode,cb){return orig.call(fs,target,mode,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}}function chmodFixSync(orig){return orig&&function(target,mode){try{return orig.call(fs,target,mode)}catch(er){if(!chownErOk(er))throw er}}}function chownFix(orig){return orig&&function(target,uid,gid,cb){return orig.call(fs,target,uid,gid,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}}function chownFixSync(orig){return orig&&function(target,uid,gid){try{return orig.call(fs,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}}function statFix(orig){return orig&&function(target,options,cb){typeof options=="function"&&(cb=options,options=null);function callback(er,stats){stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),cb&&cb.apply(this,arguments)}return options?orig.call(fs,target,options,callback):orig.call(fs,target,callback)}}function statFixSync(orig){return orig&&function(target,options){var stats=options?orig.call(fs,target,options):orig.call(fs,target);return stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),stats}}function chownErOk(er){if(!er||er.code==="ENOSYS")return!0;var nonroot=!process.getuid||process.getuid()!==0;return!!(nonroot&&(er.code==="EINVAL"||er.code==="EPERM"))}}}});var require_legacy_streams=__commonJS({"node_modules/graceful-fs/legacy-streams.js"(exports,module){var Stream=__require("stream").Stream;module.exports=legacy;function legacy(fs){return{ReadStream,WriteStream};function ReadStream(path,options){if(!(this instanceof ReadStream))return new ReadStream(path,options);Stream.call(this);var self=this;this.path=path,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){self._read()});return}fs.open(this.path,this.flags,this.mode,function(err,fd){if(err){self.emit("error",err),self.readable=!1;return}self.fd=fd,self.emit("open",fd),self._read()})}function WriteStream(path,options){if(!(this instanceof WriteStream))return new WriteStream(path,options);Stream.call(this),this.path=path,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=fs.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}}});var require_clone=__commonJS({"node_modules/graceful-fs/clone.js"(exports,module){"use strict";module.exports=clone;var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};function clone(obj){if(obj===null||typeof obj!="object")return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}}});var require_graceful_fs=__commonJS({"node_modules/graceful-fs/graceful-fs.js"(exports,module){var fs=__require("fs"),polyfills=require_polyfills(),legacy=require_legacy_streams(),clone=require_clone(),util=__require("util"),gracefulQueue,previousSymbol;typeof Symbol=="function"&&typeof Symbol.for=="function"?(gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous")):(gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous");function noop(){}function publishQueue(context,queue2){Object.defineProperty(context,gracefulQueue,{get:function(){return queue2}})}var debug=noop;util.debuglog?debug=util.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join(`
|
|
3
|
+
GFS4: `),console.error(m)});fs[gracefulQueue]||(queue=global[gracefulQueue]||[],publishQueue(fs,queue),fs.close=(function(fs$close){function close(fd,cb){return fs$close.call(fs,fd,function(err){err||resetQueue(),typeof cb=="function"&&cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close})(fs.close),fs.closeSync=(function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync})(fs.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){debug(fs[gracefulQueue]),__require("assert").equal(fs[gracefulQueue].length,0)}));var queue;global[gracefulQueue]||publishQueue(global,fs[gracefulQueue]);module.exports=patch(clone(fs));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs.__patched&&(module.exports=patch(fs),fs.__patched=!0);function patch(fs2){polyfills(fs2),fs2.gracefulify=patch,fs2.createReadStream=createReadStream,fs2.createWriteStream=createWriteStream;var fs$readFile=fs2.readFile;fs2.readFile=readFile;function readFile(path,options,cb){return typeof options=="function"&&(cb=options,options=null),go$readFile(path,options,cb);function go$readFile(path2,options2,cb2,startTime){return fs$readFile(path2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$readFile,[path2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$writeFile=fs2.writeFile;fs2.writeFile=writeFile;function writeFile(path,data,options,cb){return typeof options=="function"&&(cb=options,options=null),go$writeFile(path,data,options,cb);function go$writeFile(path2,data2,options2,cb2,startTime){return fs$writeFile(path2,data2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$writeFile,[path2,data2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$appendFile=fs2.appendFile;fs$appendFile&&(fs2.appendFile=appendFile);function appendFile(path,data,options,cb){return typeof options=="function"&&(cb=options,options=null),go$appendFile(path,data,options,cb);function go$appendFile(path2,data2,options2,cb2,startTime){return fs$appendFile(path2,data2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$appendFile,[path2,data2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$copyFile=fs2.copyFile;fs$copyFile&&(fs2.copyFile=copyFile);function copyFile(src,dest,flags,cb){return typeof flags=="function"&&(cb=flags,flags=0),go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$readdir=fs2.readdir;fs2.readdir=readdir;var noReaddirOptionVersions=/^v[0-5]\./;function readdir(path,options,cb){typeof options=="function"&&(cb=options,options=null);var go$readdir=noReaddirOptionVersions.test(process.version)?function(path2,options2,cb2,startTime){return fs$readdir(path2,fs$readdirCallback(path2,options2,cb2,startTime))}:function(path2,options2,cb2,startTime){return fs$readdir(path2,options2,fs$readdirCallback(path2,options2,cb2,startTime))};return go$readdir(path,options,cb);function fs$readdirCallback(path2,options2,cb2,startTime){return function(err,files){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$readdir,[path2,options2,cb2],err,startTime||Date.now(),Date.now()]):(files&&files.sort&&files.sort(),typeof cb2=="function"&&cb2.call(this,err,files))}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs2);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs2.ReadStream;fs$ReadStream&&(ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open);var fs$WriteStream=fs2.WriteStream;fs$WriteStream&&(WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open),Object.defineProperty(fs2,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs2,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs2,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs2,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path,options){return this instanceof ReadStream?(fs$ReadStream.apply(this,arguments),this):ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.autoClose&&that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd),that.read())})}function WriteStream(path,options){return this instanceof WriteStream?(fs$WriteStream.apply(this,arguments),this):WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd))})}function createReadStream(path,options){return new fs2.ReadStream(path,options)}function createWriteStream(path,options){return new fs2.WriteStream(path,options)}var fs$open=fs2.open;fs2.open=open;function open(path,flags,mode,cb){return typeof mode=="function"&&(cb=mode,mode=null),go$open(path,flags,mode,cb);function go$open(path2,flags2,mode2,cb2,startTime){return fs$open(path2,flags2,mode2,function(err,fd){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$open,[path2,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}return fs2}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){for(var now=Date.now(),i=0;i<fs[gracefulQueue].length;++i)fs[gracefulQueue][i].length>2&&(fs[gracefulQueue][i][3]=now,fs[gracefulQueue][i][4]=now);retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs[gracefulQueue].length!==0){var elem=fs[gracefulQueue].shift(),fn=elem[0],args=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn.name,args),fn.apply(null,args);else if(Date.now()-startTime>=6e4){debug("TIMEOUT",fn.name,args);var cb=args.pop();typeof cb=="function"&&cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);sinceAttempt>=desiredDelay?(debug("RETRY",fn.name,args),fn.apply(null,args.concat([startTime]))):fs[gracefulQueue].push(elem)}retryTimer===void 0&&(retryTimer=setTimeout(retry,0))}}}});var require_retry_operation=__commonJS({"node_modules/proper-lockfile/node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){self._attempts++,self._operationTimeoutCb&&(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref&&self._timeout.unref()),self._fn(self._attempts)},timeout);return this._options.unref&&timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/proper-lockfile/node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/proper-lockfile/node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_signals=__commonJS({"node_modules/signal-exit/signals.js"(exports,module){module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}});var require_signal_exit=__commonJS({"node_modules/signal-exit/index.js"(exports,module){var process3=global.process,processOk=function(process4){return process4&&typeof process4=="object"&&typeof process4.removeListener=="function"&&typeof process4.emit=="function"&&typeof process4.reallyExit=="function"&&typeof process4.listeners=="function"&&typeof process4.kill=="function"&&typeof process4.pid=="number"&&typeof process4.on=="function"};processOk(process3)?(assert=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process3.platform),EE=__require("events"),typeof EE!="function"&&(EE=EE.EventEmitter),process3.__signal_exit_emitter__?emitter=process3.__signal_exit_emitter__:(emitter=process3.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={}),emitter.infinite||(emitter.setMaxListeners(1/0),emitter.infinite=!0),module.exports=function(cb,opts){if(!processOk(global.process))return function(){};assert.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1&&load();var ev="exit";opts&&opts.alwaysLast&&(ev="afterexit");var remove=function(){emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0&&unload()};return emitter.on(ev,cb),remove},unload=function(){!loaded||!processOk(global.process)||(loaded=!1,signals.forEach(function(sig){try{process3.removeListener(sig,sigListeners[sig])}catch{}}),process3.emit=originalProcessEmit,process3.reallyExit=originalProcessReallyExit,emitter.count-=1)},module.exports.unload=unload,emit=function(event,code,signal){emitter.emitted[event]||(emitter.emitted[event]=!0,emitter.emit(event,code,signal))},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(processOk(global.process)){var listeners=process3.listeners(sig);listeners.length===emitter.count&&(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP"&&(sig="SIGINT"),process3.kill(process3.pid,sig))}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){loaded||!processOk(global.process)||(loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process3.on(sig,sigListeners[sig]),!0}catch{return!1}}),process3.emit=processEmit,process3.reallyExit=processReallyExit)},module.exports.load=load,originalProcessReallyExit=process3.reallyExit,processReallyExit=function(code){processOk(global.process)&&(process3.exitCode=code||0,emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),originalProcessReallyExit.call(process3,process3.exitCode))},originalProcessEmit=process3.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){arg!==void 0&&(process3.exitCode=arg);var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}):module.exports=function(){return function(){}};var assert,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit}});var require_mtime_precision=__commonJS({"node_modules/proper-lockfile/lib/mtime-precision.js"(exports,module){"use strict";var cacheSymbol=Symbol();function probe(file,fs,callback){let cachedPrecision=fs[cacheSymbol];if(cachedPrecision)return fs.stat(file,(err,stat)=>{if(err)return callback(err);callback(null,stat.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1e3)*1e3+5);fs.utimes(file,mtime,mtime,err=>{if(err)return callback(err);fs.stat(file,(err2,stat)=>{if(err2)return callback(err2);let precision=stat.mtime.getTime()%1e3===0?"s":"ms";Object.defineProperty(fs,cacheSymbol,{value:precision}),callback(null,stat.mtime,precision)})})}function getMtime(precision){let now=Date.now();return precision==="s"&&(now=Math.ceil(now/1e3)*1e3),new Date(now)}module.exports.probe=probe;module.exports.getMtime=getMtime}});var require_lockfile=__commonJS({"node_modules/proper-lockfile/lib/lockfile.js"(exports,module){"use strict";var path=__require("path"),fs=require_graceful_fs(),retry=require_retry2(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file,options){return options.lockfilePath||`${file}.lock`}function resolveCanonicalPath(file,options,callback){if(!options.realpath)return callback(null,path.resolve(file));options.fs.realpath(file,callback)}function acquireLock(file,options,callback){let lockfilePath=getLockFile(file,options);options.fs.mkdir(lockfilePath,err=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file}));options.fs.stat(lockfilePath,(err2,stat)=>{if(err2)return err2.code==="ENOENT"?acquireLock(file,{...options,stale:0},callback):callback(err2);if(!isLockStale(stat,options))return callback(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file}));removeLock(file,options,err3=>{if(err3)return callback(err3);acquireLock(file,{...options,stale:0},callback)})})})}function isLockStale(stat,options){return stat.mtime.getTime()<Date.now()-options.stale}function removeLock(file,options,callback){options.fs.rmdir(getLockFile(file,options),err=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file,options){let lock2=locks[file];lock2.updateTimeout||(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err)return err.code==="ENOENT"||isOverThreshold?setLockAsCompromised(file,lock2,Object.assign(err,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(file,options));if(!(lock2.mtime.getTime()===stat.mtime.getTime()))return setLockAsCompromised(file,lock2,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,err2=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(!lock2.released){if(err2)return err2.code==="ENOENT"||isOverThreshold2?setLockAsCompromised(file,lock2,Object.assign(err2,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(file,options));lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file,options)}})})},lock2.updateDelay),lock2.updateTimeout.unref&&lock2.updateTimeout.unref())}function setLockAsCompromised(file,lock2,err){lock2.released=!0,lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),locks[file]===lock2&&delete locks[file],lock2.options.onCompromised(err)}function lock(file,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs,onCompromised:err=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries=="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2e3),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1e3),resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file2,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file2]={lockfilePath:getLockFile(file2,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file2,options),callback(null,releasedCallback=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));unlock(file2,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file,options,callback){options={fs,realpath:!0,...options},resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);let lock2=locks[file2];if(!lock2)return callback(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file2],removeLock(file2,options,callback)})}function check(file,options,callback){options={stale:1e4,realpath:!0,fs,...options},options.stale=Math.max(options.stale||0,2e3),resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);options.fs.stat(getLockFile(file2,options),(err2,stat)=>err2?err2.code==="ENOENT"?callback(null,!1):callback(err2):callback(null,!isLockStale(stat,options)))})}function getLocks(){return locks}onExit(()=>{for(let file in locks){let options=locks[file].options;try{options.fs.rmdirSync(getLockFile(file,options))}catch{}}});module.exports.lock=lock;module.exports.unlock=unlock;module.exports.check=check;module.exports.getLocks=getLocks}});var require_adapter=__commonJS({"node_modules/proper-lockfile/lib/adapter.js"(exports,module){"use strict";var fs=require_graceful_fs();function createSyncFs(fs2){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs2};return methods.forEach(method=>{newFs[method]=(...args)=>{let callback=args.pop(),ret;try{ret=fs2[`${method}Sync`](...args)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args)=>new Promise((resolve,reject)=>{args.push((err,result)=>{err?reject(err):resolve(result)}),method(...args)})}function toSync(method){return(...args)=>{let err,result;if(args.push((_err,_result)=>{err=_err,result=_result}),method(...args),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs),typeof options.retries=="number"&&options.retries>0||options.retries&&typeof options.retries.retries=="number"&&options.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}}});var require_proper_lockfile=__commonJS({"node_modules/proper-lockfile/index.js"(exports,module){"use strict";var lockfile2=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file,options){let release=await toPromise(lockfile2.lock)(file,options);return toPromise(release)}function lockSync(file,options){let release=toSync(lockfile2.lock)(file,toSyncOptions(options));return toSync(release)}function unlock(file,options){return toPromise(lockfile2.unlock)(file,options)}function unlockSync(file,options){return toSync(lockfile2.unlock)(file,toSyncOptions(options))}function check(file,options){return toPromise(lockfile2.check)(file,options)}function checkSync(file,options){return toSync(lockfile2.check)(file,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check;module.exports.checkSync=checkSync}});import{execSync,spawnSync}from"child_process";var commandResultCache=new Map,ENV_VAR_NAME_RE=/^[A-Za-z_][A-Za-z0-9_]*$/,ENV_VAR_NAME_PREFIX_RE=/^[A-Za-z_][A-Za-z0-9_]*/;function appendLiteral(parts,value){if(!value)return;let previousPart=parts[parts.length-1];if(previousPart?.type==="literal"){previousPart.value+=value;return}parts.push({type:"literal",value})}function parseConfigValueTemplate(config){let parts=[],index=0;for(;index<config.length;){let dollarIndex=config.indexOf("$",index);if(dollarIndex<0){appendLiteral(parts,config.slice(index));break}appendLiteral(parts,config.slice(index,dollarIndex));let nextChar=config[dollarIndex+1];if(nextChar==="$"||nextChar==="!"){appendLiteral(parts,nextChar),index=dollarIndex+2;continue}if(nextChar==="{"){let endIndex=config.indexOf("}",dollarIndex+2);if(endIndex<0){appendLiteral(parts,"$"),index=dollarIndex+1;continue}let name=config.slice(dollarIndex+2,endIndex);ENV_VAR_NAME_RE.test(name)?parts.push({type:"env",name}):appendLiteral(parts,config.slice(dollarIndex,endIndex+1)),index=endIndex+1;continue}let match=config.slice(dollarIndex+1).match(ENV_VAR_NAME_PREFIX_RE);if(match){parts.push({type:"env",name:match[0]}),index=dollarIndex+1+match[0].length;continue}appendLiteral(parts,"$"),index=dollarIndex+1}return parts}function parseConfigValueReference(config){return config.startsWith("!")?{type:"command",config}:{type:"template",parts:parseConfigValueTemplate(config)}}function resolveEnvConfigValue(name,env){return env?.[name]||process.env[name]||void 0}function getTemplateEnvVarNames(parts){let names=[];for(let part of parts)part.type!=="env"||names.includes(part.name)||names.push(part.name);return names}function resolveTemplate(parts,env){let resolved="";for(let part of parts){if(part.type==="literal"){resolved+=part.value;continue}let envValue=resolveEnvConfigValue(part.name,env);if(envValue===void 0)return;resolved+=envValue}return resolved}function getConfigValueEnvVarNames(config){let reference=parseConfigValueReference(config);return reference.type==="template"?getTemplateEnvVarNames(reference.parts):[]}function getMissingConfigValueEnvVarNames(config,env){return getConfigValueEnvVarNames(config).filter(name=>resolveEnvConfigValue(name,env)===void 0)}function isCommandConfigValue(config){return parseConfigValueReference(config).type==="command"}function isConfigValueConfigured(config,env){return getMissingConfigValueEnvVarNames(config,env).length===0}function resolveConfigValue(config,env){let reference=parseConfigValueReference(config);return reference.type==="command"?executeCommand(reference.config):resolveTemplate(reference.parts,env)}function executeWithConfiguredShell(command){try{let{shell,args,commandTransport}=getShellConfig(),commandFromStdin=commandTransport==="stdin",result=spawnSync(shell,commandFromStdin?args:[...args,command],{encoding:"utf-8",input:commandFromStdin?command:void 0,timeout:1e4,stdio:[commandFromStdin?"pipe":"ignore","pipe","ignore"],shell:!1,windowsHide:!0});return result.error?result.error.code==="ENOENT"?{executed:!1,value:void 0}:{executed:!0,value:void 0}:result.status!==0?{executed:!0,value:void 0}:{executed:!0,value:(result.stdout??"").trim()||void 0}}catch{return{executed:!1,value:void 0}}}function executeWithDefaultShell(command){try{return execSync(command,{encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function executeCommandUncached(commandConfig){let command=commandConfig.slice(1);return process.platform==="win32"?(()=>{let configuredResult=executeWithConfiguredShell(command);return configuredResult.executed?configuredResult.value:executeWithDefaultShell(command)})():executeWithDefaultShell(command)}function executeCommand(commandConfig){if(commandResultCache.has(commandConfig))return commandResultCache.get(commandConfig);let result=executeCommandUncached(commandConfig);return commandResultCache.set(commandConfig,result),result}function resolveConfigValueUncached(config,env){let reference=parseConfigValueReference(config);return reference.type==="command"?executeCommandUncached(reference.config):resolveTemplate(reference.parts,env)}function resolveConfigValueOrThrow(config,description,env){let resolvedValue=resolveConfigValueUncached(config,env);if(resolvedValue!==void 0)return resolvedValue;let reference=parseConfigValueReference(config);if(reference.type==="command")throw new Error(`Failed to resolve ${description} from shell command: ${reference.config.slice(1)}`);if(reference.type==="template"){let missingEnvVars=getMissingConfigValueEnvVarNames(config,env);if(missingEnvVars.length===1)throw new Error(`Failed to resolve ${description} from environment variable: ${missingEnvVars[0]}`);if(missingEnvVars.length>1)throw new Error(`Failed to resolve ${description} from environment variables: ${missingEnvVars.join(", ")}`)}throw new Error(`Failed to resolve ${description}`)}function resolveHeadersOrThrow(headers,description,env){if(!headers)return;let resolved={};for(let[key,value]of Object.entries(headers))resolved[key]=resolveConfigValueOrThrow(value,`${description} header "${key}"`,env);return Object.keys(resolved).length>0?resolved:void 0}var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{dirname,join}from"path";import{setTimeout as sleep}from"timers/promises";function abortReason(signal){if(signal.reason!==void 0)return signal.reason;let error=new Error("The operation was aborted");return error.name="AbortError",error}function operationSignal(signal){return signal??new AbortController().signal}function raceWithAbortSignal(operation,signal){return signal?signal.aborted?(operation.catch(()=>{}),Promise.reject(abortReason(signal))):new Promise((resolve,reject)=>{let settled=!1,cleanup=()=>signal.removeEventListener("abort",onAbort),onAbort=()=>{settled||(settled=!0,cleanup(),reject(abortReason(signal)))};signal.addEventListener("abort",onAbort,{once:!0}),operation.then(value=>{settled||(settled=!0,cleanup(),resolve(value))},error=>{settled||(settled=!0,cleanup(),reject(error))}),signal.aborted&&onAbort()}):operation}var AUTH_FILE_WRITE_OPTIONS={encoding:"utf-8",mode:384},sharedAuthFileReadState,FileAuthStorageBackend=class{authPath;constructor(authPath=join(getAgentDir(),"auth.json")){this.authPath=normalizePath(authPath)}ensureParentDir(){let dir=dirname(this.authPath);existsSync(dir)||mkdirSync(dir,{recursive:!0,mode:448})}ensureFileExists(){existsSync(this.authPath)||writeFileSync(this.authPath,"{}",AUTH_FILE_WRITE_OPTIONS)}acquireLockSyncWithRetry(path){let lastError;for(let attempt=1;attempt<=10;attempt++)try{return import_proper_lockfile.default.lockSync(path,{realpath:!1})}catch(error){if((typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0)!=="ELOCKED"||attempt===10)throw error;lastError=error;let start=Date.now();for(;Date.now()-start<20;);}throw lastError??new Error("Failed to acquire auth storage lock")}withLock(fn){this.ensureParentDir(),this.ensureFileExists();let release;try{release=this.acquireLockSyncWithRetry(this.authPath);let current=existsSync(this.authPath)?readFileSync(this.authPath,"utf-8"):void 0,{result,next}=fn(current);return next!==void 0&&writeFileSync(this.authPath,next,AUTH_FILE_WRITE_OPTIONS),result}finally{release&&release()}}async acquireLockAsync(signal,onCompromised){let deadline=Date.now()+3e4,retry=0;for(;;){signal?.throwIfAborted();let release;try{release=await import_proper_lockfile.default.lock(this.authPath,{realpath:!1,retries:0,stale:3e4,onCompromised})}catch(error){signal?.throwIfAborted();let code=typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0,remainingMs=deadline-Date.now();if(code!=="ELOCKED"||remainingMs<=0)throw error;let baseDelayMs=Math.min(10*2**retry,2e3/2);retry++;let delayMs=Math.min(Math.round(baseDelayMs*(1+Math.random())),remainingMs);signal?await sleep(delayMs,void 0,{signal}):await sleep(delayMs);continue}return signal?.aborted&&(await release(),signal.throwIfAborted()),release}}async withLockAsync(fn,options){options?.signal?.throwIfAborted(),this.ensureParentDir(),this.ensureFileExists();let release,lockCompromised=!1,lockCompromisedError,throwIfCompromised=()=>{if(lockCompromised)throw lockCompromisedError??new Error("Auth storage lock was compromised")};try{release=await this.acquireLockAsync(options?.signal,error=>{lockCompromised=!0,lockCompromisedError=error}),throwIfCompromised(),options?.signal?.throwIfAborted();let current=existsSync(this.authPath)?readFileSync(this.authPath,"utf-8"):void 0,{result,next}=await fn(current);return throwIfCompromised(),options?.signal?.throwIfAborted(),next!==void 0&&writeFileSync(this.authPath,next,AUTH_FILE_WRITE_OPTIONS),throwIfCompromised(),result}finally{if(release)try{await release()}catch{}}}},ReadOnlyAuthStorage=class{authPath;data;constructor(authPath=join(getAgentDir(),"auth.json")){this.authPath=normalizePath(authPath)}load(){if(this.data)return this.data;let parsed;try{parsed=JSON.parse(stripBom(readFileSync(this.authPath,"utf-8")))}catch(error){if(error.code==="ENOENT")return this.data={},this.data;throw new Error(`Failed to read auth.json: ${error instanceof Error?error.message:String(error)}`)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error("Invalid auth.json: expected an object");for(let[providerId,credential]of Object.entries(parsed)){if(typeof credential!="object"||credential===null||Array.isArray(credential))throw new Error(`Invalid auth.json credential for provider "${providerId}"`);let value=credential;if(value.type==="api_key"){let validKey=value.key===void 0||typeof value.key=="string",validEnv=value.env===void 0||typeof value.env=="object"&&value.env!==null&&!Array.isArray(value.env)&&Object.values(value.env).every(entry=>typeof entry=="string");if(validKey&&validEnv)continue}else if(value.type==="oauth"&&typeof value.access=="string"&&typeof value.refresh=="string"&&typeof value.expires=="number"&&Number.isFinite(value.expires))continue;throw new Error(`Invalid auth.json credential for provider "${providerId}"`)}return this.data=parsed,this.data}async read(providerId,options){options?.signal?.throwIfAborted();let credential=this.load()[providerId];if(options?.signal?.throwIfAborted(),!!credential)return credential.type!=="api_key"||!credential.key||isCommandConfigValue(credential.key)?structuredClone(credential):{...credential,key:resolveConfigValue(credential.key,credential.env)}}async list(options){options?.signal?.throwIfAborted();let credentials=Object.entries(this.load()).map(([providerId,credential])=>({providerId,type:credential.type}));return options?.signal?.throwIfAborted(),credentials}async modify(_providerId,_fn,_options){throw new Error("Read-only credential storage cannot modify auth.json")}async delete(_providerId,_options){throw new Error("Read-only credential storage cannot modify auth.json")}},InMemoryAuthStorageBackend=class{value;asyncChain=Promise.resolve();withLock(fn){let{result,next}=fn(this.value);return next!==void 0&&(this.value=next),result}withLockAsync(fn,options){let previous=this.asyncChain,operation=(async()=>{await previous.catch(()=>{}),options?.signal?.throwIfAborted();let{result,next}=await fn(this.value);return options?.signal?.throwIfAborted(),next!==void 0&&(this.value=next),result})();return this.asyncChain=operation.catch(()=>{}),raceWithAbortSignal(operation,options?.signal)}},AuthStorage=class _AuthStorage{storage;authPath;readState;constructor(storage,authPath){if(this.storage=storage,this.authPath=authPath,this.readState=authPath&&sharedAuthFileReadState?.authPath===authPath?sharedAuthFileReadState.readState:{data:{}},authPath&&!sharedAuthFileReadState&&(sharedAuthFileReadState={authPath,readState:this.readState}),authPath){let revision=getFileRevision(authPath);if(revision!==void 0&&revision===this.readState.revision)return}this.reload()}static create(authPath=join(getAgentDir(),"auth.json")){let normalizedAuthPath=normalizePath(authPath);return new _AuthStorage(new FileAuthStorageBackend(normalizedAuthPath),normalizedAuthPath)}static fromStorage(storage){return new _AuthStorage(storage)}static inMemory(data={}){let storage=new InMemoryAuthStorageBackend;return storage.withLock(()=>({result:void 0,next:JSON.stringify(data,null,2)})),_AuthStorage.fromStorage(storage)}parseStorageData(content){return content?JSON.parse(stripBom(content)):{}}updateReadState(data,revision){this.readState.data=data,this.readState.revision=revision}reload(){let content,revision;try{this.storage.withLock(current=>(content=current,revision=this.authPath?getFileRevision(this.authPath):void 0,{result:void 0})),this.updateReadState(this.parseStorageData(content),revision)}catch{}}async reloadFromStorageAsync(options){return this.storage.withLockAsync(async content=>{let currentData=this.parseStorageData(content),revision=this.authPath?getFileRevision(this.authPath):void 0;return this.updateReadState(currentData,revision),{result:currentData}},options)}async readLatestData(options){if(options?.signal?.throwIfAborted(),!this.authPath){let reload2=this.reloadFromStorageAsync(options);return options?.signal?reload2:reload2.catch(()=>this.readState.data)}let revision=getFileRevision(this.authPath);if(revision!==void 0&&revision===this.readState.revision)return this.readState.data;if(!this.readState.reload){let controller=new AbortController,reload2={controller,promise:this.reloadFromStorageAsync({signal:controller.signal}),readers:0};this.readState.reload=reload2,reload2.promise.then(()=>{this.readState.reload===reload2&&(this.readState.reload=void 0)},()=>{this.readState.reload===reload2&&(this.readState.reload=void 0)})}let reload=this.readState.reload;reload.readers++;try{let result=raceWithAbortSignal(reload.promise,options?.signal);return options?.signal?await result:await result.catch(()=>this.readState.data)}finally{reload.readers--,reload.readers===0&&this.readState.reload===reload&&(this.readState.reload=void 0,reload.controller.abort())}}async read(provider,options){let credential=(await this.readLatestData(options))[provider];return options?.signal?.throwIfAborted(),credential?.type!=="api_key"||credential.key===void 0?credential:{...credential,key:resolveConfigValue(credential.key,credential.env)}}async modify(provider,fn,options){let latestData=this.readState.data,revision,result=await this.storage.withLockAsync(async content=>{let currentData=this.parseStorageData(content),next=await fn(currentData[provider]);if(next===void 0)return latestData=currentData,revision=this.authPath?getFileRevision(this.authPath):void 0,{result:currentData[provider]};let merged={...currentData,[provider]:next};return latestData=merged,{result:next,next:JSON.stringify(merged,null,2)}},options);return this.updateReadState(latestData,revision),result}async delete(provider,options){let latestData=this.readState.data;await this.storage.withLockAsync(async content=>{let currentData=this.parseStorageData(content);return delete currentData[provider],latestData=currentData,{result:void 0,next:JSON.stringify(currentData,null,2)}},options),this.updateReadState(latestData)}async list(options){let entries=Object.entries(await this.readLatestData(options));return options?.signal?.throwIfAborted(),entries.map(([providerId,credential])=>({providerId,type:credential.type}))}};function readStoredCredential(providerId,authPath=join(getAgentDir(),"auth.json")){try{return JSON.parse(stripBom(readFileSync(normalizePath(authPath),"utf-8")))[providerId]}catch{return}}var MCP_EXPOSURES=["codemode","deferred","direct","hidden"],MCP_EXPOSURE_ALIASES={"codemode-deferred":"codemode"},LOOPBACK_HOSTS=["localhost","127.0.0.1","[::1]"];function isLoopbackRedirectUri(value){if(!URL.canParse(value))return!1;let url=new URL(value);return url.protocol==="http:"&&LOOPBACK_HOSTS.includes(url.hostname)&&url.search===""&&url.hash===""}var SERVER_NAME=/^[A-Za-z0-9_-]+$/;function mcpNamespace(server){return`mcp__${server.replace(/-/g,"_")}`}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStringRecord(value){return isRecord(value)&&Object.values(value).every(entry=>typeof entry=="string")}function validateOAuth(value){if(value===void 0)return;if(!isRecord(value))return"oauth must be an object";if(value.clientId!==void 0&&typeof value.clientId!="string")return"oauth.clientId must be a string";if(value.clientSecret!==void 0&&typeof value.clientSecret!="string")return"oauth.clientSecret must be a string";let port=value.callbackPort;if(port!==void 0&&(typeof port!="number"||!Number.isInteger(port)||port<1||port>65535))return"oauth.callbackPort must be a port number";if(value.callbackUrl!==void 0){if(typeof value.callbackUrl!="string"||!isLoopbackRedirectUri(value.callbackUrl))return"oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment";let urlPort=new URL(value.callbackUrl).port;if(urlPort&&port!==void 0&&Number(urlPort)!==port)return"oauth.callbackUrl and oauth.callbackPort name different ports"}if(value.scope!==void 0&&typeof value.scope!="string")return"oauth.scope must be a string";if(value.clientName!==void 0&&(typeof value.clientName!="string"||!value.clientName.trim()))return"oauth.clientName must be a non-empty string";if(value.clientRegistration!==void 0&&value.clientRegistration!=="dcr"){if(value.clientRegistration!=="cimd")return'oauth.clientRegistration must be "dcr" or "cimd"';if(value.clientId!==void 0||value.clientName!==void 0)return'oauth.clientRegistration "cimd" cannot be combined with oauth.clientId or oauth.clientName';let callback=typeof value.callbackUrl=="string"?new URL(value.callbackUrl):void 0;if(callback&&(callback.hostname==="[::1]"||callback.pathname!=="/callback"))return'oauth.clientRegistration "cimd" requires oauth.callbackUrl on localhost or 127.0.0.1 with path /callback'}let metadataUrl=value.authServerMetadataUrl;if(metadataUrl!==void 0){let url=typeof metadataUrl=="string"&&URL.canParse(metadataUrl)?new URL(metadataUrl):void 0;if(!url||!(url.protocol==="https:"||url.protocol==="http:"&&LOOPBACK_HOSTS.includes(url.hostname)))return"oauth.authServerMetadataUrl must be an https URL, or http on localhost, 127.0.0.1, or [::1]"}}function isExposure(value){return typeof value=="string"&&MCP_EXPOSURES.includes(value)}function resolveExposureAlias(value){return typeof value=="string"?MCP_EXPOSURE_ALIASES[value]??value:value}function resolveExposureAliases(value){let{exposure,toolExposure}=value,resolved={...value};return exposure!==void 0&&(resolved.exposure=resolveExposureAlias(exposure)),isRecord(toolExposure)&&(resolved.toolExposure=Object.fromEntries(Object.entries(toolExposure).map(([tool,entry])=>[tool,resolveExposureAlias(entry)]))),resolved}function toolPatternRegExp(pattern){let source=pattern.split("*").map(part=>part.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${source}$`)}function getMcpToolExposure(config,toolName){let overrides=config.toolExposure??{},exact=overrides[toolName];if(exact!==void 0)return exact;for(let[pattern,exposure]of Object.entries(overrides))if(pattern.includes("*")&&toolPatternRegExp(pattern).test(toolName))return exposure;return config.exposure??"codemode"}function validateMcpServerConfig(name,raw){if(!SERVER_NAME.test(name))return`invalid server name "${name}" (use letters, digits, "_" and "-")`;if(!isRecord(raw))return`server "${name}" must be an object`;let value=resolveExposureAliases(raw),{type,exposure,enabled,timeout,toolExposure,description}=value,exposures=MCP_EXPOSURES.map(value2=>`"${value2}"`).join(", ");if(exposure!==void 0&&!isExposure(exposure))return`server "${name}": exposure must be one of ${exposures}`;if(toolExposure!==void 0){if(!isRecord(toolExposure))return`server "${name}": toolExposure must map tool names to exposures`;for(let[tool,value2]of Object.entries(toolExposure))if(!isExposure(value2))return`server "${name}": toolExposure "${tool}" must be one of ${exposures}`}if(enabled!==void 0&&typeof enabled!="boolean")return`server "${name}": enabled must be a boolean`;if(description!==void 0&&typeof description!="string")return`server "${name}": description must be a string`;if(timeout!==void 0&&(typeof timeout!="number"||!(timeout>0)))return`server "${name}": timeout must be a positive number of seconds`;if(type==="sse")return`server "${name}": legacy SSE transport is not supported; use the streamable HTTP URL`;if(typeof value.url=="string"&&(type===void 0||type==="http"||type==="streamable-http")){if(!URL.canParse(value.url)||!/^https?:$/.test(new URL(value.url).protocol))return`server "${name}": url must be an http or https URL`;if(value.headers!==void 0&&!isStringRecord(value.headers))return`server "${name}": headers must map names to strings`;let oauthError=validateOAuth(value.oauth);if(oauthError)return`server "${name}": ${oauthError}`;if(value.auth!==void 0){if(!isRecord(value.auth)||typeof value.auth.provider!="string"||!value.auth.provider)return`server "${name}": auth.provider must be a provider name`;let url=new URL(value.url);if(url.protocol!=="https:"&&!LOOPBACK_HOSTS.includes(url.hostname))return`server "${name}": auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]`}return value}return typeof value.command=="string"&&(type===void 0||type==="stdio")?value.args!==void 0&&!(Array.isArray(value.args)&&value.args.every(arg=>typeof arg=="string"))?`server "${name}": args must be an array of strings`:value.env!==void 0&&!isStringRecord(value.env)?`server "${name}": env must map names to strings`:value.cwd!==void 0&&typeof value.cwd!="string"?`server "${name}": cwd must be a string`:value:`server "${name}" needs either "command" (stdio) or "url" (streamable HTTP)`}var McpServerRegistry=class{servers=new Map;changeListener;register(server){this.servers.set(server.name,server),this.changeListener?.()}unregister(name,extensionPath){this.servers.get(name)?.extensionPath===extensionPath&&(this.servers.delete(name),this.changeListener?.())}get(name){return this.servers.get(name)}list(){return[...this.servers.values()].map(server=>({...server,config:structuredClone(server.config)}))}setChangeListener(listener){this.changeListener=listener}};var JSON_RPC_ERROR_CODES={parseError:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internalError:-32603},McpError=class extends Error{code;data;constructor(code,message,data){super(message),this.name="McpError",this.code=code,this.data=data}},McpConnectionClosedError=class extends Error{constructor(message="MCP connection closed"){super(message),this.name="McpConnectionClosedError"}},McpTimeoutError=class extends Error{timeoutMs;constructor(timeoutMs){super(`MCP request timed out after ${timeoutMs}ms`),this.name="McpTimeoutError",this.timeoutMs=timeoutMs}},McpAbortError=class extends Error{constructor(message="MCP request aborted"){super(message),this.name="AbortError"}};function isObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function toError(value){return value instanceof Error?value:new Error(String(value))}function isJsonRpcId(value){return typeof value=="string"||typeof value=="number"&&Number.isFinite(value)}function isJsonRpcRequest(message){return isObject(message)&&message.jsonrpc==="2.0"&&isJsonRpcId(message.id)&&typeof message.method=="string"}function isJsonRpcNotification(message){return isObject(message)&&message.jsonrpc==="2.0"&&!("id"in message)&&typeof message.method=="string"}function isJsonRpcResponse(message){return!isObject(message)||message.jsonrpc!=="2.0"||!isJsonRpcId(message.id)?!1:"result"in message?!("error"in message):!("error"in message)||!isObject(message.error)?!1:typeof message.error.code=="number"&&typeof message.error.message=="string"}function parseJsonRpcMessage(value){if(isJsonRpcRequest(value)||isJsonRpcNotification(value)||isJsonRpcResponse(value))return value;throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Invalid JSON-RPC message")}var LATEST_PROTOCOL_VERSION="2025-11-25",SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05"];var DEFAULT_REQUEST_TIMEOUT_MS=3e4,MAX_LIST_PAGES=1e3;function validateInitializeResult(value){if(!isObject(value)||typeof value.protocolVersion!="string"||!isObject(value.capabilities)||!isObject(value.serverInfo)||typeof value.serverInfo.name!="string"||typeof value.serverInfo.version!="string"||value.instructions!==void 0&&typeof value.instructions!="string")throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Invalid MCP initialize result");return value}function invalid(message){return new McpError(JSON_RPC_ERROR_CODES.invalidRequest,message)}function validateListPage(method,key,value,isItem){let items=isObject(value)?value[key]:void 0;if(!isObject(value)||!Array.isArray(items))throw invalid(`Invalid MCP ${method} result`);for(let item of items)if(!isObject(item)||!isItem(item))throw invalid(`Invalid entry in MCP ${method} result`);let nextCursor=value.nextCursor===null||value.nextCursor===""?void 0:value.nextCursor;if(nextCursor!==void 0&&typeof nextCursor!="string")throw invalid(`Invalid MCP ${method} cursor`);return{items,...nextCursor===void 0?{}:{nextCursor}}}var isTool=tool=>typeof tool.name=="string"&&isObject(tool.inputSchema),isResource=resource=>typeof resource.uri=="string"&&(resource.name===void 0||typeof resource.name=="string"),isResourceTemplate=template=>typeof template.uriTemplate=="string"&&(template.name===void 0||typeof template.name=="string");function toResource(item){return{...item,name:item.name??item.uri}}function toResourceTemplate(item){return{...item,name:item.name??item.uriTemplate}}function pageCursor(page){return page.nextCursor===void 0?{}:{nextCursor:page.nextCursor}}function validateReadResourceResult(value){if(!isObject(value)||!Array.isArray(value.contents))throw invalid("Invalid MCP resources/read result");for(let contents of value.contents)if(!isObject(contents)||typeof contents.uri!="string"||typeof contents.text!="string"&&typeof contents.blob!="string")throw invalid("Invalid contents in MCP resources/read result");return value}function validateCallToolResult(value){if(!isObject(value)||value.content!==void 0&&!Array.isArray(value.content))throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Invalid MCP tools/call result");if(value.structuredContent!==void 0&&!isObject(value.structuredContent))throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Invalid MCP tools/call structured content");return value.content===void 0?{...value,content:[]}:value}var McpClient=class{options;state="idle";transport;nextRequestId=1;serverInfoValue;serverCapabilitiesValue;instructionsValue;protocolVersionValue;pending=new Map;progressRequests=new Map;incoming=new Map;requestHandlers=new Map;notificationListeners=new Map;errorListeners=new Set;closeListeners=new Set;disposers=[];constructor(options){this.options=Object.freeze({...options}),this.requestHandlers.set("ping",()=>({}));let roots=options.roots;roots&&this.requestHandlers.set("roots/list",async()=>({roots:[...typeof roots=="function"?await roots():roots]}))}get connectionState(){return this.state}get serverInfo(){return this.serverInfoValue}get serverCapabilities(){return this.serverCapabilitiesValue}get instructions(){return this.instructionsValue}get protocolVersion(){return this.protocolVersionValue}async connect(transport){if(this.state!=="idle")throw new Error(`Cannot connect MCP client in ${this.state} state`);this.state="connecting",this.transport=transport,this.disposers=[transport.onMessage(message=>this.handleMessage(message)),transport.onError(error=>this.emitError(error)),transport.onClose(()=>this.handleTransportClose())];try{await transport.start();let capabilities={...this.options.capabilities};this.options.roots&&capabilities.roots===void 0&&(capabilities.roots={});let result=validateInitializeResult(await this.requestInternal("initialize",{protocolVersion:this.options.protocolVersion??LATEST_PROTOCOL_VERSION,capabilities,clientInfo:{name:this.options.name,version:this.options.version,...this.options.title===void 0?{}:{title:this.options.title}}},{},!0));if(!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion))throw new Error(`MCP server selected unsupported protocol version ${result.protocolVersion}`);return this.protocolVersionValue=result.protocolVersion,this.serverInfoValue=result.serverInfo,this.serverCapabilitiesValue=result.capabilities,this.instructionsValue=result.instructions,transport.setProtocolVersion?.(result.protocolVersion),await this.notifyInternal("notifications/initialized",void 0,!0),this.state="connected",result}catch(error){throw await this.close().catch(()=>{}),error}}request(method,params,options={}){return this.requestInternal(method,params,options,!1)}notify(method,params){return this.notifyInternal(method,params,!1)}setRequestHandler(method,handler){return this.requestHandlers.set(method,handler),()=>{this.requestHandlers.get(method)===handler&&this.requestHandlers.delete(method)}}onNotification(method,listener){let listeners=this.notificationListeners.get(method)??new Set;return this.notificationListeners.set(method,listeners),listeners.add(listener),()=>{listeners.delete(listener),listeners.size===0&&this.notificationListeners.delete(method)}}onError(listener){return this.errorListeners.add(listener),()=>this.errorListeners.delete(listener)}onClose(listener){return this.closeListeners.add(listener),()=>this.closeListeners.delete(listener)}async ping(options={}){await this.request("ping",void 0,options)}async listTools(options={}){return await this.listAll("tools/list","tools",isTool,options)}async listResources(options={}){return(await this.listAll("resources/list","resources",isResource,options)).map(toResource)}async listResourcesPage(cursor,options={}){let page=await this.listPage("resources/list","resources",isResource,cursor,options);return{resources:page.items.map(toResource),...pageCursor(page)}}async listResourceTemplates(options={}){return(await this.listAll("resources/templates/list","resourceTemplates",isResourceTemplate,options)).map(toResourceTemplate)}async listResourceTemplatesPage(cursor,options={}){let page=await this.listPage("resources/templates/list","resourceTemplates",isResourceTemplate,cursor,options);return{resourceTemplates:page.items.map(toResourceTemplate),...pageCursor(page)}}async readResource(uri,options={}){return validateReadResourceResult(await this.request("resources/read",{uri},options))}async listPage(method,key,isItem,cursor,options){return validateListPage(method,key,await this.request(method,cursor===void 0?void 0:{cursor},options),isItem)}async listAll(method,key,isItem,options){let items=[],cursors=new Set,cursor;for(let pageNumber=0;pageNumber<MAX_LIST_PAGES;pageNumber++){let page=await this.listPage(method,key,isItem,cursor,options);if(items.push(...page.items),page.nextCursor===void 0)return items;if(cursors.has(page.nextCursor))throw new Error(`MCP ${method} returned duplicate cursor: ${page.nextCursor}`);cursors.add(page.nextCursor),cursor=page.nextCursor}throw new Error(`MCP ${method} exceeded ${MAX_LIST_PAGES} pages`)}async callTool(name,args,options={}){return validateCallToolResult(await this.request("tools/call",{name,...args===void 0?{}:{arguments:args}},options))}async close(){let transport=this.transport;this.transport=void 0,this.disposeTransportListeners(),this.markClosed(new McpConnectionClosedError),await transport?.close()}async requestInternal(method,params,options,allowConnecting){let transport=this.requireTransport(allowConnecting);if(options.signal?.aborted)throw new McpAbortError;let id=this.nextRequestId++,progressToken=options.onProgress?id:void 0,requestParams=progressToken===void 0?params:{...params,_meta:{...isObject(params?._meta)?params._meta:{},progressToken}},message={jsonrpc:"2.0",id,method,...requestParams===void 0?{}:{params:requestParams}};return new Promise((resolve,reject)=>{let entry={resolve,reject,timeoutMs:options.timeoutMs??this.options.requestTimeoutMs??DEFAULT_REQUEST_TIMEOUT_MS,timer:void 0,signal:options.signal,onAbort:()=>this.cancelPending(id,new McpAbortError,method!=="initialize",String(options.signal?.reason??"Aborted")),cancellable:method!=="initialize",onProgress:options.onProgress,progressToken};this.pending.set(id,entry),progressToken!==void 0&&this.progressRequests.set(progressToken,id),options.signal?.addEventListener("abort",entry.onAbort,{once:!0}),this.armTimeout(id,entry),transport.send(message).catch(error=>this.cancelPending(id,error,!1))})}async notifyInternal(method,params,allowConnecting){await this.requireTransport(allowConnecting).send({jsonrpc:"2.0",method,...params===void 0?{}:{params}})}requireTransport(allowConnecting){if(this.transport&&(this.state==="connected"||allowConnecting&&this.state==="connecting"))return this.transport;throw new McpConnectionClosedError(`MCP client is ${this.state}`)}handleMessage(message){if(isJsonRpcResponse(message)){this.handleResponse(message);return}if(isJsonRpcRequest(message)){this.handleRequest(message);return}if(isJsonRpcNotification(message)){this.handleNotification(message.method,message.params);return}this.emitError(new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Received invalid JSON-RPC message"))}handleResponse(message){let entry=this.pending.get(message.id);if(!entry){this.emitError(new Error(`Received response for unknown MCP request ${String(message.id)}`));return}this.removePending(message.id,entry),"error"in message?entry.reject(new McpError(message.error.code,message.error.message,message.error.data)):entry.resolve(message.result)}async handleRequest(message){let transport=this.transport;if(!transport)return;let handler=this.requestHandlers.get(message.method);if(!handler){await transport.send({jsonrpc:"2.0",id:message.id,error:{code:JSON_RPC_ERROR_CODES.methodNotFound,message:`Method not found: ${message.method}`}}).catch(error=>this.emitError(error));return}let controller=new AbortController;this.incoming.set(message.id,controller);try{let result=await handler(message.params,{signal:controller.signal});await transport.send({jsonrpc:"2.0",id:message.id,result:result??{}})}catch(error){let responseError=error instanceof McpError?{code:error.code,message:error.message,data:error.data}:{code:JSON_RPC_ERROR_CODES.internalError,message:toError(error).message};await transport.send({jsonrpc:"2.0",id:message.id,error:responseError}).catch(sendError=>this.emitError(sendError))}finally{this.incoming.delete(message.id)}}handleNotification(method,params){method==="notifications/progress"?this.handleProgress(params):method==="notifications/cancelled"&&this.handleCancelled(params);for(let listener of this.notificationListeners.get(method)??[])try{listener(params)}catch(error){this.emitError(error)}}handleProgress(params){if(!isObject(params)||!isJsonRpcId(params.progressToken)||typeof params.progress!="number")return;let requestId=this.progressRequests.get(params.progressToken),entry=requestId===void 0?void 0:this.pending.get(requestId);if(!(requestId===void 0||!entry)){this.armTimeout(requestId,entry);try{entry.onProgress?.(params)}catch(error){this.emitError(error)}}}handleCancelled(params){isObject(params)&&isJsonRpcId(params.requestId)&&this.incoming.get(params.requestId)?.abort(params.reason)}armTimeout(id,entry){entry.timer&&clearTimeout(entry.timer),!(!Number.isFinite(entry.timeoutMs)||entry.timeoutMs<=0)&&(entry.timer=setTimeout(()=>{this.cancelPending(id,new McpTimeoutError(entry.timeoutMs),entry.cancellable,"Request timed out")},entry.timeoutMs))}cancelPending(id,error,notifyServer,reason){let entry=this.pending.get(id);entry&&(this.removePending(id,entry),entry.reject(error),notifyServer&&this.transport&&this.transport.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:id,...reason?{reason}:{}}}).catch(sendError=>this.emitError(sendError)))}removePending(id,entry){this.pending.delete(id),entry.timer&&clearTimeout(entry.timer),entry.progressToken!==void 0&&this.progressRequests.delete(entry.progressToken),entry.signal?.removeEventListener("abort",entry.onAbort)}rejectPending(error){for(let[id,entry]of this.pending)this.removePending(id,entry),entry.reject(error)}handleTransportClose(){this.markClosed(new McpConnectionClosedError)}markClosed(error){let wasClosed=this.state==="closed";this.state="closed",this.rejectPending(error);for(let controller of this.incoming.values())controller.abort(error);if(this.incoming.clear(),!wasClosed)for(let listener of[...this.closeListeners])try{listener()}catch(listenerError){this.emitError(listenerError)}}emitError(error){let normalized=toError(error);for(let listener of this.errorListeners)listener(normalized)}disposeTransportListeners(){for(let dispose of this.disposers.splice(0))dispose()}};var import_cross_spawn=__toESM(require_cross_spawn(),1);import{spawn}from"node:child_process";import process2 from"node:process";var DEFAULT_MAX_MESSAGE_BYTES=16*1024*1024,TransportEvents=class{messageListeners=new Set;errorListeners=new Set;closeListeners=new Set;closeEmitted=!1;onMessage(listener){return this.messageListeners.add(listener),()=>this.messageListeners.delete(listener)}onError(listener){return this.errorListeners.add(listener),()=>this.errorListeners.delete(listener)}onClose(listener){return this.closeListeners.add(listener),()=>this.closeListeners.delete(listener)}emitMessage(message){for(let listener of this.messageListeners)listener(message)}emitError(error){let normalized=toError(error);for(let listener of this.errorListeners)listener(normalized)}emitClose(){if(!this.closeEmitted){this.closeEmitted=!0;for(let listener of this.closeListeners)listener()}}};var DEFAULT_MAX_STDERR_BYTES=64*1024,DEFAULT_CLOSE_TIMEOUT_MS=2e3,STDIN_CLOSE_GRACE_MS=500,USE_PROCESS_GROUPS=process2.platform!=="win32",liveProcessGroups=new Set,exitHookInstalled=!1;function killProcessTree(child,signal){let pid=child.pid;if(process2.platform==="win32"&&pid!==void 0){if(child.exitCode!==null)return;spawn("taskkill",["/pid",String(pid),"/T","/F"],{stdio:"ignore",windowsHide:!0}).on("error",()=>{});return}if(USE_PROCESS_GROUPS&&pid!==void 0)try{process2.kill(-pid,signal);return}catch{}try{child.kill(signal)}catch{}}function installExitHook(){exitHookInstalled||(exitHookInstalled=!0,process2.once("exit",()=>{for(let pid of liveProcessGroups)try{process2.kill(-pid,"SIGTERM")}catch{}}))}var StdioTransport=class extends TransportEvents{options;child;stdoutBuffer=Buffer.alloc(0);stderrBuffer=Buffer.alloc(0);started=!1;closed=!1;constructor(options){super(),this.options=Object.freeze({...options,args:options.args?[...options.args]:void 0})}get pid(){return this.child?.pid}get stderr(){return this.stderrBuffer.toString("utf8")}async start(){if(this.started)throw new Error("MCP stdio transport already started");if(this.closed)throw new McpConnectionClosedError;this.started=!0;let env=this.options.inheritEnv===!1?{...this.options.env}:{...process2.env,...this.options.env},child=(0,import_cross_spawn.default)(this.options.command,this.options.args??[],{cwd:this.options.cwd,env,stdio:["pipe","pipe",this.options.stderr==="inherit"?"inherit":"pipe"],windowsHide:!0,detached:USE_PROCESS_GROUPS});this.child=child;let pid=child.pid;USE_PROCESS_GROUPS&&pid!==void 0&&(installExitHook(),liveProcessGroups.add(pid),child.once("exit",()=>liveProcessGroups.delete(pid))),child.stdout?.on("data",chunk=>this.handleStdout(chunk)),child.stdout?.on("error",error=>this.emitError(error)),child.stdin?.on("error",error=>{this.closed||this.emitError(error)}),child.stderr?.on("data",chunk=>this.handleStderr(chunk)),child.stderr?.on("error",error=>this.emitError(error)),child.on("close",()=>{this.child=void 0,this.stdoutBuffer.toString("utf8").trim()&&this.emitError(new Error("MCP stdio server closed with an incomplete JSON-RPC message")),this.stdoutBuffer=Buffer.alloc(0),this.emitClose()}),await new Promise((resolve,reject)=>{let onSpawn=()=>{child.off("error",onError),resolve()},onError=error=>{child.off("spawn",onSpawn),reject(error)};child.once("spawn",onSpawn),child.once("error",onError)}),child.on("error",error=>{this.closed||this.emitError(error)})}async send(message){let stdin=this.child?.stdin;if(!this.started||this.closed||!stdin?.writable)throw new McpConnectionClosedError;let payload=`${JSON.stringify(message)}
|
|
4
|
+
`;await new Promise((resolve,reject)=>{stdin.write(payload,error=>error?reject(error):resolve())})}async close(){if(this.closed)return;this.closed=!0;let child=this.child;if(!child){this.emitClose();return}if(child.exitCode!==null||child.signalCode!==null){child.stdin?.end();return}let closeTimeoutMs=this.options.closeTimeoutMs??DEFAULT_CLOSE_TIMEOUT_MS;await new Promise(resolve=>{let timers=[];child.once("close",()=>{for(let timer of timers)clearTimeout(timer);killProcessTree(child,"SIGTERM"),resolve()});let grace=Math.min(STDIN_CLOSE_GRACE_MS,closeTimeoutMs);timers.push(setTimeout(()=>killProcessTree(child,"SIGTERM"),grace)),timers.push(setTimeout(()=>killProcessTree(child,"SIGKILL"),grace+closeTimeoutMs)),child.stdin?.end()})}handleStdout(chunk){this.stdoutBuffer=Buffer.concat([this.stdoutBuffer,Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk)]);let maxMessageBytes=this.options.maxMessageBytes??DEFAULT_MAX_MESSAGE_BYTES;for(;;){let newline=this.stdoutBuffer.indexOf(10);if(newline<0){this.stdoutBuffer.length>maxMessageBytes&&(this.stdoutBuffer=Buffer.alloc(0),this.emitError(new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`)));return}let line=this.stdoutBuffer.subarray(0,newline);if(this.stdoutBuffer=this.stdoutBuffer.subarray(newline+1),line.length>maxMessageBytes){this.emitError(new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`));continue}let text=line.toString("utf8").replace(/\r$/,"");if(text.trim())try{this.emitMessage(parseJsonRpcMessage(JSON.parse(text)))}catch(error){this.emitError(error)}}}handleStderr(chunk){let buffer=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk),maxStderrBytes=this.options.maxStderrBytes??DEFAULT_MAX_STDERR_BYTES;this.stderrBuffer=Buffer.concat([this.stderrBuffer,buffer]),this.stderrBuffer.length>maxStderrBytes&&(this.stderrBuffer=this.stderrBuffer.subarray(-maxStderrBytes)),this.options.onStderr?.(buffer.toString("utf8"))}};var MAX_ERROR_BODY_BYTES=8*1024,ERROR_MESSAGE_BODY_CHARS=500,DEFAULT_RECONNECT_INITIAL_DELAY_MS=1e3,DEFAULT_RECONNECT_MAX_DELAY_MS=3e4,DEFAULT_RECONNECT_MAX_RETRIES=5;async function consumeSseStream(stream,options){let reader=stream.getReader(),decoder=new TextDecoder,buffered="",eventName,eventId,dataLines=[],dataBytes=0,maxEventBytes=options.maxEventBytes??DEFAULT_MAX_MESSAGE_BYTES,dispatch=()=>{if(dataLines.length===0){eventName=void 0,eventId=void 0;return}let data=dataLines.join(`
|
|
5
|
+
`);options.onEvent({...eventName?{event:eventName}:{},data,...eventId?{id:eventId}:{}}),eventName=void 0,eventId=void 0,dataLines=[],dataBytes=0},processLine=rawLine=>{let line=rawLine.endsWith("\r")?rawLine.slice(0,-1):rawLine;if(line===""){dispatch();return}if(line.startsWith(":"))return;let colon=line.indexOf(":"),field=colon<0?line:line.slice(0,colon),value=colon<0?"":line.slice(colon+1);if(value.startsWith(" ")&&(value=value.slice(1)),field==="data"){if(dataBytes+=Buffer.byteLength(value)+(dataLines.length>0?1:0),dataBytes>maxEventBytes)throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);dataLines.push(value)}else field==="event"?eventName=value:field==="id"&&!value.includes("\0")?(eventId=value,options.onId?.(value)):field==="retry"&&/^\d+$/.test(value)&&options.onRetry?.(Number(value))};try{for(;;){let{done,value}=await reader.read();if(done)break;buffered+=decoder.decode(value,{stream:!0});let newline=buffered.indexOf(`
|
|
6
|
+
`);for(;newline>=0;)processLine(buffered.slice(0,newline)),buffered=buffered.slice(newline+1),newline=buffered.indexOf(`
|
|
7
|
+
`);if(Buffer.byteLength(buffered)>maxEventBytes)throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`)}buffered+=decoder.decode(),buffered&&processLine(buffered),dispatch()}finally{reader.releaseLock()}}var McpHttpError=class extends Error{status;body;constructor(status,message,body=""){super(message),this.name="McpHttpError",this.status=status,this.body=body}},McpAuthRequiredError=class extends McpHttpError{wwwAuthenticate;constructor(response,body=""){super(401,"MCP server requires authentication",body),this.name="McpAuthRequiredError",this.wwwAuthenticate=response.headers.get("www-authenticate")}},McpSessionExpiredError=class extends McpHttpError{constructor(body=""){super(404,"MCP session expired",body),this.name="McpSessionExpiredError"}};function contentType(response){return response.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()}function needsAuthorization(response){return response.status===401?!0:response.status!==403?!1:/(?:^|[\s,])error="?insufficient_scope"?/i.test(response.headers.get("www-authenticate")??"")}function isTransientStatus(status){return status===408||status===429||status>=500}function discard(response){return response.body?.cancel().catch(()=>{})??Promise.resolve()}function describeHttpFailure(status,body){let text=body.trim(),snippet=text.length>ERROR_MESSAGE_BODY_CHARS?`${text.slice(0,ERROR_MESSAGE_BODY_CHARS-3)}...`:text;return`MCP HTTP request failed with status ${status}${snippet?`: ${snippet}`:""}`}var StreamableHttpTransport=class extends TransportEvents{url;options;fetch;controller=new AbortController;started=!1;closed=!1;sessionIdValue;protocolVersion;getStreamStarted=!1;constructor(options){super(),this.options=Object.freeze({...options,headers:options.headers?{...options.headers}:void 0}),this.url=new URL(options.url);let fetch=options.fetch??globalThis.fetch;this.fetch=(input,init)=>fetch(input,init)}get sessionId(){return this.sessionIdValue}async start(){if(this.started)throw new Error("MCP Streamable HTTP transport already started");if(this.closed)throw new McpConnectionClosedError;this.started=!0}setProtocolVersion(version){this.protocolVersion=version}async send(message){if(!this.started||this.closed)throw new McpConnectionClosedError;let response=await this.authorizedFetch("POST",{headers:{accept:"application/json, text/event-stream","content-type":"application/json"},body:JSON.stringify(message)});if(await this.checkResponse(response),this.captureSession(response),!isJsonRpcRequest(message)){await discard(response),"method"in message&&message.method==="notifications/initialized"&&this.startGetStream();return}if(response.status===202||response.status===204)throw new McpHttpError(response.status,`MCP server accepted request ${message.method} without a response`);let type=contentType(response);if(type==="application/json"){let body=await response.json();for(let item of Array.isArray(body)?body:[body])this.emitMessage(parseJsonRpcMessage(item));return}if(type==="text/event-stream"&&response.body){this.consumeResponseStream(response.body,message.id);return}throw await discard(response),new McpHttpError(response.status,`Unsupported MCP response content type: ${type??"missing"}`)}async close(){if(!this.closed){if(this.closed=!0,this.controller.abort(),this.started&&this.sessionIdValue){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),1e3);try{let{headers}=await this.headers();await this.fetch(this.url,{method:"DELETE",headers,signal:controller.signal}).then(discard).catch(()=>{})}catch{}finally{clearTimeout(timeout)}}this.emitClose()}}async authorizedFetch(method,init){let onUnauthorized=this.options.authProvider?.onUnauthorized?.bind(this.options.authProvider);for(let attempt=0;;attempt++){let{headers,token}=await this.headers(init.headers),response=await this.fetch(this.url,{method,headers,body:init.body,signal:this.controller.signal});if(attempt>0||!onUnauthorized||!needsAuthorization(response))return response;try{await onUnauthorized({response,serverUrl:this.url,fetch:this.fetch,token})}finally{await discard(response)}}}async headers(extra={}){let headers=new Headers(this.options.headers);for(let[name,value]of Object.entries(extra))headers.set(name,value);this.sessionIdValue&&headers.set("Mcp-Session-Id",this.sessionIdValue),this.protocolVersion&&headers.set("MCP-Protocol-Version",this.protocolVersion);let token=await this.options.authProvider?.token();return token&&headers.set("Authorization",`Bearer ${token}`),{headers,...token?{token}:{}}}captureSession(response){let sessionId=response.headers.get("mcp-session-id");sessionId&&(this.sessionIdValue=sessionId)}async checkResponse(response){if(response.ok)return;let body=(await response.text().catch(()=>"")).slice(0,MAX_ERROR_BODY_BYTES);throw response.status===401?new McpAuthRequiredError(response,body):response.status===404&&this.sessionIdValue?new McpSessionExpiredError(body):new McpHttpError(response.status,describeHttpFailure(response.status,body),body)}async consumeSse(stream,cursor,onMessage){await consumeSseStream(stream,{maxEventBytes:this.options.maxMessageBytes??DEFAULT_MAX_MESSAGE_BYTES,onId:id=>{cursor.lastEventId=id},onRetry:delayMs=>{cursor.retryMs=delayMs},onEvent:event=>{if(cursor.received=!0,!event.data.trim()||event.event!==void 0&&event.event!=="message")return;let message;try{message=parseJsonRpcMessage(JSON.parse(event.data))}catch(error){this.emitError(error);return}onMessage?.(message),this.emitMessage(message)}})}async consumeResponseStream(body,requestId){let cursor={lastEventId:void 0,retryMs:void 0,received:!1},answered=!1,onMessage=message=>{isJsonRpcResponse(message)&&message.id===requestId&&(answered=!0)},stream=body,failure;for(let attempt=0;;){if(stream)try{await this.consumeSse(stream,cursor,onMessage),failure=void 0}catch(error){failure=error}if(answered||this.closed)return;if(failure!==void 0&&!this.isRetryable(failure)||cursor.lastEventId===void 0||attempt>=this.maxRetries())break;if(cursor.received&&(attempt=0),cursor.received=!1,!await this.sleep(this.reconnectDelay(attempt++,cursor.retryMs)))return;try{stream=await this.openSseStream(cursor.lastEventId)}catch(error){if(failure=error,!this.isRetryable(error))break;stream=void 0}}if(this.closed)return;let reason=failure===void 0?"stream ended without a response":toError(failure).message;this.emitMessage({jsonrpc:"2.0",id:requestId,error:{code:JSON_RPC_ERROR_CODES.internalError,message:`MCP response stream failed: ${reason}`}})}startGetStream(){this.options.openGetStream===!1||this.getStreamStarted||this.closed||(this.getStreamStarted=!0,this.runGetStream())}async runGetStream(){let cursor={lastEventId:void 0,retryMs:void 0,received:!1};for(let attempt=0;!this.closed;){try{let stream=await this.openSseStream(cursor.lastEventId);if(!stream)return;let openedAt=Date.now();await this.consumeSse(stream,cursor),(cursor.received||Date.now()-openedAt>this.maxDelay())&&(attempt=0)}catch(error){if(this.closed)return;if(!this.isRetryable(error)){this.emitError(error);return}}if(cursor.received=!1,attempt>=this.maxRetries()){this.emitError(new Error("MCP server-to-client stream dropped and could not be reopened"));return}if(!await this.sleep(this.reconnectDelay(attempt++,cursor.retryMs)))return}}async openSseStream(lastEventId){let response=await this.authorizedFetch("GET",{headers:{accept:"text/event-stream",...lastEventId===void 0?{}:{"last-event-id":lastEventId}}});if(response.status===405){await discard(response);return}await this.checkResponse(response),this.captureSession(response);let type=contentType(response);if(type!=="text/event-stream"||!response.body)throw await discard(response),new McpHttpError(response.status,`Unsupported MCP GET response content type: ${type??"missing"}`);return response.body}isRetryable(error){if(error instanceof McpHttpError)return isTransientStatus(error.status);if(error instanceof TypeError)return!0;let code=error?.code;return typeof code=="string"&&(code.startsWith("E")||code.startsWith("UND_ERR"))}reconnectDelay(attempt,serverDelayMs){if(serverDelayMs!==void 0)return serverDelayMs;let initial=this.options.reconnect?.initialDelayMs??DEFAULT_RECONNECT_INITIAL_DELAY_MS;return Math.min(initial*2**attempt,this.maxDelay())}maxDelay(){return this.options.reconnect?.maxDelayMs??DEFAULT_RECONNECT_MAX_DELAY_MS}maxRetries(){return this.options.reconnect?.maxRetries??DEFAULT_RECONNECT_MAX_RETRIES}sleep(ms){let signal=this.controller.signal;return signal.aborted?Promise.resolve(!1):new Promise(resolve=>{let onAbort=()=>{clearTimeout(timer),resolve(!1)},timer=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve(!0)},ms);timer.unref?.(),signal.addEventListener("abort",onAbort,{once:!0})})}};function blockToLlmContent(block){switch(block.type){case"text":return{type:"text",text:block.text};case"image":return{type:"image",data:block.data,mimeType:block.mimeType};case"audio":return{type:"text",text:`[audio ${block.mimeType} omitted]`};case"resource_link":return{type:"text",text:`${block.name}: ${block.uri}`};case"resource":{let resource=block.resource;return"text"in resource?{type:"text",text:resource.text}:resource.mimeType?.startsWith("image/")?{type:"image",data:resource.blob,mimeType:resource.mimeType}:{type:"text",text:`[binary resource ${resource.uri} (${resource.mimeType??"unknown type"}) omitted]`}}default:return{type:"text",text:`[unsupported MCP content ${block.type}]`}}}function toLlmContent(result){let content=(result.content??[]).map(blockToLlmContent);return content.length===0&&result.structuredContent!==void 0&&content.push({type:"text",text:JSON.stringify(result.structuredContent,null,2)}),content}import{createHash}from"node:crypto";function toToolExposure(exposure){return exposure==="codemode"?"deferred":exposure}var MAX_TOOL_NAME_LENGTH=64,MCP_OUTPUT_MAX_BYTES=20*1024,OUTPUT_PREVIEW_LINES=5,READ_MCP_RESOURCE_TOOL="read_mcp_resource";function saveToTempFile(data,extension){return writeOutputFile("pi-mcp",extension,data)}function createMcpToolName(server,tool,isTaken=()=>!1){let name=`mcp__${server}__${tool}`.replace(/[^A-Za-z0-9_]/g,"_");if(name.length<=MAX_TOOL_NAME_LENGTH&&!isTaken(name))return name;let hash=createHash("sha256").update(`${server}\0${tool}`).digest("hex").slice(0,8);return`${name.slice(0,MAX_TOOL_NAME_LENGTH-hash.length-1)}_${hash}`}function textOf(content){return content.filter(block=>block.type==="text").map(block=>block.text).join(`
|
|
8
|
+
`)}function createMcpResultSchema(structuredContentSchema){return{type:"object",properties:{content:{type:"array",items:{type:"object"}},...structuredContentSchema?{structuredContent:structuredContentSchema}:{},isError:{type:"boolean"},_meta:{type:"object"}},required:["content"]}}async function limitMcpContent(content,saveOutput=saveToTempFile){let combined=textOf(content),truncation=truncateMiddle(combined,MCP_OUTPUT_MAX_BYTES);if(!truncation.truncated)return{content};let fullOutputPath,where;try{fullOutputPath=await saveOutput(combined,".txt"),where=`[Full output: ${fullOutputPath} (read it with offset/limit)]`}catch(error){where=`[Could not save the full output: ${error instanceof Error?error.message:String(error)}]`}return{content:[{type:"text",text:`Warning: truncated output (original token count: ${Math.ceil(truncation.totalBytes/4)})
|
|
9
|
+
Total output lines: ${truncation.totalLines}
|
|
10
|
+
|
|
11
|
+
${truncation.content}
|
|
12
|
+
|
|
13
|
+
${where}`},...content.filter(block=>block.type==="image")],...fullOutputPath?{fullOutputPath}:{}}}function extensionOf(uri){let path=URL.canParse(uri)?new URL(uri).pathname:uri;return/\.[A-Za-z0-9]{1,8}$/.exec(path)?.[0]??".bin"}function isTextMimeType(mimeType){if(!mimeType)return!1;let type=mimeType.split(";",1)[0].trim().toLowerCase();return type.startsWith("text/")||type==="application/json"||type.endsWith("+json")||type.endsWith("+xml")}async function blockToContent(server,block,options){if(block.type==="resource_link"){let details=[block.mimeType,block.size===void 0?void 0:formatSize(block.size)].filter(Boolean),read=options.readableResources?`. Read it with ${READ_MCP_RESOURCE_TOOL} (server "${server}")`:"",description=block.description?`: ${block.description}`:"";return[{type:"text",text:`[Resource ${block.uri} "${block.title??block.name}"${details.length>0?` (${details.join(", ")})`:""}${description}${read}]`}]}if(block.type==="resource"&&"blob"in block.resource&&!block.resource.mimeType?.startsWith("image/")){let{uri,mimeType,blob}=block.resource,data=Buffer.from(blob,"base64");if(isTextMimeType(mimeType))return[{type:"text",text:data.toString("utf8")}];let kind=`${mimeType??"unknown type"}, ${formatSize(data.length)}`;try{let path=await(options.saveOutput??saveToTempFile)(data,extensionOf(uri));return[{type:"text",text:`[Binary resource ${uri} (${kind}) saved to ${path}]`}]}catch(error){let reason=error instanceof Error?error.message:String(error);return[{type:"text",text:`[Binary resource ${uri} (${kind}) could not be saved: ${reason}]`}]}}return toLlmContent({content:[block]})}async function toModelContent(server,blocks,options={}){return(await Promise.all(blocks.map(block=>blockToContent(server,block,options)))).flat()}async function convertMcpResult(server,tool,result,options={}){let converted=result.content.length>0?await toModelContent(server,result.content,options):toLlmContent(result);result.isError&&textOf(converted)===""&&converted.push({type:"text",text:`MCP tool ${server}/${tool} returned an error`});let{content,fullOutputPath}=await limitMcpContent(converted,options.saveOutput),{_meta:_ignored,...scriptResult}=result;return{content,details:{server,tool,...fullOutputPath?{fullOutputPath}:{}},structuredContent:scriptResult,...result.isError?{isError:!0}:{}}}function toParameters(schema){return{...schema,type:schema.type??"object",...schema.properties===void 0?{properties:{}}:{}}}var ANNOTATION_HINTS=["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"];function toToolAnnotations(tool){let annotations={};for(let hint of ANNOTATION_HINTS){let value=tool.annotations?.[hint];typeof value=="boolean"&&(annotations[hint]=value)}return Object.keys(annotations).length>0?annotations:void 0}function createMcpToolDefinition(options){let{server,tool}=options,title=tool.title??tool.annotations?.title,annotations=toToolAnnotations(tool),label=`${server}/${tool.name}`;return{name:options.name,label,description:tool.description?.trim()||title||`MCP tool ${tool.name} from server ${server}`,parameters:toParameters(tool.inputSchema),outputSchema:createMcpResultSchema(tool.outputSchema),exposure:toToolExposure(options.exposure),namespace:options.namespace,...annotations?{annotations}:{},...createMcpToolRenderers(label),async execute(_toolCallId,params,signal,onUpdate){let result=await(await options.getClient()).callTool(tool.name,params??{},{signal,timeoutMs:options.timeoutMs,onProgress:progress=>{let total=progress.total===void 0?"":`/${progress.total}`,text=progress.message??`Progress ${progress.progress}${total}`;onUpdate?.({content:[{type:"text",text}],details:{server,tool:tool.name}})}});return convertMcpResult(server,tool.name,result,{readableResources:options.readableResources?.()})}}}function createMcpToolRenderers(label){return{renderCall(args,theme,context){let component=context.lastComponent??new Text("",0,0);return component.setText(formatToolCallWithArgs(label,args,theme,context.expanded)),component},renderResult(result,options,theme,context){let component=context.lastComponent??new Container;component.clear();let output=getTextOutput(result,context.showImages).trim();if(!output)return component;let color=context.isError?"error":"toolOutput",styled=replaceTabs(output).split(`
|
|
14
|
+
`).map(line=>theme.fg(color,line)).join(`
|
|
15
|
+
`);if(component.addChild(new Spacer(1)),options.expanded)component.addChild(new Text(styled,0,0));else{component.addChild(new VisualLinePreview({text:styled,maxVisualLines:OUTPUT_PREVIEW_LINES,keep:"start",formatHint:hidden=>`${theme.fg("muted",`... (${hidden} more lines,`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`}));let fullOutputPath=result.details?.fullOutputPath;fullOutputPath&&component.addChild(new Text(theme.fg("muted",`Full output: ${fullOutputPath}`),0,0))}return component}}}var LIST_MCP_RESOURCES_TOOL="list_mcp_resources",LIST_MCP_RESOURCE_TEMPLATES_TOOL="list_mcp_resource_templates";function isMcpAppResource(item){return(item.uri??item.uriTemplate??"").startsWith("ui://")||/;\s*profile\s*=\s*"?mcp-app"?/i.test(item.mimeType??"")}function listed(server,item){let{_meta,icons:_icons,...rest}=item;return{server,...rest}}var stringProperty=description=>({type:"string",description}),SERVER_FILTER=stringProperty("MCP server name. Omit to list every server with resources."),CURSOR=stringProperty("Opaque cursor from a previous call with the same server; omit for the first page."),LIST_PARAMETERS={type:"object",properties:{server:SERVER_FILTER,cursor:CURSOR},additionalProperties:!1},READ_PARAMETERS={type:"object",properties:{server:stringProperty("MCP server name exactly as configured. Must match the 'server' field returned by list_mcp_resources."),uri:stringProperty("Resource URI to read. Must be one of the URIs returned by list_mcp_resources.")},required:["server","uri"],additionalProperties:!1},optionalString={type:"string"},LISTING_ERRORS={type:"array",description:"Servers that could not be listed",items:{type:"object",properties:{server:{type:"string"},error:{type:"string"}},required:["server","error"]}},LIST_OUTPUT_SCHEMA={type:"object",properties:{server:optionalString,resources:{type:"array",items:{type:"object",properties:{server:{type:"string"},uri:{type:"string"},name:{type:"string"},title:optionalString,description:optionalString,mimeType:optionalString,size:{type:"number"}},required:["server","uri","name"]}},nextCursor:optionalString,errors:LISTING_ERRORS},required:["resources"]},LIST_TEMPLATES_OUTPUT_SCHEMA={type:"object",properties:{server:optionalString,resourceTemplates:{type:"array",items:{type:"object",properties:{server:{type:"string"},uriTemplate:{type:"string",description:"RFC 6570 URI template"},name:{type:"string"},title:optionalString,description:optionalString,mimeType:optionalString},required:["server","uriTemplate","name"]}},nextCursor:optionalString,errors:LISTING_ERRORS},required:["resourceTemplates"]},READ_OUTPUT_SCHEMA={type:"object",properties:{server:{type:"string"},uri:{type:"string"},contents:{type:"array",items:{anyOf:[{type:"object",properties:{uri:{type:"string"},mimeType:optionalString,text:{type:"string"}},required:["uri","text"]},{type:"object",properties:{uri:{type:"string"},mimeType:optionalString,blob:{type:"string",description:"base64"}},required:["uri","blob"]}]}}},required:["server","uri","contents"]};function stringArgument(params,key){let value=params?.[key];if(value!=null){if(typeof value!="string")throw new Error(`${key} must be a string`);return value.trim()||void 0}}function errorMessage(error){return error instanceof Error?error.message:String(error)}async function jsonResult(tool,server,payload){let{content,fullOutputPath}=await limitMcpContent([{type:"text",text:JSON.stringify(payload)}]);return{content,details:{server:server??"",tool,...fullOutputPath?{fullOutputPath}:{}},structuredContent:payload}}function createMcpResourceToolDefinitions(options){let readOnly={readOnlyHint:!0},findServer=name=>{let servers=options.servers(),server=servers.find(candidate=>candidate.name===name);if(server)return server;let available=servers.map(candidate=>candidate.name).join(", ");throw new Error(`MCP server "${name}" has no resources${available?`. Servers with resources: ${available}`:""}`)},list=async(params,signal,key,page,all)=>{let serverName=stringArgument(params,"server"),cursor=stringArgument(params,"cursor"),visible=item=>!isMcpAppResource(item);if(serverName){let server=findServer(serverName),result=await page(server,cursor,{signal,timeoutMs:server.timeoutMs});return{server:server.name,[key]:result.items.filter(visible).map(item=>listed(server.name,item)),...result.nextCursor===void 0?{}:{nextCursor:result.nextCursor}}}if(cursor)throw new Error("cursor can only be used when a server is specified");let servers=[...options.servers()].sort((a,b)=>a.name.localeCompare(b.name)),results=await Promise.allSettled(servers.map(server=>all(server,{signal,timeoutMs:server.timeoutMs}))),items=[],errors=[];return results.forEach((result,index)=>{let server=servers[index].name;result.status==="fulfilled"?items.push(...result.value.filter(visible).map(item=>listed(server,item))):errors.push({server,error:errorMessage(result.reason)})}),{[key]:items,...errors.length>0?{errors}:{}}},listResources={name:LIST_MCP_RESOURCES_TOOL,label:LIST_MCP_RESOURCES_TOOL,description:"Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.",parameters:LIST_PARAMETERS,outputSchema:LIST_OUTPUT_SCHEMA,exposure:toToolExposure(options.exposure),annotations:readOnly,async execute(_toolCallId,params,signal){let payload=await list(params,signal,"resources",async(server,cursor,requestOptions)=>{let result=await server.resourcesPage(cursor,requestOptions);return{items:result.resources,nextCursor:result.nextCursor}},(server,requestOptions)=>server.allResources(requestOptions));return jsonResult(LIST_MCP_RESOURCES_TOOL,stringArgument(params,"server"),payload)}},listTemplates={name:LIST_MCP_RESOURCE_TEMPLATES_TOOL,label:LIST_MCP_RESOURCE_TEMPLATES_TOOL,description:"Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.",parameters:LIST_PARAMETERS,outputSchema:LIST_TEMPLATES_OUTPUT_SCHEMA,exposure:toToolExposure(options.exposure),annotations:readOnly,async execute(_toolCallId,params,signal){let payload=await list(params,signal,"resourceTemplates",async(server,cursor,requestOptions)=>{let result=await server.resourceTemplatesPage(cursor,requestOptions);return{items:result.resourceTemplates,nextCursor:result.nextCursor}},(server,requestOptions)=>server.allResourceTemplates(requestOptions));return jsonResult(LIST_MCP_RESOURCE_TEMPLATES_TOOL,stringArgument(params,"server"),payload)}},readResource={name:READ_MCP_RESOURCE_TOOL,label:READ_MCP_RESOURCE_TOOL,description:"Read a specific resource from an MCP server given the server name and resource URI.",parameters:READ_PARAMETERS,outputSchema:READ_OUTPUT_SCHEMA,exposure:toToolExposure(options.exposure),annotations:readOnly,async execute(_toolCallId,params,signal){let serverName=stringArgument(params,"server"),uri=stringArgument(params,"uri");if(!serverName)throw new Error("server must be provided");if(!uri)throw new Error("uri must be provided");let server=findServer(serverName),result=await server.readResource(uri,{signal,timeoutMs:server.timeoutMs}),blocks=result.contents.flatMap(contents2=>[...result.contents.length>1?[{type:"text",text:`${contents2.uri}:`}]:[],{type:"resource",resource:contents2}]),converted=await toModelContent(server.name,blocks),{content,fullOutputPath}=await limitMcpContent(converted.length>0?converted:[{type:"text",text:`Resource ${uri} is empty.`}]),contents=result.contents.map(({_meta:_ignored,...rest})=>rest);return{content,details:{server:server.name,tool:READ_MCP_RESOURCE_TOOL,...fullOutputPath?{fullOutputPath}:{}},structuredContent:{server:server.name,uri,contents}}}};return[listResources,listTemplates,readResource]}export{operationSignal,raceWithAbortSignal,require_proper_lockfile,getConfigValueEnvVarNames,isCommandConfigValue,isConfigValueConfigured,resolveConfigValueOrThrow,resolveHeadersOrThrow,FileAuthStorageBackend,ReadOnlyAuthStorage,AuthStorage,readStoredCredential,mcpNamespace,getMcpToolExposure,validateMcpServerConfig,McpServerRegistry,JSON_RPC_ERROR_CODES,McpError,isObject,LATEST_PROTOCOL_VERSION,McpClient,StdioTransport,McpHttpError,McpAuthRequiredError,McpSessionExpiredError,StreamableHttpTransport,READ_MCP_RESOURCE_TOOL,createMcpToolName,createMcpToolDefinition,createMcpToolRenderers,LIST_MCP_RESOURCES_TOOL,LIST_MCP_RESOURCE_TEMPLATES_TOOL,isMcpAppResource,createMcpResourceToolDefinitions};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-
|
|
2
|
+
import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-PSQJVYXD.js";import{ProjectTrustStore,addMcpServerConfig,loadMcpConfig,openBrowser,removeMcpServerConfig}from"./chunk-6DBOMCBS.js";import{getMcpToolExposure,validateMcpServerConfig}from"./chunk-ZSQEXT6X.js";import"./chunk-UBHCV62G.js";import{APP_NAME,CONFIG_DIR_NAME,source_default}from"./chunk-AXOERKKW.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";import{existsSync}from"node:fs";import{join}from"node:path";import{createInterface}from"node:readline/promises";var HELP=`${source_default.bold("Usage:")}
|
|
3
3
|
${APP_NAME} mcp add <server> [options] -- <command> [args...]
|
|
4
4
|
${APP_NAME} mcp add <server> [options] --url <url>
|
|
5
5
|
${APP_NAME} mcp remove <server> [-l]
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{classifySystemOne,isRecord}from"./chunk-
|
|
2
|
+
import{classifySystemOne,isRecord}from"./chunk-C47CLQZK.js";import"./chunk-TEPMHNKQ.js";import"./chunk-LD2P6SFZ.js";import"./chunk-UTB4DTYQ.js";import"./chunk-KJUDFE6Y.js";import"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var LABEL="Cloudflare Workers AI";function cloudflareErrorMessage(errors){if(Array.isArray(errors)){let messages=errors.map(error=>isRecord(error)&&typeof error.message=="string"?error.message:void 0).filter(message=>message!==void 0);if(messages.length>0)return`${LABEL} error: ${messages.join("; ")}`}return`${LABEL} request failed`}var transport={api:"cloudflare-workers-ai-system-one",label:LABEL,url:model=>new URL("run",`${model.baseUrl.replace(/\/+$/u,"")}/`),payload:(model,request)=>({model:model.id,input:request}),output:body=>{if(!isRecord(body))throw new Error(`${LABEL} returned an unexpected response`);if(body.success===!1)throw new Error(cloudflareErrorMessage(body.errors));let result=body.result;if(!isRecord(result))throw new Error(`${LABEL} returned an unexpected response`);if("answers"in result)return result;if(result.state!=="Completed")throw new Error(`${LABEL} run did not complete (state: ${String(result.state)})`);if(!isRecord(result.result))throw new Error(`${LABEL} returned an unexpected response`);return result.result}},classify=(model,context,options)=>classifySystemOne(transport,model,context,options);export{classify};
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
1
|
import{parentPort,workerData}from"node:worker_threads";function createWasiShim(memoryAccessor){return{clock_time_get(clockId,_precision,resultPtr){let mem=memoryAccessor(),view=new DataView(mem.buffer);if(clockId===0||clockId===1){let timeNs=BigInt(Date.now())*1000000n;return view.setBigUint64(resultPtr,timeNs,!0),0}return 52},fd_write(fd,iovsPtr,iovsLen,nwrittenPtr){let mem=memoryAccessor(),view=new DataView(mem.buffer),bytes=new Uint8Array(mem.buffer),totalWritten=0;if(fd!==1&&fd!==2)return 8;for(let i=0;i<iovsLen;i++){let bufPtr=view.getUint32(iovsPtr+i*8,!0),bufLen=view.getUint32(iovsPtr+i*8+4,!0),chunk=bytes.slice(bufPtr,bufPtr+bufLen),text=new TextDecoder().decode(chunk);fd===1?typeof process<"u"&&process.stdout?process.stdout.write(text):console.log(text):typeof process<"u"&&process.stderr?process.stderr.write(text):console.error(text),totalWritten+=bufLen}return view.setUint32(nwrittenPtr,totalWritten,!0),0},fd_close(_fd){return 52},fd_fdstat_get(fd,statPtr){let mem=memoryAccessor(),view=new DataView(mem.buffer);return fd===1||fd===2?(view.setUint8(statPtr,2),view.setUint16(statPtr+2,0,!0),view.setBigUint64(statPtr+8,0n,!0),view.setBigUint64(statPtr+16,0n,!0),0):8},fd_seek(_fd,_offset,_whence,_resultPtr){return 52},random_get(bufPtr,bufLen){let mem=memoryAccessor(),bytes=new Uint8Array(mem.buffer,bufPtr,bufLen);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(bytes);else for(let i=0;i<bufLen;i++)bytes[i]=Math.floor(Math.random()*256);return 0}}}var decoder=new TextDecoder;function parseVersionString(memory,ptr){let mem=new Uint8Array(memory.buffer),end=ptr;for(;mem[end]!==0;)end++;if(end===ptr)return{};let str=decoder.decode(mem.slice(ptr,end)),result={};for(let line of str.split(`
|
|
3
2
|
`)){let eq=line.indexOf("=");eq>0&&(result[line.slice(0,eq)]=line.slice(eq+1))}return result}function extractExtensionVersions(ext,memory){let versionsFnName=`qjs_ext_${ext.name.replace(/-/g,"_")}_versions`,versionsFn=ext.instance.exports[versionsFnName];if(typeof versionsFn!="function")return;let ptr=versionsFn();if(ptr!==0)return parseVersionString(memory,ptr)}function readULEB128(bytes,offset){let result=0,shift=0;for(;offset.value<bytes.length;){let byte=bytes[offset.value++];if(result|=(byte&127)<<shift,(byte&128)===0)break;shift+=7}return result}function parseDylink(module){let sections=WebAssembly.Module.customSections(module,"dylink.0");if(sections.length===0)return null;let bytes=new Uint8Array(sections[0]),offset={value:0},info={memorySize:0,memoryAlignment:0,tableSize:0,tableAlignment:0,needed:[]};for(;offset.value<bytes.length;){let subsectionType=readULEB128(bytes,offset),subsectionSize=readULEB128(bytes,offset),subsectionEnd=offset.value+subsectionSize;if(subsectionType===1)info.memorySize=readULEB128(bytes,offset),info.memoryAlignment=readULEB128(bytes,offset),info.tableSize=readULEB128(bytes,offset),info.tableAlignment=readULEB128(bytes,offset);else if(subsectionType===2){let count=readULEB128(bytes,offset);for(let i=0;i<count;i++){let len=readULEB128(bytes,offset),name=new TextDecoder().decode(bytes.slice(offset.value,offset.value+len));offset.value+=len,info.needed.push(name)}}offset.value=subsectionEnd}return info}async function loadExtension(descriptor,mainExports,wasiBuiltins,wasiUserOverrides,memoryProxy,allocBase){let module;descriptor.wasm instanceof WebAssembly.Module?module=descriptor.wasm:module=await WebAssembly.compile(descriptor.wasm);let dylink=parseDylink(module);if(!dylink)throw new Error(`Extension "${descriptor.name}" is not a WASM shared library (missing dylink.0 section)`);let memory=mainExports.memory,table=mainExports.__indirect_function_table,stackPointer=mainExports.__stack_pointer,mallocFn=mainExports.malloc;if(!memory)throw new Error("Main module does not export memory");if(!table)throw new Error("Main module does not export __indirect_function_table");if(!mallocFn)throw new Error("Main module does not export malloc");let memoryBase,tableBase;if(allocBase)memoryBase=allocBase.memoryBase,tableBase=allocBase.tableBase;else if(dylink.memorySize>0){if(memoryBase=mallocFn(dylink.memorySize),memoryBase===0)throw new Error(`Failed to allocate ${dylink.memorySize} bytes for extension "${descriptor.name}"`);new Uint8Array(memory.buffer,memoryBase,dylink.memorySize).fill(0)}else memoryBase=0;allocBase?(tableBase=allocBase.tableBase,tableBase+dylink.tableSize>table.length&&table.grow(tableBase+dylink.tableSize-table.length)):(tableBase=table.length,dylink.tableSize>0&&table.grow(dylink.tableSize));let extImports=WebAssembly.Module.imports(module),importObj={env:{},"GOT.mem":{},"GOT.func":{}};if(extImports.some(imp=>imp.module==="wasi_snapshot_preview1")){let extWasi=descriptor.wasi&&memoryProxy?descriptor.wasi(memoryProxy):void 0;importObj.wasi_snapshot_preview1={...wasiBuiltins,...extWasi,...wasiUserOverrides}}let extExportNames=new Set(WebAssembly.Module.exports(module).filter(e=>e.kind==="function").map(e=>e.name)),unresolvedFuncs=new Set;for(let imp of extImports)if(imp.module==="env"){if(imp.name==="memory"&&imp.kind==="memory")importObj.env.memory=memory;else if(imp.name==="__indirect_function_table"&&imp.kind==="table")importObj.env.__indirect_function_table=table;else if(imp.name==="__memory_base"&&imp.kind==="global")importObj.env.__memory_base=new WebAssembly.Global({value:"i32",mutable:!1},memoryBase);else if(imp.name==="__table_base"&&imp.kind==="global")importObj.env.__table_base=new WebAssembly.Global({value:"i32",mutable:!1},tableBase);else if(imp.name==="__stack_pointer"&&imp.kind==="global")importObj.env.__stack_pointer=stackPointer;else if(imp.kind==="function"){let resolved=mainExports[imp.name];resolved&&typeof resolved=="function"?importObj.env[imp.name]=resolved:(unresolvedFuncs.add(imp.name),importObj.env[imp.name]=()=>{throw new Error(`Extension "${descriptor.name}" called unresolved symbol: env.${imp.name}`)})}else if(imp.kind==="global"){let resolved=mainExports[imp.name];resolved instanceof WebAssembly.Global?importObj.env[imp.name]=resolved:importObj.env[imp.name]=new WebAssembly.Global({value:"i32",mutable:!0},0)}}else if(imp.module==="GOT.mem"&&imp.kind==="global")importObj["GOT.mem"][imp.name]=new WebAssembly.Global({value:"i32",mutable:!0},0);else if(imp.module==="GOT.func"&&imp.kind==="global"){let resolved=mainExports[imp.name];if(resolved&&typeof resolved=="function"){let idx=table.length;table.grow(1),table.set(idx,resolved),importObj["GOT.func"][imp.name]=new WebAssembly.Global({value:"i32",mutable:!0},idx)}else importObj["GOT.func"][imp.name]=new WebAssembly.Global({value:"i32",mutable:!0},0)}let selfResolvable=[...unresolvedFuncs].filter(name=>extExportNames.has(name)),wrappers={};for(let name of selfResolvable){let wrapper={target:null};wrappers[name]=wrapper,importObj.env[name]=(...args)=>{if(!wrapper.target)throw new Error(`Extension "${descriptor.name}" called unresolved symbol during init: env.${name}`);return wrapper.target(...args)}}let instance=await WebAssembly.instantiate(module,importObj),extExports=instance.exports;for(let name of selfResolvable){let selfExport=extExports[name];typeof selfExport=="function"&&(wrappers[name].target=selfExport)}typeof extExports.__wasm_apply_data_relocs=="function"&&extExports.__wasm_apply_data_relocs(),typeof extExports.__wasm_call_ctors=="function"&&extExports.__wasm_call_ctors();let initFn=descriptor.initFn??`qjs_ext_${descriptor.name.replace(/-/g,"_")}_init`,ext={name:descriptor.name,module,instance,dylink,memoryBase,tableBase,initFn};return ext.versions=extractExtensionVersions(ext,memory),ext}function initExtension(ext,mainExports){let initFunc=ext.instance.exports[ext.initFn];if(typeof initFunc!="function")throw new Error(`Extension "${ext.name}" does not export init function "${ext.initFn}"`);let ctxPtr=mainExports.qjs_get_context_ptr(),rtPtr=mainExports.qjs_get_runtime_ptr(),result=initFunc(ctxPtr,rtPtr);if(result!==0)throw new Error(`Extension "${ext.name}" init function returned error code ${result}`)}async function restoreExtensions(descriptors,extensionMeta,mainExports,wasiBuiltins,wasiUserOverrides,memoryProxy){let loaded=[];for(let meta of extensionMeta){let descriptor=descriptors.find(d=>d.name===meta.name);if(!descriptor)throw new Error(`Extension "${meta.name}" required by snapshot but not provided`);let ext=await loadExtension(descriptor,mainExports,wasiBuiltins,wasiUserOverrides,memoryProxy,{memoryBase:meta.memoryBase,tableBase:meta.tableBase});ext.initFn=meta.initFn,loaded.push(ext)}return loaded}var VERSION="3.6.2";var __addDisposableResource=function(env,value,async){if(value!=null){if(typeof value!="object"&&typeof value!="function")throw new TypeError("Object expected.");var dispose,inner;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose],async&&(inner=dispose)}if(typeof dispose!="function")throw new TypeError("Object not disposable.");inner&&(dispose=function(){try{inner.call(this)}catch(e){return Promise.reject(e)}}),env.stack.push({value,dispose,async})}else async&&env.stack.push({async:!0});return value},__disposeResources=(function(SuppressedError2){return function(env){function fail(e){env.error=env.hasError?new SuppressedError2(e,env.error,"An error was suppressed during disposal."):e,env.hasError=!0}var r,s=0;function next(){for(;r=env.stack.pop();)try{if(!r.async&&s===1)return s=0,env.stack.push(r),Promise.resolve().then(next);if(r.dispose){var result=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(result).then(next,function(e){return fail(e),next()})}else s|=1}catch(e){fail(e)}if(s===1)return env.hasError?Promise.reject(env.error):Promise.resolve();if(env.hasError)throw env.error}return next()}})(typeof SuppressedError=="function"?SuppressedError:function(error,suppressed,message){var e=new Error(message);return e.name="SuppressedError",e.error=error,e.suppressed=suppressed,e}),MAX_STACK_SIZE=512*1024;var SNAPSHOT_MAGIC=1363825491,SNAPSHOT_VERSION=2,SNAPSHOT_HEADER_SIZE=24,QuickJS=class _QuickJS{exports;module;instance;encoder=new TextEncoder;decoder=new TextDecoder;disposed=!1;hostCallbacks=new Map;nextInternalId=1;interruptHandler=null;unhandledRejectionHandler=null;moduleNormalizeHandler=null;moduleLoadHandler=null;timezoneOffsetHandler=null;_global=null;_versions=null;_undefined=null;_null=null;_true=null;_false=null;_ownedHandles=new Set;_activeScope=null;loadedExtensions=[];constructor(module){this.module=module,this.instance=null,this.exports=null}setInstance(instance){this.instance=instance,this.exports=instance.exports}get versions(){if(this.assertNotDisposed(),!this._versions){let result={"quickjs-wasi":VERSION,quickjs:this.readCString(this.exports.qjs_get_quickjs_version())};for(let ext of this.loadedExtensions)ext.versions&&Object.assign(result,ext.versions);this._versions=result}return this._versions}get global(){return this._global||(this._global=new JSValueHandle(this,this.exports.qjs_get_global(),!0)),this._global}get undefined(){return this._undefined||(this._undefined=new JSValueHandle(this,this.exports.qjs_get_undefined(),!0)),this._undefined}get null(){return this._null||(this._null=new JSValueHandle(this,this.exports.qjs_get_null(),!0)),this._null}get true(){return this._true||(this._true=new JSValueHandle(this,this.exports.qjs_get_true(),!0)),this._true}get false(){return this._false||(this._false=new JSValueHandle(this,this.exports.qjs_get_false(),!0)),this._false}static async create(options){let opts=_QuickJS.normalizeOptions(options),module=await _QuickJS.resolveModule(opts.wasm),vm=new _QuickJS(module),{instance,wasiBuiltins,wasiUserOverrides,memoryProxy}=await _QuickJS.instantiate(module,vm,opts.wasi);if(vm.setInstance(instance),vm.exports._initialize(),(opts.intrinsics!==void 0?vm.exports.qjs_init2(opts.intrinsics):vm.exports.qjs_init())!==0)throw new Error("Failed to initialize QuickJS runtime");if(opts.extensions){let mainExports=instance.exports;for(let desc of opts.extensions){let ext=await loadExtension(desc,mainExports,wasiBuiltins,wasiUserOverrides,memoryProxy);vm.loadedExtensions.push(ext),initExtension(ext,mainExports)}}return _QuickJS.applyLimits(vm,opts),vm}static async restore(snapshot,options){let opts=_QuickJS.normalizeOptions(options),module=await _QuickJS.resolveModule(opts.wasm),vm=new _QuickJS(module),{instance,wasiBuiltins,wasiUserOverrides,memoryProxy}=await _QuickJS.instantiate(module,vm,opts.wasi);vm.setInstance(instance);let mainExports=instance.exports,exportedMemory=vm.exports.memory,currentPages=exportedMemory.buffer.byteLength/65536,neededPages=Math.ceil(snapshot.memory.byteLength/65536);if(neededPages>currentPages&&exportedMemory.grow(neededPages-currentPages),snapshot.extensions.length>0){let descriptors=opts.extensions??[];vm.loadedExtensions=await restoreExtensions(descriptors,snapshot.extensions,mainExports,wasiBuiltins,wasiUserOverrides,memoryProxy)}return new Uint8Array(exportedMemory.buffer).set(snapshot.memory),vm.exports.qjs_set_runtime_and_context(snapshot.runtimePtr,snapshot.contextPtr),vm.exports.__stack_pointer.value=snapshot.stackPointer,_QuickJS.applyLimits(vm,opts),vm}static serializeSnapshot(snapshot){let textEncoder=new TextEncoder,extMetaSize=4,extEncodedNames=[],extEncodedInitFns=[];for(let ext of snapshot.extensions){let nameBytes=textEncoder.encode(ext.name),initFnBytes=textEncoder.encode(ext.initFn);extEncodedNames.push(nameBytes),extEncodedInitFns.push(initFnBytes),extMetaSize+=4+nameBytes.length+4+4+4+initFnBytes.length}let totalSize=SNAPSHOT_HEADER_SIZE+extMetaSize+snapshot.memory.byteLength,buffer=new ArrayBuffer(totalSize),view=new DataView(buffer),bytes=new Uint8Array(buffer);view.setUint32(0,SNAPSHOT_MAGIC,!1),view.setUint8(4,SNAPSHOT_VERSION),view.setUint32(8,snapshot.memory.byteLength,!0),view.setUint32(12,snapshot.stackPointer,!0),view.setUint32(16,snapshot.runtimePtr,!0),view.setUint32(20,snapshot.contextPtr,!0);let offset=SNAPSHOT_HEADER_SIZE;view.setUint32(offset,snapshot.extensions.length,!0),offset+=4;for(let i=0;i<snapshot.extensions.length;i++){let ext=snapshot.extensions[i],nameBytes=extEncodedNames[i],initFnBytes=extEncodedInitFns[i];view.setUint32(offset,nameBytes.length,!0),offset+=4,bytes.set(nameBytes,offset),offset+=nameBytes.length,view.setUint32(offset,ext.memoryBase,!0),offset+=4,view.setUint32(offset,ext.tableBase,!0),offset+=4,view.setUint32(offset,initFnBytes.length,!0),offset+=4,bytes.set(initFnBytes,offset),offset+=initFnBytes.length}return bytes.set(snapshot.memory,offset),bytes}static deserializeSnapshot(data){if(data.length<SNAPSHOT_HEADER_SIZE)throw new Error("Invalid snapshot: too small");let view=new DataView(data.buffer,data.byteOffset,data.byteLength),magic=view.getUint32(0,!1);if(magic!==SNAPSHOT_MAGIC)throw new Error(`Invalid snapshot: bad magic (expected 0x${SNAPSHOT_MAGIC.toString(16)}, got 0x${magic.toString(16)})`);let version=view.getUint8(4);if(version!==SNAPSHOT_VERSION&&version!==1)throw new Error(`Unsupported snapshot version: ${version} (expected ${SNAPSHOT_VERSION})`);let memorySize=view.getUint32(8,!0),stackPointer=view.getUint32(12,!0),runtimePtr=view.getUint32(16,!0),contextPtr=view.getUint32(20,!0),extensions=[],memoryOffset=SNAPSHOT_HEADER_SIZE;if(version>=2){let extCount=view.getUint32(24,!0),offset=28,textDecoder=new TextDecoder;for(let i=0;i<extCount;i++){let nameLen=view.getUint32(offset,!0);offset+=4;let name=textDecoder.decode(data.slice(offset,offset+nameLen));offset+=nameLen;let memBase=view.getUint32(offset,!0);offset+=4;let tblBase=view.getUint32(offset,!0);offset+=4;let initFnLen=view.getUint32(offset,!0);offset+=4;let initFn=textDecoder.decode(data.slice(offset,offset+initFnLen));offset+=initFnLen,extensions.push({name,memoryBase:memBase,tableBase:tblBase,initFn})}memoryOffset=offset}let expectedSize=memoryOffset+memorySize;if(data.length<expectedSize)throw new Error(`Invalid snapshot: expected ${expectedSize} bytes, got ${data.length}`);return{memory:data.slice(memoryOffset,memoryOffset+memorySize),stackPointer,runtimePtr,contextPtr,extensions}}static normalizeOptions(options){if(!options)return{wasm:void 0};if(options instanceof WebAssembly.Module)return{wasm:options};if(typeof options=="object"&&("wasm"in options||"wasi"in options||"memoryLimit"in options||"maxStackSize"in options||"interruptHandler"in options||"onUnhandledRejection"in options||"moduleLoader"in options||"intrinsics"in options||"extensions"in options||"timezoneOffset"in options)){let opts=options;if(opts.maxStackSize!==void 0&&(!Number.isInteger(opts.maxStackSize)||opts.maxStackSize<0||opts.maxStackSize>MAX_STACK_SIZE))throw new RangeError(`maxStackSize must be an integer between 0 and ${MAX_STACK_SIZE}`);return opts}return{wasm:options}}static applyLimits(vm,opts){opts.memoryLimit!==void 0&&vm.exports.qjs_set_memory_limit(opts.memoryLimit),opts.maxStackSize!==void 0&&vm.exports.qjs_set_max_stack_size(opts.maxStackSize),opts.interruptHandler&&(vm.interruptHandler=opts.interruptHandler,vm.exports.qjs_set_interrupt_handler(1)),opts.onUnhandledRejection&&(vm.unhandledRejectionHandler=opts.onUnhandledRejection,vm.exports.qjs_set_promise_rejection_handler(1)),opts.moduleLoader&&(vm.moduleLoadHandler=opts.moduleLoader.load,vm.moduleNormalizeHandler=opts.moduleLoader.normalize??null,vm.exports.qjs_set_module_loader(1));let tz=opts.timezoneOffset;if(typeof tz=="function")vm.timezoneOffsetHandler=timeSecs=>-tz(timeSecs)*60;else if(typeof tz=="number"){let offsetSecs=-tz*60;vm.timezoneOffsetHandler=()=>offsetSecs}else vm.timezoneOffsetHandler=timeSecs=>-new Date(timeSecs*1e3).getTimezoneOffset()*60}static async resolveModule(wasmInput){if(wasmInput instanceof WebAssembly.Module)return wasmInput;if(wasmInput)return WebAssembly.compile(wasmInput);throw new TypeError("QuickJS: `wasm` option is required. Provide WASM bytes or a compiled `WebAssembly.Module`. The binary is shipped at `quickjs-wasi/quickjs.wasm` and can be loaded via your environment's preferred mechanism (e.g. `fetch()`, `node:fs/promises`, or a bundler import like Vite's `?url`).")}static async instantiate(module,vm,wasiOptions){let memory=null,memoryProxy=new Proxy({},{get(_target,prop){return memory[prop]}}),wasiBuiltins=createWasiShim(()=>memory),wasiUserOverrides=wasiOptions?wasiOptions(memoryProxy):void 0,wasiShim={...wasiBuiltins,...wasiUserOverrides},hostCall=(namePtr,nameLen,thisPtr,argc,argvPtr)=>vm.handleHostCall(namePtr,nameLen,thisPtr,argc,argvPtr),hostInterrupt=()=>vm.interruptHandler&&vm.interruptHandler()?1:0,hostPromiseRejection=(promisePtr,reasonPtr,isHandled)=>{if(!vm.unhandledRejectionHandler){vm.exports.qjs_free_value(promisePtr),vm.exports.qjs_free_value(reasonPtr);return}let promise=new JSValueHandle(vm,promisePtr),reason=new JSValueHandle(vm,reasonPtr);try{vm.unhandledRejectionHandler(promise,reason,isHandled!==0)}finally{promise.dispose(),reason.dispose()}},throwIntoContext=err=>{let errHandle=vm.newError(err instanceof Error?err:String(err));vm.exports.qjs_throw(errHandle.ptr),errHandle.dispose()},assertSyncString=(value,callbackName)=>{if(typeof value=="string")return value;let got=value!==null&&typeof value=="object"&&typeof value.then=="function"?"a Promise":`type ${typeof value}`;throw new TypeError(`moduleLoader.${callbackName} must synchronously return a string (got ${got}). Async module loading is not supported. Pre-fetch module sources instead (see the "ES Modules" section of the quickjs-wasi README).`)},hostModuleNormalize=(baseNamePtr,namePtr)=>{if(!vm.moduleNormalizeHandler){let name=vm.readCString(namePtr);return vm.writeString(name).ptr}let baseName=vm.readCString(baseNamePtr),specifier=vm.readCString(namePtr);try{let normalized=assertSyncString(vm.moduleNormalizeHandler(baseName,specifier),"normalize");return vm.writeString(normalized).ptr}catch(err){return throwIntoContext(err),0}},hostModuleLoad=(namePtr,outLenPtr)=>{if(!vm.moduleLoadHandler)return 0;let name=vm.readCString(namePtr);try{let source=assertSyncString(vm.moduleLoadHandler(name),"load"),{ptr,len}=vm.writeString(source);return new Uint32Array(vm.exports.memory.buffer,outLenPtr,1)[0]=len,ptr}catch(err){return throwIntoContext(err),0}},hostGetTimezoneOffset=(hi,lo)=>{let timeSecs=Number(BigInt(hi)<<32n|BigInt(lo>>>0));return vm.timezoneOffsetHandler?vm.timezoneOffsetHandler(timeSecs):0},instance=await WebAssembly.instantiate(module,{env:{host_call:hostCall,host_interrupt:hostInterrupt,host_promise_rejection:hostPromiseRejection,host_module_normalize:hostModuleNormalize,host_module_load:hostModuleLoad,host_get_timezone_offset:hostGetTimezoneOffset},wasi_snapshot_preview1:wasiShim});return memory=instance.exports.memory,{instance,wasiBuiltins,wasiUserOverrides,memoryProxy}}handleHostCall(namePtr,nameLen,thisPtr,argc,argvPtr){let name=this.decoder.decode(new Uint8Array(this.exports.memory.buffer,namePtr,nameLen)),callback=this.hostCallbacks.get(name);if(!callback){let errHandle=this.newError(`Host callback "${name}" is not registered: it was unregistered, its ephemeral function handle was disposed, or it was never re-registered after a snapshot restore.`);return this.exports.qjs_throw(errHandle.ptr),errHandle.dispose(),0}let thisHandle=new JSValueHandle(this,thisPtr,!1,!0),args=[];if(argc>0&&argvPtr!==0){let view=new DataView(this.exports.memory.buffer);for(let i=0;i<argc;i++){let argPtr=view.getUint32(argvPtr+i*4,!0);args.push(new JSValueHandle(this,argPtr,!1,!0))}}try{let result=callback.call(thisHandle,...args);return this.exports.qjs_dup_value(result.ptr)}catch(err){let errHandle=this.newError(err instanceof Error?err:String(err));return this.exports.qjs_throw(errHandle.ptr),errHandle.dispose(),0}}writeString(str){let encoded=encodeWtf8(str),ptr=this.exports.wasm_malloc(encoded.length+1);if(ptr===0)throw new Error("wasm_malloc failed");let mem=new Uint8Array(this.exports.memory.buffer);return mem.set(encoded,ptr),mem[ptr+encoded.length]=0,{ptr,len:encoded.length}}readCString(ptr){let mem=new Uint8Array(this.exports.memory.buffer),end=ptr;for(;mem[end]!==0;)end++;return this.decoder.decode(mem.slice(ptr,end))}throwIfException(result){if(this.exports.qjs_is_exception(result.ptr)!==0){let exc=this.getException();throw result.dispose(),this._ownedHandles.add(exc),new JSException(exc)}return result}evalCode(code,filename="<eval>",flags=0){this.assertNotDisposed();let codeStr=this.writeString(code),fnStr=this.writeString(filename),resultPtr=this.exports.qjs_eval(codeStr.ptr,codeStr.len,fnStr.ptr,flags);return this.exports.wasm_free(codeStr.ptr),this.exports.wasm_free(fnStr.ptr),this.throwIfException(new JSValueHandle(this,resultPtr))}compile(code,filename="<compile>",evalFlags=0,compileFlags=0){this.assertNotDisposed();let codeStr=this.writeString(code),fnStr=this.writeString(filename),outLenPtr=this.exports.wasm_malloc(4),bufPtr=this.exports.qjs_compile(codeStr.ptr,codeStr.len,fnStr.ptr,evalFlags,compileFlags,outLenPtr);if(this.exports.wasm_free(codeStr.ptr),this.exports.wasm_free(fnStr.ptr),bufPtr===0){this.exports.wasm_free(outLenPtr);let exc=this.getException();throw new Error(`Compilation error: ${exc.toString()}`)}let outLen=new Uint32Array(this.exports.memory.buffer,outLenPtr,1)[0];this.exports.wasm_free(outLenPtr);let bytecode=new Uint8Array(this.exports.memory.buffer,bufPtr,outLen).slice();return this.exports.wasm_free(bufPtr),bytecode}evalBytecode(bytecode){this.assertNotDisposed();let bufPtr=this.exports.wasm_malloc(bytecode.byteLength);new Uint8Array(this.exports.memory.buffer,bufPtr,bytecode.byteLength).set(bytecode);let resultPtr=this.exports.qjs_eval_bytecode(bufPtr,bytecode.byteLength);return this.exports.wasm_free(bufPtr),this.throwIfException(new JSValueHandle(this,resultPtr))}executePendingJobs(){this.assertNotDisposed();let count=0;for(;this.exports.qjs_is_job_pending();){if(this.exports.qjs_execute_pending_job()<0){let exc=this.getException();throw new Error(`Job execution error: ${exc.toString()}`)}count++}return count}runGC(){this.assertNotDisposed(),this.exports.qjs_run_gc()}get gcThreshold(){return this.assertNotDisposed(),this.exports.qjs_get_gc_threshold()}set gcThreshold(threshold){this.assertNotDisposed(),this.exports.qjs_set_gc_threshold(threshold)}getMemoryUsage(){this.assertNotDisposed();let bufPtr=this.exports.wasm_malloc(208);this.exports.qjs_compute_memory_usage(bufPtr);let view=new BigInt64Array(this.exports.memory.buffer,bufPtr,26),result={mallocSize:Number(view[0]),mallocLimit:Number(view[1]),memoryUsedSize:Number(view[2]),mallocCount:Number(view[3]),memoryUsedCount:Number(view[4]),atomCount:Number(view[5]),atomSize:Number(view[6]),strCount:Number(view[7]),strSize:Number(view[8]),objCount:Number(view[9]),objSize:Number(view[10]),propCount:Number(view[11]),propSize:Number(view[12]),shapeCount:Number(view[13]),shapeSize:Number(view[14]),jsFuncCount:Number(view[15]),jsFuncSize:Number(view[16]),jsFuncCodeSize:Number(view[17]),jsFuncPc2lineCount:Number(view[18]),jsFuncPc2lineSize:Number(view[19]),cFuncCount:Number(view[20]),arrayCount:Number(view[21]),fastArrayCount:Number(view[22]),fastArrayElements:Number(view[23]),binaryObjectCount:Number(view[24]),binaryObjectSize:Number(view[25])};return this.exports.wasm_free(bufPtr),result}getGlobal(){return this.assertNotDisposed(),new JSValueHandle(this,this.exports.qjs_get_global())}newString(str){this.assertNotDisposed();let{ptr,len}=this.writeString(str),resultPtr=this.exports.qjs_new_string(ptr,len);return this.exports.wasm_free(ptr),new JSValueHandle(this,resultPtr)}newNumber(num){return this.assertNotDisposed(),new JSValueHandle(this,this.exports.qjs_new_number(num))}newBigInt(val){this.assertNotDisposed();let lo=Number(val&0xffffffffn),hi=Number(val>>32n&0xffffffffn);return new JSValueHandle(this,this.exports.qjs_new_big_int64(lo,hi))}newObject(){return this.assertNotDisposed(),new JSValueHandle(this,this.exports.qjs_new_object())}newArray(){return this.assertNotDisposed(),new JSValueHandle(this,this.exports.qjs_new_array())}newSymbolFor(description){this.assertNotDisposed();let{ptr,len}=this.writeString(description),result=new JSValueHandle(this,this.exports.qjs_new_symbol(ptr,len,1));return this.exports.wasm_free(ptr),result}newArrayBuffer(data){this.assertNotDisposed();let bytes=data instanceof ArrayBuffer?new Uint8Array(data):data,ptr=this.exports.wasm_malloc(bytes.length);if(ptr===0)throw new Error("wasm_malloc failed");new Uint8Array(this.exports.memory.buffer).set(bytes,ptr);let result=new JSValueHandle(this,this.exports.qjs_new_array_buffer(ptr,bytes.length));return this.exports.wasm_free(ptr),result}newUint8Array(data){this.assertNotDisposed();let ptr=this.exports.wasm_malloc(data.length);if(ptr===0)throw new Error("wasm_malloc failed");new Uint8Array(this.exports.memory.buffer).set(data,ptr);let result=new JSValueHandle(this,this.exports.qjs_new_uint8_array(ptr,data.length));return this.exports.wasm_free(ptr),result}getUndefined(){return this.assertNotDisposed(),new JSValueHandle(this,this.exports.qjs_get_undefined())}getNull(){return this.assertNotDisposed(),new JSValueHandle(this,this.exports.qjs_get_null())}getTrue(){return this.assertNotDisposed(),new JSValueHandle(this,this.exports.qjs_get_true())}getFalse(){return this.assertNotDisposed(),new JSValueHandle(this,this.exports.qjs_get_false())}newFunction(name,fn){if(this.assertNotDisposed(),this.hostCallbacks.has(name))throw new Error(`Host callback with name "${name}" is already registered`);this.hostCallbacks.set(name,fn);let{ptr:namePtr,len:nameLen}=this.writeString(name),resultPtr=this.exports.qjs_new_host_function(namePtr,nameLen,0);return this.exports.wasm_free(namePtr),new JSValueHandle(this,resultPtr)}withScope(fn){this.assertNotDisposed();let enclosing=this._activeScope,tracked=new Set;this._activeScope=tracked;let scope={escape:handle=>(tracked.delete(handle),enclosing?.add(handle),handle)};try{return fn(scope)}finally{this._activeScope=enclosing;for(let handle of tracked)handle.dispose()}}exportHandle(handle){if(this.assertNotDisposed(),handle.vm!==this)throw new Error("exportHandle: handle belongs to a different VM");if(handle.disposed)throw new Error("exportHandle: handle is disposed");if(handle._isBorrowed)throw new Error("exportHandle: cannot export a borrowed handle (host-callback this/argument); its box is freed when the callback returns. dup() it and export the duplicate.");return handle.ptr}importHandle(token){if(this.assertNotDisposed(),!Number.isInteger(token)||token<=0||token>=this.exports.memory.buffer.byteLength)throw new Error(`importHandle: invalid token ${token}`);return new JSValueHandle(this,this.exports.qjs_dup_value(token))}newEphemeralFunction(fn){this.assertNotDisposed();let name=`__ephemeral:${this.nextInternalId++}`;this.hostCallbacks.set(name,fn);let{ptr:namePtr,len:nameLen}=this.writeString(name),resultPtr=this.exports.qjs_new_host_function(namePtr,nameLen,0);this.exports.wasm_free(namePtr);let handle=new JSValueHandle(this,resultPtr);return handle._onDispose=()=>{this.hostCallbacks.delete(name)},handle}unregisterHostCallback(name){return this.hostCallbacks.delete(name)}newInternalFunction(name,fn){this.hostCallbacks.set(name,fn);let{ptr:namePtr,len:nameLen}=this.writeString(name),resultPtr=this.exports.qjs_new_host_function(namePtr,nameLen,0);return this.exports.wasm_free(namePtr),new JSValueHandle(this,resultPtr)}newPromise(){this.assertNotDisposed();let resolveOutPtr=this.exports.wasm_malloc(4),rejectOutPtr=this.exports.wasm_malloc(4),promisePtr=this.exports.qjs_new_promise(resolveOutPtr,rejectOutPtr),view=new DataView(this.exports.memory.buffer),resolvePtr=view.getUint32(resolveOutPtr,!0),rejectPtr=view.getUint32(rejectOutPtr,!0);this.exports.wasm_free(resolveOutPtr),this.exports.wasm_free(rejectOutPtr);let promiseHandle=new JSValueHandle(this,promisePtr),resolveHandle=new JSValueHandle(this,resolvePtr),rejectHandle=new JSValueHandle(this,rejectPtr),vm=this;vm._ownedHandles.add(resolveHandle),vm._ownedHandles.add(rejectHandle);let _settled=null;return{handle:promiseHandle,get settled(){if(!_settled){let settledResolve;_settled=new Promise(res=>{settledResolve=res});let settleName=`__settle:${vm.nextInternalId++}`,onSettleFn=vm.newInternalFunction(settleName,()=>(settledResolve(),vm.hostCallbacks.delete(settleName),vm.undefined));vm.promiseThenRaw(promiseHandle,onSettleFn,onSettleFn).dispose(),onSettleFn.dispose()}return _settled},resolve(value){vm.callFunctionRaw(resolveHandle,vm.undefined,value).dispose(),vm._ownedHandles.delete(resolveHandle),resolveHandle.dispose()},reject(value){vm.callFunctionRaw(rejectHandle,vm.undefined,value).dispose(),vm._ownedHandles.delete(rejectHandle),rejectHandle.dispose()}}}resolvePromise(promiseHandle){if(this.assertNotDisposed(),!this.exports.qjs_is_promise(promiseHandle.ptr))return Promise.resolve({value:promiseHandle.dup()});let state=this.exports.qjs_promise_state(promiseHandle.ptr);return state===1?Promise.resolve({value:new JSValueHandle(this,this.exports.qjs_promise_result(promiseHandle.ptr))}):state===2?Promise.resolve({error:new JSValueHandle(this,this.exports.qjs_promise_result(promiseHandle.ptr))}):new Promise(hostResolve=>{let id=this.nextInternalId++,fulfilledName=`__onFulfilled:${id}`,rejectedName=`__onRejected:${id}`,onFulfilled=this.newInternalFunction(fulfilledName,(...args)=>{let val=args[0]?.dup()??this.undefined;return this.hostCallbacks.delete(fulfilledName),this.hostCallbacks.delete(rejectedName),hostResolve({value:val}),this.undefined}),onRejected=this.newInternalFunction(rejectedName,(...args)=>{let val=args[0]?.dup()??this.undefined;return this.hostCallbacks.delete(fulfilledName),this.hostCallbacks.delete(rejectedName),hostResolve({error:val}),this.undefined});this.promiseThenRaw(promiseHandle,onFulfilled,onRejected).dispose(),onFulfilled.dispose(),onRejected.dispose()})}promiseThenRaw(promise,onFulfilled,onRejected){return new JSValueHandle(this,this.exports.qjs_promise_then(promise.ptr,onFulfilled.ptr,onRejected.ptr))}markPromiseHandled(promise){this.assertNotDisposed(),this.exports.qjs_promise_mark_as_handled(promise.ptr)}callFunction(func,thisVal,...args){return this.throwIfException(this.callFunctionRaw(func,thisVal,...args))}construct(ctor,...args){this.assertNotDisposed();let argc=args.length,argvPtr=0;if(argc>0){argvPtr=this.exports.wasm_malloc(argc*4);let view=new DataView(this.exports.memory.buffer);for(let i=0;i<argc;i++)view.setUint32(argvPtr+i*4,args[i].ptr,!0)}let resultPtr=this.exports.qjs_call_constructor(ctor.ptr,argc,argvPtr);return argvPtr&&this.exports.wasm_free(argvPtr),this.throwIfException(new JSValueHandle(this,resultPtr))}callFunctionRaw(func,thisVal,...args){this.assertNotDisposed();let argc=args.length,argvPtr=0;if(argc>0){argvPtr=this.exports.wasm_malloc(argc*4);let view=new DataView(this.exports.memory.buffer);for(let i=0;i<argc;i++)view.setUint32(argvPtr+i*4,args[i].ptr,!0)}let resultPtr=this.exports.qjs_call(func.ptr,thisVal.ptr,argc,argvPtr);return argvPtr&&this.exports.wasm_free(argvPtr),new JSValueHandle(this,resultPtr)}setProp(obj,key,value){if(this.assertNotDisposed(),typeof key=="string"){let{ptr:namePtr}=this.writeString(key);this.exports.qjs_set_prop_string(obj.ptr,namePtr,value.ptr),this.exports.wasm_free(namePtr)}else this.exports.qjs_set_prop_value(obj.ptr,key.ptr,value.ptr)}defineProp(obj,key,value,descriptor){this.assertNotDisposed();let flags=0;if(descriptor?.configurable&&(flags|=1),descriptor?.writable&&(flags|=2),descriptor?.enumerable&&(flags|=4),typeof key=="string"){let{ptr:namePtr}=this.writeString(key);this.exports.qjs_define_prop_string(obj.ptr,namePtr,value.ptr,flags),this.exports.wasm_free(namePtr)}else this.exports.qjs_define_prop_value(obj.ptr,key.ptr,value.ptr,flags)}getProp(obj,key){return this.assertNotDisposed(),new JSValueHandle(this,this.exports.qjs_get_prop_value(obj.ptr,key.ptr))}getException(){return this.assertNotDisposed(),new JSValueHandle(this,this.exports.qjs_get_exception())}newError(messageOrError){this.assertNotDisposed();let errPtr=this.exports.qjs_new_error(),errHandle=new JSValueHandle(this,errPtr);if(typeof messageOrError=="string"){let msgHandle=this.newString(messageOrError);errHandle.setProp("message",msgHandle),msgHandle.dispose()}else{let msgHandle=this.newString(messageOrError.message);if(errHandle.setProp("message",msgHandle),msgHandle.dispose(),messageOrError.name){let nameHandle=this.newString(messageOrError.name);errHandle.setProp("name",nameHandle),nameHandle.dispose()}if(messageOrError.stack){let stackHandle=this.newString(messageOrError.stack);errHandle.setProp("stack",stackHandle),stackHandle.dispose()}}return errHandle}typeof(handle){this.assertNotDisposed();let e=this.exports;return e.qjs_is_undefined(handle.ptr)?"undefined":e.qjs_is_null(handle.ptr)?"object":e.qjs_is_bool(handle.ptr)?"boolean":e.qjs_is_number(handle.ptr)?"number":e.qjs_is_big_int(handle.ptr)?"bigint":e.qjs_is_string(handle.ptr)?"string":e.qjs_is_symbol(handle.ptr)?"symbol":e.qjs_is_function(handle.ptr)?"function":e.qjs_is_object(handle.ptr)?"object":"unknown"}dump(handle){return this.assertNotDisposed(),this._dump(handle,new Map)}_dump(handle,visited){let e=this.exports;if(!e.qjs_is_undefined(handle.ptr)){if(e.qjs_is_null(handle.ptr))return null;if(e.qjs_is_bool(handle.ptr))return e.qjs_get_bool(handle.ptr)!==0;if(e.qjs_is_number(handle.ptr))return e.qjs_get_float64(handle.ptr);if(e.qjs_is_string(handle.ptr))return handle.toString();if(e.qjs_is_big_int(handle.ptr))return handle.toBigInt();if(e.qjs_is_symbol(handle.ptr)){let descOutPtr=e.wasm_malloc(4),kind=e.qjs_get_symbol_description(handle.ptr,descOutPtr),descPtr=new DataView(e.memory.buffer).getUint32(descOutPtr,!0);if(e.wasm_free(descOutPtr),kind===1){let descHandle=new JSValueHandle(this,descPtr),description=descHandle.toString();return descHandle.dispose(),Symbol.for(description)}else if(kind===2){new JSValueHandle(this,descPtr).dispose();return}return}if(e.qjs_is_array_buffer(handle.ptr))return handle.toArrayBuffer();if(e.qjs_is_exception(handle.ptr)){let exc=this.getException(),msg=exc.toString();return exc.dispose(),new Error(msg)}if(!e.qjs_is_function(handle.ptr)){if(e.qjs_is_object(handle.ptr)){let objPtr=e.qjs_get_value_ptr(handle.ptr);if(objPtr){let existing=visited.get(objPtr);if(existing!==void 0)return existing}}if(e.qjs_is_object(handle.ptr)){let byteOffsetPtr=e.wasm_malloc(4),byteLengthPtr=e.wasm_malloc(4),bytesPerElemPtr=e.wasm_malloc(4),abPtr=e.qjs_get_typed_array_buffer(handle.ptr,byteOffsetPtr,byteLengthPtr,bytesPerElemPtr),abHandle=new JSValueHandle(this,abPtr);if(e.qjs_is_exception(abHandle.ptr)===0){let view=new DataView(e.memory.buffer),byteOffset=view.getUint32(byteOffsetPtr,!0),byteLength=view.getUint32(byteLengthPtr,!0),bytesPerElement=view.getUint32(bytesPerElemPtr,!0);e.wasm_free(byteOffsetPtr),e.wasm_free(byteLengthPtr),e.wasm_free(bytesPerElemPtr);let abLenPtr=e.wasm_malloc(4),abDataPtr=e.qjs_get_array_buffer(abHandle.ptr,abLenPtr);if(e.wasm_free(abLenPtr),abHandle.dispose(),abDataPtr!==0){let rawBytes=new Uint8Array(e.memory.buffer,abDataPtr+byteOffset,byteLength).slice();switch(bytesPerElement){case 1:return rawBytes;case 2:return new Uint16Array(rawBytes.buffer);case 4:return new Uint32Array(rawBytes.buffer);case 8:return new Float64Array(rawBytes.buffer);default:return rawBytes}}}else abHandle.dispose(),e.wasm_free(byteOffsetPtr),e.wasm_free(byteLengthPtr),e.wasm_free(bytesPerElemPtr)}if(e.qjs_is_array(handle.ptr)){let lenHandle=handle.getProp("length"),len=e.qjs_get_float64(lenHandle.ptr);lenHandle.dispose();let arr=[],objPtr=e.qjs_get_value_ptr(handle.ptr);objPtr&&visited.set(objPtr,arr);for(let i=0;i<len;i++){let elemPtr=e.qjs_get_prop_uint32(handle.ptr,i),elemHandle=new JSValueHandle(this,elemPtr);arr.push(this._dump(elemHandle,visited)),elemHandle.dispose()}return arr}if(e.qjs_is_error(handle.ptr)){let nameHandle=handle.getProp("name"),msgHandle=handle.getProp("message"),stackHandle=handle.getProp("stack"),name=nameHandle.isUndefined?"Error":nameHandle.toString(),message=msgHandle.isUndefined?"":msgHandle.toString(),stack=stackHandle.isUndefined?void 0:stackHandle.toString();nameHandle.dispose(),msgHandle.dispose(),stackHandle.dispose();let err=new Error(message);return err.name=name,stack!==void 0&&(err.stack=stack),err}if(e.qjs_is_object(handle.ptr)){let keysPtr=e.qjs_get_own_property_names(handle.ptr),keysHandle=new JSValueHandle(this,keysPtr);if(e.qjs_is_exception(keysHandle.ptr)!==0)return keysHandle.dispose(),{};let lenHandle=keysHandle.getProp("length"),len=e.qjs_get_float64(lenHandle.ptr);lenHandle.dispose();let obj={},objPtr=e.qjs_get_value_ptr(handle.ptr);objPtr&&visited.set(objPtr,obj);for(let i=0;i<len;i++){let keyPtr=e.qjs_get_prop_uint32(keysHandle.ptr,i),keyHandle=new JSValueHandle(this,keyPtr),key=keyHandle.toString();keyHandle.dispose();let valHandle=handle.getProp(key);obj[key]=this._dump(valHandle,visited),valHandle.dispose()}return keysHandle.dispose(),obj}}}}hostToHandle(value){if(this.assertNotDisposed(),value===void 0)return this.undefined;if(value===null)return this.null;if(value===!0)return this.true;if(value===!1)return this.false;if(typeof value=="number")return this.newNumber(value);if(typeof value=="string")return this.newString(value);if(typeof value=="bigint")return this.newBigInt(value);if(typeof value=="symbol"){let key=Symbol.keyFor(value);if(key!==void 0)return this.newSymbolFor(key);throw new Error("Cannot convert local symbol to QuickJS handle. Use Symbol.for() for cross-boundary symbols.")}if(value instanceof Promise){let deferred=this.newPromise();return value.then(r=>{deferred.resolve(this.hostToHandle(r)),this.executePendingJobs()},err=>{deferred.reject(this.hostToHandle(err)),this.executePendingJobs()}),deferred.handle}if(value instanceof Error)return this.newError(value);if(value instanceof ArrayBuffer)return this.newArrayBuffer(value);if(value instanceof Uint8Array)return this.newUint8Array(value);if(ArrayBuffer.isView(value))return this.newArrayBuffer(new Uint8Array(value.buffer,value.byteOffset,value.byteLength));if(Array.isArray(value)){let arr=this.newArray();for(let i=0;i<value.length;i++){let elemHandle=this.hostToHandle(value[i]);this.exports.qjs_set_prop_uint32(arr.ptr,i,elemHandle.ptr),elemHandle.dispose()}return arr}if(typeof value=="object"&&value!==null){let obj=this.newObject();for(let[key,val]of Object.entries(value)){let valHandle=this.hostToHandle(val);obj.setProp(key,valHandle),valHandle.dispose()}return obj}return this.undefined}snapshot(){return this.assertNotDisposed(),{memory:new Uint8Array(this.exports.memory.buffer).slice(),stackPointer:this.exports.__stack_pointer.value,runtimePtr:this.exports.qjs_get_runtime_ptr(),contextPtr:this.exports.qjs_get_context_ptr(),extensions:this.loadedExtensions.map(ext=>({name:ext.name,memoryBase:ext.memoryBase,tableBase:ext.tableBase,initFn:ext.initFn}))}}registerHostCallback(name,fn){this.hostCallbacks.set(name,fn)}dispose(){this.disposed||(this.disposed=!0,this._global=null,this._undefined=null,this._null=null,this._true=null,this._false=null,this._ownedHandles.clear(),this.hostCallbacks.clear(),this._activeScope=null,this.exports=null,this.instance=null,this.module=null)}[Symbol.dispose](){this.dispose()}assertNotDisposed(){if(this.disposed)throw new Error("QuickJS instance has been disposed")}_getExports(){return this.exports}_getMemory(){return this.exports.memory}_writeString(str){return this.writeString(str)}_readCString(ptr){return this.readCString(ptr)}};function stringKeyNeedsValuePath(key){return key.includes("\0")||LONE_SURROGATE_RE.test(key)}var wtf8Decoder=new TextDecoder,wtf8Encoder=new TextEncoder,LONE_SURROGATE_RE=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF]))|(?:(?<![\uD800-\uDBFF])[\uDC00-\uDFFF])/;function encodeWtf8(str){if(!LONE_SURROGATE_RE.test(str))return wtf8Encoder.encode(str);let bytes=[];for(let i=0;i<str.length;i++){let code=str.charCodeAt(i);if(code<128)bytes.push(code);else if(code<2048)bytes.push(192|code>>6,128|code&63);else if(code>=55296&&code<=56319&&i+1<str.length){let next=str.charCodeAt(i+1);if(next>=56320&&next<=57343){let cp=65536+(code-55296<<10)+(next-56320);bytes.push(240|cp>>18,128|cp>>12&63,128|cp>>6&63,128|cp&63),i++;continue}bytes.push(224|code>>12,128|code>>6&63,128|code&63)}else bytes.push(224|code>>12,128|code>>6&63,128|code&63)}return new Uint8Array(bytes)}function decodeWtf8(bytes){let hasSurrogateSequence=!1;for(let i2=0;i2<bytes.length-1;i2++)if(bytes[i2]===237&&bytes[i2+1]>=160&&bytes[i2+1]<=191){hasSurrogateSequence=!0;break}if(!hasSurrogateSequence)return wtf8Decoder.decode(bytes);let out="",i=0;for(;i<bytes.length;){let b0=bytes[i];if(b0<128)out+=String.fromCharCode(b0),i+=1;else if(b0<224)out+=String.fromCharCode((b0&31)<<6|bytes[i+1]&63),i+=2;else if(b0<240)out+=String.fromCharCode((b0&15)<<12|(bytes[i+1]&63)<<6|bytes[i+2]&63),i+=3;else{let cp=(b0&7)<<18|(bytes[i+1]&63)<<12|(bytes[i+2]&63)<<6|bytes[i+3]&63;out+=String.fromCodePoint(cp),i+=4}}return out}var JSException=class extends Error{handle;#name;#message;#stack;constructor(handle){let env_1={stack:[],error:void 0,hasError:!1};try{super(),this.handle=handle,delete this.stack;let msgHandle=__addDisposableResource(env_1,handle.getProp("message"),!1);this.#name=handle.getProp("name").consume(h=>h.isUndefined?"Error":h.toString()),this.#message=msgHandle.isUndefined?handle.toString():msgHandle.toString(),this.#stack=handle.getProp("stack").consume(h=>h.isUndefined?void 0:h.toString())}catch(e_1){env_1.error=e_1,env_1.hasError=!0}finally{__disposeResources(env_1)}}get name(){return this.#name}set name(v){this.#name=v}get message(){return this.#message}set message(v){this.#message=v}get stack(){return this.#stack}set stack(v){this.#stack=v}dispose(){this.handle.dispose()}[Symbol.dispose](){this.handle.dispose()}},JSValueHandle=class _JSValueHandle{vm;ptr;disposed_=!1;singleton;borrowed;_onDispose;constructor(vm,ptr,singleton=!1,borrowed=!1){this.vm=vm,this.ptr=ptr,this.singleton=singleton,this.borrowed=borrowed,!singleton&&!borrowed&&vm._activeScope?.add(this)}get _isBorrowed(){return this.borrowed}get disposed(){return this.disposed_}get isUndefined(){return this.vm._getExports().qjs_is_undefined(this.ptr)!==0}get isNull(){return this.vm._getExports().qjs_is_null(this.ptr)!==0}get isBool(){return this.vm._getExports().qjs_is_bool(this.ptr)!==0}get isNumber(){return this.vm._getExports().qjs_is_number(this.ptr)!==0}get isString(){return this.vm._getExports().qjs_is_string(this.ptr)!==0}get isSymbol(){return this.vm._getExports().qjs_is_symbol(this.ptr)!==0}get isBigInt(){return this.vm._getExports().qjs_is_big_int(this.ptr)!==0}get isObject(){return this.vm._getExports().qjs_is_object(this.ptr)!==0}get isArray(){return this.vm._getExports().qjs_is_array(this.ptr)!==0}get isFunction(){return this.vm._getExports().qjs_is_function(this.ptr)!==0}get isError(){return this.vm._getExports().qjs_is_error(this.ptr)!==0}get isPromise(){return this.vm._getExports().qjs_is_promise(this.ptr)!==0}get isArrayBuffer(){return this.vm._getExports().qjs_is_array_buffer(this.ptr)!==0}get isProxy(){return this.vm._getExports().qjs_is_proxy(this.ptr)!==0}get isMap(){return this.vm._getExports().qjs_is_map(this.ptr)!==0}get isSet(){return this.vm._getExports().qjs_is_set(this.ptr)!==0}get isDate(){return this.vm._getExports().qjs_is_date(this.ptr)!==0}get isRegExp(){return this.vm._getExports().qjs_is_regexp(this.ptr)!==0}get isWeakRef(){return this.vm._getExports().qjs_is_weak_ref(this.ptr)!==0}get isWeakMap(){return this.vm._getExports().qjs_is_weak_map(this.ptr)!==0}get isWeakSet(){return this.vm._getExports().qjs_is_weak_set(this.ptr)!==0}get isDataView(){return this.vm._getExports().qjs_is_data_view(this.ptr)!==0}get identity(){return this.vm._getExports().qjs_get_value_ptr(this.ptr)}toBoolean(){return this.vm._getExports().qjs_get_bool(this.ptr)!==0}get classId(){return this.vm._getExports().qjs_get_class_id(this.ptr)}get className(){let h=new _JSValueHandle(this.vm,this.vm._getExports().qjs_get_class_name(this.ptr));if(this.vm._getExports().qjs_is_exception(h.ptr)!==0)throw h.dispose(),new JSException(this.vm.getException());try{return h.isUndefined?void 0:h.toString()}finally{h.dispose()}}get promiseState(){return this.vm._getExports().qjs_promise_state(this.ptr)}get typeof(){return this.vm.typeof(this)}get length(){let h=this.getProp("length"),n=h.toNumber();return h.dispose(),n}get constructorName(){let ctor=this.getProp("constructor");if(ctor.isUndefined||ctor.isNull){ctor.dispose();return}let name=ctor.getProp("name");if(ctor.dispose(),name.isUndefined||name.isNull){name.dispose();return}let result=name.toString();return name.dispose(),result}keys(){let e=this.vm._getExports(),keysPtr=e.qjs_get_own_property_names(this.ptr),keysHandle=new _JSValueHandle(this.vm,keysPtr);if(e.qjs_is_exception(keysHandle.ptr)!==0)return keysHandle.dispose(),[];let lenHandle=keysHandle.getProp("length"),len=e.qjs_get_float64(lenHandle.ptr);lenHandle.dispose();let result=[];for(let i=0;i<len;i++){let keyPtr=e.qjs_get_prop_uint32(keysHandle.ptr,i),keyHandle=new _JSValueHandle(this.vm,keyPtr);result.push(keyHandle.toString()),keyHandle.dispose()}return keysHandle.dispose(),result}getOwnPropertyNames(){let e=this.vm._getExports(),keysPtr=e.qjs_get_own_property_names_all(this.ptr),keysHandle=new _JSValueHandle(this.vm,keysPtr);if(e.qjs_is_exception(keysHandle.ptr)!==0)return keysHandle.dispose(),[];let lenHandle=keysHandle.getProp("length"),len=e.qjs_get_float64(lenHandle.ptr);lenHandle.dispose();let result=[];for(let i=0;i<len;i++){let keyPtr=e.qjs_get_prop_uint32(keysHandle.ptr,i),keyHandle=new _JSValueHandle(this.vm,keyPtr);result.push(keyHandle.toString()),keyHandle.dispose()}return keysHandle.dispose(),result}getOwnPropertyKeys(){let e=this.vm._getExports(),keysPtr=e.qjs_get_own_property_keys(this.ptr),keysHandle=new _JSValueHandle(this.vm,keysPtr);if(e.qjs_is_exception(keysHandle.ptr)!==0)return keysHandle.dispose(),[];let lenHandle=keysHandle.getProp("length"),len=e.qjs_get_float64(lenHandle.ptr);lenHandle.dispose();let result=[];for(let i=0;i<len;i++){let keyPtr=e.qjs_get_prop_uint32(keysHandle.ptr,i),keyHandle=new _JSValueHandle(this.vm,keyPtr);keyHandle.isSymbol?result.push(keyHandle):(result.push(keyHandle.toString()),keyHandle.dispose())}return keysHandle.dispose(),result}getOwnPropertyDescriptor(key){let env_2={stack:[],error:void 0,hasError:!1};try{let e=this.vm._getExports(),keyHandle,keyPtr;typeof key=="string"?(keyHandle=this.vm.newString(key),keyPtr=keyHandle.ptr):keyPtr=key.ptr;let descPtr=e.qjs_get_own_property_descriptor(this.ptr,keyPtr);if(keyHandle?.dispose(),descPtr===0)return;let descHandle=__addDisposableResource(env_2,new _JSValueHandle(this.vm,descPtr),!1);if(e.qjs_is_exception(descHandle.ptr)!==0)throw new JSException(this.vm.getException());let enumerable=descHandle.getProp("enumerable").consume(h=>e.qjs_get_bool(h.ptr)!==0),configurable=descHandle.getProp("configurable").consume(h=>e.qjs_get_bool(h.ptr)!==0);return descHandle.hasOwnProperty("value")?{value:descHandle.getProp("value"),writable:descHandle.getProp("writable").consume(h=>e.qjs_get_bool(h.ptr)!==0),enumerable,configurable}:{get:descHandle.getProp("get"),set:descHandle.getProp("set"),enumerable,configurable}}catch(e_2){env_2.error=e_2,env_2.hasError=!0}finally{__disposeResources(env_2)}}hasOwnProperty(name){if(stringKeyNeedsValuePath(name)){let env_3={stack:[],error:void 0,hasError:!1};try{let keyHandle=__addDisposableResource(env_3,this.vm.newString(name),!1);return this.vm._getExports().qjs_has_own_property_value(this.ptr,keyHandle.ptr)===1}catch(e_3){env_3.error=e_3,env_3.hasError=!0}finally{__disposeResources(env_3)}}let{ptr:namePtr}=this.vm._writeString(name),result=this.vm._getExports().qjs_has_own_property(this.ptr,namePtr);return this.vm._getExports().wasm_free(namePtr),result===1}propertyIsEnumerable(name){if(stringKeyNeedsValuePath(name)){let env_4={stack:[],error:void 0,hasError:!1};try{let keyHandle=__addDisposableResource(env_4,this.vm.newString(name),!1);return this.vm._getExports().qjs_property_is_enumerable_value(this.ptr,keyHandle.ptr)===1}catch(e_4){env_4.error=e_4,env_4.hasError=!0}finally{__disposeResources(env_4)}}let{ptr:namePtr}=this.vm._writeString(name),result=this.vm._getExports().qjs_property_is_enumerable(this.ptr,namePtr);return this.vm._getExports().wasm_free(namePtr),result===1}getPrototypeOf(){let protoPtr=this.vm._getExports().qjs_get_prototype_of(this.ptr);return new _JSValueHandle(this.vm,protoPtr)}getProxyTarget(){let ptr=this.vm._getExports().qjs_get_proxy_target(this.ptr),handle=new _JSValueHandle(this.vm,ptr);if(this.vm._getExports().qjs_is_exception(handle.ptr)!==0)throw handle.dispose(),new JSException(this.vm.getException());return handle}getProxyHandler(){let ptr=this.vm._getExports().qjs_get_proxy_handler(this.ptr),handle=new _JSValueHandle(this.vm,ptr);if(this.vm._getExports().qjs_is_exception(handle.ptr)!==0)throw handle.dispose(),new JSException(this.vm.getException());return handle}getProp(name){if(stringKeyNeedsValuePath(name)){let env_5={stack:[],error:void 0,hasError:!1};try{let keyHandle=__addDisposableResource(env_5,this.vm.newString(name),!1);return this.vm.getProp(this,keyHandle)}catch(e_5){env_5.error=e_5,env_5.hasError=!0}finally{__disposeResources(env_5)}}let{ptr:namePtr}=this.vm._writeString(name),resultPtr=this.vm._getExports().qjs_get_prop_string(this.ptr,namePtr);return this.vm._getExports().wasm_free(namePtr),new _JSValueHandle(this.vm,resultPtr)}setProp(name,value){if(stringKeyNeedsValuePath(name)){let env_6={stack:[],error:void 0,hasError:!1};try{let keyHandle=__addDisposableResource(env_6,this.vm.newString(name),!1);this.vm.setProp(this,keyHandle,value);return}catch(e_6){env_6.error=e_6,env_6.hasError=!0}finally{__disposeResources(env_6)}}let{ptr:namePtr}=this.vm._writeString(name);this.vm._getExports().qjs_set_prop_string(this.ptr,namePtr,value.ptr),this.vm._getExports().wasm_free(namePtr)}defineProp(key,value,descriptor){let flags=0;if(descriptor?.configurable&&(flags|=1),descriptor?.writable&&(flags|=2),descriptor?.enumerable&&(flags|=4),typeof key=="string"){if(stringKeyNeedsValuePath(key)){let env_7={stack:[],error:void 0,hasError:!1};try{let keyHandle=__addDisposableResource(env_7,this.vm.newString(key),!1);this.vm._getExports().qjs_define_prop_value(this.ptr,keyHandle.ptr,value.ptr,flags);return}catch(e_7){env_7.error=e_7,env_7.hasError=!0}finally{__disposeResources(env_7)}}let{ptr:namePtr}=this.vm._writeString(key);this.vm._getExports().qjs_define_prop_string(this.ptr,namePtr,value.ptr,flags),this.vm._getExports().wasm_free(namePtr)}else this.vm._getExports().qjs_define_prop_value(this.ptr,key.ptr,value.ptr,flags)}toNumber(){return this.vm._getExports().qjs_get_float64(this.ptr)}toBigInt(){let e=this.vm._getExports(),loPtr=e.wasm_malloc(4),hiPtr=e.wasm_malloc(4);if(e.qjs_get_big_int64(this.ptr,loPtr,hiPtr)!==0)throw e.wasm_free(loPtr),e.wasm_free(hiPtr),new Error("Failed to convert value to BigInt");let view=new DataView(e.memory.buffer),lo=view.getUint32(loPtr,!0),hi=view.getInt32(hiPtr,!0);return e.wasm_free(loPtr),e.wasm_free(hiPtr),BigInt(hi)<<32n|BigInt(lo)}toArrayBuffer(){let e=this.vm._getExports(),lenOutPtr=e.wasm_malloc(4);if(e.qjs_is_array_buffer(this.ptr)){let dataPtr=e.qjs_get_array_buffer(this.ptr,lenOutPtr);if(dataPtr===0)throw e.wasm_free(lenOutPtr),new Error("Failed to get ArrayBuffer data");let len=new DataView(e.memory.buffer).getUint32(lenOutPtr,!0);return e.wasm_free(lenOutPtr),new Uint8Array(e.memory.buffer,dataPtr,len).slice().buffer}e.wasm_free(lenOutPtr);let byteOffsetPtr=e.wasm_malloc(4),byteLengthPtr=e.wasm_malloc(4),bytesPerElemPtr=e.wasm_malloc(4),abPtr=e.qjs_get_typed_array_buffer(this.ptr,byteOffsetPtr,byteLengthPtr,bytesPerElemPtr),abHandle=new _JSValueHandle(this.vm,abPtr);if(this.vm._getExports().qjs_is_exception(abHandle.ptr)!==0)throw abHandle.dispose(),e.wasm_free(byteOffsetPtr),e.wasm_free(byteLengthPtr),e.wasm_free(bytesPerElemPtr),new Error("Value is not an ArrayBuffer or typed array");let view=new DataView(e.memory.buffer),byteOffset=view.getUint32(byteOffsetPtr,!0),byteLength=view.getUint32(byteLengthPtr,!0);e.wasm_free(byteOffsetPtr),e.wasm_free(byteLengthPtr),e.wasm_free(bytesPerElemPtr);let abLenPtr=e.wasm_malloc(4),abDataPtr=e.qjs_get_array_buffer(abHandle.ptr,abLenPtr);if(e.wasm_free(abLenPtr),abHandle.dispose(),abDataPtr===0)throw new Error("Failed to get ArrayBuffer data from typed array");return new Uint8Array(e.memory.buffer,abDataPtr+byteOffset,byteLength).slice().buffer}toUint8Array(){return new Uint8Array(this.toArrayBuffer())}toString(){let e=this.vm._getExports(),lenPtr=e.wasm_malloc(4);if(lenPtr===0)throw new Error("wasm_malloc failed");try{let cstrPtr=e.qjs_get_string_len(this.ptr,lenPtr);if(cstrPtr===0)return"<null>";let len=new DataView(e.memory.buffer).getUint32(lenPtr,!0),bytes=new Uint8Array(e.memory.buffer,cstrPtr,len),str=decodeWtf8(bytes);return e.qjs_free_cstring(cstrPtr),str}finally{e.wasm_free(lenPtr)}}consume(fn){try{return fn(this)}finally{this.dispose()}}dup(){return new _JSValueHandle(this.vm,this.vm._getExports().qjs_dup_value(this.ptr))}dispose(){if(!(this.singleton||this.borrowed)&&!this.disposed_){this.disposed_=!0,this._onDispose?.(),this._onDispose=void 0;let exports=this.vm._getExports();exports&&exports.qjs_free_value(this.ptr)}}[Symbol.dispose](){this.dispose()}};var IMAGE_HELPER_EXPECTS="image expects a non-empty image URL string, an object with image_url, or a raw MCP image block",PRELUDE_SOURCE=`(function (bridge, toolsJson, globalsJson, storeJson) {
|
|
4
3
|
"use strict";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{ARMIN_HEIGHT,ARMIN_WIDTH,isArminPixel}from"./chunk-2KAZSACP.js";import{backgroundAnsi,colorToRgb,foregroundAnsi,formatKeyText,getKeybindings,indexedColor,rgbColor,theme,visibleWidth}from"./chunk-6FX7UEPL.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";var DEPTH=.7,FLY_START=.1,FLY_DURATION=1.3,START_SCALE=.1;function createModel(columns,rows,pixel,options){let blocks=[];for(let row=0;row<rows;row++)for(let column=0;column<columns;column++){let color=pixel(column,row);color&&blocks.push({home:[column,row,0],color})}return{columns,rows,blocks,cameraDistance:options.cameraDistance,radius:Math.hypot(columns/2,rows/2,1+DEPTH/2),widthShare:options.widthShare,puzzleMoves:random=>options.puzzleMoves(random,blocks.length),origin:options.origin}}var CORAL=[228,138,122],BLUE=[79,142,179],YELLOW=[234,182,93],PI_LOGO_PIXELS=["ccc.","b.c.","bb.y","b..y"],PI_LOGO_COLORS={c:CORAL,b:BLUE,y:YELLOW};function piLogoModel(origin){return createModel(4,4,(column,row)=>PI_LOGO_COLORS[PI_LOGO_PIXELS[row][column]],{cameraDistance:10,widthShare:.35,puzzleMoves:random=>random<.4?2:1,origin})}function arminModel(color){return createModel(ARMIN_WIDTH,ARMIN_HEIGHT,(column,row)=>isArminPixel(column,row)?color:void 0,{cameraDistance:80,widthShare:.45,puzzleMoves:(random,blockCount)=>Math.round(blockCount*(.03+random*.04)),origin:void 0})}var PUZZLE_START=FLY_START+FLY_DURATION+3,PUZZLE_STEP=.3,PUZZLE_STEPS=12,PUZZLE_RETURN=1,PUZZLE_HOLD=.6,PUZZLE_CYCLE=PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD,PUZZLE_MOVES=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]];function shuffleSteps(model,cycle){let{columns,rows}=model,positions=model.blocks.map(block=>block.home),steps=[positions],lastMoved=new Set,random=cycle*7919+1,next=()=>hash(random++),key=([x,y,z])=>((z+1)*rows+y)*columns+x;for(let step=0;step<PUZZLE_STEPS;step++){let occupied=new Set(positions.map(key)),nextPositions=[...positions],moved=new Set,moveCount=model.puzzleMoves(next());for(let move=0;move<moveCount;move++){let candidates=[];for(let block=0;block<positions.length;block++){if(moved.has(block))continue;let[x,y,z]=positions[block];for(let[dx,dy,dz]of PUZZLE_MOVES){let target=[x+dx,y+dy,z+dz];target[0]<0||target[0]>=columns||target[1]<0||target[1]>=rows||target[2]<-1||target[2]>1||occupied.has(key(target))||candidates.push({block,target})}}let fresh=candidates.filter(candidate=>!lastMoved.has(candidate.block)),pool=fresh.length>0?fresh:candidates,choice=pool[Math.floor(next()*pool.length)];if(!choice)break;occupied.add(key(choice.target)),nextPositions[choice.block]=choice.target,moved.add(choice.block)}lastMoved.clear();for(let block of moved)lastMoved.add(block);positions=nextPositions,steps.push(positions)}return steps}var FRAME_MS=1e3/30,DUST_DURATION=.35,WAVE_SPREAD=.55,WAVE_JITTER=.12,DISSOLVE_END=FLY_START+WAVE_SPREAD+WAVE_JITTER+DUST_DURATION,BACKGROUND_FADE=.5,EXIT_DURATION=1.1,STARS_START=2.5,STARS_FADE=2,STAR_DENSITY=.018,STAR_TINTS=[[255,255,255],[170,195,255],[255,225,170],[255,190,205]],LOGO_COLOR_STEP=5,LIGHT_HALO_STRENGTH=.3,HALO_RADIUS_X=6,HALO_RADIUS_Y=3,HALO_LEVELS=32,STAR_ALPHA_LEVELS=8,STAR_FLICKER_LEVELS=3,HINT_FADE=.5,DOT_BITS=[1,8,2,16,4,32,64,128],BRAILLE=Array.from({length:256},(_,bits)=>String.fromCharCode(10240+bits)),LIGHT=normalize([-.45,-.6,.75]),HALF_VECTOR=normalize([LIGHT[0],LIGHT[1],LIGHT[2]+1]);function normalize(v){let length=Math.hypot(v[0],v[1],v[2]);return[v[0]/length,v[1]/length,v[2]/length]}function clamp01(value){return value<0?0:value>1?1:value}function smooth(value){let t=clamp01(value);return t*t*t*(t*(t*6-15)+10)}function easeOut(value){let t=1-clamp01(value);return 1-t*t*t}function mix(a,b,amount){return[a[0]+(b[0]-a[0])*amount,a[1]+(b[1]-a[1])*amount,a[2]+(b[2]-a[2])*amount]}function hash(value){let x=Math.imul(value^2654435769,2246822507);return x^=x>>>13,x=Math.imul(x,3266489909),x^=x>>>16,(x>>>0)/4294967296}function isLight([r,g,b]){return .2126*r+.7152*g+.0722*b>128}function toRgb(color){let{r,g,b}=colorToRgb(color);return[r,g,b]}function glyphInk(text,seed){return text.trim()===""?0:/^[.,:;'`\-_·]$/.test(text)?2:/^[\u2500-\u257f]$/.test(text)?3:4+Math.floor(seed*3)}var segmenter=new Intl.Segmenter;function parseScreen(lines,width,foreground,background){let palette=index=>toRgb(indexedColor(index));return lines.map(line=>{let cells=[],fg,bg,dim=!1,inverse=!1,applySgr=params=>{let codes=params===""?["0"]:params.split(";");for(let i2=0;i2<codes.length;i2++){let parts=codes[i2].split(":").map(part=>Number.parseInt(part,10)),code=parts[0]??0;if(code===38||code===48){let args;if(parts.length>1)args=parts.slice(1).filter(part=>!Number.isNaN(part));else{let kind=Number.parseInt(codes[i2+1]??"",10),count=kind===5?2:kind===2?4:1;args=codes.slice(i2+1,i2+1+count).map(part=>Number.parseInt(part,10)),i2+=count}let color;args[0]===5&&args[1]!==void 0?color=palette(args[1]):args[0]===2&&args.length>=4&&(color=[args[1],args[2],args[3]]),color&&(code===38?fg=color:bg=color)}else code===0?(fg=void 0,bg=void 0,dim=!1,inverse=!1):code===2?dim=!0:code===22?dim=!1:code===7?inverse=!0:code===27?inverse=!1:code>=30&&code<=37?fg=palette(code-30):code>=90&&code<=97?fg=palette(code-90+8):code===39?fg=void 0:code>=40&&code<=47?bg=palette(code-40):code>=100&&code<=107?bg=palette(code-100+8):code===49&&(bg=void 0)}},pushText=text=>{for(let{segment}of segmenter.segment(text)){let glyphWidth=visibleWidth(segment);if(glyphWidth===0||cells.length+glyphWidth>width)continue;let cellFg=fg??foreground,cellBg=bg;inverse&&(cellFg=bg??background,cellBg=fg??foreground),dim&&(cellFg=mix(cellFg,cellBg??background,.4));let cell={text:segment,width:glyphWidth,fg:cellFg,bg:cellBg,delay:0,ink:0,seed:0};cells.push(cell),glyphWidth===2&&cells.push({...cell,text:"",width:0})}},i=0;for(;i<line.length;){let sequenceStart=line.indexOf("\x1B",i);if(sequenceStart===-1){pushText(line.slice(i));break}sequenceStart>i&&pushText(line.slice(i,sequenceStart));let kind=line[sequenceStart+1];if(kind==="["){let end=sequenceStart+2;for(;end<line.length&&(line.charCodeAt(end)<64||line.charCodeAt(end)>126);)end++;line[end]==="m"&&applySgr(line.slice(sequenceStart+2,end)),i=end+1}else if(kind==="]"||kind==="_"||kind==="P"||kind==="^"){let bell=line.indexOf("\x07",sequenceStart+2),st=line.indexOf("\x1B\\",sequenceStart+2);if(bell===-1&&st===-1)break;i=bell!==-1&&(st===-1||bell<st)?bell+1:st+2}else i=sequenceStart+2}return cells})}function rotation(yaw,pitch,roll){let[sy,cy,sx,cx,sz,cz]=[Math.sin(yaw),Math.cos(yaw),Math.sin(pitch),Math.cos(pitch),Math.sin(roll),Math.cos(roll)],ry=[cy,0,sy,0,1,0,-sy,0,cy],rx=[1,0,0,0,cx,-sx,0,sx,cx],rz=[cz,-sz,0,sz,cz,0,0,0,1];return multiply(rz,multiply(rx,ry))}function multiply(a,b){let result=new Array(9);for(let row=0;row<3;row++)for(let column=0;column<3;column++)result[row*3+column]=a[row*3]*b[column]+a[row*3+1]*b[3+column]+a[row*3+2]*b[6+column];return result}var SPIN_RAMP=1.4,SPIN_SPEED=Math.PI*2/PUZZLE_CYCLE,SPIN_LINGER=.6,FIRST_FRONT_VIEW=PUZZLE_START+PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD/2;function baseSpinPhase(time){let elapsed=time-FLY_START;if(elapsed<=0)return 0;let u=elapsed/SPIN_RAMP;return u<1?SPIN_SPEED*SPIN_RAMP*(u**6-3*u**5+2.5*u**4):SPIN_SPEED*(SPIN_RAMP*.5+elapsed-SPIN_RAMP)}var SPIN_ALIGNMENT=Math.PI*2-baseSpinPhase(FIRST_FRONT_VIEW)%(Math.PI*2);function spinPhase(time){return baseSpinPhase(time)+SPIN_ALIGNMENT*smooth((time-FLY_START)/FLY_DURATION)}function spinAngle(time){let phase=spinPhase(time);return phase-SPIN_LINGER*Math.sin(phase)}var BlockRaster=class{bits=new Uint8Array(0);counts=new Uint8Array(0);rgb=new Float32Array(0);haloAmount=new Float32Array(0);haloRgb=new Float32Array(0);width=0;height=0;depth=new Float32Array(0);faceIds=new Uint16Array(0);dirty;haloDirty;cameraDistance;constructor(cameraDistance){this.cameraDistance=cameraDistance}render(width,height,pose,boxes,background,haloStrength){let dotWidth=width*2,dotHeight=height*4;if(width!==this.width||height!==this.height)this.width=width,this.height=height,this.bits=new Uint8Array(width*height),this.counts=new Uint8Array(width*height),this.rgb=new Float32Array(width*height*3),this.haloAmount=new Float32Array(width*height),this.haloRgb=new Float32Array(width*height*3),this.haloDirty=void 0,this.depth=new Float32Array(dotWidth*dotHeight).fill(1/0),this.faceIds=new Uint16Array(dotWidth*dotHeight),this.dirty=void 0;else if(this.dirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.dirty;for(let row=minY2;row<=maxY2;row++)this.bits.fill(0,row*width+minX2,row*width+maxX2+1),this.counts.fill(0,row*width+minX2,row*width+maxX2+1),this.rgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.dirty=void 0}if(this.haloDirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.haloDirty;for(let row=minY2;row<=maxY2;row++)this.haloAmount.fill(0,row*width+minX2,row*width+maxX2+1),this.haloRgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.haloDirty=void 0}let m=rotation(pose.yaw,pose.pitch,pose.roll),{centerX,centerY,scale}=pose,cameraDistance=this.cameraDistance,origin=[m[6]*cameraDistance,m[7]*cameraDistance,m[8]*cameraDistance],light=isLight(background),faces=this.visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,light);if(faces.length===0)return;let minX=dotWidth,minY=dotHeight,maxX=-1,maxY=-1;for(let face of faces)minX=Math.min(minX,face.minX),minY=Math.min(minY,face.minY),maxX=Math.max(maxX,face.maxX),maxY=Math.max(maxY,face.maxY);if(maxX<minX||maxY<minY)return;let depth=this.depth,faceIds=this.faceIds;for(let faceIndex=0;faceIndex<faces.length;faceIndex++){let face=faces[faceIndex],a=face.axis,u=(a+1)%3,v=(a+2)%3,originA=origin[a],originU=origin[u],originV=origin[v],stepA=m[a]/scale,stepU=m[u]/scale,stepV=m[v]/scale,sx=(face.minX+.5-centerX)/scale;for(let dotY=face.minY;dotY<=face.maxY;dotY++){let sy=(dotY+.5-centerY)/scale,directionA=m[a]*sx+m[3+a]*sy-m[6+a]*cameraDistance,directionU=m[u]*sx+m[3+u]*sy-m[6+u]*cameraDistance,directionV=m[v]*sx+m[3+v]*sy-m[6+v]*cameraDistance,index=dotY*dotWidth+face.minX;for(let dotX=face.minX;dotX<=face.maxX;dotX++,index++){let t=(face.plane-originA)/directionA;if(t>0&&t<depth[index]){let hitU=originU+t*directionU,hitV=originV+t*directionV;hitU>=face.uMin&&hitU<=face.uMax&&hitV>=face.vMin&&hitV<=face.vMax&&(depth[index]=t,faceIds[index]=faceIndex+1)}directionA+=stepA,directionU+=stepU,directionV+=stepV}}}let bits=this.bits,counts=this.counts,rgb=this.rgb,cellMinX=width,cellMinY=height,cellMaxX=-1,cellMaxY=-1;for(let dotY=minY;dotY<=maxY;dotY++){let index=dotY*dotWidth+minX;for(let dotX=minX;dotX<=maxX;dotX++,index++){let id=faceIds[index];if(id===0)continue;let face=faces[id-1],fog=clamp01(.15-cameraDistance*(1-depth[index])*.12)*(light?.5:1);faceIds[index]=0,depth[index]=1/0;let cellX=dotX>>1,cellY=dotY>>2,cell=cellY*width+cellX;bits[cell]|=DOT_BITS[(dotY&3)*2+(dotX&1)],counts[cell]++,rgb[cell*3]+=face.red+(background[0]-face.red)*fog,rgb[cell*3+1]+=face.green+(background[1]-face.green)*fog,rgb[cell*3+2]+=face.blue+(background[2]-face.blue)*fog,cellX<cellMinX&&(cellMinX=cellX),cellX>cellMaxX&&(cellMaxX=cellX),cellY<cellMinY&&(cellMinY=cellY),cellY>cellMaxY&&(cellMaxY=cellY)}}cellMaxX>=0&&(this.dirty={minX:cellMinX,minY:cellMinY,maxX:cellMaxX,maxY:cellMaxY}),haloStrength>0&&this.renderHalo(haloStrength)}renderHalo(strength){let cells=this.dirty;if(!cells)return;let{width,height,counts,rgb}=this,minX=Math.max(0,cells.minX-HALO_RADIUS_X),maxX=Math.min(width-1,cells.maxX+HALO_RADIUS_X),minY=Math.max(0,cells.minY-HALO_RADIUS_Y),maxY=Math.min(height-1,cells.maxY+HALO_RADIUS_Y),regionWidth=maxX-minX+1,tent=radius=>{let weights=Array.from({length:radius*2+1},(_,i)=>radius+1-Math.abs(i-radius)),total=weights.reduce((sum,weight)=>sum+weight,0);return weights.map(weight=>weight/total)},weightsX=tent(HALO_RADIUS_X),weightsY=tent(HALO_RADIUS_Y),rows=cells.maxY-cells.minY+1,horizontal=new Float32Array(rows*regionWidth*4);for(let y=cells.minY;y<=cells.maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dx=-HALO_RADIUS_X;dx<=HALO_RADIUS_X;dx++){let sourceX=x+dx;if(sourceX<cells.minX||sourceX>cells.maxX)continue;let source=y*width+sourceX,count=counts[source];if(count===0)continue;let weight=weightsX[dx+HALO_RADIUS_X]/8;coverage+=count*weight,red+=rgb[source*3]*weight,green+=rgb[source*3+1]*weight,blue+=rgb[source*3+2]*weight}let target=((y-cells.minY)*regionWidth+(x-minX))*4;horizontal[target]=coverage,horizontal[target+1]=red,horizontal[target+2]=green,horizontal[target+3]=blue}for(let y=minY;y<=maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dy=-HALO_RADIUS_Y;dy<=HALO_RADIUS_Y;dy++){let sourceY=y+dy;if(sourceY<cells.minY||sourceY>cells.maxY)continue;let weight=weightsY[dy+HALO_RADIUS_Y],source=((sourceY-cells.minY)*regionWidth+(x-minX))*4;coverage+=horizontal[source]*weight,red+=horizontal[source+1]*weight,green+=horizontal[source+2]*weight,blue+=horizontal[source+3]*weight}let target=y*width+x,count=counts[target];if(count>0&&count/8>coverage&&(coverage=count/8,red=rgb[target*3]/count*coverage,green=rgb[target*3+1]/count*coverage,blue=rgb[target*3+2]/count*coverage),coverage<=0)continue;let amount=Math.round(strength*Math.min(1,coverage)**.7*HALO_LEVELS)/HALO_LEVELS;amount<=0||(this.haloAmount[target]=amount,this.haloRgb[target*3]=Math.round(red/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+1]=Math.round(green/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+2]=Math.round(blue/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP)}this.haloDirty={minX,minY,maxX,maxY}}visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,lightBackground){let faces=[],cameraDistance=this.cameraDistance;for(let box of boxes)for(let a=0;a<3;a++){let u=(a+1)%3,v=(a+2)%3;for(let side of[-1,1]){let plane=side>0?box.max[a]:box.min[a];if((origin[a]-plane)*side<=0||boxes.some(other=>other!==box&&(side>0?other.min[a]:other.max[a])===plane&&other.min[u]<=box.min[u]&&other.max[u]>=box.max[u]&&other.min[v]<=box.min[v]&&other.max[v]>=box.max[v]))continue;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0,corner=[0,0,0];for(let cornerU of[box.min[u],box.max[u]])for(let cornerV of[box.min[v],box.max[v]]){corner[a]=plane,corner[u]=cornerU,corner[v]=cornerV;let x=m[0]*corner[0]+m[1]*corner[1]+m[2]*corner[2],y=m[3]*corner[0]+m[4]*corner[1]+m[5]*corner[2],z=m[6]*corner[0]+m[7]*corner[1]+m[8]*corner[2],perspective=pose.scale*cameraDistance/(cameraDistance-z),screenX=pose.centerX+x*perspective,screenY=pose.centerY+y*perspective;minX=Math.min(minX,screenX),minY=Math.min(minY,screenY),maxX=Math.max(maxX,screenX),maxY=Math.max(maxY,screenY)}let face={minX:Math.max(0,Math.floor(minX)),minY:Math.max(0,Math.floor(minY)),maxX:Math.min(dotWidth-1,Math.ceil(maxX)),maxY:Math.min(dotHeight-1,Math.ceil(maxY))};if(face.maxX<face.minX||face.maxY<face.minY)continue;let nx=m[a]*side,ny=m[3+a]*side,nz=m[6+a]*side,diffuse=Math.max(0,nx*LIGHT[0]+ny*LIGHT[1]+nz*LIGHT[2]),rim=Math.max(0,nx*.8-nz*.3),specular=lightBackground?0:Math.max(0,nx*HALF_VECTOR[0]+ny*HALF_VECTOR[1]+nz*HALF_VECTOR[2])**24*.6*255,light=lightBackground?Math.min(1,.55+diffuse*.45+rim*.1):.45+diffuse*.78+rim*.25;faces.push({axis:a,plane,uMin:box.min[u],uMax:box.max[u],vMin:box.min[v],vMax:box.max[v],...face,red:Math.min(255,box.color[0]*light+specular),green:Math.min(255,box.color[1]*light+specular),blue:Math.min(255,box.color[2]*light+specular)})}}return faces}},playing=!1;async function playEasterEgg3d(tui,screen,egg){if(playing)return;playing=!0;let reported=await tui.queryTerminalColors({timeoutMs:100}),dark=theme.appearance==="dark",toRgbTuple=(rgb,fallback)=>rgb?[rgb.r,rgb.g,rgb.b]:fallback,colors={foreground:toRgbTuple(reported.foreground,toRgb(theme.colors.text)),background:toRgbTuple(reported.background,dark?[0,0,0]:[255,255,255])};if(tui.hasOverlay()){playing=!1;return}let model=egg.kind==="armin"?arminModel(toRgb(theme.colors.accent)):piLogoModel({column:egg.column,row:egg.row}),animation=new EasterEgg3dAnimation(tui,screen,model,colors,()=>{playing=!1,overlay.hide()}),overlay=tui.showOverlay(animation,{anchor:"top-left",width:"100%",maxHeight:"100%"})}var EasterEgg3dAnimation=class{tui;screen;model;foreground;background;onDone;startTime=performance.now();lastRender=performance.now();timer;exit;shuffle;screenWidth=-1;screenHeight=-1;stars=[];cells=[];ansiCache=new Map;raster;constructor(tui,screen,model,colors,onDone){this.tui=tui,this.screen=screen,this.model=model,this.raster=new BlockRaster(model.cameraDistance),this.foreground=colors.foreground,this.background=colors.background,this.onDone=onDone,this.timer=setInterval(()=>{this.exit&&this.exitProgress()>=1||performance.now()-this.lastRender>1e3?this.finish():this.tui.requestRender()},FRAME_MS),this.timer.unref?.()}close(){if(this.exit){this.finish();return}let time=this.elapsed(),yaw=spinAngle(time),turn=Math.PI*2;this.exit={start:performance.now(),time,yaw,targetYaw:Math.ceil(yaw/turn)*turn,offsets:this.blockOffsets(time)}}handleInput(data){let keybindings=getKeybindings();(keybindings.matches(data,"tui.select.cancel")||keybindings.matches(data,"app.clear"))&&this.close()}handleMouse(event){return event.type==="click"&&this.close(),{handled:!0,render:!1}}invalidate(){this.screenWidth=-1,this.screenHeight=-1,this.ansiCache.clear()}render(width){let height=Math.max(1,this.tui.terminal.rows),foreground=this.foreground,background=this.background;this.lastRender=performance.now(),(width!==this.screenWidth||height!==this.screenHeight)&&(this.screenWidth=width,this.screenHeight=height,this.cells=this.prepareCells(width,foreground),this.stars=this.prepareStars(width,height));let dissolveTime,pose,hintAlpha,starAlpha,offsets;if(this.exit){let progress=this.exitProgress(),landing=clamp01(progress/.8),settle=1-smooth(landing);dissolveTime=Math.min(this.exit.time,DISSOLVE_END)*(1-progress),pose=this.pose(width,height,this.flyProgress(this.exit.time)*settle,this.exit.time),pose.yaw=this.exit.yaw+(this.exit.targetYaw-this.exit.yaw)*easeOut(landing),pose.pitch*=settle,pose.roll*=settle,hintAlpha=this.hintAlpha(this.exit.time)*(1-smooth(progress/.2)),starAlpha=this.starAlpha(this.exit.time)*(1-smooth(progress/.3));let gather=1-smooth(progress/.5);offsets=this.exit.offsets.map(([x,y,z])=>[x*gather,y*gather,z*gather])}else{let time=this.elapsed();dissolveTime=time,pose=this.pose(width,height,this.flyProgress(time),time),hintAlpha=this.hintAlpha(time),starAlpha=this.starAlpha(time),offsets=this.blockOffsets(time)}let{columns,rows}=this.model,boxes=this.model.blocks.map((block,index)=>{let[dx,dy,dz]=offsets[index],x=block.home[0]-columns/2+dx,y=block.home[1]-rows/2+dy;return{min:[x,y,dz-DEPTH/2],max:[x+1,y+1,dz+DEPTH/2],color:block.color}}),raster=this.raster;raster.render(width,height,pose,boxes,background,isLight(background)?LIGHT_HALO_STRENGTH:0);let halo=(index,base)=>{let amount=raster.haloAmount[index];if(amount<=0)return base;let color=raster.haloRgb;return mix(base??background,[color[index*3],color[index*3+1],color[index*3+2]],amount)},backgroundFade=smooth(dissolveTime/BACKGROUND_FADE),textFade=smooth(dissolveTime/.6)*.3,textActive=dissolveTime<DISSOLVE_END||backgroundFade<1,hint=this.hint(width,height,hintAlpha,background),frame=Math.floor(dissolveTime*14),now=this.elapsed(),starLevel=Math.round(starAlpha*STAR_ALPHA_LEVELS)/STAR_ALPHA_LEVELS,starfield=index=>{if(starLevel<=0)return;let star=this.stars[index];if(!star)return;let flicker=Math.round((.5+.5*Math.sin(now*star.speed+star.phase))*STAR_FLICKER_LEVELS)/STAR_FLICKER_LEVELS;return{text:star.glyph,fg:mix(background,mix(foreground,star.tint,.5),star.strength*(.7+.3*flicker)*starLevel)}},lines=[];for(let row=0;row<height;row++){let cells=this.cells[row]??[],line="",currentFg=-1,currentBg=-1,emit=(text,fg,bg)=>{let fgKey=fg?this.pack(fg):-1,bgKey=bg?this.pack(bg):-1;fgKey!==currentFg&&text!==" "&&(line+=fg?this.ansi(fgKey,!1):"\x1B[39m",currentFg=fgKey),bgKey!==currentBg&&(line+=bg?this.ansi(bgKey,!0):"\x1B[49m",currentBg=bgKey),line+=text};for(let column=0;column<width;column++){let index=row*width+column,cell=textActive?cells[column]:void 0,cellBg=halo(index,cell?.bg&&backgroundFade<1?mix(cell.bg,background,backgroundFade):void 0);if(hint&&row===hint.row&&column>=hint.start&&column<hint.start+hint.text.length){let offset=column-hint.start;emit(hint.text[offset],offset<hint.keyLength?hint.keyColor:hint.color,cellBg);continue}let dots=raster.bits[index];if(dots){let step=LOGO_COLOR_STEP*raster.counts[index],rgb=raster.rgb,color=[Math.round(rgb[index*3]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+1]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+2]/step)*LOGO_COLOR_STEP];emit(BRAILLE[dots],color,cellBg);continue}if(!cell){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let dust=(dissolveTime-cell.delay)/DUST_DURATION;if(dust<0&&cell.width===2&&!raster.bits[index+1]){emit(cell.text,mix(cell.fg,background,textFade),cellBg),column++;continue}if(dust<0&&cell.width===1){emit(cell.text,mix(cell.fg,background,textFade),cellBg);continue}let dotCount=dust<0?cell.ink:Math.round(cell.ink*(1-clamp01(dust)));if(dotCount<=0){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let bits=0,placed=0;for(let attempt=0;placed<dotCount&&attempt<32;attempt++){let bit=DOT_BITS[Math.floor(hash(cell.seed*7919+frame*131+attempt)*8)];bits&bit||(bits|=bit,placed++)}let fade=textFade+(1-textFade)*clamp01(dust)**.8;emit(BRAILLE[bits],mix(cell.fg,background,fade),cellBg)}lines.push(`${line}\x1B[0m`)}return lines}elapsed(){return(performance.now()-this.startTime)/1e3}exitProgress(){return this.exit?clamp01((performance.now()-this.exit.start)/1e3/EXIT_DURATION):0}finish(){this.timer&&(clearInterval(this.timer),this.timer=void 0,this.onDone())}blockOffsets(time){let blocks=this.model.blocks,home=()=>blocks.map(()=>[0,0,0]);if(time<PUZZLE_START)return home();let cycle=Math.floor((time-PUZZLE_START)/PUZZLE_CYCLE),local=time-PUZZLE_START-cycle*PUZZLE_CYCLE;this.shuffle?.cycle!==cycle&&(this.shuffle={cycle,steps:shuffleSteps(this.model,cycle)});let steps=this.shuffle.steps,offset=(position,index)=>{let block=blocks[index].home;return[position[0]-block[0],position[1]-block[1],position[2]-block[2]]},shuffleEnd=PUZZLE_STEP*PUZZLE_STEPS;if(local<shuffleEnd){let step=Math.floor(local/PUZZLE_STEP),progress=smooth((local-step*PUZZLE_STEP)/PUZZLE_STEP);return steps[step].map((from,index)=>{let a=offset(from,index),b=offset(steps[step+1][index],index);return[a[0]+(b[0]-a[0])*progress,a[1]+(b[1]-a[1])*progress,a[2]+(b[2]-a[2])*progress]})}if(local<shuffleEnd+PUZZLE_RETURN){let u=(local-shuffleEnd)/PUZZLE_RETURN,remaining=1-smooth(u),arc=Math.sin(Math.PI*clamp01(u))*.8;return steps[PUZZLE_STEPS].map((position,index)=>{let[x,y,z]=offset(position,index);return[x*remaining,y*remaining,z*remaining+(index%2===0?arc:-arc)]})}return home()}flyProgress(time){return smooth((time-FLY_START)/FLY_DURATION)}starAlpha(time){return smooth((time-STARS_START)/STARS_FADE)}hintAlpha(time){return smooth((time-FLY_START-FLY_DURATION)/HINT_FADE)}pose(width,height,progress,time){let{columns,rows,cameraDistance,radius,widthShare,origin}=this.model,reach=radius*(cameraDistance/(cameraDistance-radius)),startScale=origin?2*(cameraDistance-DEPTH/2)/cameraDistance:START_SCALE,endScale=Math.max(startScale,Math.min(width*2*widthShare,(height*4-8)*.48)/reach),endX=width,endY=height*2-2,startX=origin?origin.column*2+columns:endX,startY=origin?origin.row*4+rows:endY;return{centerX:startX+(endX-startX)*progress,centerY:startY+(endY-startY)*progress,scale:startScale*(endScale/startScale)**progress,yaw:spinAngle(time),pitch:.3*Math.sin(spinPhase(time))*progress,roll:.06*Math.sin(2*spinPhase(time))*progress}}hint(width,height,alpha,background){if(alpha<=0)return;let key=formatKeyText(getKeybindings().getKeys("tui.select.cancel")[0]??"escape"),text=`${key} to return`;if(!(text.length>width))return{row:height-2,start:Math.floor((width-text.length)/2),text,keyLength:key.length,keyColor:mix(background,toRgb(theme.colors.muted),alpha),color:mix(background,toRgb(theme.colors.dim),alpha)}}prepareStars(width,height){let stars=new Array(width*height);for(let index=0;index<width*height;index++){if(hash(index*3+20973)>=STAR_DENSITY)continue;let random=salt=>hash(index*7+salt*40503);stars[index]={glyph:BRAILLE[DOT_BITS[Math.floor(random(1)*8)]],tint:STAR_TINTS[Math.floor(random(2)*STAR_TINTS.length)],strength:.1+random(3)*.12,phase:random(4)*Math.PI*2,speed:.4+random(5)*.8}}return stars}prepareCells(width,foreground){let cells=parseScreen(this.screen,width,foreground,this.background),height=Math.max(1,this.tui.terminal.rows),{columns,rows,origin}=this.model,centerX=origin?origin.column+columns/2:width/2,centerY=origin?origin.row+rows/4:height/2,farthest=Math.hypot(Math.max(centerX,width-centerX),Math.max(centerY,height-centerY)*2);for(let row=0;row<cells.length;row++){let line=cells[row];for(let column=0;column<line.length;column++){let cell=line[column],owner=cell.width===0?line[column-1]:cell,seed=hash(row*65537+column);if(cell.width!==0){let distance=Math.hypot(column-centerX,(row-centerY)*2)/farthest;cell.delay=FLY_START+distance*WAVE_SPREAD+seed*WAVE_JITTER}else cell.delay=owner.delay;cell.seed=row*65537+column,cell.ink=glyphInk(owner.text,seed)}}if(origin)for(let row=origin.row;row<origin.row+Math.ceil(rows/2);row++){let line=cells[row];if(line)for(let column=origin.column;column<origin.column+columns;column++){let cell=line[column];cell&&(cell.text=" ",cell.width=1,cell.ink=0,cell.bg=void 0)}}return cells}pack(color){return Math.round(color[0])<<16|Math.round(color[1])<<8|Math.round(color[2])}ansi(key,isBackground){let cacheKey=key*2+(isBackground?1:0),value=this.ansiCache.get(cacheKey);if(value===void 0){let color=rgbColor(key>>16&255,key>>8&255,key&255),mode=theme.getColorMode();value=isBackground?backgroundAnsi(color,mode):foregroundAnsi(color,mode),this.ansiCache.set(cacheKey,value)}return value}};export{EasterEgg3dAnimation,playEasterEgg3d};
|
|
2
|
+
import{ARMIN_HEIGHT,ARMIN_WIDTH,isArminPixel}from"./chunk-7TP2J6F2.js";import{backgroundAnsi,colorToRgb,foregroundAnsi,formatKeyText,getKeybindings,indexedColor,rgbColor,theme,visibleWidth}from"./chunk-AXOERKKW.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";var DEPTH=.7,FLY_START=.1,FLY_DURATION=1.3,START_SCALE=.1;function createModel(columns,rows,pixel,options){let blocks=[];for(let row=0;row<rows;row++)for(let column=0;column<columns;column++){let color=pixel(column,row);color&&blocks.push({home:[column,row,0],color})}return{columns,rows,blocks,cameraDistance:options.cameraDistance,radius:Math.hypot(columns/2,rows/2,1+DEPTH/2),widthShare:options.widthShare,puzzleMoves:random=>options.puzzleMoves(random,blocks.length),origin:options.origin}}var CORAL=[228,138,122],BLUE=[79,142,179],YELLOW=[234,182,93],PI_LOGO_PIXELS=["ccc.","b.c.","bb.y","b..y"],PI_LOGO_COLORS={c:CORAL,b:BLUE,y:YELLOW};function piLogoModel(origin){return createModel(4,4,(column,row)=>PI_LOGO_COLORS[PI_LOGO_PIXELS[row][column]],{cameraDistance:10,widthShare:.35,puzzleMoves:random=>random<.4?2:1,origin})}function arminModel(color){return createModel(ARMIN_WIDTH,ARMIN_HEIGHT,(column,row)=>isArminPixel(column,row)?color:void 0,{cameraDistance:80,widthShare:.45,puzzleMoves:(random,blockCount)=>Math.round(blockCount*(.03+random*.04)),origin:void 0})}var PUZZLE_START=FLY_START+FLY_DURATION+3,PUZZLE_STEP=.3,PUZZLE_STEPS=12,PUZZLE_RETURN=1,PUZZLE_HOLD=.6,PUZZLE_CYCLE=PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD,PUZZLE_MOVES=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]];function shuffleSteps(model,cycle){let{columns,rows}=model,positions=model.blocks.map(block=>block.home),steps=[positions],lastMoved=new Set,random=cycle*7919+1,next=()=>hash(random++),key=([x,y,z])=>((z+1)*rows+y)*columns+x;for(let step=0;step<PUZZLE_STEPS;step++){let occupied=new Set(positions.map(key)),nextPositions=[...positions],moved=new Set,moveCount=model.puzzleMoves(next());for(let move=0;move<moveCount;move++){let candidates=[];for(let block=0;block<positions.length;block++){if(moved.has(block))continue;let[x,y,z]=positions[block];for(let[dx,dy,dz]of PUZZLE_MOVES){let target=[x+dx,y+dy,z+dz];target[0]<0||target[0]>=columns||target[1]<0||target[1]>=rows||target[2]<-1||target[2]>1||occupied.has(key(target))||candidates.push({block,target})}}let fresh=candidates.filter(candidate=>!lastMoved.has(candidate.block)),pool=fresh.length>0?fresh:candidates,choice=pool[Math.floor(next()*pool.length)];if(!choice)break;occupied.add(key(choice.target)),nextPositions[choice.block]=choice.target,moved.add(choice.block)}lastMoved.clear();for(let block of moved)lastMoved.add(block);positions=nextPositions,steps.push(positions)}return steps}var FRAME_MS=1e3/30,DUST_DURATION=.35,WAVE_SPREAD=.55,WAVE_JITTER=.12,DISSOLVE_END=FLY_START+WAVE_SPREAD+WAVE_JITTER+DUST_DURATION,BACKGROUND_FADE=.5,EXIT_DURATION=1.1,STARS_START=2.5,STARS_FADE=2,STAR_DENSITY=.018,STAR_TINTS=[[255,255,255],[170,195,255],[255,225,170],[255,190,205]],LOGO_COLOR_STEP=5,LIGHT_HALO_STRENGTH=.3,HALO_RADIUS_X=6,HALO_RADIUS_Y=3,HALO_LEVELS=32,STAR_ALPHA_LEVELS=8,STAR_FLICKER_LEVELS=3,HINT_FADE=.5,DOT_BITS=[1,8,2,16,4,32,64,128],BRAILLE=Array.from({length:256},(_,bits)=>String.fromCharCode(10240+bits)),LIGHT=normalize([-.45,-.6,.75]),HALF_VECTOR=normalize([LIGHT[0],LIGHT[1],LIGHT[2]+1]);function normalize(v){let length=Math.hypot(v[0],v[1],v[2]);return[v[0]/length,v[1]/length,v[2]/length]}function clamp01(value){return value<0?0:value>1?1:value}function smooth(value){let t=clamp01(value);return t*t*t*(t*(t*6-15)+10)}function easeOut(value){let t=1-clamp01(value);return 1-t*t*t}function mix(a,b,amount){return[a[0]+(b[0]-a[0])*amount,a[1]+(b[1]-a[1])*amount,a[2]+(b[2]-a[2])*amount]}function hash(value){let x=Math.imul(value^2654435769,2246822507);return x^=x>>>13,x=Math.imul(x,3266489909),x^=x>>>16,(x>>>0)/4294967296}function isLight([r,g,b]){return .2126*r+.7152*g+.0722*b>128}function toRgb(color){let{r,g,b}=colorToRgb(color);return[r,g,b]}function glyphInk(text,seed){return text.trim()===""?0:/^[.,:;'`\-_·]$/.test(text)?2:/^[\u2500-\u257f]$/.test(text)?3:4+Math.floor(seed*3)}var segmenter=new Intl.Segmenter;function parseScreen(lines,width,foreground,background){let palette=index=>toRgb(indexedColor(index));return lines.map(line=>{let cells=[],fg,bg,dim=!1,inverse=!1,applySgr=params=>{let codes=params===""?["0"]:params.split(";");for(let i2=0;i2<codes.length;i2++){let parts=codes[i2].split(":").map(part=>Number.parseInt(part,10)),code=parts[0]??0;if(code===38||code===48){let args;if(parts.length>1)args=parts.slice(1).filter(part=>!Number.isNaN(part));else{let kind=Number.parseInt(codes[i2+1]??"",10),count=kind===5?2:kind===2?4:1;args=codes.slice(i2+1,i2+1+count).map(part=>Number.parseInt(part,10)),i2+=count}let color;args[0]===5&&args[1]!==void 0?color=palette(args[1]):args[0]===2&&args.length>=4&&(color=[args[1],args[2],args[3]]),color&&(code===38?fg=color:bg=color)}else code===0?(fg=void 0,bg=void 0,dim=!1,inverse=!1):code===2?dim=!0:code===22?dim=!1:code===7?inverse=!0:code===27?inverse=!1:code>=30&&code<=37?fg=palette(code-30):code>=90&&code<=97?fg=palette(code-90+8):code===39?fg=void 0:code>=40&&code<=47?bg=palette(code-40):code>=100&&code<=107?bg=palette(code-100+8):code===49&&(bg=void 0)}},pushText=text=>{for(let{segment}of segmenter.segment(text)){let glyphWidth=visibleWidth(segment);if(glyphWidth===0||cells.length+glyphWidth>width)continue;let cellFg=fg??foreground,cellBg=bg;inverse&&(cellFg=bg??background,cellBg=fg??foreground),dim&&(cellFg=mix(cellFg,cellBg??background,.4));let cell={text:segment,width:glyphWidth,fg:cellFg,bg:cellBg,delay:0,ink:0,seed:0};cells.push(cell),glyphWidth===2&&cells.push({...cell,text:"",width:0})}},i=0;for(;i<line.length;){let sequenceStart=line.indexOf("\x1B",i);if(sequenceStart===-1){pushText(line.slice(i));break}sequenceStart>i&&pushText(line.slice(i,sequenceStart));let kind=line[sequenceStart+1];if(kind==="["){let end=sequenceStart+2;for(;end<line.length&&(line.charCodeAt(end)<64||line.charCodeAt(end)>126);)end++;line[end]==="m"&&applySgr(line.slice(sequenceStart+2,end)),i=end+1}else if(kind==="]"||kind==="_"||kind==="P"||kind==="^"){let bell=line.indexOf("\x07",sequenceStart+2),st=line.indexOf("\x1B\\",sequenceStart+2);if(bell===-1&&st===-1)break;i=bell!==-1&&(st===-1||bell<st)?bell+1:st+2}else i=sequenceStart+2}return cells})}function rotation(yaw,pitch,roll){let[sy,cy,sx,cx,sz,cz]=[Math.sin(yaw),Math.cos(yaw),Math.sin(pitch),Math.cos(pitch),Math.sin(roll),Math.cos(roll)],ry=[cy,0,sy,0,1,0,-sy,0,cy],rx=[1,0,0,0,cx,-sx,0,sx,cx],rz=[cz,-sz,0,sz,cz,0,0,0,1];return multiply(rz,multiply(rx,ry))}function multiply(a,b){let result=new Array(9);for(let row=0;row<3;row++)for(let column=0;column<3;column++)result[row*3+column]=a[row*3]*b[column]+a[row*3+1]*b[3+column]+a[row*3+2]*b[6+column];return result}var SPIN_RAMP=1.4,SPIN_SPEED=Math.PI*2/PUZZLE_CYCLE,SPIN_LINGER=.6,FIRST_FRONT_VIEW=PUZZLE_START+PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD/2;function baseSpinPhase(time){let elapsed=time-FLY_START;if(elapsed<=0)return 0;let u=elapsed/SPIN_RAMP;return u<1?SPIN_SPEED*SPIN_RAMP*(u**6-3*u**5+2.5*u**4):SPIN_SPEED*(SPIN_RAMP*.5+elapsed-SPIN_RAMP)}var SPIN_ALIGNMENT=Math.PI*2-baseSpinPhase(FIRST_FRONT_VIEW)%(Math.PI*2);function spinPhase(time){return baseSpinPhase(time)+SPIN_ALIGNMENT*smooth((time-FLY_START)/FLY_DURATION)}function spinAngle(time){let phase=spinPhase(time);return phase-SPIN_LINGER*Math.sin(phase)}var BlockRaster=class{bits=new Uint8Array(0);counts=new Uint8Array(0);rgb=new Float32Array(0);haloAmount=new Float32Array(0);haloRgb=new Float32Array(0);width=0;height=0;depth=new Float32Array(0);faceIds=new Uint16Array(0);dirty;haloDirty;cameraDistance;constructor(cameraDistance){this.cameraDistance=cameraDistance}render(width,height,pose,boxes,background,haloStrength){let dotWidth=width*2,dotHeight=height*4;if(width!==this.width||height!==this.height)this.width=width,this.height=height,this.bits=new Uint8Array(width*height),this.counts=new Uint8Array(width*height),this.rgb=new Float32Array(width*height*3),this.haloAmount=new Float32Array(width*height),this.haloRgb=new Float32Array(width*height*3),this.haloDirty=void 0,this.depth=new Float32Array(dotWidth*dotHeight).fill(1/0),this.faceIds=new Uint16Array(dotWidth*dotHeight),this.dirty=void 0;else if(this.dirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.dirty;for(let row=minY2;row<=maxY2;row++)this.bits.fill(0,row*width+minX2,row*width+maxX2+1),this.counts.fill(0,row*width+minX2,row*width+maxX2+1),this.rgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.dirty=void 0}if(this.haloDirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.haloDirty;for(let row=minY2;row<=maxY2;row++)this.haloAmount.fill(0,row*width+minX2,row*width+maxX2+1),this.haloRgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.haloDirty=void 0}let m=rotation(pose.yaw,pose.pitch,pose.roll),{centerX,centerY,scale}=pose,cameraDistance=this.cameraDistance,origin=[m[6]*cameraDistance,m[7]*cameraDistance,m[8]*cameraDistance],light=isLight(background),faces=this.visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,light);if(faces.length===0)return;let minX=dotWidth,minY=dotHeight,maxX=-1,maxY=-1;for(let face of faces)minX=Math.min(minX,face.minX),minY=Math.min(minY,face.minY),maxX=Math.max(maxX,face.maxX),maxY=Math.max(maxY,face.maxY);if(maxX<minX||maxY<minY)return;let depth=this.depth,faceIds=this.faceIds;for(let faceIndex=0;faceIndex<faces.length;faceIndex++){let face=faces[faceIndex],a=face.axis,u=(a+1)%3,v=(a+2)%3,originA=origin[a],originU=origin[u],originV=origin[v],stepA=m[a]/scale,stepU=m[u]/scale,stepV=m[v]/scale,sx=(face.minX+.5-centerX)/scale;for(let dotY=face.minY;dotY<=face.maxY;dotY++){let sy=(dotY+.5-centerY)/scale,directionA=m[a]*sx+m[3+a]*sy-m[6+a]*cameraDistance,directionU=m[u]*sx+m[3+u]*sy-m[6+u]*cameraDistance,directionV=m[v]*sx+m[3+v]*sy-m[6+v]*cameraDistance,index=dotY*dotWidth+face.minX;for(let dotX=face.minX;dotX<=face.maxX;dotX++,index++){let t=(face.plane-originA)/directionA;if(t>0&&t<depth[index]){let hitU=originU+t*directionU,hitV=originV+t*directionV;hitU>=face.uMin&&hitU<=face.uMax&&hitV>=face.vMin&&hitV<=face.vMax&&(depth[index]=t,faceIds[index]=faceIndex+1)}directionA+=stepA,directionU+=stepU,directionV+=stepV}}}let bits=this.bits,counts=this.counts,rgb=this.rgb,cellMinX=width,cellMinY=height,cellMaxX=-1,cellMaxY=-1;for(let dotY=minY;dotY<=maxY;dotY++){let index=dotY*dotWidth+minX;for(let dotX=minX;dotX<=maxX;dotX++,index++){let id=faceIds[index];if(id===0)continue;let face=faces[id-1],fog=clamp01(.15-cameraDistance*(1-depth[index])*.12)*(light?.5:1);faceIds[index]=0,depth[index]=1/0;let cellX=dotX>>1,cellY=dotY>>2,cell=cellY*width+cellX;bits[cell]|=DOT_BITS[(dotY&3)*2+(dotX&1)],counts[cell]++,rgb[cell*3]+=face.red+(background[0]-face.red)*fog,rgb[cell*3+1]+=face.green+(background[1]-face.green)*fog,rgb[cell*3+2]+=face.blue+(background[2]-face.blue)*fog,cellX<cellMinX&&(cellMinX=cellX),cellX>cellMaxX&&(cellMaxX=cellX),cellY<cellMinY&&(cellMinY=cellY),cellY>cellMaxY&&(cellMaxY=cellY)}}cellMaxX>=0&&(this.dirty={minX:cellMinX,minY:cellMinY,maxX:cellMaxX,maxY:cellMaxY}),haloStrength>0&&this.renderHalo(haloStrength)}renderHalo(strength){let cells=this.dirty;if(!cells)return;let{width,height,counts,rgb}=this,minX=Math.max(0,cells.minX-HALO_RADIUS_X),maxX=Math.min(width-1,cells.maxX+HALO_RADIUS_X),minY=Math.max(0,cells.minY-HALO_RADIUS_Y),maxY=Math.min(height-1,cells.maxY+HALO_RADIUS_Y),regionWidth=maxX-minX+1,tent=radius=>{let weights=Array.from({length:radius*2+1},(_,i)=>radius+1-Math.abs(i-radius)),total=weights.reduce((sum,weight)=>sum+weight,0);return weights.map(weight=>weight/total)},weightsX=tent(HALO_RADIUS_X),weightsY=tent(HALO_RADIUS_Y),rows=cells.maxY-cells.minY+1,horizontal=new Float32Array(rows*regionWidth*4);for(let y=cells.minY;y<=cells.maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dx=-HALO_RADIUS_X;dx<=HALO_RADIUS_X;dx++){let sourceX=x+dx;if(sourceX<cells.minX||sourceX>cells.maxX)continue;let source=y*width+sourceX,count=counts[source];if(count===0)continue;let weight=weightsX[dx+HALO_RADIUS_X]/8;coverage+=count*weight,red+=rgb[source*3]*weight,green+=rgb[source*3+1]*weight,blue+=rgb[source*3+2]*weight}let target=((y-cells.minY)*regionWidth+(x-minX))*4;horizontal[target]=coverage,horizontal[target+1]=red,horizontal[target+2]=green,horizontal[target+3]=blue}for(let y=minY;y<=maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dy=-HALO_RADIUS_Y;dy<=HALO_RADIUS_Y;dy++){let sourceY=y+dy;if(sourceY<cells.minY||sourceY>cells.maxY)continue;let weight=weightsY[dy+HALO_RADIUS_Y],source=((sourceY-cells.minY)*regionWidth+(x-minX))*4;coverage+=horizontal[source]*weight,red+=horizontal[source+1]*weight,green+=horizontal[source+2]*weight,blue+=horizontal[source+3]*weight}let target=y*width+x,count=counts[target];if(count>0&&count/8>coverage&&(coverage=count/8,red=rgb[target*3]/count*coverage,green=rgb[target*3+1]/count*coverage,blue=rgb[target*3+2]/count*coverage),coverage<=0)continue;let amount=Math.round(strength*Math.min(1,coverage)**.7*HALO_LEVELS)/HALO_LEVELS;amount<=0||(this.haloAmount[target]=amount,this.haloRgb[target*3]=Math.round(red/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+1]=Math.round(green/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+2]=Math.round(blue/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP)}this.haloDirty={minX,minY,maxX,maxY}}visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,lightBackground){let faces=[],cameraDistance=this.cameraDistance;for(let box of boxes)for(let a=0;a<3;a++){let u=(a+1)%3,v=(a+2)%3;for(let side of[-1,1]){let plane=side>0?box.max[a]:box.min[a];if((origin[a]-plane)*side<=0||boxes.some(other=>other!==box&&(side>0?other.min[a]:other.max[a])===plane&&other.min[u]<=box.min[u]&&other.max[u]>=box.max[u]&&other.min[v]<=box.min[v]&&other.max[v]>=box.max[v]))continue;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0,corner=[0,0,0];for(let cornerU of[box.min[u],box.max[u]])for(let cornerV of[box.min[v],box.max[v]]){corner[a]=plane,corner[u]=cornerU,corner[v]=cornerV;let x=m[0]*corner[0]+m[1]*corner[1]+m[2]*corner[2],y=m[3]*corner[0]+m[4]*corner[1]+m[5]*corner[2],z=m[6]*corner[0]+m[7]*corner[1]+m[8]*corner[2],perspective=pose.scale*cameraDistance/(cameraDistance-z),screenX=pose.centerX+x*perspective,screenY=pose.centerY+y*perspective;minX=Math.min(minX,screenX),minY=Math.min(minY,screenY),maxX=Math.max(maxX,screenX),maxY=Math.max(maxY,screenY)}let face={minX:Math.max(0,Math.floor(minX)),minY:Math.max(0,Math.floor(minY)),maxX:Math.min(dotWidth-1,Math.ceil(maxX)),maxY:Math.min(dotHeight-1,Math.ceil(maxY))};if(face.maxX<face.minX||face.maxY<face.minY)continue;let nx=m[a]*side,ny=m[3+a]*side,nz=m[6+a]*side,diffuse=Math.max(0,nx*LIGHT[0]+ny*LIGHT[1]+nz*LIGHT[2]),rim=Math.max(0,nx*.8-nz*.3),specular=lightBackground?0:Math.max(0,nx*HALF_VECTOR[0]+ny*HALF_VECTOR[1]+nz*HALF_VECTOR[2])**24*.6*255,light=lightBackground?Math.min(1,.55+diffuse*.45+rim*.1):.45+diffuse*.78+rim*.25;faces.push({axis:a,plane,uMin:box.min[u],uMax:box.max[u],vMin:box.min[v],vMax:box.max[v],...face,red:Math.min(255,box.color[0]*light+specular),green:Math.min(255,box.color[1]*light+specular),blue:Math.min(255,box.color[2]*light+specular)})}}return faces}},playing=!1;async function playEasterEgg3d(tui,screen,egg){if(playing)return;playing=!0;let reported=await tui.queryTerminalColors({timeoutMs:100}),dark=theme.appearance==="dark",toRgbTuple=(rgb,fallback)=>rgb?[rgb.r,rgb.g,rgb.b]:fallback,colors={foreground:toRgbTuple(reported.foreground,toRgb(theme.colors.text)),background:toRgbTuple(reported.background,dark?[0,0,0]:[255,255,255])};if(tui.hasOverlay()){playing=!1;return}let model=egg.kind==="armin"?arminModel(toRgb(theme.colors.accent)):piLogoModel({column:egg.column,row:egg.row}),animation=new EasterEgg3dAnimation(tui,screen,model,colors,()=>{playing=!1,overlay.hide()}),overlay=tui.showOverlay(animation,{anchor:"top-left",width:"100%",maxHeight:"100%"})}var EasterEgg3dAnimation=class{tui;screen;model;foreground;background;onDone;startTime=performance.now();lastRender=performance.now();timer;exit;shuffle;screenWidth=-1;screenHeight=-1;stars=[];cells=[];ansiCache=new Map;raster;constructor(tui,screen,model,colors,onDone){this.tui=tui,this.screen=screen,this.model=model,this.raster=new BlockRaster(model.cameraDistance),this.foreground=colors.foreground,this.background=colors.background,this.onDone=onDone,this.timer=setInterval(()=>{this.exit&&this.exitProgress()>=1||performance.now()-this.lastRender>1e3?this.finish():this.tui.requestRender()},FRAME_MS),this.timer.unref?.()}close(){if(this.exit){this.finish();return}let time=this.elapsed(),yaw=spinAngle(time),turn=Math.PI*2;this.exit={start:performance.now(),time,yaw,targetYaw:Math.ceil(yaw/turn)*turn,offsets:this.blockOffsets(time)}}handleInput(data){let keybindings=getKeybindings();(keybindings.matches(data,"tui.select.cancel")||keybindings.matches(data,"app.clear"))&&this.close()}handleMouse(event){return event.type==="click"&&this.close(),{handled:!0,render:!1}}invalidate(){this.screenWidth=-1,this.screenHeight=-1,this.ansiCache.clear()}render(width){let height=Math.max(1,this.tui.terminal.rows),foreground=this.foreground,background=this.background;this.lastRender=performance.now(),(width!==this.screenWidth||height!==this.screenHeight)&&(this.screenWidth=width,this.screenHeight=height,this.cells=this.prepareCells(width,foreground),this.stars=this.prepareStars(width,height));let dissolveTime,pose,hintAlpha,starAlpha,offsets;if(this.exit){let progress=this.exitProgress(),landing=clamp01(progress/.8),settle=1-smooth(landing);dissolveTime=Math.min(this.exit.time,DISSOLVE_END)*(1-progress),pose=this.pose(width,height,this.flyProgress(this.exit.time)*settle,this.exit.time),pose.yaw=this.exit.yaw+(this.exit.targetYaw-this.exit.yaw)*easeOut(landing),pose.pitch*=settle,pose.roll*=settle,hintAlpha=this.hintAlpha(this.exit.time)*(1-smooth(progress/.2)),starAlpha=this.starAlpha(this.exit.time)*(1-smooth(progress/.3));let gather=1-smooth(progress/.5);offsets=this.exit.offsets.map(([x,y,z])=>[x*gather,y*gather,z*gather])}else{let time=this.elapsed();dissolveTime=time,pose=this.pose(width,height,this.flyProgress(time),time),hintAlpha=this.hintAlpha(time),starAlpha=this.starAlpha(time),offsets=this.blockOffsets(time)}let{columns,rows}=this.model,boxes=this.model.blocks.map((block,index)=>{let[dx,dy,dz]=offsets[index],x=block.home[0]-columns/2+dx,y=block.home[1]-rows/2+dy;return{min:[x,y,dz-DEPTH/2],max:[x+1,y+1,dz+DEPTH/2],color:block.color}}),raster=this.raster;raster.render(width,height,pose,boxes,background,isLight(background)?LIGHT_HALO_STRENGTH:0);let halo=(index,base)=>{let amount=raster.haloAmount[index];if(amount<=0)return base;let color=raster.haloRgb;return mix(base??background,[color[index*3],color[index*3+1],color[index*3+2]],amount)},backgroundFade=smooth(dissolveTime/BACKGROUND_FADE),textFade=smooth(dissolveTime/.6)*.3,textActive=dissolveTime<DISSOLVE_END||backgroundFade<1,hint=this.hint(width,height,hintAlpha,background),frame=Math.floor(dissolveTime*14),now=this.elapsed(),starLevel=Math.round(starAlpha*STAR_ALPHA_LEVELS)/STAR_ALPHA_LEVELS,starfield=index=>{if(starLevel<=0)return;let star=this.stars[index];if(!star)return;let flicker=Math.round((.5+.5*Math.sin(now*star.speed+star.phase))*STAR_FLICKER_LEVELS)/STAR_FLICKER_LEVELS;return{text:star.glyph,fg:mix(background,mix(foreground,star.tint,.5),star.strength*(.7+.3*flicker)*starLevel)}},lines=[];for(let row=0;row<height;row++){let cells=this.cells[row]??[],line="",currentFg=-1,currentBg=-1,emit=(text,fg,bg)=>{let fgKey=fg?this.pack(fg):-1,bgKey=bg?this.pack(bg):-1;fgKey!==currentFg&&text!==" "&&(line+=fg?this.ansi(fgKey,!1):"\x1B[39m",currentFg=fgKey),bgKey!==currentBg&&(line+=bg?this.ansi(bgKey,!0):"\x1B[49m",currentBg=bgKey),line+=text};for(let column=0;column<width;column++){let index=row*width+column,cell=textActive?cells[column]:void 0,cellBg=halo(index,cell?.bg&&backgroundFade<1?mix(cell.bg,background,backgroundFade):void 0);if(hint&&row===hint.row&&column>=hint.start&&column<hint.start+hint.text.length){let offset=column-hint.start;emit(hint.text[offset],offset<hint.keyLength?hint.keyColor:hint.color,cellBg);continue}let dots=raster.bits[index];if(dots){let step=LOGO_COLOR_STEP*raster.counts[index],rgb=raster.rgb,color=[Math.round(rgb[index*3]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+1]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+2]/step)*LOGO_COLOR_STEP];emit(BRAILLE[dots],color,cellBg);continue}if(!cell){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let dust=(dissolveTime-cell.delay)/DUST_DURATION;if(dust<0&&cell.width===2&&!raster.bits[index+1]){emit(cell.text,mix(cell.fg,background,textFade),cellBg),column++;continue}if(dust<0&&cell.width===1){emit(cell.text,mix(cell.fg,background,textFade),cellBg);continue}let dotCount=dust<0?cell.ink:Math.round(cell.ink*(1-clamp01(dust)));if(dotCount<=0){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let bits=0,placed=0;for(let attempt=0;placed<dotCount&&attempt<32;attempt++){let bit=DOT_BITS[Math.floor(hash(cell.seed*7919+frame*131+attempt)*8)];bits&bit||(bits|=bit,placed++)}let fade=textFade+(1-textFade)*clamp01(dust)**.8;emit(BRAILLE[bits],mix(cell.fg,background,fade),cellBg)}lines.push(`${line}\x1B[0m`)}return lines}elapsed(){return(performance.now()-this.startTime)/1e3}exitProgress(){return this.exit?clamp01((performance.now()-this.exit.start)/1e3/EXIT_DURATION):0}finish(){this.timer&&(clearInterval(this.timer),this.timer=void 0,this.onDone())}blockOffsets(time){let blocks=this.model.blocks,home=()=>blocks.map(()=>[0,0,0]);if(time<PUZZLE_START)return home();let cycle=Math.floor((time-PUZZLE_START)/PUZZLE_CYCLE),local=time-PUZZLE_START-cycle*PUZZLE_CYCLE;this.shuffle?.cycle!==cycle&&(this.shuffle={cycle,steps:shuffleSteps(this.model,cycle)});let steps=this.shuffle.steps,offset=(position,index)=>{let block=blocks[index].home;return[position[0]-block[0],position[1]-block[1],position[2]-block[2]]},shuffleEnd=PUZZLE_STEP*PUZZLE_STEPS;if(local<shuffleEnd){let step=Math.floor(local/PUZZLE_STEP),progress=smooth((local-step*PUZZLE_STEP)/PUZZLE_STEP);return steps[step].map((from,index)=>{let a=offset(from,index),b=offset(steps[step+1][index],index);return[a[0]+(b[0]-a[0])*progress,a[1]+(b[1]-a[1])*progress,a[2]+(b[2]-a[2])*progress]})}if(local<shuffleEnd+PUZZLE_RETURN){let u=(local-shuffleEnd)/PUZZLE_RETURN,remaining=1-smooth(u),arc=Math.sin(Math.PI*clamp01(u))*.8;return steps[PUZZLE_STEPS].map((position,index)=>{let[x,y,z]=offset(position,index);return[x*remaining,y*remaining,z*remaining+(index%2===0?arc:-arc)]})}return home()}flyProgress(time){return smooth((time-FLY_START)/FLY_DURATION)}starAlpha(time){return smooth((time-STARS_START)/STARS_FADE)}hintAlpha(time){return smooth((time-FLY_START-FLY_DURATION)/HINT_FADE)}pose(width,height,progress,time){let{columns,rows,cameraDistance,radius,widthShare,origin}=this.model,reach=radius*(cameraDistance/(cameraDistance-radius)),startScale=origin?2*(cameraDistance-DEPTH/2)/cameraDistance:START_SCALE,endScale=Math.max(startScale,Math.min(width*2*widthShare,(height*4-8)*.48)/reach),endX=width,endY=height*2-2,startX=origin?origin.column*2+columns:endX,startY=origin?origin.row*4+rows:endY;return{centerX:startX+(endX-startX)*progress,centerY:startY+(endY-startY)*progress,scale:startScale*(endScale/startScale)**progress,yaw:spinAngle(time),pitch:.3*Math.sin(spinPhase(time))*progress,roll:.06*Math.sin(2*spinPhase(time))*progress}}hint(width,height,alpha,background){if(alpha<=0)return;let key=formatKeyText(getKeybindings().getKeys("tui.select.cancel")[0]??"escape"),text=`${key} to return`;if(!(text.length>width))return{row:height-2,start:Math.floor((width-text.length)/2),text,keyLength:key.length,keyColor:mix(background,toRgb(theme.colors.muted),alpha),color:mix(background,toRgb(theme.colors.dim),alpha)}}prepareStars(width,height){let stars=new Array(width*height);for(let index=0;index<width*height;index++){if(hash(index*3+20973)>=STAR_DENSITY)continue;let random=salt=>hash(index*7+salt*40503);stars[index]={glyph:BRAILLE[DOT_BITS[Math.floor(random(1)*8)]],tint:STAR_TINTS[Math.floor(random(2)*STAR_TINTS.length)],strength:.1+random(3)*.12,phase:random(4)*Math.PI*2,speed:.4+random(5)*.8}}return stars}prepareCells(width,foreground){let cells=parseScreen(this.screen,width,foreground,this.background),height=Math.max(1,this.tui.terminal.rows),{columns,rows,origin}=this.model,centerX=origin?origin.column+columns/2:width/2,centerY=origin?origin.row+rows/4:height/2,farthest=Math.hypot(Math.max(centerX,width-centerX),Math.max(centerY,height-centerY)*2);for(let row=0;row<cells.length;row++){let line=cells[row];for(let column=0;column<line.length;column++){let cell=line[column],owner=cell.width===0?line[column-1]:cell,seed=hash(row*65537+column);if(cell.width!==0){let distance=Math.hypot(column-centerX,(row-centerY)*2)/farthest;cell.delay=FLY_START+distance*WAVE_SPREAD+seed*WAVE_JITTER}else cell.delay=owner.delay;cell.seed=row*65537+column,cell.ink=glyphInk(owner.text,seed)}}if(origin)for(let row=origin.row;row<origin.row+Math.ceil(rows/2);row++){let line=cells[row];if(line)for(let column=origin.column;column<origin.column+columns;column++){let cell=line[column];cell&&(cell.text=" ",cell.width=1,cell.ink=0,cell.bg=void 0)}}return cells}pack(color){return Math.round(color[0])<<16|Math.round(color[1])<<8|Math.round(color[2])}ansi(key,isBackground){let cacheKey=key*2+(isBackground?1:0),value=this.ansiCache.get(cacheKey);if(value===void 0){let color=rgbColor(key>>16&255,key>>8&255,key&255),mode=theme.getColorMode();value=isBackground?backgroundAnsi(color,mode):foregroundAnsi(color,mode),this.ansiCache.set(cacheKey,value)}return value}};export{EasterEgg3dAnimation,playEasterEgg3d};
|