@e2b/cli 0.3.3 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -3
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -71,7 +71,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),Ue=H,N=ee);let oe={cod
|
|
|
71
71
|
`:`
|
|
72
72
|
`.charCodeAt(),n=typeof e=="string"?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,e.length-1)),e[e.length-1]===n&&(e=e.slice(0,e.length-1)),e}});var ML=E((Efe,qa)=>{"use strict";l();var Ya=require("path"),vL=vE(),xL=e=>{e={cwd:process.cwd(),path:process.env[vL()],execPath:process.execPath,...e};let t,n=Ya.resolve(e.cwd),r=[];for(;t!==n;)r.push(Ya.join(n,"node_modules/.bin")),t=n,n=Ya.resolve(n,"..");let i=Ya.resolve(e.cwd,e.execPath,"..");return r.push(i),r.concat(e.path).join(Ya.delimiter)};qa.exports=xL;qa.exports.default=xL;qa.exports.env=e=>{e={env:process.env,...e};let t={...e.env},n=vL({env:t});return e.path=t[n],t[n]=qa.exports(e),t}});var LL=E((gfe,UE)=>{"use strict";l();var wL=(e,t)=>{for(let n of Reflect.ownKeys(t))Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n));return e};UE.exports=wL;UE.exports.default=wL});var FL=E((Sfe,eu)=>{"use strict";l();var _X=LL(),Jc=new WeakMap,PL=(e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,r=0,i=e.displayName||e.name||"<anonymous>",s=function(...a){if(Jc.set(s,++r),r===1)n=e.apply(this,a),e=null;else if(t.throw===!0)throw new Error(`Function \`${i}\` can only be called once`);return n};return _X(s,e),Jc.set(s,r),s};eu.exports=PL;eu.exports.default=PL;eu.exports.callCount=e=>{if(!Jc.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Jc.get(e)}});var kL=E(tu=>{"use strict";l();Object.defineProperty(tu,"__esModule",{value:!0});tu.SIGNALS=void 0;var mX=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}];tu.SIGNALS=mX});var GE=E(_s=>{"use strict";l();Object.defineProperty(_s,"__esModule",{value:!0});_s.SIGRTMAX=_s.getRealtimeSignals=void 0;var pX=function(){let e=UL-BL+1;return Array.from({length:e},EX)};_s.getRealtimeSignals=pX;var EX=function(e,t){return{name:`SIGRT${t+1}`,number:BL+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}},BL=34,UL=64;_s.SIGRTMAX=UL});var GL=E(nu=>{"use strict";l();Object.defineProperty(nu,"__esModule",{value:!0});nu.getSignals=void 0;var fX=require("os"),gX=kL(),hX=GE(),SX=function(){let e=(0,hX.getRealtimeSignals)();return[...gX.SIGNALS,...e].map(TX)};nu.getSignals=SX;var TX=function({name:e,number:t,description:n,action:r,forced:i=!1,standard:s}){let{signals:{[e]:a}}=fX.constants,o=a!==void 0;return{name:e,number:o?a:t,description:n,supported:o,action:r,forced:i,standard:s}}});var YL=E(ms=>{"use strict";l();Object.defineProperty(ms,"__esModule",{value:!0});ms.signalsByNumber=ms.signalsByName=void 0;var bX=require("os"),HL=GL(),DX=GE(),CX=function(){return(0,HL.getSignals)().reduce(RX,{})},RX=function(e,{name:t,number:n,description:r,supported:i,action:s,forced:a,standard:o}){return{...e,[t]:{name:t,number:n,description:r,supported:i,action:s,forced:a,standard:o}}},AX=CX();ms.signalsByName=AX;var OX=function(){let e=(0,HL.getSignals)(),t=DX.SIGRTMAX+1,n=Array.from({length:t},(r,i)=>NX(i,e));return Object.assign({},...n)},NX=function(e,t){let n=yX(e,t);if(n===void 0)return{};let{name:r,description:i,supported:s,action:a,forced:o,standard:c}=n;return{[e]:{name:r,number:e,description:i,supported:s,action:a,forced:o,standard:c}}},yX=function(e,t){let n=t.find(({name:r})=>bX.constants.signals[r]===e);return n!==void 0?n:t.find(r=>r.number===e)},IX=OX();ms.signalsByNumber=IX});var $L=E((Ife,qL)=>{"use strict";l();var{signalsByName:vX}=YL(),xX=({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:i,exitCode:s,isCanceled:a})=>e?`timed out after ${t} milliseconds`:a?"was canceled":n!==void 0?`failed with ${n}`:r!==void 0?`was killed with ${r} (${i})`:s!==void 0?`failed with exit code ${s}`:"failed",MX=({stdout:e,stderr:t,all:n,error:r,signal:i,exitCode:s,command:a,escapedCommand:o,timedOut:c,isCanceled:u,killed:d,parsed:{options:{timeout:m}}})=>{s=s===null?void 0:s,i=i===null?void 0:i;let g=i===void 0?void 0:vX[i].description,S=r&&r.code,C=`Command ${xX({timedOut:c,timeout:m,errorCode:S,signal:i,signalDescription:g,exitCode:s,isCanceled:u})}: ${a}`,I=Object.prototype.toString.call(r)==="[object Error]",F=I?`${C}
|
|
73
73
|
${r.message}`:C,U=[F,t,e].filter(Boolean).join(`
|
|
74
|
-
`);return I?(r.originalMessage=r.message,r.message=U):r=new Error(U),r.shortMessage=F,r.command=a,r.escapedCommand=o,r.exitCode=s,r.signal=i,r.signalDescription=g,r.stdout=e,r.stderr=t,n!==void 0&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!c,r.isCanceled=u,r.killed=d&&!c,r};qL.exports=MX});var WL=E((xfe,HE)=>{"use strict";l();var ru=["stdin","stdout","stderr"],wX=e=>ru.some(t=>e[t]!==void 0),VL=e=>{if(!e)return;let{stdio:t}=e;if(t===void 0)return ru.map(r=>e[r]);if(wX(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${ru.map(r=>`\`${r}\``).join(", ")}`);if(typeof t=="string")return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);let n=Math.max(t.length,ru.length);return Array.from({length:n},(r,i)=>t[i])};HE.exports=VL;HE.exports.node=e=>{let t=VL(e);return t==="ipc"?"ipc":t===void 0||typeof t=="string"?[t,t,t,"ipc"]:t.includes("ipc")?t:[...t,"ipc"]}});var KL=E((wfe,iu)=>{"use strict";l();iu.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&iu.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&iu.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var $E=E((Pfe,fs)=>{"use strict";l();var ke=global.process,oi=function(e){return e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function"};oi(ke)?(zL=require("assert"),ps=KL(),QL=/^win/i.test(ke.platform),$a=require("events"),typeof $a!="function"&&($a=$a.EventEmitter),ke.__signal_exit_emitter__?ot=ke.__signal_exit_emitter__:(ot=ke.__signal_exit_emitter__=new $a,ot.count=0,ot.emitted={}),ot.infinite||(ot.setMaxListeners(1/0),ot.infinite=!0),fs.exports=function(e,t){if(!oi(global.process))return function(){};zL.equal(typeof e,"function","a callback must be provided for exit handler"),Es===!1&&YE();var n="exit";t&&t.alwaysLast&&(n="afterexit");var r=function(){ot.removeListener(n,e),ot.listeners("exit").length===0&&ot.listeners("afterexit").length===0&&su()};return ot.on(n,e),r},su=function(){!Es||!oi(global.process)||(Es=!1,ps.forEach(function(t){try{ke.removeListener(t,au[t])}catch{}}),ke.emit=ou,ke.reallyExit=qE,ot.count-=1)},fs.exports.unload=su,li=function(t,n,r){ot.emitted[t]||(ot.emitted[t]=!0,ot.emit(t,n,r))},au={},ps.forEach(function(e){au[e]=function(){if(oi(global.process)){var n=ke.listeners(e);n.length===ot.count&&(su(),li("exit",null,e),li("afterexit",null,e),QL&&e==="SIGHUP"&&(e="SIGINT"),ke.kill(ke.pid,e))}}}),fs.exports.signals=function(){return ps},Es=!1,YE=function(){Es||!oi(global.process)||(Es=!0,ot.count+=1,ps=ps.filter(function(t){try{return ke.on(t,au[t]),!0}catch{return!1}}),ke.emit=jL,ke.reallyExit=XL)},fs.exports.load=YE,qE=ke.reallyExit,XL=function(t){oi(global.process)&&(ke.exitCode=t||0,li("exit",ke.exitCode,null),li("afterexit",ke.exitCode,null),qE.call(ke,ke.exitCode))},ou=ke.emit,jL=function(t,n){if(t==="exit"&&oi(global.process)){n!==void 0&&(ke.exitCode=n);var r=ou.apply(this,arguments);return li("exit",ke.exitCode,null),li("afterexit",ke.exitCode,null),r}else return ou.apply(this,arguments)}):fs.exports=function(){return function(){}};var zL,ps,QL,$a,ot,su,li,au,Es,YE,qE,XL,ou,jL});var JL=E((kfe,ZL)=>{"use strict";l();var LX=require("os"),PX=$E(),FX=1e3*5,kX=(e,t="SIGTERM",n={})=>{let r=e(t);return BX(e,t,n,r),r},BX=(e,t,n,r)=>{if(!UX(t,n,r))return;let i=HX(n),s=setTimeout(()=>{e("SIGKILL")},i);s.unref&&s.unref()},UX=(e,{forceKillAfterTimeout:t},n)=>GX(e)&&t!==!1&&n,GX=e=>e===LX.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM",HX=({forceKillAfterTimeout:e=!0})=>{if(e===!0)return FX;if(!Number.isFinite(e)||e<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`);return e},YX=(e,t)=>{e.kill()&&(t.isCanceled=!0)},qX=(e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},$X=(e,{timeout:t,killSignal:n="SIGTERM"},r)=>{if(t===0||t===void 0)return r;let i,s=new Promise((o,c)=>{i=setTimeout(()=>{qX(e,n,c)},t)}),a=r.finally(()=>{clearTimeout(i)});return Promise.race([s,a])},VX=({timeout:e})=>{if(e!==void 0&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},WX=async(e,{cleanup:t,detached:n},r)=>{if(!t||n)return r;let i=PX(()=>{e.kill()});return r.finally(()=>{i()})};ZL.exports={spawnedKill:kX,spawnedCancel:YX,setupTimeout:$X,validateTimeout:VX,setExitHandler:WX}});var t9=E((Ufe,e9)=>{"use strict";l();var Tn=e=>e!==null&&typeof e=="object"&&typeof e.pipe=="function";Tn.writable=e=>Tn(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object";Tn.readable=e=>Tn(e)&&e.readable!==!1&&typeof e._read=="function"&&typeof e._readableState=="object";Tn.duplex=e=>Tn.writable(e)&&Tn.readable(e);Tn.transform=e=>Tn.duplex(e)&&typeof e._transform=="function";e9.exports=Tn});var r9=E((Hfe,n9)=>{"use strict";l();var{PassThrough:KX}=require("stream");n9.exports=e=>{e={...e};let{array:t}=e,{encoding:n}=e,r=n==="buffer",i=!1;t?i=!(n||r):n=n||"utf8",r&&(n=null);let s=new KX({objectMode:i});n&&s.setEncoding(n);let a=0,o=[];return s.on("data",c=>{o.push(c),i?a=o.length:a+=c.length}),s.getBufferedValue=()=>t?o:r?Buffer.concat(o,a):o.join(""),s.getBufferedLength=()=>a,s}});var WE=E((qfe,Va)=>{"use strict";l();var{constants:zX}=require("buffer"),QX=require("stream"),{promisify:XX}=require("util"),jX=r9(),ZX=XX(QX.pipeline),lu=class extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};async function VE(e,t){if(!e)throw new Error("Expected a stream");t={maxBuffer:1/0,...t};let{maxBuffer:n}=t,r=jX(t);return await new Promise((i,s)=>{let a=o=>{o&&r.getBufferedLength()<=zX.MAX_LENGTH&&(o.bufferedData=r.getBufferedValue()),s(o)};(async()=>{try{await ZX(e,r),i()}catch(o){a(o)}})(),r.on("data",()=>{r.getBufferedLength()>n&&a(new lu)})}),r.getBufferedValue()}Va.exports=VE;Va.exports.buffer=(e,t)=>VE(e,{...t,encoding:"buffer"});Va.exports.array=(e,t)=>VE(e,{...t,array:!0});Va.exports.MaxBufferError=lu});var KE=E((Vfe,i9)=>{"use strict";l();var{PassThrough:JX}=require("stream");i9.exports=function(){var e=[],t=new JX({objectMode:!0});return t.setMaxListeners(0),t.add=n,t.isEmpty=r,t.on("unpipe",i),Array.prototype.slice.call(arguments).forEach(n),t;function n(s){return Array.isArray(s)?(s.forEach(n),this):(e.push(s),s.once("end",i.bind(null,s)),s.once("error",t.emit.bind(t,"error")),s.pipe(t,{end:!1}),this)}function r(){return e.length==0}function i(s){e=e.filter(function(a){return a!==s}),!e.length&&t.readable&&t.end()}}});var l9=E((Kfe,o9)=>{"use strict";l();var a9=t9(),s9=WE(),ej=KE(),tj=(e,t)=>{t===void 0||e.stdin===void 0||(a9(t)?t.pipe(e.stdin):e.stdin.end(t))},nj=(e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;let n=ej();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},zE=async(e,t)=>{if(e){e.destroy();try{return await t}catch(n){return n.bufferedData}}},QE=(e,{encoding:t,buffer:n,maxBuffer:r})=>{if(!(!e||!n))return t?s9(e,{encoding:t,maxBuffer:r}):s9.buffer(e,{maxBuffer:r})},rj=async({stdout:e,stderr:t,all:n},{encoding:r,buffer:i,maxBuffer:s},a)=>{let o=QE(e,{encoding:r,buffer:i,maxBuffer:s}),c=QE(t,{encoding:r,buffer:i,maxBuffer:s}),u=QE(n,{encoding:r,buffer:i,maxBuffer:s*2});try{return await Promise.all([a,o,c,u])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},zE(e,o),zE(t,c),zE(n,u)])}},ij=({input:e})=>{if(a9(e))throw new TypeError("The `input` option cannot be a stream in sync mode")};o9.exports={handleInput:tj,makeAllStream:nj,getSpawnedResult:rj,validateInputSync:ij}});var u9=E((Qfe,c9)=>{"use strict";l();var sj=(async()=>{})().constructor.prototype,aj=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(sj,e)]),oj=(e,t)=>{for(let[n,r]of aj){let i=typeof t=="function"?(...s)=>Reflect.apply(r.value,t(),s):r.value.bind(t);Reflect.defineProperty(e,n,{...r,value:i})}return e},lj=e=>new Promise((t,n)=>{e.on("exit",(r,i)=>{t({exitCode:r,signal:i})}),e.on("error",r=>{n(r)}),e.stdin&&e.stdin.on("error",r=>{n(r)})});c9.exports={mergePromise:oj,getSpawnedPromise:lj}});var m9=E((jfe,_9)=>{"use strict";l();var d9=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],cj=/^[\w.-]+$/,uj=/"/g,dj=e=>typeof e!="string"||cj.test(e)?e:`"${e.replace(uj,'\\"')}"`,_j=(e,t)=>d9(e,t).join(" "),mj=(e,t)=>d9(e,t).map(n=>dj(n)).join(" "),pj=/ +/g,Ej=e=>{let t=[];for(let n of e.trim().split(pj)){let r=t[t.length-1];r&&r.endsWith("\\")?t[t.length-1]=`${r.slice(0,-1)} ${n}`:t.push(n)}return t};_9.exports={joinCommand:_j,getEscapedCommand:mj,parseCommand:Ej}});var T9=E((Jfe,gs)=>{"use strict";l();var fj=require("path"),XE=require("child_process"),gj=BE(),hj=IL(),Sj=ML(),Tj=FL(),cu=$L(),E9=WL(),{spawnedKill:bj,spawnedCancel:Dj,setupTimeout:Cj,validateTimeout:Rj,setExitHandler:Aj}=JL(),{handleInput:Oj,getSpawnedResult:Nj,makeAllStream:yj,validateInputSync:Ij}=l9(),{mergePromise:p9,getSpawnedPromise:vj}=u9(),{joinCommand:f9,parseCommand:g9,getEscapedCommand:h9}=m9(),xj=1e3*1e3*100,Mj=({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:i})=>{let s=t?{...process.env,...e}:e;return n?Sj.env({env:s,cwd:r,execPath:i}):s},S9=(e,t,n={})=>{let r=gj._parse(e,t,n);return e=r.command,t=r.args,n=r.options,n={maxBuffer:xj,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||process.cwd(),execPath:process.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,...n},n.env=Mj(n),n.stdio=E9(n),process.platform==="win32"&&fj.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},Wa=(e,t,n)=>typeof t!="string"&&!Buffer.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?hj(t):t,uu=(e,t,n)=>{let r=S9(e,t,n),i=f9(e,t),s=h9(e,t);Rj(r.options);let a;try{a=XE.spawn(r.file,r.args,r.options)}catch(S){let h=new XE.ChildProcess,C=Promise.reject(cu({error:S,stdout:"",stderr:"",all:"",command:i,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return p9(h,C)}let o=vj(a),c=Cj(a,r.options,o),u=Aj(a,r.options,c),d={isCanceled:!1};a.kill=bj.bind(null,a.kill.bind(a)),a.cancel=Dj.bind(null,a,d);let g=Tj(async()=>{let[{error:S,exitCode:h,signal:C,timedOut:I},F,U,B]=await Nj(a,r.options,u),w=Wa(r.options,F),Y=Wa(r.options,U),k=Wa(r.options,B);if(S||h!==0||C!==null){let q=cu({error:S,exitCode:h,signal:C,stdout:w,stderr:Y,all:k,command:i,escapedCommand:s,parsed:r,timedOut:I,isCanceled:d.isCanceled,killed:a.killed});if(!r.options.reject)return q;throw q}return{command:i,escapedCommand:s,exitCode:0,stdout:w,stderr:Y,all:k,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return Oj(a,r.options.input),a.all=yj(a,r.options),p9(a,g)};gs.exports=uu;gs.exports.sync=(e,t,n)=>{let r=S9(e,t,n),i=f9(e,t),s=h9(e,t);Ij(r.options);let a;try{a=XE.spawnSync(r.file,r.args,r.options)}catch(u){throw cu({error:u,stdout:"",stderr:"",all:"",command:i,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1})}let o=Wa(r.options,a.stdout,a.error),c=Wa(r.options,a.stderr,a.error);if(a.error||a.status!==0||a.signal!==null){let u=cu({stdout:o,stderr:c,error:a.error,signal:a.signal,exitCode:a.status,command:i,escapedCommand:s,parsed:r,timedOut:a.error&&a.error.code==="ETIMEDOUT",isCanceled:!1,killed:a.signal!==null});if(!r.options.reject)return u;throw u}return{command:i,escapedCommand:s,exitCode:0,stdout:o,stderr:c,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}};gs.exports.command=(e,t)=>{let[n,...r]=g9(e);return uu(n,r,t)};gs.exports.commandSync=(e,t)=>{let[n,...r]=g9(e);return uu.sync(n,r,t)};gs.exports.node=(e,t,n={})=>{t&&!Array.isArray(t)&&typeof t=="object"&&(n=t,t=[]);let r=E9.node(n),i=process.execArgv.filter(o=>!o.startsWith("--inspect")),{nodePath:s=process.execPath,nodeOptions:a=i}=n;return uu(s,[...a,e,...Array.isArray(t)?t:[]],{...n,stdin:void 0,stdout:void 0,stderr:void 0,stdio:r,shell:!1})}});var AZ={};Nu(AZ,{pkg:()=>Ru});module.exports=qP(AZ);l();var I2=J(require("update-notifier"));var yu={};Nu(yu,{author:()=>QP,bin:()=>r5,bugs:()=>XP,default:()=>a5,dependencies:()=>i5,description:()=>WP,devDependencies:()=>t5,engines:()=>s5,files:()=>n5,homepage:()=>KP,license:()=>zP,name:()=>VP,publishConfig:()=>ZP,repository:()=>jP,scripts:()=>e5,sideEffects:()=>JP,version:()=>Iu});var VP="@e2b/cli",Iu="0.3.3",WP="CLI for managing e2b sandbox templates",KP="https://e2b.dev",zP="MIT",QP={name:"FoundryLabs, Inc.",email:"hello@e2b.dev",url:"https://e2b.dev"},XP="https://github.com/e2b-dev/e2b/issues",jP={type:"git",url:"https://github.com/e2b-dev/e2b",directory:"packages/cli"},ZP={access:"public"},JP=!1,e5={prepublishOnly:"pnpm build",build:"tsc --noEmit --skipLibCheck && tsup --minify",dev:"tsup --watch",test:"pnpm build && cd testground/demo-basic && ../../dist/index.js template build","check-deps":"knip","update-deps":"ncu -u && pnpm i"},t5={"@types/inquirer":"^9.0.7","@types/node":"^18.18.6","@types/tar-fs":"^2.0.3","@types/update-notifier":"6.0.5",knip:"^2.33.4","npm-check-updates":"^16.14.6",tsup:"^7.2.0",typescript:"^5.2.2",vitest:"^0.34.6"},n5=["dist","LICENSE","README","package.json"],r5={e2b:"dist/index.js"},i5={"@balena/dockerignore":"^1.0.2","@iarna/toml":"^2.2.5","@nodelib/fs.walk":"^2.0.0","async-listen":"^3.0.1",boxen:"^7.1.1",chalk:"^5.3.0","cli-highlight":"^2.1.11",commander:"^11.1.0","console-table-printer":"^2.11.2",e2b:"^0.12.3",ignore:"^5.2.4",inquirer:"^9.2.12",open:"^9.1.0","strip-ansi":"^7.1.0","tar-fs":"^3.0.4","update-notifier":"5.1.0",yup:"^1.3.2"},s5={node:">=18"},a5={name:VP,version:Iu,description:WP,homepage:KP,license:zP,author:QP,bugs:XP,repository:jP,publishConfig:ZP,sideEffects:JP,scripts:e5,devDependencies:t5,files:n5,bin:r5,dependencies:i5,engines:s5};l();l();var W1=J(V1(),1),{program:qZ,createCommand:$Z,createArgument:VZ,createOption:WZ,CommanderError:KZ,InvalidArgumentError:zZ,InvalidOptionArgumentError:QZ,Command:Ae,Argument:XZ,Option:ci,Help:jZ}=W1.default;l();l();l();var K1=(e=0)=>t=>`\x1B[${t+e}m`,z1=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,Q1=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,Pe={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},JZ=Object.keys(Pe.modifier),R5=Object.keys(Pe.color),A5=Object.keys(Pe.bgColor),eJ=[...R5,...A5];function O5(){let e=new Map;for(let[t,n]of Object.entries(Pe)){for(let[r,i]of Object.entries(n))Pe[r]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},n[r]=Pe[r],e.set(i[0],i[1]);Object.defineProperty(Pe,t,{value:n,enumerable:!1})}return Object.defineProperty(Pe,"codes",{value:e,enumerable:!1}),Pe.color.close="\x1B[39m",Pe.bgColor.close="\x1B[49m",Pe.color.ansi=K1(),Pe.color.ansi256=z1(),Pe.color.ansi16m=Q1(),Pe.bgColor.ansi=K1(10),Pe.bgColor.ansi256=z1(10),Pe.bgColor.ansi16m=Q1(10),Object.defineProperties(Pe,{rgbToAnsi256:{value(t,n,r){return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));let i=Number.parseInt(r,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:t=>Pe.rgbToAnsi256(...Pe.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,i;if(t>=232)n=((t-232)*10+8)/255,r=n,i=n;else{t-=16;let o=t%36;n=Math.floor(t/36)/5,r=Math.floor(o/6)/5,i=o%6/5}let s=Math.max(n,r,i)*2;if(s===0)return 30;let a=30+(Math.round(i)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(t,n,r)=>Pe.ansi256ToAnsi(Pe.rgbToAnsi256(t,n,r)),enumerable:!1},hexToAnsi:{value:t=>Pe.ansi256ToAnsi(Pe.hexToAnsi256(t)),enumerable:!1}}),Pe}var N5=O5(),Qt=N5;l();var so=J(require("process"),1),j1=J(require("os"),1),qu=J(require("tty"),1);function kt(e,t=globalThis.Deno?globalThis.Deno.args:so.default.argv){let n=e.startsWith("-")?"":e.length===1?"-":"--",r=t.indexOf(n+e),i=t.indexOf("--");return r!==-1&&(i===-1||r<i)}var{env:Ge}=so.default,io;kt("no-color")||kt("no-colors")||kt("color=false")||kt("color=never")?io=0:(kt("color")||kt("colors")||kt("color=true")||kt("color=always"))&&(io=1);function y5(){if("FORCE_COLOR"in Ge)return Ge.FORCE_COLOR==="true"?1:Ge.FORCE_COLOR==="false"?0:Ge.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(Ge.FORCE_COLOR,10),3)}function I5(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function v5(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=y5();r!==void 0&&(io=r);let i=n?io:r;if(i===0)return 0;if(n){if(kt("color=16m")||kt("color=full")||kt("color=truecolor"))return 3;if(kt("color=256"))return 2}if("TF_BUILD"in Ge&&"AGENT_NAME"in Ge)return 1;if(e&&!t&&i===void 0)return 0;let s=i||0;if(Ge.TERM==="dumb")return s;if(so.default.platform==="win32"){let a=j1.default.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in Ge)return"GITHUB_ACTIONS"in Ge||"GITEA_ACTIONS"in Ge?3:["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(a=>a in Ge)||Ge.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in Ge)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Ge.TEAMCITY_VERSION)?1:0;if(Ge.COLORTERM==="truecolor"||Ge.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in Ge){let a=Number.parseInt((Ge.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Ge.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Ge.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Ge.TERM)||"COLORTERM"in Ge?1:s}function X1(e,t={}){let n=v5(e,{streamIsTTY:e&&e.isTTY,...t});return I5(n)}var x5={stdout:X1({isTTY:qu.default.isatty(1)}),stderr:X1({isTTY:qu.default.isatty(2)})},Z1=x5;l();function J1(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,s=0,a="";do a+=e.slice(s,r)+t+n,s=r+i,r=e.indexOf(t,s);while(r!==-1);return a+=e.slice(s),a}function ef(e,t,n,r){let i=0,s="";do{let a=e[r-1]==="\r";s+=e.slice(i,a?r-1:r)+t+(a?`\r
|
|
74
|
+
`);return I?(r.originalMessage=r.message,r.message=U):r=new Error(U),r.shortMessage=F,r.command=a,r.escapedCommand=o,r.exitCode=s,r.signal=i,r.signalDescription=g,r.stdout=e,r.stderr=t,n!==void 0&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!c,r.isCanceled=u,r.killed=d&&!c,r};qL.exports=MX});var WL=E((xfe,HE)=>{"use strict";l();var ru=["stdin","stdout","stderr"],wX=e=>ru.some(t=>e[t]!==void 0),VL=e=>{if(!e)return;let{stdio:t}=e;if(t===void 0)return ru.map(r=>e[r]);if(wX(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${ru.map(r=>`\`${r}\``).join(", ")}`);if(typeof t=="string")return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);let n=Math.max(t.length,ru.length);return Array.from({length:n},(r,i)=>t[i])};HE.exports=VL;HE.exports.node=e=>{let t=VL(e);return t==="ipc"?"ipc":t===void 0||typeof t=="string"?[t,t,t,"ipc"]:t.includes("ipc")?t:[...t,"ipc"]}});var KL=E((wfe,iu)=>{"use strict";l();iu.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&iu.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&iu.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var $E=E((Pfe,fs)=>{"use strict";l();var ke=global.process,oi=function(e){return e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function"};oi(ke)?(zL=require("assert"),ps=KL(),QL=/^win/i.test(ke.platform),$a=require("events"),typeof $a!="function"&&($a=$a.EventEmitter),ke.__signal_exit_emitter__?ot=ke.__signal_exit_emitter__:(ot=ke.__signal_exit_emitter__=new $a,ot.count=0,ot.emitted={}),ot.infinite||(ot.setMaxListeners(1/0),ot.infinite=!0),fs.exports=function(e,t){if(!oi(global.process))return function(){};zL.equal(typeof e,"function","a callback must be provided for exit handler"),Es===!1&&YE();var n="exit";t&&t.alwaysLast&&(n="afterexit");var r=function(){ot.removeListener(n,e),ot.listeners("exit").length===0&&ot.listeners("afterexit").length===0&&su()};return ot.on(n,e),r},su=function(){!Es||!oi(global.process)||(Es=!1,ps.forEach(function(t){try{ke.removeListener(t,au[t])}catch{}}),ke.emit=ou,ke.reallyExit=qE,ot.count-=1)},fs.exports.unload=su,li=function(t,n,r){ot.emitted[t]||(ot.emitted[t]=!0,ot.emit(t,n,r))},au={},ps.forEach(function(e){au[e]=function(){if(oi(global.process)){var n=ke.listeners(e);n.length===ot.count&&(su(),li("exit",null,e),li("afterexit",null,e),QL&&e==="SIGHUP"&&(e="SIGINT"),ke.kill(ke.pid,e))}}}),fs.exports.signals=function(){return ps},Es=!1,YE=function(){Es||!oi(global.process)||(Es=!0,ot.count+=1,ps=ps.filter(function(t){try{return ke.on(t,au[t]),!0}catch{return!1}}),ke.emit=jL,ke.reallyExit=XL)},fs.exports.load=YE,qE=ke.reallyExit,XL=function(t){oi(global.process)&&(ke.exitCode=t||0,li("exit",ke.exitCode,null),li("afterexit",ke.exitCode,null),qE.call(ke,ke.exitCode))},ou=ke.emit,jL=function(t,n){if(t==="exit"&&oi(global.process)){n!==void 0&&(ke.exitCode=n);var r=ou.apply(this,arguments);return li("exit",ke.exitCode,null),li("afterexit",ke.exitCode,null),r}else return ou.apply(this,arguments)}):fs.exports=function(){return function(){}};var zL,ps,QL,$a,ot,su,li,au,Es,YE,qE,XL,ou,jL});var JL=E((kfe,ZL)=>{"use strict";l();var LX=require("os"),PX=$E(),FX=1e3*5,kX=(e,t="SIGTERM",n={})=>{let r=e(t);return BX(e,t,n,r),r},BX=(e,t,n,r)=>{if(!UX(t,n,r))return;let i=HX(n),s=setTimeout(()=>{e("SIGKILL")},i);s.unref&&s.unref()},UX=(e,{forceKillAfterTimeout:t},n)=>GX(e)&&t!==!1&&n,GX=e=>e===LX.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM",HX=({forceKillAfterTimeout:e=!0})=>{if(e===!0)return FX;if(!Number.isFinite(e)||e<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`);return e},YX=(e,t)=>{e.kill()&&(t.isCanceled=!0)},qX=(e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},$X=(e,{timeout:t,killSignal:n="SIGTERM"},r)=>{if(t===0||t===void 0)return r;let i,s=new Promise((o,c)=>{i=setTimeout(()=>{qX(e,n,c)},t)}),a=r.finally(()=>{clearTimeout(i)});return Promise.race([s,a])},VX=({timeout:e})=>{if(e!==void 0&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},WX=async(e,{cleanup:t,detached:n},r)=>{if(!t||n)return r;let i=PX(()=>{e.kill()});return r.finally(()=>{i()})};ZL.exports={spawnedKill:kX,spawnedCancel:YX,setupTimeout:$X,validateTimeout:VX,setExitHandler:WX}});var t9=E((Ufe,e9)=>{"use strict";l();var Tn=e=>e!==null&&typeof e=="object"&&typeof e.pipe=="function";Tn.writable=e=>Tn(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object";Tn.readable=e=>Tn(e)&&e.readable!==!1&&typeof e._read=="function"&&typeof e._readableState=="object";Tn.duplex=e=>Tn.writable(e)&&Tn.readable(e);Tn.transform=e=>Tn.duplex(e)&&typeof e._transform=="function";e9.exports=Tn});var r9=E((Hfe,n9)=>{"use strict";l();var{PassThrough:KX}=require("stream");n9.exports=e=>{e={...e};let{array:t}=e,{encoding:n}=e,r=n==="buffer",i=!1;t?i=!(n||r):n=n||"utf8",r&&(n=null);let s=new KX({objectMode:i});n&&s.setEncoding(n);let a=0,o=[];return s.on("data",c=>{o.push(c),i?a=o.length:a+=c.length}),s.getBufferedValue=()=>t?o:r?Buffer.concat(o,a):o.join(""),s.getBufferedLength=()=>a,s}});var WE=E((qfe,Va)=>{"use strict";l();var{constants:zX}=require("buffer"),QX=require("stream"),{promisify:XX}=require("util"),jX=r9(),ZX=XX(QX.pipeline),lu=class extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};async function VE(e,t){if(!e)throw new Error("Expected a stream");t={maxBuffer:1/0,...t};let{maxBuffer:n}=t,r=jX(t);return await new Promise((i,s)=>{let a=o=>{o&&r.getBufferedLength()<=zX.MAX_LENGTH&&(o.bufferedData=r.getBufferedValue()),s(o)};(async()=>{try{await ZX(e,r),i()}catch(o){a(o)}})(),r.on("data",()=>{r.getBufferedLength()>n&&a(new lu)})}),r.getBufferedValue()}Va.exports=VE;Va.exports.buffer=(e,t)=>VE(e,{...t,encoding:"buffer"});Va.exports.array=(e,t)=>VE(e,{...t,array:!0});Va.exports.MaxBufferError=lu});var KE=E((Vfe,i9)=>{"use strict";l();var{PassThrough:JX}=require("stream");i9.exports=function(){var e=[],t=new JX({objectMode:!0});return t.setMaxListeners(0),t.add=n,t.isEmpty=r,t.on("unpipe",i),Array.prototype.slice.call(arguments).forEach(n),t;function n(s){return Array.isArray(s)?(s.forEach(n),this):(e.push(s),s.once("end",i.bind(null,s)),s.once("error",t.emit.bind(t,"error")),s.pipe(t,{end:!1}),this)}function r(){return e.length==0}function i(s){e=e.filter(function(a){return a!==s}),!e.length&&t.readable&&t.end()}}});var l9=E((Kfe,o9)=>{"use strict";l();var a9=t9(),s9=WE(),ej=KE(),tj=(e,t)=>{t===void 0||e.stdin===void 0||(a9(t)?t.pipe(e.stdin):e.stdin.end(t))},nj=(e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;let n=ej();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},zE=async(e,t)=>{if(e){e.destroy();try{return await t}catch(n){return n.bufferedData}}},QE=(e,{encoding:t,buffer:n,maxBuffer:r})=>{if(!(!e||!n))return t?s9(e,{encoding:t,maxBuffer:r}):s9.buffer(e,{maxBuffer:r})},rj=async({stdout:e,stderr:t,all:n},{encoding:r,buffer:i,maxBuffer:s},a)=>{let o=QE(e,{encoding:r,buffer:i,maxBuffer:s}),c=QE(t,{encoding:r,buffer:i,maxBuffer:s}),u=QE(n,{encoding:r,buffer:i,maxBuffer:s*2});try{return await Promise.all([a,o,c,u])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},zE(e,o),zE(t,c),zE(n,u)])}},ij=({input:e})=>{if(a9(e))throw new TypeError("The `input` option cannot be a stream in sync mode")};o9.exports={handleInput:tj,makeAllStream:nj,getSpawnedResult:rj,validateInputSync:ij}});var u9=E((Qfe,c9)=>{"use strict";l();var sj=(async()=>{})().constructor.prototype,aj=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(sj,e)]),oj=(e,t)=>{for(let[n,r]of aj){let i=typeof t=="function"?(...s)=>Reflect.apply(r.value,t(),s):r.value.bind(t);Reflect.defineProperty(e,n,{...r,value:i})}return e},lj=e=>new Promise((t,n)=>{e.on("exit",(r,i)=>{t({exitCode:r,signal:i})}),e.on("error",r=>{n(r)}),e.stdin&&e.stdin.on("error",r=>{n(r)})});c9.exports={mergePromise:oj,getSpawnedPromise:lj}});var m9=E((jfe,_9)=>{"use strict";l();var d9=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],cj=/^[\w.-]+$/,uj=/"/g,dj=e=>typeof e!="string"||cj.test(e)?e:`"${e.replace(uj,'\\"')}"`,_j=(e,t)=>d9(e,t).join(" "),mj=(e,t)=>d9(e,t).map(n=>dj(n)).join(" "),pj=/ +/g,Ej=e=>{let t=[];for(let n of e.trim().split(pj)){let r=t[t.length-1];r&&r.endsWith("\\")?t[t.length-1]=`${r.slice(0,-1)} ${n}`:t.push(n)}return t};_9.exports={joinCommand:_j,getEscapedCommand:mj,parseCommand:Ej}});var T9=E((Jfe,gs)=>{"use strict";l();var fj=require("path"),XE=require("child_process"),gj=BE(),hj=IL(),Sj=ML(),Tj=FL(),cu=$L(),E9=WL(),{spawnedKill:bj,spawnedCancel:Dj,setupTimeout:Cj,validateTimeout:Rj,setExitHandler:Aj}=JL(),{handleInput:Oj,getSpawnedResult:Nj,makeAllStream:yj,validateInputSync:Ij}=l9(),{mergePromise:p9,getSpawnedPromise:vj}=u9(),{joinCommand:f9,parseCommand:g9,getEscapedCommand:h9}=m9(),xj=1e3*1e3*100,Mj=({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:i})=>{let s=t?{...process.env,...e}:e;return n?Sj.env({env:s,cwd:r,execPath:i}):s},S9=(e,t,n={})=>{let r=gj._parse(e,t,n);return e=r.command,t=r.args,n=r.options,n={maxBuffer:xj,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||process.cwd(),execPath:process.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,...n},n.env=Mj(n),n.stdio=E9(n),process.platform==="win32"&&fj.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},Wa=(e,t,n)=>typeof t!="string"&&!Buffer.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?hj(t):t,uu=(e,t,n)=>{let r=S9(e,t,n),i=f9(e,t),s=h9(e,t);Rj(r.options);let a;try{a=XE.spawn(r.file,r.args,r.options)}catch(S){let h=new XE.ChildProcess,C=Promise.reject(cu({error:S,stdout:"",stderr:"",all:"",command:i,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return p9(h,C)}let o=vj(a),c=Cj(a,r.options,o),u=Aj(a,r.options,c),d={isCanceled:!1};a.kill=bj.bind(null,a.kill.bind(a)),a.cancel=Dj.bind(null,a,d);let g=Tj(async()=>{let[{error:S,exitCode:h,signal:C,timedOut:I},F,U,B]=await Nj(a,r.options,u),w=Wa(r.options,F),Y=Wa(r.options,U),k=Wa(r.options,B);if(S||h!==0||C!==null){let q=cu({error:S,exitCode:h,signal:C,stdout:w,stderr:Y,all:k,command:i,escapedCommand:s,parsed:r,timedOut:I,isCanceled:d.isCanceled,killed:a.killed});if(!r.options.reject)return q;throw q}return{command:i,escapedCommand:s,exitCode:0,stdout:w,stderr:Y,all:k,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return Oj(a,r.options.input),a.all=yj(a,r.options),p9(a,g)};gs.exports=uu;gs.exports.sync=(e,t,n)=>{let r=S9(e,t,n),i=f9(e,t),s=h9(e,t);Ij(r.options);let a;try{a=XE.spawnSync(r.file,r.args,r.options)}catch(u){throw cu({error:u,stdout:"",stderr:"",all:"",command:i,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1})}let o=Wa(r.options,a.stdout,a.error),c=Wa(r.options,a.stderr,a.error);if(a.error||a.status!==0||a.signal!==null){let u=cu({stdout:o,stderr:c,error:a.error,signal:a.signal,exitCode:a.status,command:i,escapedCommand:s,parsed:r,timedOut:a.error&&a.error.code==="ETIMEDOUT",isCanceled:!1,killed:a.signal!==null});if(!r.options.reject)return u;throw u}return{command:i,escapedCommand:s,exitCode:0,stdout:o,stderr:c,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}};gs.exports.command=(e,t)=>{let[n,...r]=g9(e);return uu(n,r,t)};gs.exports.commandSync=(e,t)=>{let[n,...r]=g9(e);return uu.sync(n,r,t)};gs.exports.node=(e,t,n={})=>{t&&!Array.isArray(t)&&typeof t=="object"&&(n=t,t=[]);let r=E9.node(n),i=process.execArgv.filter(o=>!o.startsWith("--inspect")),{nodePath:s=process.execPath,nodeOptions:a=i}=n;return uu(s,[...a,e,...Array.isArray(t)?t:[]],{...n,stdin:void 0,stdout:void 0,stderr:void 0,stdio:r,shell:!1})}});var AZ={};Nu(AZ,{pkg:()=>Ru});module.exports=qP(AZ);l();var I2=J(require("update-notifier"));var yu={};Nu(yu,{author:()=>QP,bin:()=>r5,bugs:()=>XP,default:()=>a5,dependencies:()=>i5,description:()=>WP,devDependencies:()=>t5,engines:()=>s5,files:()=>n5,homepage:()=>KP,license:()=>zP,name:()=>VP,publishConfig:()=>ZP,repository:()=>jP,scripts:()=>e5,sideEffects:()=>JP,version:()=>Iu});var VP="@e2b/cli",Iu="0.3.4",WP="CLI for managing e2b sandbox templates",KP="https://e2b.dev",zP="MIT",QP={name:"FoundryLabs, Inc.",email:"hello@e2b.dev",url:"https://e2b.dev"},XP="https://github.com/e2b-dev/e2b/issues",jP={type:"git",url:"https://github.com/e2b-dev/e2b",directory:"packages/cli"},ZP={access:"public"},JP=!1,e5={prepublishOnly:"pnpm build",build:"tsc --noEmit --skipLibCheck && tsup --minify",dev:"tsup --watch",test:"pnpm build && cd testground/demo-basic && ../../dist/index.js template build","check-deps":"knip","update-deps":"ncu -u && pnpm i"},t5={"@types/inquirer":"^9.0.7","@types/node":"^18.18.6","@types/tar-fs":"^2.0.3","@types/update-notifier":"6.0.5",knip:"^2.33.4","npm-check-updates":"^16.14.6",tsup:"^7.2.0",typescript:"^5.2.2",vitest:"^0.34.6"},n5=["dist","LICENSE","README","package.json"],r5={e2b:"dist/index.js"},i5={"@balena/dockerignore":"^1.0.2","@iarna/toml":"^2.2.5","@nodelib/fs.walk":"^2.0.0","async-listen":"^3.0.1",boxen:"^7.1.1",chalk:"^5.3.0","cli-highlight":"^2.1.11",commander:"^11.1.0","console-table-printer":"^2.11.2",e2b:"^0.12.4",ignore:"^5.2.4",inquirer:"^9.2.12",open:"^9.1.0","strip-ansi":"^7.1.0","tar-fs":"^3.0.4","update-notifier":"5.1.0",yup:"^1.3.2"},s5={node:">=18"},a5={name:VP,version:Iu,description:WP,homepage:KP,license:zP,author:QP,bugs:XP,repository:jP,publishConfig:ZP,sideEffects:JP,scripts:e5,devDependencies:t5,files:n5,bin:r5,dependencies:i5,engines:s5};l();l();var W1=J(V1(),1),{program:qZ,createCommand:$Z,createArgument:VZ,createOption:WZ,CommanderError:KZ,InvalidArgumentError:zZ,InvalidOptionArgumentError:QZ,Command:Ae,Argument:XZ,Option:ci,Help:jZ}=W1.default;l();l();l();var K1=(e=0)=>t=>`\x1B[${t+e}m`,z1=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,Q1=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,Pe={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},JZ=Object.keys(Pe.modifier),R5=Object.keys(Pe.color),A5=Object.keys(Pe.bgColor),eJ=[...R5,...A5];function O5(){let e=new Map;for(let[t,n]of Object.entries(Pe)){for(let[r,i]of Object.entries(n))Pe[r]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},n[r]=Pe[r],e.set(i[0],i[1]);Object.defineProperty(Pe,t,{value:n,enumerable:!1})}return Object.defineProperty(Pe,"codes",{value:e,enumerable:!1}),Pe.color.close="\x1B[39m",Pe.bgColor.close="\x1B[49m",Pe.color.ansi=K1(),Pe.color.ansi256=z1(),Pe.color.ansi16m=Q1(),Pe.bgColor.ansi=K1(10),Pe.bgColor.ansi256=z1(10),Pe.bgColor.ansi16m=Q1(10),Object.defineProperties(Pe,{rgbToAnsi256:{value(t,n,r){return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));let i=Number.parseInt(r,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:t=>Pe.rgbToAnsi256(...Pe.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,i;if(t>=232)n=((t-232)*10+8)/255,r=n,i=n;else{t-=16;let o=t%36;n=Math.floor(t/36)/5,r=Math.floor(o/6)/5,i=o%6/5}let s=Math.max(n,r,i)*2;if(s===0)return 30;let a=30+(Math.round(i)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(t,n,r)=>Pe.ansi256ToAnsi(Pe.rgbToAnsi256(t,n,r)),enumerable:!1},hexToAnsi:{value:t=>Pe.ansi256ToAnsi(Pe.hexToAnsi256(t)),enumerable:!1}}),Pe}var N5=O5(),Qt=N5;l();var so=J(require("process"),1),j1=J(require("os"),1),qu=J(require("tty"),1);function kt(e,t=globalThis.Deno?globalThis.Deno.args:so.default.argv){let n=e.startsWith("-")?"":e.length===1?"-":"--",r=t.indexOf(n+e),i=t.indexOf("--");return r!==-1&&(i===-1||r<i)}var{env:Ge}=so.default,io;kt("no-color")||kt("no-colors")||kt("color=false")||kt("color=never")?io=0:(kt("color")||kt("colors")||kt("color=true")||kt("color=always"))&&(io=1);function y5(){if("FORCE_COLOR"in Ge)return Ge.FORCE_COLOR==="true"?1:Ge.FORCE_COLOR==="false"?0:Ge.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(Ge.FORCE_COLOR,10),3)}function I5(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function v5(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=y5();r!==void 0&&(io=r);let i=n?io:r;if(i===0)return 0;if(n){if(kt("color=16m")||kt("color=full")||kt("color=truecolor"))return 3;if(kt("color=256"))return 2}if("TF_BUILD"in Ge&&"AGENT_NAME"in Ge)return 1;if(e&&!t&&i===void 0)return 0;let s=i||0;if(Ge.TERM==="dumb")return s;if(so.default.platform==="win32"){let a=j1.default.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in Ge)return"GITHUB_ACTIONS"in Ge||"GITEA_ACTIONS"in Ge?3:["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(a=>a in Ge)||Ge.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in Ge)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Ge.TEAMCITY_VERSION)?1:0;if(Ge.COLORTERM==="truecolor"||Ge.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in Ge){let a=Number.parseInt((Ge.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Ge.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Ge.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Ge.TERM)||"COLORTERM"in Ge?1:s}function X1(e,t={}){let n=v5(e,{streamIsTTY:e&&e.isTTY,...t});return I5(n)}var x5={stdout:X1({isTTY:qu.default.isatty(1)}),stderr:X1({isTTY:qu.default.isatty(2)})},Z1=x5;l();function J1(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,s=0,a="";do a+=e.slice(s,r)+t+n,s=r+i,r=e.indexOf(t,s);while(r!==-1);return a+=e.slice(s),a}function ef(e,t,n,r){let i=0,s="";do{let a=e[r-1]==="\r";s+=e.slice(i,a?r-1:r)+t+(a?`\r
|
|
75
75
|
`:`
|
|
76
76
|
`)+n,i=r+1,r=e.indexOf(`
|
|
77
77
|
`,i)}while(r!==-1);return s+=e.slice(i),s}var{stdout:tf,stderr:nf}=Z1,$u=Symbol("GENERATOR"),ui=Symbol("STYLER"),Rs=Symbol("IS_EMPTY"),rf=["ansi","ansi","ansi256","ansi16m"],di=Object.create(null),M5=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let n=tf?tf.level:0;e.level=t.level===void 0?n:t.level};var w5=e=>{let t=(...n)=>n.join(" ");return M5(t,e),Object.setPrototypeOf(t,As.prototype),t};function As(e){return w5(e)}Object.setPrototypeOf(As.prototype,Function.prototype);for(let[e,t]of Object.entries(Qt))di[e]={get(){let n=ao(this,Wu(t.open,t.close,this[ui]),this[Rs]);return Object.defineProperty(this,e,{value:n}),n}};di.visible={get(){let e=ao(this,this[ui],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var Vu=(e,t,n,...r)=>e==="rgb"?t==="ansi16m"?Qt[n].ansi16m(...r):t==="ansi256"?Qt[n].ansi256(Qt.rgbToAnsi256(...r)):Qt[n].ansi(Qt.rgbToAnsi(...r)):e==="hex"?Vu("rgb",t,n,...Qt.hexToRgb(...r)):Qt[n][e](...r),L5=["rgb","hex","ansi256"];for(let e of L5){di[e]={get(){let{level:n}=this;return function(...r){let i=Wu(Vu(e,rf[n],"color",...r),Qt.color.close,this[ui]);return ao(this,i,this[Rs])}}};let t="bg"+e[0].toUpperCase()+e.slice(1);di[t]={get(){let{level:n}=this;return function(...r){let i=Wu(Vu(e,rf[n],"bgColor",...r),Qt.bgColor.close,this[ui]);return ao(this,i,this[Rs])}}}}var P5=Object.defineProperties(()=>{},{...di,level:{enumerable:!0,get(){return this[$u].level},set(e){this[$u].level=e}}}),Wu=(e,t,n)=>{let r,i;return n===void 0?(r=e,i=t):(r=n.openAll+e,i=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:n}},ao=(e,t,n)=>{let r=(...i)=>F5(r,i.length===1?""+i[0]:i.join(" "));return Object.setPrototypeOf(r,P5),r[$u]=e,r[ui]=t,r[Rs]=n,r},F5=(e,t)=>{if(e.level<=0||!t)return e[Rs]?"":t;let n=e[ui];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes("\x1B"))for(;n!==void 0;)t=J1(t,n.close,n.open),n=n.parent;let s=t.indexOf(`
|
|
@@ -87,10 +87,10 @@ ${r.message}`:C,U=[F,t,e].filter(Boolean).join(`
|
|
|
87
87
|
`),C=Math.max(...h.map(I=>st(I)));for(let I of h){let F;switch(r){case"center":{F=Ct.repeat((o-C)/2)+I;break}case"right":{F=Ct.repeat(o-C)+I;break}default:{F=I;break}}d.push(F)}}s=d}r==="center"&&a<o?s=s.map(d=>Ct.repeat((o-a)/2)+d):r==="right"&&a<o&&(s=s.map(d=>Ct.repeat(o-a)+d));let c=Ct.repeat(t.left),u=Ct.repeat(t.right);return s=s.map(d=>c+d+u),s=s.map(d=>{if(n-st(d)>0)switch(r){case"center":return d+Ct.repeat(n-st(d));case"right":return d+Ct.repeat(n-st(d));default:return d+Ct.repeat(n-st(d))}return d}),t.top>0&&(s=[...Array.from({length:t.top}).fill(Ct.repeat(n)),...s]),t.bottom>0&&(s=[...s,...Array.from({length:t.bottom}).fill(Ct.repeat(n))]),i&&s.length>i?s=s.slice(0,i):i&&s.length<i&&(s=[...s,...Array.from({length:i-s.length}).fill(Ct.repeat(n))]),s.join(sr)},fH=(e,t,n)=>{let r=d=>{let m=n.borderColor?SH(n.borderColor)(d):d;return n.dimBorder?Ze.dim(m):m},i=d=>n.backgroundColor?TH(n.backgroundColor)(d):d,s=mH(n.borderStyle),a=ZO(),o=Ct.repeat(n.margin.left);if(n.float==="center"){let d=Math.max((a-t-js(n.borderStyle))/2,0);o=Ct.repeat(d)}else if(n.float==="right"){let d=Math.max(a-t-n.margin.right-js(n.borderStyle),0);o=Ct.repeat(d)}let c="";n.margin.top&&(c+=sr.repeat(n.margin.top)),(n.borderStyle!==Xs||n.title)&&(c+=r(o+s.topLeft+(n.title?pH(n.title,s.top.repeat(t),n.titleAlignment):s.top.repeat(t))+s.topRight)+sr);let u=e.split(sr);return c+=u.map(d=>o+r(s.left)+i(d)+r(s.right)).join(sr),n.borderStyle!==Xs&&(c+=sr+r(o+s.bottomLeft+s.bottom.repeat(t)+s.bottomRight)),n.margin.bottom&&(c+=sr.repeat(n.margin.bottom)),c},gH=e=>{if(e.fullscreen&&Qs.default?.stdout){let t=[Qs.default.stdout.columns,Qs.default.stdout.rows];typeof e.fullscreen=="function"&&(t=e.fullscreen(...t)),e.width||(e.width=t[0]),e.height||(e.height=t[1])}return e.width&&(e.width=Math.max(1,e.width-js(e.borderStyle))),e.height&&(e.height=Math.max(1,e.height-js(e.borderStyle))),e},QO=(e,t)=>t===Xs?e:` ${e} `,hH=(e,t)=>{t=gH(t);let n=t.width!==void 0,r=ZO(),i=js(t.borderStyle),s=r-t.margin.left-t.margin.right-i,a=ml(El(e,r-i,{hard:!0,trim:!1}))+t.padding.left+t.padding.right;if(t.title&&n?(t.title=t.title.slice(0,Math.max(0,t.width-2)),t.title&&(t.title=QO(t.title,t.borderStyle))):t.title&&(t.title=t.title.slice(0,Math.max(0,s-2)),t.title&&(t.title=QO(t.title,t.borderStyle),st(t.title)>a&&(t.width=st(t.title)))),t.width=t.width?t.width:a,!n){if(t.margin.left&&t.margin.right&&t.width>s){let c=(r-t.width-i)/(t.margin.left+t.margin.right);t.margin.left=Math.max(0,Math.floor(t.margin.left*c)),t.margin.right=Math.max(0,Math.floor(t.margin.right*c))}t.width=Math.min(t.width,r-i-t.margin.left-t.margin.right)}return t.width-(t.padding.left+t.padding.right)<=0&&(t.padding.left=0,t.padding.right=0),t.height&&t.height-(t.padding.top+t.padding.bottom)<=0&&(t.padding.top=0,t.padding.bottom=0),t},L_=e=>e.match(/^#(?:[0-f]{3}){1,2}$/i),XO=e=>typeof e=="string"&&(Ze[e]??L_(e)),SH=e=>L_(e)?Ze.hex(e):Ze[e],TH=e=>L_(e)?Ze.bgHex(e):Ze[N_(["bg",e])];function Ur(e,t){if(t={padding:0,borderStyle:"single",dimBorder:!1,textAlignment:"left",float:"left",titleAlignment:"left",...t},t.align&&(t.textAlignment=t.align),t.borderColor&&!XO(t.borderColor))throw new Error(`${t.borderColor} is not a valid borderColor`);if(t.backgroundColor&&!XO(t.backgroundColor))throw new Error(`${t.backgroundColor} is not a valid backgroundColor`);return t.padding=zO(t.padding),t.margin=zO(t.margin),t=hH(e,t),e=EH(e,t),fH(e,t.width,t)}l();var ey=J(nN()),ty=J(qN()),Gr=J(require("fs")),ny=J(JN()),dt=J(require("path")),ry=J(require("util")),$Y=ry.promisify(ty.walk);async function iy(e,t){let n;if(t?.respectGitignore){let a=dt.join(e,".gitignore");Gr.existsSync(a)&&(n=ny.default().add(Gr.readFileSync(a).toString()))}let r;if(t?.respectDockerignore){let a=dt.join(e,".dockerignore");if(Gr.existsSync(a)){let c=Gr.readFileSync(a,"utf-8").split(`
|
|
88
88
|
`).map(u=>u.trim());r=ey.default().add(c)}}let i=await $Y(e,{entryFilter:a=>[!!a.stats?.isFile(),t?.extension?a.name.endsWith(t.extension):!0,t?.name?a.name===t.name:!0,!(n&&n.ignores(dt.relative(e,a.path))),!(r&&r.ignores(dt.relative(e,a.path)))].every(Boolean),stats:!0}),s=await Promise.all(i.map(async a=>({path:a.path,rootPath:dt.join("/",dt.relative(e,a.path)),name:a.name})));if(t?.overrideIgnoreFor)for(let a of t.overrideIgnoreFor){let o=dt.join(e,a);s.map(c=>c.path).indexOf(o)===-1&&Gr.existsSync(o)&&s.push({path:o,rootPath:dt.join("/",a),name:dt.basename(o)})}return s}function _r(e){let t=process.cwd();return e?dt.isAbsolute(e)?e:dt.resolve(t,e):t}function sy(e){return dt.relative(process.cwd(),e)}var VY="#FFB766";function _t(e,t){let n=Sm(e.aliases),r=n?De(n):"",i=t?WY(" <-> ")+at(t):"";return`${`${e.templateID} `}${r}${i}`.trim()}function Pi(e,t){return Ze.redBright(`${e?`${e}
|
|
89
89
|
`:""}${t?t.stack:""}
|
|
90
|
-
`)}function WY(e){return Ze.dim(e)}function De(e){return Ze.bold(e)}function yt(e){return Ze.hex(VY)(e)}function et(e){return Ze.blue(e)}function at(e){return e?et("./"+sy(e)):""}function hm(e){return Ze.blueBright(e)}function Sm(e){if(e)return e.join(" | ")}function ly(e){return gm.default(e,{language:"typescript",ignoreIllegals:!0})}function cy(e){return gm.default(e,{language:"python",ignoreIllegals:!0})}var KY={topLeft:"",topRight:"",bottomLeft:"",bottomRight:"",top:"",bottom:"",left:"",right:""},ay=2,oy=1;function Tm(e,t,n){return Ur(e,{borderStyle:{...KY,top:"\u2500",bottom:n?"\u2500":""},titleAlignment:"center",float:"left",title:t?De(t):void 0,margin:{top:0,bottom:0,left:1,right:0},fullscreen:r=>[r,0],padding:{bottom:n?oy:0,left:ay,right:ay,top:oy}})}l();l();var Pa=J(require("fs")),Vn=J(require("path"));l();l();var bm={};Nu(bm,{ApiError:()=>mr,Fetcher:()=>dy,arrayRequestBody:()=>_y});l();l();l();var Jce=Symbol(),mr=class extends Error{constructor(t){super(t.statusText),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"statusText",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.setPrototypeOf(this,new.target.prototype),this.headers=t.headers,this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.data=t.data}};var ta=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(a){a(s)})}return new(n||(n=Promise))(function(s,a){function o(d){try{u(r.next(d))}catch(m){a(m)}}function c(d){try{u(r.throw(d))}catch(m){a(m)}}function u(d){d.done?s(d.value):i(d.value).then(o,c)}u((r=r.apply(e,t||[])).next())})},uy=e=>e==="post"||e==="put"||e==="patch"||e==="delete";function zY(e){let t=[],n=(r,i)=>`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`;return Object.keys(e).forEach(r=>{let i=e[r];i!=null&&(Array.isArray(i)?i.forEach(s=>t.push(n(r,s))):t.push(n(r,i)))}),t.length>0?`?${t.join("&")}`:""}function QY(e,t){return e.replace(/\{([^}]+)\}/g,(n,r)=>{let i=encodeURIComponent(t[r]);return delete t[r],i})}function XY(e,t,n){let r={};return uy(e)?n.forEach(i=>{r[i]=t[i],delete t[i]}):r=Object.assign({},t),zY(r)}function jY(e,t){let n=new Headers(t);return e!==void 0&&!n.has("Content-Type")&&n.append("Content-Type","application/json"),n.has("Accept")||n.append("Accept","application/json"),n}function ZY(e,t){let n=uy(e)?JSON.stringify(t):void 0;return e==="delete"&&n==="{}"?void 0:n}function JY(e,t){let n=new Headers(e?.headers),r=new Headers(t?.headers);for(let i of r.keys()){let s=r.get(i);s!=null&&n.set(i,s)}return Object.assign(Object.assign(Object.assign({},e),t),{headers:n})}function eq(e){var t;let n=Object.assign(Array.isArray(e.payload)?[]:{},e.payload),r=QY(e.path,n),i=XY(e.method,n,e.queryParams),s=ZY(e.method,n),a=jY(s,(t=e.init)===null||t===void 0?void 0:t.headers),o=e.baseUrl+r+i,c=Object.assign(Object.assign({},e.init),{method:e.method.toUpperCase(),headers:a,body:s});return{url:o,init:c}}function tq(e){return ta(this,void 0,void 0,function*(){let t=e.headers.get("content-type");if(e.status===204)return;if(t&&t.indexOf("application/json")!==-1)return yield e.json();let n=yield e.text();try{return JSON.parse(n)}catch{return n}})}function nq(e,t){return ta(this,void 0,void 0,function*(){let n=yield fetch(e,t),r=yield tq(n),i={headers:n.headers,url:n.url,ok:n.ok,status:n.status,statusText:n.statusText,data:r};if(i.ok)return i;throw new mr(i)})}function rq(e,t){let n=(r,i,s)=>ta(this,void 0,void 0,function*(){if(e==null||r===e.length)return t(i,s);let a=e[r];return yield a(i,s,(o,c)=>n(r+1,o,c))});return(r,i)=>n(0,r,i)}function iq(e){return ta(this,void 0,void 0,function*(){let{url:t,init:n}=eq(e);return yield e.fetch(t,n)})}function sq(e){let t=(n,r)=>ta(this,void 0,void 0,function*(){try{return yield e(n,r)}catch(i){throw i instanceof mr?new t.Error(i):i}});return t.Error=class extends mr{constructor(n){super(n),Object.setPrototypeOf(this,new.target.prototype)}getActualType(){return{status:this.status,data:this.data}}},t}function aq(){let e="",t={},n=[],r=rq(n,nq);return{configure:i=>{e=i.baseUrl||"",t=i.init||{},n.splice(0),n.push(...i.use||[])},use:i=>n.push(i),path:i=>({method:s=>({create:a=>sq((o,c)=>iq({baseUrl:e||"",path:i,method:s,queryParams:Object.keys(a||{}),payload:o,init:JY(t,c),fetch:r}))})})}}var dy={for:()=>aq()};l();function _y(e,t){return Object.assign([...e],t)}l();var my=process?.env?.E2B_DEBUG,py=process?.env?.E2B_DOMAIN||"e2b.dev",Dm=(process?.env?.E2B_SECURE||"true").toLowerCase()==="true",oq=my?"localhost:3000":`api.${py}`,na=`${Dm&&!my?"https":"http"}://${oq}`,Cm=py,Pl=49982,Ey="/ws",fy="/file";l();var kl=J(gy());var hy="0.12.
|
|
90
|
+
`)}function WY(e){return Ze.dim(e)}function De(e){return Ze.bold(e)}function yt(e){return Ze.hex(VY)(e)}function et(e){return Ze.blue(e)}function at(e){return e?et("./"+sy(e)):""}function hm(e){return Ze.blueBright(e)}function Sm(e){if(e)return e.join(" | ")}function ly(e){return gm.default(e,{language:"typescript",ignoreIllegals:!0})}function cy(e){return gm.default(e,{language:"python",ignoreIllegals:!0})}var KY={topLeft:"",topRight:"",bottomLeft:"",bottomRight:"",top:"",bottom:"",left:"",right:""},ay=2,oy=1;function Tm(e,t,n){return Ur(e,{borderStyle:{...KY,top:"\u2500",bottom:n?"\u2500":""},titleAlignment:"center",float:"left",title:t?De(t):void 0,margin:{top:0,bottom:0,left:1,right:0},fullscreen:r=>[r,0],padding:{bottom:n?oy:0,left:ay,right:ay,top:oy}})}l();l();var Pa=J(require("fs")),Vn=J(require("path"));l();l();var bm={};Nu(bm,{ApiError:()=>mr,Fetcher:()=>dy,arrayRequestBody:()=>_y});l();l();l();var Jce=Symbol(),mr=class extends Error{constructor(t){super(t.statusText),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"statusText",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.setPrototypeOf(this,new.target.prototype),this.headers=t.headers,this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.data=t.data}};var ta=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(a){a(s)})}return new(n||(n=Promise))(function(s,a){function o(d){try{u(r.next(d))}catch(m){a(m)}}function c(d){try{u(r.throw(d))}catch(m){a(m)}}function u(d){d.done?s(d.value):i(d.value).then(o,c)}u((r=r.apply(e,t||[])).next())})},uy=e=>e==="post"||e==="put"||e==="patch"||e==="delete";function zY(e){let t=[],n=(r,i)=>`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`;return Object.keys(e).forEach(r=>{let i=e[r];i!=null&&(Array.isArray(i)?i.forEach(s=>t.push(n(r,s))):t.push(n(r,i)))}),t.length>0?`?${t.join("&")}`:""}function QY(e,t){return e.replace(/\{([^}]+)\}/g,(n,r)=>{let i=encodeURIComponent(t[r]);return delete t[r],i})}function XY(e,t,n){let r={};return uy(e)?n.forEach(i=>{r[i]=t[i],delete t[i]}):r=Object.assign({},t),zY(r)}function jY(e,t){let n=new Headers(t);return e!==void 0&&!n.has("Content-Type")&&n.append("Content-Type","application/json"),n.has("Accept")||n.append("Accept","application/json"),n}function ZY(e,t){let n=uy(e)?JSON.stringify(t):void 0;return e==="delete"&&n==="{}"?void 0:n}function JY(e,t){let n=new Headers(e?.headers),r=new Headers(t?.headers);for(let i of r.keys()){let s=r.get(i);s!=null&&n.set(i,s)}return Object.assign(Object.assign(Object.assign({},e),t),{headers:n})}function eq(e){var t;let n=Object.assign(Array.isArray(e.payload)?[]:{},e.payload),r=QY(e.path,n),i=XY(e.method,n,e.queryParams),s=ZY(e.method,n),a=jY(s,(t=e.init)===null||t===void 0?void 0:t.headers),o=e.baseUrl+r+i,c=Object.assign(Object.assign({},e.init),{method:e.method.toUpperCase(),headers:a,body:s});return{url:o,init:c}}function tq(e){return ta(this,void 0,void 0,function*(){let t=e.headers.get("content-type");if(e.status===204)return;if(t&&t.indexOf("application/json")!==-1)return yield e.json();let n=yield e.text();try{return JSON.parse(n)}catch{return n}})}function nq(e,t){return ta(this,void 0,void 0,function*(){let n=yield fetch(e,t),r=yield tq(n),i={headers:n.headers,url:n.url,ok:n.ok,status:n.status,statusText:n.statusText,data:r};if(i.ok)return i;throw new mr(i)})}function rq(e,t){let n=(r,i,s)=>ta(this,void 0,void 0,function*(){if(e==null||r===e.length)return t(i,s);let a=e[r];return yield a(i,s,(o,c)=>n(r+1,o,c))});return(r,i)=>n(0,r,i)}function iq(e){return ta(this,void 0,void 0,function*(){let{url:t,init:n}=eq(e);return yield e.fetch(t,n)})}function sq(e){let t=(n,r)=>ta(this,void 0,void 0,function*(){try{return yield e(n,r)}catch(i){throw i instanceof mr?new t.Error(i):i}});return t.Error=class extends mr{constructor(n){super(n),Object.setPrototypeOf(this,new.target.prototype)}getActualType(){return{status:this.status,data:this.data}}},t}function aq(){let e="",t={},n=[],r=rq(n,nq);return{configure:i=>{e=i.baseUrl||"",t=i.init||{},n.splice(0),n.push(...i.use||[])},use:i=>n.push(i),path:i=>({method:s=>({create:a=>sq((o,c)=>iq({baseUrl:e||"",path:i,method:s,queryParams:Object.keys(a||{}),payload:o,init:JY(t,c),fetch:r}))})})}}var dy={for:()=>aq()};l();function _y(e,t){return Object.assign([...e],t)}l();var my=process?.env?.E2B_DEBUG,py=process?.env?.E2B_DOMAIN||"e2b.dev",Dm=(process?.env?.E2B_SECURE||"true").toLowerCase()==="true",oq=my?"localhost:3000":`api.${py}`,na=`${Dm&&!my?"https":"http"}://${oq}`,Cm=py,Pl=49982,Ey="/ws",fy="/file";l();var kl=J(gy());var hy="0.12.4";var Sy={browser:typeof window<"u"&&kl.default.name||"undefined",lang:"js",lang_version:kl.default.version||"unknown",package_version:hy,publisher:"e2b",sdk_runtime:typeof window>"u"?"node":"browser",system:kl.default.os?.family||"unknown"};var{Fetcher:cq}=bm,Ty=cq.for();Ty.configure({baseUrl:na,init:{headers:Sy}});function Hr(e){let t=(n,r,i)=>e(r,{...i,headers:{Authorization:`Bearer ${n}`,...i?.headers}});return t.Error=e.Error,t}function _n(e){let t=(n,r,i)=>e(r,{...i,headers:{"X-API-KEY":n,...i?.headers}});return t.Error=e.Error,t}var gt=Ty;l();var Yr="terminal",Bl=class{_data="";get data(){return this._data}addData(t){this._data+=t}},Ul=class{constructor(t,n,r,i,s){this.terminalID=t;this.sandbox=n;this.triggerExit=r;this.output=s;this.finished=i}finished;get data(){return this.output.data}async kill(){try{await this.sandbox._call(Yr,"destroy",[this.terminalID])}finally{this.triggerExit(),await this.finished}}async wait(){return this.finished}async sendData(t){await this.sandbox._call(Yr,"data",[this.terminalID,t])}async resize({cols:t,rows:n}){await this.sandbox._call(Yr,"resize",[this.terminalID,t,n])}};l();l();l();var Rm=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Am=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},by=e=>globalThis.DOMException===void 0?new Am(e):new DOMException(e),Dy=e=>{let t=e.reason===void 0?by("This operation was aborted."):e.reason;return t instanceof Error?t:by(t)};function Om(e,t){let{milliseconds:n,fallback:r,message:i,customTimers:s={setTimeout,clearTimeout}}=t,a,c=new Promise((u,d)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(t.signal){let{signal:g}=t;g.aborted&&d(Dy(g)),g.addEventListener("abort",()=>{d(Dy(g))})}if(n===Number.POSITIVE_INFINITY){e.then(u,d);return}let m=new Rm;a=s.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){d(g)}return}typeof e.cancel=="function"&&e.cancel(),i===!1?u():i instanceof Error?d(i):(m.message=i??`Promise timed out after ${n} milliseconds`,d(m))},n),(async()=>{try{u(await e)}catch(g){d(g)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},c}function Cy(e){return e.status==="fulfilled"}function ia(e){if(!e.every(t=>t.status==="fulfilled"))return e.reduce((t,n,r)=>n.status==="rejected"?t+`
|
|
91
91
|
[${r}]: ${JSON.stringify(n)}`:t,`errors:
|
|
92
92
|
`)}function sa(){let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),reject:t,resolve:e}}function mn(e,t=6e4){return t===void 0||t<=0||t===Number.POSITIVE_INFINITY?e:(...n)=>Om(e(...n),{milliseconds:t})}l();var pn="filesystem";var Nm=class{constructor(t,n){this.sessConn=t;this.path=n;this.listeners=new Set}listeners;rpcSubscriptionID;async start(t){return await mn(async()=>{this.rpcSubscriptionID||(this.handleFilesystemEvents=this.handleFilesystemEvents.bind(this),this.rpcSubscriptionID=await this.sessConn._subscribe(pn,this.handleFilesystemEvents,"watchDir",this.path))},t?.timeout)()}async stop(){this.listeners.clear(),this.rpcSubscriptionID&&await this.sessConn._unsubscribe(this.rpcSubscriptionID)}addEventListener(t){return this.listeners.add(t),()=>this.listeners.delete(t)}handleFilesystemEvents(t){this.listeners.forEach(n=>{n(t)})}},Ry=Nm;l();var qr="process",aa=class{constructor(t,n,r){this.line=t;this.timestamp=n;this.error=r}toString(){return this.line}},Gl=class{delimiter=`
|
|
93
|
-
`;messages=[];_finished=!1;_error=!1;_exitCode;get error(){return this._error}get exitCode(){if(!this._finished)throw new Error("Process has not finished yet");return this._exitCode}get stdout(){return this.messages.filter(t=>!t.error).map(t=>t.line).join(this.delimiter)}get stderr(){return this.messages.filter(t=>t.error).map(t=>t.line).join(this.delimiter)}addStdout(t){this.insertByTimestamp(t)}addStderr(t){this._error=!0,this.insertByTimestamp(t)}setExitCode(t){this._exitCode=t,this._finished=!0}insertByTimestamp(t){let n=this.messages.length-1;for(;n>=0&&this.messages[n].timestamp>t.timestamp;)n-=1;this.messages.splice(n+1,0,t)}},Hl=class{constructor(t,n,r,i,s){this.processID=t;this.sandbox=n;this.triggerExit=r;this.output=s;this.finished=i}finished;async kill(){try{await this.sandbox._call(qr,"kill",[this.processID])}finally{this.triggerExit(),await this.finished}}async wait(t){return await mn(()=>this.finished,t)()}async sendStdin(t,n){await this.sandbox._call(qr,"stdin",[this.processID,t],n)}};l();var cv=J(Oy());l();function Fi(e){let t="",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=n.length;for(let i=0;i<e;i++)t+=n.charAt(Math.floor(Math.random()*r));return t}l();var Ny="codeSnippet";l();l();var tv=J(ev());var tc=class{ws;onOpenHandlers=[];onAnyMessageHandlers=[];onNotification=[];onRequest=[];onSuccessResponse=[];onErrorResponse=[];onErrorHandlers=[];onCloseHandlers=[];config={responseTimeout:1e4};idAwaiter={};constructor(){this.ws=void 0}connect(t,n){return this.ws=new tv.default(t,n),this.listen()}onOpen(t){this.onOpenHandlers.push(t)}onAnyMessage(t){this.onAnyMessageHandlers.push(t)}onError(t){this.onErrorHandlers.push(t)}onClose(t){this.onCloseHandlers.push(t)}listenMessages(){let t;this.ws.onmessage&&(t=this.ws.onmessage.bind(this.ws)),this.ws.onmessage=n=>{t&&t(n);for(let i of this.onAnyMessageHandlers)i(n);let r=JSON.parse(n.data.toString());if(this.isNotification(r))for(let i of this.onNotification)i(r);else if(this.isRequest(r))for(let i of this.onRequest)i(r);else if(this.isSuccessResponse(r)){for(let i of this.onSuccessResponse)i(r);this.idAwaiter[r.id](r.result)}else if(this.isErrorResponse(r)){for(let i of this.onErrorResponse)i(r);this.idAwaiter[r.id](r.error)}}}call(t,n){return new Promise((r,i)=>{let s=this.buildRequest(t,n),a;this.config.responseTimeout&&(a=setTimeout(()=>{delete this.idAwaiter[s.id],i(new Error(`Awaiting response to "${t}" with id: ${s.id} timed out.`))},this.config.responseTimeout)),this.idAwaiter[s.id]=c=>{if(clearInterval(a),delete this.idAwaiter[s.id],this.isRpcError(c)){i(new Error(`RPC Error (${c.code}): ${c.message}`));return}r(c)};let o=JSON.stringify(s);this.ws.send(o)})}notify(t,n){this.ws.send(JSON.stringify(this.buildNotification(t,n)))}customId(t){this.idFn=t}noRpc(){this.buildRequest=this.buildRequestBase,this.buildNotification=this.buildNotificationBase,this.buildRpcSuccessResponse=this.buildRpcSuccessResponseBase,this.buildRpcErrorResponse=this.buildRpcErrorResponseBase}configure(t){Object.assign(this.config,t)}changeSocket(t){this.ws=t}listen(){return new Promise((t,n)=>{this.ws.onopen=r=>{for(let i of this.onOpenHandlers)i(r);t(r)},this.listenMessages(),this.ws.onerror=r=>{for(let i of this.onErrorHandlers)i(r)},this.ws.onclose=r=>{for(let i of this.onCloseHandlers)i(r);n(new Error(`WebSocket closed with code: ${r.code} and reason: ${r.reason}`))}})}buildRequest(t,n){let r=this.buildRequestBase(t,n);return r.jsonrpc="2.0",r}buildRequestBase(t,n){let r={};return r.id=this.idFn(),r.method=t,n&&(r.params=n),r}buildNotification(t,n){let r=this.buildNotificationBase(t,n);return r.jsonrpc="2.0",r}buildNotificationBase(t,n){let r={};return r.method=t,n&&(r.params=n),r}buildRpcSuccessResponse(t,n){let r=this.buildRpcSuccessResponseBase(t,n);return r.jsonrpc="2.0",r}buildRpcSuccessResponseBase(t,n){let r={};return r.id=t,r.result=n,r}buildRpcErrorResponse(t,n){let r=this.buildRpcErrorResponseBase(t,n);return r.jsonrpc="2.0",r}buildRpcErrorResponseBase(t,n){let r={};return r.id=t,r.error=n,r}idFn(){return Fi(12)}isNotification(t){return!t.id}isRequest(t){return t.method}isSuccessResponse(t){return t.hasOwnProperty("result")}isErrorResponse(t){return t.hasOwnProperty("error")}isRpcError(t){return typeof t?.code<"u"}};l();function M$(e){return new Promise(t=>setTimeout(t,e))}var ip=M$;l();l();var nc=class extends Error{constructor(t){super(t),this.name="AuthenticationError"}},rc=class extends Error{constructor(t){super(t),this.name="CurrentWorkingDirectoryDoesntExistError"}};function ic(e){if(e=e||process?.env?.E2B_API_KEY,!e)throw new nc("API key is required, please visit https://e2b.dev/docs to get your API key. You can either set the environment variable `E2B_API_KEY` or you can pass it directly to the sandbox like Sandbox.create({apiKey: 'e2b_...'})");return e}var nv=_n(gt.path("/sandboxes").method("get").create()),rv=_n(gt.path("/sandboxes").method("post").create()),iv=_n(gt.path("/sandboxes/{sandboxID}").method("delete").create()),sp=_n(gt.path("/sandboxes/{sandboxID}/refreshes").method("post").create()),sc=class{constructor(t){this.opts=t;this.sandbox=t.__sandbox,this.apiKey=ic(t.apiKey),this.cwd=t.cwd,this.cwd&&this.cwd.startsWith("~")&&(this.cwd=this.cwd.replace("~","/home/user"));let n={PYTHONUNBUFFERED:"1"};this.envVars={...n,...t.envVars||{}},this.logger=t.logger??{info:console.info,warn:console.warn,error:console.error},this.logger.debug?.(`Sandbox "${this.templateID}" initialized`)}cwd;envVars;logger;sandbox;isOpen=!1;apiKey;rpc=new tc;subscribers=[];get id(){return`${this.sandbox?.sandboxID}-${this.sandbox?.clientID}`}get templateID(){return this.opts.template||this.opts.id||"base"}static async list(t){t=ic(t);try{return(await nv(t,{})).data.map(r=>({sandboxID:`${r.sandboxID}-${r.clientID}`,templateID:r.templateID,cpuCount:r.cpuCount,memoryMB:r.memoryMB,...r.alias&&{alias:r.alias},...r.metadata&&{metadata:r.metadata},startedAt:new Date(r.startedAt)}))}catch(n){if(n instanceof nv.Error){let r=n.getActualType();if(r.status===401)throw new Error(`Error listing sandboxes - (${r.status}) unauthenticated: ${r.data.message}`);if(r.status===500)throw new Error(`Error listing sandboxes - (${r.status}) server error: ${r.data.message}`)}throw n}}static async kill(t,n){n=ic(n);try{await iv(n,{sandboxID:t})}catch(r){if(r instanceof iv.Error){let i=r.getActualType();if(i.status===401)throw new Error(`Error killing sandbox (${t}) - (${i.status}) unauthenticated: ${i.data.message}`);if(i.status===500)throw new Error(`Error killing sandbox (${t}) - (${i.status}) server error: ${i.data.message}`)}throw r}}async keepAlive(t){if(t=Math.round(t/1e3),t<0||t>3600)throw new Error("Duration must be between 0 and 3600 seconds");if(!this.sandbox)throw new Error("Cannot keep alive - sandbox is not initialized");await sp(this.apiKey,{sandboxID:this.sandbox?.sandboxID,duration:t})}getHostname(t){if(this.opts.__debug_hostname)return t&&this.opts.__debug_devEnv==="remote"?`${t}-${this.opts.__debug_hostname}`:t?`${this.opts.__debug_hostname}:${t}`:this.opts.__debug_hostname;if(!this.sandbox)throw new Error("Cannot get sandbox's hostname - sandbox is not initialized");let n=`${this.id}.${Cm}`;return t?`${t}-${n}`:n}getProtocol(t="http",n=Dm){return n?`${t}s`:t}async close(){this.isOpen&&(this.logger.debug?.(`Closing sandbox "${this.id}"`),this.isOpen=!1,this.rpc.ws?.terminate?.(),this.rpc.ws?.close?.(),this.subscribers=[],this.logger.debug?.("Disconnected from the sandbox"))}async _call(t,n,r,i){return this.logger.debug?.(`Calling "${t}_${n}" with params:`,r),await mn(async(a,o)=>await this.rpc.call(a,o),i?.timeout)(`${t}_${n}`,r)}async _handleSubscriptions(...t){let n=await Promise.allSettled(t);if(n.every(r=>r.status==="fulfilled"))return n.map(r=>r.status==="fulfilled"?r.value:void 0);throw await Promise.all(n.filter(Cy).map(r=>r.value?this._unsubscribe(r.value):void 0)),new Error(ia(n))}async _unsubscribe(t){let n=this.subscribers.find(r=>r.subID===t);n&&(await this._call(n.service,"unsubscribe",[n.subID]),this.subscribers=this.subscribers.filter(r=>r!==n),this.logger.debug?.(`Unsubscribed '${t}' from '${n.service}'`))}async _subscribe(t,n,r,...i){let s=await this._call(t,"subscribe",[r,...i]);if(typeof s!="string")throw new Error(`Cannot subscribe to ${t}_${r}${i.length>0?" with params ["+i.join(", ")+"]":""}. Expected response should have been a subscription ID, instead we got ${JSON.stringify(s)}`);return this.subscribers.push({handler:n,service:t,subID:s}),this.logger.debug?.(`Subscribed to "${t}_${r}"${i.length>0?" with params ["+i.join(", ")+"] and":""} with id "${s}"`),s}async _open(t){let n=async()=>{if(this.isOpen)throw new Error("Sandbox connect was already called");if(this.isOpen=!0,this.logger.debug?.("Opening sandbox..."),!this.sandbox&&!this.opts.__debug_hostname)try{let r=await rv(this.apiKey,{templateID:this.templateID,metadata:this.opts.metadata});this.sandbox=r.data,this.logger.debug?.(`Acquired sandbox "${this.id}"`)}catch(r){if(r instanceof rv.Error){let i=r.getActualType();if(i.status===400)throw new Error(`Error creating sandbox - (${i.status}) bad request: ${i.data.message}`);if(i.status===401)throw new Error(`Error creating sandbox - (${i.status}) unauthenticated: ${i.data.message}`);if(i.status===500)throw new Error(`Error creating sandbox - (${i.status}) server error: ${i.data.message}`)}throw r}return this.sandbox&&!this.opts.__debug_hostname&&this.refresh(this.sandbox.sandboxID),await this.connectRpc(),this};try{return await mn(n,t?.timeout)()}catch(r){throw await this.close(),r}}async connectRpc(){let t=this.getHostname(this.opts.__debug_port||Pl),r=`${this.getProtocol("ws",this.opts.__debug_devEnv!=="local")}://${t}${Ey}`,i=!1,s,a,o=new Promise((c,u)=>{s=()=>{i||(i=!0,c())},a=()=>{i||(i=!0,u())}});this.rpc.onOpen(()=>{this.logger.debug?.(`Connected to sandbox "${this.id}"`),s?.()}),this.rpc.onError(async c=>{if(this.logger.debug?.(`Error in WebSocket of sandbox "${this.id}": ${c.message??c.code??c.toString()}. Trying to reconnect...`),this.isOpen){await ip(150),this.logger.debug?.(`Reconnecting to sandbox "${this.id}"`);try{this.subscribers=[],await this.rpc.connect(r),this.logger.debug?.(`Reconnected to sandbox "${this.id}"`)}catch(u){this.logger.debug?.(`Failed reconnecting to sandbox "${this.id}": ${u.message??u.code??u.toString()}`)}}else a?.()}),this.rpc.onClose(async()=>{this.logger.debug?.(`WebSocket connection to sandbox "${this.id}" closed`)}),this.rpc.onNotification.push(this.handleNotification.bind(this)),(async()=>{try{this.logger.debug?.(`Connecting to sandbox "${this.id}"`),await this.rpc.connect(r)}catch(c){this.logger.debug?.(`Error connecting to sandbox "${this.id}": ${c.message??c.code??c.toString()}`)}})(),await o}handleNotification(t){this.logger.debug?.("Handling notification:",t),this.subscribers.filter(n=>n.subID===t.params?.subscription).forEach(n=>n.handler(t.params?.result))}async refresh(t){this.logger.debug?.(`Started refreshing sandbox "${t}"`);try{for(;;){if(!this.isOpen){this.logger.debug?.(`Cannot refresh sandbox ${this.id} - it was closed`);return}await ip(5e3);try{await sp(this.apiKey,{sandboxID:t,duration:0}),this.logger.debug?.(`Refreshed sandbox "${t}"`)}catch(n){if(n instanceof sp.Error){let r=n.getActualType();if(r.status===404){this.logger.warn?.(`Error refreshing sandbox - (${r.status}): ${r.data.message}`);return}this.logger.warn?.(`Refreshing sandbox "${t}" failed - (${r.status})`)}}}}finally{this.logger.debug?.(`Stopped refreshing sandbox "${t}"`),await this.close()}}};l();var ga=J(ov()),lv=(e,t,n)=>{let r;return e.startsWith("./")?(r=ga.default.posix.join(t||"/home/user",e),t||n.warn?.(`Path starts with './' and cwd isn't set. The path '${e}' will evaluate to '${r}', which may not be what you want.`),r):e.startsWith("../")?(r=ga.default.posix.join(t||"/home/user",e),t||n.warn?.(`Path starts with '../' and cwd isn't set. The path '${e}' will evaluate to '${r}', which may not be what you want.`),r):e.startsWith("~/")?(r=ga.default.posix.join(t||"/home/user",e.substring(2)),t||n.warn?.(`Path starts with '~/' and cwd isn't set. The path '${e}' will evaluate to '${r}', which may not be what you want.`),r):!e.startsWith("/")&&t?ga.default.posix.join(t,e):e};l();var ac=class{constructor(t){this.sandbox=t}async run(t){if(t.status!=="requires_action")return[];if(!t.required_action)return[];let n=[];for(let r of t.required_action.submit_tool_outputs.tool_calls){let i=this.sandbox._actions.get(r.function.name);if(!i){console.warn(`Action ${r.function.name} not found`);continue}let s=JSON.parse(r.function.arguments),a=await i(this.sandbox,s);n.push({tool_call_id:r.id,output:a})}return n}};var Kr=class e extends sc{terminal;filesystem;process;_actions=new Map;onScanPorts;constructor(t){t=t||{},super(t),this.onScanPorts=t.onScanPorts,this.filesystem={list:async(r,i)=>await this._call(pn,"list",[n(r)],i),read:async(r,i)=>await this._call(pn,"read",[n(r)],i),remove:async(r,i)=>{await this._call(pn,"remove",[n(r)],i)},write:async(r,i,s)=>{await this._call(pn,"write",[n(r),i],s)},writeBytes:async(r,i)=>{let s=Buffer.from(i).toString("base64");await this._call(pn,"writeBase64",[n(r),s])},readBytes:async r=>{let i=await this._call(pn,"readBase64",[n(r)]);return Buffer.from(i,"base64")},makeDir:async(r,i)=>{await this._call(pn,"makeDir",[n(r)],i)},watchDir:r=>{this.logger.debug?.(`Watching directory "${r}"`);let i=(0,cv.default)(n(r));return new Ry(this,i)}},this.terminal={start:async({onData:r,size:i,onExit:s,envVars:a,cmd:o,cwd:c="",terminalID:u=Fi(12),timeout:d=void 0})=>await mn(async({onData:g,size:S,onExit:h,envVars:C,cmd:I,cwd:F="",rootDir:U,terminalID:B=Fi(12)})=>{this.logger.debug?.(`Starting terminal "${B}"`),!F&&U&&(this.logger.warn?.("The rootDir parameter is deprecated, use cwd instead."),F=U),!F&&this.cwd&&(F=this.cwd),C=C||{},C={...this.envVars,...C};let{promise:w,resolve:Y}=sa(),k=new Bl;function q(ie){k.addData(ie),g?.(ie)}let[M,L]=await this._handleSubscriptions(this._subscribe(Yr,q,"onData",B),this._subscribe(Yr,Y,"onExit",B)),{promise:$,resolve:V}=sa();w.then(async()=>{Promise.allSettled([this._unsubscribe(L),this._unsubscribe(M)]).then(ie=>{let se=ia(ie);se&&this.logger.debug?.(se)}),this.logger.debug?.(`Terminal "${B}" exited`),h?.(),V(k)});try{await this._call(Yr,"start",[B,S.cols,S.rows,...I!==void 0?[C,I,F]:[]])}catch(ie){throw Y(),await $,ie}return new Ul(B,this,Y,$,k)},d)({onData:r,size:i,onExit:s,envVars:a,cmd:o,cwd:c,terminalID:u})},this.process={start:async r=>{let i=typeof r=="string"?{cmd:r}:r,s=async({cmd:o,onStdout:c,onStderr:u,onExit:d,envVars:m={},cwd:g="",rootDir:S,processID:h=Fi(12)})=>{if(!g&&S&&(this.logger.warn?.("The rootDir parameter is deprecated, use cwd instead."),g=S),!g&&this.cwd&&(g=this.cwd),!o)throw new Error("cmd is required");m=m||{},m={...this.envVars,...m},this.logger.debug?.(`Starting process "${h}", cmd: "${o}"`);let{promise:C,resolve:I}=sa(),F=new Gl,U=$=>{F.setExitCode($),I()},B=$=>{let V=new aa($.line,$.timestamp,!1);F.addStdout(V),c?c(V):this.opts.onStdout&&this.opts.onStdout(V)},w=$=>{let V=new aa($.line,$.timestamp,!0);F.addStderr(V),u?u(V):this.opts.onStderr&&this.opts.onStderr(V)},[Y,k,q]=await this._handleSubscriptions(this._subscribe(qr,U,"onExit",h),this._subscribe(qr,B,"onStdout",h),this._subscribe(qr,w,"onStderr",h)),{promise:M,resolve:L}=sa();C.then(async()=>{Promise.allSettled([this._unsubscribe(Y),k?this._unsubscribe(k):void 0,q?this._unsubscribe(q):void 0]).then($=>{let V=ia($);V&&this.logger.debug?.(V)}),this.logger.debug?.(`Process "${h}" exited`),d?d(F.exitCode||0):this.opts.onExit&&this.opts.onExit(),L(F)});try{await this._call(qr,"start",[h,o,m,g])}catch($){throw I(),await M,/error starting process '\w+': fork\/exec \/bin\/bash: no such file or directory/.test($?.message)?new rc(`Failed to start the process. You are trying set 'cwd' to a directory that does not exist.
|
|
93
|
+
`;messages=[];_finished=!1;_error=!1;_exitCode;get error(){return this._error}get exitCode(){if(!this._finished)throw new Error("Process has not finished yet");return this._exitCode}get stdout(){return this.messages.filter(t=>!t.error).map(t=>t.line).join(this.delimiter)}get stderr(){return this.messages.filter(t=>t.error).map(t=>t.line).join(this.delimiter)}addStdout(t){this.insertByTimestamp(t)}addStderr(t){this._error=!0,this.insertByTimestamp(t)}setExitCode(t){this._exitCode=t,this._finished=!0}insertByTimestamp(t){let n=this.messages.length-1;for(;n>=0&&this.messages[n].timestamp>t.timestamp;)n-=1;this.messages.splice(n+1,0,t)}},Hl=class{constructor(t,n,r,i,s){this.processID=t;this.sandbox=n;this.triggerExit=r;this.output=s;this.finished=i}finished;async kill(){try{await this.sandbox._call(qr,"kill",[this.processID])}finally{this.triggerExit(),await this.finished}}async wait(t){return await mn(()=>this.finished,t)()}async sendStdin(t,n){await this.sandbox._call(qr,"stdin",[this.processID,t],n)}};l();var cv=J(Oy());l();function Fi(e){let t="",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=n.length;for(let i=0;i<e;i++)t+=n.charAt(Math.floor(Math.random()*r));return t}l();var Ny="codeSnippet";l();l();var tv=J(ev());var tc=class{ws;onOpenHandlers=[];onAnyMessageHandlers=[];onNotification=[];onRequest=[];onSuccessResponse=[];onErrorResponse=[];onErrorHandlers=[];onCloseHandlers=[];config={responseTimeout:1e4};idAwaiter={};constructor(){this.ws=void 0}connect(t,n){return this.ws=new tv.default(t,n),this.listen()}onOpen(t){this.onOpenHandlers.push(t)}onAnyMessage(t){this.onAnyMessageHandlers.push(t)}onError(t){this.onErrorHandlers.push(t)}onClose(t){this.onCloseHandlers.push(t)}listenMessages(){let t;this.ws.onmessage&&(t=this.ws.onmessage.bind(this.ws)),this.ws.onmessage=n=>{t&&t(n);for(let i of this.onAnyMessageHandlers)i(n);let r=JSON.parse(n.data.toString());if(this.isNotification(r))for(let i of this.onNotification)i(r);else if(this.isRequest(r))for(let i of this.onRequest)i(r);else if(this.isSuccessResponse(r)){for(let i of this.onSuccessResponse)i(r);this.idAwaiter[r.id](r.result)}else if(this.isErrorResponse(r)){for(let i of this.onErrorResponse)i(r);this.idAwaiter[r.id](r.error)}}}call(t,n){return new Promise((r,i)=>{let s=this.buildRequest(t,n),a;this.config.responseTimeout&&(a=setTimeout(()=>{delete this.idAwaiter[s.id],i(new Error(`Awaiting response to "${t}" with id: ${s.id} timed out.`))},this.config.responseTimeout)),this.idAwaiter[s.id]=c=>{if(clearInterval(a),delete this.idAwaiter[s.id],this.isRpcError(c)){i(new Error(`RPC Error (${c.code}): ${c.message}`));return}r(c)};let o=JSON.stringify(s);this.ws.send(o)})}notify(t,n){this.ws.send(JSON.stringify(this.buildNotification(t,n)))}customId(t){this.idFn=t}noRpc(){this.buildRequest=this.buildRequestBase,this.buildNotification=this.buildNotificationBase,this.buildRpcSuccessResponse=this.buildRpcSuccessResponseBase,this.buildRpcErrorResponse=this.buildRpcErrorResponseBase}configure(t){Object.assign(this.config,t)}changeSocket(t){this.ws=t}listen(){return new Promise((t,n)=>{this.ws.onopen=r=>{for(let i of this.onOpenHandlers)i(r);t(r)},this.listenMessages(),this.ws.onerror=r=>{for(let i of this.onErrorHandlers)i(r)},this.ws.onclose=r=>{for(let i of this.onCloseHandlers)i(r);n(new Error(`WebSocket closed with code: ${r.code} and reason: ${r.reason}`))}})}buildRequest(t,n){let r=this.buildRequestBase(t,n);return r.jsonrpc="2.0",r}buildRequestBase(t,n){let r={};return r.id=this.idFn(),r.method=t,n&&(r.params=n),r}buildNotification(t,n){let r=this.buildNotificationBase(t,n);return r.jsonrpc="2.0",r}buildNotificationBase(t,n){let r={};return r.method=t,n&&(r.params=n),r}buildRpcSuccessResponse(t,n){let r=this.buildRpcSuccessResponseBase(t,n);return r.jsonrpc="2.0",r}buildRpcSuccessResponseBase(t,n){let r={};return r.id=t,r.result=n,r}buildRpcErrorResponse(t,n){let r=this.buildRpcErrorResponseBase(t,n);return r.jsonrpc="2.0",r}buildRpcErrorResponseBase(t,n){let r={};return r.id=t,r.error=n,r}idFn(){return Fi(12)}isNotification(t){return!t.id}isRequest(t){return t.method}isSuccessResponse(t){return t.hasOwnProperty("result")}isErrorResponse(t){return t.hasOwnProperty("error")}isRpcError(t){return typeof t?.code<"u"}};l();function M$(e){return new Promise(t=>setTimeout(t,e))}var ip=M$;l();l();var nc=class extends Error{constructor(t){super(t),this.name="AuthenticationError"}},rc=class extends Error{constructor(t){super(t),this.name="CurrentWorkingDirectoryDoesntExistError"}};function ic(e){if(e=e||process?.env?.E2B_API_KEY,!e)throw new nc("API key is required, please visit https://e2b.dev/docs to get your API key. You can either set the environment variable `E2B_API_KEY` or you can pass it directly to the sandbox like Sandbox.create({apiKey: 'e2b_...'})");return e}var nv=_n(gt.path("/sandboxes").method("get").create()),rv=_n(gt.path("/sandboxes").method("post").create()),iv=_n(gt.path("/sandboxes/{sandboxID}").method("delete").create()),sp=_n(gt.path("/sandboxes/{sandboxID}/refreshes").method("post").create()),sc=class{constructor(t){this.opts=t;this.sandbox=t.__sandbox,this.apiKey=ic(t.apiKey),this.cwd=t.cwd,this.cwd&&this.cwd.startsWith("~")&&(this.cwd=this.cwd.replace("~","/home/user"));let n={PYTHONUNBUFFERED:"1"};this.envVars={...n,...t.envVars||{}},this.logger=t.logger??{info:console.info,warn:console.warn,error:console.error},this.logger.debug?.(`Sandbox "${this.templateID}" initialized`)}cwd;envVars;logger;sandbox;isOpen=!1;apiKey;rpc=new tc;subscribers=[];get id(){return`${this.sandbox?.sandboxID}-${this.sandbox?.clientID}`}get templateID(){return this.opts.template||this.opts.id||"base"}static async list(t){t=ic(t);try{return(await nv(t,{})).data.map(r=>({sandboxID:`${r.sandboxID}-${r.clientID}`,templateID:r.templateID,cpuCount:r.cpuCount,memoryMB:r.memoryMB,...r.alias&&{alias:r.alias},...r.metadata&&{metadata:r.metadata},startedAt:new Date(r.startedAt)}))}catch(n){if(n instanceof nv.Error){let r=n.getActualType();if(r.status===401)throw new Error(`Error listing sandboxes - (${r.status}) unauthenticated: ${r.data.message}`);if(r.status===500)throw new Error(`Error listing sandboxes - (${r.status}) server error: ${r.data.message}`)}throw n}}static async kill(t,n){n=ic(n);let r=t.split("-")[0];try{await iv(n,{sandboxID:r})}catch(i){if(i instanceof iv.Error){let s=i.getActualType();if(s.status===401)throw new Error(`Error killing sandbox (${t}) - (${s.status}) unauthenticated: ${s.data.message}`);if(s.status===500)throw new Error(`Error killing sandbox (${t}) - (${s.status}) server error: ${s.data.message}`)}throw i}}async keepAlive(t){if(t=Math.round(t/1e3),t<0||t>3600)throw new Error("Duration must be between 0 and 3600 seconds");if(!this.sandbox)throw new Error("Cannot keep alive - sandbox is not initialized");await sp(this.apiKey,{sandboxID:this.sandbox?.sandboxID,duration:t})}getHostname(t){if(this.opts.__debug_hostname)return t&&this.opts.__debug_devEnv==="remote"?`${t}-${this.opts.__debug_hostname}`:t?`${this.opts.__debug_hostname}:${t}`:this.opts.__debug_hostname;if(!this.sandbox)throw new Error("Cannot get sandbox's hostname - sandbox is not initialized");let n=`${this.id}.${Cm}`;return t?`${t}-${n}`:n}getProtocol(t="http",n=Dm){return n?`${t}s`:t}async close(){this.isOpen&&(this.logger.debug?.(`Closing sandbox "${this.id}"`),this.isOpen=!1,this.rpc.ws?.terminate?.(),this.rpc.ws?.close?.(),this.subscribers=[],this.logger.debug?.("Disconnected from the sandbox"))}async _call(t,n,r,i){return this.logger.debug?.(`Calling "${t}_${n}" with params:`,r),await mn(async(a,o)=>await this.rpc.call(a,o),i?.timeout)(`${t}_${n}`,r)}async _handleSubscriptions(...t){let n=await Promise.allSettled(t);if(n.every(r=>r.status==="fulfilled"))return n.map(r=>r.status==="fulfilled"?r.value:void 0);throw await Promise.all(n.filter(Cy).map(r=>r.value?this._unsubscribe(r.value):void 0)),new Error(ia(n))}async _unsubscribe(t){let n=this.subscribers.find(r=>r.subID===t);n&&(await this._call(n.service,"unsubscribe",[n.subID]),this.subscribers=this.subscribers.filter(r=>r!==n),this.logger.debug?.(`Unsubscribed '${t}' from '${n.service}'`))}async _subscribe(t,n,r,...i){let s=await this._call(t,"subscribe",[r,...i]);if(typeof s!="string")throw new Error(`Cannot subscribe to ${t}_${r}${i.length>0?" with params ["+i.join(", ")+"]":""}. Expected response should have been a subscription ID, instead we got ${JSON.stringify(s)}`);return this.subscribers.push({handler:n,service:t,subID:s}),this.logger.debug?.(`Subscribed to "${t}_${r}"${i.length>0?" with params ["+i.join(", ")+"] and":""} with id "${s}"`),s}async _open(t){let n=async()=>{if(this.isOpen)throw new Error("Sandbox connect was already called");if(this.isOpen=!0,this.logger.debug?.("Opening sandbox..."),!this.sandbox&&!this.opts.__debug_hostname)try{let r=await rv(this.apiKey,{templateID:this.templateID,metadata:this.opts.metadata});this.sandbox=r.data,this.logger.debug?.(`Acquired sandbox "${this.id}"`)}catch(r){if(r instanceof rv.Error){let i=r.getActualType();if(i.status===400)throw new Error(`Error creating sandbox - (${i.status}) bad request: ${i.data.message}`);if(i.status===401)throw new Error(`Error creating sandbox - (${i.status}) unauthenticated: ${i.data.message}`);if(i.status===500)throw new Error(`Error creating sandbox - (${i.status}) server error: ${i.data.message}`)}throw r}return this.sandbox&&!this.opts.__debug_hostname&&this.refresh(this.sandbox.sandboxID),await this.connectRpc(),this};try{return await mn(n,t?.timeout)()}catch(r){throw await this.close(),r}}async connectRpc(){let t=this.getHostname(this.opts.__debug_port||Pl),r=`${this.getProtocol("ws",this.opts.__debug_devEnv!=="local")}://${t}${Ey}`,i=!1,s,a,o=new Promise((c,u)=>{s=()=>{i||(i=!0,c())},a=()=>{i||(i=!0,u())}});this.rpc.onOpen(()=>{this.logger.debug?.(`Connected to sandbox "${this.id}"`),s?.()}),this.rpc.onError(async c=>{if(this.logger.debug?.(`Error in WebSocket of sandbox "${this.id}": ${c.message??c.code??c.toString()}. Trying to reconnect...`),this.isOpen){await ip(150),this.logger.debug?.(`Reconnecting to sandbox "${this.id}"`);try{this.subscribers=[],await this.rpc.connect(r),this.logger.debug?.(`Reconnected to sandbox "${this.id}"`)}catch(u){this.logger.debug?.(`Failed reconnecting to sandbox "${this.id}": ${u.message??u.code??u.toString()}`)}}else a?.()}),this.rpc.onClose(async()=>{this.logger.debug?.(`WebSocket connection to sandbox "${this.id}" closed`)}),this.rpc.onNotification.push(this.handleNotification.bind(this)),(async()=>{try{this.logger.debug?.(`Connecting to sandbox "${this.id}"`),await this.rpc.connect(r)}catch(c){this.logger.debug?.(`Error connecting to sandbox "${this.id}": ${c.message??c.code??c.toString()}`)}})(),await o}handleNotification(t){this.logger.debug?.("Handling notification:",t),this.subscribers.filter(n=>n.subID===t.params?.subscription).forEach(n=>n.handler(t.params?.result))}async refresh(t){this.logger.debug?.(`Started refreshing sandbox "${t}"`);try{for(;;){if(!this.isOpen){this.logger.debug?.(`Cannot refresh sandbox ${this.id} - it was closed`);return}await ip(5e3);try{await sp(this.apiKey,{sandboxID:t,duration:0}),this.logger.debug?.(`Refreshed sandbox "${t}"`)}catch(n){if(n instanceof sp.Error){let r=n.getActualType();if(r.status===404){this.logger.warn?.(`Error refreshing sandbox - (${r.status}): ${r.data.message}`);return}this.logger.warn?.(`Refreshing sandbox "${t}" failed - (${r.status})`)}}}}finally{this.logger.debug?.(`Stopped refreshing sandbox "${t}"`),await this.close()}}};l();var ga=J(ov()),lv=(e,t,n)=>{let r;return e.startsWith("./")?(r=ga.default.posix.join(t||"/home/user",e),t||n.warn?.(`Path starts with './' and cwd isn't set. The path '${e}' will evaluate to '${r}', which may not be what you want.`),r):e.startsWith("../")?(r=ga.default.posix.join(t||"/home/user",e),t||n.warn?.(`Path starts with '../' and cwd isn't set. The path '${e}' will evaluate to '${r}', which may not be what you want.`),r):e.startsWith("~/")?(r=ga.default.posix.join(t||"/home/user",e.substring(2)),t||n.warn?.(`Path starts with '~/' and cwd isn't set. The path '${e}' will evaluate to '${r}', which may not be what you want.`),r):!e.startsWith("/")&&t?ga.default.posix.join(t,e):e};l();var ac=class{constructor(t){this.sandbox=t}async run(t){if(t.status!=="requires_action")return[];if(!t.required_action)return[];let n=[];for(let r of t.required_action.submit_tool_outputs.tool_calls){let i=this.sandbox._actions.get(r.function.name);if(!i){console.warn(`Action ${r.function.name} not found`);continue}let s=JSON.parse(r.function.arguments),a=await i(this.sandbox,s);n.push({tool_call_id:r.id,output:a})}return n}};var Kr=class e extends sc{terminal;filesystem;process;_actions=new Map;onScanPorts;constructor(t){t=t||{},super(t),this.onScanPorts=t.onScanPorts,this.filesystem={list:async(r,i)=>await this._call(pn,"list",[n(r)],i),read:async(r,i)=>await this._call(pn,"read",[n(r)],i),remove:async(r,i)=>{await this._call(pn,"remove",[n(r)],i)},write:async(r,i,s)=>{await this._call(pn,"write",[n(r),i],s)},writeBytes:async(r,i)=>{let s=Buffer.from(i).toString("base64");await this._call(pn,"writeBase64",[n(r),s])},readBytes:async r=>{let i=await this._call(pn,"readBase64",[n(r)]);return Buffer.from(i,"base64")},makeDir:async(r,i)=>{await this._call(pn,"makeDir",[n(r)],i)},watchDir:r=>{this.logger.debug?.(`Watching directory "${r}"`);let i=(0,cv.default)(n(r));return new Ry(this,i)}},this.terminal={start:async({onData:r,size:i,onExit:s,envVars:a,cmd:o,cwd:c="",terminalID:u=Fi(12),timeout:d=void 0})=>await mn(async({onData:g,size:S,onExit:h,envVars:C,cmd:I,cwd:F="",rootDir:U,terminalID:B=Fi(12)})=>{this.logger.debug?.(`Starting terminal "${B}"`),!F&&U&&(this.logger.warn?.("The rootDir parameter is deprecated, use cwd instead."),F=U),!F&&this.cwd&&(F=this.cwd),C=C||{},C={...this.envVars,...C};let{promise:w,resolve:Y}=sa(),k=new Bl;function q(ie){k.addData(ie),g?.(ie)}let[M,L]=await this._handleSubscriptions(this._subscribe(Yr,q,"onData",B),this._subscribe(Yr,Y,"onExit",B)),{promise:$,resolve:V}=sa();w.then(async()=>{Promise.allSettled([this._unsubscribe(L),this._unsubscribe(M)]).then(ie=>{let se=ia(ie);se&&this.logger.debug?.(se)}),this.logger.debug?.(`Terminal "${B}" exited`),h?.(),V(k)});try{await this._call(Yr,"start",[B,S.cols,S.rows,...I!==void 0?[C,I,F]:[]])}catch(ie){throw Y(),await $,ie}return new Ul(B,this,Y,$,k)},d)({onData:r,size:i,onExit:s,envVars:a,cmd:o,cwd:c,terminalID:u})},this.process={start:async r=>{let i=typeof r=="string"?{cmd:r}:r,s=async({cmd:o,onStdout:c,onStderr:u,onExit:d,envVars:m={},cwd:g="",rootDir:S,processID:h=Fi(12)})=>{if(!g&&S&&(this.logger.warn?.("The rootDir parameter is deprecated, use cwd instead."),g=S),!g&&this.cwd&&(g=this.cwd),!o)throw new Error("cmd is required");m=m||{},m={...this.envVars,...m},this.logger.debug?.(`Starting process "${h}", cmd: "${o}"`);let{promise:C,resolve:I}=sa(),F=new Gl,U=$=>{F.setExitCode($),I()},B=$=>{let V=new aa($.line,$.timestamp,!1);F.addStdout(V),c?c(V):this.opts.onStdout&&this.opts.onStdout(V)},w=$=>{let V=new aa($.line,$.timestamp,!0);F.addStderr(V),u?u(V):this.opts.onStderr&&this.opts.onStderr(V)},[Y,k,q]=await this._handleSubscriptions(this._subscribe(qr,U,"onExit",h),this._subscribe(qr,B,"onStdout",h),this._subscribe(qr,w,"onStderr",h)),{promise:M,resolve:L}=sa();C.then(async()=>{Promise.allSettled([this._unsubscribe(Y),k?this._unsubscribe(k):void 0,q?this._unsubscribe(q):void 0]).then($=>{let V=ia($);V&&this.logger.debug?.(V)}),this.logger.debug?.(`Process "${h}" exited`),d?d(F.exitCode||0):this.opts.onExit&&this.opts.onExit(),L(F)});try{await this._call(qr,"start",[h,o,m,g])}catch($){throw I(),await M,/error starting process '\w+': fork\/exec \/bin\/bash: no such file or directory/.test($?.message)?new rc(`Failed to start the process. You are trying set 'cwd' to a directory that does not exist.
|
|
94
94
|
${$?.message}`):$}return new Hl(h,this,I,M,F)},a=i.timeout;return await mn(s,a)(i)},startAndWait:async r=>{let i=typeof r=="string"?{cmd:r}:r;return await(await this.process.start(i)).wait()}};let n=r=>lv(r,this.cwd,this.logger)}get fileURL(){let t=this.getProtocol("http",this.opts.__debug_devEnv!=="local"),n=this.getHostname(this.opts.__debug_port||Pl);return`${t}://${n}${fy}`}get actions(){return new Map(this._actions)}get openai(){return{actions:new ac(this)}}static async create(t){let n=typeof t=="string"?{template:t}:t,r=new e(n);return await r._open({timeout:n?.timeout}),r}static async reconnect(t){let n,r;typeof t=="string"?(n=t,r={}):(n=t.sandboxID,r=t);let i=n.split("-"),s=i[0],a=i[1];r.__sandbox={sandboxID:s,clientID:a,templateID:"unknown"};let o=new this(r);return await o._open({timeout:r?.timeout}),o}addAction(t,n){if(typeof t=="string"){if(!n)throw new Error("Action is required");return this._actions.set(t,n),this}else if(typeof t=="function"){if(n=t,!n.name)throw new Error("Action name is required");this._actions.set(n.name,n)}else throw new Error("Action or action name and action is required");return this}removeAction(t){return this._actions.delete(t),this}async uploadFile(t,n){let r=new FormData,i=t instanceof Blob?t:new Blob([t],{type:"application/octet-stream"});r.append("file",i,n);let s=await fetch(this.fileURL,{method:"POST",body:r});if(!s.ok){let a=await s.text();throw new Error(`Failed to upload file ${s.status} - ${s.statusText}: ${a}`)}return`/home/user/${n}`}async downloadFile(t,n){t=encodeURIComponent(t);let r=await fetch(`${this.fileURL}?path=${t}`);if(!r.ok){let i=await r.text();throw new Error(`Failed to download file '${t}': ${i}`)}switch(n){case"base64":return Buffer.from(await r.arrayBuffer()).toString("base64");case"blob":return await r.blob();case"buffer":return Buffer.from(await r.arrayBuffer());case"arraybuffer":return await r.arrayBuffer();case"text":return await r.text();default:return await r.arrayBuffer()}}async _open(t){await super._open(t);let n=this.onScanPorts?r=>this.onScanPorts?.(r.map(i=>({ip:i.Ip,port:i.Port,state:i.State}))):void 0;return await this._handleSubscriptions(n?this._subscribe(Ny,n,"scanOpenedPorts"):void 0),this.cwd&&(console.log(`Custom cwd for Sandbox set: "${this.cwd}"`),await this.filesystem.makeDir(this.cwd)),(this.opts.onStdout||this.opts.onStderr)&&this.handleStartCmdLogs(),this}async handleStartCmdLogs(){try{await this.process.startAndWait({cmd:"sudo journalctl --follow --lines=all -o cat _SYSTEMD_UNIT=start_cmd.service",envVars:{},cwd:"/"})}catch(t){this.logger.debug?.("start command not started",t)}}};l();async function uv(e){return new Promise(t=>setTimeout(t,e))}l();l();var dv=J(require("os")),_v=J(require("path")),oc=J(require("fs")),gr=_v.join(dv.homedir(),".e2b","config.json"),ap=process.env.E2B_DOCS_BASE||"https://e2b.dev/docs";function Qr(){return oc.existsSync(gr)?JSON.parse(oc.readFileSync(gr,"utf8")):null}var lc=process.env.E2B_API_KEY,cc=process.env.E2B_ACCESS_TOKEN,mv=Ur(`You must be logged in to use this command. Run ${De("e2b auth login")}.
|
|
95
95
|
|
|
96
96
|
If you are seeing this message in CI/CD you may need to set the ${De("E2B_ACCESS_TOKEN")} environment variable.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@e2b/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.4",
|
|
4
4
|
"description": "CLI for managing e2b sandbox templates",
|
|
5
5
|
"homepage": "https://e2b.dev",
|
|
6
6
|
"license": "MIT",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"cli-highlight": "^2.1.11",
|
|
50
50
|
"commander": "^11.1.0",
|
|
51
51
|
"console-table-printer": "^2.11.2",
|
|
52
|
-
"e2b": "^0.12.
|
|
52
|
+
"e2b": "^0.12.4",
|
|
53
53
|
"ignore": "^5.2.4",
|
|
54
54
|
"inquirer": "^9.2.12",
|
|
55
55
|
"open": "^9.1.0",
|