@capgo/cli 7.88.0 → 7.88.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/sdk.js CHANGED
@@ -127,7 +127,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
127
127
  `)}),$.__defineSetter__("stack",function(X){return[X].concat($.stack).join(`
128
128
 
129
129
  `)}),$}});var jx=T((DhD,Rx)=>{var d6=p("constants"),gQD=process.cwd,WY=null,mQD=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!WY)WY=gQD.call(process);return WY};try{process.cwd()}catch(D){}if(typeof process.chdir==="function"){if(KY=process.chdir,process.chdir=function(D){WY=null,KY.call(process,D)},Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,KY)}var KY;Rx.exports=cQD;function cQD(D){if(d6.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./))$(D);if(!D.lutimes)X(D);if(D.chown=Q(D.chown),D.fchown=Q(D.fchown),D.lchown=Q(D.lchown),D.chmod=Y(D.chmod),D.fchmod=Y(D.fchmod),D.lchmod=Y(D.lchmod),D.chownSync=F(D.chownSync),D.fchownSync=F(D.fchownSync),D.lchownSync=F(D.lchownSync),D.chmodSync=J(D.chmodSync),D.fchmodSync=J(D.fchmodSync),D.lchmodSync=J(D.lchmodSync),D.stat=Z(D.stat),D.fstat=Z(D.fstat),D.lstat=Z(D.lstat),D.statSync=w(D.statSync),D.fstatSync=w(D.fstatSync),D.lstatSync=w(D.lstatSync),D.chmod&&!D.lchmod)D.lchmod=function(U,O,q){if(q)process.nextTick(q)},D.lchmodSync=function(){};if(D.chown&&!D.lchown)D.lchown=function(U,O,q,z){if(z)process.nextTick(z)},D.lchownSync=function(){};if(mQD==="win32")D.rename=typeof D.rename!=="function"?D.rename:function(U){function O(q,z,B){var W=Date.now(),L=0;U(q,z,function M(I){if(I&&(I.code==="EACCES"||I.code==="EPERM"||I.code==="EBUSY")&&Date.now()-W<60000){if(setTimeout(function(){D.stat(z,function(K,V){if(K&&K.code==="ENOENT")U(q,z,M);else B(I)})},L),L<100)L+=10;return}if(B)B(I)})}if(Object.setPrototypeOf)Object.setPrototypeOf(O,U);return O}(D.rename);D.read=typeof D.read!=="function"?D.read:function(U){function O(q,z,B,W,L,M){var I;if(M&&typeof M==="function"){var K=0;I=function(V,N,R){if(V&&V.code==="EAGAIN"&&K<10)return K++,U.call(D,q,z,B,W,L,I);M.apply(this,arguments)}}return U.call(D,q,z,B,W,L,I)}if(Object.setPrototypeOf)Object.setPrototypeOf(O,U);return O}(D.read),D.readSync=typeof D.readSync!=="function"?D.readSync:function(U){return function(O,q,z,B,W){var L=0;while(!0)try{return U.call(D,O,q,z,B,W)}catch(M){if(M.code==="EAGAIN"&&L<10){L++;continue}throw M}}}(D.readSync);function $(U){U.lchmod=function(O,q,z){U.open(O,d6.O_WRONLY|d6.O_SYMLINK,q,function(B,W){if(B){if(z)z(B);return}U.fchmod(W,q,function(L){U.close(W,function(M){if(z)z(L||M)})})})},U.lchmodSync=function(O,q){var z=U.openSync(O,d6.O_WRONLY|d6.O_SYMLINK,q),B=!0,W;try{W=U.fchmodSync(z,q),B=!1}finally{if(B)try{U.closeSync(z)}catch(L){}else U.closeSync(z)}return W}}function X(U){if(d6.hasOwnProperty("O_SYMLINK")&&U.futimes)U.lutimes=function(O,q,z,B){U.open(O,d6.O_SYMLINK,function(W,L){if(W){if(B)B(W);return}U.futimes(L,q,z,function(M){U.close(L,function(I){if(B)B(M||I)})})})},U.lutimesSync=function(O,q,z){var B=U.openSync(O,d6.O_SYMLINK),W,L=!0;try{W=U.futimesSync(B,q,z),L=!1}finally{if(L)try{U.closeSync(B)}catch(M){}else U.closeSync(B)}return W};else if(U.futimes)U.lutimes=function(O,q,z,B){if(B)process.nextTick(B)},U.lutimesSync=function(){}}function Y(U){if(!U)return U;return function(O,q,z){return U.call(D,O,q,function(B){if(G(B))B=null;if(z)z.apply(this,arguments)})}}function J(U){if(!U)return U;return function(O,q){try{return U.call(D,O,q)}catch(z){if(!G(z))throw z}}}function Q(U){if(!U)return U;return function(O,q,z,B){return U.call(D,O,q,z,function(W){if(G(W))W=null;if(B)B.apply(this,arguments)})}}function F(U){if(!U)return U;return function(O,q,z){try{return U.call(D,O,q,z)}catch(B){if(!G(B))throw B}}}function Z(U){if(!U)return U;return function(O,q,z){if(typeof q==="function")z=q,q=null;function B(W,L){if(L){if(L.uid<0)L.uid+=4294967296;if(L.gid<0)L.gid+=4294967296}if(z)z.apply(this,arguments)}return q?U.call(D,O,q,B):U.call(D,O,B)}}function w(U){if(!U)return U;return function(O,q){var z=q?U.call(D,O,q):U.call(D,O);if(z){if(z.uid<0)z.uid+=4294967296;if(z.gid<0)z.gid+=4294967296}return z}}function G(U){if(!U)return!0;if(U.code==="ENOSYS")return!0;var O=!process.getuid||process.getuid()!==0;if(O){if(U.code==="EINVAL"||U.code==="EPERM")return!0}return!1}}});var Cx=T(($hD,Tx)=>{var Ex=p("stream").Stream;Tx.exports=dQD;function dQD(D){return{ReadStream:$,WriteStream:X};function $(Y,J){if(!(this instanceof $))return new $(Y,J);Ex.call(this);var Q=this;this.path=Y,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,J=J||{};var F=Object.keys(J);for(var Z=0,w=F.length;Z<w;Z++){var G=F[Z];this[G]=J[G]}if(this.encoding)this.setEncoding(this.encoding);if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!=="number")throw TypeError("end must be a Number");if(this.start>this.end)throw Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){Q._read()});return}D.open(this.path,this.flags,this.mode,function(U,O){if(U){Q.emit("error",U),Q.readable=!1;return}Q.fd=O,Q.emit("open",O),Q._read()})}function X(Y,J){if(!(this instanceof X))return new X(Y,J);Ex.call(this),this.path=Y,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,J=J||{};var Q=Object.keys(J);for(var F=0,Z=Q.length;F<Z;F++){var w=Q[F];this[w]=J[w]}if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.start<0)throw Error("start must be >= zero");this.pos=this.start}if(this.busy=!1,this._queue=[],this.fd===null)this._open=D.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush()}}});var xx=T((XhD,Px)=>{Px.exports=nQD;var lQD=Object.getPrototypeOf||function(D){return D.__proto__};function nQD(D){if(D===null||typeof D!=="object")return D;if(D instanceof Object)var $={__proto__:lQD(D)};else var $=Object.create(null);return Object.getOwnPropertyNames(D).forEach(function(X){Object.defineProperty($,X,Object.getOwnPropertyDescriptor(D,X))}),$}});var S0=T((JhD,CO)=>{var M0=p("fs"),iQD=jx(),pQD=Cx(),rQD=xx(),HY=p("util"),o0,NY;if(typeof Symbol==="function"&&typeof Symbol.for==="function")o0=Symbol.for("graceful-fs.queue"),NY=Symbol.for("graceful-fs.previous");else o0="___graceful-fs.queue",NY="___graceful-fs.previous";function oQD(){}function ux(D,$){Object.defineProperty(D,o0,{get:function(){return $}})}var $8=oQD;if(HY.debuglog)$8=HY.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))$8=function(){var D=HY.format.apply(HY,arguments);D="GFS4: "+D.split(/\n/).join(`
130
- GFS4: `),console.error(D)};if(!M0[o0]){if(jO=global[o0]||[],ux(M0,jO),M0.close=function(D){function $(X,Y){return D.call(M0,X,function(J){if(!J)Sx();if(typeof Y==="function")Y.apply(this,arguments)})}return Object.defineProperty($,NY,{value:D}),$}(M0.close),M0.closeSync=function(D){function $(X){D.apply(M0,arguments),Sx()}return Object.defineProperty($,NY,{value:D}),$}(M0.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){$8(M0[o0]),p("assert").equal(M0[o0].length,0)})}var jO;if(!global[o0])ux(global,M0[o0]);CO.exports=EO(rQD(M0));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!M0.__patched)CO.exports=EO(M0),M0.__patched=!0;function EO(D){iQD(D),D.gracefulify=EO,D.createReadStream=N,D.createWriteStream=R;var $=D.readFile;D.readFile=X;function X(_,u,x){if(typeof u==="function")x=u,u=null;return h(_,u,x);function h(b,l,f,j){return $(b,l,function(S){if(S&&(S.code==="EMFILE"||S.code==="ENFILE"))k9([h,[b,l,f],S,j||Date.now(),Date.now()]);else if(typeof f==="function")f.apply(this,arguments)})}}var Y=D.writeFile;D.writeFile=J;function J(_,u,x,h){if(typeof x==="function")h=x,x=null;return b(_,u,x,h);function b(l,f,j,S,v){return Y(l,f,j,function(y){if(y&&(y.code==="EMFILE"||y.code==="ENFILE"))k9([b,[l,f,j,S],y,v||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}var Q=D.appendFile;if(Q)D.appendFile=F;function F(_,u,x,h){if(typeof x==="function")h=x,x=null;return b(_,u,x,h);function b(l,f,j,S,v){return Q(l,f,j,function(y){if(y&&(y.code==="EMFILE"||y.code==="ENFILE"))k9([b,[l,f,j,S],y,v||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}var Z=D.copyFile;if(Z)D.copyFile=w;function w(_,u,x,h){if(typeof x==="function")h=x,x=0;return b(_,u,x,h);function b(l,f,j,S,v){return Z(l,f,j,function(y){if(y&&(y.code==="EMFILE"||y.code==="ENFILE"))k9([b,[l,f,j,S],y,v||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}var G=D.readdir;D.readdir=O;var U=/^v[0-5]\./;function O(_,u,x){if(typeof u==="function")x=u,u=null;var h=U.test(process.version)?function(f,j,S,v){return G(f,b(f,j,S,v))}:function(f,j,S,v){return G(f,j,b(f,j,S,v))};return h(_,u,x);function b(l,f,j,S){return function(v,y){if(v&&(v.code==="EMFILE"||v.code==="ENFILE"))k9([h,[l,f,j],v,S||Date.now(),Date.now()]);else{if(y&&y.sort)y.sort();if(typeof j==="function")j.call(this,v,y)}}}}if(process.version.substr(0,4)==="v0.8"){var q=pQD(D);M=q.ReadStream,K=q.WriteStream}var z=D.ReadStream;if(z)M.prototype=Object.create(z.prototype),M.prototype.open=I;var B=D.WriteStream;if(B)K.prototype=Object.create(B.prototype),K.prototype.open=V;Object.defineProperty(D,"ReadStream",{get:function(){return M},set:function(_){M=_},enumerable:!0,configurable:!0}),Object.defineProperty(D,"WriteStream",{get:function(){return K},set:function(_){K=_},enumerable:!0,configurable:!0});var W=M;Object.defineProperty(D,"FileReadStream",{get:function(){return W},set:function(_){W=_},enumerable:!0,configurable:!0});var L=K;Object.defineProperty(D,"FileWriteStream",{get:function(){return L},set:function(_){L=_},enumerable:!0,configurable:!0});function M(_,u){if(this instanceof M)return z.apply(this,arguments),this;else return M.apply(Object.create(M.prototype),arguments)}function I(){var _=this;A(_.path,_.flags,_.mode,function(u,x){if(u){if(_.autoClose)_.destroy();_.emit("error",u)}else _.fd=x,_.emit("open",x),_.read()})}function K(_,u){if(this instanceof K)return B.apply(this,arguments),this;else return K.apply(Object.create(K.prototype),arguments)}function V(){var _=this;A(_.path,_.flags,_.mode,function(u,x){if(u)_.destroy(),_.emit("error",u);else _.fd=x,_.emit("open",x)})}function N(_,u){return new D.ReadStream(_,u)}function R(_,u){return new D.WriteStream(_,u)}var C=D.open;D.open=A;function A(_,u,x,h){if(typeof x==="function")h=x,x=null;return b(_,u,x,h);function b(l,f,j,S,v){return C(l,f,j,function(y,g){if(y&&(y.code==="EMFILE"||y.code==="ENFILE"))k9([b,[l,f,j,S],y,v||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}return D}function k9(D){$8("ENQUEUE",D[0].name,D[1]),M0[o0].push(D),TO()}var VY;function Sx(){var D=Date.now();for(var $=0;$<M0[o0].length;++$)if(M0[o0][$].length>2)M0[o0][$][3]=D,M0[o0][$][4]=D;TO()}function TO(){if(clearTimeout(VY),VY=void 0,M0[o0].length===0)return;var D=M0[o0].shift(),$=D[0],X=D[1],Y=D[2],J=D[3],Q=D[4];if(J===void 0)$8("RETRY",$.name,X),$.apply(null,X);else if(Date.now()-J>=60000){$8("TIMEOUT",$.name,X);var F=X.pop();if(typeof F==="function")F.call(null,Y)}else{var Z=Date.now()-Q,w=Math.max(Q-J,1),G=Math.min(w*1.2,100);if(Z>=G)$8("RETRY",$.name,X),$.apply(null,X.concat([J]));else M0[o0].push(D)}if(VY===void 0)VY=setTimeout(TO,0)}});var _x=T((YhD,vx)=>{function e1(D,$){if(typeof $==="boolean")$={forever:$};if(this._originalTimeouts=JSON.parse(JSON.stringify(D)),this._timeouts=D,this._options=$||{},this._maxRetryTime=$&&$.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}vx.exports=e1;e1.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};e1.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};e1.prototype.retry=function(D){if(this._timeout)clearTimeout(this._timeout);if(!D)return!1;var $=new Date().getTime();if(D&&$-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(D);var X=this._timeouts.shift();if(X===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),X=this._timeouts.shift();else return!1;var Y=this,J=setTimeout(function(){if(Y._attempts++,Y._operationTimeoutCb){if(Y._timeout=setTimeout(function(){Y._operationTimeoutCb(Y._attempts)},Y._operationTimeout),Y._options.unref)Y._timeout.unref()}Y._fn(Y._attempts)},X);if(this._options.unref)J.unref();return!0};e1.prototype.attempt=function(D,$){if(this._fn=D,$){if($.timeout)this._operationTimeout=$.timeout;if($.cb)this._operationTimeoutCb=$.cb}var X=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){X._operationTimeoutCb()},X._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};e1.prototype.try=function(D){console.log("Using RetryOperation.try() is deprecated"),this.attempt(D)};e1.prototype.start=function(D){console.log("Using RetryOperation.start() is deprecated"),this.attempt(D)};e1.prototype.start=e1.prototype.try;e1.prototype.errors=function(){return this._errors};e1.prototype.attempts=function(){return this._attempts};e1.prototype.mainError=function(){if(this._errors.length===0)return null;var D={},$=null,X=0;for(var Y=0;Y<this._errors.length;Y++){var J=this._errors[Y],Q=J.message,F=(D[Q]||0)+1;if(D[Q]=F,F>=X)$=J,X=F}return $}});var fx=T((tQD)=>{var aQD=_x();tQD.operation=function(D){var $=tQD.timeouts(D);return new aQD($,{forever:D&&D.forever,unref:D&&D.unref,maxRetryTime:D&&D.maxRetryTime})};tQD.timeouts=function(D){if(D instanceof Array)return[].concat(D);var $={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var X in D)$[X]=D[X];if($.minTimeout>$.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var Y=[];for(var J=0;J<$.retries;J++)Y.push(this.createTimeout(J,$));if(D&&D.forever&&!Y.length)Y.push(this.createTimeout(J,$));return Y.sort(function(Q,F){return Q-F}),Y};tQD.createTimeout=function(D,$){var X=$.randomize?Math.random()+1:1,Y=Math.round(X*$.minTimeout*Math.pow($.factor,D));return Y=Math.min(Y,$.maxTimeout),Y};tQD.wrap=function(D,$,X){if($ instanceof Array)X=$,$=null;if(!X){X=[];for(var Y in D)if(typeof D[Y]==="function")X.push(Y)}for(var J=0;J<X.length;J++){var Q=X[J],F=D[Q];D[Q]=function(w){var G=tQD.operation($),U=Array.prototype.slice.call(arguments,1),O=U.pop();U.push(function(q){if(G.retry(q))return;if(q)arguments[0]=G.mainError();O.apply(this,arguments)}),G.attempt(function(){w.apply(D,U)})}.bind(D,F),D[Q].options=$}}});var yx=T((FhD,LY)=>{LY.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")LY.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")LY.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var AY=T((ZhD,y9)=>{var K0=global.process,X8=function(D){return D&&typeof D==="object"&&typeof D.removeListener==="function"&&typeof D.emit==="function"&&typeof D.reallyExit==="function"&&typeof D.listeners==="function"&&typeof D.kill==="function"&&typeof D.pid==="number"&&typeof D.on==="function"};if(!X8(K0))y9.exports=function(){return function(){}};else{if(PO=p("assert"),J8=yx(),xO=/^win/i.test(K0.platform),f9=p("events"),typeof f9!=="function")f9=f9.EventEmitter;if(K0.__signal_exit_emitter__)g0=K0.__signal_exit_emitter__;else g0=K0.__signal_exit_emitter__=new f9,g0.count=0,g0.emitted={};if(!g0.infinite)g0.setMaxListeners(1/0),g0.infinite=!0;y9.exports=function(D,$){if(!X8(global.process))return function(){};if(PO.equal(typeof D,"function","a callback must be provided for exit handler"),Y8===!1)MY();var X="exit";if($&&$.alwaysLast)X="afterexit";var Y=function(){if(g0.removeListener(X,D),g0.listeners("exit").length===0&&g0.listeners("afterexit").length===0)B3()};return g0.on(X,D),Y},B3=function(){if(!Y8||!X8(global.process))return;Y8=!1,J8.forEach(function($){try{K0.removeListener($,W3[$])}catch(X){}}),K0.emit=K3,K0.reallyExit=IY,g0.count-=1},y9.exports.unload=B3,l6=function($,X,Y){if(g0.emitted[$])return;g0.emitted[$]=!0,g0.emit($,X,Y)},W3={},J8.forEach(function(D){W3[D]=function(){if(!X8(global.process))return;var X=K0.listeners(D);if(X.length===g0.count){if(B3(),l6("exit",null,D),l6("afterexit",null,D),xO&&D==="SIGHUP")D="SIGINT";K0.kill(K0.pid,D)}}}),y9.exports.signals=function(){return J8},Y8=!1,MY=function(){if(Y8||!X8(global.process))return;Y8=!0,g0.count+=1,J8=J8.filter(function($){try{return K0.on($,W3[$]),!0}catch(X){return!1}}),K0.emit=uO,K0.reallyExit=SO},y9.exports.load=MY,IY=K0.reallyExit,SO=function($){if(!X8(global.process))return;K0.exitCode=$||0,l6("exit",K0.exitCode,null),l6("afterexit",K0.exitCode,null),IY.call(K0,K0.exitCode)},K3=K0.emit,uO=function($,X){if($==="exit"&&X8(global.process)){if(X!==void 0)K0.exitCode=X;var Y=K3.apply(this,arguments);return l6("exit",K0.exitCode,null),l6("afterexit",K0.exitCode,null),Y}else return K3.apply(this,arguments)}}var PO,J8,xO,f9,g0,B3,l6,W3,Y8,MY,IY,SO,K3,uO});var hx=T((JFD,vO)=>{var bx=Symbol();function $FD(D,$,X){let Y=$[bx];if(Y)return $.stat(D,(Q,F)=>{if(Q)return X(Q);X(null,F.mtime,Y)});let J=new Date(Math.ceil(Date.now()/1000)*1000+5);$.utimes(D,J,J,(Q)=>{if(Q)return X(Q);$.stat(D,(F,Z)=>{if(F)return X(F);let w=Z.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty($,bx,{value:w}),X(null,Z.mtime,w)})})}function XFD(D){let $=Date.now();if(D==="s")$=Math.ceil($/1000)*1000;return new Date($)}JFD.probe=$FD;JFD.getMtime=XFD});var lx=T((qFD,V3)=>{var FFD=p("path"),fO=S0(),ZFD=fx(),wFD=AY(),gx=hx(),Z6={};function H3(D,$){return $.lockfilePath||`${D}.lock`}function yO(D,$,X){if(!$.realpath)return X(null,FFD.resolve(D));$.fs.realpath(D,X)}function kO(D,$,X){let Y=H3(D,$);$.fs.mkdir(Y,(J)=>{if(!J)return gx.probe(Y,$.fs,(Q,F,Z)=>{if(Q)return $.fs.rmdir(Y,()=>{}),X(Q);X(null,F,Z)});if(J.code!=="EEXIST")return X(J);if($.stale<=0)return X(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:D}));$.fs.stat(Y,(Q,F)=>{if(Q){if(Q.code==="ENOENT")return kO(D,{...$,stale:0},X);return X(Q)}if(!mx(F,$))return X(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:D}));cx(D,$,(Z)=>{if(Z)return X(Z);kO(D,{...$,stale:0},X)})})})}function mx(D,$){return D.mtime.getTime()<Date.now()-$.stale}function cx(D,$,X){$.fs.rmdir(H3(D,$),(Y)=>{if(Y&&Y.code!=="ENOENT")return X(Y);X()})}function RY(D,$){let X=Z6[D];if(X.updateTimeout)return;if(X.updateDelay=X.updateDelay||$.update,X.updateTimeout=setTimeout(()=>{X.updateTimeout=null,$.fs.stat(X.lockfilePath,(Y,J)=>{let Q=X.lastUpdate+$.stale<Date.now();if(Y){if(Y.code==="ENOENT"||Q)return _O(D,X,Object.assign(Y,{code:"ECOMPROMISED"}));return X.updateDelay=1000,RY(D,$)}if(X.mtime.getTime()!==J.mtime.getTime())return _O(D,X,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let Z=gx.getMtime(X.mtimePrecision);$.fs.utimes(X.lockfilePath,Z,Z,(w)=>{let G=X.lastUpdate+$.stale<Date.now();if(X.released)return;if(w){if(w.code==="ENOENT"||G)return _O(D,X,Object.assign(w,{code:"ECOMPROMISED"}));return X.updateDelay=1000,RY(D,$)}X.mtime=Z,X.lastUpdate=Date.now(),X.updateDelay=null,RY(D,$)})})},X.updateDelay),X.updateTimeout.unref)X.updateTimeout.unref()}function _O(D,$,X){if($.released=!0,$.updateTimeout)clearTimeout($.updateTimeout);if(Z6[D]===$)delete Z6[D];$.options.onCompromised(X)}function GFD(D,$,X){$={stale:1e4,update:null,realpath:!0,retries:0,fs:fO,onCompromised:(Y)=>{throw Y},...$},$.retries=$.retries||0,$.retries=typeof $.retries==="number"?{retries:$.retries}:$.retries,$.stale=Math.max($.stale||0,2000),$.update=$.update==null?$.stale/2:$.update||0,$.update=Math.max(Math.min($.update,$.stale/2),1000),yO(D,$,(Y,J)=>{if(Y)return X(Y);let Q=ZFD.operation($.retries);Q.attempt(()=>{kO(J,$,(F,Z,w)=>{if(Q.retry(F))return;if(F)return X(Q.mainError());let G=Z6[J]={lockfilePath:H3(J,$),mtime:Z,mtimePrecision:w,options:$,lastUpdate:Date.now()};RY(J,$),X(null,(U)=>{if(G.released)return U&&U(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));dx(J,{...$,realpath:!1},U)})})})})}function dx(D,$,X){$={fs:fO,realpath:!0,...$},yO(D,$,(Y,J)=>{if(Y)return X(Y);let Q=Z6[J];if(!Q)return X(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));Q.updateTimeout&&clearTimeout(Q.updateTimeout),Q.released=!0,delete Z6[J],cx(J,$,X)})}function UFD(D,$,X){$={stale:1e4,realpath:!0,fs:fO,...$},$.stale=Math.max($.stale||0,2000),yO(D,$,(Y,J)=>{if(Y)return X(Y);$.fs.stat(H3(J,$),(Q,F)=>{if(Q)return Q.code==="ENOENT"?X(null,!1):X(Q);return X(null,!mx(F,$))})})}function OFD(){return Z6}wFD(()=>{for(let D in Z6){let $=Z6[D].options;try{$.fs.rmdirSync(H3(D,$))}catch(X){}}});qFD.lock=GFD;qFD.unlock=dx;qFD.check=UFD;qFD.getLocks=OFD});var ix=T((whD,nx)=>{var HFD=S0();function VFD(D){let $=["mkdir","realpath","stat","rmdir","utimes"],X={...D};return $.forEach((Y)=>{X[Y]=(...J)=>{let Q=J.pop(),F;try{F=D[`${Y}Sync`](...J)}catch(Z){return Q(Z)}Q(null,F)}}),X}function NFD(D){return(...$)=>new Promise((X,Y)=>{$.push((J,Q)=>{if(J)Y(J);else X(Q)}),D(...$)})}function LFD(D){return(...$)=>{let X,Y;if($.push((J,Q)=>{X=J,Y=Q}),D(...$),X)throw X;return Y}}function MFD(D){if(D={...D},D.fs=VFD(D.fs||HFD),typeof D.retries==="number"&&D.retries>0||D.retries&&typeof D.retries.retries==="number"&&D.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return D}nx.exports={toPromise:NFD,toSync:LFD,toSyncOptions:MFD}});var rx=T((GhD,n6)=>{var b9=lx(),{toPromise:jY,toSync:EY,toSyncOptions:bO}=ix();async function px(D,$){let X=await jY(b9.lock)(D,$);return jY(X)}function IFD(D,$){let X=EY(b9.lock)(D,bO($));return EY(X)}function AFD(D,$){return jY(b9.unlock)(D,$)}function RFD(D,$){return EY(b9.unlock)(D,bO($))}function jFD(D,$){return jY(b9.check)(D,$)}function EFD(D,$){return EY(b9.check)(D,bO($))}n6.exports=px;n6.exports.lock=px;n6.exports.unlock=AFD;n6.exports.lockSync=IFD;n6.exports.unlockSync=RFD;n6.exports.check=jFD;n6.exports.checkSync=EFD});var $S=T((ex)=>{Object.defineProperty(ex,"__esModule",{value:!0});ex.canStoreURLs=ex.FileUrlStorage=void 0;var ox=p("fs"),TFD=PFD(Ax()),ax=CFD(rx());function sx(D){if(typeof WeakMap!="function")return null;var $=new WeakMap,X=new WeakMap;return(sx=function(Y){return Y?X:$})(D)}function CFD(D,$){if(!$&&D&&D.__esModule)return D;if(D===null||typeof D!="object"&&typeof D!="function")return{default:D};var X=sx($);if(X&&X.has(D))return X.get(D);var Y={__proto__:null},J=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var Q in D)if(Q!=="default"&&{}.hasOwnProperty.call(D,Q)){var F=J?Object.getOwnPropertyDescriptor(D,Q):null;F&&(F.get||F.set)?Object.defineProperty(Y,Q,F):Y[Q]=D[Q]}return Y.default=D,X&&X.set(D,Y),Y}function PFD(D){return D&&D.__esModule?D:{default:D}}function N3(D){return N3=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function($){return typeof $}:function($){return $&&typeof Symbol=="function"&&$.constructor===Symbol&&$!==Symbol.prototype?"symbol":typeof $},N3(D)}function xFD(D,$){if(!(D instanceof $))throw TypeError("Cannot call a class as a function")}function tx(D,$){for(var X=0;X<$.length;X++){var Y=$[X];if(Y.enumerable=Y.enumerable||!1,Y.configurable=!0,"value"in Y)Y.writable=!0;Object.defineProperty(D,uFD(Y.key),Y)}}function SFD(D,$,X){if($)tx(D.prototype,$);if(X)tx(D,X);return Object.defineProperty(D,"prototype",{writable:!1}),D}function uFD(D){var $=vFD(D,"string");return N3($)=="symbol"?$:$+""}function vFD(D,$){if(N3(D)!="object"||!D)return D;var X=D[Symbol.toPrimitive];if(X!==void 0){var Y=X.call(D,$||"default");if(N3(Y)!="object")return Y;throw TypeError("@@toPrimitive must return a primitive value.")}return($==="string"?String:Number)(D)}var UhD=ex.canStoreURLs=!0,OhD=ex.FileUrlStorage=function(){function D($){xFD(this,D),this.path=$}return SFD(D,[{key:"findAllUploads",value:function(){var X=this;return new Promise(function(Y,J){X._getItems("tus::",function(Q,F){if(Q)J(Q);else Y(F)})})}},{key:"findUploadsByFingerprint",value:function(X){var Y=this;return new Promise(function(J,Q){Y._getItems("tus::".concat(X),function(F,Z){if(F)Q(F);else J(Z)})})}},{key:"removeUpload",value:function(X){var Y=this;return new Promise(function(J,Q){Y._removeItem(X,function(F){if(F)Q(F);else J()})})}},{key:"addUpload",value:function(X,Y){var J=this,Q=Math.round(Math.random()*1000000000000),F="tus::".concat(X,"::").concat(Q);return new Promise(function(Z,w){J._setItem(F,Y,function(G){if(G)w(G);else Z(F)})})}},{key:"_setItem",value:function(X,Y,J){var Q=this;ax.lock(this.path,this._lockfileOptions()).then(function(F){J=Q._releaseAndCb(F,J),Q._getData(function(Z,w){if(Z){J(Z);return}w[X]=Y,Q._writeData(w,function(G){return J(G)})})}).catch(J)}},{key:"_getItems",value:function(X,Y){this._getData(function(J,Q){if(J){Y(J);return}var F=Object.keys(Q).filter(function(Z){return Z.startsWith(X)}).map(function(Z){var w=Q[Z];return w.urlStorageKey=Z,w});Y(null,F)})}},{key:"_removeItem",value:function(X,Y){var J=this;ax.lock(this.path,this._lockfileOptions()).then(function(Q){Y=J._releaseAndCb(Q,Y),J._getData(function(F,Z){if(F){Y(F);return}delete Z[X],J._writeData(Z,function(w){return Y(w)})})}).catch(Y)}},{key:"_lockfileOptions",value:function(){return{realpath:!1,retries:{retries:5,minTimeout:20}}}},{key:"_releaseAndCb",value:function(X,Y){return function(J){if(J){X().then(function(){return Y(J)}).catch(function(Q){return Y((0,TFD.default)([J,Q]))});return}X().then(Y).catch(Y)}}},{key:"_writeData",value:function(X,Y){var J={encoding:"utf8",mode:432,flag:"w"};(0,ox.writeFile)(this.path,JSON.stringify(X),J,function(Q){return Y(Q)})}},{key:"_getData",value:function(X){(0,ox.readFile)(this.path,"utf8",function(Y,J){if(Y){if(Y.code==="ENOENT")X(null,{});else X(Y);return}try{J=!J.trim().length?{}:JSON.parse(J)}catch(Q){X(Q);return}X(null,J)})}}])}()});var CY=T((i6)=>{Object.defineProperty(i6,"__esModule",{value:!0});Object.defineProperty(i6,"DefaultHttpStack",{enumerable:!0,get:function(){return QS.default}});Object.defineProperty(i6,"DetailedError",{enumerable:!0,get:function(){return kFD.default}});Object.defineProperty(i6,"FileUrlStorage",{enumerable:!0,get:function(){return FS.FileUrlStorage}});Object.defineProperty(i6,"StreamSource",{enumerable:!0,get:function(){return gFD.default}});i6.Upload=void 0;Object.defineProperty(i6,"canStoreURLs",{enumerable:!0,get:function(){return FS.canStoreURLs}});i6.defaultOptions=void 0;Object.defineProperty(i6,"enableDebugLog",{enumerable:!0,get:function(){return fFD.enableDebugLog}});i6.isSupported=void 0;var kFD=Q8(bU()),fFD=hU(),yFD=Q8(rT()),hO=Q8(TC()),bFD=Q8(pC()),hFD=Q8(sC()),QS=Q8(BP()),gFD=Q8(aU()),FS=$S();function Q8(D){return D&&D.__esModule?D:{default:D}}function g9(D){return g9=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function($){return typeof $}:function($){return $&&typeof Symbol=="function"&&$.constructor===Symbol&&$!==Symbol.prototype?"symbol":typeof $},g9(D)}function mFD(D,$){if(!(D instanceof $))throw TypeError("Cannot call a class as a function")}function XS(D,$){for(var X=0;X<$.length;X++){var Y=$[X];if(Y.enumerable=Y.enumerable||!1,Y.configurable=!0,"value"in Y)Y.writable=!0;Object.defineProperty(D,wS(Y.key),Y)}}function cFD(D,$,X){if($)XS(D.prototype,$);if(X)XS(D,X);return Object.defineProperty(D,"prototype",{writable:!1}),D}function dFD(D,$,X){return $=TY($),lFD(D,ZS()?Reflect.construct($,X||[],TY(D).constructor):$.apply(D,X))}function lFD(D,$){if($&&(g9($)==="object"||typeof $==="function"))return $;else if($!==void 0)throw TypeError("Derived constructors may only return object or undefined");return nFD(D)}function nFD(D){if(D===void 0)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return D}function ZS(){try{var D=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch($){}return(ZS=function(){return!!D})()}function TY(D){return TY=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(X){return X.__proto__||Object.getPrototypeOf(X)},TY(D)}function iFD(D,$){if(typeof $!=="function"&&$!==null)throw TypeError("Super expression must either be null or a function");if(D.prototype=Object.create($&&$.prototype,{constructor:{value:D,writable:!0,configurable:!0}}),Object.defineProperty(D,"prototype",{writable:!1}),$)gO(D,$)}function gO(D,$){return gO=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(Y,J){return Y.__proto__=J,Y},gO(D,$)}function JS(D,$){var X=Object.keys(D);if(Object.getOwnPropertySymbols){var Y=Object.getOwnPropertySymbols(D);$&&(Y=Y.filter(function(J){return Object.getOwnPropertyDescriptor(D,J).enumerable})),X.push.apply(X,Y)}return X}function h9(D){for(var $=1;$<arguments.length;$++){var X=arguments[$]!=null?arguments[$]:{};$%2?JS(Object(X),!0).forEach(function(Y){pFD(D,Y,X[Y])}):Object.getOwnPropertyDescriptors?Object.defineProperties(D,Object.getOwnPropertyDescriptors(X)):JS(Object(X)).forEach(function(Y){Object.defineProperty(D,Y,Object.getOwnPropertyDescriptor(X,Y))})}return D}function pFD(D,$,X){if($=wS($),$ in D)Object.defineProperty(D,$,{value:X,enumerable:!0,configurable:!0,writable:!0});else D[$]=X;return D}function wS(D){var $=rFD(D,"string");return g9($)=="symbol"?$:$+""}function rFD(D,$){if(g9(D)!="object"||!D)return D;var X=D[Symbol.toPrimitive];if(X!==void 0){var Y=X.call(D,$||"default");if(g9(Y)!="object")return Y;throw TypeError("@@toPrimitive must return a primitive value.")}return($==="string"?String:Number)(D)}var YS=i6.defaultOptions=h9(h9({},hO.default.defaultOptions),{},{httpStack:new QS.default,fileReader:new bFD.default,urlStorage:new yFD.default,fingerprint:hFD.default}),zhD=i6.Upload=function(D){function $(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,Y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return mFD(this,$),Y=h9(h9({},YS),Y),dFD(this,$,[X,Y])}return iFD($,D),cFD($,null,[{key:"terminate",value:function(Y){var J=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return J=h9(h9({},YS),J),hO.default.terminate(Y,J)}}])}(hO.default),BhD=i6.isSupported=!0});var H$;var L3=o(()=>{H$={name:"@capgo/cli",type:"module",version:"7.88.0",description:"A CLI to upload to capgo servers",author:"Martin martin@capgo.app",license:"Apache 2.0",homepage:"https://github.com/Cap-go/CLI#readme",repository:{type:"git",url:"git+https://github.com/Cap-go/CLI.git"},bugs:{url:"https://github.com/Cap-go/CLI/issues"},keywords:["appflow alternative","ionic","capacitor","auto update","live update","capgo","cli","upload","capgo-cli","sdk","tanstack-intent"],exports:{".":{import:"./dist/index.js",require:"./dist/index.js"},"./sdk":{types:"./dist/src/sdk.d.ts",import:"./dist/src/sdk.js"}},main:"dist/index.js",types:"dist/src/index.d.ts",bin:{capgo:"dist/index.js"},files:["!skills/_artifacts","dist","skills"],engines:{npm:">=8.0.0",node:">=20.0.0"},scripts:{build:"tsc && bun build.mjs",dev:"NODE_ENV=development ncc build","no-debug":"node dist/index.js","dev-build":"SUPA_DB=development ncc build",pack:"pkg",types:"npx --yes supabase gen types typescript --project-id=xvwzpoazmxkqosrdewyv > src/types/supabase.types.ts",typecheck:"tsc --noEmit",lint:'eslint "src/**/*.ts" --fix',"check-posix-paths":"node test/check-posix-paths.js","generate-docs":"node dist/index.js generate-docs README.md","test:bundle":"bun test/test-bundle.mjs","test:functional":"bun test/test-functional.mjs","test:semver":"bun test/test-semver-validation.mjs","test:version-edge-cases":"bun test/test-version-validation.mjs","test:regex":"bun test/test-regex-validation.mjs","test:upload":"bun test/test-upload-validation.mjs","test:credentials":"bun test/test-credentials.mjs","test:credentials-validation":"bun test/test-credentials-validation.mjs","test:build-zip-filter":"bun test/test-build-zip-filter.mjs","test:checksum":"bun test/test-checksum-algorithm.mjs","test:esm-sdk":"node test/test-sdk-esm.mjs","test:mcp":"node test/test-mcp.mjs","test:version-detection":"node test/test-get-installed-version.mjs","test:version-detection:setup":"./test/fixtures/setup-test-projects.sh","test:platform-paths":"bun test/test-platform-paths.mjs","test:payload-split":"bun test/test-payload-split.mjs",test:"bun run test:bundle && bun run test:functional && bun run test:semver && bun run test:version-edge-cases && bun run test:regex && bun run test:upload && bun run test:credentials && bun run test:credentials-validation && bun run test:build-zip-filter && bun run test:checksum && bun run test:esm-sdk && bun run test:mcp && bun run test:version-detection && bun run test:platform-paths && bun run test:payload-split"},devDependencies:{"@antfu/eslint-config":"^7.0.0","@bradenmacdonald/s3-lite-client":"npm:@jsr/bradenmacdonald__s3-lite-client@0.9.4","@capacitor/cli":"^8.0.0","@capgo/find-package-manager":"^0.0.18","@clack/prompts":"^1.0.0","@modelcontextprotocol/sdk":"^1.25.3","@sauber/table":"npm:@jsr/sauber__table","@std/semver":"npm:@jsr/std__semver@1.0.8","@supabase/supabase-js":"^2.79.0","@tanstack/intent":"^0.0.23","@types/adm-zip":"^0.5.7","@types/jsonwebtoken":"^9.0.10","@types/node":"^25.0.0","@types/node-forge":"^1.3.14","@types/prettyjson":"^0.0.33","@types/react":"^18.3.28","@types/tmp":"^0.2.6","@vercel/ncc":"^0.38.4","adm-zip":"^0.5.16","ci-info":"^4.3.1",commander:"^14.0.2",eslint:"^9.38.0","git-format-staged":"4.0.1",husky:"^9.1.7","is-wsl":"^3.1.0",micromatch:"^4.0.8",open:"^11.0.0",partysocket:"^1.1.11",prettyjson:"^1.2.5",tmp:"^0.2.5","tus-js-client":"^4.3.1",typescript:"^5.9.3",ws:"^8.18.3",zod:"^4.3.6"},dependencies:{"@inkjs/ui":"^2.0.0",ink:"^5.2.1","ink-spinner":"^5.0.0",jsonwebtoken:"^9.0.3","node-forge":"^1.3.3",react:"^18.3.1"}}});async function PY(D){try{let X=`https://registry.npmjs.org/${encodeURIComponent(D.toLowerCase())}`,Y=await fetch(X,{headers:{accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"}});if(!Y.ok)return null;return(await Y.json())["dist-tags"]?.latest||null}catch{return null}}async function F0(){let D=await PY("@capgo/cli")??"",$=D?.split(".")[0];if(D!==H$.version)H.warning(`\uD83D\uDEA8 You are using @capgo/cli@${H$.version} it's not the latest version.
130
+ GFS4: `),console.error(D)};if(!M0[o0]){if(jO=global[o0]||[],ux(M0,jO),M0.close=function(D){function $(X,Y){return D.call(M0,X,function(J){if(!J)Sx();if(typeof Y==="function")Y.apply(this,arguments)})}return Object.defineProperty($,NY,{value:D}),$}(M0.close),M0.closeSync=function(D){function $(X){D.apply(M0,arguments),Sx()}return Object.defineProperty($,NY,{value:D}),$}(M0.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){$8(M0[o0]),p("assert").equal(M0[o0].length,0)})}var jO;if(!global[o0])ux(global,M0[o0]);CO.exports=EO(rQD(M0));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!M0.__patched)CO.exports=EO(M0),M0.__patched=!0;function EO(D){iQD(D),D.gracefulify=EO,D.createReadStream=N,D.createWriteStream=R;var $=D.readFile;D.readFile=X;function X(_,u,x){if(typeof u==="function")x=u,u=null;return h(_,u,x);function h(b,l,f,j){return $(b,l,function(S){if(S&&(S.code==="EMFILE"||S.code==="ENFILE"))k9([h,[b,l,f],S,j||Date.now(),Date.now()]);else if(typeof f==="function")f.apply(this,arguments)})}}var Y=D.writeFile;D.writeFile=J;function J(_,u,x,h){if(typeof x==="function")h=x,x=null;return b(_,u,x,h);function b(l,f,j,S,v){return Y(l,f,j,function(y){if(y&&(y.code==="EMFILE"||y.code==="ENFILE"))k9([b,[l,f,j,S],y,v||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}var Q=D.appendFile;if(Q)D.appendFile=F;function F(_,u,x,h){if(typeof x==="function")h=x,x=null;return b(_,u,x,h);function b(l,f,j,S,v){return Q(l,f,j,function(y){if(y&&(y.code==="EMFILE"||y.code==="ENFILE"))k9([b,[l,f,j,S],y,v||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}var Z=D.copyFile;if(Z)D.copyFile=w;function w(_,u,x,h){if(typeof x==="function")h=x,x=0;return b(_,u,x,h);function b(l,f,j,S,v){return Z(l,f,j,function(y){if(y&&(y.code==="EMFILE"||y.code==="ENFILE"))k9([b,[l,f,j,S],y,v||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}var G=D.readdir;D.readdir=O;var U=/^v[0-5]\./;function O(_,u,x){if(typeof u==="function")x=u,u=null;var h=U.test(process.version)?function(f,j,S,v){return G(f,b(f,j,S,v))}:function(f,j,S,v){return G(f,j,b(f,j,S,v))};return h(_,u,x);function b(l,f,j,S){return function(v,y){if(v&&(v.code==="EMFILE"||v.code==="ENFILE"))k9([h,[l,f,j],v,S||Date.now(),Date.now()]);else{if(y&&y.sort)y.sort();if(typeof j==="function")j.call(this,v,y)}}}}if(process.version.substr(0,4)==="v0.8"){var q=pQD(D);M=q.ReadStream,K=q.WriteStream}var z=D.ReadStream;if(z)M.prototype=Object.create(z.prototype),M.prototype.open=I;var B=D.WriteStream;if(B)K.prototype=Object.create(B.prototype),K.prototype.open=V;Object.defineProperty(D,"ReadStream",{get:function(){return M},set:function(_){M=_},enumerable:!0,configurable:!0}),Object.defineProperty(D,"WriteStream",{get:function(){return K},set:function(_){K=_},enumerable:!0,configurable:!0});var W=M;Object.defineProperty(D,"FileReadStream",{get:function(){return W},set:function(_){W=_},enumerable:!0,configurable:!0});var L=K;Object.defineProperty(D,"FileWriteStream",{get:function(){return L},set:function(_){L=_},enumerable:!0,configurable:!0});function M(_,u){if(this instanceof M)return z.apply(this,arguments),this;else return M.apply(Object.create(M.prototype),arguments)}function I(){var _=this;A(_.path,_.flags,_.mode,function(u,x){if(u){if(_.autoClose)_.destroy();_.emit("error",u)}else _.fd=x,_.emit("open",x),_.read()})}function K(_,u){if(this instanceof K)return B.apply(this,arguments),this;else return K.apply(Object.create(K.prototype),arguments)}function V(){var _=this;A(_.path,_.flags,_.mode,function(u,x){if(u)_.destroy(),_.emit("error",u);else _.fd=x,_.emit("open",x)})}function N(_,u){return new D.ReadStream(_,u)}function R(_,u){return new D.WriteStream(_,u)}var C=D.open;D.open=A;function A(_,u,x,h){if(typeof x==="function")h=x,x=null;return b(_,u,x,h);function b(l,f,j,S,v){return C(l,f,j,function(y,g){if(y&&(y.code==="EMFILE"||y.code==="ENFILE"))k9([b,[l,f,j,S],y,v||Date.now(),Date.now()]);else if(typeof S==="function")S.apply(this,arguments)})}}return D}function k9(D){$8("ENQUEUE",D[0].name,D[1]),M0[o0].push(D),TO()}var VY;function Sx(){var D=Date.now();for(var $=0;$<M0[o0].length;++$)if(M0[o0][$].length>2)M0[o0][$][3]=D,M0[o0][$][4]=D;TO()}function TO(){if(clearTimeout(VY),VY=void 0,M0[o0].length===0)return;var D=M0[o0].shift(),$=D[0],X=D[1],Y=D[2],J=D[3],Q=D[4];if(J===void 0)$8("RETRY",$.name,X),$.apply(null,X);else if(Date.now()-J>=60000){$8("TIMEOUT",$.name,X);var F=X.pop();if(typeof F==="function")F.call(null,Y)}else{var Z=Date.now()-Q,w=Math.max(Q-J,1),G=Math.min(w*1.2,100);if(Z>=G)$8("RETRY",$.name,X),$.apply(null,X.concat([J]));else M0[o0].push(D)}if(VY===void 0)VY=setTimeout(TO,0)}});var _x=T((YhD,vx)=>{function e1(D,$){if(typeof $==="boolean")$={forever:$};if(this._originalTimeouts=JSON.parse(JSON.stringify(D)),this._timeouts=D,this._options=$||{},this._maxRetryTime=$&&$.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}vx.exports=e1;e1.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};e1.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};e1.prototype.retry=function(D){if(this._timeout)clearTimeout(this._timeout);if(!D)return!1;var $=new Date().getTime();if(D&&$-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(D);var X=this._timeouts.shift();if(X===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),X=this._timeouts.shift();else return!1;var Y=this,J=setTimeout(function(){if(Y._attempts++,Y._operationTimeoutCb){if(Y._timeout=setTimeout(function(){Y._operationTimeoutCb(Y._attempts)},Y._operationTimeout),Y._options.unref)Y._timeout.unref()}Y._fn(Y._attempts)},X);if(this._options.unref)J.unref();return!0};e1.prototype.attempt=function(D,$){if(this._fn=D,$){if($.timeout)this._operationTimeout=$.timeout;if($.cb)this._operationTimeoutCb=$.cb}var X=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){X._operationTimeoutCb()},X._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};e1.prototype.try=function(D){console.log("Using RetryOperation.try() is deprecated"),this.attempt(D)};e1.prototype.start=function(D){console.log("Using RetryOperation.start() is deprecated"),this.attempt(D)};e1.prototype.start=e1.prototype.try;e1.prototype.errors=function(){return this._errors};e1.prototype.attempts=function(){return this._attempts};e1.prototype.mainError=function(){if(this._errors.length===0)return null;var D={},$=null,X=0;for(var Y=0;Y<this._errors.length;Y++){var J=this._errors[Y],Q=J.message,F=(D[Q]||0)+1;if(D[Q]=F,F>=X)$=J,X=F}return $}});var fx=T((tQD)=>{var aQD=_x();tQD.operation=function(D){var $=tQD.timeouts(D);return new aQD($,{forever:D&&D.forever,unref:D&&D.unref,maxRetryTime:D&&D.maxRetryTime})};tQD.timeouts=function(D){if(D instanceof Array)return[].concat(D);var $={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var X in D)$[X]=D[X];if($.minTimeout>$.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var Y=[];for(var J=0;J<$.retries;J++)Y.push(this.createTimeout(J,$));if(D&&D.forever&&!Y.length)Y.push(this.createTimeout(J,$));return Y.sort(function(Q,F){return Q-F}),Y};tQD.createTimeout=function(D,$){var X=$.randomize?Math.random()+1:1,Y=Math.round(X*$.minTimeout*Math.pow($.factor,D));return Y=Math.min(Y,$.maxTimeout),Y};tQD.wrap=function(D,$,X){if($ instanceof Array)X=$,$=null;if(!X){X=[];for(var Y in D)if(typeof D[Y]==="function")X.push(Y)}for(var J=0;J<X.length;J++){var Q=X[J],F=D[Q];D[Q]=function(w){var G=tQD.operation($),U=Array.prototype.slice.call(arguments,1),O=U.pop();U.push(function(q){if(G.retry(q))return;if(q)arguments[0]=G.mainError();O.apply(this,arguments)}),G.attempt(function(){w.apply(D,U)})}.bind(D,F),D[Q].options=$}}});var yx=T((FhD,LY)=>{LY.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")LY.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")LY.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var AY=T((ZhD,y9)=>{var K0=global.process,X8=function(D){return D&&typeof D==="object"&&typeof D.removeListener==="function"&&typeof D.emit==="function"&&typeof D.reallyExit==="function"&&typeof D.listeners==="function"&&typeof D.kill==="function"&&typeof D.pid==="number"&&typeof D.on==="function"};if(!X8(K0))y9.exports=function(){return function(){}};else{if(PO=p("assert"),J8=yx(),xO=/^win/i.test(K0.platform),f9=p("events"),typeof f9!=="function")f9=f9.EventEmitter;if(K0.__signal_exit_emitter__)g0=K0.__signal_exit_emitter__;else g0=K0.__signal_exit_emitter__=new f9,g0.count=0,g0.emitted={};if(!g0.infinite)g0.setMaxListeners(1/0),g0.infinite=!0;y9.exports=function(D,$){if(!X8(global.process))return function(){};if(PO.equal(typeof D,"function","a callback must be provided for exit handler"),Y8===!1)MY();var X="exit";if($&&$.alwaysLast)X="afterexit";var Y=function(){if(g0.removeListener(X,D),g0.listeners("exit").length===0&&g0.listeners("afterexit").length===0)B3()};return g0.on(X,D),Y},B3=function(){if(!Y8||!X8(global.process))return;Y8=!1,J8.forEach(function($){try{K0.removeListener($,W3[$])}catch(X){}}),K0.emit=K3,K0.reallyExit=IY,g0.count-=1},y9.exports.unload=B3,l6=function($,X,Y){if(g0.emitted[$])return;g0.emitted[$]=!0,g0.emit($,X,Y)},W3={},J8.forEach(function(D){W3[D]=function(){if(!X8(global.process))return;var X=K0.listeners(D);if(X.length===g0.count){if(B3(),l6("exit",null,D),l6("afterexit",null,D),xO&&D==="SIGHUP")D="SIGINT";K0.kill(K0.pid,D)}}}),y9.exports.signals=function(){return J8},Y8=!1,MY=function(){if(Y8||!X8(global.process))return;Y8=!0,g0.count+=1,J8=J8.filter(function($){try{return K0.on($,W3[$]),!0}catch(X){return!1}}),K0.emit=uO,K0.reallyExit=SO},y9.exports.load=MY,IY=K0.reallyExit,SO=function($){if(!X8(global.process))return;K0.exitCode=$||0,l6("exit",K0.exitCode,null),l6("afterexit",K0.exitCode,null),IY.call(K0,K0.exitCode)},K3=K0.emit,uO=function($,X){if($==="exit"&&X8(global.process)){if(X!==void 0)K0.exitCode=X;var Y=K3.apply(this,arguments);return l6("exit",K0.exitCode,null),l6("afterexit",K0.exitCode,null),Y}else return K3.apply(this,arguments)}}var PO,J8,xO,f9,g0,B3,l6,W3,Y8,MY,IY,SO,K3,uO});var hx=T((JFD,vO)=>{var bx=Symbol();function $FD(D,$,X){let Y=$[bx];if(Y)return $.stat(D,(Q,F)=>{if(Q)return X(Q);X(null,F.mtime,Y)});let J=new Date(Math.ceil(Date.now()/1000)*1000+5);$.utimes(D,J,J,(Q)=>{if(Q)return X(Q);$.stat(D,(F,Z)=>{if(F)return X(F);let w=Z.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty($,bx,{value:w}),X(null,Z.mtime,w)})})}function XFD(D){let $=Date.now();if(D==="s")$=Math.ceil($/1000)*1000;return new Date($)}JFD.probe=$FD;JFD.getMtime=XFD});var lx=T((qFD,V3)=>{var FFD=p("path"),fO=S0(),ZFD=fx(),wFD=AY(),gx=hx(),Z6={};function H3(D,$){return $.lockfilePath||`${D}.lock`}function yO(D,$,X){if(!$.realpath)return X(null,FFD.resolve(D));$.fs.realpath(D,X)}function kO(D,$,X){let Y=H3(D,$);$.fs.mkdir(Y,(J)=>{if(!J)return gx.probe(Y,$.fs,(Q,F,Z)=>{if(Q)return $.fs.rmdir(Y,()=>{}),X(Q);X(null,F,Z)});if(J.code!=="EEXIST")return X(J);if($.stale<=0)return X(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:D}));$.fs.stat(Y,(Q,F)=>{if(Q){if(Q.code==="ENOENT")return kO(D,{...$,stale:0},X);return X(Q)}if(!mx(F,$))return X(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:D}));cx(D,$,(Z)=>{if(Z)return X(Z);kO(D,{...$,stale:0},X)})})})}function mx(D,$){return D.mtime.getTime()<Date.now()-$.stale}function cx(D,$,X){$.fs.rmdir(H3(D,$),(Y)=>{if(Y&&Y.code!=="ENOENT")return X(Y);X()})}function RY(D,$){let X=Z6[D];if(X.updateTimeout)return;if(X.updateDelay=X.updateDelay||$.update,X.updateTimeout=setTimeout(()=>{X.updateTimeout=null,$.fs.stat(X.lockfilePath,(Y,J)=>{let Q=X.lastUpdate+$.stale<Date.now();if(Y){if(Y.code==="ENOENT"||Q)return _O(D,X,Object.assign(Y,{code:"ECOMPROMISED"}));return X.updateDelay=1000,RY(D,$)}if(X.mtime.getTime()!==J.mtime.getTime())return _O(D,X,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let Z=gx.getMtime(X.mtimePrecision);$.fs.utimes(X.lockfilePath,Z,Z,(w)=>{let G=X.lastUpdate+$.stale<Date.now();if(X.released)return;if(w){if(w.code==="ENOENT"||G)return _O(D,X,Object.assign(w,{code:"ECOMPROMISED"}));return X.updateDelay=1000,RY(D,$)}X.mtime=Z,X.lastUpdate=Date.now(),X.updateDelay=null,RY(D,$)})})},X.updateDelay),X.updateTimeout.unref)X.updateTimeout.unref()}function _O(D,$,X){if($.released=!0,$.updateTimeout)clearTimeout($.updateTimeout);if(Z6[D]===$)delete Z6[D];$.options.onCompromised(X)}function GFD(D,$,X){$={stale:1e4,update:null,realpath:!0,retries:0,fs:fO,onCompromised:(Y)=>{throw Y},...$},$.retries=$.retries||0,$.retries=typeof $.retries==="number"?{retries:$.retries}:$.retries,$.stale=Math.max($.stale||0,2000),$.update=$.update==null?$.stale/2:$.update||0,$.update=Math.max(Math.min($.update,$.stale/2),1000),yO(D,$,(Y,J)=>{if(Y)return X(Y);let Q=ZFD.operation($.retries);Q.attempt(()=>{kO(J,$,(F,Z,w)=>{if(Q.retry(F))return;if(F)return X(Q.mainError());let G=Z6[J]={lockfilePath:H3(J,$),mtime:Z,mtimePrecision:w,options:$,lastUpdate:Date.now()};RY(J,$),X(null,(U)=>{if(G.released)return U&&U(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));dx(J,{...$,realpath:!1},U)})})})})}function dx(D,$,X){$={fs:fO,realpath:!0,...$},yO(D,$,(Y,J)=>{if(Y)return X(Y);let Q=Z6[J];if(!Q)return X(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));Q.updateTimeout&&clearTimeout(Q.updateTimeout),Q.released=!0,delete Z6[J],cx(J,$,X)})}function UFD(D,$,X){$={stale:1e4,realpath:!0,fs:fO,...$},$.stale=Math.max($.stale||0,2000),yO(D,$,(Y,J)=>{if(Y)return X(Y);$.fs.stat(H3(J,$),(Q,F)=>{if(Q)return Q.code==="ENOENT"?X(null,!1):X(Q);return X(null,!mx(F,$))})})}function OFD(){return Z6}wFD(()=>{for(let D in Z6){let $=Z6[D].options;try{$.fs.rmdirSync(H3(D,$))}catch(X){}}});qFD.lock=GFD;qFD.unlock=dx;qFD.check=UFD;qFD.getLocks=OFD});var ix=T((whD,nx)=>{var HFD=S0();function VFD(D){let $=["mkdir","realpath","stat","rmdir","utimes"],X={...D};return $.forEach((Y)=>{X[Y]=(...J)=>{let Q=J.pop(),F;try{F=D[`${Y}Sync`](...J)}catch(Z){return Q(Z)}Q(null,F)}}),X}function NFD(D){return(...$)=>new Promise((X,Y)=>{$.push((J,Q)=>{if(J)Y(J);else X(Q)}),D(...$)})}function LFD(D){return(...$)=>{let X,Y;if($.push((J,Q)=>{X=J,Y=Q}),D(...$),X)throw X;return Y}}function MFD(D){if(D={...D},D.fs=VFD(D.fs||HFD),typeof D.retries==="number"&&D.retries>0||D.retries&&typeof D.retries.retries==="number"&&D.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return D}nx.exports={toPromise:NFD,toSync:LFD,toSyncOptions:MFD}});var rx=T((GhD,n6)=>{var b9=lx(),{toPromise:jY,toSync:EY,toSyncOptions:bO}=ix();async function px(D,$){let X=await jY(b9.lock)(D,$);return jY(X)}function IFD(D,$){let X=EY(b9.lock)(D,bO($));return EY(X)}function AFD(D,$){return jY(b9.unlock)(D,$)}function RFD(D,$){return EY(b9.unlock)(D,bO($))}function jFD(D,$){return jY(b9.check)(D,$)}function EFD(D,$){return EY(b9.check)(D,bO($))}n6.exports=px;n6.exports.lock=px;n6.exports.unlock=AFD;n6.exports.lockSync=IFD;n6.exports.unlockSync=RFD;n6.exports.check=jFD;n6.exports.checkSync=EFD});var $S=T((ex)=>{Object.defineProperty(ex,"__esModule",{value:!0});ex.canStoreURLs=ex.FileUrlStorage=void 0;var ox=p("fs"),TFD=PFD(Ax()),ax=CFD(rx());function sx(D){if(typeof WeakMap!="function")return null;var $=new WeakMap,X=new WeakMap;return(sx=function(Y){return Y?X:$})(D)}function CFD(D,$){if(!$&&D&&D.__esModule)return D;if(D===null||typeof D!="object"&&typeof D!="function")return{default:D};var X=sx($);if(X&&X.has(D))return X.get(D);var Y={__proto__:null},J=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var Q in D)if(Q!=="default"&&{}.hasOwnProperty.call(D,Q)){var F=J?Object.getOwnPropertyDescriptor(D,Q):null;F&&(F.get||F.set)?Object.defineProperty(Y,Q,F):Y[Q]=D[Q]}return Y.default=D,X&&X.set(D,Y),Y}function PFD(D){return D&&D.__esModule?D:{default:D}}function N3(D){return N3=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function($){return typeof $}:function($){return $&&typeof Symbol=="function"&&$.constructor===Symbol&&$!==Symbol.prototype?"symbol":typeof $},N3(D)}function xFD(D,$){if(!(D instanceof $))throw TypeError("Cannot call a class as a function")}function tx(D,$){for(var X=0;X<$.length;X++){var Y=$[X];if(Y.enumerable=Y.enumerable||!1,Y.configurable=!0,"value"in Y)Y.writable=!0;Object.defineProperty(D,uFD(Y.key),Y)}}function SFD(D,$,X){if($)tx(D.prototype,$);if(X)tx(D,X);return Object.defineProperty(D,"prototype",{writable:!1}),D}function uFD(D){var $=vFD(D,"string");return N3($)=="symbol"?$:$+""}function vFD(D,$){if(N3(D)!="object"||!D)return D;var X=D[Symbol.toPrimitive];if(X!==void 0){var Y=X.call(D,$||"default");if(N3(Y)!="object")return Y;throw TypeError("@@toPrimitive must return a primitive value.")}return($==="string"?String:Number)(D)}var UhD=ex.canStoreURLs=!0,OhD=ex.FileUrlStorage=function(){function D($){xFD(this,D),this.path=$}return SFD(D,[{key:"findAllUploads",value:function(){var X=this;return new Promise(function(Y,J){X._getItems("tus::",function(Q,F){if(Q)J(Q);else Y(F)})})}},{key:"findUploadsByFingerprint",value:function(X){var Y=this;return new Promise(function(J,Q){Y._getItems("tus::".concat(X),function(F,Z){if(F)Q(F);else J(Z)})})}},{key:"removeUpload",value:function(X){var Y=this;return new Promise(function(J,Q){Y._removeItem(X,function(F){if(F)Q(F);else J()})})}},{key:"addUpload",value:function(X,Y){var J=this,Q=Math.round(Math.random()*1000000000000),F="tus::".concat(X,"::").concat(Q);return new Promise(function(Z,w){J._setItem(F,Y,function(G){if(G)w(G);else Z(F)})})}},{key:"_setItem",value:function(X,Y,J){var Q=this;ax.lock(this.path,this._lockfileOptions()).then(function(F){J=Q._releaseAndCb(F,J),Q._getData(function(Z,w){if(Z){J(Z);return}w[X]=Y,Q._writeData(w,function(G){return J(G)})})}).catch(J)}},{key:"_getItems",value:function(X,Y){this._getData(function(J,Q){if(J){Y(J);return}var F=Object.keys(Q).filter(function(Z){return Z.startsWith(X)}).map(function(Z){var w=Q[Z];return w.urlStorageKey=Z,w});Y(null,F)})}},{key:"_removeItem",value:function(X,Y){var J=this;ax.lock(this.path,this._lockfileOptions()).then(function(Q){Y=J._releaseAndCb(Q,Y),J._getData(function(F,Z){if(F){Y(F);return}delete Z[X],J._writeData(Z,function(w){return Y(w)})})}).catch(Y)}},{key:"_lockfileOptions",value:function(){return{realpath:!1,retries:{retries:5,minTimeout:20}}}},{key:"_releaseAndCb",value:function(X,Y){return function(J){if(J){X().then(function(){return Y(J)}).catch(function(Q){return Y((0,TFD.default)([J,Q]))});return}X().then(Y).catch(Y)}}},{key:"_writeData",value:function(X,Y){var J={encoding:"utf8",mode:432,flag:"w"};(0,ox.writeFile)(this.path,JSON.stringify(X),J,function(Q){return Y(Q)})}},{key:"_getData",value:function(X){(0,ox.readFile)(this.path,"utf8",function(Y,J){if(Y){if(Y.code==="ENOENT")X(null,{});else X(Y);return}try{J=!J.trim().length?{}:JSON.parse(J)}catch(Q){X(Q);return}X(null,J)})}}])}()});var CY=T((i6)=>{Object.defineProperty(i6,"__esModule",{value:!0});Object.defineProperty(i6,"DefaultHttpStack",{enumerable:!0,get:function(){return QS.default}});Object.defineProperty(i6,"DetailedError",{enumerable:!0,get:function(){return kFD.default}});Object.defineProperty(i6,"FileUrlStorage",{enumerable:!0,get:function(){return FS.FileUrlStorage}});Object.defineProperty(i6,"StreamSource",{enumerable:!0,get:function(){return gFD.default}});i6.Upload=void 0;Object.defineProperty(i6,"canStoreURLs",{enumerable:!0,get:function(){return FS.canStoreURLs}});i6.defaultOptions=void 0;Object.defineProperty(i6,"enableDebugLog",{enumerable:!0,get:function(){return fFD.enableDebugLog}});i6.isSupported=void 0;var kFD=Q8(bU()),fFD=hU(),yFD=Q8(rT()),hO=Q8(TC()),bFD=Q8(pC()),hFD=Q8(sC()),QS=Q8(BP()),gFD=Q8(aU()),FS=$S();function Q8(D){return D&&D.__esModule?D:{default:D}}function g9(D){return g9=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function($){return typeof $}:function($){return $&&typeof Symbol=="function"&&$.constructor===Symbol&&$!==Symbol.prototype?"symbol":typeof $},g9(D)}function mFD(D,$){if(!(D instanceof $))throw TypeError("Cannot call a class as a function")}function XS(D,$){for(var X=0;X<$.length;X++){var Y=$[X];if(Y.enumerable=Y.enumerable||!1,Y.configurable=!0,"value"in Y)Y.writable=!0;Object.defineProperty(D,wS(Y.key),Y)}}function cFD(D,$,X){if($)XS(D.prototype,$);if(X)XS(D,X);return Object.defineProperty(D,"prototype",{writable:!1}),D}function dFD(D,$,X){return $=TY($),lFD(D,ZS()?Reflect.construct($,X||[],TY(D).constructor):$.apply(D,X))}function lFD(D,$){if($&&(g9($)==="object"||typeof $==="function"))return $;else if($!==void 0)throw TypeError("Derived constructors may only return object or undefined");return nFD(D)}function nFD(D){if(D===void 0)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return D}function ZS(){try{var D=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch($){}return(ZS=function(){return!!D})()}function TY(D){return TY=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(X){return X.__proto__||Object.getPrototypeOf(X)},TY(D)}function iFD(D,$){if(typeof $!=="function"&&$!==null)throw TypeError("Super expression must either be null or a function");if(D.prototype=Object.create($&&$.prototype,{constructor:{value:D,writable:!0,configurable:!0}}),Object.defineProperty(D,"prototype",{writable:!1}),$)gO(D,$)}function gO(D,$){return gO=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(Y,J){return Y.__proto__=J,Y},gO(D,$)}function JS(D,$){var X=Object.keys(D);if(Object.getOwnPropertySymbols){var Y=Object.getOwnPropertySymbols(D);$&&(Y=Y.filter(function(J){return Object.getOwnPropertyDescriptor(D,J).enumerable})),X.push.apply(X,Y)}return X}function h9(D){for(var $=1;$<arguments.length;$++){var X=arguments[$]!=null?arguments[$]:{};$%2?JS(Object(X),!0).forEach(function(Y){pFD(D,Y,X[Y])}):Object.getOwnPropertyDescriptors?Object.defineProperties(D,Object.getOwnPropertyDescriptors(X)):JS(Object(X)).forEach(function(Y){Object.defineProperty(D,Y,Object.getOwnPropertyDescriptor(X,Y))})}return D}function pFD(D,$,X){if($=wS($),$ in D)Object.defineProperty(D,$,{value:X,enumerable:!0,configurable:!0,writable:!0});else D[$]=X;return D}function wS(D){var $=rFD(D,"string");return g9($)=="symbol"?$:$+""}function rFD(D,$){if(g9(D)!="object"||!D)return D;var X=D[Symbol.toPrimitive];if(X!==void 0){var Y=X.call(D,$||"default");if(g9(Y)!="object")return Y;throw TypeError("@@toPrimitive must return a primitive value.")}return($==="string"?String:Number)(D)}var YS=i6.defaultOptions=h9(h9({},hO.default.defaultOptions),{},{httpStack:new QS.default,fileReader:new bFD.default,urlStorage:new yFD.default,fingerprint:hFD.default}),zhD=i6.Upload=function(D){function $(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,Y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return mFD(this,$),Y=h9(h9({},YS),Y),dFD(this,$,[X,Y])}return iFD($,D),cFD($,null,[{key:"terminate",value:function(Y){var J=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return J=h9(h9({},YS),J),hO.default.terminate(Y,J)}}])}(hO.default),BhD=i6.isSupported=!0});var H$;var L3=o(()=>{H$={name:"@capgo/cli",type:"module",version:"7.88.2",description:"A CLI to upload to capgo servers",author:"Martin martin@capgo.app",license:"Apache 2.0",homepage:"https://github.com/Cap-go/CLI#readme",repository:{type:"git",url:"git+https://github.com/Cap-go/CLI.git"},bugs:{url:"https://github.com/Cap-go/CLI/issues"},keywords:["appflow alternative","ionic","capacitor","auto update","live update","capgo","cli","upload","capgo-cli","sdk","tanstack-intent"],exports:{".":{import:"./dist/index.js",require:"./dist/index.js"},"./sdk":{types:"./dist/src/sdk.d.ts",import:"./dist/src/sdk.js"}},main:"dist/index.js",types:"dist/src/index.d.ts",bin:{capgo:"dist/index.js"},files:["!skills/_artifacts","dist","skills"],engines:{npm:">=8.0.0",node:">=20.0.0"},scripts:{build:"tsc && bun build.mjs",dev:"NODE_ENV=development ncc build","no-debug":"node dist/index.js","dev-build":"SUPA_DB=development ncc build",pack:"pkg",types:"npx --yes supabase gen types typescript --project-id=xvwzpoazmxkqosrdewyv > src/types/supabase.types.ts",typecheck:"tsc --noEmit",lint:'eslint "src/**/*.ts" --fix',"check-posix-paths":"node test/check-posix-paths.js","generate-docs":"node dist/index.js generate-docs README.md","test:bundle":"bun test/test-bundle.mjs","test:functional":"bun test/test-functional.mjs","test:semver":"bun test/test-semver-validation.mjs","test:version-edge-cases":"bun test/test-version-validation.mjs","test:regex":"bun test/test-regex-validation.mjs","test:upload":"bun test/test-upload-validation.mjs","test:credentials":"bun test/test-credentials.mjs","test:credentials-validation":"bun test/test-credentials-validation.mjs","test:build-zip-filter":"bun test/test-build-zip-filter.mjs","test:checksum":"bun test/test-checksum-algorithm.mjs","test:esm-sdk":"node test/test-sdk-esm.mjs","test:mcp":"node test/test-mcp.mjs","test:version-detection":"node test/test-get-installed-version.mjs","test:version-detection:setup":"./test/fixtures/setup-test-projects.sh","test:platform-paths":"bun test/test-platform-paths.mjs","test:payload-split":"bun test/test-payload-split.mjs",test:"bun run test:bundle && bun run test:functional && bun run test:semver && bun run test:version-edge-cases && bun run test:regex && bun run test:upload && bun run test:credentials && bun run test:credentials-validation && bun run test:build-zip-filter && bun run test:checksum && bun run test:esm-sdk && bun run test:mcp && bun run test:version-detection && bun run test:platform-paths && bun run test:payload-split"},devDependencies:{"@antfu/eslint-config":"^7.0.0","@bradenmacdonald/s3-lite-client":"npm:@jsr/bradenmacdonald__s3-lite-client@0.9.5","@capacitor/cli":"^8.0.0","@capgo/find-package-manager":"^0.0.18","@clack/prompts":"^1.0.0","@modelcontextprotocol/sdk":"^1.25.3","@sauber/table":"npm:@jsr/sauber__table","@std/semver":"npm:@jsr/std__semver@1.0.8","@supabase/supabase-js":"^2.79.0","@tanstack/intent":"^0.0.23","@types/adm-zip":"^0.5.7","@types/jsonwebtoken":"^9.0.10","@types/node":"^25.0.0","@types/node-forge":"^1.3.14","@types/prettyjson":"^0.0.33","@types/react":"^18.3.28","@types/tmp":"^0.2.6","@vercel/ncc":"^0.38.4","adm-zip":"^0.5.16","ci-info":"^4.3.1",commander:"^14.0.2",eslint:"^9.38.0","git-format-staged":"4.0.1",husky:"^9.1.7","is-wsl":"^3.1.0",micromatch:"^4.0.8",open:"^11.0.0",partysocket:"^1.1.11",prettyjson:"^1.2.5",tmp:"^0.2.5","tus-js-client":"^4.3.1",typescript:"^5.9.3",ws:"^8.18.3",zod:"^4.3.6"},dependencies:{"@inkjs/ui":"^2.0.0",ink:"^5.2.1","ink-spinner":"^5.0.0",jsonwebtoken:"^9.0.3","node-forge":"^1.3.3",react:"^18.3.1"}}});async function PY(D){try{let X=`https://registry.npmjs.org/${encodeURIComponent(D.toLowerCase())}`,Y=await fetch(X,{headers:{accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"}});if(!Y.ok)return null;return(await Y.json())["dist-tags"]?.latest||null}catch{return null}}async function F0(){let D=await PY("@capgo/cli")??"",$=D?.split(".")[0];if(D!==H$.version)H.warning(`\uD83D\uDEA8 You are using @capgo/cli@${H$.version} it's not the latest version.
131
131
  Please use @capgo/cli@${D}" or @capgo/cli@${$} to keep up to date with the latest features and bug fixes.`)}var O1=o(()=>{vD();L3()});async function qS(D,$,X,Y,J,Q="✅"){await AD(X,{channel:D,event:Y,icon:Q,user_id:$,...J?{tags:{"app-id":J}}:{},notify:!1})}var zS=o(()=>{vD();D6();O1();kD()});import{Buffer as BS}from"node:buffer";import{createHash as aFD}from"node:crypto";function sFD(D){let $=4294967295;for(let X=0;X<D.length;X++){let Y=D[X];$=tFD[($^Y)&255]^$>>>8}return $=$^4294967295,($>>>0).toString(16).padStart(8,"0")}async function p6(D,$="sha256"){let X=BS.isBuffer(D)?D:BS.from(D);if($==="crc32")return sFD(X);let Y=aFD($);return Y.update(X),Y.digest("hex")}var tFD;var M3=o(()=>{tFD=(()=>{let D=[];for(let $=0;$<256;$++){let X=$;for(let Y=0;Y<8;Y++)X=X&1?3988292384^X>>>1:X>>>1;D[$]=X}return D})()});var KS=T((xhD,WS)=>{var m9=1000,c9=m9*60,d9=c9*60,F8=d9*24,eFD=F8*7,DZD=F8*365.25;WS.exports=function(D,$){$=$||{};var X=typeof D;if(X==="string"&&D.length>0)return $ZD(D);else if(X==="number"&&isFinite(D))return $.long?JZD(D):XZD(D);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(D))};function $ZD(D){if(D=String(D),D.length>100)return;var $=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(D);if(!$)return;var X=parseFloat($[1]),Y=($[2]||"ms").toLowerCase();switch(Y){case"years":case"year":case"yrs":case"yr":case"y":return X*DZD;case"weeks":case"week":case"w":return X*eFD;case"days":case"day":case"d":return X*F8;case"hours":case"hour":case"hrs":case"hr":case"h":return X*d9;case"minutes":case"minute":case"mins":case"min":case"m":return X*c9;case"seconds":case"second":case"secs":case"sec":case"s":return X*m9;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return X;default:return}}function XZD(D){var $=Math.abs(D);if($>=F8)return Math.round(D/F8)+"d";if($>=d9)return Math.round(D/d9)+"h";if($>=c9)return Math.round(D/c9)+"m";if($>=m9)return Math.round(D/m9)+"s";return D+"ms"}function JZD(D){var $=Math.abs(D);if($>=F8)return xY(D,$,F8,"day");if($>=d9)return xY(D,$,d9,"hour");if($>=c9)return xY(D,$,c9,"minute");if($>=m9)return xY(D,$,m9,"second");return D+" ms"}function xY(D,$,X,Y){var J=$>=X*1.5;return Math.round(D/X)+" "+Y+(J?"s":"")}});var mO=T((ShD,HS)=>{function YZD(D){X.debug=X,X.default=X,X.coerce=w,X.disable=F,X.enable=J,X.enabled=Z,X.humanize=KS(),X.destroy=G,Object.keys(D).forEach((U)=>{X[U]=D[U]}),X.names=[],X.skips=[],X.formatters={};function $(U){let O=0;for(let q=0;q<U.length;q++)O=(O<<5)-O+U.charCodeAt(q),O|=0;return X.colors[Math.abs(O)%X.colors.length]}X.selectColor=$;function X(U){let O,q=null,z,B;function W(...L){if(!W.enabled)return;let M=W,I=Number(new Date),K=I-(O||I);if(M.diff=K,M.prev=O,M.curr=I,O=I,L[0]=X.coerce(L[0]),typeof L[0]!=="string")L.unshift("%O");let V=0;L[0]=L[0].replace(/%([a-zA-Z%])/g,(R,C)=>{if(R==="%%")return"%";V++;let A=X.formatters[C];if(typeof A==="function"){let _=L[V];R=A.call(M,_),L.splice(V,1),V--}return R}),X.formatArgs.call(M,L),(M.log||X.log).apply(M,L)}if(W.namespace=U,W.useColors=X.useColors(),W.color=X.selectColor(U),W.extend=Y,W.destroy=X.destroy,Object.defineProperty(W,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(q!==null)return q;if(z!==X.namespaces)z=X.namespaces,B=X.enabled(U);return B},set:(L)=>{q=L}}),typeof X.init==="function")X.init(W);return W}function Y(U,O){let q=X(this.namespace+(typeof O>"u"?":":O)+U);return q.log=this.log,q}function J(U){X.save(U),X.namespaces=U,X.names=[],X.skips=[];let O=(typeof U==="string"?U:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let q of O)if(q[0]==="-")X.skips.push(q.slice(1));else X.names.push(q)}function Q(U,O){let q=0,z=0,B=-1,W=0;while(q<U.length)if(z<O.length&&(O[z]===U[q]||O[z]==="*"))if(O[z]==="*")B=z,W=q,z++;else q++,z++;else if(B!==-1)z=B+1,W++,q=W;else return!1;while(z<O.length&&O[z]==="*")z++;return z===O.length}function F(){let U=[...X.names,...X.skips.map((O)=>"-"+O)].join(",");return X.enable(""),U}function Z(U){for(let O of X.skips)if(Q(U,O))return!1;for(let O of X.names)if(Q(U,O))return!0;return!1}function w(U){if(U instanceof Error)return U.stack||U.message;return U}function G(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return X.enable(X.load()),X}HS.exports=YZD});var NS=T((VS,SY)=>{VS.formatArgs=FZD;VS.save=ZZD;VS.load=wZD;VS.useColors=QZD;VS.storage=GZD();VS.destroy=(()=>{let D=!1;return()=>{if(!D)D=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();VS.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function QZD(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let D;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(D=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(D[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function FZD(D){if(D[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+D[0]+(this.useColors?"%c ":" ")+"+"+SY.exports.humanize(this.diff),!this.useColors)return;let $="color: "+this.color;D.splice(1,0,$,"color: inherit");let X=0,Y=0;D[0].replace(/%[a-zA-Z%]/g,(J)=>{if(J==="%%")return;if(X++,J==="%c")Y=X}),D.splice(Y,0,$)}VS.log=console.debug||console.log||(()=>{});function ZZD(D){try{if(D)VS.storage.setItem("debug",D);else VS.storage.removeItem("debug")}catch($){}}function wZD(){let D;try{D=VS.storage.getItem("debug")||VS.storage.getItem("DEBUG")}catch($){}if(!D&&typeof process<"u"&&"env"in process)D=process.env.DEBUG;return D}function GZD(){try{return localStorage}catch(D){}}SY.exports=mO()(VS);var{formatters:UZD}=SY.exports;UZD.j=function(D){try{return JSON.stringify(D)}catch($){return"[UnexpectedJSONParseError]: "+$.message}}});var MS=T((vhD,LS)=>{LS.exports=(D,$=process.argv)=>{let X=D.startsWith("-")?"":D.length===1?"-":"--",Y=$.indexOf(X+D),J=$.indexOf("--");return Y!==-1&&(J===-1||Y<J)}});var RS=T((_hD,AS)=>{var VZD=p("os"),IS=p("tty"),D$=MS(),{env:n0}=process,r6;if(D$("no-color")||D$("no-colors")||D$("color=false")||D$("color=never"))r6=0;else if(D$("color")||D$("colors")||D$("color=true")||D$("color=always"))r6=1;if("FORCE_COLOR"in n0)if(n0.FORCE_COLOR==="true")r6=1;else if(n0.FORCE_COLOR==="false")r6=0;else r6=n0.FORCE_COLOR.length===0?1:Math.min(parseInt(n0.FORCE_COLOR,10),3);function cO(D){if(D===0)return!1;return{level:D,hasBasic:!0,has256:D>=2,has16m:D>=3}}function dO(D,$){if(r6===0)return 0;if(D$("color=16m")||D$("color=full")||D$("color=truecolor"))return 3;if(D$("color=256"))return 2;if(D&&!$&&r6===void 0)return 0;let X=r6||0;if(n0.TERM==="dumb")return X;if(process.platform==="win32"){let Y=VZD.release().split(".");if(Number(Y[0])>=10&&Number(Y[2])>=10586)return Number(Y[2])>=14931?3:2;return 1}if("CI"in n0){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((Y)=>(Y in n0))||n0.CI_NAME==="codeship")return 1;return X}if("TEAMCITY_VERSION"in n0)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(n0.TEAMCITY_VERSION)?1:0;if(n0.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in n0){let Y=parseInt((n0.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(n0.TERM_PROGRAM){case"iTerm.app":return Y>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(n0.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(n0.TERM))return 1;if("COLORTERM"in n0)return 1;return X}function NZD(D){let $=dO(D,D&&D.isTTY);return cO($)}AS.exports={supportsColor:NZD,stdout:cO(dO(!0,IS.isatty(1))),stderr:cO(dO(!0,IS.isatty(2)))}});var CS=T((ES,vY)=>{var LZD=p("tty"),uY=p("util");ES.init=TZD;ES.log=RZD;ES.formatArgs=IZD;ES.save=jZD;ES.load=EZD;ES.useColors=MZD;ES.destroy=uY.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ES.colors=[6,2,3,4,5,1];try{let D=RS();if(D&&(D.stderr||D).level>=2)ES.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(D){}ES.inspectOpts=Object.keys(process.env).filter((D)=>{return/^debug_/i.test(D)}).reduce((D,$)=>{let X=$.substring(6).toLowerCase().replace(/_([a-z])/g,(J,Q)=>{return Q.toUpperCase()}),Y=process.env[$];if(/^(yes|on|true|enabled)$/i.test(Y))Y=!0;else if(/^(no|off|false|disabled)$/i.test(Y))Y=!1;else if(Y==="null")Y=null;else Y=Number(Y);return D[X]=Y,D},{});function MZD(){return"colors"in ES.inspectOpts?Boolean(ES.inspectOpts.colors):LZD.isatty(process.stderr.fd)}function IZD(D){let{namespace:$,useColors:X}=this;if(X){let Y=this.color,J="\x1B[3"+(Y<8?Y:"8;5;"+Y),Q=` ${J};1m${$} \x1B[0m`;D[0]=Q+D[0].split(`
132
132
  `).join(`
133
133
  `+Q),D.push(J+"m+"+vY.exports.humanize(this.diff)+"\x1B[0m")}else D[0]=AZD()+$+" "+D[0]}function AZD(){if(ES.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function RZD(...D){return process.stderr.write(uY.formatWithOptions(ES.inspectOpts,...D)+`
@@ -465,7 +465,7 @@ const partysocket = new PartySocket({
465
465
  \uD83D\uDD12 Security: Credentials are never stored on Capgo servers`),F.info(" They are used only during build and deleted after"),F.info(` Build outputs can optionally be uploaded for time-limited download links
466
466
  `),Q)F.info(`API host: ${G}`);let q={};if($.buildCertificateBase64)q.BUILD_CERTIFICATE_BASE64=$.buildCertificateBase64;if($.p12Password)q.P12_PASSWORD=$.p12Password;if($.appleKeyId)q.APPLE_KEY_ID=$.appleKeyId;if($.appleIssuerId)q.APPLE_ISSUER_ID=$.appleIssuerId;if($.appleKeyContent)q.APPLE_KEY_CONTENT=$.appleKeyContent;if($.appStoreConnectTeamId)q.APP_STORE_CONNECT_TEAM_ID=$.appStoreConnectTeamId;if($.iosScheme)q.CAPGO_IOS_SCHEME=$.iosScheme;if($.iosTarget)q.CAPGO_IOS_TARGET=$.iosTarget;if($.iosDistribution)q.CAPGO_IOS_DISTRIBUTION=$.iosDistribution;if($.iosProvisioningProfile&&$.iosProvisioningProfile.length>0){let u=De($.iosProvisioningProfile,Je($.path||MM()));q.CAPGO_IOS_PROVISIONING_MAP=JSON.stringify(u)}if($.iosProvisioningMap)q.CAPGO_IOS_PROVISIONING_MAP=$.iosProvisioningMap;if($.androidKeystoreFile)q.ANDROID_KEYSTORE_FILE=$.androidKeystoreFile;if($.keystoreKeyAlias)q.KEYSTORE_KEY_ALIAS=$.keystoreKeyAlias;let z=!!$.keystoreKeyPassword,B=!!$.keystoreStorePassword;if(z&&!B)q.KEYSTORE_KEY_PASSWORD=$.keystoreKeyPassword,q.KEYSTORE_STORE_PASSWORD=$.keystoreKeyPassword;else if(!z&&B)q.KEYSTORE_KEY_PASSWORD=$.keystoreStorePassword,q.KEYSTORE_STORE_PASSWORD=$.keystoreStorePassword;else if(z&&B)q.KEYSTORE_KEY_PASSWORD=$.keystoreKeyPassword,q.KEYSTORE_STORE_PASSWORD=$.keystoreStorePassword;if(typeof $.androidFlavor==="string"){let u=$.androidFlavor.trim();if(u)q.CAPGO_ANDROID_FLAVOR=u}if($.playConfigJson)q.PLAY_CONFIG_JSON=$.playConfigJson;if($.outputUpload!==void 0)q.BUILD_OUTPUT_UPLOAD_ENABLED=O7($.outputUpload)?"true":"false";if($.outputRetention)q.BUILD_OUTPUT_RETENTION_SECONDS=String(bw($.outputRetention));if($.skipBuildNumberBump!==void 0)q.SKIP_BUILD_NUMBER_BUMP=O7($.skipBuildNumberBump)?"true":"false";let W=await ls(D,$.platform,Object.keys(q).length>0?q:void 0);if($.playstoreUpload===!1&&W)delete W.PLAY_CONFIG_JSON,F.info("ℹ️ --no-playstore-upload specified, Play Store upload disabled for this build");let L=I2(w?.config,$.platform);if(W&&L)if($.platform==="ios")W.CAPGO_IOS_SOURCE_DIR=L,W.CAPGO_IOS_APP_DIR=L,W.CAPGO_IOS_PROJECT_DIR=L,W.IOS_PROJECT_DIR=L;else W.CAPGO_ANDROID_SOURCE_DIR=L,W.CAPGO_ANDROID_APP_DIR=L,W.CAPGO_ANDROID_PROJECT_DIR=L,W.ANDROID_PROJECT_DIR=L;if(!W)throw F.error("❌ No credentials found for this app and platform"),F.error(""),F.error("You must provide credentials via:"),F.error(" 1. CLI arguments (--apple-key-id, --p12-password, etc.)"),F.error(" 2. Environment variables (APPLE_KEY_ID, P12_PASSWORD, etc.)"),F.error(" 3. Saved credentials file:"),F.error(` npx @capgo/cli build credentials save --appId ${D} --platform ${$.platform}`),F.error(""),F.error("Documentation:"),F.error(" https://capgo.app/docs/cli/cloud-build/credentials/"),Error("No credentials found. Please provide credentials before building.");let M=[];if($.platform==="ios"){let u=W.CAPGO_IOS_DISTRIBUTION,x=["app_store","ad_hoc"];if(u&&!x.includes(u))M.push(`Invalid CAPGO_IOS_DISTRIBUTION value: '${u}'. Must be one of: ${x.join(", ")}`);let h=u&&x.includes(u)?u:"app_store";if(!u)F.info("ℹ️ --ios-distribution not specified, defaulting to app_store");if(W.CAPGO_IOS_DISTRIBUTION=h,!W.BUILD_CERTIFICATE_BASE64)M.push("BUILD_CERTIFICATE_BASE64 (or --build-certificate-base64)");if(!W.P12_PASSWORD)F.warn("⚠️ P12_PASSWORD not provided - assuming certificate has no password"),F.warn(" If your certificate requires a password, provide it with --p12-password");if(!!(W.BUILD_PROVISION_PROFILE_BASE64||W.APPLE_PROFILE_NAME)&&!W.CAPGO_IOS_PROVISIONING_MAP)throw F.error("❌ Legacy provisioning profile format detected. Run:"),F.error(" npx @capgo/cli build credentials migrate --platform ios"),F.error(""),F.error(" This will convert your existing provisioning profile to the new multi-target format."),Error("Legacy provisioning profile format detected. Run: npx @capgo/cli build credentials migrate --platform ios");if(!W.CAPGO_IOS_PROVISIONING_MAP)M.push('CAPGO_IOS_PROVISIONING_MAP (use --ios-provisioning-profile or save via "build credentials save")');if(h==="app_store"){let l=!!W.APPLE_KEY_ID,f=!!W.APPLE_ISSUER_ID,j=!!W.APPLE_KEY_CONTENT,S=l||f||j;if(!(l&&f&&j))if(S){let y=[];if(!l)y.push("APPLE_KEY_ID (or --apple-key-id)");if(!f)y.push("APPLE_ISSUER_ID (or --apple-issuer-id)");if(!j)y.push("APPLE_KEY_CONTENT (or --apple-key-content)");M.push(`Incomplete App Store Connect API key - missing: ${y.join(", ")}`)}else if(W.BUILD_OUTPUT_UPLOAD_ENABLED!=="true")M.push("APPLE_KEY_ID/APPLE_ISSUER_ID/APPLE_KEY_CONTENT or BUILD_OUTPUT_UPLOAD_ENABLED=true (or --output-upload) (build has no output destination - enable either TestFlight upload or Capgo download link)");else if(W.SKIP_BUILD_NUMBER_BUMP!=="true")M.push("APPLE_KEY_ID/APPLE_ISSUER_ID/APPLE_KEY_CONTENT or --skip-build-number-bump (App Store Connect API key not provided - build numbers cannot be auto-incremented without it)");else F.warn("⚠️ App Store Connect API key not provided - build will succeed but cannot auto-upload to TestFlight")}else if(h==="ad_hoc")F.info("\uD83D\uDCE6 Ad-hoc distribution mode: App Store Connect API key not required"),F.info(" Build number will use timestamp-based fallback");if(!W.APP_STORE_CONNECT_TEAM_ID)M.push("APP_STORE_CONNECT_TEAM_ID (or --app-store-connect-team-id)")}else if($.platform==="android"){if(!W.ANDROID_KEYSTORE_FILE)M.push("ANDROID_KEYSTORE_FILE (or --android-keystore-file)");if(!W.KEYSTORE_KEY_ALIAS)M.push("KEYSTORE_KEY_ALIAS (or --keystore-key-alias)");if(!W.KEYSTORE_KEY_PASSWORD&&!W.KEYSTORE_STORE_PASSWORD)M.push("KEYSTORE_KEY_PASSWORD or KEYSTORE_STORE_PASSWORD (at least one password required)");if(!W.PLAY_CONFIG_JSON)if(W.BUILD_OUTPUT_UPLOAD_ENABLED!=="true")M.push("PLAY_CONFIG_JSON or BUILD_OUTPUT_UPLOAD_ENABLED=true (build has no output destination - enable either Play Store upload or Capgo download link)");else F.warn("⚠️ PLAY_CONFIG_JSON not provided - build will succeed but cannot auto-upload to Play Store")}if(M.length>0){F.error(`❌ Missing required credentials for ${$.platform}:`),F.error("");for(let u of M)F.error(` • ${u}`);throw F.error(""),F.error("Provide credentials via:"),F.error(` 1. CLI arguments: npx @capgo/cli build request --platform ${$.platform} ${$.platform==="ios"?'--apple-key-id "..." --apple-issuer-id "..." --apple-key-content "..."':'--android-keystore-file "..." --keystore-key-alias "..."'}`),F.error(` 2. Environment variables: ${$.platform==="ios"?'export APPLE_KEY_ID="..." APPLE_ISSUER_ID="..." APPLE_KEY_CONTENT="..."':'export ANDROID_KEYSTORE_FILE="..." KEYSTORE_KEY_ALIAS="..."'}`),F.error(` 3. Saved credentials: npx @capgo/cli build credentials save --platform ${$.platform} ...`),F.error(""),F.error("Documentation:"),F.error(` https://capgo.app/docs/cli/cloud-build/${$.platform}/`),Error(`Missing required credentials for ${$.platform}: ${M.join(", ")}`)}if(!$.buildMode)F.info("ℹ️ --build-mode not specified, defaulting to release");if(!W.BUILD_OUTPUT_UPLOAD_ENABLED)F.info("ℹ️ --output-upload not specified, defaulting to false (no Capgo download link)");if(!W.BUILD_OUTPUT_RETENTION_SECONDS)F.info(`ℹ️ --output-retention not specified, defaulting to ${m8}s (1 hour)`);if(!W.SKIP_BUILD_NUMBER_BUMP)F.info("ℹ️ --skip-build-number-bump not specified, build number will be auto-incremented (default)");let{buildOptions:I,buildCredentials:K}=HxD(W,$.platform,$.buildMode||"release",H$.version),V={app_id:D,platform:$.platform,build_mode:$.buildMode||"release",build_options:I,build_credentials:K};if(F.info("✓ Using credentials (merged from CLI args, env vars, and saved file)"),Q){let u=Object.keys(K);F.info(`Credentials provided: ${u.join(", ")}`),F.info(`Build options: platform=${I.platform}, mode=${I.buildMode}, cliVersion=${I.cliVersion}`)}F.info("Requesting build from Capgo...");let N=3,R=await UxD(`${G}/build/request`,{method:"POST",headers:{"Content-Type":"application/json",authorization:$.apikey},body:JSON.stringify(V)},N,F);if(!R.ok){let u=await R.text();throw Error(`Failed to request build: ${R.status} - ${u}`)}let C=await R.json();if(F.success(`Build job created: ${C.job_id}`),F.info(`Status: ${C.status}`),Q)F.info(`Upload URL: ${C.upload_url}`),F.info(`Upload expires: ${C.upload_expires_at}`);await AD($.apikey,{channel:"native-builder",event:"Build requested",icon:"\uD83C\uDFD7️",user_id:O,tags:{"app-id":D,platform:$.platform},notify:!1}).catch();let A=s$(ZxD(),`capgo-build-${Date.now()}`);await JxD(A,{recursive:!0});let _=s$(A,`${Xe(Z)}.zip`);try{F.info(`Zipping ${$.platform} project from ${Z}...`),await WxD(Z,_,$.platform,w?.config);let x=((await QxD(_)).size/1024/1024).toFixed(2);if(F.success(`Created zip: ${_} (${x} MB)`),F.info("Uploading to builder..."),Q)F.info(`Upload endpoint: ${C.upload_url}`),F.info(`File size: ${x} MB`),F.info(`Job ID: ${C.job_id}`);let h=$xD(_);F.uploadProgress(0),await new Promise((r,YD)=>{let P=new mw.Upload(h,{endpoint:C.upload_url,chunkSize:5242880,metadata:{filename:Xe(_),filetype:"application/zip"},headers:{authorization:$.apikey},onBeforeRequest(E){if(Q){F.info(`[TUS] ${E.getMethod()} ${E.getURL()}`);let n=E.getHeader("authorization");F.info(`[TUS] Authorization header present: ${!!n}`)}},onAfterResponse(E,n){if(Q){F.info(`[TUS] Response status: ${n.getStatus()}`);let k=n.getHeader("upload-offset"),zD=n.getHeader("tus-resumable");F.info(`[TUS] Upload-Offset: ${k}, Tus-Resumable: ${zD}`)}},onError(E){if(F.error(`Upload error: ${E.message}`),E instanceof mw.DetailedError){let n=E.originalResponse?.getBody(),k=E.originalResponse?.getStatus(),zD=E.originalRequest?.getURL();if(Q)F.error(`[TUS] Request URL: ${zD}`),F.error(`[TUS] Response status: ${k}`),F.error(`[TUS] Response body: ${n}`);let t="Unknown error";try{let BD=JSON.parse(n||'{"error": "unknown error"}');t=BD.status||BD.error||BD.message||"unknown error"}catch{t=n||E.message}YD(Error(`TUS upload failed: ${t}`))}else YD(Error(`TUS upload failed: ${E.message||E.toString()}`))},onProgress(E,n){let k=Number.parseFloat((E/n*100).toFixed(2));F.uploadProgress(k)},onSuccess(){if(F.uploadProgress(100),Q)F.success("TUS upload completed successfully");r()}});if(Q)F.info("[TUS] Starting upload...");P.start()}),F.info("Starting build job...");let b=await fetch(`${G}/build/start/${C.job_id}`,{method:"POST",headers:{"Content-Type":"application/json",authorization:$.apikey},body:JSON.stringify({app_id:D})});if(!b.ok){let r=await b.text();throw Error(`Failed to start build: ${b.status} - ${r}`)}let l=await b.json();F.success("Build started!"),F.info("Streaming build logs...");let f=new AbortController,j=!1,S=async()=>{if(j)return;j=!0;let r=new AbortController,YD=setTimeout(()=>r.abort(),4000);try{await fetch(`${G}/build/cancel/${C.job_id}`,{method:"POST",headers:{"Content-Type":"application/json",authorization:$.apikey},body:JSON.stringify({app_id:D}),signal:r.signal})}catch{}finally{clearTimeout(YD)}},v=async()=>{try{if(j)LM.exit(1);F.warn("Canceling build... (press Ctrl+C again to force quit)"),await S(),f.abort()}catch{}};LM.on("SIGINT",v);let y,g=!1,d=async()=>{try{let r=await fetch(`${G}/build/status?job_id=${encodeURIComponent(C.job_id)}&app_id=${encodeURIComponent(D)}&platform=${$.platform}`,{headers:{authorization:$.apikey}});if(!r.ok)return null;let YD=await r.json(),P=YD.status?.toLowerCase?.()??"";if(g)F.info(`Build status: ${P||YD.status}`);if(gw.has(P))return P;return null}catch{return null}},a=null;try{a=await qxD(X,Q,l.logs_url,l.logs_token,d,f.signal,()=>{g=!0},X&&!Y?void 0:F)}finally{LM.removeListener("SIGINT",v)}if(a){if(y=a,gw.has(a))await d().catch(()=>{})}else y=await zxD(G,C.job_id,D,$.platform,$.apikey,X,g,f.signal,F);if(y==="succeeded")F.success("Build completed successfully!");else if(y==="failed")F.error("Build failed");else F.warn(`Build finished with status: ${y}`);let m=((Date.now()-J)/1000).toFixed(2);return await AD($.apikey,{channel:"native-builder",event:y==="succeeded"?"Build succeeded":"Build failed",icon:y==="succeeded"?"✅":"❌",user_id:O,tags:{"app-id":D,platform:$.platform,status:y||"unknown",time:m},notify:!1}).catch(),{success:y==="succeeded",jobId:C.job_id,uploadUrl:C.upload_url,status:y||l.status||C.status}}finally{await YxD(A,{recursive:!0,force:!0})}}catch(Z){let w=Z instanceof Error?Z.message:String(Z);return F.error(w),{success:!1,error:w}}}vD();X6();O1();kD();async function VxD(D,$,X,Y){for await(let J of D){if(!Y)H.warn(`Removing ${J.name} created on ${$7(J.created_at)}`);await Mw($,X,J.name)}}function NxD(D,$,X){let Y=[];for(let J of D??[]){let Q=eD(J.name);if(lG(Q,$)&&S4(Q,X))Y.push(J)}return Y}async function Ue(D,$,X=!1){if(!X)VD("Cleanup versions in Capgo");await F0(),$.apikey=$.apikey||WD();let{bundle:Y,keep:J=4}=$,Q=$.force||!1,F=$.ignoreChannel||!1,Z=await ID();if(D=mD(D,Z?.config),!$.apikey){if(!X)H.error("Missing API key, you need to provide an API key to delete your app");throw Error("Missing API key")}if(!D){if(!X)H.error("Missing argument, you need to provide a appid, or be in a capacitor project");throw Error("Missing appId")}let w=await jD($.apikey,$.supaHost,$.supaAnon);if(await m0(w,D,X),await xD(w,$.apikey,["write","all"]),await u0(w,$.apikey,D,3,X,!0),!X)H.info("Querying all available versions in Capgo");let G=await Iw(w,D),U=await Lt(w,D);if(!X)H.info(`Total active versions in Capgo: ${G?.length??0}`);if(!G?.length){if(!X)H.error("No versions found, aborting cleanup");throw Error("No versions found")}if(Y){let z=eD(Y),B=P7(z,"major");if(!X)H.info(`Querying available versions in Capgo between ${q$(z)} and ${q$(B)}`);if(G=NxD(G,z,B),!X)H.info(`Active versions in Capgo between ${q$(z)} and ${q$(B)}: ${G?.length??0}`)}let O=[],q=0;for(let z of G){let B=U.find((W)=>W===z.id);if(q<J||B&&!F)z.keep=B?"✅ (Linked to channel)":"✅",q+=1;else z.keep="❌",O.push(z)}if(!O.length){if(!X)H.warn("Nothing to be removed, aborting removal...");return{removed:0,kept:q}}if(!X)Nt(G);if(!Q)if(!X){let z=await d0({message:"Do you want to continue removing the versions specified?"});if(bD(z)||!z)throw H.warn("Not confirmed, aborting removal..."),Error("Cleanup cancelled by user")}else throw Error("Cleanup requires force=true in SDK mode to prevent accidental deletions");if(!X)H.success("You have confirmed removal, removing versions now");if(await VxD(O,w,D,X),!X)ND("Done ✅");return{removed:O.length,kept:q}}vD();D6();kD();async function Oe(D,$,X=!1){if(!X)VD("Check compatibility");let Y={...$,apikey:$.apikey||WD()},J=D?void 0:await ID(),Q=mD(D,J?.config),F=Y.channel;if(!F){if(!X)H.error("Missing argument, you need to provide a channel");throw Error("Missing channel")}if(!Y.apikey){if(!X)H.error("Missing API key, you need to provide an API key to access Capgo Cloud metadata");throw Error("Missing API key")}if(!Q){if(!X)H.error("Missing argument, you need to provide an appId, or be in a capacitor project");throw Error("Missing appId")}let Z=await jD(Y.apikey,Y.supaHost,Y.supaAnon);await m0(Z,Q,X),await xD(Z,Y.apikey,["write","all","read","upload"]),await u0(Z,Y.apikey,Q,1,X,!0);let w=await Lw(Z,Q,F,Y.packageJson,Y.nodeModules),G=w.finalCompatibility.some((U)=>!M4(U));if(!X){let U=new R0;U.headers=["Package","Local","Remote","Status","Details"],U.theme=R0.roundTheme,U.rows=[];let O=Y.text?"OK":"✅",q=Y.text?"FAIL":"❌";for(let z of w.finalCompatibility){let{name:B,localVersion:W,remoteVersion:L}=z,M=k8(z),I=M.compatible?O:q;U.rows.push([B,W||"-",L||"-",I,M.message])}if(H.success("Compatibility Check Results"),H.info(U.toString()),G){let z=w.finalCompatibility.filter((B)=>!M4(B)).length;H.warn(`
467
467
  ${z} package(s) are incompatible with channel "${F}"`),H.warn("An app store update may be required for these changes to take effect.")}else H.success(`
468
- All packages are compatible with channel "${F}"`)}return{finalCompatibility:w.finalCompatibility,hasIncompatible:G,resolvedAppId:Q,channel:F}}vD();X6();import{existsSync as RM,readFileSync as Ne,writeFileSync as RxD}from"node:fs";import{cwd as jxD}from"node:process";import{Buffer as C6}from"node:buffer";import{constants as LxD,createCipheriv as MxD,createDecipheriv as IxD,generateKeyPairSync as AxD,privateEncrypt as IM,publicDecrypt as AM,randomBytes as qe}from"node:crypto";var ze="aes-128-cbc",P6="base64",cw="hex",q7=LxD.RSA_PKCS1_PADDING;function dw(D){let $=qe(16),X=qe(16),Y=$.toString(P6),J=IM({key:D,padding:q7},X).toString(P6);return{sessionKey:X,ivSessionKey:`${Y}:${J}`}}function z7(D,$,X){let[Y]=X.split(":"),J=C6.from(Y,P6),Q=MxD(ze,$,J);return Q.setAutoPadding(!0),C6.concat([Q.update(D),Q.final()])}function Be(D,$,X){let[Y,J]=$.split(":"),Q=AM({key:X,padding:q7},C6.from(J,P6)),F=C6.from(Y,P6),Z=IxD(ze,Q,F);return Z.setAutoPadding(!0),C6.concat([Z.update(D),Z.final()])}function B7(D,$){return IM({key:$,padding:q7},C6.from(D,P6)).toString(P6)}function W7(D,$){return IM({key:$,padding:q7},C6.from(D,cw)).toString(cw)}function We(D,$){return AM({key:$,padding:q7},C6.from(D,P6)).toString(P6)}function Ke(D,$){return AM({key:$,padding:q7},C6.from(D,cw)).toString(cw)}function He(){let{publicKey:D,privateKey:$}=AxD("rsa",{modulusLength:2048});return{publicKey:D.export({type:"pkcs1",format:"pem"}),privateKey:$.export({type:"pkcs1",format:"pem"})}}function Ve(D){if(!D)return"";return D.replace(/-----BEGIN RSA PUBLIC KEY-----/g,"").replace(/-----END RSA PUBLIC KEY-----/g,"").replace(/\n/g,"").replace(/\r/g,"").replace(/ /g,"").substring(0,20)}O1();M3();kD();var ExD="5.30.0",TxD="6.30.0",CxD="7.30.0";function PxD(D,$){let X=D.key||R6,Y=$.config.plugins?.CapacitorUpdater?.publicKey;if(RM(X))Y=Ne(X,"utf8");else if(!Y&&D.keyData)Y=D.keyData;return{publicKey:Y,fallbackKeyPath:X}}async function Le(D,$,X,Y=!1){if(!Y)VD("Decrypt zip file");try{if(await F0(),!RM(D)){let O=`Zip not found at the path ${D}`;if(!Y)H.error(O);throw Error(O)}let J=await ID();if(!X.key&&!RM(R6)&&!J.config.plugins?.CapacitorUpdater?.publicKey){let O=`Public Key not found at the path ${R6} or in ${J.path}`;if(!Y)H.error(O);throw Error(O)}let{publicKey:Q,fallbackKeyPath:F}=PxD(X,J);if(!Q){let O=`Cannot find public key ${F} or as keyData option or in ${J.path}`;if(!Y)H.error(O);throw Error(O)}let Z=Ne(D),w=Be(Z,$,X.keyData??Q),G=`${D}_decrypted.zip`;if(RxD(G,w),!Y)H.info(`Decrypted zip file at ${G}`);let U;if(X.checksum){let O=await p6(w,"sha256"),q=e0(jxD()),z=await y1("@capgo/capacitor-updater",q,X.packageJson),B=!1,W;try{W=z?eD(z):void 0}catch{W=void 0}if(W)B=!w$(W,ExD,TxD,CxD);if(!Y)H.info(`Decrypting checksum with ${B?"V3":"V2"} (based on updater version ${z||"unknown"})`);let L=B?Ke(X.checksum,X.keyData??Q):We(X.checksum,X.keyData??Q);if(U=O===L,!U){let M=`Checksum does not match ${O} !== ${L}`;if(!Y)H.error(M);throw Error(M)}if(!Y)H.info("Checksum matches")}if(!Y)ND("✅ done");return{outputPath:G,checksumMatches:U}}catch(J){if(!Y)H.error(`Error decrypting zip file ${s(J)}`);throw J instanceof Error?J:Error(String(J))}}vD();kD();async function Me(D,$,X,Y=!1){if(!Y)VD("Delete bundle");X.apikey=X.apikey||WD();let J=await ID();if($=mD($,J?.config),!X.apikey){if(!Y)H.error("Missing API key, you need to provide an API key to upload your bundle");throw Error("Missing API key")}if(!$){if(!Y)H.error("Missing argument, you need to provide a appId, or be in a capacitor project");throw Error("Missing appId")}if(!D){if(!Y)H.error("Missing argument, you need to provide a bundleId, or be in a capacitor project");throw Error("Missing bundleId")}let Q=await jD(X.apikey,X.supaHost,X.supaAnon);if(await m0(Q,$,Y),await xD(Q,X.apikey,["write","all"]),await u0(Q,X.apikey,$,3,Y,!0),!Y)H.info(`Deleting bundle ${$}@${D} from Capgo`),H.info("Keep in mind that you will not be able to reuse this bundle version, it's gone forever");await Mw(Q,$,D);let F=await l0(Q,$);if(await AD(X.apikey,{channel:"app",event:"Bundle Deleted",icon:"\uD83D\uDDD1️",user_id:F,tags:{"app-id":$,bundle:D},notify:!1,notifyConsole:!0}).catch(()=>{}),!Y)H.success(`Bundle ${$}@${D} deleted in Capgo`),ND("Done");return!0}vD();X6();import{existsSync as jM,readFileSync as Ie,writeFileSync as xxD}from"node:fs";import{cwd as SxD}from"node:process";O1();kD();var uxD="5.30.0",vxD="6.30.0",_xD="7.30.0";function R2(D){console.error(s(D))}async function Ae(D,$,X,Y=!1){let{json:J}=X,Q=!J&&!Y;if(Q)VD("Encryption"),await F0();try{let F=await ID(),Z=!!F.config.plugins?.CapacitorUpdater?.privateKey,w=!!F.config.plugins?.CapacitorUpdater?.publicKey;if(Z&&Q)H.warning("There is still a privateKey in the config");if(!jM(D)){let N=`Zip not found at the path ${D}`;if(!Y)if(J)R2({error:"zip_not_found"});else H.error(`Error: ${N}`);throw Error(N)}if(!w){if(!Y)if(J)R2({error:"missing_public_key"});else H.warning("Warning: Missing Public Key in config");throw Error("Missing public key in config")}let G=X.key||i1,U=X.keyData||"";if(!jM(G)&&!U){if(!Y)if(J)R2({error:"missing_key"});else H.warning(`Cannot find a private key at ${G} or as a keyData option`),H.error("Error: Missing key");throw Error("Missing private key")}else if(jM(G))U=Ie(G,"utf8");if(U&&!U.startsWith("-----BEGIN RSA PRIVATE KEY-----")){if(!Y)if(J)R2({error:"invalid_private_key"});else H.error("The private key provided is not a valid RSA Private key");throw Error("Invalid private key format")}let O=Ie(D),{sessionKey:q,ivSessionKey:z}=dw(U),B=z7(O,q,z),W=e0(SxD()),L=await y1("@capgo/capacitor-updater",W,X.packageJson),M=!1,I;try{I=L?eD(L):void 0}catch{I=void 0}if(I)M=!w$(I,uxD,vxD,_xD);let K=M?W7($,U):B7($,U);if(Q)H.info(`Encrypting checksum with ${M?"V3":"V2"} (based on updater version ${L||"unknown"})`);let V=`${D}_encrypted.zip`;if(xxD(V,B),!Y)if(J)console.log(JSON.stringify({checksum:K,filename:V,ivSessionKey:z},null,2));else H.success(`Encoded Checksum: ${K}`),H.success(`ivSessionKey: ${z}`),H.success(`Encrypted zip saved at ${V}`),ND("Done ✅");return{checksum:K,filename:V,ivSessionKey:z}}catch(F){if(!Y)if(X.json)R2(F);else H.error(`Error encrypting zip file ${s(F)}`);throw F instanceof Error?F:Error(String(F))}}import{randomUUID as YvD}from"node:crypto";import{existsSync as YG,readFileSync as QvD}from"node:fs";import{cwd as YI,stdin as FvD,stdout as ZvD}from"node:process";class EM extends TransformStream{outChunkSize;constructor(D){let $=new Uint8Array(D),X=0;super({transform(Y,J){let Q=0;while(Q<Y.length){let F=D-X,Z=Math.min(F,Y.length-Q);if($.set(Y.subarray(Q,Q+Z),X),Q+=Z,X+=Z,X===D)J.enqueue($),$=new Uint8Array(D),X=0}},flush(Y){if(X>0)Y.enqueue($.subarray(0,X))}}),this.outChunkSize=D}}function E4(D){return D=D.trim(),D=D.replace(/<!--[\s\S]*?-->/g,""),$();function $(){return{declaration:X(),root:Y()}}function X(){if(!w(/^<\?xml\s*/))return;let q={attributes:{}};while(!(G()||U("?>"))){let z=Q();if(!z)return q;q.attributes[z.name]=z.value}return w(/\?>\s*/),q}function Y(){let O=w(/^<([\w-:.]+)\s*/);if(!O)return;let q={name:O[1],attributes:{},children:[]};while(!(G()||U(">")||U("?>")||U("/>"))){let B=Q();if(!B)return q;q.attributes[B.name]=B.value}if(w(/^\s*\/>\s*/))return q;w(/\??>\s*/),q.content=J();let z;while(z=Y())q.children.push(z);return w(/^<\/[\w-:.]+>\s*/),q}function J(){let O=w(/^([^<]*)/);if(O)return Z(O[1]);return""}function Q(){let O=w(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/);if(!O)return;return{name:O[1],value:Z(F(O[2]))}}function F(O){return O.replace(/^['"]|['"]$/g,"")}function Z(O){return O.replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}function w(O){let q=D.match(O);if(!q)return;return D=D.slice(q[0].length),q}function G(){return D.length===0}function U(O){return D.startsWith(O)}}class x6 extends Error{}class R1 extends x6{}class lw extends x6{}class TM extends x6{bucketName;constructor(D){super(`Invalid bucket name: ${D}`),this.bucketName=D}}class S6 extends x6{objectName;constructor(D){super(`Invalid object name: ${D}`),this.objectName=D}}class c8 extends x6{constructor(){super("accessKey is required")}}class j2 extends x6{constructor(){super("secretKey is required")}}class nw extends x6{constructor(){super("expirySeconds cannot be less than 1 second or more than 7 days")}}class T4 extends x6{statusCode;code;key;bucketName;resource;region;constructor(D,$,X,Y={}){super(X),this.statusCode=D,this.code=$,this.key=Y.key,this.bucketName=Y.bucketName,this.resource=Y.resource,this.region=Y.region}}async function Re(D){try{let X=E4(await D.text()).root;if(X?.name!=="Error")throw Error("Invalid root, expected <Error>");let Y=X.children.find((G)=>G.name==="Code")?.content??"UnknownErrorCode",J=X.children.find((G)=>G.name==="Message")?.content??"The error message could not be determined.",Q=X.children.find((G)=>G.name==="Key")?.content,F=X.children.find((G)=>G.name==="BucketName")?.content,Z=X.children.find((G)=>G.name==="Resource")?.content,w=X.children.find((G)=>G.name==="Region")?.content;return new T4(D.status,Y,J,{key:Q,bucketName:F,resource:Z,region:w})}catch{return new T4(D.status,"UnrecognizedError",`Error: Unexpected response code ${D.status} ${D.statusText}. Unable to parse response as XML.`)}}function je(D){if(typeof D!=="number"||isNaN(D))return!1;return D>=1&&D<=65535}function Ee(D){if(typeof D!=="string")return!1;if(D.length<3||D.length>63)return!1;if(D.includes(".."))return!1;if(D.match(/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/))return!1;if(D.match(/^[a-z0-9][a-z0-9.-]+[a-z0-9]$/))return!0;return!1}function C4(D){if(!kxD(D))return!1;if(D.length===0)return!1;return!0}function kxD(D){if(typeof D!=="string")return!1;if(D.length>1024)return!1;return!0}function E2(D){return Array.from(D).map(($)=>$.toString(16).padStart(2,"0")).join("")}function d8(D=""){let $={'"':"","&quot;":"","&#34;":"","&QUOT;":"","&#x00022":""};return D.replace(/^("|&quot;|&#34;)|("|&quot;|&#34;)$/g,(X)=>$[X])}function PM(D){return D.get("x-amz-version-id")??null}function l8(D){let $=D.toISOString();return $.slice(0,4)+$.slice(5,7)+$.slice(8,13)+$.slice(14,16)+$.slice(17,19)+"Z"}function xM(D){return l8(D).slice(0,8)}function SM(D,$){return`${xM($)}/${D}/s3/aws4_request`}async function iw(D){if(!(D instanceof Uint8Array))D=new TextEncoder().encode(D);return E2(new Uint8Array(await crypto.subtle.digest("SHA-256",D)))}var fxD=["x-amz-server-side-encryption-customer-algorithm","x-amz-server-side-encryption-customer-key","x-amz-server-side-encryption-customer-key-MD5"];class uM extends WritableStream{getResult;constructor({client:D,bucketName:$,objectName:X,partSize:Y,metadata:J}){let Q,F=1,Z,w=[],G,U=[];super({start(){},async write(O,q){let B=F++;try{if(B==1&&O.length<Y){let M=await D.makeRequest({method:"PUT",headers:new Headers({...J,"Content-Length":String(O.length)}),bucketName:$,objectName:X,payload:O});Q={etag:d8(M.headers.get("etag")??void 0),versionId:PM(M.headers)};return}if(B===1)Z=(await yxD({client:D,bucketName:$,objectName:X,metadata:J})).uploadId;let W={"Content-Length":String(O.length)};for(let M of fxD){let I=J[M];if(I)W[M]=I}let L=D.makeRequest({method:"PUT",query:{partNumber:B.toString(),uploadId:Z},headers:new Headers(W),bucketName:$,objectName:X,payload:O}).then((M)=>{let I=M.headers.get("etag")??"";if(I)I=I.replace(/^"/,"").replace(/"$/,"");return w.push({part:B,etag:I}),M});U.push(L.catch((M)=>{if(!G)G=M}))}catch(W){throw W}},async close(){if(Q);else if(Z){if(await Promise.all(U),G)throw G;w.sort((O,q)=>O.part>q.part?1:-1),Q=await bxD({client:D,bucketName:$,objectName:X,uploadId:Z,etags:w})}else throw Error("Stream was closed without uploading any data.")}});this.getResult=()=>{if(Q===void 0)throw Error("Result is not ready. await the stream first.");return Q}}}async function yxD(D){let X=new Headers(D.metadata),Y="uploads",Q=await(await D.client.makeRequest({method:"POST",bucketName:D.bucketName,objectName:D.objectName,query:"uploads",headers:X,returnBody:!0})).text(),F=E4(Q).root;if(!F||F.name!=="InitiateMultipartUploadResult")throw Error(`Unexpected response: ${Q}`);let Z=F.children.find((w)=>w.name==="UploadId")?.content;if(!Z)throw Error(`Unable to get UploadId from response: ${Q}`);return{uploadId:Z}}async function bxD({client:D,bucketName:$,objectName:X,uploadId:Y,etags:J}){let Q=`
468
+ All packages are compatible with channel "${F}"`)}return{finalCompatibility:w.finalCompatibility,hasIncompatible:G,resolvedAppId:Q,channel:F}}vD();X6();import{existsSync as RM,readFileSync as Ne,writeFileSync as RxD}from"node:fs";import{cwd as jxD}from"node:process";import{Buffer as C6}from"node:buffer";import{constants as LxD,createCipheriv as MxD,createDecipheriv as IxD,generateKeyPairSync as AxD,privateEncrypt as IM,publicDecrypt as AM,randomBytes as qe}from"node:crypto";var ze="aes-128-cbc",P6="base64",cw="hex",q7=LxD.RSA_PKCS1_PADDING;function dw(D){let $=qe(16),X=qe(16),Y=$.toString(P6),J=IM({key:D,padding:q7},X).toString(P6);return{sessionKey:X,ivSessionKey:`${Y}:${J}`}}function z7(D,$,X){let[Y]=X.split(":"),J=C6.from(Y,P6),Q=MxD(ze,$,J);return Q.setAutoPadding(!0),C6.concat([Q.update(D),Q.final()])}function Be(D,$,X){let[Y,J]=$.split(":"),Q=AM({key:X,padding:q7},C6.from(J,P6)),F=C6.from(Y,P6),Z=IxD(ze,Q,F);return Z.setAutoPadding(!0),C6.concat([Z.update(D),Z.final()])}function B7(D,$){return IM({key:$,padding:q7},C6.from(D,P6)).toString(P6)}function W7(D,$){return IM({key:$,padding:q7},C6.from(D,cw)).toString(cw)}function We(D,$){return AM({key:$,padding:q7},C6.from(D,P6)).toString(P6)}function Ke(D,$){return AM({key:$,padding:q7},C6.from(D,cw)).toString(cw)}function He(){let{publicKey:D,privateKey:$}=AxD("rsa",{modulusLength:2048});return{publicKey:D.export({type:"pkcs1",format:"pem"}),privateKey:$.export({type:"pkcs1",format:"pem"})}}function Ve(D){if(!D)return"";return D.replace(/-----BEGIN RSA PUBLIC KEY-----/g,"").replace(/-----END RSA PUBLIC KEY-----/g,"").replace(/\n/g,"").replace(/\r/g,"").replace(/ /g,"").substring(0,20)}O1();M3();kD();var ExD="5.30.0",TxD="6.30.0",CxD="7.30.0";function PxD(D,$){let X=D.key||R6,Y=$.config.plugins?.CapacitorUpdater?.publicKey;if(RM(X))Y=Ne(X,"utf8");else if(!Y&&D.keyData)Y=D.keyData;return{publicKey:Y,fallbackKeyPath:X}}async function Le(D,$,X,Y=!1){if(!Y)VD("Decrypt zip file");try{if(await F0(),!RM(D)){let O=`Zip not found at the path ${D}`;if(!Y)H.error(O);throw Error(O)}let J=await ID();if(!X.key&&!RM(R6)&&!J.config.plugins?.CapacitorUpdater?.publicKey){let O=`Public Key not found at the path ${R6} or in ${J.path}`;if(!Y)H.error(O);throw Error(O)}let{publicKey:Q,fallbackKeyPath:F}=PxD(X,J);if(!Q){let O=`Cannot find public key ${F} or as keyData option or in ${J.path}`;if(!Y)H.error(O);throw Error(O)}let Z=Ne(D),w=Be(Z,$,X.keyData??Q),G=`${D}_decrypted.zip`;if(RxD(G,w),!Y)H.info(`Decrypted zip file at ${G}`);let U;if(X.checksum){let O=await p6(w,"sha256"),q=e0(jxD()),z=await y1("@capgo/capacitor-updater",q,X.packageJson),B=!1,W;try{W=z?eD(z):void 0}catch{W=void 0}if(W)B=!w$(W,ExD,TxD,CxD);if(!Y)H.info(`Decrypting checksum with ${B?"V3":"V2"} (based on updater version ${z||"unknown"})`);let L=B?Ke(X.checksum,X.keyData??Q):We(X.checksum,X.keyData??Q);if(U=O===L,!U){let M=`Checksum does not match ${O} !== ${L}`;if(!Y)H.error(M);throw Error(M)}if(!Y)H.info("Checksum matches")}if(!Y)ND("✅ done");return{outputPath:G,checksumMatches:U}}catch(J){if(!Y)H.error(`Error decrypting zip file ${s(J)}`);throw J instanceof Error?J:Error(String(J))}}vD();kD();async function Me(D,$,X,Y=!1){if(!Y)VD("Delete bundle");X.apikey=X.apikey||WD();let J=await ID();if($=mD($,J?.config),!X.apikey){if(!Y)H.error("Missing API key, you need to provide an API key to upload your bundle");throw Error("Missing API key")}if(!$){if(!Y)H.error("Missing argument, you need to provide a appId, or be in a capacitor project");throw Error("Missing appId")}if(!D){if(!Y)H.error("Missing argument, you need to provide a bundleId, or be in a capacitor project");throw Error("Missing bundleId")}let Q=await jD(X.apikey,X.supaHost,X.supaAnon);if(await m0(Q,$,Y),await xD(Q,X.apikey,["write","all"]),await u0(Q,X.apikey,$,3,Y,!0),!Y)H.info(`Deleting bundle ${$}@${D} from Capgo`),H.info("Keep in mind that you will not be able to reuse this bundle version, it's gone forever");await Mw(Q,$,D);let F=await l0(Q,$);if(await AD(X.apikey,{channel:"app",event:"Bundle Deleted",icon:"\uD83D\uDDD1️",user_id:F,tags:{"app-id":$,bundle:D},notify:!1,notifyConsole:!0}).catch(()=>{}),!Y)H.success(`Bundle ${$}@${D} deleted in Capgo`),ND("Done");return!0}vD();X6();import{existsSync as jM,readFileSync as Ie,writeFileSync as xxD}from"node:fs";import{cwd as SxD}from"node:process";O1();kD();var uxD="5.30.0",vxD="6.30.0",_xD="7.30.0";function R2(D){console.error(s(D))}async function Ae(D,$,X,Y=!1){let{json:J}=X,Q=!J&&!Y;if(Q)VD("Encryption"),await F0();try{let F=await ID(),Z=!!F.config.plugins?.CapacitorUpdater?.privateKey,w=!!F.config.plugins?.CapacitorUpdater?.publicKey;if(Z&&Q)H.warning("There is still a privateKey in the config");if(!jM(D)){let N=`Zip not found at the path ${D}`;if(!Y)if(J)R2({error:"zip_not_found"});else H.error(`Error: ${N}`);throw Error(N)}if(!w){if(!Y)if(J)R2({error:"missing_public_key"});else H.warning("Warning: Missing Public Key in config");throw Error("Missing public key in config")}let G=X.key||i1,U=X.keyData||"";if(!jM(G)&&!U){if(!Y)if(J)R2({error:"missing_key"});else H.warning(`Cannot find a private key at ${G} or as a keyData option`),H.error("Error: Missing key");throw Error("Missing private key")}else if(jM(G))U=Ie(G,"utf8");if(U&&!U.startsWith("-----BEGIN RSA PRIVATE KEY-----")){if(!Y)if(J)R2({error:"invalid_private_key"});else H.error("The private key provided is not a valid RSA Private key");throw Error("Invalid private key format")}let O=Ie(D),{sessionKey:q,ivSessionKey:z}=dw(U),B=z7(O,q,z),W=e0(SxD()),L=await y1("@capgo/capacitor-updater",W,X.packageJson),M=!1,I;try{I=L?eD(L):void 0}catch{I=void 0}if(I)M=!w$(I,uxD,vxD,_xD);let K=M?W7($,U):B7($,U);if(Q)H.info(`Encrypting checksum with ${M?"V3":"V2"} (based on updater version ${L||"unknown"})`);let V=`${D}_encrypted.zip`;if(xxD(V,B),!Y)if(J)console.log(JSON.stringify({checksum:K,filename:V,ivSessionKey:z},null,2));else H.success(`Encoded Checksum: ${K}`),H.success(`ivSessionKey: ${z}`),H.success(`Encrypted zip saved at ${V}`),ND("Done ✅");return{checksum:K,filename:V,ivSessionKey:z}}catch(F){if(!Y)if(X.json)R2(F);else H.error(`Error encrypting zip file ${s(F)}`);throw F instanceof Error?F:Error(String(F))}}import{randomUUID as YvD}from"node:crypto";import{existsSync as YG,readFileSync as QvD}from"node:fs";import{cwd as YI,stdin as FvD,stdout as ZvD}from"node:process";class EM extends TransformStream{outChunkSize;constructor(D){let $=new Uint8Array(D),X=0;super({transform(Y,J){let Q=0;while(Q<Y.length){let F=D-X,Z=Math.min(F,Y.length-Q);if($.set(Y.subarray(Q,Q+Z),X),Q+=Z,X+=Z,X===D)J.enqueue($),$=new Uint8Array(D),X=0}},flush(Y){if(X>0)Y.enqueue($.subarray(0,X))}}),this.outChunkSize=D}}function E4(D){return D=D.trim(),D=D.replace(/<!--[\s\S]*?-->/g,""),$();function $(){return{declaration:X(),root:Y()}}function X(){if(!w(/^<\?xml\s*/))return;let q={attributes:{}};while(!(G()||U("?>"))){let z=Q();if(!z)return q;q.attributes[z.name]=z.value}return w(/\?>\s*/),q}function Y(){let O=w(/^<([\w-:.]+)\s*/);if(!O)return;let q={name:O[1],attributes:{},children:[]};while(!(G()||U(">")||U("?>")||U("/>"))){let B=Q();if(!B)return q;q.attributes[B.name]=B.value}if(w(/^\s*\/>\s*/))return q;w(/\??>\s*/),q.content=J();let z;while(z=Y())q.children.push(z);return w(/^<\/[\w-:.]+>\s*/),q}function J(){let O=w(/^([^<]*)/);if(O)return Z(O[1]);return""}function Q(){let O=w(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/);if(!O)return;return{name:O[1],value:Z(F(O[2]))}}function F(O){return O.replace(/^['"]|['"]$/g,"")}function Z(O){return O.replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}function w(O){let q=D.match(O);if(!q)return;return D=D.slice(q[0].length),q}function G(){return D.length===0}function U(O){return D.startsWith(O)}}class x6 extends Error{}class R1 extends x6{}class lw extends x6{}class TM extends x6{bucketName;constructor(D){super(`Invalid bucket name: ${D}`),this.bucketName=D}}class S6 extends x6{objectName;constructor(D){super(`Invalid object name: ${D}`),this.objectName=D}}class c8 extends x6{constructor(){super("accessKey is required")}}class j2 extends x6{constructor(){super("secretKey is required")}}class nw extends x6{constructor(){super("expirySeconds cannot be less than 1 second or more than 7 days")}}class T4 extends x6{statusCode;code;key;bucketName;resource;region;constructor(D,$,X,Y={}){super(X),this.statusCode=D,this.code=$,this.key=Y.key,this.bucketName=Y.bucketName,this.resource=Y.resource,this.region=Y.region}}async function Re(D){try{let X=E4(await D.text()).root;if(X?.name!=="Error")throw Error("Invalid root, expected <Error>");let Y=X.children.find((G)=>G.name==="Code")?.content??"UnknownErrorCode",J=X.children.find((G)=>G.name==="Message")?.content??"The error message could not be determined.",Q=X.children.find((G)=>G.name==="Key")?.content,F=X.children.find((G)=>G.name==="BucketName")?.content,Z=X.children.find((G)=>G.name==="Resource")?.content,w=X.children.find((G)=>G.name==="Region")?.content;return new T4(D.status,Y,J,{key:Q,bucketName:F,resource:Z,region:w})}catch{return new T4(D.status,"UnrecognizedError",`Error: Unexpected response code ${D.status} ${D.statusText}. Unable to parse response as XML.`)}}function je(D){if(typeof D!=="number"||isNaN(D))return!1;return D>=1&&D<=65535}function Ee(D){if(typeof D!=="string")return!1;if(D.length>255)return!1;if(D.includes(".."))return!1;return Boolean(D.match(/^[a-zA-Z0-9][a-zA-Z0-9.-]+[a-zA-Z0-9]$/))}function C4(D){if(!kxD(D))return!1;if(D.length===0)return!1;return!0}function kxD(D){if(typeof D!=="string")return!1;if(D.length>1024)return!1;return!0}function E2(D){return Array.from(D).map(($)=>$.toString(16).padStart(2,"0")).join("")}function d8(D=""){let $={'"':"","&quot;":"","&#34;":"","&QUOT;":"","&#x00022":""};return D.replace(/^("|&quot;|&#34;)|("|&quot;|&#34;)$/g,(X)=>$[X])}function PM(D){return D.get("x-amz-version-id")??null}function l8(D){let $=D.toISOString();return $.slice(0,4)+$.slice(5,7)+$.slice(8,13)+$.slice(14,16)+$.slice(17,19)+"Z"}function xM(D){return l8(D).slice(0,8)}function SM(D,$){return`${xM($)}/${D}/s3/aws4_request`}async function iw(D){if(!(D instanceof Uint8Array))D=new TextEncoder().encode(D);return E2(new Uint8Array(await crypto.subtle.digest("SHA-256",D)))}var fxD=["x-amz-server-side-encryption-customer-algorithm","x-amz-server-side-encryption-customer-key","x-amz-server-side-encryption-customer-key-MD5"];class uM extends WritableStream{getResult;constructor({client:D,bucketName:$,objectName:X,partSize:Y,metadata:J}){let Q,F=1,Z,w=[],G,U=[];super({start(){},async write(O,q){let B=F++;try{if(B==1&&O.length<Y){let M=await D.makeRequest({method:"PUT",headers:new Headers({...J,"Content-Length":String(O.length)}),bucketName:$,objectName:X,payload:O});Q={etag:d8(M.headers.get("etag")??void 0),versionId:PM(M.headers)};return}if(B===1)Z=(await yxD({client:D,bucketName:$,objectName:X,metadata:J})).uploadId;let W={"Content-Length":String(O.length)};for(let M of fxD){let I=J[M];if(I)W[M]=I}let L=D.makeRequest({method:"PUT",query:{partNumber:B.toString(),uploadId:Z},headers:new Headers(W),bucketName:$,objectName:X,payload:O}).then((M)=>{let I=M.headers.get("etag")??"";if(I)I=I.replace(/^"/,"").replace(/"$/,"");return w.push({part:B,etag:I}),M});U.push(L.catch((M)=>{if(!G)G=M}))}catch(W){throw W}},async close(){if(Q);else if(Z){if(await Promise.all(U),G)throw G;w.sort((O,q)=>O.part>q.part?1:-1),Q=await bxD({client:D,bucketName:$,objectName:X,uploadId:Z,etags:w})}else throw Error("Stream was closed without uploading any data.")}});this.getResult=()=>{if(Q===void 0)throw Error("Result is not ready. await the stream first.");return Q}}}async function yxD(D){let X=new Headers(D.metadata),Y="uploads",Q=await(await D.client.makeRequest({method:"POST",bucketName:D.bucketName,objectName:D.objectName,query:"uploads",headers:X,returnBody:!0})).text(),F=E4(Q).root;if(!F||F.name!=="InitiateMultipartUploadResult")throw Error(`Unexpected response: ${Q}`);let Z=F.children.find((w)=>w.name==="UploadId")?.content;if(!Z)throw Error(`Unable to get UploadId from response: ${Q}`);return{uploadId:Z}}async function bxD({client:D,bucketName:$,objectName:X,uploadId:Y,etags:J}){let Q=`
469
469
  <CompleteMultipartUpload xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
470
470
  ${J.map((O)=>` <Part><PartNumber>${O.part}</PartNumber><ETag>${O.etag}</ETag></Part>`).join(`
471
471
  `)}
@@ -474,7 +474,7 @@ All packages are compatible with channel "${F}"`)}return{finalCompatibility:w.fi
474
474
  `)+`
475
475
  `,Y.join(";").toLowerCase(),J].join(`
476
476
  `)}async function Se(D,$,X){let Y=await iw(D),J=SM(X,$);return[T2,l8($),J,Y].join(`
477
- `)}async function _M(D,$,X){let Y=xM(D),J=await i8("AWS4"+X,Y),Q=await i8(J,$),F=await i8(Q,"s3");return await i8(F,"aws4_request")}function kM(D,$,X){return`${D}/${SM($,X)}`}async function i8(D,$){let X=new TextEncoder,Y=await crypto.subtle.importKey("raw",D instanceof Uint8Array?D:X.encode(D),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"]),J=await crypto.subtle.sign("HMAC",Y,$ instanceof Uint8Array?$:X.encode($));return new Uint8Array(J)}async function ue(D){if(!D.accessKey)throw new c8;if(!D.secretKey)throw new j2;if(D.expirySeconds<1||D.expirySeconds>604800)throw new nw;let $=new Date(D.date);$.setSeconds($.getSeconds()+D.expirySeconds);let X=kM(D.accessKey,D.region,D.date),Y=l8(D.date),J={"X-Amz-Algorithm":T2,"X-Amz-Credential":X,"X-Amz-Date":Y,key:D.objectKey,...D.fields},Q=[{bucket:D.bucket},{key:D.objectKey},{"X-Amz-Algorithm":T2},{"X-Amz-Credential":X},{"X-Amz-Date":Y}];if(D.conditions)Q.push(...D.conditions);for(let[z,B]of Object.entries(D.fields||{})){if(["key","X-Amz-Algorithm","X-Amz-Credential","X-Amz-Date"].includes(z))continue;Q.push({[z]:B})}let F={expiration:$.toISOString(),conditions:Q},Z=new TextEncoder().encode(JSON.stringify(F)),w=btoa(String.fromCharCode(...Z));J.policy=w;let G=w,U=await _M(D.date,D.region,D.secretKey),O=E2(await i8(U,G)).toLowerCase();return J["X-Amz-Signature"]=O,{url:`${D.protocol}//${D.host}/${D.bucket}`,fields:J}}var gxD=["Content-Type","Cache-Control","Content-Disposition","Content-Encoding","Content-Language","Expires","x-amz-checksum-sha256","x-amz-grant-full-control","x-amz-grant-read","x-amz-grant-read-acp","x-amz-grant-write-acp","x-amz-server-side-encryption","x-amz-storage-class","x-amz-website-redirect-location","x-amz-server-side-encryption-customer-algorithm","x-amz-server-side-encryption-customer-key","x-amz-server-side-encryption-customer-key-MD5","x-amz-server-side-encryption-aws-kms-key-id","x-amz-server-side-encryption-context","x-amz-server-side-encryption-bucket-key-enabled","x-amz-request-payer","x-amz-tagging","x-amz-object-lock-mode","x-amz-object-lock-retain-until-date","x-amz-object-lock-legal-hold","x-amz-expected-bucket-owner"],mxD=5242880,cxD=5368709120,fM=5497558138880;class pw{host;port;protocol;accessKey;#D;sessionToken;defaultBucket;region;userAgent="s3-lite-client";pathStyle;pathPrefix;constructor({endPoint:D,useSSL:$,port:X,pathPrefix:Y,...J}){if(/^https?:\/\//i.test(D)){if($!==void 0||X!==void 0||Y!==void 0)throw new R1("useSSL/port/pathPrefix cannot be specified if endPoint is a URL.");try{let F=new URL(D);if(D=F.hostname,$=F.protocol==="https:",X=F.port?parseInt(F.port,10):$?443:80,F.pathname&&F.pathname!=="/")Y=F.pathname.endsWith("/")?F.pathname.slice(0,-1):F.pathname}catch{throw new lw(`Invalid endPoint URL: ${D}`)}}if(typeof D!=="string"||D.length===0)throw new lw(`Invalid endPoint: ${D}`);if($===void 0)$=!0;if(X!==void 0&&!je(X))throw new R1(`Invalid port: ${X}`);if(J.accessKey&&!J.secretKey)throw new R1("If specifying access key, secret key must also be provided.");if(J.accessKey&&J.accessKey.startsWith("ASIA")&&!J.sessionToken)throw new R1("If specifying temporary access key, session token must also be provided.");let Q=$?443:80;if(this.port=X??Q,this.host=D.toLowerCase()+(this.port!==Q?`:${this.port}`:""),this.protocol=$?"https:":"http:",this.accessKey=J.accessKey,this.#D=J.secretKey??"",this.sessionToken=J.sessionToken,this.pathStyle=J.pathStyle??!0,this.pathPrefix=Y??"",this.defaultBucket=J.bucket,this.region=J.region,this.pathPrefix){if(!this.pathStyle)throw new R1("pathPrefix is incompatible with pathStyle=false");if(!this.pathPrefix.startsWith("/"))throw new R1("pathPrefix should start with /");if(this.pathPrefix.endsWith("/"))throw new R1("pathPrefix should not end with /")}}getBucketName(D){let $=D?.bucketName??this.defaultBucket;if($===void 0||!Ee($))throw new TM($??"");return $}buildRequestOptions(D){let $=this.getBucketName(D),X=this.pathStyle?this.host:`${$}.${this.host}`,Y=D.headers??new Headers;Y.set("host",X);let J=typeof D.query==="object"?new URLSearchParams(D.query).toString().replace("+","%20"):D.query,Q=this.pathStyle?`${this.pathPrefix}/${$}/${D.objectName}`:`/${D.objectName}`,F=J?`?${J}`:"",Z=Q+F,w=Q.split("/").map((G)=>encodeURIComponent(G)).join("/")+F;return{headers:Y,host:X,path:Z,encodedPath:w}}async makeRequest({method:D,payload:$,...X}){let Y=new Date,{headers:J,host:Q,path:F,encodedPath:Z}=this.buildRequestOptions(X),w=X.statusCode??200;if(D==="POST"||D==="PUT"||D==="DELETE"){if($===void 0)$=new Uint8Array;else if(typeof $==="string")$=new TextEncoder().encode($);J.set("Content-Length",String($.length))}else if($)throw Error(`Unexpected payload on ${D} request.`);let G=await iw($??new Uint8Array);if(J.set("x-amz-date",l8(Y)),J.set("x-amz-content-sha256",G),this.accessKey){if(this.sessionToken)J.set("x-amz-security-token",this.sessionToken);J.set("authorization",await Te({headers:J,method:D,path:F,accessKey:this.accessKey,secretKey:this.#D,region:this.region,date:Y}))}let U=`${this.protocol}//${Q}${Z}`,O=await fetch(U,{method:D,headers:J,body:$});if(O.status!==w){if(O.status>=400)throw await Re(O);else if(O.status===301)throw new T4(O.status,"UnexpectedRedirect",'The server unexpectedly returned a redirect response. With AWS S3, this usually means you need to use a region-specific endpoint like "s3.us-west-2.amazonaws.com" instead of "s3.amazonaws.com"');throw new T4(O.status,"UnexpectedStatusCode",`Unexpected response code from the server (expected ${w}, got ${O.status} ${O.statusText}).`)}if(!X.returnBody)await O.body?.getReader().read();return O}async deleteObject(D,$={}){let X=this.getBucketName($);if(!C4(D))throw new S6(D);let Y=$.versionId?{versionId:$.versionId}:{},J=new Headers;if($.governanceBypass)J.set("X-Amz-Bypass-Governance-Retention","true");await this.makeRequest({method:"DELETE",bucketName:X,objectName:D,headers:J,query:Y,statusCode:204})}async exists(D,$){try{return await this.statObject(D,$),!0}catch(X){if(X instanceof T4&&X.statusCode===404)return!1;throw X}}getObject(D,$){return this.getPartialObject(D,{...$,offset:0,length:0})}async getPartialObject(D,{offset:$,length:X,...Y}){let J=this.getBucketName(Y);if(!C4(D))throw new S6(D);let Q=new Headers(Object.entries(Y.metadata??{})),F=200;if($||X){let w="";if($)w=`bytes=${+$}-`;else w="bytes=0-",$=0;if(X)w+=`${+X+$-1}`;Q.set("Range",w),F=206}let Z={...Y.responseParams,...Y.versionId?{versionId:Y.versionId}:{}};return await this.makeRequest({method:"GET",bucketName:J,objectName:D,headers:Q,query:Z,statusCode:F,returnBody:!0})}getPresignedUrl(D,$,X={}){if(!this.accessKey)throw new c8;if(!C4($))throw new S6($);let{headers:Y,path:J}=this.buildRequestOptions({objectName:$,bucketName:X.bucketName,query:X.parameters}),Q=X.requestDate??new Date,F=X.expirySeconds??604800;return Ce({protocol:this.protocol,headers:Y,method:D,path:J,accessKey:this.accessKey,secretKey:this.#D,sessionToken:this.sessionToken,region:this.region,date:Q,expirySeconds:F})}presignedGetObject(D,$={}){let{versionId:X,responseParams:Y,...J}=$,Q={...Y,...X?{versionId:X}:{}};return this.getPresignedUrl("GET",D,{parameters:Q,...J})}async*listObjects(D={}){for await(let $ of this.listObjectsGrouped({...D,delimiter:""}))if($.type==="Object")yield $;else throw Error(`Unexpected result from listObjectsGrouped(): ${$}`)}async*listObjectsGrouped(D){let $=this.getBucketName(D),X="",Y=D.pageSize??1000;if(Y<1||Y>1000)throw new R1("pageSize must be between 1 and 1,000.");let J=0;while(!0){let Q=D.maxResults?Math.min(Y,D.maxResults-J):Y;if(Q===0)return;let Z=await(await this.makeRequest({method:"GET",bucketName:$,objectName:"",query:{"list-type":"2",prefix:D.prefix??"",delimiter:D.delimiter,"max-keys":String(Q),...X?{"continuation-token":X}:{}},returnBody:!0})).text(),w=E4(Z).root;if(!w||w.name!=="ListBucketResult")throw Error(`Unexpected response: ${Z}`);let G=w.children.filter((q)=>q.name==="CommonPrefixes").flatMap((q)=>q.children),U=[];for(let q of G)U.push({type:"CommonPrefix",prefix:q.content??""}),J++;for(let q of w.children.filter((z)=>z.name==="Contents"))U.push({type:"Object",key:q.children.find((z)=>z.name==="Key")?.content??"",etag:d8(q.children.find((z)=>z.name==="ETag")?.content??""),size:parseInt(q.children.find((z)=>z.name==="Size")?.content??"",10),lastModified:new Date(q.children.find((z)=>z.name==="LastModified")?.content??"invalid")}),J++;U.sort((q,z)=>{let B=q.type==="Object"?q.key:q.prefix,W=z.type==="Object"?z.key:z.prefix;return B>W?1:B<W?-1:0});for(let q of U)yield q;if(w.children.find((q)=>q.name==="IsTruncated")?.content==="true"){let q=w.children.find((z)=>z.name==="NextContinuationToken")?.content;if(!q)throw Error("Unexpectedly missing continuation token, but server said there are more results.");X=q}else return}}async putObject(D,$,X){let Y=this.getBucketName(X);if(!C4(D))throw new S6(D);let J,Q;if(typeof $==="string"){let G=new TextEncoder().encode($);if(typeof ReadableStream.from<"u")Q=ReadableStream.from([G]);else Q=new ReadableStream({start(U){U.enqueue(G),U.close()}});J=G.length}else if($ instanceof Uint8Array){if(typeof ReadableStream.from<"u")Q=ReadableStream.from([$]);else Q=new ReadableStream({start(G){G.enqueue($),G.close()}});J=$.byteLength}else if($ instanceof ReadableStream)Q=$;else throw new R1("Invalid stream/data type provided.");if(X?.size!==void 0){if(J!==void 0&&X?.size!==J)throw new R1(`size was specified (${X.size}) but doesn't match auto-detected size (${J}).`);if(typeof X.size!=="number"||X.size<0||isNaN(X.size))throw new R1(`invalid size specified: ${X.size}`);else J=X.size}let F=X?.partSize??this.calculatePartSize(J);if(F<mxD)throw new R1("Part size should be greater than 5MB");else if(F>cxD)throw new R1("Part size should be less than 6MB");let Z=new EM(F),w=new uM({client:this,bucketName:Y,objectName:D,partSize:F,metadata:X?.metadata??{}});return await Q.pipeThrough(Z).pipeTo(w),w.getResult()}calculatePartSize(D){if(D===void 0)D=fM;if(D>fM)throw TypeError(`size should not be more than ${fM}`);let $=67108864;while(!0){if($*1e4>D)return $;$+=16777216}}async statObject(D,$){let X=this.getBucketName($);if(!C4(D))throw new S6(D);let Y={};if($?.versionId)Y.versionId=$.versionId;let J=await this.makeRequest({method:"HEAD",bucketName:X,objectName:D,query:Y,headers:new Headers($?.headers)}),Q={};for(let F of gxD)if(J.headers.has(F))Q[F]=J.headers.get(F);return J.headers.forEach((F,Z)=>{if(Z.startsWith("x-amz-meta-"))Q[Z]=J.headers.get(Z)}),{type:"Object",key:D,size:parseInt(J.headers.get("content-length")??"",10),metadata:Q,lastModified:new Date(J.headers.get("Last-Modified")??"error: missing last modified"),versionId:J.headers.get("x-amz-version-id")||null,etag:d8(J.headers.get("ETag")??"")}}async copyObject(D,$,X){let Y=this.getBucketName(X),J=D.sourceBucketName??Y;if(!C4($))throw new S6($);let Q=`${J}/${D.sourceKey}`;if(D.sourceVersionId)Q+=`?versionId=${D.sourceVersionId}`;let F=new Headers(X?.metadata);if(X?.metadata!==void 0)F.set("x-amz-metadata-directive","REPLACE");F.set("x-amz-copy-source",Q);let Z=await this.makeRequest({method:"PUT",bucketName:Y,objectName:$,headers:F,returnBody:!0}),w=await Z.text(),G=E4(w).root;if(!G||G.name!=="CopyObjectResult")throw Error(`Unexpected response: ${w}`);let U=G.children.find((q)=>q.name==="ETag")?.content??"",O=G.children.find((q)=>q.name==="LastModified")?.content;if(O===void 0)throw Error("Unable to find <LastModified>...</LastModified> from the server.");return{copySourceVersionId:Z.headers.get("x-amz-copy-source-version-id")||null,etag:d8(U),lastModified:new Date(O),versionId:Z.headers.get("x-amz-version-id")||null}}async bucketExists(D){try{return await this.listObjects({bucketName:D}).next(),!0}catch($){if($ instanceof T4&&$.statusCode===404)return!1;throw $}}async makeBucket(D){await this.makeRequest({method:"PUT",bucketName:this.getBucketName({bucketName:D}),objectName:"",statusCode:200})}async removeBucket(D){await this.makeRequest({method:"DELETE",bucketName:this.getBucketName({bucketName:D}),objectName:"",statusCode:204})}presignedPostObject(D,$={}){if(!C4(D))throw new S6(D);let X=this.getBucketName($);if(!X)throw Error("Bucket name is required for presignedPost, but none was provided either to this method nor to the client constructor");let Y=$.requestDate||new Date,J=$.expirySeconds??3600;return ue({protocol:this.protocol,host:this.host,bucket:X,objectKey:D,accessKey:this.accessKey||"",secretKey:this.#D||"",region:this.region,date:Y,expirySeconds:J,conditions:$.conditions,fields:$.fields})}}vD();D6();X6();L3();O1();M3();import{spawn as dxD,spawnSync as lxD}from"node:child_process";var u6="Cap-go",nxD="capacitor-updater",ke=`${u6}/${nxD}`,ve="capacitor-",yM=[`${u6}/CLI`,`${u6}/capgo`,`${u6}/capgo-skills`],rw=[ke,...yM],ixD=20,pxD=180,rxD=4,fe=new Set;class ye extends Error{results;constructor(D=[]){super("Star-all interrupted by user.");this.name="StarAllRepositoriesAbortedError",this.results=D}}function C2(D){return D.toLowerCase()}function hM(D){fe.add(C2(D))}function be(D){let $=aw(D);return fe.has(C2($))}function _e(D,$){if(typeof D!=="number")return $;if(!Number.isFinite(D))return $;if(D<0)return $;return Math.floor(D)}function oxD(D,$){let X=_e(D,ixD),Y=_e($,pxD);if(X<=Y)return{min:X,max:Y};return{min:Y,max:X}}function axD(D,$){if(D===$)return D;return Math.floor(Math.random()*($-D+1))+D}function txD(D,$){if(typeof D!=="number")return $;if(!Number.isFinite(D))return $;if(D<1)return $;return Math.min(Math.floor(D),16)}function ow(D=[]){return new ye(D)}function p8(D,$=[]){if(D?.aborted)throw ow($)}async function sxD(D,$){if(D<=0)return;if(!$)return new Promise((X)=>setTimeout(X,D));if($.aborted)throw ow();return new Promise((X,Y)=>{let J,Q=()=>{clearTimeout(J),$.removeEventListener("abort",Q),Y(ow())};J=setTimeout(()=>{$.removeEventListener("abort",Q),X()},D),$.addEventListener("abort",Q,{once:!0})})}function bM(D){let $=new Set,X=[];for(let Y of D){let J=aw(Y),Q=C2(J);if(!$.has(Q))$.add(Q),X.push(J)}return X}async function exD(D,$){p8($),D?.(`Discovering repositories in the ${u6} organization.`);let X=r8(["api","--paginate",`orgs/${u6}/repos`,"--jq",`map(select(.name | startswith("${ve}")) | .nameWithOwner)[]`]);if(X.status===0&&X.stdout.trim().length>0){let J=X.stdout.split(`
477
+ `)}async function _M(D,$,X){let Y=xM(D),J=await i8("AWS4"+X,Y),Q=await i8(J,$),F=await i8(Q,"s3");return await i8(F,"aws4_request")}function kM(D,$,X){return`${D}/${SM($,X)}`}async function i8(D,$){let X=new TextEncoder,Y=await crypto.subtle.importKey("raw",D instanceof Uint8Array?D:X.encode(D),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"]),J=await crypto.subtle.sign("HMAC",Y,$ instanceof Uint8Array?$:X.encode($));return new Uint8Array(J)}async function ue(D){if(!D.accessKey)throw new c8;if(!D.secretKey)throw new j2;if(D.expirySeconds<1||D.expirySeconds>604800)throw new nw;let $=new Date(D.date);$.setSeconds($.getSeconds()+D.expirySeconds);let X=kM(D.accessKey,D.region,D.date),Y=l8(D.date),J={"X-Amz-Algorithm":T2,"X-Amz-Credential":X,"X-Amz-Date":Y,key:D.objectKey,...D.fields},Q=[{bucket:D.bucket},{key:D.objectKey},{"X-Amz-Algorithm":T2},{"X-Amz-Credential":X},{"X-Amz-Date":Y}];if(D.conditions)Q.push(...D.conditions);for(let[z,B]of Object.entries(D.fields||{})){if(["key","X-Amz-Algorithm","X-Amz-Credential","X-Amz-Date"].includes(z))continue;Q.push({[z]:B})}let F={expiration:$.toISOString(),conditions:Q},Z=new TextEncoder().encode(JSON.stringify(F)),w=btoa(String.fromCharCode(...Z));J.policy=w;let G=w,U=await _M(D.date,D.region,D.secretKey),O=E2(await i8(U,G)).toLowerCase();return J["X-Amz-Signature"]=O,{url:`${D.protocol}//${D.host}/${D.bucket}`,fields:J}}var gxD=["Content-Type","Cache-Control","Content-Disposition","Content-Encoding","Content-Language","Expires","x-amz-checksum-sha256","x-amz-grant-full-control","x-amz-grant-read","x-amz-grant-read-acp","x-amz-grant-write-acp","x-amz-server-side-encryption","x-amz-storage-class","x-amz-website-redirect-location","x-amz-server-side-encryption-customer-algorithm","x-amz-server-side-encryption-customer-key","x-amz-server-side-encryption-customer-key-MD5","x-amz-server-side-encryption-aws-kms-key-id","x-amz-server-side-encryption-context","x-amz-server-side-encryption-bucket-key-enabled","x-amz-request-payer","x-amz-tagging","x-amz-object-lock-mode","x-amz-object-lock-retain-until-date","x-amz-object-lock-legal-hold","x-amz-expected-bucket-owner"],mxD=5242880,cxD=5368709120,fM=5497558138880;class pw{host;port;protocol;accessKey;#D;sessionToken;defaultBucket;region;userAgent="s3-lite-client";pathStyle;pathPrefix;constructor({endPoint:D,useSSL:$,port:X,pathPrefix:Y,...J}){if(/^https?:\/\//i.test(D)){if($!==void 0||X!==void 0||Y!==void 0)throw new R1("useSSL/port/pathPrefix cannot be specified if endPoint is a URL.");try{let F=new URL(D);if(D=F.hostname,$=F.protocol==="https:",X=F.port?parseInt(F.port,10):$?443:80,F.pathname&&F.pathname!=="/")Y=F.pathname.endsWith("/")?F.pathname.slice(0,-1):F.pathname}catch{throw new lw(`Invalid endPoint URL: ${D}`)}}if(typeof D!=="string"||D.length===0)throw new lw(`Invalid endPoint: ${D}`);if($===void 0)$=!0;if(X!==void 0&&!je(X))throw new R1(`Invalid port: ${X}`);if(J.accessKey&&!J.secretKey)throw new R1("If specifying access key, secret key must also be provided.");if(J.accessKey&&J.accessKey.startsWith("ASIA")&&!J.sessionToken)throw new R1("If specifying temporary access key, session token must also be provided.");let Q=$?443:80;if(this.port=X??Q,this.host=D.toLowerCase()+(this.port!==Q?`:${this.port}`:""),this.protocol=$?"https:":"http:",this.accessKey=J.accessKey,this.#D=J.secretKey??"",this.sessionToken=J.sessionToken,this.pathStyle=J.pathStyle??!0,this.pathPrefix=Y??"",this.defaultBucket=J.bucket,this.region=J.region,this.pathPrefix){if(!this.pathStyle)throw new R1("pathPrefix is incompatible with pathStyle=false");if(!this.pathPrefix.startsWith("/"))throw new R1("pathPrefix should start with /");if(this.pathPrefix.endsWith("/"))throw new R1("pathPrefix should not end with /")}}getBucketName(D){let $=D?.bucketName??this.defaultBucket;if($===void 0||!Ee($))throw new TM($??"");return $}buildRequestOptions(D){let $=this.getBucketName(D),X=this.pathStyle?this.host:`${$}.${this.host}`,Y=D.headers??new Headers;Y.set("host",X);let J=typeof D.query==="object"?new URLSearchParams(D.query).toString().replace("+","%20"):D.query,Q=this.pathStyle?`${this.pathPrefix}/${$}/${D.objectName}`:`/${D.objectName}`,F=J?`?${J}`:"",Z=Q+F,w=Q.split("/").map((G)=>encodeURIComponent(G)).join("/")+F;return{headers:Y,host:X,path:Z,encodedPath:w}}async makeRequest({method:D,payload:$,...X}){let Y=new Date,{headers:J,host:Q,path:F,encodedPath:Z}=this.buildRequestOptions(X),w=X.statusCode??200;if(D==="POST"||D==="PUT"||D==="DELETE"){if($===void 0)$=new Uint8Array;else if(typeof $==="string")$=new TextEncoder().encode($);J.set("Content-Length",String($.length))}else if($)throw Error(`Unexpected payload on ${D} request.`);let G=await iw($??new Uint8Array);if(J.set("x-amz-date",l8(Y)),J.set("x-amz-content-sha256",G),this.accessKey){if(this.sessionToken)J.set("x-amz-security-token",this.sessionToken);J.set("authorization",await Te({headers:J,method:D,path:F,accessKey:this.accessKey,secretKey:this.#D,region:this.region,date:Y}))}let U=`${this.protocol}//${Q}${Z}`,O=await fetch(U,{method:D,headers:J,body:$});if(O.status!==w){if(O.status>=400)throw await Re(O);else if(O.status===301)throw new T4(O.status,"UnexpectedRedirect",'The server unexpectedly returned a redirect response. With AWS S3, this usually means you need to use a region-specific endpoint like "s3.us-west-2.amazonaws.com" instead of "s3.amazonaws.com"');throw new T4(O.status,"UnexpectedStatusCode",`Unexpected response code from the server (expected ${w}, got ${O.status} ${O.statusText}).`)}if(!X.returnBody)await O.body?.getReader().read();return O}async deleteObject(D,$={}){let X=this.getBucketName($);if(!C4(D))throw new S6(D);let Y=$.versionId?{versionId:$.versionId}:{},J=new Headers;if($.governanceBypass)J.set("X-Amz-Bypass-Governance-Retention","true");await this.makeRequest({method:"DELETE",bucketName:X,objectName:D,headers:J,query:Y,statusCode:204})}async exists(D,$){try{return await this.statObject(D,$),!0}catch(X){if(X instanceof T4&&X.statusCode===404)return!1;throw X}}getObject(D,$){return this.getPartialObject(D,{...$,offset:0,length:0})}async getPartialObject(D,{offset:$,length:X,...Y}){let J=this.getBucketName(Y);if(!C4(D))throw new S6(D);let Q=new Headers(Object.entries(Y.metadata??{})),F=200;if($||X){let w="";if($)w=`bytes=${+$}-`;else w="bytes=0-",$=0;if(X)w+=`${+X+$-1}`;Q.set("Range",w),F=206}let Z={...Y.responseParams,...Y.versionId?{versionId:Y.versionId}:{}};return await this.makeRequest({method:"GET",bucketName:J,objectName:D,headers:Q,query:Z,statusCode:F,returnBody:!0})}getPresignedUrl(D,$,X={}){if(!this.accessKey)throw new c8;if(!C4($))throw new S6($);let{headers:Y,path:J}=this.buildRequestOptions({objectName:$,bucketName:X.bucketName,query:X.parameters}),Q=X.requestDate??new Date,F=X.expirySeconds??604800;return Ce({protocol:this.protocol,headers:Y,method:D,path:J,accessKey:this.accessKey,secretKey:this.#D,sessionToken:this.sessionToken,region:this.region,date:Q,expirySeconds:F})}presignedGetObject(D,$={}){let{versionId:X,responseParams:Y,...J}=$,Q={...Y,...X?{versionId:X}:{}};return this.getPresignedUrl("GET",D,{parameters:Q,...J})}async*listObjects(D={}){for await(let $ of this.listObjectsGrouped({...D,delimiter:""}))if($.type==="Object")yield $;else throw Error(`Unexpected result from listObjectsGrouped(): ${$}`)}async*listObjectsGrouped(D){let $=this.getBucketName(D),X="",Y=D.pageSize??1000;if(Y<1||Y>1000)throw new R1("pageSize must be between 1 and 1,000.");let J=0;while(!0){let Q=D.maxResults?Math.min(Y,D.maxResults-J):Y;if(Q===0)return;let Z=await(await this.makeRequest({method:"GET",bucketName:$,objectName:"",query:{"list-type":"2",prefix:D.prefix??"",delimiter:D.delimiter,"max-keys":String(Q),...X?{"continuation-token":X}:{}},returnBody:!0})).text(),w=E4(Z).root;if(!w||w.name!=="ListBucketResult")throw Error(`Unexpected response: ${Z}`);let G=w.children.filter((q)=>q.name==="CommonPrefixes").flatMap((q)=>q.children),U=[];for(let q of G)U.push({type:"CommonPrefix",prefix:q.content??""}),J++;for(let q of w.children.filter((z)=>z.name==="Contents"))U.push({type:"Object",key:q.children.find((z)=>z.name==="Key")?.content??"",etag:d8(q.children.find((z)=>z.name==="ETag")?.content??""),size:parseInt(q.children.find((z)=>z.name==="Size")?.content??"",10),lastModified:new Date(q.children.find((z)=>z.name==="LastModified")?.content??"invalid")}),J++;U.sort((q,z)=>{let B=q.type==="Object"?q.key:q.prefix,W=z.type==="Object"?z.key:z.prefix;return B>W?1:B<W?-1:0});for(let q of U)yield q;if(w.children.find((q)=>q.name==="IsTruncated")?.content==="true"){let q=w.children.find((z)=>z.name==="NextContinuationToken")?.content;if(!q)throw Error("Unexpectedly missing continuation token, but server said there are more results.");X=q}else return}}async putObject(D,$,X){let Y=this.getBucketName(X);if(!C4(D))throw new S6(D);let J,Q;if(typeof $==="string"){let G=new TextEncoder().encode($);if(typeof ReadableStream.from<"u")Q=ReadableStream.from([G]);else Q=new ReadableStream({start(U){U.enqueue(G),U.close()}});J=G.length}else if($ instanceof Uint8Array){if(typeof ReadableStream.from<"u")Q=ReadableStream.from([$]);else Q=new ReadableStream({start(G){G.enqueue($),G.close()}});J=$.byteLength}else if($ instanceof ReadableStream)Q=$;else throw new R1("Invalid stream/data type provided.");if(X?.size!==void 0){if(J!==void 0&&X?.size!==J)throw new R1(`size was specified (${X.size}) but doesn't match auto-detected size (${J}).`);if(typeof X.size!=="number"||X.size<0||isNaN(X.size))throw new R1(`invalid size specified: ${X.size}`);else J=X.size}let F=X?.partSize??this.calculatePartSize(J);if(F<mxD)throw new R1("Part size should be greater than 5MB");else if(F>cxD)throw new R1("Part size should be less than 6MB");let Z=new EM(F),w=new uM({client:this,bucketName:Y,objectName:D,partSize:F,metadata:X?.metadata??{}});return await Q.pipeThrough(Z).pipeTo(w),w.getResult()}calculatePartSize(D){if(D===void 0)D=fM;if(D>fM)throw TypeError(`size should not be more than ${fM}`);let $=67108864;while(!0){if($*1e4>D)return $;$+=16777216}}async statObject(D,$){let X=this.getBucketName($);if(!C4(D))throw new S6(D);let Y={};if($?.versionId)Y.versionId=$.versionId;let J=await this.makeRequest({method:"HEAD",bucketName:X,objectName:D,query:Y,headers:new Headers($?.headers)}),Q={};for(let F of gxD)if(J.headers.has(F))Q[F]=J.headers.get(F);return J.headers.forEach((F,Z)=>{if(Z.startsWith("x-amz-meta-"))Q[Z]=J.headers.get(Z)}),{type:"Object",key:D,size:parseInt(J.headers.get("content-length")??"",10),metadata:Q,lastModified:new Date(J.headers.get("Last-Modified")??"error: missing last modified"),versionId:J.headers.get("x-amz-version-id")||null,etag:d8(J.headers.get("ETag")??"")}}async copyObject(D,$,X){let Y=this.getBucketName(X),J=D.sourceBucketName??Y;if(!C4($))throw new S6($);let Q=`${J}/${D.sourceKey.split("/").map((q)=>encodeURIComponent(q)).join("/")}`;if(D.sourceVersionId)Q+=`?versionId=${D.sourceVersionId}`;let F=new Headers(X?.metadata);if(X?.metadata!==void 0)F.set("x-amz-metadata-directive","REPLACE");F.set("x-amz-copy-source",Q);let Z=await this.makeRequest({method:"PUT",bucketName:Y,objectName:$,headers:F,returnBody:!0}),w=await Z.text(),G=E4(w).root;if(!G||G.name!=="CopyObjectResult")throw Error(`Unexpected response: ${w}`);let U=G.children.find((q)=>q.name==="ETag")?.content??"",O=G.children.find((q)=>q.name==="LastModified")?.content;if(O===void 0)throw Error("Unable to find <LastModified>...</LastModified> from the server.");return{copySourceVersionId:Z.headers.get("x-amz-copy-source-version-id")||null,etag:d8(U),lastModified:new Date(O),versionId:Z.headers.get("x-amz-version-id")||null}}async bucketExists(D){try{return await this.listObjects({bucketName:D}).next(),!0}catch($){if($ instanceof T4&&$.statusCode===404)return!1;throw $}}async makeBucket(D){await this.makeRequest({method:"PUT",bucketName:this.getBucketName({bucketName:D}),objectName:"",statusCode:200})}async removeBucket(D){await this.makeRequest({method:"DELETE",bucketName:this.getBucketName({bucketName:D}),objectName:"",statusCode:204})}presignedPostObject(D,$={}){if(!C4(D))throw new S6(D);let X=this.getBucketName($);if(!X)throw Error("Bucket name is required for presignedPost, but none was provided either to this method nor to the client constructor");let Y=$.requestDate||new Date,J=$.expirySeconds??3600;return ue({protocol:this.protocol,host:this.host,bucket:X,objectKey:D,accessKey:this.accessKey||"",secretKey:this.#D||"",region:this.region,date:Y,expirySeconds:J,conditions:$.conditions,fields:$.fields})}}vD();D6();X6();L3();O1();M3();import{spawn as dxD,spawnSync as lxD}from"node:child_process";var u6="Cap-go",nxD="capacitor-updater",ke=`${u6}/${nxD}`,ve="capacitor-",yM=[`${u6}/CLI`,`${u6}/capgo`,`${u6}/capgo-skills`],rw=[ke,...yM],ixD=20,pxD=180,rxD=4,fe=new Set;class ye extends Error{results;constructor(D=[]){super("Star-all interrupted by user.");this.name="StarAllRepositoriesAbortedError",this.results=D}}function C2(D){return D.toLowerCase()}function hM(D){fe.add(C2(D))}function be(D){let $=aw(D);return fe.has(C2($))}function _e(D,$){if(typeof D!=="number")return $;if(!Number.isFinite(D))return $;if(D<0)return $;return Math.floor(D)}function oxD(D,$){let X=_e(D,ixD),Y=_e($,pxD);if(X<=Y)return{min:X,max:Y};return{min:Y,max:X}}function axD(D,$){if(D===$)return D;return Math.floor(Math.random()*($-D+1))+D}function txD(D,$){if(typeof D!=="number")return $;if(!Number.isFinite(D))return $;if(D<1)return $;return Math.min(Math.floor(D),16)}function ow(D=[]){return new ye(D)}function p8(D,$=[]){if(D?.aborted)throw ow($)}async function sxD(D,$){if(D<=0)return;if(!$)return new Promise((X)=>setTimeout(X,D));if($.aborted)throw ow();return new Promise((X,Y)=>{let J,Q=()=>{clearTimeout(J),$.removeEventListener("abort",Q),Y(ow())};J=setTimeout(()=>{$.removeEventListener("abort",Q),X()},D),$.addEventListener("abort",Q,{once:!0})})}function bM(D){let $=new Set,X=[];for(let Y of D){let J=aw(Y),Q=C2(J);if(!$.has(Q))$.add(Q),X.push(J)}return X}async function exD(D,$){p8($),D?.(`Discovering repositories in the ${u6} organization.`);let X=r8(["api","--paginate",`orgs/${u6}/repos`,"--jq",`map(select(.name | startswith("${ve}")) | .nameWithOwner)[]`]);if(X.status===0&&X.stdout.trim().length>0){let J=X.stdout.split(`
478
478
  `).map((Q)=>Q.trim()).filter((Q)=>Q.length>0);if(J.length>0){let Q=bM([...J,...yM]);return D?.(`Found ${Q.length} matching repositories from the GitHub API.`),Q}D?.("No matching repositories were returned from the paginated GitHub API. Trying a fallback request.")}else D?.("Paginated GitHub API request failed. Trying a fallback request.");let Y=r8(["api",`orgs/${u6}/repos?per_page=100`]);if(Y.status!==0)return D?.("Fallback request failed. Using the default repository list instead."),[...rw];try{let J=JSON.parse(Y.stdout);if(!Array.isArray(J))return D?.("Fallback response format was invalid. Using the default repository list instead."),[...rw];let Q=J.filter((F)=>typeof F==="object"&&F!==null).map((F)=>F.name).filter((F)=>!!F&&F.startsWith(ve)).map((F)=>`${u6}/${F}`);if(Q.length>0){let F=bM([...Q,...yM]);return D?.(`Found ${F.length} matching repositories from the fallback request.`),F}}catch{return D?.("Fallback response could not be parsed. Using the default repository list instead."),[...rw]}return D?.("No matching repositories were found. Using the default repository list instead."),[...rw]}function DSD(D,$){return new Promise((X)=>{let Y="",J="",Q=!1,F,Z=()=>{},w=(G)=>{if(Q)return;Q=!0,$?.removeEventListener("abort",Z),X(G)};if(Z=()=>{F?.kill("SIGINT"),w({status:130,stderr:"GitHub command interrupted by user.",stdout:Y})},F=dxD("gh",D,{stdio:["ignore","pipe","pipe"]}),F.stdout?.setEncoding("utf8"),F.stdout?.on("data",(G)=>{Y+=G}),F.stderr?.setEncoding("utf8"),F.stderr?.on("data",(G)=>{J+=G}),F.on("error",()=>{w({status:1,stderr:"`gh` command is not available in PATH.",stdout:""})}),F.on("close",(G)=>{w({status:G??1,stderr:J,stdout:Y})}),$){if($.aborted){Z();return}$.addEventListener("abort",Z,{once:!0})}})}function r8(D){try{let $=lxD("gh",D,{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{status:$.status??1,stderr:$.stderr?.toString()??"",stdout:$.stdout?.toString()??""}}catch{return{status:1,stderr:"`gh` command is not available in PATH.",stdout:""}}}function he(){if(!ce())throw Error("GitHub CLI (`gh`) is not installed. Install it from https://cli.github.com/");if(!de())throw Error("GitHub CLI is not logged in. Run `gh auth login` first.")}async function $SD(D,$,X){if(D.length===0)return new Set;let Y=new Set;return $?.(`Checking ${D.length} target repositories against your GitHub stars.`),await ge(D,Math.min(D.length,8),X,()=>[],async(J)=>{let Q=await DSD(["api","-X","GET",`/user/starred/${J}`],X);if(Q.status===0){Y.add(C2(J));return}if(Q.status===1)return;if(Q.status===130&&X?.aborted)throw ow();throw Error(`Unable to check star status for ${J}. ${Q.stderr||Q.stdout}`.trim())}),$?.(`Found ${Y.size} repositories already starred.`),Y}async function ge(D,$,X,Y,J){let Q=0;async function F(){while(!0){p8(X,Y());let w=Q;if(Q+=1,w>=D.length)return;await J(D[w],w)}}let Z=Math.min($,D.length);await Promise.all(Array.from({length:Z},()=>F()))}function XSD(D,$,X){let Y=Promise.resolve();return async()=>{p8(X);let J,Q=Y;Y=new Promise((F)=>{J=F}),await Q,await sxD(axD(D,$),X),J?.()}}function me(D){let $=r8(["api","-X","PUT",`/user/starred/${D}`]);if($.status!==0){let X=$.stderr||$.stdout||`GitHub returned status ${$.status}`;throw Error(`Failed to star ${D}: ${X.trim()}`)}return hM(D),{repository:D,alreadyStarred:!1}}function aw(D){let X=(D?.trim()||ke).replace(/\.git$/i,"");if(/^https?:\/\//.test(X))try{let Y=new URL(X);if(Y.hostname.endsWith("github.com")){let[J,Q]=Y.pathname.split("/").filter((F)=>F.length>0);if(J&&Q)return`${J}/${Q}`}}catch{}if(X.startsWith("git@github.com:")){let[,Y]=X.split("git@github.com:");if(Y){let[J,Q]=Y.split("/");if(J&&Q)return`${J}/${Q}`}}if(X.includes("/")){let[Y,J]=X.split("/");if(Y&&J)return`${Y}/${J}`}return`${u6}/${X}`}function JSD(D){return r8(["repo","view",D,"--json","nameWithOwner"]).status===0}function YSD(D){let $=r8(["api","-X","GET",`/user/starred/${D}`]);if($.status===0)return!0;if($.status===1)return!1;throw Error(`Unable to check star status for ${D}.`)}function ce(){return r8(["--version"]).status===0}function de(){return r8(["auth","status"]).status===0}function le(D){let $=aw(D);if(!ce())return{repository:$,ghInstalled:!1,ghLoggedIn:!1,repositoryExists:!1,starred:!1};if(!de())return{repository:$,ghInstalled:!0,ghLoggedIn:!1,repositoryExists:!1,starred:!1};if(!JSD($))return{repository:$,ghInstalled:!0,ghLoggedIn:!0,repositoryExists:!1,starred:!1};return{repository:$,ghInstalled:!0,ghLoggedIn:!0,repositoryExists:!0,starred:YSD($)}}async function ne(D={}){he(),p8(D.signal);let $=D.repositories?.length?D.repositories:await exD(D.onDiscovery,D.signal);D.onDiscovery?.(`Prepared ${$.length} repositories to process.`);let X=oxD(D.minDelayMs,D.maxDelayMs),Y=bM($),J=txD(D.maxConcurrency,rxD);p8(D.signal);let Q=await $SD(Y,D.onDiscovery,D.signal),F=Array.from({length:Y.length}),Z=()=>F.filter((U)=>!!U),w=[];for(let U=0;U<Y.length;U++){p8(D.signal,Z());let O=Y[U],q=C2(O);if(be(O)){let z={repository:O,alreadyStarred:!0,skipped:!0,status:"already_starred"};D.onProgress?.(z),F[U]=z;continue}if(Q.has(q)){hM(O);let z={repository:O,alreadyStarred:!0,skipped:!0,status:"already_starred"};D.onProgress?.(z),F[U]=z;continue}w.push({index:U,repository:O})}let G=XSD(X.min,X.max,D.signal);return await ge(w,J,D.signal,Z,async({index:U,repository:O})=>{await G(),p8(D.signal,Z());try{let z={repository:me(O).repository,alreadyStarred:!1,skipped:!1,status:"starred"};D.onProgress?.(z),F[U]=z}catch(q){let z={repository:O,alreadyStarred:!1,skipped:!1,status:"failed",error:q instanceof Error?q.message:String(q)};D.onProgress?.(z),F[U]=z}}),Z()}function gM(D){let $=aw(D);he();let X=le($);if(!X.repositoryExists)throw Error(`Cannot star ${$}: repository is not reachable or does not exist.`);if(X.starred)return hM($),{repository:$,alreadyStarred:!0};return me($)}vD();import ie from"node:process";var QSD=[{code:"aws:eu-central-1",label:"EU (Frankfurt)"},{code:"gcp:me-central1",label:"Middle East (Riyadh)"},{code:"gcp:asia-east2",label:"Hong Kong"},{code:"aws:ap-northeast-1",label:"Japan (Tokyo)"},{code:"aws:ap-south-1",label:"India (Mumbai)"},{code:"aws:us-east-1",label:"North America (Virginia)"},{code:"gcp:africa-south1",label:"Africa (South Africa)"},{code:"aws:ap-southeast-2",label:"Oceania (Sydney)"},{code:"aws:sa-east-1",label:"South America (São Paulo)"}],FSD=60000,ZSD=1000,pe=20;function wSD(){if(typeof Intl>"u")return null;return Intl.DateTimeFormat().resolvedOptions().timeZone||null}function GSD(){let D=wSD();if(!D)return null;if(/^America\//.test(D))return"aws:us-east-1";if(/^Europe\//.test(D)||/^Atlantic\//.test(D))return"aws:eu-central-1";if(/^Africa\//.test(D))return"gcp:africa-south1";if(/^Asia\//.test(D)){let $=(D.split("/")[1]??"").toLowerCase();if(["tokyo","osaka","seoul","pyongyang"].includes($))return"aws:ap-northeast-1";if(["kolkata","mumbai","calcutta","chennai","bangalore","hyderabad","delhi","dhaka","colombo","karachi"].includes($))return"aws:ap-south-1";if(["hong_kong","singapore","manila","jakarta","kuala_lumpur","beijing","shanghai","hongkong","taipei"].includes($))return"gcp:asia-east2";if(["sydney","melbourne","canberra","perth","brisbane","darwin","adelaide"].includes($))return"aws:ap-southeast-2";return"gcp:asia-east2"}if(/^Pacific\//.test(D)||/^Australia\//.test(D))return"aws:ap-southeast-2";return null}function USD(){let D=[...QSD],$=GSD();if(!$)return D;let X=D.findIndex((J)=>J.code===$);if(X<0)return D;let[Y]=D.splice(X,1);return D.push(Y),D}function OSD(D,$,X){let Y=Math.min(Math.max(D,0),X);return Math.floor(Y/X*$)}function qSD(D){let $=Math.min(Math.max(D,0),100),X=Math.round($/100*pe);return`${"█".repeat(X)}${"░".repeat(pe-X)}`}function zSD(D){return`${Math.max(0,D)}s`}function re({interactive:D=ie.stdout.isTTY&&ie.stderr.isTTY,totalMs:$=FSD,updateIntervalMs:X=ZSD,title:Y="Replicating your bundle in all regions...",completeMessage:J="Your update is now available worldwide."}={}){if(!D||$<=0)return Promise.resolve();let Q=USD();if(!Q.length)return Promise.resolve();H.info(Y),H.info(`Regions: ${Q.map((U)=>U.label).join(" • ")}`);let F=A0(),Z=Date.now(),w=Q.length,G=null;return new Promise((U)=>{let O=()=>{let q=Date.now()-Z,z=Math.max(0,$-q),B=OSD(q,w,$),W=Math.min(100,Math.round(q/$*100)),L=qSD(W),M=B<w?Q[B]?.label||"Finalizing":"Complete",I=`${B}/${w} regions updated • ${zSD(Math.ceil(z/1000))} left • ${L} • Next: ${M}`;F.message(I)};F.start(Y),O(),G=setInterval(O,X),setTimeout(()=>{if(G)clearInterval(G);F.stop(J),U()},$)})}kD();vD();X6();function oe(D){try{let $=eD(D);return q$(P7($,"patch"))}catch{let $=D.match(/^(\d+)\.(\d+)\.(\d+)/);if($){let[,X,Y,J]=$;return`${X}.${Y}.${Number.parseInt(J)+1}`}return"1.0.1"}}async function ae(D,$){let X=oe(D),Y=$?` for ${$}`:"",J=await t1({message:`How do you want to handle the version${Y}?`,options:[{value:"auto",label:`Auto: Bump patch version (${D} → ${X})`},{value:"manual",label:"Manual: I'll provide the version number"}]});if(bD(J))return null;if(J==="auto")return H.info(`\uD83D\uDD22 Auto-bumped version from ${D} to ${X}`),X;let Q=await k6({message:`Current version is ${D}. Enter new version:`,validate:(F)=>{if(!F)return"Version is required";if(!F.match(/^\d+\.\d+\.\d+/))return"Please enter a valid version (x.y.z)"}});if(bD(Q))return null;return Q}function te(D){let $=oe(D);try{let X=eD(D);return[$,q$(P7(X,"minor")),`${D}-beta.1`,`${D}.1`]}catch{return[$,`${D}.1`,`${D}-beta.1`,`${D}-rc.1`]}}import{readdirSync as se,readFileSync as BSD,statSync as WSD}from"node:fs";import{extname as KSD,join as HSD}from"node:path";function VSD(D,$){return BSD(D,"utf8").includes($)}function P2(D,$){let X=se(D);for(let Y of X){let J=HSD(D,Y),Q=WSD(J);if(Q.isDirectory()){if(P2(J,$))return!0}else if(Q.isFile()&&KSD(J)===".js"){if(VSD(J,$))return!0}}return!1}function tw(D){if(se(D).indexOf("index.html")>-1)return!0;return!1}vD();X6();var Q0D=V0(J0D(),1),F0D=V0(CY(),1);import{Buffer as duD}from"node:buffer";import{createHash as luD}from"node:crypto";import{createReadStream as XI,statSync as nuD}from"node:fs";import{platform as iuD}from"node:os";import{join as puD,posix as ruD,win32 as Y0D}from"node:path";import{cwd as ouD}from"node:process";import{buffer as JI}from"node:stream/consumers";import{createBrotliCompress as auD}from"node:zlib";kD();async function tuD(D,$){try{let X=new URL(`${D.hostFilesApi}/files/read/attachments/${encodeURIComponent($)}`);return X.searchParams.set("nocache",`${Date.now()}`),(await fetch(X.toString(),{method:"GET",headers:{range:"bytes=0-0","cache-control":"no-cache"}})).ok}catch{return!1}}var suD=8192;async function euD(D){let $=e0(ouD()),X=await y1("@capgo/capacitor-updater",$,D.packageJson),Y;try{Y=X?eD(X):void 0}catch{Y=void 0}if(!X||!Y)return{version:null,supportsBrotliV2:!1};let J=!w$(Y,void 0,void 0,z2);return{version:`${Y.major}.${Y.minor}.${Y.patch}`,supportsBrotliV2:J}}function DvD(D,$){if(!$)return!1;let X=$.split(",").map((Y)=>Y.trim()).filter((Y)=>!!Y);if(X.length===0)return!1;return Q0D.isMatch(D,X)}async function $vD(D,$,X){let J=nuD(D).size,Q=await JI(XI(D));if(J===0)return{buffer:Q,useBrotli:!1};if(DvD($,X.noBrotliPatterns))return{buffer:Q,useBrotli:!1};if(J<suD)return{buffer:Q,useBrotli:!1};try{let F=await JI(XI(D).pipe(auD({})));if(F.length>=J-10)return{buffer:Q,useBrotli:!1};return{buffer:F,useBrotli:!0}}catch(F){return H.warn(`Brotli compression failed for ${D}: ${F}, using original file`),{buffer:Q,useBrotli:!1}}}async function Z0D(D,$,X,Y,J,Q,F=!1){let Z=A0();Z.start(J!=="v2"?"Generating the update manifest":`Generating the update manifest with ${F?"V3":"V2"} encryption`);let w=await Xt(D);if(J==="v2")for(let G of w)G.hash=F?W7(G.hash,Q):B7(G.hash,Q);return Z.stop("Manifest generated successfully"),await AD($,{channel:"partial-update",event:"Generate manifest",icon:"\uD83D\uDCC2",user_id:X,tags:{"app-id":Y},notify:!1}),w}function XvD(D){if(iuD()!=="win32")return D;return Y0D.normalize(D).split(Y0D.sep).join(ruD.sep)}function JvD(D){let $=D.split("/").map((X)=>encodeURIComponent(X)).join("/");if(D.includes(" "))H.warn(`File "${D}" contains spaces in its name.`);return $}async function w0D(D,$,X,Y,J,Q,F){let Z=A0();Z.start("Preparing partial update with TUS protocol");let w=performance.now(),G=await v$(),U=!!(F.partial||F.delta||F.partialOnly||F.deltaOnly),{version:O,supportsBrotliV2:q}=await euD(F);if(!q)throw Error(`Your project is using an older version of @capgo/capacitor-updater (${O||"unknown"}). To use Delta updates, please upgrade to version ${Ww} (v5), ${Kw} (v6) or ${z2} (v7) or higher.`);else if(F.disableBrotli)H.info("Brotli compression disabled by user request");else if(F.noBrotliPatterns)H.info(`Files matching patterns (${F.noBrotliPatterns}) will be excluded from brotli compression`);let z=$.filter((M)=>M.file.includes(" "));if(z.length>0)throw Error(`Files with spaces in their names (${z.map((M)=>M.file).join(", ")}). Please rename the files.`);let B=0,W=$.length,L=0;try{Z.message(`Uploading ${W} files using TUS protocol`);let M=async(R)=>{let C=puD(X,R.file),A=XvD(R.file),_,u=!1;if(F.disableBrotli)_=await JI(XI(C)),u=!1;else{let j=await $vD(C,A,F);_=j.buffer,u=j.useBrotli}let x=_;if(Q)x=z7(_,Q.sessionKey,Q.ivSessionKey);let h=A;if(u)h=`${A}.br`,L++;let b=JvD(h),l=luD("sha256").update(R.hash).digest("hex"),f;if(Q){let j=duD.from(Q.ivSessionKey).toString("hex");f=`orgs/${J}/apps/${Y}/delta/${j}/${l}_${b}`}else f=`orgs/${J}/apps/${Y}/delta/${l}_${b}`;if(!Q&&await tuD(G,f))return B++,Promise.resolve({file_name:b,s3_path:f,file_hash:R.hash});return new Promise((j,S)=>{Z.message(`Prepare upload partial file: ${A}`);let v=L4(h);new F0D.Upload(x,{endpoint:`${G.hostFilesApi}/files/upload/attachments/`,chunkSize:F.tusChunkSize,retryDelays:[0,1000,3000,5000,1e4],removeFingerprintOnSuccess:!0,metadata:{filename:f,filetype:v},headers:{Authorization:D},onError:(g)=>{let d=g.toString(),a;try{let r=d.match(/response text: (\{.*?\})/);if(r&&r[1])a=JSON.parse(r[1]).moreInfo?.requestId}catch{}let m=a?` [requestId: ${a}]`:"";H.error(`Failed to upload ${A}: ${d}${m}`),S(g)},onProgress(){let g=(B/W*100).toFixed(2);Z.message(`Uploading partial update: ${g}%`)},onSuccess(){B++,j({file_name:b,s3_path:f,file_hash:R.hash})}}).start()})},I=500,K=[];for(let R=0;R<$.length;R+=I){let C=$.slice(R,R+I),A=Math.floor(R/I)+1,_=Math.ceil($.length/I);if(_>1)Z.message(`Processing batch ${A}/${_} (${C.length} files)`);let u=await Promise.all(C.map((x)=>M(x)));K.push(...u)}let N=((performance.now()-w)/1000).toFixed(2);if(Z.stop(`Partial update uploaded successfully \uD83D\uDCAA in (${N} seconds)`),L>0)H.info(`${L} of ${W} files were compressed with brotli and use .br extension`);return await AD(D,{channel:"app",event:`App Partial TUS done${L>0?" with .br extension":""}`,icon:"⏫",user_id:J,tags:{"app-id":Y},notify:!1}),await AD(D,{channel:"performance",event:"Partial upload performance",icon:"\uD83D\uDE84",user_id:J,tags:{"app-id":Y,time:N},notify:!1}),K}catch(M){let K=((performance.now()-w)/1000).toFixed(2);if(Z.error(`Failed to upload Partial bundle (after ${K} seconds)`),U)throw H.error(`Error uploading partial update: ${M}`),H.error("Delta/partial upload was explicitly requested but failed. Upload aborted."),M;else return H.info(`Error uploading partial update: ${M}, This is not a critical error, the bundle has been uploaded without the partial files`),null}}function H0(D){throw H.error(D),Error(D)}function wvD(D){let $=new R0;$.headers=["Package","Local","Remote","Status","Details"],$.theme=R0.roundTheme,$.rows=[];for(let X of D){let{name:Y,localVersion:J,remoteVersion:Q}=X,F=k8(X),Z=F.compatible?"✅":"❌";$.rows.push([Y,J||"-",Q||"-",Z,F.message])}H.info($.toString())}async function GvD(D,$){let X=N4("",$.packageJson),Y=$.bundle||D?.plugins?.CapacitorUpdater?.version||X||`0.0.1-beta.${YvD().split("-")[0]}`;if(!e5.test(Y))H0(`Your bundle name ${Y}, is not valid it should follow semver convention : https://semver.org/`);return Y}function UvD(D){let $=D.apikey||WD();if(!$)H0("Missing API key, you need to provide an API key to upload your bundle");return $}function OvD(D,$,X){let Y=mD(D,X),J=$.path||X?.webDir;if(!Y)H0("Missing argument, you need to provide a appid or be in a capacitor project");if(!J)H0("Missing argument, you need to provide a path (--path), or be in a capacitor project");if(!YG(J))H0(`Path ${J} does not exist, build your app first, or provide a valid path`);return{appid:Y,path:J}}function qvD(D,$){let X=D.codeCheck;if(typeof X>"u"||X){if(!P2($,"notifyAppReady"))H0(`notifyAppReady() is missing in the build folder of your app. see: https://capgo.app/docs/plugin/api/#notifyappready
479
479
  If you are sure your app has this code, you can use the --no-code-check option`);if(!tw($))H0(`index.html is missing in the root folder of ${$}`)}}async function zvD(D,$,X,Y,J,Q){let{ignoreMetadataCheck:F,autoMinUpdateVersion:Z,minUpdateVersion:w}=X,{data:G,error:U}=await D.from("channels").select("disable_auto_update, version ( min_update_version, native_packages )").eq("name",Y).eq("app_id",J).single(),O=!!G&&G.disable_auto_update==="version_number",q,z;if(!U&&G&&G.version&&G.version.native_packages&&!F){let L=A0();L.start(`Checking bundle compatibility with channel ${Y}`);let{finalCompatibility:M,localDependencies:I}=await Lw(D,J,Y,X.packageJson,X.nodeModules);if(z=M,q=I,z.filter((V)=>!M4(V)).length>0){if(L.error(`Bundle NOT compatible with ${Y} channel`),H.warn(""),wvD(z),H.warn(""),H.warn("An app store update may be required for these changes to take effect."),Z)w=Q,H.info(`Auto set min-update-version to ${w}`)}else if(Z)try{let{min_update_version:V}=G.version;if(!V||!e5.test(V))H0("Invalid remote min update version, skipping auto setting compatibility");w=V,L.stop(`Auto set min-update-version to ${w}`)}catch{H0(`Cannot auto set compatibility, invalid data ${G}`)}else L.stop(`Bundle compatible with ${Y} channel`)}else if(!F){if(H.warn(`Channel ${Y} is new or it's your first upload with compatibility check, it will be ignored this time`),q=await oL(X.packageJson,X.nodeModules),Z)w=Q,H.info(`Auto set min-update-version to ${w}`)}if(O&&!w&&!F)H0("You need to provide a min-update-version to upload a bundle to this channel");if(w){if(!e5.test(w))H0(`Your minimal version update ${w}, is not valid it should follow semver convention : https://semver.org/`)}let B=q?new Map(q.filter((L)=>!!L.native&&L.native!==void 0).map((L)=>[L.name,L])):new Map;return{nativePackages:B.size>0||!X.ignoreMetadataCheck?Array.from(B,([L,M])=>({name:L,version:M.version,...M.ios_checksum&&{ios_checksum:M.ios_checksum},...M.android_checksum&&{android_checksum:M.android_checksum}})):void 0,minUpdateVersion:w}}async function BvD(D,$,X,Y=!1,J=!1){let{data:Q,error:F}=await D.rpc("exist_app_versions",{appid:$,name_version:X}).single();if(Q||F){if(Y)return H.warn(`Version ${X} already exists - exiting gracefully due to --silent-fail option`),ND("Bundle version already exists - exiting gracefully \uD83C\uDF89"),!0;if(J){H.error(`❌ Version ${X} already exists`);let Z=te(X);H.info("\uD83D\uDCA1 Here are some suggestions:"),Z.forEach((U,O)=>{H.info(` ${O+1}. ${U}`)});let w=await t1({message:"What would you like to do?",options:[{value:"suggest1",label:`Use ${Z[0]}`},{value:"suggest2",label:`Use ${Z[1]}`},{value:"suggest3",label:`Use ${Z[2]}`},{value:"suggest4",label:`Use ${Z[3]}`},{value:"custom",label:"Enter a custom version"},{value:"cancel",label:"Cancel upload"}]});if(bD(w)||w==="cancel")H0("Upload cancelled by user");let G;if(w==="custom"){let U=await ae(X,"upload");if(!U)H0("Upload cancelled by user");G=U}else{let U=Number.parseInt(w.replace("suggest",""))-1;G=Z[U]}return H.info(`\uD83D\uDD04 Retrying with new version: ${G}`),G}H0(`Version ${X} already exists ${s(F)}`)}return!1}async function WvD(D,$,X,Y,J,Q,F,Z){let w,G,U="",O=null,q="none",z="",B="",W=$.keyV2,L=$.key===!1,M=A0();M.start(`Zipping bundle from ${D}`),O=await Hw(D),M.message("Calculating checksum");let I=e0(YI()),K=await y1("@capgo/capacitor-updater",I,$.packageJson),V=!1,N;try{N=K?eD(K):void 0}catch{N=void 0}if(!K)H0("Cannot find @capgo/capacitor-updater in node_modules, please install it first with your package manager");else if(N)V=!w$(N,Ww,Kw,z2);else if(K==="link:@capgo/capacitor-updater"||K==="file:.."||K==="file:../")H.warn("Using local @capgo/capacitor-updater. Assuming latest version for checksum calculation."),V=!0;let R=$.forceCrc32Checksum===!0,C=!R&&((W||$.keyDataV2||YG(i1))&&!L||V);if(U=await p6(O,C?"sha256":"crc32"),M.stop(`Checksum ${C?"SHA256":"CRC32"}${R?" (forced)":""}: ${U}`),L)H.info("Encryption ignored");else if((W||YG(i1)||$.keyDataV2)&&!$.oldEncryption){let u=typeof W==="string"?W:i1,x=$.keyDataV2||"";if(!x&&!YG(u))H0(`Cannot find private key ${u}`);if(await AD(X,{channel:"app",event:"App encryption v2",icon:"\uD83D\uDD11",user_id:Y,tags:{"app-id":J},notify:!1},$.verbose),!x)x=QvD(u).toString();let h=N&&!w$(N,"5.30.0","6.30.0","7.30.0");H.info(`Encrypting your bundle with ${h?"V3":"V2"}`);let{sessionKey:b,ivSessionKey:l}=dw(x),f=z7(O,b,l);if(U=h?W7(U,x):B7(U,x),w=l,G=b,q="v2",z=x,Z){if(B=Ve(Z),$.verbose)H.info(`[Verbose] Encryption key_id: ${B}`)}if($.displayIvSession)H.info(`Your Iv Session key is ${w},
480
480
  keep it safe, you will need it to decrypt your bundle.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@capgo/cli",
3
3
  "type": "module",
4
- "version": "7.88.0",
4
+ "version": "7.88.2",
5
5
  "description": "A CLI to upload to capgo servers",
6
6
  "author": "Martin martin@capgo.app",
7
7
  "license": "Apache 2.0",
@@ -81,7 +81,7 @@
81
81
  },
82
82
  "devDependencies": {
83
83
  "@antfu/eslint-config": "^7.0.0",
84
- "@bradenmacdonald/s3-lite-client": "npm:@jsr/bradenmacdonald__s3-lite-client@0.9.4",
84
+ "@bradenmacdonald/s3-lite-client": "npm:@jsr/bradenmacdonald__s3-lite-client@0.9.5",
85
85
  "@capacitor/cli": "^8.0.0",
86
86
  "@capgo/find-package-manager": "^0.0.18",
87
87
  "@clack/prompts": "^1.0.0",
@@ -9,13 +9,14 @@ Use this skill for Capgo Cloud native iOS and Android build workflows.
9
9
 
10
10
  ## Onboarding (automated iOS setup)
11
11
 
12
- ### `build onboarding`
12
+ ### `build init` (alias: `build onboarding`)
13
13
 
14
14
  - Interactive command that automates iOS certificate and provisioning profile creation.
15
15
  - Reduces iOS setup from ~10 manual steps to 1 manual step (creating an API key) + 1 command.
16
- - Example: `npx @capgo/cli@latest build onboarding`
16
+ - Example: `npx @capgo/cli@latest build init`
17
+ - Backward compatibility: `npx @capgo/cli@latest build onboarding` still works.
17
18
  - Notes:
18
- - Uses Ink (React for terminal) for the interactive UI only command that uses Ink; all other commands use `@clack/prompts`.
19
+ - Uses Ink (React for terminal) for the interactive UI, alongside the main `init` onboarding flow.
19
20
  - Requires running inside a Capacitor project directory with an `ios/` folder.
20
21
  - The user creates ONE App Store Connect API key (.p8 file), then the CLI handles everything else.
21
22
  - On macOS, offers a native file picker dialog for .p8 selection.
@@ -24,7 +24,7 @@ TanStack Intent skills should stay focused and under the validator line limit, s
24
24
 
25
25
  ### Project setup and diagnostics
26
26
 
27
- - `init [apikey] [appId]`: guided first-time setup for Capgo in a Capacitor app. In interactive use, onboarding can also offer a final `npx skills add https://github.com/Cap-go/capgo-skills -g -y` install step before the GitHub support prompt; if accepted, the support menu includes `Cap-go/capgo-skills` alongside the updater-only and all-Capgo choices. If iOS sync validation fails during onboarding, the CLI can offer to run a one-line native reset command, wait for you to type `ready` after a manual fix, and offer cancellation every third failed retry.
27
+ - `init [apikey] [appId]`: guided first-time setup for Capgo in a Capacitor app. The interactive flow now runs as a real Ink-based fullscreen onboarding so it uses the same UI stack as `build init` (alias: `build onboarding`), with a persistent dashboard, phase roadmap, progress cards, shared log area, and resume support. When dependency auto-detection fails on macOS, the flow opens a native file picker for `package.json` before falling back to manual path entry. If the user reuses a pending app that was already created in the web onboarding flow, the CLI syncs that selected dashboard app ID back into `capacitor.config.*` before the remaining steps continue. Outside that reused pending-app path, the CLI keeps using the local Capacitor app ID. It can also offer a final `npx skills add https://github.com/Cap-go/capgo-skills -g -y` install step before the GitHub support prompt; if accepted, the support menu includes `Cap-go/capgo-skills` alongside the updater-only and all-Capgo choices. If iOS sync validation fails during onboarding, the CLI can offer to run a one-line native reset command, wait for you to type `ready` after a manual fix, and offer cancellation every third failed retry.
28
28
  - `login [apikey]`: store an API key locally.
29
29
  - `doctor`: inspect installation health and gather troubleshooting details.
30
30
  - `probe`: test whether the update endpoint would deliver an update.