@e2b/cli 0.1.6 → 0.1.8

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.
Files changed (2) hide show
  1. package/dist/index.js +6 -6
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -71,7 +71,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),ke=H,N=J);let oe={code
71
71
  `),a+=t+"[["+s+`]]
72
72
  `,a+=P1(s+".",t,o)}),a}function bX(e,t,n,r){var i=e+Jc(n),s="";return t9(r).length>0&&(s+=t+"["+i+`]
73
73
  `),s+P1(i+".",t,r)}});var c9=E(B1=>{"use strict";l();B1.parse=e9();B1.stringify=l9()});var Y1=E(Ji=>{"use strict";l();Object.defineProperty(Ji,"__esModule",{value:!0});Ji.DEFAULT_COLOR_MAP=void 0;Ji.DEFAULT_COLOR_MAP={red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",white_bold:"\x1B[01m",reset:"\x1B[0m"};var H1=class{constructor(t=Ji.DEFAULT_COLOR_MAP){this.text="",this.colorMap=t}addCharsWithColor(t,n){let r=this.colorMap[t];this.text+=r!==void 0?`${r}${n}${this.colorMap.reset}`:n}renderConsole(){return this.text}};Ji.default=H1});var La=E(Qe=>{"use strict";l();Object.defineProperty(Qe,"__esModule",{value:!0});Qe.DEFAULT_HEADER_ALIGNMENT=Qe.DEFAULT_ROW_ALIGNMENT=Qe.DEFAULT_HEADER_FONT_COLOR=Qe.DEFAULT_ROW_FONT_COLOR=Qe.COLORS=Qe.ALIGNMENTS=Qe.DEFAULT_TABLE_STYLE=Qe.DEFAULT_ROW_SEPARATOR=Qe.DEFAULT_COLUMN_LEN=void 0;Qe.DEFAULT_COLUMN_LEN=20;Qe.DEFAULT_ROW_SEPARATOR=!1;Qe.DEFAULT_TABLE_STYLE={headerTop:{left:"\u250C",mid:"\u252C",right:"\u2510",other:"\u2500"},headerBottom:{left:"\u251C",mid:"\u253C",right:"\u2524",other:"\u2500"},tableBottom:{left:"\u2514",mid:"\u2534",right:"\u2518",other:"\u2500"},vertical:"\u2502",rowSeparator:{left:"\u251C",mid:"\u253C",right:"\u2524",other:"\u2500"}};Qe.ALIGNMENTS=["right","left","center"];Qe.COLORS=["red","green","yellow","white","blue","magenta","cyan","white_bold","reset"];Qe.DEFAULT_ROW_FONT_COLOR="white";Qe.DEFAULT_HEADER_FONT_COLOR="white_bold";Qe.DEFAULT_ROW_ALIGNMENT="right";Qe.DEFAULT_HEADER_ALIGNMENT="center"});var q1=E(Bn=>{"use strict";l();Object.defineProperty(Bn,"__esModule",{value:!0});Bn.rawColumnToInternalColumn=Bn.objIfExists=void 0;var OX=La(),IX=(e,t)=>t?{[e]:t}:{};Bn.objIfExists=IX;var yX=e=>{var t;return Object.assign(Object.assign(Object.assign(Object.assign({name:e.name,title:(t=e.title)!==null&&t!==void 0?t:e.name},(0,Bn.objIfExists)("color",e.color)),(0,Bn.objIfExists)("maxLen",e.maxLen)),(0,Bn.objIfExists)("minLen",e.minLen)),{alignment:e.alignment||OX.DEFAULT_ROW_ALIGNMENT})};Bn.rawColumnToInternalColumn=yX});var f9=E(V1=>{"use strict";l();Object.defineProperty(V1,"__esModule",{value:!0});var vX=[{first:768,last:879},{first:1155,last:1158},{first:1160,last:1161},{first:1425,last:1469},{first:1471,last:1471},{first:1473,last:1474},{first:1476,last:1477},{first:1479,last:1479},{first:1536,last:1539},{first:1552,last:1557},{first:1611,last:1630},{first:1648,last:1648},{first:1750,last:1764},{first:1767,last:1768},{first:1770,last:1773},{first:1807,last:1807},{first:1809,last:1809},{first:1840,last:1866},{first:1958,last:1968},{first:2027,last:2035},{first:2305,last:2306},{first:2364,last:2364},{first:2369,last:2376},{first:2381,last:2381},{first:2385,last:2388},{first:2402,last:2403},{first:2433,last:2433},{first:2492,last:2492},{first:2497,last:2500},{first:2509,last:2509},{first:2530,last:2531},{first:2561,last:2562},{first:2620,last:2620},{first:2625,last:2626},{first:2631,last:2632},{first:2635,last:2637},{first:2672,last:2673},{first:2689,last:2690},{first:2748,last:2748},{first:2753,last:2757},{first:2759,last:2760},{first:2765,last:2765},{first:2786,last:2787},{first:2817,last:2817},{first:2876,last:2876},{first:2879,last:2879},{first:2881,last:2883},{first:2893,last:2893},{first:2902,last:2902},{first:2946,last:2946},{first:3008,last:3008},{first:3021,last:3021},{first:3134,last:3136},{first:3142,last:3144},{first:3146,last:3149},{first:3157,last:3158},{first:3260,last:3260},{first:3263,last:3263},{first:3270,last:3270},{first:3276,last:3277},{first:3298,last:3299},{first:3393,last:3395},{first:3405,last:3405},{first:3530,last:3530},{first:3538,last:3540},{first:3542,last:3542},{first:3633,last:3633},{first:3636,last:3642},{first:3655,last:3662},{first:3761,last:3761},{first:3764,last:3769},{first:3771,last:3772},{first:3784,last:3789},{first:3864,last:3865},{first:3893,last:3893},{first:3895,last:3895},{first:3897,last:3897},{first:3953,last:3966},{first:3968,last:3972},{first:3974,last:3975},{first:3984,last:3991},{first:3993,last:4028},{first:4038,last:4038},{first:4141,last:4144},{first:4146,last:4146},{first:4150,last:4151},{first:4153,last:4153},{first:4184,last:4185},{first:4448,last:4607},{first:4959,last:4959},{first:5906,last:5908},{first:5938,last:5940},{first:5970,last:5971},{first:6002,last:6003},{first:6068,last:6069},{first:6071,last:6077},{first:6086,last:6086},{first:6089,last:6099},{first:6109,last:6109},{first:6155,last:6157},{first:6313,last:6313},{first:6432,last:6434},{first:6439,last:6440},{first:6450,last:6450},{first:6457,last:6459},{first:6679,last:6680},{first:6912,last:6915},{first:6964,last:6964},{first:6966,last:6970},{first:6972,last:6972},{first:6978,last:6978},{first:7019,last:7027},{first:7616,last:7626},{first:7678,last:7679},{first:8203,last:8207},{first:8234,last:8238},{first:8288,last:8291},{first:8298,last:8303},{first:8400,last:8431},{first:12330,last:12335},{first:12441,last:12442},{first:43014,last:43014},{first:43019,last:43019},{first:43045,last:43046},{first:64286,last:64286},{first:65024,last:65039},{first:65056,last:65059},{first:65279,last:65279},{first:65529,last:65531},{first:68097,last:68099},{first:68101,last:68102},{first:68108,last:68111},{first:68152,last:68154},{first:68159,last:68159},{first:119143,last:119145},{first:119155,last:119170},{first:119173,last:119179},{first:119210,last:119213},{first:119362,last:119364},{first:917505,last:917505},{first:917536,last:917631},{first:917760,last:917999}];V1.default=vX});var g9=E($1=>{"use strict";l();Object.defineProperty($1,"__esModule",{value:!0});var xX=(e,t,n)=>{let r=0,i,s=n;if(e<t[0].first||e>t[s].last)return 0;for(;s>=r;)if(i=Math.floor((r+s)/2),e>t[i].last)r=i+1;else if(e<t[i].first)s=i-1;else return 1;return 0};$1.default=xX});var W1=E(wa=>{"use strict";l();var S9=wa&&wa.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(wa,"__esModule",{value:!0});var h9=S9(f9()),MX=S9(g9()),LX=e=>e===0?0:e<32||e>=127&&e<160?-1:MX.default(e,h9.default,h9.default.length-1)?0:1+ +(e>=4352&&(e<=4447||e===9001||e===9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=131072&&e<=196605||e>=196608&&e<=262141));wa.default=LX});var T9=E(Pa=>{"use strict";l();var wX=Pa&&Pa.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Pa,"__esModule",{value:!0});var PX=wX(W1()),FX=e=>{let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n),i=PX.default(r);if(i<0)return-1;t+=i}return t};Pa.default=FX});var D9=E(Tr=>{"use strict";l();var b9=Tr&&Tr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Tr,"__esModule",{value:!0});Tr.wcswidth=Tr.wcwidth=void 0;var kX=b9(T9());Tr.wcswidth=kX.default;var BX=b9(W1());Tr.wcwidth=BX.default});var K1=E(Xr=>{"use strict";l();Object.defineProperty(Xr,"__esModule",{value:!0});Xr.findWidthInConsole=Xr.stripAnsi=void 0;var UX=D9(),GX=/\x1b\[\d{1,3}(;\d{1,3})*m/g,HX=e=>e.replace(GX,"");Xr.stripAnsi=HX;var YX=(e,t)=>{let n=0;return e=(0,Xr.stripAnsi)(e),t&&Object.entries(t).forEach(([r,i])=>{let s=new RegExp(r,"g");n+=(e.match(s)||[]).length*i,e=e.replace(r,"")}),n+=(0,UX.wcswidth)(e),n};Xr.findWidthInConsole=YX});var Q1=E(br=>{"use strict";l();Object.defineProperty(br,"__esModule",{value:!0});br.biggestWordInSentence=br.limitWidth=br.textWithPadding=void 0;var z1=K1(),qX=(e,t,n,r)=>{let i=(0,z1.findWidthInConsole)(e,r),s=Math.floor((n-i)/2),a=n-s-i;if(n<i)return e;switch(t){case"left":return e.concat(" ".repeat(n-i));case"center":return" ".repeat(s).concat(e).concat(" ".repeat(a));case"right":default:return" ".repeat(n-i).concat(e)}};br.textWithPadding=qX;var VX=(e,t,n)=>{let r=[],i=e.split(" "),s=[],a=0;return i.forEach(o=>{let c=(0,z1.findWidthInConsole)(o,n);a+c<=t?(a+=c+1,s.push(o)):(r.push(s.join(" ")),s=[o],a=c+1)}),r.push(s.join(" ")),r};br.limitWidth=VX;var $X=(e,t)=>e.split(" ").reduce((n,r)=>Math.max(n,(0,z1.findWidthInConsole)(r,t)),0);br.biggestWordInSentence=$X});var Fa=E(ve=>{"use strict";l();Object.defineProperty(ve,"__esModule",{value:!0});ve.getWidthLimitedColumnsArray=ve.createHeaderAsRow=ve.renderTableHorizontalBorders=ve.findLenOfColumn=ve.createRow=ve.createColumFromComputedColumn=ve.createColumFromOnlyName=ve.createTableHorizontalBorders=ve.convertRawRowOptionsToStandard=ve.cellText=void 0;var X1=q1(),C9=K1(),j1=Q1(),ru=La(),es=(e,t)=>Math.max(e,t),WX=e=>e==null?"":`${e}`;ve.cellText=WX;var KX=e=>{if(e)return{color:e.color,separator:e.separator||ru.DEFAULT_ROW_SEPARATOR}};ve.convertRawRowOptionsToStandard=KX;var zX=({left:e,mid:t,right:n,other:r},i)=>{let s=e;return i.forEach(a=>{s+=r.repeat(a+2),s+=t}),s=s.slice(0,-t.length),s+=n,s};ve.createTableHorizontalBorders=zX;var QX=e=>({name:e,title:e});ve.createColumFromOnlyName=QX;var XX=e=>{var t;return Object.assign(Object.assign(Object.assign(Object.assign({name:e.name,title:(t=e.title)!==null&&t!==void 0?t:e.name},(0,X1.objIfExists)("color",e.color)),(0,X1.objIfExists)("maxLen",e.maxLen)),(0,X1.objIfExists)("minLen",e.minLen)),{alignment:e.alignment||ru.DEFAULT_ROW_ALIGNMENT})};ve.createColumFromComputedColumn=XX;var jX=(e,t,n)=>({color:e,separator:n,text:t});ve.createRow=jX;var ZX=(e,t,n)=>{let r=e.name,i=e.title,s=es(0,e?.minLen||0);return e.maxLen?(s=es(s,es(e.maxLen,(0,j1.biggestWordInSentence)(i,n))),s=t.reduce((a,o)=>es(a,(0,j1.biggestWordInSentence)((0,ve.cellText)(o.text[r]),n)),s),s):(s=es(s,(0,C9.findWidthInConsole)(i,n)),t.forEach(a=>{s=es(s,(0,C9.findWidthInConsole)((0,ve.cellText)(a.text[r]),n))}),s)};ve.findLenOfColumn=ZX;var JX=(e,t)=>(0,ve.createTableHorizontalBorders)(e,t);ve.renderTableHorizontalBorders=JX;var ej=(e,t)=>{let n=ru.DEFAULT_HEADER_FONT_COLOR,r=e(n,{},!1);return t.forEach(i=>{r.text[i.name]=i.title}),r};ve.createHeaderAsRow=ej;var tj=(e,t,n)=>{let r={};return e.forEach(i=>{r[i.name]=(0,j1.limitWidth)((0,ve.cellText)(t.text[i.name]),i.length||ru.DEFAULT_COLUMN_LEN,n)}),r};ve.getWidthLimitedColumnsArray=tj});var A9=E(ts=>{"use strict";l();Object.defineProperty(ts,"__esModule",{value:!0});ts.preProcessRows=ts.preProcessColumns=void 0;var nj=Fa(),rj=e=>{e.computedColumns.length&&e.computedColumns.forEach(t=>{e.addColumn(t),e.rows.forEach(n=>{n.text[t.name]=t.function(n.text)})})},ij=e=>{e.enabledColumns.length&&(e.columns=e.columns.filter(t=>e.enabledColumns.includes(t.name)))},sj=e=>{e.disabledColumns.length&&(e.columns=e.columns.filter(t=>!e.disabledColumns.includes(t.name)))},aj=e=>{e.columns.forEach(t=>{t.length=(0,nj.findLenOfColumn)(t,e.rows,e.charLength)})},oj=e=>{rj(e),sj(e),ij(e),aj(e)};ts.preProcessColumns=oj;var lj=e=>{let t=e.rows.filter(n=>e.filterFunction(n.text)).sort((n,r)=>e.sortFunction(n.text,r.text));e.rows=t};ts.preProcessRows=lj});var Z1=E(Yt=>{"use strict";l();var N9=Yt&&Yt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Yt,"__esModule",{value:!0});Yt.printSimpleTable=Yt.renderSimpleTable=Yt.renderTable=void 0;var O9=N9(Y1()),I9=Q1(),Jt=La(),Dr=Fa(),cj=N9(J1()),R9=A9(),uj=(e,t,n,r,i,s,a,o)=>{let c=new O9.default(a);return c.addCharsWithColor("",e.vertical),t.forEach(u=>{let m=n<r[u.name].length?(0,Dr.cellText)(r[u.name][n]):"";c.addCharsWithColor(Jt.DEFAULT_ROW_FONT_COLOR," "),c.addCharsWithColor(i&&Jt.DEFAULT_HEADER_FONT_COLOR||u.color||s.color,(0,I9.textWithPadding)(m,u.alignment||Jt.DEFAULT_ROW_ALIGNMENT,u.length||Jt.DEFAULT_COLUMN_LEN,o)),c.addCharsWithColor("",` ${e.vertical}`)}),c.renderConsole()},y9=(e,t,n,r,i,s)=>{let a=(0,Dr.getWidthLimitedColumnsArray)(t,n,s),o=Object.values(a).reduce((u,_)=>Math.max(u,_.length),0),c=[];for(let u=0;u<o;u+=1){let _=uj(e,t,u,a,i,n,r,s);c.push(_)}return c},_j=(e,t)=>{let n=[];return n=n.concat(y9(e.tableStyle,e.columns,t,e.colorMap,void 0,e.charLength)),n},dj=e=>{let t=[];if(e.title===void 0)return t;let n=()=>{let s=(a,o)=>a+o+2+1;return e.columns.map(a=>a.length||Jt.DEFAULT_COLUMN_LEN).reduce(s,1)},r=(0,I9.textWithPadding)(e.title,Jt.DEFAULT_HEADER_ALIGNMENT,n()),i=new O9.default(e.colorMap);return i.addCharsWithColor(Jt.DEFAULT_HEADER_FONT_COLOR,r),t.push(i.renderConsole()),t},mj=e=>{let t=[];t.push((0,Dr.renderTableHorizontalBorders)(e.tableStyle.headerTop,e.columns.map(r=>r.length||Jt.DEFAULT_COLUMN_LEN)));let n=(0,Dr.createHeaderAsRow)(Dr.createRow,e.columns);return t=t.concat(y9(e.tableStyle,e.columns,n,e.colorMap,!0)),t.push((0,Dr.renderTableHorizontalBorders)(e.tableStyle.headerBottom,e.columns.map(r=>r.length||Jt.DEFAULT_COLUMN_LEN))),t},pj=e=>{let t=[];return t.push((0,Dr.renderTableHorizontalBorders)(e.tableStyle.tableBottom,e.columns.map(n=>n.length||Jt.DEFAULT_COLUMN_LEN))),t},Ej=(e,t)=>{let n=[],r=e.rows.length-1;return e.rows.indexOf(t)!==r&&t.separator&&n.push((0,Dr.renderTableHorizontalBorders)(e.tableStyle.rowSeparator,e.columns.map(s=>s.length||Jt.DEFAULT_COLUMN_LEN))),n},fj=e=>{(0,R9.preProcessColumns)(e),(0,R9.preProcessRows)(e);let t=[];return dj(e).forEach(n=>t.push(n)),mj(e).forEach(n=>t.push(n)),e.rows.forEach(n=>{_j(e,n).forEach(r=>t.push(r)),Ej(e,n).forEach(r=>t.push(r))}),pj(e).forEach(n=>t.push(n)),t.join(`
74
- `)};Yt.renderTable=fj;var gj=e=>{let t=new cj.default;return t.addRows(e),(0,Yt.renderTable)(t)};Yt.renderSimpleTable=gj;var hj=e=>{console.log((0,Yt.renderSimpleTable)(e))};Yt.printSimpleTable=hj});var J1=E(tE=>{"use strict";l();Object.defineProperty(tE,"__esModule",{value:!0});var Sj=Y1(),iu=La(),su=Fa(),Tj=q1(),bj=Z1(),Dj=()=>0,Cj=()=>!0,eE=class{initSimple(t){this.columns=t.map(n=>({name:n,title:n,alignment:iu.DEFAULT_ROW_ALIGNMENT}))}initDetailed(t){var n;this.title=t?.title||this.title,this.tableStyle=t?.style||this.tableStyle,this.sortFunction=t?.sort||this.sortFunction,this.filterFunction=t?.filter||this.filterFunction,this.enabledColumns=t?.enabledColumns||this.enabledColumns,this.disabledColumns=t?.disabledColumns||this.disabledColumns,this.computedColumns=t?.computedColumns||this.computedColumns,this.columns=((n=t?.columns)===null||n===void 0?void 0:n.map(Tj.rawColumnToInternalColumn))||this.columns,this.rowSeparator=t?.rowSeparator||this.rowSeparator,this.charLength=t?.charLength||this.charLength,t?.colorMap&&(this.colorMap=Object.assign(Object.assign({},this.colorMap),t.colorMap)),t.rows!==void 0&&this.addRows(t.rows)}constructor(t){this.rows=[],this.columns=[],this.title=void 0,this.tableStyle=iu.DEFAULT_TABLE_STYLE,this.filterFunction=Cj,this.sortFunction=Dj,this.enabledColumns=[],this.disabledColumns=[],this.computedColumns=[],this.rowSeparator=iu.DEFAULT_ROW_SEPARATOR,this.colorMap=Sj.DEFAULT_COLOR_MAP,this.charLength={},t instanceof Array?this.initSimple(t):typeof t=="object"&&this.initDetailed(t)}createColumnFromRow(t){let n=this.columns.map(r=>r.name);Object.keys(t).forEach(r=>{n.includes(r)||this.columns.push((0,su.createColumFromOnlyName)(r))})}addColumn(t){typeof t=="string"?this.columns.push((0,su.createColumFromOnlyName)(t)):this.columns.push((0,su.createColumFromComputedColumn)(t))}addColumns(t){t.forEach(n=>{this.addColumn(n)})}addRow(t,n){this.createColumnFromRow(t),this.rows.push((0,su.createRow)(n?.color||iu.DEFAULT_ROW_FONT_COLOR,t,n?.separator!==void 0?n?.separator:this.rowSeparator))}addRows(t,n){t.forEach(r=>{this.addRow(r,n)})}renderTable(){return(0,bj.renderTable)(this)}};tE.default=eE});var x9=E(ka=>{"use strict";l();var Aj=ka&&ka.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ka,"__esModule",{value:!0});var Rj=Aj(J1()),v9=Fa(),nE=class{constructor(t){this.table=new Rj.default(t)}addColumn(t){return this.table.addColumn(t),this}addColumns(t){return this.table.addColumns(t),this}addRow(t,n){return this.table.addRow(t,(0,v9.convertRawRowOptionsToStandard)(n)),this}addRows(t,n){return this.table.addRows(t,(0,v9.convertRawRowOptionsToStandard)(n)),this}printTable(){let t=this.table.renderTable();console.log(t)}render(){return this.table.renderTable()}};ka.default=nE});var L9=E(pn=>{"use strict";l();var Nj=pn&&pn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(pn,"__esModule",{value:!0});pn.renderTable=pn.printTable=pn.Table=void 0;var Oj=Nj(x9());pn.Table=Oj.default;var M9=Z1();Object.defineProperty(pn,"printTable",{enumerable:!0,get:function(){return M9.printSimpleTable}});Object.defineProperty(pn,"renderTable",{enumerable:!0,get:function(){return M9.renderSimpleTable}})});var vj={};dE(vj,{pkg:()=>Xl});module.exports=s5(vj);l();var $9=te(require("update-notifier"));var ou={};dE(ou,{author:()=>_5,bin:()=>S5,bugs:()=>d5,default:()=>D5,dependencies:()=>T5,description:()=>l5,devDependencies:()=>g5,engines:()=>b5,files:()=>h5,homepage:()=>c5,license:()=>u5,name:()=>o5,publishConfig:()=>p5,repository:()=>m5,scripts:()=>f5,sideEffects:()=>E5,version:()=>lu});var o5="@e2b/cli",lu="0.1.6",l5="CLI for managing e2b sandbox templates",c5="https://e2b.dev",u5="MIT",_5={name:"FoundryLabs, Inc.",email:"hello@e2b.dev",url:"https://e2b.dev"},d5="https://github.com/e2b-dev/e2b/issues",m5={type:"git",url:"https://github.com/e2b-dev/e2b",directory:"packages/cli"},p5={access:"public"},E5=!1,f5={prepublishOnly:"pnpm run build",build:"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"},g5={"@types/common-tags":"^1.8.2","@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"},h5=["dist","LICENSE","README","package.json"],S5={e2b:"dist/index.js"},T5={"@balena/dockerignore":"^1.0.2","@e2b/sdk":"^0.8.5","@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","common-tags":"^1.8.2","console-table-printer":"^2.11.2",ignore:"^5.2.4",open:"^9.1.0","strip-ansi":"^7.1.0","tar-fs":"^3.0.4","update-notifier":"5.1.0",yup:"^1.3.2"},b5={node:">=18"},D5={name:o5,version:lu,description:l5,homepage:c5,license:u5,author:_5,bugs:d5,repository:m5,publishConfig:p5,sideEffects:E5,scripts:f5,devDependencies:g5,files:h5,bin:S5,dependencies:T5,engines:b5};l();l();var IE=te(OE(),1),{program:zj,createCommand:Qj,createArgument:Xj,createOption:jj,CommanderError:Zj,InvalidArgumentError:Jj,InvalidOptionArgumentError:eZ,Command:gt,Argument:tZ,Option:qa,Help:nZ}=IE.default;l();var Kv=te(vE());var Ql=te(require("fs")),zv=te(require("http"));l();var Eo=te(require("process"),1),Ch=require("buffer"),h_=te(require("path"),1),Ah=require("url"),Rh=te(require("child_process"),1),fo=te(require("fs/promises"),1),S_=require("fs"),fs=te(FE(),1);l();function Cr(e,t,n){let r=i=>Object.defineProperty(e,t,{value:i,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let i=n();return r(i),i},set(i){r(i)}}),e}l();var mo=te(require("process"),1);l();var YE=te(require("os"),1),qE=require("fs"),VE=te(BE(),1),$E=te(HE(),1),nP=Number(YE.default.release().split(".")[0]),rP=(0,$E.default)(nP>=14?"~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist":"~/Library/Preferences/com.apple.LaunchServices.plist");async function Ru(){if(process.platform!=="darwin")throw new Error("macOS only");let e="com.apple.Safari",t;try{t=await qE.promises.readFile(rP)}catch(i){if(i.code==="ENOENT")return e;throw i}let n=VE.default.parseBuffer(t),r=n&&n[0].LSHandlers;if(!r||r.length===0)return e;for(let i of r)if(i.LSHandlerURLScheme==="http"&&i.LSHandlerRoleAll){e=i.LSHandlerRoleAll;break}return e}l();l();var Ng=te(Rg(),1);async function Og(e){if(process.platform!=="darwin")throw new Error("macOS only");let{stdout:t}=await(0,Ng.default)("osascript",["-e",e]);return t}async function Qu(e){return Og(`tell application "Finder" to set app_path to application file id "${e}" as string
74
+ `)};Yt.renderTable=fj;var gj=e=>{let t=new cj.default;return t.addRows(e),(0,Yt.renderTable)(t)};Yt.renderSimpleTable=gj;var hj=e=>{console.log((0,Yt.renderSimpleTable)(e))};Yt.printSimpleTable=hj});var J1=E(tE=>{"use strict";l();Object.defineProperty(tE,"__esModule",{value:!0});var Sj=Y1(),iu=La(),su=Fa(),Tj=q1(),bj=Z1(),Dj=()=>0,Cj=()=>!0,eE=class{initSimple(t){this.columns=t.map(n=>({name:n,title:n,alignment:iu.DEFAULT_ROW_ALIGNMENT}))}initDetailed(t){var n;this.title=t?.title||this.title,this.tableStyle=t?.style||this.tableStyle,this.sortFunction=t?.sort||this.sortFunction,this.filterFunction=t?.filter||this.filterFunction,this.enabledColumns=t?.enabledColumns||this.enabledColumns,this.disabledColumns=t?.disabledColumns||this.disabledColumns,this.computedColumns=t?.computedColumns||this.computedColumns,this.columns=((n=t?.columns)===null||n===void 0?void 0:n.map(Tj.rawColumnToInternalColumn))||this.columns,this.rowSeparator=t?.rowSeparator||this.rowSeparator,this.charLength=t?.charLength||this.charLength,t?.colorMap&&(this.colorMap=Object.assign(Object.assign({},this.colorMap),t.colorMap)),t.rows!==void 0&&this.addRows(t.rows)}constructor(t){this.rows=[],this.columns=[],this.title=void 0,this.tableStyle=iu.DEFAULT_TABLE_STYLE,this.filterFunction=Cj,this.sortFunction=Dj,this.enabledColumns=[],this.disabledColumns=[],this.computedColumns=[],this.rowSeparator=iu.DEFAULT_ROW_SEPARATOR,this.colorMap=Sj.DEFAULT_COLOR_MAP,this.charLength={},t instanceof Array?this.initSimple(t):typeof t=="object"&&this.initDetailed(t)}createColumnFromRow(t){let n=this.columns.map(r=>r.name);Object.keys(t).forEach(r=>{n.includes(r)||this.columns.push((0,su.createColumFromOnlyName)(r))})}addColumn(t){typeof t=="string"?this.columns.push((0,su.createColumFromOnlyName)(t)):this.columns.push((0,su.createColumFromComputedColumn)(t))}addColumns(t){t.forEach(n=>{this.addColumn(n)})}addRow(t,n){this.createColumnFromRow(t),this.rows.push((0,su.createRow)(n?.color||iu.DEFAULT_ROW_FONT_COLOR,t,n?.separator!==void 0?n?.separator:this.rowSeparator))}addRows(t,n){t.forEach(r=>{this.addRow(r,n)})}renderTable(){return(0,bj.renderTable)(this)}};tE.default=eE});var x9=E(ka=>{"use strict";l();var Aj=ka&&ka.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ka,"__esModule",{value:!0});var Rj=Aj(J1()),v9=Fa(),nE=class{constructor(t){this.table=new Rj.default(t)}addColumn(t){return this.table.addColumn(t),this}addColumns(t){return this.table.addColumns(t),this}addRow(t,n){return this.table.addRow(t,(0,v9.convertRawRowOptionsToStandard)(n)),this}addRows(t,n){return this.table.addRows(t,(0,v9.convertRawRowOptionsToStandard)(n)),this}printTable(){let t=this.table.renderTable();console.log(t)}render(){return this.table.renderTable()}};ka.default=nE});var L9=E(pn=>{"use strict";l();var Nj=pn&&pn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(pn,"__esModule",{value:!0});pn.renderTable=pn.printTable=pn.Table=void 0;var Oj=Nj(x9());pn.Table=Oj.default;var M9=Z1();Object.defineProperty(pn,"printTable",{enumerable:!0,get:function(){return M9.printSimpleTable}});Object.defineProperty(pn,"renderTable",{enumerable:!0,get:function(){return M9.renderSimpleTable}})});var vj={};dE(vj,{pkg:()=>Xl});module.exports=s5(vj);l();var $9=te(require("update-notifier"));var ou={};dE(ou,{author:()=>_5,bin:()=>S5,bugs:()=>d5,default:()=>D5,dependencies:()=>T5,description:()=>l5,devDependencies:()=>g5,engines:()=>b5,files:()=>h5,homepage:()=>c5,license:()=>u5,name:()=>o5,publishConfig:()=>p5,repository:()=>m5,scripts:()=>f5,sideEffects:()=>E5,version:()=>lu});var o5="@e2b/cli",lu="0.1.8",l5="CLI for managing e2b sandbox templates",c5="https://e2b.dev",u5="MIT",_5={name:"FoundryLabs, Inc.",email:"hello@e2b.dev",url:"https://e2b.dev"},d5="https://github.com/e2b-dev/e2b/issues",m5={type:"git",url:"https://github.com/e2b-dev/e2b",directory:"packages/cli"},p5={access:"public"},E5=!1,f5={prepublishOnly:"pnpm run build",build:"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"},g5={"@types/common-tags":"^1.8.2","@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"},h5=["dist","LICENSE","README","package.json"],S5={e2b:"dist/index.js"},T5={"@balena/dockerignore":"^1.0.2","@e2b/sdk":"^0.8.5","@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","common-tags":"^1.8.2","console-table-printer":"^2.11.2",ignore:"^5.2.4",open:"^9.1.0","strip-ansi":"^7.1.0","tar-fs":"^3.0.4","update-notifier":"5.1.0",yup:"^1.3.2"},b5={node:">=18"},D5={name:o5,version:lu,description:l5,homepage:c5,license:u5,author:_5,bugs:d5,repository:m5,publishConfig:p5,sideEffects:E5,scripts:f5,devDependencies:g5,files:h5,bin:S5,dependencies:T5,engines:b5};l();l();var IE=te(OE(),1),{program:zj,createCommand:Qj,createArgument:Xj,createOption:jj,CommanderError:Zj,InvalidArgumentError:Jj,InvalidOptionArgumentError:eZ,Command:gt,Argument:tZ,Option:qa,Help:nZ}=IE.default;l();var Kv=te(vE());var Ql=te(require("fs")),zv=te(require("http"));l();var Eo=te(require("process"),1),Ch=require("buffer"),h_=te(require("path"),1),Ah=require("url"),Rh=te(require("child_process"),1),fo=te(require("fs/promises"),1),S_=require("fs"),fs=te(FE(),1);l();function Cr(e,t,n){let r=i=>Object.defineProperty(e,t,{value:i,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let i=n();return r(i),i},set(i){r(i)}}),e}l();var mo=te(require("process"),1);l();var YE=te(require("os"),1),qE=require("fs"),VE=te(BE(),1),$E=te(HE(),1),nP=Number(YE.default.release().split(".")[0]),rP=(0,$E.default)(nP>=14?"~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist":"~/Library/Preferences/com.apple.LaunchServices.plist");async function Ru(){if(process.platform!=="darwin")throw new Error("macOS only");let e="com.apple.Safari",t;try{t=await qE.promises.readFile(rP)}catch(i){if(i.code==="ENOENT")return e;throw i}let n=VE.default.parseBuffer(t),r=n&&n[0].LSHandlers;if(!r||r.length===0)return e;for(let i of r)if(i.LSHandlerURLScheme==="http"&&i.LSHandlerRoleAll){e=i.LSHandlerRoleAll;break}return e}l();l();var Ng=te(Rg(),1);async function Og(e){if(process.platform!=="darwin")throw new Error("macOS only");let{stdout:t}=await(0,Ng.default)("osascript",["-e",e]);return t}async function Qu(e){return Og(`tell application "Finder" to set app_path to application file id "${e}" as string
75
75
  tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}l();function Xu(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.toLowerCase().replace(/(?:^|\s|-)\S/g,t=>t.toUpperCase())}l();var mh=require("buffer"),ph=te(require("path"),1),uo=te(require("child_process"),1),ms=te(require("process"),1),Eh=te(Fu(),1);l();function ju(e){let t=typeof e=="string"?`
76
76
  `:`
77
77
  `.charCodeAt(),n=typeof e=="string"?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}l();var _s=te(require("process"),1),si=te(require("path"),1),Ig=te(require("url"),1);l();function io(e={}){let{env:t=process.env,platform:n=process.platform}=e;return n!=="win32"?"PATH":Object.keys(t).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"}function jF(e={}){let{cwd:t=_s.default.cwd(),path:n=_s.default.env[io()],execPath:r=_s.default.execPath}=e,i,s=t instanceof URL?Ig.default.fileURLToPath(t):t,a=si.default.resolve(s),o=[];for(;i!==a;)o.push(si.default.join(a,"node_modules/.bin")),i=a,a=si.default.resolve(a,"..");return o.push(si.default.resolve(s,r,"..")),[...o,n].join(si.default.delimiter)}function yg({env:e=_s.default.env,...t}={}){e={...e};let n=io({env:e});return t.path=e[n],e[n]=jF(t),e}l();l();var ZF=(e,t,n,r)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;let i=Object.getOwnPropertyDescriptor(e,n),s=Object.getOwnPropertyDescriptor(t,n);!JF(i,s)&&r||Object.defineProperty(e,n,s)},JF=function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},e8=(e,t)=>{let n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},t8=(e,t)=>`/* Wrapped ${e}*/
@@ -97,7 +97,7 @@ ${r.message}`:y,G=[B,t,e].filter(Boolean).join(`
97
97
  `)}function u$(e){return St.dim(e)}function ot(e){return St.bold(e)}function lr(e){return St.hex("#FFB766")(e)}function ln(e){return St.blue(e)}function At(e){return e?ln("./"+Gv(e)):""}function Xm(e){return St.blueBright(e)}function jm(e){if(e)return e.join(" | ")}function qv(e){return Qm.default(e,{language:"typescript",ignoreIllegals:!0})}function Vv(e){return Qm.default(e,{language:"python",ignoreIllegals:!0})}var $v={topLeft:"",topRight:"",bottomLeft:"",bottomRight:"",top:"",bottom:"",left:"",right:""},zl=2,Hv=1;function Zm(e,t,n){return tr(e,{borderStyle:{...$v,top:"\u2500"},titleAlignment:"center",float:"left",title:t?ot(t):void 0,margin:0,height:0,fullscreen:r=>[r,0],padding:{bottom:n?0:Hv,left:zl,right:zl,top:Hv}})}function Wv(e){return tr(e,{borderStyle:$v,margin:0,float:"left",padding:{bottom:0,left:zl,right:zl,top:0}})}var Xv=new gt("login").description("Log in to CLI").action(async()=>{let e;try{e=gs()}catch(t){console.error(Yv("Failed to read user config",t))}if(e){console.log(`Already logged in as ${ot(e.email)}, if you want to login as a different user, logout first by running 'e2b logout'.`);return}else if(!e){if(console.log("Attempting to login..."),e=await _$(),!e){console.info("Login aborted");return}Ql.mkdirSync(Qv.dirname(Yn),{recursive:!0}),Ql.writeFileSync(Yn,JSON.stringify(e,null,2))}console.log(`Logged in as ${ot(e.email)}`),process.exit(0)});async function _$(){let e=zv.createServer(),{port:t}=await Kv.default(e,0,"127.0.0.1"),n=new URL(`${b_}/api/cli`);return n.searchParams.set("next",`http://localhost:${t}`),n.searchParams.set("cliVersion",Xl.version),new Promise((r,i)=>(e.once("request",(s,a)=>{a.setHeader("connection","close");let o=new URL(`${b_}/api/cli`),c=new URL(s.url||"/","http://localhost").searchParams,u=Object.fromEntries(c.entries()),{error:_}=u;_?(i(new Error(_)),o.searchParams.set("state","error"),o.searchParams.set("error",_)):(r(u),o.searchParams.set("state","success"),o.searchParams.set("email",u.email)),a.statusCode=302,a.setHeader("location",o.href),a.end()}),Nh(n.toString())))}l();var jl=te(require("fs"));var jv=new gt("logout").description("Log out of CLI").action(()=>{jl.existsSync(Yn)?(jl.unlinkSync(Yn),console.log("Logged out.")):console.log("Not logged in, nothing to do")});l();var Ma=te(require("fs")),kn=te(require("path"));l();l();var YM=te(Jv());l();var d$="api.e2b.dev",Qs=process?.env?.E2B_DEBUG?"http://localhost:3000":`https://${d$}`,Jm="e2b.dev",Zl=49982,ex="/ws",tx="/file";l();function Jl(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();l();var ec=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},tc=class extends Error{constructor(t){super(t),this.name="AuthenticationError"}};function nx(e){return e.status==="fulfilled"}function Xs(e){if(!e.every(t=>t.status==="fulfilled"))return e.reduce((t,n,r)=>n.status==="rejected"?t+`
98
98
  [${r}]: ${JSON.stringify(n)}`:t,`errors:
99
99
  `)}function js(){let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),reject:t,resolve:e}}function cr(e,t=6e4){if(t===void 0||t<=0||t===Number.POSITIVE_INFINITY)return e;let n,r=new Promise((i,s)=>{n=setTimeout(()=>s(new ec(`Calling "${e.name}" timeouted after ${t}ms.`)),t)});return(...i)=>{let s=Promise.race([r,e(...i)]);return s.finally(()=>clearTimeout(n)),s}}l();var rx="codeSnippet";l();var cn="filesystem";l();var ep=class{constructor(t,n){this.sessConn=t;this.path=n;this.listeners=new Set}async start(t){return await cr(async()=>{this.rpcSubscriptionID||(this.handleFilesystemEvents=this.handleFilesystemEvents.bind(this),this.rpcSubscriptionID=await this.sessConn._subscribe(cn,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)})}},ix=ep;l();var Pr="process",Zs=class{constructor(t,n,r){this.line=t;this.timestamp=n;this.error=r}toString(){return this.line}},nc=class{constructor(){this.delimiter=`
100
- `;this.messages=[];this._finished=!1;this._error=!1}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)}},rc=class{constructor(t,n,r,i,s){this.processID=t;this.sandbox=n;this.triggerExit=r;this.output=s;this.finished=i}async kill(){try{await this.sandbox._call(Pr,"kill",[this.processID])}finally{this.triggerExit(),await this.finished}}async wait(){return this.finished}async sendStdin(t,n){await this.sandbox._call(Pr,"stdin",[this.processID,t],n)}};l();l();var xW=dx(),MW=yM(),Fi;(function(e){e.RPC_VERSION="2.0"})(Fi||(Fi={}));var vM=function(){function e(){this.idAwaiter={},this.onOpenHandlers=[],this.onAnyMessageHandlers=[],this.onNotification=[],this.onRequest=[],this.onSuccessResponse=[],this.onErrorResponse=[],this.onErrorHandlers=[],this.onCloseHandlers=[],this.config={responseTimeout:1e4},this.ws=void 0}return e.prototype.connect=function(t,n){return this.ws=new MW(t,n),this.listen()},e.prototype.onOpen=function(t){this.onOpenHandlers.push(t)},e.prototype.onAnyMessage=function(t){this.onAnyMessageHandlers.push(t)},e.prototype.onError=function(t){this.onErrorHandlers.push(t)},e.prototype.onClose=function(t){this.onCloseHandlers.push(t)},e.prototype.listenMessages=function(){var t=this,n;this.ws.onmessage&&(n=this.ws.onmessage.bind(this.ws)),this.ws.onmessage=function(r){n&&n(r);for(var i=0,s=t.onAnyMessageHandlers;i<s.length;i++){var a=s[i];a(r)}var o=JSON.parse(r.data.toString());if(t.isNotification(o))for(var c=0,u=t.onNotification;c<u.length;c++){var a=u[c];a(o)}else if(t.isRequest(o))for(var _=0,m=t.onRequest;_<m.length;_++){var a=m[_];a(o)}else if(t.isSuccessResponse(o)){for(var f=0,S=t.onSuccessResponse;f<S.length;f++){var a=S[f];a(o)}t.idAwaiter[o.id](o.result)}else if(t.isErrorResponse(o)){for(var h=0,O=t.onErrorResponse;h<O.length;h++){var a=O[h];a(o)}t.idAwaiter[o.id](o.error)}}},e.prototype.call=function(t,n){var r=this;return new Promise(function(i,s){var a=r.buildRequest(t,n),o;r.config.responseTimeout&&(o=setTimeout(function(){delete r.idAwaiter[a.id],s('Awaiting response to "'+t+'" with id: '+a.id+" timed out.")},r.config.responseTimeout)),r.idAwaiter[a.id]=function(u){if(clearInterval(o),delete r.idAwaiter[a.id],r.isRpcError(u)){s(u);return}i(u)};var c=JSON.stringify(a);r.ws.send(c)})},e.prototype.notify=function(t,n){this.ws.send(JSON.stringify(this.buildNotification(t,n)))},e.prototype.customId=function(t){this.idFn=t},e.prototype.noRpc=function(){this.buildRequest=this.buildRequestBase,this.buildNotification=this.buildNotificationBase,this.buildRpcSuccessResponse=this.buildRpcSuccessResponseBase,this.buildRpcErrorResponse=this.buildRpcErrorResponseBase},e.prototype.configure=function(t){Object.assign(this.config,t)},e.prototype.changeSocket=function(t){this.ws=t},e.prototype.listen=function(){var t=this;return new Promise(function(n,r){t.ws.onopen=function(i){for(var s=0,a=t.onOpenHandlers;s<a.length;s++){var o=a[s];o(i)}n(i)},t.listenMessages(),t.ws.onerror=function(i){for(var s=0,a=t.onErrorHandlers;s<a.length;s++){var o=a[s];o(i)}},t.ws.onclose=function(i){for(var s=0,a=t.onCloseHandlers;s<a.length;s++){var o=a[s];o(i)}r(i)}})},e.prototype.buildRequest=function(t,n){var r=this.buildRequestBase(t,n);return r.jsonrpc=Fi.RPC_VERSION,r},e.prototype.buildRequestBase=function(t,n){var r={};return r.id=this.idFn(),r.method=t,n&&(r.params=n),r},e.prototype.buildNotification=function(t,n){var r=this.buildNotificationBase(t,n);return r.jsonrpc=Fi.RPC_VERSION,r},e.prototype.buildNotificationBase=function(t,n){var r={};return r.method=t,n&&(r.params=n),r},e.prototype.buildRpcSuccessResponse=function(t,n){var r=this.buildRpcSuccessResponseBase(t,n);return r.jsonrpc=Fi.RPC_VERSION,r},e.prototype.buildRpcSuccessResponseBase=function(t,n){var r={};return r.id=t,r.result=n,r},e.prototype.buildRpcErrorResponse=function(t,n){var r=this.buildRpcErrorResponseBase(t,n);return r.jsonrpc=Fi.RPC_VERSION,r},e.prototype.buildRpcErrorResponseBase=function(t,n){var r={};return r.id=t,r.error=n,r},e.prototype.idFn=function(){return xW()},e.prototype.isNotification=function(t){return!t.id},e.prototype.isRequest=function(t){return t.method},e.prototype.isSuccessResponse=function(t){return t.hasOwnProperty("result")},e.prototype.isErrorResponse=function(t){return t.hasOwnProperty("error")},e.prototype.isRpcError=function(t){var n;return typeof((n=t)===null||n===void 0?void 0:n.code)<"u"},e}();l();l();l();l();var zme=Symbol(),Ur=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 la=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(_){try{u(r.next(_))}catch(m){a(m)}}function c(_){try{u(r.throw(_))}catch(m){a(m)}}function u(_){_.done?s(_.value):i(_.value).then(o,c)}u((r=r.apply(e,t||[])).next())})},xM=e=>e==="post"||e==="put"||e==="patch"||e==="delete";function LW(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 wW(e,t){return e.replace(/\{([^}]+)\}/g,(n,r)=>{let i=encodeURIComponent(t[r]);return delete t[r],i})}function PW(e,t,n){let r={};return xM(e)?n.forEach(i=>{r[i]=t[i],delete t[i]}):r=Object.assign({},t),LW(r)}function FW(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 kW(e,t){let n=xM(e)?JSON.stringify(t):void 0;return e==="delete"&&n==="{}"?void 0:n}function BW(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 UW(e){var t;let n=Object.assign(Array.isArray(e.payload)?[]:{},e.payload),r=wW(e.path,n),i=PW(e.method,n,e.queryParams),s=kW(e.method,n),a=FW(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 GW(e){return la(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 HW(e,t){return la(this,void 0,void 0,function*(){let n=yield fetch(e,t),r=yield GW(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 Ur(i)})}function YW(e,t){let n=(r,i,s)=>la(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 qW(e){return la(this,void 0,void 0,function*(){let{url:t,init:n}=UW(e);return yield e.fetch(t,n)})}function VW(e){let t=(n,r)=>la(this,void 0,void 0,function*(){try{return yield e(n,r)}catch(i){throw i instanceof Ur?new t.Error(i):i}});return t.Error=class extends Ur{constructor(n){super(n),Object.setPrototypeOf(this,new.target.prototype)}getActualType(){return{status:this.status,data:this.data}}},t}function $W(){let e="",t={},n=[],r=YW(n,HW);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=>VW((o,c)=>qW({baseUrl:e||"",path:i,method:s,queryParams:Object.keys(a||{}),payload:o,init:BW(t,c),fetch:r}))})})}}var Up={for:()=>$W()};l();l();var _c=te(MM());var LM="0.8.5";var wM={browser:typeof window<"u"&&_c.default.name||"undefined",lang:"js",lang_version:_c.default.version||"unknown",package_version:LM,publisher:"e2b",sdk_runtime:typeof window>"u"?"node":"browser",system:_c.default.os?.family||"unknown"};var PM=Up.for();PM.configure({baseUrl:Qs,init:{headers:wM}});function ua(e){let t=(n,r,i)=>e(r,{...i,headers:{Authorization:`Bearer ${n}`,...i?.headers}});return t.Error=e.Error,t}function dc(e){let t=(n,r,i)=>e(r,{...i,headers:{"X-API-KEY":n,...i?.headers}});return t.Error=e.Error,t}var dr=PM;l();function KW(e){return new Promise(t=>setTimeout(t,e))}var Gp=KW;var FM=dc(dr.path("/instances").method("post").create()),kM=dc(dr.path("/instances/{instanceID}/refreshes").method("post").create()),mc=class{constructor(t){this.opts=t;this.isOpen=!1;this.rpc=new vM;this.subscribers=[];let n=t.apiKey||process?.env?.E2B_API_KEY;if(!n)throw new tc("API key is required, please visit https://e2b.dev/docs to get your API key");this.apiKey=n,this.cwd=t.cwd,this.cwd&&this.cwd.startsWith("~")&&(this.cwd=this.cwd.replace("~","/home/user")),this.envVars=t.envVars||{},this.logger=t.logger??{info:console.info,warn:console.warn,error:console.error},this.logger.info?.(`Sandbox "${this.templateID}" initialized`)}get templateID(){return this.opts.id||"base"}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)return;let n=`${this.sandbox.instanceID}-${this.sandbox.clientID}.${Jm}`;return t?`${t}-${n}`:n}async close(){this.isOpen&&(this.logger.debug?.(`Closing sandbox "${this.sandbox?.instanceID}"`),this.isOpen=!1,this.logger.debug?.("Unsubscribing..."),(await Promise.allSettled(this.subscribers.map(n=>this._unsubscribe(n.subID)))).forEach(n=>{n.status==="rejected"&&this.logger.warn?.(`Failed to unsubscribe: "${n.reason}"`)}),this.rpc.ws?.terminate?.(),this.rpc.ws?.close?.(),this.logger.info?.("Disconnected from the sandbox"))}async _call(t,n,r,i){return this.logger.debug?.(`Calling "${t}_${n}" with params:`,r),await cr(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(nx).map(r=>r.value?this._unsubscribe(r.value):void 0)),new Error(Xs(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){return await cr(async()=>{if(this.isOpen||this.sandbox)throw new Error("Sandbox connect was already called");if(this.isOpen=!0,this.logger.debug?.("Opening sandbox..."),!this.opts.__debug_hostname)try{let _=await FM(this.apiKey,{envID:this.templateID});this.sandbox=_.data,this.logger.debug?.(`Acquired sandbox "${this.sandbox.instanceID}"`),this.refresh(this.sandbox.instanceID)}catch(_){if(_ instanceof FM.Error){let m=_.getActualType();if(m.status===400)throw new Error(`Error creating sandbox - (${m.status}) bad request: ${m.data.message}`);if(m.status===401)throw new Error(`Error creating sandbox - (${m.status}) unauthenticated: ${m.data.message}`);if(m.status===500)throw new Error(`Error creating sandbox - (${m.status}) server error: ${m.data.message}`)}throw _}let r=this.getHostname(this.opts.__debug_port||Zl);if(!r)throw new Error("Cannot get sandbox's hostname");let s=`${this.opts.__debug_devEnv==="local"?"ws":"wss"}://${r}${ex}`;this.rpc.onError(_=>{this.logger.debug?.(`Error in WebSocket of sandbox "${this.sandbox?.instanceID}": ${_.message??_.code??_.toString()}. Trying to reconnect...`)});let a=!1,o,c,u=new Promise((_,m)=>{o=()=>{a||(a=!0,_())},c=()=>{a||(a=!0,m())}});this.rpc.onOpen(()=>{this.logger.debug?.(`Connected to sandbox "${this.sandbox?.instanceID}"`),o?.()}),this.rpc.onClose(async()=>{if(this.logger.debug?.(`Closing WebSocket connection to sandbox "${this.sandbox?.instanceID}"`),this.isOpen){await Gp(600),this.logger.debug?.(`Reconnecting to sandbox "${this.sandbox?.instanceID}"`);try{this.subscribers=[],await this.rpc.connect(s),this.logger.debug?.(`Reconnected to sandbox "${this.sandbox?.instanceID}"`)}catch(_){this.logger.debug?.(`Failed reconnecting to sandbox "${this.sandbox?.instanceID}": ${_.message??_.code??_.toString()}`)}}else c?.()}),this.rpc.onNotification.push(this.handleNotification.bind(this));try{this.logger.debug?.(`Connection to sandbox "${this.sandbox?.instanceID}"`),await this.rpc.connect(s)}catch(_){this.logger.debug?.(`Error connecting to sandbox "${this.sandbox?.instanceID}": ${_.message??_.code??_.toString()}`)}return await u,this},t?.timeout)()}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.sandbox?.instanceID} - it was closed`);return}await Gp(5e3);try{this.logger.debug?.(`Refreshed sandbox "${t}"`),await kM(this.apiKey,{instanceID:t})}catch(n){if(n instanceof kM.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 Gr="terminal",pc=class{constructor(){this._data=""}get data(){return this._data}addData(t){this._data+=t}},Ec=class{constructor(t,n,r,i,s){this.terminalID=t;this.sandbox=n;this.triggerExit=r;this.output=s;this.finished=i}get data(){return this.output.data}async kill(){try{await this.sandbox._call(Gr,"destroy",[this.terminalID])}finally{this.triggerExit(),await this.finished}}async wait(){return this.finished}async sendData(t){await this.sandbox._call(Gr,"data",[this.terminalID,t])}async resize({cols:t,rows:n}){await this.sandbox._call(Gr,"resize",[this.terminalID,t,n])}};l();var _a=te(GM()),HM=(e,t,n)=>{let r;return e.startsWith("./")?(r=_a.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=_a.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=_a.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?_a.default.posix.join(t,e):e};var da=class e extends mc{constructor(n){n=n||{};super(n);this.onScanPorts=n.onScanPorts,this.filesystem={list:async(i,s)=>await this._call(cn,"list",[r(i)],s),read:async(i,s)=>await this._call(cn,"read",[r(i)],s),remove:async(i,s)=>{await this._call(cn,"remove",[r(i)],s)},write:async(i,s,a)=>{await this._call(cn,"write",[r(i),s],a)},writeBytes:async(i,s)=>{let a=Buffer.from(s).toString("base64");await this._call(cn,"writeBase64",[r(i),a])},readBytes:async i=>{let s=await this._call(cn,"readBase64",[r(i)]);return Buffer.from(s,"base64")},makeDir:async(i,s)=>{await this._call(cn,"makeDir",[r(i)],s)},watchDir:i=>{this.logger.debug?.(`Watching directory "${i}"`);let s=(0,YM.default)(r(i));return new ix(this,s)}},this.terminal={start:async({onData:i,size:s,onExit:a,envVars:o,cmd:c,cwd:u="",terminalID:_=Jl(12),timeout:m=void 0})=>await cr(async({onData:S,size:h,onExit:O,envVars:y,cmd:k,cwd:B="",rootDir:G,terminalID:L=Jl(12)})=>{this.logger.debug?.(`Starting terminal "${L}"`),!B&&G&&(this.logger.warn?.("The rootDir parameter is deprecated, use cwd instead."),B=G),!B&&this.cwd&&(B=this.cwd),y=y||{},y={...this.envVars,...y};let{promise:Y,resolve:F}=js(),q=new pc;function M(ie){q.addData(ie),S?.(ie)}let[w,V]=await this._handleSubscriptions(this._subscribe(Gr,M,"onData",L),this._subscribe(Gr,F,"onExit",L)),{promise:$,resolve:se}=js();Y.then(async()=>{let ie=await Promise.allSettled([this._unsubscribe(V),this._unsubscribe(w)]);this.logger.debug?.(`Terminal "${L}" exited`);let pe=Xs(ie);pe&&this.logger.error?.(pe),O?.(),se(q)});try{await this._call(Gr,"start",[L,h.cols,h.rows,...k!==void 0?[y,k,B]:[]])}catch(ie){throw F(),await $,ie}return new Ec(L,this,F,$,q)},m)({onData:i,size:s,onExit:a,envVars:o,cmd:c,cwd:u,terminalID:_})},this.process={start:async i=>{let s=async({cmd:o,onStdout:c,onStderr:u,onExit:_,envVars:m={},cwd:f="",rootDir:S,processID:h=Jl(12)})=>{if(!f&&S&&(this.logger.warn?.("The rootDir parameter is deprecated, use cwd instead."),f=S),!f&&this.cwd&&(f=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:O,resolve:y}=js(),k=new nc,B=V=>{k.setExitCode(V),y()},G=V=>{let $=new Zs(V.line,V.timestamp,!1);k.addStdout($),c?c($):this.opts.onStdout&&this.opts.onStdout($)},L=V=>{let $=new Zs(V.line,V.timestamp,!0);k.addStderr($),u?u($):this.opts.onStderr&&this.opts.onStderr($)},[Y,F,q]=await this._handleSubscriptions(this._subscribe(Pr,B,"onExit",h),this._subscribe(Pr,G,"onStdout",h),this._subscribe(Pr,L,"onStderr",h)),{promise:M,resolve:w}=js();O.then(async()=>{let V=await Promise.allSettled([this._unsubscribe(Y),F?this._unsubscribe(F):void 0,q?this._unsubscribe(q):void 0]);this.logger.debug?.(`Process "${h}" exited`);let $=Xs(V);$&&this.logger.error?.($),_?_(k.exitCode||0):this.opts.onExit&&this.opts.onExit(),w(k)});try{await this._call(Pr,"start",[h,o,m,f])}catch(V){throw y(),await M,V}return new rc(h,this,y,M,k)},a=i.timeout;return await cr(s,a)(i)}};let r=i=>HM(i,this.cwd,this.logger)}get fileURL(){let n=this.opts.__debug_devEnv==="local"?"http":"https",r=this.getHostname(this.opts.__debug_port||Zl);return`${n}://${r}${tx}`}static async create(n){return new e(n)._open({timeout:n?.timeout}).then(async r=>(n?.cwd&&(console.log(`Custom cwd for Sandbox set: "${n.cwd}"`),await r.filesystem.makeDir(n.cwd)),r))}async _open(n){await super._open(n);let r=this.onScanPorts?i=>this.onScanPorts?.(i.map(s=>({ip:s.Ip,port:s.Port,state:s.State}))):void 0;return await this._handleSubscriptions(r?this._subscribe(rx,r,"scanOpenedPorts"):void 0),this}async uploadFile(n,r){let i=new FormData,s=n instanceof Blob?n:new Blob([n],{type:"application/octet-stream"});i.append("file",s,r);let a=await fetch(this.fileURL,{method:"POST",body:i});if(!a.ok){let o=await a.text();throw new Error(`Failed to upload file ${a.status} - ${a.statusText}: ${o}`)}return`/home/user/${r}`}async downloadFile(n,r){n=encodeURIComponent(n);let i=await fetch(`${this.fileURL}?path=${n}`);if(!i.ok){let s=await i.text();throw new Error(`Failed to download file '${n}': ${s}`)}switch(r){case"base64":return Buffer.from(await i.arrayBuffer()).toString("base64");case"blob":return await i.blob();case"buffer":return Buffer.from(await i.arrayBuffer());case"arraybuffer":return await i.arrayBuffer();case"text":return await i.text();default:return await i.arrayBuffer()}}};l();async function qM(e){return new Promise(t=>setTimeout(t,e))}l();var fc=process.env.E2B_API_KEY,gc=process.env.E2B_ACCESS_TOKEN,VM=tr(`You must be logged in to use this command. Run ${ot("e2b login")}.`,{width:70,float:"center",padding:.5,margin:1,borderStyle:"round",borderColor:"redBright"});function $M(){if(fc||(fc=gs()?.defaultTeamApiKey),!fc)console.error(VM),process.exit(1);else return fc}function hc(){if(gc||(gc=gs()?.accessToken),!gc)console.error(VM),process.exit(1);else return gc}l();var Bi=new qa("-p, --path <path>",`Change root directory where command is executed to ${ot("<path>")} directory`);l();var lw=te(ow()),gr=te(require("path"));async function cw(e,t,n){let r=n.map(({oldPath:s,newPath:a})=>({oldPath:gr.join(gr.sep,s),newPath:gr.join(gr.sep,a)}));return await new Promise((s,a)=>{let o=[],c=lw.pack(e,{entries:t.filter(u=>r.every(({oldPath:_})=>gr.resolve(_)!==u.path)).map(({rootPath:u})=>u),map:u=>{let _=r.find(({oldPath:m})=>u.name===m);return _&&(u.name=_.newPath),u}});c.on("data",u=>{o.push(u)}),c.on("end",()=>{let u=new Blob(o);s(u)}),c.on("error",u=>{a(new Error(`Error creating tar blob: ${u.message}`))})})}l();var hr="e2b.Dockerfile",Qi="Dockerfile",uw=`# You can use most Debian-based base images
100
+ `;this.messages=[];this._finished=!1;this._error=!1}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)}},rc=class{constructor(t,n,r,i,s){this.processID=t;this.sandbox=n;this.triggerExit=r;this.output=s;this.finished=i}async kill(){try{await this.sandbox._call(Pr,"kill",[this.processID])}finally{this.triggerExit(),await this.finished}}async wait(){return this.finished}async sendStdin(t,n){await this.sandbox._call(Pr,"stdin",[this.processID,t],n)}};l();l();var xW=dx(),MW=yM(),Fi;(function(e){e.RPC_VERSION="2.0"})(Fi||(Fi={}));var vM=function(){function e(){this.idAwaiter={},this.onOpenHandlers=[],this.onAnyMessageHandlers=[],this.onNotification=[],this.onRequest=[],this.onSuccessResponse=[],this.onErrorResponse=[],this.onErrorHandlers=[],this.onCloseHandlers=[],this.config={responseTimeout:1e4},this.ws=void 0}return e.prototype.connect=function(t,n){return this.ws=new MW(t,n),this.listen()},e.prototype.onOpen=function(t){this.onOpenHandlers.push(t)},e.prototype.onAnyMessage=function(t){this.onAnyMessageHandlers.push(t)},e.prototype.onError=function(t){this.onErrorHandlers.push(t)},e.prototype.onClose=function(t){this.onCloseHandlers.push(t)},e.prototype.listenMessages=function(){var t=this,n;this.ws.onmessage&&(n=this.ws.onmessage.bind(this.ws)),this.ws.onmessage=function(r){n&&n(r);for(var i=0,s=t.onAnyMessageHandlers;i<s.length;i++){var a=s[i];a(r)}var o=JSON.parse(r.data.toString());if(t.isNotification(o))for(var c=0,u=t.onNotification;c<u.length;c++){var a=u[c];a(o)}else if(t.isRequest(o))for(var _=0,m=t.onRequest;_<m.length;_++){var a=m[_];a(o)}else if(t.isSuccessResponse(o)){for(var f=0,S=t.onSuccessResponse;f<S.length;f++){var a=S[f];a(o)}t.idAwaiter[o.id](o.result)}else if(t.isErrorResponse(o)){for(var h=0,O=t.onErrorResponse;h<O.length;h++){var a=O[h];a(o)}t.idAwaiter[o.id](o.error)}}},e.prototype.call=function(t,n){var r=this;return new Promise(function(i,s){var a=r.buildRequest(t,n),o;r.config.responseTimeout&&(o=setTimeout(function(){delete r.idAwaiter[a.id],s('Awaiting response to "'+t+'" with id: '+a.id+" timed out.")},r.config.responseTimeout)),r.idAwaiter[a.id]=function(u){if(clearInterval(o),delete r.idAwaiter[a.id],r.isRpcError(u)){s(u);return}i(u)};var c=JSON.stringify(a);r.ws.send(c)})},e.prototype.notify=function(t,n){this.ws.send(JSON.stringify(this.buildNotification(t,n)))},e.prototype.customId=function(t){this.idFn=t},e.prototype.noRpc=function(){this.buildRequest=this.buildRequestBase,this.buildNotification=this.buildNotificationBase,this.buildRpcSuccessResponse=this.buildRpcSuccessResponseBase,this.buildRpcErrorResponse=this.buildRpcErrorResponseBase},e.prototype.configure=function(t){Object.assign(this.config,t)},e.prototype.changeSocket=function(t){this.ws=t},e.prototype.listen=function(){var t=this;return new Promise(function(n,r){t.ws.onopen=function(i){for(var s=0,a=t.onOpenHandlers;s<a.length;s++){var o=a[s];o(i)}n(i)},t.listenMessages(),t.ws.onerror=function(i){for(var s=0,a=t.onErrorHandlers;s<a.length;s++){var o=a[s];o(i)}},t.ws.onclose=function(i){for(var s=0,a=t.onCloseHandlers;s<a.length;s++){var o=a[s];o(i)}r(i)}})},e.prototype.buildRequest=function(t,n){var r=this.buildRequestBase(t,n);return r.jsonrpc=Fi.RPC_VERSION,r},e.prototype.buildRequestBase=function(t,n){var r={};return r.id=this.idFn(),r.method=t,n&&(r.params=n),r},e.prototype.buildNotification=function(t,n){var r=this.buildNotificationBase(t,n);return r.jsonrpc=Fi.RPC_VERSION,r},e.prototype.buildNotificationBase=function(t,n){var r={};return r.method=t,n&&(r.params=n),r},e.prototype.buildRpcSuccessResponse=function(t,n){var r=this.buildRpcSuccessResponseBase(t,n);return r.jsonrpc=Fi.RPC_VERSION,r},e.prototype.buildRpcSuccessResponseBase=function(t,n){var r={};return r.id=t,r.result=n,r},e.prototype.buildRpcErrorResponse=function(t,n){var r=this.buildRpcErrorResponseBase(t,n);return r.jsonrpc=Fi.RPC_VERSION,r},e.prototype.buildRpcErrorResponseBase=function(t,n){var r={};return r.id=t,r.error=n,r},e.prototype.idFn=function(){return xW()},e.prototype.isNotification=function(t){return!t.id},e.prototype.isRequest=function(t){return t.method},e.prototype.isSuccessResponse=function(t){return t.hasOwnProperty("result")},e.prototype.isErrorResponse=function(t){return t.hasOwnProperty("error")},e.prototype.isRpcError=function(t){var n;return typeof((n=t)===null||n===void 0?void 0:n.code)<"u"},e}();l();l();l();l();var zme=Symbol(),Ur=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 la=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(_){try{u(r.next(_))}catch(m){a(m)}}function c(_){try{u(r.throw(_))}catch(m){a(m)}}function u(_){_.done?s(_.value):i(_.value).then(o,c)}u((r=r.apply(e,t||[])).next())})},xM=e=>e==="post"||e==="put"||e==="patch"||e==="delete";function LW(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 wW(e,t){return e.replace(/\{([^}]+)\}/g,(n,r)=>{let i=encodeURIComponent(t[r]);return delete t[r],i})}function PW(e,t,n){let r={};return xM(e)?n.forEach(i=>{r[i]=t[i],delete t[i]}):r=Object.assign({},t),LW(r)}function FW(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 kW(e,t){let n=xM(e)?JSON.stringify(t):void 0;return e==="delete"&&n==="{}"?void 0:n}function BW(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 UW(e){var t;let n=Object.assign(Array.isArray(e.payload)?[]:{},e.payload),r=wW(e.path,n),i=PW(e.method,n,e.queryParams),s=kW(e.method,n),a=FW(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 GW(e){return la(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 HW(e,t){return la(this,void 0,void 0,function*(){let n=yield fetch(e,t),r=yield GW(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 Ur(i)})}function YW(e,t){let n=(r,i,s)=>la(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 qW(e){return la(this,void 0,void 0,function*(){let{url:t,init:n}=UW(e);return yield e.fetch(t,n)})}function VW(e){let t=(n,r)=>la(this,void 0,void 0,function*(){try{return yield e(n,r)}catch(i){throw i instanceof Ur?new t.Error(i):i}});return t.Error=class extends Ur{constructor(n){super(n),Object.setPrototypeOf(this,new.target.prototype)}getActualType(){return{status:this.status,data:this.data}}},t}function $W(){let e="",t={},n=[],r=YW(n,HW);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=>VW((o,c)=>qW({baseUrl:e||"",path:i,method:s,queryParams:Object.keys(a||{}),payload:o,init:BW(t,c),fetch:r}))})})}}var Up={for:()=>$W()};l();l();var _c=te(MM());var LM="0.8.6";var wM={browser:typeof window<"u"&&_c.default.name||"undefined",lang:"js",lang_version:_c.default.version||"unknown",package_version:LM,publisher:"e2b",sdk_runtime:typeof window>"u"?"node":"browser",system:_c.default.os?.family||"unknown"};var PM=Up.for();PM.configure({baseUrl:Qs,init:{headers:wM}});function ua(e){let t=(n,r,i)=>e(r,{...i,headers:{Authorization:`Bearer ${n}`,...i?.headers}});return t.Error=e.Error,t}function dc(e){let t=(n,r,i)=>e(r,{...i,headers:{"X-API-KEY":n,...i?.headers}});return t.Error=e.Error,t}var dr=PM;l();function KW(e){return new Promise(t=>setTimeout(t,e))}var Gp=KW;var FM=dc(dr.path("/instances").method("post").create()),kM=dc(dr.path("/instances/{instanceID}/refreshes").method("post").create()),mc=class{constructor(t){this.opts=t;this.isOpen=!1;this.rpc=new vM;this.subscribers=[];let n=t.apiKey||process?.env?.E2B_API_KEY;if(!n)throw new tc("API key is required, please visit https://e2b.dev/docs to get your API key");this.apiKey=n,this.cwd=t.cwd,this.cwd&&this.cwd.startsWith("~")&&(this.cwd=this.cwd.replace("~","/home/user")),this.envVars=t.envVars||{},this.logger=t.logger??{info:console.info,warn:console.warn,error:console.error},this.logger.debug?.(`Sandbox "${this.templateID}" initialized`)}get templateID(){return this.opts.id||"base"}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)return;let n=`${this.sandbox.instanceID}-${this.sandbox.clientID}.${Jm}`;return t?`${t}-${n}`:n}async close(){this.isOpen&&(this.logger.debug?.(`Closing sandbox "${this.sandbox?.instanceID}"`),this.isOpen=!1,this.logger.debug?.("Unsubscribing..."),(await Promise.allSettled(this.subscribers.map(n=>this._unsubscribe(n.subID)))).forEach(n=>{n.status==="rejected"&&this.logger.warn?.(`Failed to unsubscribe: "${n.reason}"`)}),this.rpc.ws?.terminate?.(),this.rpc.ws?.close?.(),this.logger.debug?.("Disconnected from the sandbox"))}async _call(t,n,r,i){return this.logger.debug?.(`Calling "${t}_${n}" with params:`,r),await cr(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(nx).map(r=>r.value?this._unsubscribe(r.value):void 0)),new Error(Xs(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){return await cr(async()=>{if(this.isOpen||this.sandbox)throw new Error("Sandbox connect was already called");if(this.isOpen=!0,this.logger.debug?.("Opening sandbox..."),!this.opts.__debug_hostname)try{let _=await FM(this.apiKey,{envID:this.templateID});this.sandbox=_.data,this.logger.debug?.(`Acquired sandbox "${this.sandbox.instanceID}"`),this.refresh(this.sandbox.instanceID)}catch(_){if(_ instanceof FM.Error){let m=_.getActualType();if(m.status===400)throw new Error(`Error creating sandbox - (${m.status}) bad request: ${m.data.message}`);if(m.status===401)throw new Error(`Error creating sandbox - (${m.status}) unauthenticated: ${m.data.message}`);if(m.status===500)throw new Error(`Error creating sandbox - (${m.status}) server error: ${m.data.message}`)}throw _}let r=this.getHostname(this.opts.__debug_port||Zl);if(!r)throw new Error("Cannot get sandbox's hostname");let s=`${this.opts.__debug_devEnv==="local"?"ws":"wss"}://${r}${ex}`;this.rpc.onError(_=>{this.logger.debug?.(`Error in WebSocket of sandbox "${this.sandbox?.instanceID}": ${_.message??_.code??_.toString()}. Trying to reconnect...`)});let a=!1,o,c,u=new Promise((_,m)=>{o=()=>{a||(a=!0,_())},c=()=>{a||(a=!0,m())}});this.rpc.onOpen(()=>{this.logger.debug?.(`Connected to sandbox "${this.sandbox?.instanceID}"`),o?.()}),this.rpc.onClose(async()=>{if(this.logger.debug?.(`Closing WebSocket connection to sandbox "${this.sandbox?.instanceID}"`),this.isOpen){await Gp(600),this.logger.debug?.(`Reconnecting to sandbox "${this.sandbox?.instanceID}"`);try{this.subscribers=[],await this.rpc.connect(s),this.logger.debug?.(`Reconnected to sandbox "${this.sandbox?.instanceID}"`)}catch(_){this.logger.debug?.(`Failed reconnecting to sandbox "${this.sandbox?.instanceID}": ${_.message??_.code??_.toString()}`)}}else c?.()}),this.rpc.onNotification.push(this.handleNotification.bind(this));try{this.logger.debug?.(`Connection to sandbox "${this.sandbox?.instanceID}"`),await this.rpc.connect(s)}catch(_){this.logger.debug?.(`Error connecting to sandbox "${this.sandbox?.instanceID}": ${_.message??_.code??_.toString()}`)}return await u,this},t?.timeout)()}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.sandbox?.instanceID} - it was closed`);return}await Gp(5e3);try{this.logger.debug?.(`Refreshed sandbox "${t}"`),await kM(this.apiKey,{instanceID:t})}catch(n){if(n instanceof kM.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 Gr="terminal",pc=class{constructor(){this._data=""}get data(){return this._data}addData(t){this._data+=t}},Ec=class{constructor(t,n,r,i,s){this.terminalID=t;this.sandbox=n;this.triggerExit=r;this.output=s;this.finished=i}get data(){return this.output.data}async kill(){try{await this.sandbox._call(Gr,"destroy",[this.terminalID])}finally{this.triggerExit(),await this.finished}}async wait(){return this.finished}async sendData(t){await this.sandbox._call(Gr,"data",[this.terminalID,t])}async resize({cols:t,rows:n}){await this.sandbox._call(Gr,"resize",[this.terminalID,t,n])}};l();var _a=te(GM()),HM=(e,t,n)=>{let r;return e.startsWith("./")?(r=_a.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=_a.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=_a.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?_a.default.posix.join(t,e):e};var da=class e extends mc{constructor(n){n=n||{};super(n);this.onScanPorts=n.onScanPorts,this.filesystem={list:async(i,s)=>await this._call(cn,"list",[r(i)],s),read:async(i,s)=>await this._call(cn,"read",[r(i)],s),remove:async(i,s)=>{await this._call(cn,"remove",[r(i)],s)},write:async(i,s,a)=>{await this._call(cn,"write",[r(i),s],a)},writeBytes:async(i,s)=>{let a=Buffer.from(s).toString("base64");await this._call(cn,"writeBase64",[r(i),a])},readBytes:async i=>{let s=await this._call(cn,"readBase64",[r(i)]);return Buffer.from(s,"base64")},makeDir:async(i,s)=>{await this._call(cn,"makeDir",[r(i)],s)},watchDir:i=>{this.logger.debug?.(`Watching directory "${i}"`);let s=(0,YM.default)(r(i));return new ix(this,s)}},this.terminal={start:async({onData:i,size:s,onExit:a,envVars:o,cmd:c,cwd:u="",terminalID:_=Jl(12),timeout:m=void 0})=>await cr(async({onData:S,size:h,onExit:O,envVars:y,cmd:k,cwd:B="",rootDir:G,terminalID:L=Jl(12)})=>{this.logger.debug?.(`Starting terminal "${L}"`),!B&&G&&(this.logger.warn?.("The rootDir parameter is deprecated, use cwd instead."),B=G),!B&&this.cwd&&(B=this.cwd),y=y||{},y={...this.envVars,...y};let{promise:Y,resolve:F}=js(),q=new pc;function M(ie){q.addData(ie),S?.(ie)}let[w,V]=await this._handleSubscriptions(this._subscribe(Gr,M,"onData",L),this._subscribe(Gr,F,"onExit",L)),{promise:$,resolve:se}=js();Y.then(async()=>{let ie=await Promise.allSettled([this._unsubscribe(V),this._unsubscribe(w)]);this.logger.debug?.(`Terminal "${L}" exited`);let pe=Xs(ie);pe&&this.logger.error?.(pe),O?.(),se(q)});try{await this._call(Gr,"start",[L,h.cols,h.rows,...k!==void 0?[y,k,B]:[]])}catch(ie){throw F(),await $,ie}return new Ec(L,this,F,$,q)},m)({onData:i,size:s,onExit:a,envVars:o,cmd:c,cwd:u,terminalID:_})},this.process={start:async i=>{let s=async({cmd:o,onStdout:c,onStderr:u,onExit:_,envVars:m={},cwd:f="",rootDir:S,processID:h=Jl(12)})=>{if(!f&&S&&(this.logger.warn?.("The rootDir parameter is deprecated, use cwd instead."),f=S),!f&&this.cwd&&(f=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:O,resolve:y}=js(),k=new nc,B=V=>{k.setExitCode(V),y()},G=V=>{let $=new Zs(V.line,V.timestamp,!1);k.addStdout($),c?c($):this.opts.onStdout&&this.opts.onStdout($)},L=V=>{let $=new Zs(V.line,V.timestamp,!0);k.addStderr($),u?u($):this.opts.onStderr&&this.opts.onStderr($)},[Y,F,q]=await this._handleSubscriptions(this._subscribe(Pr,B,"onExit",h),this._subscribe(Pr,G,"onStdout",h),this._subscribe(Pr,L,"onStderr",h)),{promise:M,resolve:w}=js();O.then(async()=>{let V=await Promise.allSettled([this._unsubscribe(Y),F?this._unsubscribe(F):void 0,q?this._unsubscribe(q):void 0]);this.logger.debug?.(`Process "${h}" exited`);let $=Xs(V);$&&this.logger.error?.($),_?_(k.exitCode||0):this.opts.onExit&&this.opts.onExit(),w(k)});try{await this._call(Pr,"start",[h,o,m,f])}catch(V){throw y(),await M,V}return new rc(h,this,y,M,k)},a=i.timeout;return await cr(s,a)(i)}};let r=i=>HM(i,this.cwd,this.logger)}get fileURL(){let n=this.opts.__debug_devEnv==="local"?"http":"https",r=this.getHostname(this.opts.__debug_port||Zl);return`${n}://${r}${tx}`}static async create(n){return new e(n)._open({timeout:n?.timeout}).then(async r=>(n?.cwd&&(console.log(`Custom cwd for Sandbox set: "${n.cwd}"`),await r.filesystem.makeDir(n.cwd)),r))}async _open(n){await super._open(n);let r=this.onScanPorts?i=>this.onScanPorts?.(i.map(s=>({ip:s.Ip,port:s.Port,state:s.State}))):void 0;return await this._handleSubscriptions(r?this._subscribe(rx,r,"scanOpenedPorts"):void 0),this}async uploadFile(n,r){let i=new FormData,s=n instanceof Blob?n:new Blob([n],{type:"application/octet-stream"});i.append("file",s,r);let a=await fetch(this.fileURL,{method:"POST",body:i});if(!a.ok){let o=await a.text();throw new Error(`Failed to upload file ${a.status} - ${a.statusText}: ${o}`)}return`/home/user/${r}`}async downloadFile(n,r){n=encodeURIComponent(n);let i=await fetch(`${this.fileURL}?path=${n}`);if(!i.ok){let s=await i.text();throw new Error(`Failed to download file '${n}': ${s}`)}switch(r){case"base64":return Buffer.from(await i.arrayBuffer()).toString("base64");case"blob":return await i.blob();case"buffer":return Buffer.from(await i.arrayBuffer());case"arraybuffer":return await i.arrayBuffer();case"text":return await i.text();default:return await i.arrayBuffer()}}};l();async function qM(e){return new Promise(t=>setTimeout(t,e))}l();var fc=process.env.E2B_API_KEY,gc=process.env.E2B_ACCESS_TOKEN,VM=tr(`You must be logged in to use this command. Run ${ot("e2b login")}.`,{width:70,float:"center",padding:.5,margin:1,borderStyle:"round",borderColor:"redBright"});function $M(){if(fc||(fc=gs()?.defaultTeamApiKey),!fc)console.error(VM),process.exit(1);else return fc}function hc(){if(gc||(gc=gs()?.accessToken),!gc)console.error(VM),process.exit(1);else return gc}l();var Bi=new qa("-p, --path <path>",`Change root directory where command is executed to ${ot("<path>")} directory`);l();var lw=te(ow()),gr=te(require("path"));async function cw(e,t,n){let r=n.map(({oldPath:s,newPath:a})=>({oldPath:gr.join(gr.sep,s),newPath:gr.join(gr.sep,a)}));return await new Promise((s,a)=>{let o=[],c=lw.pack(e,{entries:t.filter(u=>r.every(({oldPath:_})=>gr.resolve(_)!==u.path)).map(({rootPath:u})=>u),map:u=>{let _=r.find(({oldPath:m})=>u.name===m);return _&&(u.name=_.newPath),u}});c.on("data",u=>{o.push(u)}),c.on("end",()=>{let u=new Blob(o);s(u)}),c.on("error",u=>{a(new Error(`Error creating tar blob: ${u.message}`))})})}l();var hr="e2b.Dockerfile",Qi="Dockerfile",uw=`# You can use most Debian-based base images
101
101
  FROM ubuntu:22.04
102
102
 
103
103
  # Install dependencies and customize sandbox
@@ -106,8 +106,8 @@ FROM ubuntu:22.04
106
106
  attempted value: ${a}
107
107
  `+(o!==a?`result of cast: ${o}`:""))}return s}_cast(t,n){let r=t===void 0?t:this.transforms.reduce((i,s)=>s.call(this,i,t,this),t);return r===void 0&&(r=this.getDefault(n)),r}_validate(t,n={},r,i){let{path:s,originalValue:a=t,strict:o=this.spec.strict}=n,c=t;o||(c=this._cast(c,Object.assign({assert:!1},n)));let u=[];for(let _ of Object.values(this.internalTests))_&&u.push(_);this.runTests({path:s,value:c,originalValue:a,options:n,tests:u},r,_=>{if(_.length)return i(_,c);this.runTests({path:s,value:c,originalValue:a,options:n,tests:this.tests},r,i)})}runTests(t,n,r){let i=!1,{tests:s,value:a,originalValue:o,path:c,options:u}=t,_=O=>{i||(i=!0,n(O,a))},m=O=>{i||(i=!0,r(O,a))},f=s.length,S=[];if(!f)return m([]);let h={value:a,originalValue:o,path:c,options:u,schema:this};for(let O=0;O<s.length;O++){let y=s[O];y(h,_,function(B){B&&(Array.isArray(B)?S.push(...B):S.push(B)),--f<=0&&m(S)})}}asNestedTest({key:t,index:n,parent:r,parentPath:i,originalParent:s,options:a}){let o=t??n;if(o==null)throw TypeError("Must include `key` or `index` for nested validations");let c=typeof o=="number",u=r[o],_=Object.assign({},a,{strict:!0,parent:r,value:u,originalValue:s[o],key:void 0,[c?"index":"key"]:o,path:c||o.includes(".")?`${i||""}[${u?o:`"${o}"`}]`:(i?`${i}.`:"")+t});return(m,f,S)=>this.resolve(_)._validate(u,_,f,S)}validate(t,n){var r;let i=this.resolve(Object.assign({},n,{value:t})),s=(r=n?.disableStackTrace)!=null?r:i.spec.disableStackTrace;return new Promise((a,o)=>i._validate(t,n,(c,u)=>{xt.isError(c)&&(c.value=u),o(c)},(c,u)=>{c.length?o(new xt(c,u,void 0,void 0,s)):a(u)}))}validateSync(t,n){var r;let i=this.resolve(Object.assign({},n,{value:t})),s,a=(r=n?.disableStackTrace)!=null?r:i.spec.disableStackTrace;return i._validate(t,Object.assign({},n,{sync:!0}),(o,c)=>{throw xt.isError(o)&&(o.value=c),o},(o,c)=>{if(o.length)throw new xt(o,t,void 0,void 0,a);s=c}),s}isValid(t,n){return this.validate(t,n).then(()=>!0,r=>{if(xt.isError(r))return!1;throw r})}isValidSync(t,n){try{return this.validateSync(t,n),!0}catch(r){if(xt.isError(r))return!1;throw r}}_getDefault(t){let n=this.spec.default;return n==null?n:typeof n=="function"?n.call(this,t):ji(n)}getDefault(t){return this.resolve(t||{})._getDefault(t)}default(t){return arguments.length===0?this._getDefault():this.clone({default:t})}strict(t=!0){return this.clone({strict:t})}nullability(t,n){let r=this.clone({nullable:t});return r.internalTests.nullable=Xi({message:n,name:"nullable",test(i){return i===null?this.schema.spec.nullable:!0}}),r}optionality(t,n){let r=this.clone({optional:t});return r.internalTests.optionality=Xi({message:n,name:"optionality",test(i){return i===void 0?this.schema.spec.optional:!0}}),r}optional(){return this.optionality(!0)}defined(t=mn.defined){return this.optionality(!1,t)}nullable(){return this.nullability(!0)}nonNullable(t=mn.notNull){return this.nullability(!1,t)}required(t=mn.required){return this.clone().withMutation(n=>n.nonNullable(t).defined(t))}notRequired(){return this.clone().withMutation(t=>t.nullable().optional())}transform(t){let n=this.clone();return n.transforms.push(t),n}test(...t){let n;if(t.length===1?typeof t[0]=="function"?n={test:t[0]}:n=t[0]:t.length===2?n={name:t[0],test:t[1]}:n={name:t[0],message:t[1],test:t[2]},n.message===void 0&&(n.message=mn.default),typeof n.test!="function")throw new TypeError("`test` is a required parameters");let r=this.clone(),i=Xi(n),s=n.exclusive||n.name&&r.exclusiveTests[n.name]===!0;if(n.exclusive&&!n.name)throw new TypeError("Exclusive tests must provide a unique `name` identifying the test");return n.name&&(r.exclusiveTests[n.name]=!!n.exclusive),r.tests=r.tests.filter(a=>!(a.OPTIONS.name===n.name&&(s||a.OPTIONS.test===i.OPTIONS.test))),r.tests.push(i),r}when(t,n){!Array.isArray(t)&&typeof t!="string"&&(n=t,t=".");let r=this.clone(),i=Nw(t).map(s=>new Fn(s));return i.forEach(s=>{s.isSibling&&r.deps.push(s.key)}),r.conditions.push(typeof n=="function"?new kc(i,n):kc.fromOptions(i,n)),r}typeError(t){let n=this.clone();return n.internalTests.typeError=Xi({message:t,name:"typeError",skipAbsent:!0,test(r){return this.schema._typeCheck(r)?!0:this.createError({params:{type:this.schema.type}})}}),n}oneOf(t,n=mn.oneOf){let r=this.clone();return t.forEach(i=>{r._whitelist.add(i),r._blacklist.delete(i)}),r.internalTests.whiteList=Xi({message:n,name:"oneOf",skipAbsent:!0,test(i){let s=this.schema._whitelist,a=s.resolveAll(this.resolve);return a.includes(i)?!0:this.createError({params:{values:Array.from(s).join(", "),resolved:a}})}}),r}notOneOf(t,n=mn.notOneOf){let r=this.clone();return t.forEach(i=>{r._blacklist.add(i),r._whitelist.delete(i)}),r.internalTests.blacklist=Xi({message:n,name:"notOneOf",test(i){let s=this.schema._blacklist,a=s.resolveAll(this.resolve);return a.includes(i)?this.createError({params:{values:Array.from(s).join(", "),resolved:a}}):!0}}),r}strip(t=!0){let n=this.clone();return n.spec.strip=t,n}describe(t){let n=(t?this.resolve(t):this).clone(),{label:r,meta:i,optional:s,nullable:a}=n.spec;return{meta:i,label:r,optional:s,nullable:a,default:n.getDefault(t),type:n.type,oneOf:n._whitelist.describe(),notOneOf:n._blacklist.describe(),tests:n.tests.map(c=>({name:c.OPTIONS.name,params:c.OPTIONS.params})).filter((c,u,_)=>_.findIndex(m=>m.name===c.name)===u)}}};lt.prototype.__isYupSchema__=!0;for(let e of["validate","validateSync"])lt.prototype[`${e}At`]=function(t,n,r={}){let{parent:i,parentPath:s,schema:a}=IQ(this,t,n,r.context);return a[e](i&&i[s],Object.assign({},r,{parent:i,path:t}))};for(let e of["equals","is"])lt.prototype[e]=lt.prototype.oneOf;for(let e of["not","nope"])lt.prototype[e]=lt.prototype.notOneOf;var yQ=()=>!0;function vQ(e){return new Uc(e)}var Uc=class extends lt{constructor(t){super(typeof t=="function"?{type:"mixed",check:t}:Object.assign({type:"mixed",check:yQ},t))}};vQ.prototype=Uc.prototype;function xQ(){return new Gc}var Gc=class extends lt{constructor(){super({type:"boolean",check(t){return t instanceof Boolean&&(t=t.valueOf()),typeof t=="boolean"}}),this.withMutation(()=>{this.transform((t,n,r)=>{if(r.spec.coerce&&!r.isType(t)){if(/^(true|1)$/i.test(String(t)))return!0;if(/^(false|0)$/i.test(String(t)))return!1}return t})})}isTrue(t=y1.isValue){return this.test({message:t,name:"is-value",exclusive:!0,params:{value:"true"},test(n){return Zt(n)||n===!0}})}isFalse(t=y1.isValue){return this.test({message:t,name:"is-value",exclusive:!0,params:{value:"false"},test(n){return Zt(n)||n===!1}})}default(t){return super.default(t)}defined(t){return super.defined(t)}optional(){return super.optional()}required(t){return super.required(t)}notRequired(){return super.notRequired()}nullable(){return super.nullable()}nonNullable(t){return super.nonNullable(t)}strip(t){return super.strip(t)}};xQ.prototype=Gc.prototype;var MQ=/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,LQ=/^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,wQ=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,PQ=e=>Zt(e)||e===e.trim(),FQ={}.toString();function Ia(){return new Hc}var Hc=class extends lt{constructor(){super({type:"string",check(t){return t instanceof String&&(t=t.valueOf()),typeof t=="string"}}),this.withMutation(()=>{this.transform((t,n,r)=>{if(!r.spec.coerce||r.isType(t)||Array.isArray(t))return t;let i=t!=null&&t.toString?t.toString():t;return i===FQ?t:i})})}required(t){return super.required(t).withMutation(n=>n.test({message:t||mn.required,name:"required",skipAbsent:!0,test:r=>!!r.length}))}notRequired(){return super.notRequired().withMutation(t=>(t.tests=t.tests.filter(n=>n.OPTIONS.name!=="required"),t))}length(t,n=jt.length){return this.test({message:n,name:"length",exclusive:!0,params:{length:t},skipAbsent:!0,test(r){return r.length===this.resolve(t)}})}min(t,n=jt.min){return this.test({message:n,name:"min",exclusive:!0,params:{min:t},skipAbsent:!0,test(r){return r.length>=this.resolve(t)}})}max(t,n=jt.max){return this.test({name:"max",exclusive:!0,message:n,params:{max:t},skipAbsent:!0,test(r){return r.length<=this.resolve(t)}})}matches(t,n){let r=!1,i,s;return n&&(typeof n=="object"?{excludeEmptyString:r=!1,message:i,name:s}=n:i=n),this.test({name:s||"matches",message:i||jt.matches,params:{regex:t},skipAbsent:!0,test:a=>a===""&&r||a.search(t)!==-1})}email(t=jt.email){return this.matches(MQ,{name:"email",message:t,excludeEmptyString:!0})}url(t=jt.url){return this.matches(LQ,{name:"url",message:t,excludeEmptyString:!0})}uuid(t=jt.uuid){return this.matches(wQ,{name:"uuid",message:t,excludeEmptyString:!1})}ensure(){return this.default("").transform(t=>t===null?"":t)}trim(t=jt.trim){return this.transform(n=>n!=null?n.trim():n).test({message:t,name:"trim",test:PQ})}lowercase(t=jt.lowercase){return this.transform(n=>Zt(n)?n:n.toLowerCase()).test({message:t,name:"string_case",exclusive:!0,skipAbsent:!0,test:n=>Zt(n)||n===n.toLowerCase()})}uppercase(t=jt.uppercase){return this.transform(n=>Zt(n)?n:n.toUpperCase()).test({message:t,name:"string_case",exclusive:!0,skipAbsent:!0,test:n=>Zt(n)||n===n.toUpperCase()})}};Ia.prototype=Hc.prototype;var kQ=e=>e!=+e;function BQ(){return new Yc}var Yc=class extends lt{constructor(){super({type:"number",check(t){return t instanceof Number&&(t=t.valueOf()),typeof t=="number"&&!kQ(t)}}),this.withMutation(()=>{this.transform((t,n,r)=>{if(!r.spec.coerce)return t;let i=t;if(typeof i=="string"){if(i=i.replace(/\s/g,""),i==="")return NaN;i=+i}return r.isType(i)||i===null?i:parseFloat(i)})})}min(t,n=Sr.min){return this.test({message:n,name:"min",exclusive:!0,params:{min:t},skipAbsent:!0,test(r){return r>=this.resolve(t)}})}max(t,n=Sr.max){return this.test({message:n,name:"max",exclusive:!0,params:{max:t},skipAbsent:!0,test(r){return r<=this.resolve(t)}})}lessThan(t,n=Sr.lessThan){return this.test({message:n,name:"max",exclusive:!0,params:{less:t},skipAbsent:!0,test(r){return r<this.resolve(t)}})}moreThan(t,n=Sr.moreThan){return this.test({message:n,name:"min",exclusive:!0,params:{more:t},skipAbsent:!0,test(r){return r>this.resolve(t)}})}positive(t=Sr.positive){return this.moreThan(0,t)}negative(t=Sr.negative){return this.lessThan(0,t)}integer(t=Sr.integer){return this.test({name:"integer",message:t,skipAbsent:!0,test:n=>Number.isInteger(n)})}truncate(){return this.transform(t=>Zt(t)?t:t|0)}round(t){var n;let r=["ceil","floor","round","trunc"];if(t=((n=t)==null?void 0:n.toLowerCase())||"round",t==="trunc")return this.truncate();if(r.indexOf(t.toLowerCase())===-1)throw new TypeError("Only valid options for round() are: "+r.join(", "));return this.transform(i=>Zt(i)?i:Math[t](i))}};BQ.prototype=Yc.prototype;var UQ=/^(\d{4}|[+-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,.](\d{1,}))?)?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?)?)?$/;function wn(e,t=0){return Number(e)||t}function GQ(e){let t=UQ.exec(e);if(!t)return Date.parse?Date.parse(e):Number.NaN;let n={year:wn(t[1]),month:wn(t[2],1)-1,day:wn(t[3],1),hour:wn(t[4]),minute:wn(t[5]),second:wn(t[6]),millisecond:t[7]?wn(t[7].substring(0,3)):0,z:t[8]||void 0,plusMinus:t[9]||void 0,hourOffset:wn(t[10]),minuteOffset:wn(t[11])};if(n.z===void 0&&n.plusMinus===void 0)return new Date(n.year,n.month,n.day,n.hour,n.minute,n.second,n.millisecond).valueOf();let r=0;return n.z!=="Z"&&n.plusMinus!==void 0&&(r=n.hourOffset*60+n.minuteOffset,n.plusMinus==="+"&&(r=0-r)),Date.UTC(n.year,n.month,n.day,n.hour,n.minute+r,n.second,n.millisecond)}var yw=new Date(""),HQ=e=>Object.prototype.toString.call(e)==="[object Date]";function vw(){return new Oa}var Oa=class e extends lt{constructor(){super({type:"date",check(t){return HQ(t)&&!isNaN(t.getTime())}}),this.withMutation(()=>{this.transform((t,n,r)=>!r.spec.coerce||r.isType(t)||t===null?t:(t=GQ(t),isNaN(t)?e.INVALID_DATE:new Date(t)))})}prepareParam(t,n){let r;if(Fn.isRef(t))r=t;else{let i=this.cast(t);if(!this._typeCheck(i))throw new TypeError(`\`${n}\` must be a Date or a value that can be \`cast()\` to a Date`);r=i}return r}min(t,n=I1.min){let r=this.prepareParam(t,"min");return this.test({message:n,name:"min",exclusive:!0,params:{min:t},skipAbsent:!0,test(i){return i>=this.resolve(r)}})}max(t,n=I1.max){let r=this.prepareParam(t,"max");return this.test({message:n,name:"max",exclusive:!0,params:{max:t},skipAbsent:!0,test(i){return i<=this.resolve(r)}})}};Oa.INVALID_DATE=yw;vw.prototype=Oa.prototype;vw.INVALID_DATE=yw;function YQ(e,t=[]){let n=[],r=new Set,i=new Set(t.map(([a,o])=>`${a}-${o}`));function s(a,o){let c=(0,Ht.split)(a)[0];r.add(c),i.has(`${o}-${c}`)||n.push([o,c])}for(let a of Object.keys(e)){let o=e[a];r.add(a),Fn.isRef(o)&&o.isSibling?s(o.path,a):Wc(o)&&"deps"in o&&o.deps.forEach(c=>s(c,a))}return Rw.default.array(Array.from(r),n).reverse()}function Cw(e,t){let n=1/0;return e.some((r,i)=>{var s;if((s=t.path)!=null&&s.includes(r))return n=i,!0}),n}function xw(e){return(t,n)=>Cw(e,t)-Cw(e,n)}var Mw=(e,t,n)=>{if(typeof e!="string")return e;let r=e;try{r=JSON.parse(e)}catch{}return n.isType(r)?r:e};function Fc(e){if("fields"in e){let t={};for(let[n,r]of Object.entries(e.fields))t[n]=Fc(r);return e.setFields(t)}if(e.type==="array"){let t=e.optional();return t.innerType&&(t.innerType=Fc(t.innerType)),t}return e.type==="tuple"?e.optional().clone({types:e.spec.types.map(Fc)}):"optional"in e?e.optional():e}var qQ=(e,t)=>{let n=[...(0,Ht.normalizePath)(t)];if(n.length===1)return n[0]in e;let r=n.pop(),i=(0,Ht.getter)((0,Ht.join)(n),!0)(e);return!!(i&&r in i)},Aw=e=>Object.prototype.toString.call(e)==="[object Object]";function VQ(e,t){let n=Object.keys(e.fields);return Object.keys(t).filter(r=>n.indexOf(r)===-1)}var $Q=xw([]);function x1(e){return new qc(e)}var qc=class extends lt{constructor(t){super({type:"object",check(n){return Aw(n)||typeof n=="function"}}),this.fields=Object.create(null),this._sortErrors=$Q,this._nodes=[],this._excludedEdges=[],this.withMutation(()=>{t&&this.shape(t)})}_cast(t,n={}){var r;let i=super._cast(t,n);if(i===void 0)return this.getDefault(n);if(!this._typeCheck(i))return i;let s=this.fields,a=(r=n.stripUnknown)!=null?r:this.spec.noUnknown,o=[].concat(this._nodes,Object.keys(i).filter(m=>!this._nodes.includes(m))),c={},u=Object.assign({},n,{parent:c,__validating:n.__validating||!1}),_=!1;for(let m of o){let f=s[m],S=m in i;if(f){let h,O=i[m];u.path=(n.path?`${n.path}.`:"")+m,f=f.resolve({value:O,context:n.context,parent:c});let y=f instanceof lt?f.spec:void 0,k=y?.strict;if(y!=null&&y.strip){_=_||m in i;continue}h=!n.__validating||!k?f.cast(i[m],u):i[m],h!==void 0&&(c[m]=h)}else S&&!a&&(c[m]=i[m]);(S!==m in c||c[m]!==i[m])&&(_=!0)}return _?c:i}_validate(t,n={},r,i){let{from:s=[],originalValue:a=t,recursive:o=this.spec.recursive}=n;n.from=[{schema:this,value:a},...s],n.__validating=!0,n.originalValue=a,super._validate(t,n,r,(c,u)=>{if(!o||!Aw(u)){i(c,u);return}a=a||u;let _=[];for(let m of this._nodes){let f=this.fields[m];!f||Fn.isRef(f)||_.push(f.asNestedTest({options:n,key:m,parent:u,parentPath:n.path,originalParent:a}))}this.runTests({tests:_,value:u,originalValue:a,options:n},r,m=>{i(m.sort(this._sortErrors).concat(c),u)})})}clone(t){let n=super.clone(t);return n.fields=Object.assign({},this.fields),n._nodes=this._nodes,n._excludedEdges=this._excludedEdges,n._sortErrors=this._sortErrors,n}concat(t){let n=super.concat(t),r=n.fields;for(let[i,s]of Object.entries(this.fields)){let a=r[i];r[i]=a===void 0?s:a}return n.withMutation(i=>i.setFields(r,[...this._excludedEdges,...t._excludedEdges]))}_getDefault(t){if("default"in this.spec)return super._getDefault(t);if(!this._nodes.length)return;let n={};return this._nodes.forEach(r=>{var i;let s=this.fields[r],a=t;(i=a)!=null&&i.value&&(a=Object.assign({},a,{parent:a.value,value:a.value[r]})),n[r]=s&&"getDefault"in s?s.getDefault(a):void 0}),n}setFields(t,n){let r=this.clone();return r.fields=t,r._nodes=YQ(t,n),r._sortErrors=xw(Object.keys(t)),n&&(r._excludedEdges=n),r}shape(t,n=[]){return this.clone().withMutation(r=>{let i=r._excludedEdges;return n.length&&(Array.isArray(n[0])||(n=[n]),i=[...r._excludedEdges,...n]),r.setFields(Object.assign(r.fields,t),i)})}partial(){let t={};for(let[n,r]of Object.entries(this.fields))t[n]="optional"in r&&r.optional instanceof Function?r.optional():r;return this.setFields(t)}deepPartial(){return Fc(this)}pick(t){let n={};for(let r of t)this.fields[r]&&(n[r]=this.fields[r]);return this.setFields(n,this._excludedEdges.filter(([r,i])=>t.includes(r)&&t.includes(i)))}omit(t){let n=[];for(let r of Object.keys(this.fields))t.includes(r)||n.push(r);return this.pick(n)}from(t,n,r){let i=(0,Ht.getter)(t,!0);return this.transform(s=>{if(!s)return s;let a=s;return qQ(s,t)&&(a=Object.assign({},s),r||delete a[t],a[n]=i(s)),a})}json(){return this.transform(Mw)}noUnknown(t=!0,n=v1.noUnknown){typeof t!="boolean"&&(n=t,t=!0);let r=this.test({name:"noUnknown",exclusive:!0,message:n,test(i){if(i==null)return!0;let s=VQ(this.schema,i);return!t||s.length===0||this.createError({params:{unknown:s.join(", ")}})}});return r.spec.noUnknown=t,r}unknown(t=!0,n=v1.noUnknown){return this.noUnknown(!t,n)}transformKeys(t){return this.transform(n=>{if(!n)return n;let r={};for(let i of Object.keys(n))r[t(i)]=n[i];return r})}camelCase(){return this.transformKeys(Na.camelCase)}snakeCase(){return this.transformKeys(Na.snakeCase)}constantCase(){return this.transformKeys(t=>(0,Na.snakeCase)(t).toUpperCase())}describe(t){let n=(t?this.resolve(t):this).clone(),r=super.describe(t);r.fields={};for(let[s,a]of Object.entries(n.fields)){var i;let o=t;(i=o)!=null&&i.value&&(o=Object.assign({},o,{parent:o.value,value:o.value[s]})),r.fields[s]=a.describe(o)}return r}};x1.prototype=qc.prototype;function WQ(e){return new Vc(e)}var Vc=class extends lt{constructor(t){super({type:"array",spec:{types:t},check(n){return Array.isArray(n)}}),this.innerType=void 0,this.innerType=t}_cast(t,n){let r=super._cast(t,n);if(!this._typeCheck(r)||!this.innerType)return r;let i=!1,s=r.map((a,o)=>{let c=this.innerType.cast(a,Object.assign({},n,{path:`${n.path||""}[${o}]`}));return c!==a&&(i=!0),c});return i?s:r}_validate(t,n={},r,i){var s;let a=this.innerType,o=(s=n.recursive)!=null?s:this.spec.recursive;n.originalValue!=null&&n.originalValue,super._validate(t,n,r,(c,u)=>{var _;if(!o||!a||!this._typeCheck(u)){i(c,u);return}let m=new Array(u.length);for(let S=0;S<u.length;S++){var f;m[S]=a.asNestedTest({options:n,index:S,parent:u,parentPath:n.path,originalParent:(f=n.originalValue)!=null?f:t})}this.runTests({value:u,tests:m,originalValue:(_=n.originalValue)!=null?_:t,options:n},r,S=>i(S.concat(c),u))})}clone(t){let n=super.clone(t);return n.innerType=this.innerType,n}json(){return this.transform(Mw)}concat(t){let n=super.concat(t);return n.innerType=this.innerType,t.innerType&&(n.innerType=n.innerType?n.innerType.concat(t.innerType):t.innerType),n}of(t){let n=this.clone();if(!Wc(t))throw new TypeError("`array.of()` sub-schema must be a valid yup schema not: "+Pn(t));return n.innerType=t,n.spec=Object.assign({},n.spec,{types:t}),n}length(t,n=Pc.length){return this.test({message:n,name:"length",exclusive:!0,params:{length:t},skipAbsent:!0,test(r){return r.length===this.resolve(t)}})}min(t,n){return n=n||Pc.min,this.test({message:n,name:"min",exclusive:!0,params:{min:t},skipAbsent:!0,test(r){return r.length>=this.resolve(t)}})}max(t,n){return n=n||Pc.max,this.test({message:n,name:"max",exclusive:!0,params:{max:t},skipAbsent:!0,test(r){return r.length<=this.resolve(t)}})}ensure(){return this.default(()=>[]).transform((t,n)=>this._typeCheck(t)?t:n==null?[]:[].concat(n))}compact(t){let n=t?(r,i,s)=>!t(r,i,s):r=>!!r;return this.transform(r=>r!=null?r.filter(n):r)}describe(t){let n=(t?this.resolve(t):this).clone(),r=super.describe(t);if(n.innerType){var i;let s=t;(i=s)!=null&&i.value&&(s=Object.assign({},s,{parent:s.value,value:s.value[0]})),r.innerType=n.innerType.describe(s)}return r}};WQ.prototype=Vc.prototype;function KQ(e){return new $c(e)}var $c=class extends lt{constructor(t){super({type:"tuple",spec:{types:t},check(n){let r=this.spec.types;return Array.isArray(n)&&n.length===r.length}}),this.withMutation(()=>{this.typeError(Iw.notType)})}_cast(t,n){let{types:r}=this.spec,i=super._cast(t,n);if(!this._typeCheck(i))return i;let s=!1,a=r.map((o,c)=>{let u=o.cast(i[c],Object.assign({},n,{path:`${n.path||""}[${c}]`}));return u!==i[c]&&(s=!0),u});return s?a:i}_validate(t,n={},r,i){let s=this.spec.types;super._validate(t,n,r,(a,o)=>{var c;if(!this._typeCheck(o)){i(a,o);return}let u=[];for(let[m,f]of s.entries()){var _;u[m]=f.asNestedTest({options:n,index:m,parent:o,parentPath:n.path,originalParent:(_=n.originalValue)!=null?_:t})}this.runTests({value:o,tests:u,originalValue:(c=n.originalValue)!=null?c:t,options:n},r,m=>i(m.concat(a),o))})}describe(t){let n=(t?this.resolve(t):this).clone(),r=super.describe(t);return r.innerType=n.spec.types.map((i,s)=>{var a;let o=t;return(a=o)!=null&&a.value&&(o=Object.assign({},o,{parent:o.value,value:o.value[s]})),i.describe(o)}),r}};KQ.prototype=$c.prototype;var eu=te(c9()),xa=te(require("fs/promises")),u9=te(require("fs")),_9=te(require("path"));var U1="e2b.toml",DX=`# This is a config for E2B sandbox template
108
108
 
109
- `,d9=x1({name:Ia(),id:Ia().required(),dockerfile:Ia().required()});async function tu(e){let t=await xa.readFile(e,"utf-8"),n=eu.parse(t);return await d9.validate(n)}async function m9(e,t,n){try{if(!n&&u9.existsSync(e))throw new Error(`Config already exists on path ${At(e)}`);let r=await d9.validate(t,{stripUnknown:!0}),i=eu.stringify(r);await xa.writeFile(e,DX+i)}catch(r){throw new Error(`E2B sandbox template config ${Gt({envID:t.id},e)} cannot be saved: ${r.message}`)}}function nu(e){return _9.join(e,U1)}var CX=1e3,p9=ua(dr.path("/envs/{envID}/builds/{buildID}").method("get").create()),E9=new gt("build").description(`Build sandbox template defined by ${At(hr)} or ${At(Qi)} in root directory. By default the root directory is the current working directory. This command also creates ${ln(U1)} config`).argument("[id]",`Specify ${ot("[id]")} of sandbox template to rebuild it. If you don's specify ${ot("[id]")} and there is no ${ln("e2b.toml")} a new sandbox will be created`).addOption(Bi).option("-d, --dockerfile <file>",`Specify path to Dockerfile. By default E2B tries to find ${ln(hr)} or ${ln(Qi)} in root directory`).option("-n, --name <name>","Specify name of sandbox template. You can use the name to start the sandbox in the SDK. The name must be lowercase and contain only letters, numbers, dashes and underscores.").alias("bd").action(async(e,t)=>{try{let n=hc();process.stdout.write(`
110
- `);let r=t.name?.trim();r&&!/[a-z0-9-_]+/.test(r)&&(console.error(`Name ${ln(r)} is not valid. Name can only contain lowercase letters, numbers, dashes and underscores.`),process.exit(1));let i=e,s=t.dockerfile,a=wi(t.path),o=nu(a),c=Ma.existsSync(o)?await tu(o):void 0,u=kn.relative(a,o);c&&(console.log(`Found sandbox template ${Gt({envID:c.id,aliases:c.name?[c.name]:void 0},u)}`),i=c.id,s=c.dockerfile),c&&e&&c.id!==e&&(console.error("You can't specify different ID than the one in config. If you want to build a new sandbox template remove the config file."),process.exit(1));let _=await Uv(a,{respectGitignore:!1,respectDockerignore:!0});r&&c?.name&&r!==c?.name&&console.log(`The name of the sandbox will be changed from ${ln(c.name)} to ${ln(r)}.`);let m=r||c?.name;console.log(`Preparing sandbox template building (${_.length} files in Docker build context). ${_.length?"":`If you are using ${ln(".dockerignore")} check if it is configured correctly.`}`);let{dockerfileContent:f,dockerfileRelativePath:S}=RX(a,s);console.log(`Found ${At(S)} that will be used to build the sandbox template.`);let h=new FormData;h.append("dockerfile",f);let O=await cw(a,_,S!==Qi?[{oldPath:S,newPath:Qi}]:[]);h.append("buildContext",O,"env.tar.gz.e2b"),m&&h.append("alias",m);let y=await NX(n,h,i);console.log(`Started building the sandbox template ${Gt(y)} `),await AX(n,y.envID,y.buildID,m),await m9(o,{id:y.envID,dockerfile:S,name:m},!0)}catch(n){console.error(n),process.exit(1)}});async function AX(e,t,n,r){let i=0,s,a=r?[r]:void 0;process.stdout.write(`
109
+ `,d9=x1({name:Ia(),id:Ia().required(),dockerfile:Ia().required()});async function tu(e){let t=await xa.readFile(e,"utf-8"),n=eu.parse(t);return await d9.validate(n)}async function m9(e,t,n){try{if(!n&&u9.existsSync(e))throw new Error(`Config already exists on path ${At(e)}`);let r=await d9.validate(t,{stripUnknown:!0}),i=eu.stringify(r);await xa.writeFile(e,DX+i)}catch(r){throw new Error(`E2B sandbox template config ${Gt({envID:t.id},e)} cannot be saved: ${r.message}`)}}function nu(e){return _9.join(e,U1)}var CX=1e3,p9=ua(dr.path("/envs/{envID}/builds/{buildID}").method("get").create()),E9=new gt("build").description(`Build sandbox template defined by ${At(hr)} or ${At(Qi)} in root directory. By default the root directory is the current working directory. This command also creates ${ln(U1)} config`).argument("[id]",`Specify ${ot("[id]")} of sandbox template to rebuild it. If you don's specify ${ot("[id]")} and there is no ${ln("e2b.toml")} a new sandbox will be created`).addOption(Bi).option("-d, --dockerfile <file>",`Specify path to Dockerfile. By default E2B tries to find ${ln(hr)} or ${ln(Qi)} in root directory`).option("-n, --name <template-name>","Specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores").alias("bd").action(async(e,t)=>{try{let n=hc();process.stdout.write(`
110
+ `);let r=t.name?.trim();r&&!/[a-z0-9-_]+/.test(r)&&(console.error(`Name ${ln(r)} is not valid. Name can only contain lowercase letters, numbers, dashes and underscores.`),process.exit(1));let i=e,s=t.dockerfile,a=wi(t.path),o=nu(a),c=Ma.existsSync(o)?await tu(o):void 0,u=kn.relative(a,o);c&&(console.log(`Found sandbox template ${Gt({envID:c.id,aliases:c.name?[c.name]:void 0},u)}`),i=c.id,s=c.dockerfile),c&&e&&c.id!==e&&(console.error("You can't specify different ID than the one in config. If you want to build a new sandbox template remove the config file."),process.exit(1));let _=await Uv(a,{respectGitignore:!1,respectDockerignore:!0});r&&c?.name&&r!==c?.name&&console.log(`The sandbox template name will be changed from ${ln(c.name)} to ${ln(r)}.`);let m=r||c?.name;console.log(`Preparing sandbox template building (${_.length} files in Docker build context). ${_.length?"":`If you are using ${ln(".dockerignore")} check if it is configured correctly.`}`);let{dockerfileContent:f,dockerfileRelativePath:S}=RX(a,s);console.log(`Found ${At(S)} that will be used to build the sandbox template.`);let h=new FormData;h.append("dockerfile",f);let O=await cw(a,_,S!==Qi?[{oldPath:S,newPath:Qi}]:[]);h.append("buildContext",O,"env.tar.gz.e2b"),m&&h.append("alias",m);let y=await NX(n,h,i);console.log(`Started building the sandbox template ${Gt(y)} `),await AX(n,y.envID,y.buildID,m),await m9(o,{id:y.envID,dockerfile:S,name:m},!0)}catch(n){console.error(n),process.exit(1)}});async function AX(e,t,n,r){let i=0,s,a=r?[r]:void 0;process.stdout.write(`
111
111
  `);do{await qM(CX);try{s=await p9(e,{envID:t,logsOffset:i,buildID:n})}catch(o){if(o instanceof p9.Error){let c=o.getActualType();if(c.status===401)throw new Error(`Error getting build info - (${c.status}) bad request: ${c.data.message}`);if(c.status===404)throw new Error(`Error getting build info - (${c.status}) not found: ${c.data.message}`);if(c.status===500)throw new Error(`Error getting build info - (${c.status}) server error: ${c.data.message}`)}throw o}switch(i+=s.data.logs.length,s.data.status){case"building":s.data.logs.forEach(o=>process.stdout.write(Xm(Qt(o))));break;case"ready":{let o=Vv(`from e2b import Sandbox
112
112
 
113
113
  # Start sandbox
@@ -133,8 +133,8 @@ ${Zm(o,"Python SDK")}${Zm(c,"JS SDK",!0)}`;console.log(`
133
133
  ${tr(_,{float:"left",padding:0,margin:1,title:"Usage examples"})}`);break}case"error":throw s.data.logs.forEach(o=>process.stdout.write(Xm(Qt(o)))),new Error(`
134
134
  \u274C Building sandbox template ${Gt({aliases:a,...s.data})} failed.
135
135
  Check the logs above for more details or contact us ${lr("(https://e2b.dev/docs/getting-help)")} to get help.
136
- `)}}while(s.data.status==="building")}function G1(e){if(Ma.existsSync(e))return Ma.readFileSync(e,"utf-8")}function RX(e,t){if(t){let o=kn.join(e,t),c=G1(o),u=kn.relative(e,o);if(c===void 0)throw new Error(`No ${At(u)} found in the root directory.`);return{dockerfilePath:o,dockerfileContent:c,dockerfileRelativePath:u}}let n=kn.join(e,hr),r=G1(n),i=kn.relative(e,n),s=i;if(r!==void 0)return{dockerfilePath:n,dockerfileContent:r,dockerfileRelativePath:s};n=kn.join(e,Qi),r=G1(n);let a=kn.relative(e,n);if(s=a,r!==void 0)return{dockerfilePath:n,dockerfileContent:r,dockerfileRelativePath:s};throw new Error(`No ${At(i)} or ${At(a)} found in the root directory.You can specify a custom Dockerfile with ${ot("--dockerfile <file>")} option.`)}async function NX(e,t,n){let r=await fetch(Qs+(n?`/envs/${n}`:"/envs"),{method:"POST",headers:{Authorization:`Bearer ${e}`},body:t}),i=await r.json();if(!r.ok){let s=i;throw s.code===401?new Error(`Authentication error: ${r.statusText}, ${s.message??"no message"}`):s.code===500?new Error(`Server error: ${r.statusText}, ${s.message??"no message"}`):new Error(`API request failed: ${r.statusText}, ${s.message??"no message"}`)}return i}l();var w9=te(L9());var Ij=ua(dr.path("/envs").method("get").create()),P9=new gt("list").description("List sandbox templates").alias("ls").action(async()=>{try{let e=hc();process.stdout.write(`
137
- `);let n=(await Ij(e,{})).data;n?.length?(new w9.Table({title:"Sandbox templates",columns:[{name:"envID",alignment:"left",title:"Template ID"},{name:"aliases",alignment:"left",title:"Name",color:"blue"}],disabledColumns:["public","buildID"],rows:n.map(i=>({...i,aliases:jm(i.aliases)})),sort:(i,s)=>i.envID.localeCompare(s.envID)}).printTable(),process.stdout.write(`
136
+ `)}}while(s.data.status==="building")}function G1(e){if(Ma.existsSync(e))return Ma.readFileSync(e,"utf-8")}function RX(e,t){if(t){let o=kn.join(e,t),c=G1(o),u=kn.relative(e,o);if(c===void 0)throw new Error(`No ${At(u)} found in the root directory.`);return{dockerfilePath:o,dockerfileContent:c,dockerfileRelativePath:u}}let n=kn.join(e,hr),r=G1(n),i=kn.relative(e,n),s=i;if(r!==void 0)return{dockerfilePath:n,dockerfileContent:r,dockerfileRelativePath:s};n=kn.join(e,Qi),r=G1(n);let a=kn.relative(e,n);if(s=a,r!==void 0)return{dockerfilePath:n,dockerfileContent:r,dockerfileRelativePath:s};throw new Error(`No ${At(i)} or ${At(a)} found in the root directory.You can specify a custom Dockerfile with ${ot("--dockerfile <file>")} option.`)}async function NX(e,t,n){let r=await fetch(Qs+(n?`/envs/${n}`:"/envs"),{method:"POST",headers:{Authorization:`Bearer ${e}`},body:t}),i;try{i=await r.json()}catch{throw new Error(`Build API request failed: ${r.statusText}`)}if(!r.ok){let s=i;throw s.code===401?new Error(`Authentication error: ${r.statusText}, ${s.message??"no message"}`):s.code===500?new Error(`Server error: ${r.statusText}, ${s.message??"no message"}`):new Error(`API request failed: ${r.statusText}, ${s.message??"no message"}`)}return i}l();var w9=te(L9());var Ij=ua(dr.path("/envs").method("get").create()),P9=new gt("list").description("List sandbox templates").alias("ls").action(async()=>{try{let e=hc();process.stdout.write(`
137
+ `);let n=(await Ij(e,{})).data;n?.length?(new w9.Table({title:"Sandbox templates",columns:[{name:"envID",alignment:"left",title:"Template ID"},{name:"aliases",alignment:"left",title:"Template Name",color:"blue"}],disabledColumns:["public","buildID"],rows:n.map(i=>({...i,aliases:jm(i.aliases)})),sort:(i,s)=>i.envID.localeCompare(s.envID)}).printTable(),process.stdout.write(`
138
138
  `)):console.log("No templates found.")}catch(e){console.error(e),process.exit(1)}});l();l();l();function F9(){let e,t,n=new Promise((r,i)=>{e=r,t=i});return{resolve:e,reject:t,promise:n}}function k9(){return{cols:process.stdout.columns,rows:process.stdout.rows}}async function B9(e,t,n){let{promise:r,resolve:i}=F9();console.log(t);let s=await e.start({onData:c=>process.stdout.write(c),size:k9(),onExit:i,envVars:{TERM:"xterm-256color"}});process.stdin.setEncoding("utf8"),process.stdin.setRawMode(!0),process.stdout.setEncoding("utf8");let a=process.stdout.on("resize",()=>s.resize(k9())),o=process.stdin.on("data",c=>s.sendData(c.toString("utf8")));return r.then(()=>{console.log(n),a.destroy(),o.destroy()}),{kill:s.kill.bind(s),exited:r}}var U9=te(require("fs"));var G9=te(require("path")),H9=new gt("shell").description("Connect terminal to sandbox").argument("[id]",`Connect to sandbox specified by ${ot("[id]")}`).addOption(Bi).alias("sh").action(async(e,t)=>{try{let n=$M(),r=e,i=wi(t.path),s=nu(i),a=U9.default.existsSync(s)?await tu(s):void 0,o=G9.default.relative(i,s);!r&&a&&(console.log(`Found sandbox template ${Gt({envID:a.id,aliases:a.name?[a.name]:void 0},o)}`),r=a.id),r||(console.error("You need to specify sandbox template ID or path to sandbox template config"),process.exit(1)),await yj({apiKey:n,template:{envID:r}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}});async function yj({apiKey:e,template:t}){let n=await da.create({apiKey:e,id:t.envID});if(n.terminal){let{exited:r}=await B9(n.terminal,`Terminal connected to sandbox ${Gt(t)}
139
139
  with sandbox URL ${ot(`https://${n.getHostname()}`)}`,`Disconnecting terminal from sandbox ${Gt(t)}`);await r,console.log(`Closing terminal connection to sandbox ${Gt(t)}`)}else throw new Error("Cannot start terminal - no sandbox")}l();var Y9=te(require("fs/promises")),q9=te(require("fs")),rE=te(require("path"));var V9=new gt("init").description(`Create basic E2B Dockerfile (${At("e2b.Dockerfile")}) in root directory. You can then run ${lr("e2b build")} to build sandbox template from this Dockerfile`).addOption(Bi).alias("it").action(async e=>{try{process.stdout.write(`
140
140
  `);let t=wi(e.path),n=rE.join(t,hr),r=q9.existsSync(n),i=e.path?rE.join(e.path,hr):hr;if(r){console.log(`Dockerfile ${At(i)} already exists.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e2b/cli",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "description": "CLI for managing e2b sandbox templates",
5
5
  "homepage": "https://e2b.dev",
6
6
  "license": "MIT",