@capgo/cli 7.21.1 → 7.21.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/package.json
CHANGED
|
@@ -9,6 +9,6 @@ interface PartialEncryptionOptions {
|
|
|
9
9
|
sessionKey: Buffer;
|
|
10
10
|
ivSessionKey: string;
|
|
11
11
|
}
|
|
12
|
-
export declare function uploadPartial(apikey: string, manifest: manifestType, path: string, appId: string,
|
|
12
|
+
export declare function uploadPartial(apikey: string, manifest: manifestType, path: string, appId: string, orgId: string, encryptionOptions: PartialEncryptionOptions | undefined, options: OptionsUpload): Promise<any[] | null>;
|
|
13
13
|
export {};
|
|
14
14
|
//# sourceMappingURL=partial.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"partial.d.ts","sourceRoot":"","sources":["../../../src/bundle/partial.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AAC5C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAyHvD,wBAAsB,yBAAyB,CAC7C,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,gBAAgB,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,EACtC,YAAY,EAAE,MAAM;;;KA0BrB;AAoBD,UAAU,wBAAwB;IAChC,UAAU,EAAE,MAAM,CAAA;IAClB,YAAY,EAAE,MAAM,CAAA;CACrB;AAED,wBAAsB,aAAa,CACjC,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,YAAY,EACtB,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,
|
|
1
|
+
{"version":3,"file":"partial.d.ts","sourceRoot":"","sources":["../../../src/bundle/partial.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AAC5C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAyHvD,wBAAsB,yBAAyB,CAC7C,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,gBAAgB,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,EACtC,YAAY,EAAE,MAAM;;;KA0BrB;AAoBD,UAAU,wBAAwB;IAChC,UAAU,EAAE,MAAM,CAAA;IAClB,YAAY,EAAE,MAAM,CAAA;CACrB;AAED,wBAAsB,aAAa,CACjC,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,YAAY,EACtB,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,iBAAiB,EAAE,wBAAwB,GAAG,SAAS,EACvD,OAAO,EAAE,aAAa,GACrB,OAAO,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CA0MvB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../../../src/bundle/upload.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAcvD,OAAO,EAAmG,oBAAoB,EAAob,MAAM,UAAU,CAAA;AAIlkB,KAAK,YAAY,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,oBAAoB,CAAC,CAAC,CAAA;AAIpE,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,OAAO,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACxB,gBAAgB,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAAA;IACtC,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC5B,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAujBD,wBAAsB,uBAAuB,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,0BAanG;AAED,wBAAsB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,UAAQ,GAAG,OAAO,CAAC,kBAAkB,CAAC,
|
|
1
|
+
{"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../../../src/bundle/upload.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAcvD,OAAO,EAAmG,oBAAoB,EAAob,MAAM,UAAU,CAAA;AAIlkB,KAAK,YAAY,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,oBAAoB,CAAC,CAAC,CAAA;AAIpE,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,OAAO,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACxB,gBAAgB,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAAA;IACtC,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC5B,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAujBD,wBAAsB,uBAAuB,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,0BAanG;AAED,wBAAsB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,UAAQ,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAudhI;AA2CD,wBAAsB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,iBASvE"}
|
package/dist/src/sdk.js
CHANGED
|
@@ -280,7 +280,7 @@ ${Y.default.gray(uu)} ${t}
|
|
|
280
280
|
`);let y=0,C=0;f(),s=setInterval(()=>{if(n&&a===u)return;g(),u=a;let k=Y.default.magenta(e[y]);if(n)process.stdout.write(`${k} ${a}...`);else if(t==="timer")process.stdout.write(`${k} ${a} ${S(c)}`);else{let v=".".repeat(Math.floor(C)).slice(0,3);process.stdout.write(`${k} ${a}${v}`)}y=y+1<e.length?y+1:0,C=C<e.length?C+.125:0},r)},p=(D="",y=0)=>{o=!1,clearInterval(s),g();let C=y===0?Y.default.green(bm):y===1?Y.default.red(WE):Y.default.red(XE);a=b(D??a),t==="timer"?process.stdout.write(`${C} ${a} ${S(c)}
|
|
281
281
|
`):process.stdout.write(`${C} ${a}
|
|
282
282
|
`),m(),i()};return{start:A,stop:p,message:(D="")=>{a=b(D??a)}}};function YE(t,e){let n=["normal","bold","dim","italic","underline","strikethrough"].indexOf(t),i="\x1B[";return i+n+"m"+e+i+"0m"}var Ht=class t{title=null;headers=[];rows=[];static narrowTheme={top:["\u2554","\u2550","\u2564","\u2557"],row:["\u2551"," ","\u2502","\u2551"],div:["\u255F","\u2500","\u253C","\u2562"],bot:["\u255A","\u2550","\u2567","\u255D"]};static wideTheme={top:["\u2554\u2550","\u2550","\u2550\u2564\u2550","\u2550\u2557"],row:["\u2551 "," "," \u2502 "," \u2551"],div:["\u255F\u2500","\u2500","\u2500\u253C\u2500","\u2500\u2562"],bot:["\u255A\u2550","\u2550","\u2550\u2567\u2550","\u2550\u255D"]};static roundTheme={top:["\u256D\u2500","\u2500","\u2500\u252C\u2500","\u2500\u256E"],row:["\u2502 "," "," \u2502 "," \u2502"],div:["\u251C\u2500","\u2500","\u2500\u253C\u2500","\u2500\u2524"],bot:["\u2570\u2500","\u2500","\u2500\u2534\u2500","\u2500\u256F"]};theme=t.wideTheme;columnWidth(){let e=[this.headers,...this.rows].filter(n=>n.length>0),r=e[0].map(n=>this.cast(n).length);for(let n of e.slice(1))for(let i=0;i<r.length;i++){let s=this.cast(n[i]).length;s>r[i]&&(r[i]=s)}return r}cast(e){return typeof e=="object"?"obj":e!==void 0&&typeof e.toString=="function"?e.toString():""}renderTitle(){return"[ "+this.title+" ]"}renderLine(e){let r=this.columnWidth();return e[0]+r.map(n=>e[1].repeat(n)).join(e[2])+e[3]}renderCell(e,r,n=!1){let i=this.cast(e),s=n?YE("bold",i):i,o=r-i.length,a=this.theme.row[1];switch(typeof e){case"number":return a.repeat(o)+s;case"string":return s+a.repeat(o);case"boolean":case"object":return a.repeat(Math.ceil(o/2))+YE("italic",i)+a.repeat(Math.floor(o/2));default:return a.repeat(o)}}renderRow(e,r=!1){let n=this.theme.row,i=this.columnWidth();return n[0]+e.map((s,o)=>this.renderCell(s,i[o],r)).join(n[2])+n[3]}toString(){let e=this.theme,r=this.headers.length>0,n=this.rows.length>0;return[this.title?this.renderTitle():"",r||n?this.renderLine(e.top):"",r?this.renderRow(this.headers,!0):"",r&&n?this.renderLine(e.div):"",...this.rows.map(i=>this.renderRow(i)),r||n?this.renderLine(e.bot):""].filter(i=>i.length>0).join(`
|
|
283
|
-
`)}};var $8=require("node:child_process"),At=require("node:fs"),Ip=require("node:os"),Tt=xe(require("node:path")),di=require("node:process"),ns=xe(Sl());var Jt=require("fs"),lu=(t=".",e="unknown")=>{let r=`${t}/bun.lockb`,n=`${t}/bun.lock`,i=`${t}/pnpm-lock.yaml`,s=`${t}/shrinkwrap.yaml`,o=`${t}/yarn.lock`,a=`${t}/package-lock.json`,u=`${t}/npm-shrinkwrap.json`;return(0,Jt.existsSync)(r)||(0,Jt.existsSync)(n)?"bun":(0,Jt.existsSync)(i)||(0,Jt.existsSync)(s)?"pnpm":(0,Jt.existsSync)(o)?"yarn":(0,Jt.existsSync)(a)||(0,Jt.existsSync)(u)?"npm":e},Al=(t=lu(),e=!1)=>{switch(t){case"bun":return e?"bun install":"install";case"pnpm":return e?"pnpm install":"install";case"yarn":return e?"yarn install":"install";case"npm":return e?"npm install":"install";case"unknown":return e?"unknown unknown":"unknown";default:return e?"npm install":"install"}},JE=(t=".",e="npx")=>{let r=`${t}/bun.lockb`,n=`${t}/bun.lock`,i=`${t}/pnpm-lock.yaml`,s=`${t}/shrinkwrap.yaml`,o=`${t}/yarn.lock`,a=`${t}/package-lock.json`,u=`${t}/npm-shrinkwrap.json`;return(0,Jt.existsSync)(r)||(0,Jt.existsSync)(n)?"bunx":(0,Jt.existsSync)(i)||(0,Jt.existsSync)(s)?"pnpm exec":(0,Jt.existsSync)(o)?"yarn dlx":(0,Jt.existsSync)(a)||(0,Jt.existsSync)(u)?"npx":e};function Ol(t,e){if(isNaN(t)||isNaN(e))throw new Error("Cannot compare against non-numbers");return t===e?0:t<e?-1:1}function e_(t=[],e=[]){return t.length&&!e.length?-1:!t.length&&e.length?1:0}function Sm(t=[],e=[]){let r=Math.max(t.length,e.length);for(let n=0;n<r;n++){let i=t[n],s=e[n];if(i===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(i===void 0)return-1;if(typeof i=="string"&&typeof s=="number")return 1;if(typeof i=="number"&&typeof s=="string"||i<s)return-1;if(i>s)return 1}return 0}var wo="0|[1-9]\\d*",yU="\\d*[a-zA-Z-][a-zA-Z0-9-]*",DU=`(?<major>${wo})\\.(?<minor>${wo})\\.(?<patch>${wo})`,ZE=`(?:${wo}|${yU})`,t_=`(?:-(?<prerelease>${ZE}(?:\\.${ZE})*))`,QE="[0-9A-Za-z-]+",r_=`(?:\\+(?<buildmetadata>${QE}(?:\\.${QE})*))`,n_=`v?${DU}${t_}?${r_}?`,i_=new RegExp(`^${n_}$`),s_="(?:<|>)?=?",wU="x|X|\\*",Cm=`${wo}|${wU}`,xl=`[v=\\s]*(?<major>${Cm})(?:\\.(?<minor>${Cm})(?:\\.(?<patch>${Cm})${t_}?${r_}?)?)?`,o_=new RegExp(`^(?<operator>~>?|\\^|${s_})\\s*${xl}$`),a_=new RegExp(`^(?<operator>${s_})\\s*(${n_})$|^$`);function Am(t){return typeof t=="number"&&!Number.isNaN(t)&&(!Number.isFinite(t)||0<=t&&t<=Number.MAX_SAFE_INTEGER)}var Om=256;var bU=new RegExp(`^${wo}$`);function Zt(t){return t.split(".").filter(Boolean).map(e=>{if(bU.test(e)){let r=Number(e);if(Am(r))return r}return e})}function Zr(t){return t.split(".").filter(Boolean)}function Ei(t,e){let r=Number(t);if(!Am(r))throw new TypeError(e);return r}function Un(t){return Number.isNaN(t.major)&&Number.isNaN(t.minor)&&Number.isNaN(t.patch)&&(t.prerelease===void 0||t.prerelease.length===0)&&(t.build===void 0||t.build.length===0)}function Qt(t,e){return t===e?0:Ol(t.major,e.major)||Ol(t.minor,e.minor)||Ol(t.patch,e.patch)||e_(t.prerelease,e.prerelease)||Sm(t.prerelease,e.prerelease)}function xm(t){return t.toFixed(0)}function _i(t){let e=xm(t.major),r=xm(t.minor),n=xm(t.patch),i=t.prerelease?.join(".")??"",s=t.build?.join(".")??"";return[[`${e}.${r}.${n}`,i].filter(u=>u).join("-"),s].filter(u=>u).join("+")}function vU(t,e){if(Un(e))return!0;let r=Qt(t,e);switch(e.operator){case"=":case void 0:return r===0;case"!=":return r!==0;case">":return r>0;case"<":return r<0;case">=":return r>=0;case"<=":return r<=0}}function Tl(t,e){for(let r of e)if(!vU(t,r))return!1;if(t.prerelease&&t.prerelease.length>0){for(let r of e){if(Un(r))continue;let{major:n,minor:i,patch:s,prerelease:o}=r;if(o&&o.length>0&&t.major===n&&t.minor===i&&t.patch===s)return!0}return!1}return!0}function fu(t,e){return e.some(r=>Tl(t,r))}function EU(t=[]){let e=[...t],r=e.length;for(;r>=0;){let n=e[r];if(typeof n=="number"){e[r]=n+1;break}r-=1}return r===-1&&e.push(0),e}function hu(t=[],e){let r=EU(t);if(!e)return r;let n=Zt(e);if(n.every(i=>typeof i=="string")){if(n.every((i,s)=>i===r[s])&&typeof r[n.length]=="number")return r;n=[...n,0]}return n}function u_(t,e,r={}){let n=r.build!==void 0?Zr(r.build):t.build??[];switch(e){case"premajor":return{major:t.major+1,minor:0,patch:0,prerelease:hu(t.prerelease,r.prerelease),build:n};case"preminor":return{major:t.major,minor:t.minor+1,patch:0,prerelease:hu(t.prerelease,r.prerelease),build:n};case"prepatch":return{major:t.major,minor:t.minor,patch:t.patch+1,prerelease:hu(t.prerelease,r.prerelease),build:n};case"prerelease":{let s=(t.prerelease??[]).length===0?t.patch+1:t.patch;return{major:t.major,minor:t.minor,patch:s,prerelease:hu(t.prerelease,r.prerelease),build:n}}case"major":return{major:(t.prerelease??[]).length===0||t.minor!==0||t.patch!==0?t.major+1:t.major,minor:0,patch:0,prerelease:[],build:n};case"minor":{let s=(t.prerelease??[]).length===0||t.patch!==0?t.minor+1:t.minor;return{major:t.major,minor:s,patch:0,prerelease:[],build:n}}case"patch":{let s=(t.prerelease??[]).length===0?t.patch+1:t.patch;return{major:t.major,minor:t.minor,patch:s,prerelease:[],build:n}}case"pre":return{major:t.major,minor:t.minor,patch:t.patch,prerelease:hu(t.prerelease,r.prerelease),build:n};default:throw new TypeError(`Cannot increment version: invalid argument ${e}`)}}var Fl={major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]},bo={operator:void 0,...Fl};function Tm(t,e){return Qt(t,e)>0}function Fm(t,e){return Qt(t,e)<0}function _U(t){let r=t.match(a_)?.groups;if(!r)return null;let{operator:n,prerelease:i,buildmetadata:s}=r,o=r.major?{major:Ei(r.major,`Cannot parse comparator ${t}: invalid major version`),minor:Ei(r.minor,`Cannot parse comparator ${t}: invalid minor version`),patch:Ei(r.patch,`Cannot parse comparator ${t}: invalid patch version`),prerelease:i?Zt(i):[],build:s?Zr(s):[]}:Fl;return{operator:n||void 0,...o}}function qe(t){return!t||t.toLowerCase()==="x"||t==="*"}function CU(t){if(!qe(t.major))return qe(t.minor)?{operator:">=",major:+t.major,minor:0,patch:0,prerelease:[],build:[]}:qe(t.patch)?{operator:">=",major:+t.major,minor:+t.minor,patch:0,prerelease:[],build:[]}:{operator:">=",major:+t.major,minor:+t.minor,patch:+t.patch,prerelease:t.prerelease?Zt(t.prerelease):[],build:[]}}function SU(t){if(!qe(t.major))return qe(t.minor)?{operator:"<",major:+t.major+1,minor:0,patch:0,prerelease:[],build:[]}:qe(t.patch)?{operator:"<",major:+t.major,minor:+t.minor+1,patch:0,prerelease:[],build:[]}:t.prerelease?{operator:"<=",major:+t.major,minor:+t.minor,patch:+t.patch,prerelease:Zt(t.prerelease),build:[]}:{operator:"<=",major:+t.major,minor:+t.minor,patch:+t.patch,prerelease:[],build:[]}}function AU(t){let e=t.match(new RegExp(`^${xl}`)),r=e?.groups;if(!r)return null;let n=e[0].length,i=t.slice(n).match(/^\s+-\s+/);if(!i)return null;let s=i[0].length,a=t.slice(n+s).match(new RegExp(`^${xl}\\s*$`))?.groups;if(!a)return null;let u=CU(r),c=SU(a);return[u,c].filter(Boolean)}function OU(t){let e=qe(t.major),r=qe(t.minor),n=qe(t.patch),i=+t.major,s=+t.minor,o=+t.patch;if(e)return[bo];if(r)return[{operator:">=",major:i,minor:0,patch:0},{operator:"<",major:i+1,minor:0,patch:0}];if(n)return i===0?[{operator:">=",major:i,minor:s,patch:0},{operator:"<",major:i,minor:s+1,patch:0}]:[{operator:">=",major:i,minor:s,patch:0},{operator:"<",major:i+1,minor:0,patch:0}];let a=Zt(t.prerelease??"");return i===0?s===0?[{operator:">=",major:i,minor:s,patch:o,prerelease:a},{operator:"<",major:i,minor:s,patch:o+1}]:[{operator:">=",major:i,minor:s,patch:o,prerelease:a},{operator:"<",major:i,minor:s+1,patch:0}]:[{operator:">=",major:i,minor:s,patch:o,prerelease:a},{operator:"<",major:i+1,minor:0,patch:0}]}function xU(t){let e=qe(t.major),r=qe(t.minor),n=qe(t.patch),i=+t.major,s=+t.minor,o=+t.patch;if(e)return[bo];if(r)return[{operator:">=",major:i,minor:0,patch:0},{operator:"<",major:i+1,minor:0,patch:0}];if(n)return[{operator:">=",major:i,minor:s,patch:0},{operator:"<",major:i,minor:s+1,patch:0}];let a=Zt(t.prerelease??"");return[{operator:">=",major:i,minor:s,patch:o,prerelease:a},{operator:"<",major:i,minor:s+1,patch:0}]}function TU(t){let e=qe(t.major),r=qe(t.minor),n=qe(t.patch),i=+t.major,s=+t.minor,o=+t.patch;if(e)return[{operator:"<",major:0,minor:0,patch:0}];if(r)return n?[{operator:"<",major:i,minor:0,patch:0}]:[{operator:"<",major:i,minor:0,patch:0}];if(n)return[{operator:"<",major:i,minor:s,patch:0}];let a=Zt(t.prerelease??""),u=Zr(t.build??"");return[{operator:"<",major:i,minor:s,patch:o,prerelease:a,build:u}]}function FU(t){let e=qe(t.minor),r=qe(t.patch),n=+t.major,i=+t.minor,s=+t.patch;if(e)return r?[{operator:"<",major:n+1,minor:0,patch:0}]:[{operator:"<",major:n,minor:i+1,patch:0}];if(r)return[{operator:"<",major:n,minor:i+1,patch:0}];let o=Zt(t.prerelease??""),a=Zr(t.build??"");return[{operator:"<=",major:n,minor:i,patch:s,prerelease:o,build:a}]}function IU(t){let e=qe(t.major),r=qe(t.minor),n=qe(t.patch),i=+t.major,s=+t.minor,o=+t.patch;if(e)return[{operator:"<",major:0,minor:0,patch:0}];if(r)return[{operator:">=",major:i+1,minor:0,patch:0}];if(n)return[{operator:">=",major:i,minor:s+1,patch:0}];let a=Zt(t.prerelease??""),u=Zr(t.build??"");return[{operator:">",major:i,minor:s,patch:o,prerelease:a,build:u}]}function kU(t){let e=qe(t.major),r=qe(t.minor),n=qe(t.patch),i=+t.major,s=+t.minor,o=+t.patch;if(e)return[bo];if(r)return n?[{operator:">=",major:i,minor:0,patch:0}]:[{operator:">=",major:i,minor:0,patch:0}];if(n)return[{operator:">=",major:i,minor:s,patch:0}];let a=Zt(t.prerelease??""),u=Zr(t.build??"");return[{operator:">=",major:i,minor:s,patch:o,prerelease:a,build:u}]}function PU(t){let e=qe(t.major),r=qe(t.minor),n=qe(t.patch),i=+t.major,s=+t.minor,o=+t.patch;if(e)return[bo];if(r)return[{operator:">=",major:i,minor:0,patch:0},{operator:"<",major:i+1,minor:0,patch:0}];if(n)return[{operator:">=",major:i,minor:s,patch:0},{operator:"<",major:i,minor:s+1,patch:0}];let a=Zt(t.prerelease??""),u=Zr(t.build??"");return[{operator:void 0,major:i,minor:s,patch:o,prerelease:a,build:u}]}function RU(t){let e=t.match(o_)?.groups;if(!e)return _U(t);switch(e.operator){case"^":return OU(e);case"~":case"~>":return xU(e);case"<":return TU(e);case"<=":return FU(e);case">":return IU(e);case">=":return kU(e);case"=":case"":return PU(e);default:throw new Error(`Cannot parse version range: '${e.operator}' is not a valid operator`)}}function NU(t){return t.split(/\s+/).flatMap(RU)}function Il(t){let e=t.replaceAll(/(?<=<|>|=|~|\^)(\s+)/g,"").split(/\s*\|\|\s*/).map(r=>AU(r)||NU(r));if(e.some(r=>r.includes(null)))throw new TypeError(`Cannot parse version range: range "${t}" is invalid`);return e}function Et(t){if(typeof t!="string")throw new TypeError(`Cannot parse version as version must be a string: received ${typeof t}`);if(t.length>Om)throw new TypeError(`Cannot parse version as version length is too long: length is ${t.length}, max length is ${Om}`);t=t.trim();let e=t.match(i_)?.groups;if(!e)throw new TypeError(`Cannot parse version: ${t}`);let r=Ei(e.major,`Cannot parse version ${t}: invalid major version`),n=Ei(e.minor,`Cannot parse version ${t}: invalid minor version`),i=Ei(e.patch,`Cannot parse version ${t}: invalid patch version`),s=e.prerelease?Zt(e.prerelease):[],o=e.buildmetadata?Zr(e.buildmetadata):[];return{major:r,minor:n,patch:i,prerelease:s,build:o}}function c_(t,e){let r=t.operator,n=e.operator;if(r===void 0)return Un(t)?!0:fu(t,[[e]]);if(n===void 0)return Un(e)?!0:fu(e,[[t]]);let i=Qt(t,e);return(r===">="||r===">")&&(n===">="||n===">")||(r==="<="||r==="<")&&(n==="<="||n==="<")||i===0&&((r===">="||r==="<=")&&(n===">="||n==="<="))||i===-1&&(r===">="||r===">")&&(n==="<="||n==="<")||i===1&&(r==="<="||r==="<")&&(n===">="||n===">")}function $U(t){return t.every(e=>e.some(r=>LU(r)))}function LU(t){for(let e=0;e<t.length-1;e++){let r=t[e];for(let n of t.slice(e+1))if(!c_(r,n))return!1}return!0}function l_(t,e){return $U([t,e])&&t.some(r=>e.some(n=>r.every(i=>n.every(s=>c_(i,s)))))}function f_(t){try{return Et(t),!0}catch{return!1}}function Ci(t,e){return Qt(t,e)>=0}var Ga=xe(uS()),Wv=xe(qS()),L8=xe(DA()),kp=xe(n0());var Ri={name:"@capgo/cli",version:"7.21.1",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"],exports:{".":{import:"./dist/index.js",require:"./dist/index.js"},"./sdk":{types:"./dist/src/sdk.d.ts",import:"./dist/src/sdk.js",require:"./dist/src/sdk.js"}},main:"dist/index.js",types:"dist/src/index.d.ts",bin:{capgo:"dist/index.js"},engines:{npm:">=8.0.0",node:">=20.0.0"},scripts:{build:"tsc && node 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",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:"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"},devDependencies:{"@antfu/eslint-config":"^6.1.0","@bradenmacdonald/s3-lite-client":"npm:@jsr/bradenmacdonald__s3-lite-client@0.9.4","@capacitor/cli":"^7.4.4","@capgo/find-package-manager":"^0.0.18","@clack/prompts":"^0.11.0","@sauber/table":"npm:@jsr/sauber__table","@std/semver":"npm:@jsr/std__semver@1.0.6","@supabase/supabase-js":"^2.79.0","@types/adm-zip":"^0.5.7","@types/node":"^24.9.1","@types/prettyjson":"^0.0.33","@types/tmp":"^0.2.6","@vercel/ncc":"^0.38.4","adm-zip":"^0.5.16","ci-info":"^4.3.1",commander:"^14.0.2",esbuild:"^0.25.11",eslint:"^9.38.0","git-format-staged":"3.1.1",husky:"^9.1.7","is-wsl":"^3.1.0",open:"^10.1.2",prettyjson:"^1.2.5",tmp:"^0.2.5","tus-js-client":"^4.3.1",typescript:"^5.9.3"}};async function Rh(t){try{let r=`https://registry.npmjs.org/${encodeURIComponent(t.toLowerCase())}`,n=await fetch(r,{headers:{accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"}});return n.ok&&(await n.json())["dist-tags"]?.latest||null}catch{return null}}async function ze(){let t=await Rh("@capgo/cli")??"",e=t?.split(".")[0];t!==Ri.version&&w.warning(`\u{1F6A8} You are using @capgo/cli@${Ri.version} it's not the latest version.
|
|
283
|
+
`)}};var $8=require("node:child_process"),At=require("node:fs"),Ip=require("node:os"),Tt=xe(require("node:path")),di=require("node:process"),ns=xe(Sl());var Jt=require("fs"),lu=(t=".",e="unknown")=>{let r=`${t}/bun.lockb`,n=`${t}/bun.lock`,i=`${t}/pnpm-lock.yaml`,s=`${t}/shrinkwrap.yaml`,o=`${t}/yarn.lock`,a=`${t}/package-lock.json`,u=`${t}/npm-shrinkwrap.json`;return(0,Jt.existsSync)(r)||(0,Jt.existsSync)(n)?"bun":(0,Jt.existsSync)(i)||(0,Jt.existsSync)(s)?"pnpm":(0,Jt.existsSync)(o)?"yarn":(0,Jt.existsSync)(a)||(0,Jt.existsSync)(u)?"npm":e},Al=(t=lu(),e=!1)=>{switch(t){case"bun":return e?"bun install":"install";case"pnpm":return e?"pnpm install":"install";case"yarn":return e?"yarn install":"install";case"npm":return e?"npm install":"install";case"unknown":return e?"unknown unknown":"unknown";default:return e?"npm install":"install"}},JE=(t=".",e="npx")=>{let r=`${t}/bun.lockb`,n=`${t}/bun.lock`,i=`${t}/pnpm-lock.yaml`,s=`${t}/shrinkwrap.yaml`,o=`${t}/yarn.lock`,a=`${t}/package-lock.json`,u=`${t}/npm-shrinkwrap.json`;return(0,Jt.existsSync)(r)||(0,Jt.existsSync)(n)?"bunx":(0,Jt.existsSync)(i)||(0,Jt.existsSync)(s)?"pnpm exec":(0,Jt.existsSync)(o)?"yarn dlx":(0,Jt.existsSync)(a)||(0,Jt.existsSync)(u)?"npx":e};function Ol(t,e){if(isNaN(t)||isNaN(e))throw new Error("Cannot compare against non-numbers");return t===e?0:t<e?-1:1}function e_(t=[],e=[]){return t.length&&!e.length?-1:!t.length&&e.length?1:0}function Sm(t=[],e=[]){let r=Math.max(t.length,e.length);for(let n=0;n<r;n++){let i=t[n],s=e[n];if(i===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(i===void 0)return-1;if(typeof i=="string"&&typeof s=="number")return 1;if(typeof i=="number"&&typeof s=="string"||i<s)return-1;if(i>s)return 1}return 0}var wo="0|[1-9]\\d*",yU="\\d*[a-zA-Z-][a-zA-Z0-9-]*",DU=`(?<major>${wo})\\.(?<minor>${wo})\\.(?<patch>${wo})`,ZE=`(?:${wo}|${yU})`,t_=`(?:-(?<prerelease>${ZE}(?:\\.${ZE})*))`,QE="[0-9A-Za-z-]+",r_=`(?:\\+(?<buildmetadata>${QE}(?:\\.${QE})*))`,n_=`v?${DU}${t_}?${r_}?`,i_=new RegExp(`^${n_}$`),s_="(?:<|>)?=?",wU="x|X|\\*",Cm=`${wo}|${wU}`,xl=`[v=\\s]*(?<major>${Cm})(?:\\.(?<minor>${Cm})(?:\\.(?<patch>${Cm})${t_}?${r_}?)?)?`,o_=new RegExp(`^(?<operator>~>?|\\^|${s_})\\s*${xl}$`),a_=new RegExp(`^(?<operator>${s_})\\s*(${n_})$|^$`);function Am(t){return typeof t=="number"&&!Number.isNaN(t)&&(!Number.isFinite(t)||0<=t&&t<=Number.MAX_SAFE_INTEGER)}var Om=256;var bU=new RegExp(`^${wo}$`);function Zt(t){return t.split(".").filter(Boolean).map(e=>{if(bU.test(e)){let r=Number(e);if(Am(r))return r}return e})}function Zr(t){return t.split(".").filter(Boolean)}function Ei(t,e){let r=Number(t);if(!Am(r))throw new TypeError(e);return r}function Un(t){return Number.isNaN(t.major)&&Number.isNaN(t.minor)&&Number.isNaN(t.patch)&&(t.prerelease===void 0||t.prerelease.length===0)&&(t.build===void 0||t.build.length===0)}function Qt(t,e){return t===e?0:Ol(t.major,e.major)||Ol(t.minor,e.minor)||Ol(t.patch,e.patch)||e_(t.prerelease,e.prerelease)||Sm(t.prerelease,e.prerelease)}function xm(t){return t.toFixed(0)}function _i(t){let e=xm(t.major),r=xm(t.minor),n=xm(t.patch),i=t.prerelease?.join(".")??"",s=t.build?.join(".")??"";return[[`${e}.${r}.${n}`,i].filter(u=>u).join("-"),s].filter(u=>u).join("+")}function vU(t,e){if(Un(e))return!0;let r=Qt(t,e);switch(e.operator){case"=":case void 0:return r===0;case"!=":return r!==0;case">":return r>0;case"<":return r<0;case">=":return r>=0;case"<=":return r<=0}}function Tl(t,e){for(let r of e)if(!vU(t,r))return!1;if(t.prerelease&&t.prerelease.length>0){for(let r of e){if(Un(r))continue;let{major:n,minor:i,patch:s,prerelease:o}=r;if(o&&o.length>0&&t.major===n&&t.minor===i&&t.patch===s)return!0}return!1}return!0}function fu(t,e){return e.some(r=>Tl(t,r))}function EU(t=[]){let e=[...t],r=e.length;for(;r>=0;){let n=e[r];if(typeof n=="number"){e[r]=n+1;break}r-=1}return r===-1&&e.push(0),e}function hu(t=[],e){let r=EU(t);if(!e)return r;let n=Zt(e);if(n.every(i=>typeof i=="string")){if(n.every((i,s)=>i===r[s])&&typeof r[n.length]=="number")return r;n=[...n,0]}return n}function u_(t,e,r={}){let n=r.build!==void 0?Zr(r.build):t.build??[];switch(e){case"premajor":return{major:t.major+1,minor:0,patch:0,prerelease:hu(t.prerelease,r.prerelease),build:n};case"preminor":return{major:t.major,minor:t.minor+1,patch:0,prerelease:hu(t.prerelease,r.prerelease),build:n};case"prepatch":return{major:t.major,minor:t.minor,patch:t.patch+1,prerelease:hu(t.prerelease,r.prerelease),build:n};case"prerelease":{let s=(t.prerelease??[]).length===0?t.patch+1:t.patch;return{major:t.major,minor:t.minor,patch:s,prerelease:hu(t.prerelease,r.prerelease),build:n}}case"major":return{major:(t.prerelease??[]).length===0||t.minor!==0||t.patch!==0?t.major+1:t.major,minor:0,patch:0,prerelease:[],build:n};case"minor":{let s=(t.prerelease??[]).length===0||t.patch!==0?t.minor+1:t.minor;return{major:t.major,minor:s,patch:0,prerelease:[],build:n}}case"patch":{let s=(t.prerelease??[]).length===0?t.patch+1:t.patch;return{major:t.major,minor:t.minor,patch:s,prerelease:[],build:n}}case"pre":return{major:t.major,minor:t.minor,patch:t.patch,prerelease:hu(t.prerelease,r.prerelease),build:n};default:throw new TypeError(`Cannot increment version: invalid argument ${e}`)}}var Fl={major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]},bo={operator:void 0,...Fl};function Tm(t,e){return Qt(t,e)>0}function Fm(t,e){return Qt(t,e)<0}function _U(t){let r=t.match(a_)?.groups;if(!r)return null;let{operator:n,prerelease:i,buildmetadata:s}=r,o=r.major?{major:Ei(r.major,`Cannot parse comparator ${t}: invalid major version`),minor:Ei(r.minor,`Cannot parse comparator ${t}: invalid minor version`),patch:Ei(r.patch,`Cannot parse comparator ${t}: invalid patch version`),prerelease:i?Zt(i):[],build:s?Zr(s):[]}:Fl;return{operator:n||void 0,...o}}function qe(t){return!t||t.toLowerCase()==="x"||t==="*"}function CU(t){if(!qe(t.major))return qe(t.minor)?{operator:">=",major:+t.major,minor:0,patch:0,prerelease:[],build:[]}:qe(t.patch)?{operator:">=",major:+t.major,minor:+t.minor,patch:0,prerelease:[],build:[]}:{operator:">=",major:+t.major,minor:+t.minor,patch:+t.patch,prerelease:t.prerelease?Zt(t.prerelease):[],build:[]}}function SU(t){if(!qe(t.major))return qe(t.minor)?{operator:"<",major:+t.major+1,minor:0,patch:0,prerelease:[],build:[]}:qe(t.patch)?{operator:"<",major:+t.major,minor:+t.minor+1,patch:0,prerelease:[],build:[]}:t.prerelease?{operator:"<=",major:+t.major,minor:+t.minor,patch:+t.patch,prerelease:Zt(t.prerelease),build:[]}:{operator:"<=",major:+t.major,minor:+t.minor,patch:+t.patch,prerelease:[],build:[]}}function AU(t){let e=t.match(new RegExp(`^${xl}`)),r=e?.groups;if(!r)return null;let n=e[0].length,i=t.slice(n).match(/^\s+-\s+/);if(!i)return null;let s=i[0].length,a=t.slice(n+s).match(new RegExp(`^${xl}\\s*$`))?.groups;if(!a)return null;let u=CU(r),c=SU(a);return[u,c].filter(Boolean)}function OU(t){let e=qe(t.major),r=qe(t.minor),n=qe(t.patch),i=+t.major,s=+t.minor,o=+t.patch;if(e)return[bo];if(r)return[{operator:">=",major:i,minor:0,patch:0},{operator:"<",major:i+1,minor:0,patch:0}];if(n)return i===0?[{operator:">=",major:i,minor:s,patch:0},{operator:"<",major:i,minor:s+1,patch:0}]:[{operator:">=",major:i,minor:s,patch:0},{operator:"<",major:i+1,minor:0,patch:0}];let a=Zt(t.prerelease??"");return i===0?s===0?[{operator:">=",major:i,minor:s,patch:o,prerelease:a},{operator:"<",major:i,minor:s,patch:o+1}]:[{operator:">=",major:i,minor:s,patch:o,prerelease:a},{operator:"<",major:i,minor:s+1,patch:0}]:[{operator:">=",major:i,minor:s,patch:o,prerelease:a},{operator:"<",major:i+1,minor:0,patch:0}]}function xU(t){let e=qe(t.major),r=qe(t.minor),n=qe(t.patch),i=+t.major,s=+t.minor,o=+t.patch;if(e)return[bo];if(r)return[{operator:">=",major:i,minor:0,patch:0},{operator:"<",major:i+1,minor:0,patch:0}];if(n)return[{operator:">=",major:i,minor:s,patch:0},{operator:"<",major:i,minor:s+1,patch:0}];let a=Zt(t.prerelease??"");return[{operator:">=",major:i,minor:s,patch:o,prerelease:a},{operator:"<",major:i,minor:s+1,patch:0}]}function TU(t){let e=qe(t.major),r=qe(t.minor),n=qe(t.patch),i=+t.major,s=+t.minor,o=+t.patch;if(e)return[{operator:"<",major:0,minor:0,patch:0}];if(r)return n?[{operator:"<",major:i,minor:0,patch:0}]:[{operator:"<",major:i,minor:0,patch:0}];if(n)return[{operator:"<",major:i,minor:s,patch:0}];let a=Zt(t.prerelease??""),u=Zr(t.build??"");return[{operator:"<",major:i,minor:s,patch:o,prerelease:a,build:u}]}function FU(t){let e=qe(t.minor),r=qe(t.patch),n=+t.major,i=+t.minor,s=+t.patch;if(e)return r?[{operator:"<",major:n+1,minor:0,patch:0}]:[{operator:"<",major:n,minor:i+1,patch:0}];if(r)return[{operator:"<",major:n,minor:i+1,patch:0}];let o=Zt(t.prerelease??""),a=Zr(t.build??"");return[{operator:"<=",major:n,minor:i,patch:s,prerelease:o,build:a}]}function IU(t){let e=qe(t.major),r=qe(t.minor),n=qe(t.patch),i=+t.major,s=+t.minor,o=+t.patch;if(e)return[{operator:"<",major:0,minor:0,patch:0}];if(r)return[{operator:">=",major:i+1,minor:0,patch:0}];if(n)return[{operator:">=",major:i,minor:s+1,patch:0}];let a=Zt(t.prerelease??""),u=Zr(t.build??"");return[{operator:">",major:i,minor:s,patch:o,prerelease:a,build:u}]}function kU(t){let e=qe(t.major),r=qe(t.minor),n=qe(t.patch),i=+t.major,s=+t.minor,o=+t.patch;if(e)return[bo];if(r)return n?[{operator:">=",major:i,minor:0,patch:0}]:[{operator:">=",major:i,minor:0,patch:0}];if(n)return[{operator:">=",major:i,minor:s,patch:0}];let a=Zt(t.prerelease??""),u=Zr(t.build??"");return[{operator:">=",major:i,minor:s,patch:o,prerelease:a,build:u}]}function PU(t){let e=qe(t.major),r=qe(t.minor),n=qe(t.patch),i=+t.major,s=+t.minor,o=+t.patch;if(e)return[bo];if(r)return[{operator:">=",major:i,minor:0,patch:0},{operator:"<",major:i+1,minor:0,patch:0}];if(n)return[{operator:">=",major:i,minor:s,patch:0},{operator:"<",major:i,minor:s+1,patch:0}];let a=Zt(t.prerelease??""),u=Zr(t.build??"");return[{operator:void 0,major:i,minor:s,patch:o,prerelease:a,build:u}]}function RU(t){let e=t.match(o_)?.groups;if(!e)return _U(t);switch(e.operator){case"^":return OU(e);case"~":case"~>":return xU(e);case"<":return TU(e);case"<=":return FU(e);case">":return IU(e);case">=":return kU(e);case"=":case"":return PU(e);default:throw new Error(`Cannot parse version range: '${e.operator}' is not a valid operator`)}}function NU(t){return t.split(/\s+/).flatMap(RU)}function Il(t){let e=t.replaceAll(/(?<=<|>|=|~|\^)(\s+)/g,"").split(/\s*\|\|\s*/).map(r=>AU(r)||NU(r));if(e.some(r=>r.includes(null)))throw new TypeError(`Cannot parse version range: range "${t}" is invalid`);return e}function Et(t){if(typeof t!="string")throw new TypeError(`Cannot parse version as version must be a string: received ${typeof t}`);if(t.length>Om)throw new TypeError(`Cannot parse version as version length is too long: length is ${t.length}, max length is ${Om}`);t=t.trim();let e=t.match(i_)?.groups;if(!e)throw new TypeError(`Cannot parse version: ${t}`);let r=Ei(e.major,`Cannot parse version ${t}: invalid major version`),n=Ei(e.minor,`Cannot parse version ${t}: invalid minor version`),i=Ei(e.patch,`Cannot parse version ${t}: invalid patch version`),s=e.prerelease?Zt(e.prerelease):[],o=e.buildmetadata?Zr(e.buildmetadata):[];return{major:r,minor:n,patch:i,prerelease:s,build:o}}function c_(t,e){let r=t.operator,n=e.operator;if(r===void 0)return Un(t)?!0:fu(t,[[e]]);if(n===void 0)return Un(e)?!0:fu(e,[[t]]);let i=Qt(t,e);return(r===">="||r===">")&&(n===">="||n===">")||(r==="<="||r==="<")&&(n==="<="||n==="<")||i===0&&((r===">="||r==="<=")&&(n===">="||n==="<="))||i===-1&&(r===">="||r===">")&&(n==="<="||n==="<")||i===1&&(r==="<="||r==="<")&&(n===">="||n===">")}function $U(t){return t.every(e=>e.some(r=>LU(r)))}function LU(t){for(let e=0;e<t.length-1;e++){let r=t[e];for(let n of t.slice(e+1))if(!c_(r,n))return!1}return!0}function l_(t,e){return $U([t,e])&&t.some(r=>e.some(n=>r.every(i=>n.every(s=>c_(i,s)))))}function f_(t){try{return Et(t),!0}catch{return!1}}function Ci(t,e){return Qt(t,e)>=0}var Ga=xe(uS()),Wv=xe(qS()),L8=xe(DA()),kp=xe(n0());var Ri={name:"@capgo/cli",version:"7.21.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"],exports:{".":{import:"./dist/index.js",require:"./dist/index.js"},"./sdk":{types:"./dist/src/sdk.d.ts",import:"./dist/src/sdk.js",require:"./dist/src/sdk.js"}},main:"dist/index.js",types:"dist/src/index.d.ts",bin:{capgo:"dist/index.js"},engines:{npm:">=8.0.0",node:">=20.0.0"},scripts:{build:"tsc && node 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",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:"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"},devDependencies:{"@antfu/eslint-config":"^6.1.0","@bradenmacdonald/s3-lite-client":"npm:@jsr/bradenmacdonald__s3-lite-client@0.9.4","@capacitor/cli":"^7.4.4","@capgo/find-package-manager":"^0.0.18","@clack/prompts":"^0.11.0","@sauber/table":"npm:@jsr/sauber__table","@std/semver":"npm:@jsr/std__semver@1.0.6","@supabase/supabase-js":"^2.79.0","@types/adm-zip":"^0.5.7","@types/node":"^24.9.1","@types/prettyjson":"^0.0.33","@types/tmp":"^0.2.6","@vercel/ncc":"^0.38.4","adm-zip":"^0.5.16","ci-info":"^4.3.1",commander:"^14.0.2",esbuild:"^0.25.11",eslint:"^9.38.0","git-format-staged":"3.1.1",husky:"^9.1.7","is-wsl":"^3.1.0",open:"^10.1.2",prettyjson:"^1.2.5",tmp:"^0.2.5","tus-js-client":"^4.3.1",typescript:"^5.9.3"}};async function Rh(t){try{let r=`https://registry.npmjs.org/${encodeURIComponent(t.toLowerCase())}`,n=await fetch(r,{headers:{accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"}});return n.ok&&(await n.json())["dist-tags"]?.latest||null}catch{return null}}async function ze(){let t=await Rh("@capgo/cli")??"",e=t?.split(".")[0];t!==Ri.version&&w.warning(`\u{1F6A8} You are using @capgo/cli@${Ri.version} it's not the latest version.
|
|
284
284
|
Please use @capgo/cli@${t}" or @capgo/cli@${e} to keep up to date with the latest features and bug fixes.`)}async function F1(t,e,r,n,i,s="\u2705"){await Ae(r,{channel:t,event:n,icon:s,user_id:e,...i?{tags:{"app-id":i}}:{},notify:!1})}var i0=require("node:buffer"),I1=require("node:crypto"),GX=(()=>{let t=[];for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r}return t})();function KX(t){let e=4294967295;for(let r=0;r<t.length;r++){let n=t[r];e=GX[(e^n)&255]^e>>>8}return e=e^4294967295,(e>>>0).toString(16).padStart(8,"0")}async function Jn(t,e="sha256"){let r=i0.Buffer.isBuffer(t)?t:i0.Buffer.from(t);if(e==="crc32")return KX(r);let n=(0,I1.createHash)(e);return n.update(r),n.digest("hex")}var Zc=xe(e8());async function t8(){let t=await(0,Zc.loadConfig)();return{config:t.app.extConfig,path:t.app.extConfigFilePath}}async function Sv(t,e,r=!1){let n=await(0,Zc.loadConfig)(),{extConfig:i}=n.app;i&&(i.plugins||(i.plugins={extConfig:{},[t]:{}}),i.plugins[t]||(i.plugins[t]={}),r?i=e.config:i.plugins[t]=e.config.plugins?.[t],(0,Zc.writeConfig)(i,n.app.extConfigFilePath))}async function Ua(t,e=!1){await Sv("CapacitorUpdater",t,e)}var Ka=".capgo_key",Ir=".capgo_key_v2",Pp=`${Ka}.pub`,pi=`${Ir}.pub`,F8="https://capgo.app",I8="https://files.capgo.app",k8="https://api.capgo.app",P8="https://console.capgo.app",Xv=12e4,fle=1024*1024*20,hle=1024*1024*1024,dle=1024*1024*99,$n="package.json",Wa=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-z-][0-9a-z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-z-][0-9a-z-]*))*))?(?:\+([0-9a-z-]+(?:\.[0-9a-z-]+)*))?$/i,W=t=>t?`
|
|
285
285
|
${L8.default.render(t)}`:"";function Fp(t){return new Promise(e=>{setTimeout(e,t)})}function Xr(t){return(0,ns.isMonorepo)(t)?(0,ns.findMonorepoRoot)(t):(0,ns.isNXMonorepo)(t)?(0,ns.findNXMonorepoRoot)(t):t}function ple(t=Xr((0,di.cwd)()),e=void 0){let r=e?.split(",")[0];if(r&&!(0,At.existsSync)(r)){let i=`Package.json at ${r} does not exist`;throw w.error(i),new Error(i)}let n=(0,At.readFileSync)(r??(0,Tt.join)(t,$n));return JSON.parse(n)}function is(t=Xr((0,di.cwd)()),e=void 0){return ple(t,e).version??""}function R8(t){let e=t.replace("^","").replace("~","");if(f_(e))try{let r=Et(e);return _i(r)}catch{return e}return e}async function Ln(t=Xr((0,di.cwd)()),e=void 0){let r=e?.split(",");if(r??=[(0,Tt.join)(t,$n)],r){for(let i of r)if(!(0,At.existsSync)(i)){let s=`Package.json at ${i} does not exist`;throw w.error(s),new Error(s)}}let n=new Map;for(let i of r){let s=(0,At.readFileSync)(i),o=JSON.parse(s);for(let a in o.dependencies)n.set(a,R8(o.dependencies[a]));for(let a in o.devDependencies)n.set(a,R8(o.devDependencies[a]))}return n}async function de(){try{let t=await t8();if(!t){let e="No capacitor config file found, run `cap init` first";throw w.error(e),new Error(e)}return t}catch(t){let e=`No capacitor config file found, run \`cap init\` first ${W(t)}`;throw w.error(e),new Error(e)}}async function mle(t,e){let r=await de();return r?.config&&(r.config.plugins??={},r.config.plugins.extConfig??={},r.config.plugins[t]??={},r.config.plugins[t]={...r.config.plugins[t],...e},await Sv(t,r)),r}async function j8(t){return mle("CapacitorUpdater",t)}async function wn(){try{let t=await de(),e={host:t?.config?.plugins?.CapacitorUpdater?.localHost||F8,hostWeb:t?.config?.plugins?.CapacitorUpdater?.localWebHost||P8,hostFilesApi:t?.config?.plugins?.CapacitorUpdater?.localApiFiles||I8,hostApi:t?.config?.plugins?.CapacitorUpdater?.localApi||k8};return t?.config?.plugins?.CapacitorUpdater?.localSupa&&t?.config?.plugins?.CapacitorUpdater?.localSupaAnon&&(w.info("Using custom supabase instance from capacitor.config.json"),e.supaKey=t?.config?.plugins?.CapacitorUpdater?.localSupaAnon,e.supaHost=t?.config?.plugins?.CapacitorUpdater?.localSupa),e}catch{return{host:F8,hostWeb:P8,hostFilesApi:I8,hostApi:k8}}}var gle=/([A-Za-z0-9]+)\.(java|swift|kt|scala)$/;async function Rp(){let t=await wn();try{let e=await fetch(`${t.hostApi}/private/config`);if(!e.ok)throw new Error(`HTTP error! status: ${e.status}`);return{...await e.json(),...t}}catch{return w.info(`Local config ${W(t)}`),t}}async function B8(){let t=await wn();try{let e=await fetch(`${t.hostFilesApi}/files/config`);if(!e.ok)throw new Error(`HTTP error! status: ${e.status}`);return await e.json()}catch{return{partialUpload:!1,TUSUpload:!1,partialUploadForced:!1,TUSUploadForced:!1,maxUploadLength:hle,maxChunkSize:dle,alertUploadSize:fle}}}async function pe(t,e,r){let n=await Rp();if(e&&r&&(w.info("Using custom supabase instance from provided options"),n.supaHost=e,n.supaKey=r),!n.supaHost||!n.supaKey)throw w.error("Cannot connect to server please try again later"),new Error("Cannot connect to server please try again later");return(0,Ga.createClient)(n.supaHost,n.supaKey,{auth:{persistSession:!1},global:{headers:{capgkey:t}}})}async function yle(t,e,r){let{data:n}=await t.rpc("is_allowed_capgkey",{apikey:e,keymode:r}).single();if(!n){w.error("Invalid API key or insufficient permissions.");let s=`Your key should be: ${r.map((o,a)=>r.length===1?`"${o}"`:a===r.length-1?`or "${o}"`:`"${o}", `).join("")} mode.`;throw w.error(s),new Error("Invalid API key or insufficient permissions.")}}async function M8(t,e){let{data:r}=await t.rpc("is_paying_org",{orgid:e}).single();return r||!1}async function q8(t,e){let{data:r}=await t.rpc("is_trial_org",{orgid:e}).single();return r||0}async function Dle(t,e){let{data:r}=await t.rpc("is_allowed_action_org",{orgid:e}).single();return!!r}async function wle(t,e,r){let{data:n}=await t.rpc("is_allowed_action",{apikey:r,appid:e}).single();return!!n}var fr=(o=>(o[o.none=0]="none",o[o.read=1]="read",o[o.upload=2]="upload",o[o.write=3]="write",o[o.admin=4]="admin",o[o.super_admin=5]="super_admin",o))(fr||{}),Xa=(t,e)=>t>=e;async function U8(t,e,r){let{data:n,error:i}=await t.rpc("get_org_perm_for_apikey",{apikey:e,app_id:r}).single();if(i)throw w.error("Cannot get permissions for organization!"),console.error(i),new Error("Cannot get permissions for organization");if(n.includes("perm")){let a=null;switch(n){case"perm_none":{a=0;break}case"perm_read":{a=1;break}case"perm_upload":{a=2;break}case"perm_write":{a=3;break}case"perm_admin":{a=4;break}case"perm_owner":{a=5;break}default:throw n.includes("invite")?(w.info("Please accept/deny the organization invitation before trying to access the app"),new Error("Organization invitation pending")):(w.error(`Invalid output when fetching organization permission. Response: ${n}`),new Error(`Invalid output when fetching organization permission. Response: ${n}`))}return{okay:!0,data:a}}let o=null;switch(n){case"INVALID_APIKEY":{o="INVALID_APIKEY";break}case"NO_APP":{o="NO_APP";break}case"NO_ORG":{o="NO_ORG";break}default:throw w.error(`Invalid error when fetching organization permission. Response: ${n}`),new Error(`Invalid error when fetching organization permission. Response: ${n}`)}return{okay:!1,error:o}}async function H8(t,e,r){let{data:n,error:i}=await t.rpc("get_organization_cli_warnings",{orgid:e,cli_version:r});if(i){w.error(`Cannot get cli warnings: ${W(i)}`);return}if(n.length>0){w.warn(`Found ${n.length} cli warnings for your organization.`);let s=null;for(let o of n){if(typeof o!="object"||typeof o.message!="string"||typeof o.fatal!="boolean"){w.error(`Invalid cli warning: ${o}`);continue}let a=o;a.fatal?(w.error(`${a.message.replaceAll("\\n",`
|
|
286
286
|
`)}`),s=new Error(a.message)):w.warn(`${a.message.replaceAll("\\n",`
|
|
@@ -325,7 +325,7 @@ ${W(s)}`),new Error(`Cannot retrieve unknown version for app ${e}: ${W(s)}`);ret
|
|
|
325
325
|
`)+`
|
|
326
326
|
`,n.join(";").toLowerCase(),i].join(`
|
|
327
327
|
`)}async function LM(t,e,r){let n=await Gp(t),i=iE(r,e);return[ol,ao(e),i,n].join(`
|
|
328
|
-
`)}async function oE(t,e,r){let n=nE(t),i=await co("AWS4"+r,n),s=await co(i,e),o=await co(s,"s3");return await co(o,"aws4_request")}function aE(t,e,r){return`${t}/${iE(e,r)}`}async function co(t,e){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",t instanceof Uint8Array?t:r.encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"]),i=await crypto.subtle.sign("HMAC",n,e instanceof Uint8Array?e:r.encode(e));return new Uint8Array(i)}async function jM(t){if(!t.accessKey)throw new as;if(!t.secretKey)throw new ru;if(t.expirySeconds<1||t.expirySeconds>604800)throw new il;let e=new Date(t.date);e.setSeconds(e.getSeconds()+t.expirySeconds);let r=aE(t.accessKey,t.region,t.date),n=ao(t.date),i={"X-Amz-Algorithm":ol,"X-Amz-Credential":r,"X-Amz-Date":n,key:t.objectKey,...t.fields},s=[{bucket:t.bucket},{key:t.objectKey},{"X-Amz-Algorithm":ol},{"X-Amz-Credential":r},{"X-Amz-Date":n}];t.conditions&&s.push(...t.conditions);for(let[f,m]of Object.entries(t.fields||{}))["key","X-Amz-Algorithm","X-Amz-Credential","X-Amz-Date"].includes(f)||s.push({[f]:m});let o={expiration:e.toISOString(),conditions:s},a=new TextEncoder().encode(JSON.stringify(o)),u=btoa(String.fromCharCode(...a));i.policy=u;let c=u,l=await oE(t.date,t.region,t.secretKey),h=sl(await co(l,c)).toLowerCase();return i["X-Amz-Signature"]=h,{url:`${t.protocol}//${t.host}/${t.bucket}`,fields:i}}var jle=["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"],Ble=5*1024*1024,Mle=5*1024*1024*1024,uE=5*1024*1024*1024*1024,al=class{host;port;protocol;accessKey;#e;sessionToken;defaultBucket;region;userAgent="s3-lite-client";pathStyle;pathPrefix;constructor({endPoint:e,useSSL:r,port:n,pathPrefix:i,...s}){if(/^https?:\/\//i.test(e)){if(r!==void 0||n!==void 0||i!==void 0)throw new Yt("useSSL/port/pathPrefix cannot be specified if endPoint is a URL.");try{let a=new URL(e);e=a.hostname,r=a.protocol==="https:",n=a.port?parseInt(a.port,10):r?443:80,a.pathname&&a.pathname!=="/"&&(i=a.pathname.endsWith("/")?a.pathname.slice(0,-1):a.pathname)}catch{throw new nl(`Invalid endPoint URL: ${e}`)}}if(typeof e!="string"||e.length===0)throw new nl(`Invalid endPoint: ${e}`);if(r===void 0&&(r=!0),n!==void 0&&!IM(n))throw new Yt(`Invalid port: ${n}`);if(s.accessKey&&!s.secretKey)throw new Yt("If specifying access key, secret key must also be provided.");if(s.accessKey&&s.accessKey.startsWith("ASIA")&&!s.sessionToken)throw new Yt("If specifying temporary access key, session token must also be provided.");let o=r?443:80;if(this.port=n??o,this.host=e.toLowerCase()+(this.port!==o?`:${this.port}`:""),this.protocol=r?"https:":"http:",this.accessKey=s.accessKey,this.#e=s.secretKey??"",this.sessionToken=s.sessionToken,this.pathStyle=s.pathStyle??!0,this.pathPrefix=i??"",this.defaultBucket=s.bucket,this.region=s.region,this.pathPrefix){if(!this.pathStyle)throw new Yt("pathPrefix is incompatible with pathStyle=false");if(!this.pathPrefix.startsWith("/"))throw new Yt("pathPrefix should start with /");if(this.pathPrefix.endsWith("/"))throw new Yt("pathPrefix should not end with /")}}getBucketName(e){let r=e?.bucketName??this.defaultBucket;if(r===void 0||!kM(r))throw new zp(r??"");return r}buildRequestOptions(e){let r=this.getBucketName(e),n=this.pathStyle?this.host:`${r}.${this.host}`,i=e.headers??new Headers;i.set("host",n);let s=typeof e.query=="object"?new URLSearchParams(e.query).toString().replace("+","%20"):e.query,o=this.pathStyle?`${this.pathPrefix}/${r}/${e.objectName}`:`/${e.objectName}`,a=s?`?${s}`:"",u=o+a,c=o.split("/").map(l=>encodeURIComponent(l)).join("/")+a;return{headers:i,host:n,path:u,encodedPath:c}}async makeRequest({method:e,payload:r,...n}){let i=new Date,{headers:s,host:o,path:a,encodedPath:u}=this.buildRequestOptions(n),c=n.statusCode??200;if(e==="POST"||e==="PUT"||e==="DELETE")r===void 0?r=new Uint8Array:typeof r=="string"&&(r=new TextEncoder().encode(r)),s.set("Content-Length",String(r.length));else if(r)throw new Error(`Unexpected payload on ${e} request.`);let l=await Gp(r??new Uint8Array);s.set("x-amz-date",ao(i)),s.set("x-amz-content-sha256",l),this.accessKey&&(this.sessionToken&&s.set("x-amz-security-token",this.sessionToken),s.set("authorization",await PM({headers:s,method:e,path:a,accessKey:this.accessKey,secretKey:this.#e,region:this.region,date:i})));let h=`${this.protocol}//${o}${u}`,d=await fetch(h,{method:e,headers:s,body:r});if(d.status!==c)throw d.status>=400?await FM(d):d.status===301?new Di(d.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"'):new Di(d.status,"UnexpectedStatusCode",`Unexpected response code from the server (expected ${c}, got ${d.status} ${d.statusText}).`);return n.returnBody||await d.body?.getReader().read(),d}async deleteObject(e,r={}){let n=this.getBucketName(r);if(!us(e))throw new Bn(e);let i=r.versionId?{versionId:r.versionId}:{},s=new Headers;r.governanceBypass&&s.set("X-Amz-Bypass-Governance-Retention","true"),await this.makeRequest({method:"DELETE",bucketName:n,objectName:e,headers:s,query:i,statusCode:204})}async exists(e,r){try{return await this.statObject(e,r),!0}catch(n){if(n instanceof Di&&n.statusCode===404)return!1;throw n}}getObject(e,r){return this.getPartialObject(e,{...r,offset:0,length:0})}async getPartialObject(e,{offset:r,length:n,...i}){let s=this.getBucketName(i);if(!us(e))throw new Bn(e);let o=new Headers(Object.entries(i.metadata??{})),a=200;if(r||n){let c="";r?c=`bytes=${+r}-`:(c="bytes=0-",r=0),n&&(c+=`${+n+r-1}`),o.set("Range",c),a=206}let u={...i.responseParams,...i.versionId?{versionId:i.versionId}:{}};return await this.makeRequest({method:"GET",bucketName:s,objectName:e,headers:o,query:u,statusCode:a,returnBody:!0})}getPresignedUrl(e,r,n={}){if(!this.accessKey)throw new as;if(!us(r))throw new Bn(r);let{headers:i,path:s}=this.buildRequestOptions({objectName:r,bucketName:n.bucketName,query:n.parameters}),o=n.requestDate??new Date,a=n.expirySeconds??1440*60*7;return RM({protocol:this.protocol,headers:i,method:e,path:s,accessKey:this.accessKey,secretKey:this.#e,sessionToken:this.sessionToken,region:this.region,date:o,expirySeconds:a})}presignedGetObject(e,r={}){let{versionId:n,responseParams:i,...s}=r,o={...i,...n?{versionId:n}:{}};return this.getPresignedUrl("GET",e,{parameters:o,...s})}async*listObjects(e={}){for await(let r of this.listObjectsGrouped({...e,delimiter:""}))if(r.type==="Object")yield r;else throw new Error(`Unexpected result from listObjectsGrouped(): ${r}`)}async*listObjectsGrouped(e){let r=this.getBucketName(e),n="",i=e.pageSize??1e3;if(i<1||i>1e3)throw new Yt("pageSize must be between 1 and 1,000.");let s=0;for(;;){let o=e.maxResults?Math.min(i,e.maxResults-s):i;if(o===0)return;let u=await(await this.makeRequest({method:"GET",bucketName:r,objectName:"",query:{"list-type":"2",prefix:e.prefix??"",delimiter:e.delimiter,"max-keys":String(o),...n?{"continuation-token":n}:{}},returnBody:!0})).text(),c=os(u).root;if(!c||c.name!=="ListBucketResult")throw new Error(`Unexpected response: ${u}`);let l=c.children.filter(f=>f.name==="CommonPrefixes").flatMap(f=>f.children),h=[];for(let f of l)h.push({type:"CommonPrefix",prefix:f.content??""}),s++;for(let f of c.children.filter(m=>m.name==="Contents"))h.push({type:"Object",key:f.children.find(m=>m.name==="Key")?.content??"",etag:oo(f.children.find(m=>m.name==="ETag")?.content??""),size:parseInt(f.children.find(m=>m.name==="Size")?.content??"",10),lastModified:new Date(f.children.find(m=>m.name==="LastModified")?.content??"invalid")}),s++;h.sort((f,m)=>{let g=f.type==="Object"?f.key:f.prefix,b=m.type==="Object"?m.key:m.prefix;return g>b?1:g<b?-1:0});for(let f of h)yield f;if(c.children.find(f=>f.name==="IsTruncated")?.content==="true"){let f=c.children.find(m=>m.name==="NextContinuationToken")?.content;if(!f)throw new Error("Unexpectedly missing continuation token, but server said there are more results.");n=f}else return}}async putObject(e,r,n){let i=this.getBucketName(n);if(!us(e))throw new Bn(e);let s,o;if(typeof r=="string"){let l=new TextEncoder().encode(r);typeof ReadableStream.from<"u"?o=ReadableStream.from([l]):o=new ReadableStream({start(h){h.enqueue(l),h.close()}}),s=l.length}else if(r instanceof Uint8Array)typeof ReadableStream.from<"u"?o=ReadableStream.from([r]):o=new ReadableStream({start(l){l.enqueue(r),l.close()}}),s=r.byteLength;else if(r instanceof ReadableStream)o=r;else throw new Yt("Invalid stream/data type provided.");if(n?.size!==void 0){if(s!==void 0&&n?.size!==s)throw new Yt(`size was specified (${n.size}) but doesn't match auto-detected size (${s}).`);if(typeof n.size!="number"||n.size<0||isNaN(n.size))throw new Yt(`invalid size specified: ${n.size}`);s=n.size}let a=n?.partSize??this.calculatePartSize(s);if(a<Ble)throw new Yt("Part size should be greater than 5MB");if(a>Mle)throw new Yt("Part size should be less than 6MB");let u=new Vp(a),c=new Kp({client:this,bucketName:i,objectName:e,partSize:a,metadata:n?.metadata??{}});return await o.pipeThrough(u).pipeTo(c),c.getResult()}calculatePartSize(e){if(e===void 0&&(e=uE),e>uE)throw new TypeError(`size should not be more than ${uE}`);let r=64*1024*1024;for(;;){if(r*1e4>e)return r;r+=16*1024*1024}}async statObject(e,r){let n=this.getBucketName(r);if(!us(e))throw new Bn(e);let i={};r?.versionId&&(i.versionId=r.versionId);let s=await this.makeRequest({method:"HEAD",bucketName:n,objectName:e,query:i,headers:new Headers(r?.headers)}),o={};for(let a of jle)s.headers.has(a)&&(o[a]=s.headers.get(a));return s.headers.forEach((a,u)=>{u.startsWith("x-amz-meta-")&&(o[u]=s.headers.get(u))}),{type:"Object",key:e,size:parseInt(s.headers.get("content-length")??"",10),metadata:o,lastModified:new Date(s.headers.get("Last-Modified")??"error: missing last modified"),versionId:s.headers.get("x-amz-version-id")||null,etag:oo(s.headers.get("ETag")??"")}}async copyObject(e,r,n){let i=this.getBucketName(n),s=e.sourceBucketName??i;if(!us(r))throw new Bn(r);let o=`${s}/${e.sourceKey}`;e.sourceVersionId&&(o+=`?versionId=${e.sourceVersionId}`);let a=new Headers(n?.metadata);n?.metadata!==void 0&&a.set("x-amz-metadata-directive","REPLACE"),a.set("x-amz-copy-source",o);let u=await this.makeRequest({method:"PUT",bucketName:i,objectName:r,headers:a,returnBody:!0}),c=await u.text(),l=os(c).root;if(!l||l.name!=="CopyObjectResult")throw new Error(`Unexpected response: ${c}`);let h=l.children.find(f=>f.name==="ETag")?.content??"",d=l.children.find(f=>f.name==="LastModified")?.content;if(d===void 0)throw new Error("Unable to find <LastModified>...</LastModified> from the server.");return{copySourceVersionId:u.headers.get("x-amz-copy-source-version-id")||null,etag:oo(h),lastModified:new Date(d),versionId:u.headers.get("x-amz-version-id")||null}}async bucketExists(e){try{return await this.listObjects({bucketName:e}).next(),!0}catch(r){if(r instanceof Di&&r.statusCode===404)return!1;throw r}}async makeBucket(e){await this.makeRequest({method:"PUT",bucketName:this.getBucketName({bucketName:e}),objectName:"",statusCode:200})}async removeBucket(e){await this.makeRequest({method:"DELETE",bucketName:this.getBucketName({bucketName:e}),objectName:"",statusCode:204})}presignedPostObject(e,r={}){if(!us(e))throw new Bn(e);let n=this.getBucketName(r);if(!n)throw new Error("Bucket name is required for presignedPost, but none was provided either to this method nor to the client constructor");let i=r.requestDate||new Date,s=r.expirySeconds??3600;return jM({protocol:this.protocol,host:this.host,bucket:n,objectKey:e,accessKey:this.accessKey||"",secretKey:this.#e||"",region:this.region,date:i,expirySeconds:s,conditions:r.conditions,fields:r.fields})}};var lo=require("node:fs"),Wp=require("node:path");function qle(t,e){return(0,lo.readFileSync)(t,"utf8").includes(e)}function ul(t,e){let r=(0,lo.readdirSync)(t);for(let n of r){let i=(0,Wp.join)(t,n),s=(0,lo.statSync)(i);if(s.isDirectory()){if(ul(i,e))return!0}else if(s.isFile()&&(0,Wp.extname)(i)===".js"&&qle(i,e))return!0}return!1}function Xp(t){return(0,lo.readdirSync)(t).indexOf("index.html")>-1}var su=require("node:fs"),K6=require("node:os"),cs=require("node:path"),W6=require("node:process"),nm=require("node:stream/consumers"),X6=require("node:zlib");var Y6=xe(G6()),J6=xe(n0());async function rhe(t,e){try{return(await fetch(`${t.hostFilesApi}/files/read/attachments/${encodeURIComponent(e)}`,{method:"HEAD"})).ok}catch{return!1}}var Z6=8192,Q6="6.25.0",eq="7.0.35";async function nhe(t){let e=(0,cs.join)(Xr((0,W6.cwd)()),$n),n=(await Ln(void 0,t.packageJson||e)).get("@capgo/capacitor-updater"),i;try{i=n?Et(n):void 0}catch{i=void 0}if(!n||!i)return{version:null,supportsBrotliV2:!1};let s=i.major===6&&Ci(i,Et(Q6)),o=i.major>=7&&Ci(i,Et(eq)),a=s||o;return{version:`${i.major}.${i.minor}.${i.patch}`,supportsBrotliV2:a}}function ihe(t,e){if(!e)return!1;let r=e.split(",").map(n=>n.trim()).filter(n=>!!n);return r.length===0?!1:Y6.isMatch(t,r)}async function she(t,e,r){let i=(0,su.statSync)(t).size,s=await(0,nm.buffer)((0,su.createReadStream)(t));if(i===0)return{buffer:s,useBrotli:!1};if(ihe(e,r.noBrotliPatterns))return w.info(`Skipping brotli for excluded file: ${e}`),{buffer:s,useBrotli:!1};if(i<Z6)return{buffer:s,useBrotli:!1};try{let o=await(0,nm.buffer)((0,su.createReadStream)(t).pipe((0,X6.createBrotliCompress)({})));return o.length>=i-10?(w.info(`Brotli not effective for ${e} (${i} bytes), using original file`),{buffer:s,useBrotli:!1}):{buffer:o,useBrotli:!0}}catch(o){return w.warn(`Brotli compression failed for ${t}: ${o}, using original file`),{buffer:s,useBrotli:!1}}}async function tq(t,e,r,n,i,s){let o=Ft();o.start(i!=="v2"?"Generating the update manifest":"Generating the update manifest with v2 encryption");let a=await W8(t);if(i==="v2")for(let u of a)u.hash=tu(u.hash,s);return o.stop("Manifest generated successfully"),await Ae(e,{channel:"partial-update",event:"Generate manifest",icon:"\u{1F4C2}",user_id:r,tags:{"app-id":n},notify:!1}),a}function ohe(t){return(0,K6.platform)()!=="win32"?t:cs.win32.normalize(t).split(cs.win32.sep).join(cs.posix.sep)}function ahe(t){let e=t.split("/").map(r=>encodeURIComponent(r)).join("/");return t.includes(" ")&&w.warn(`File "${t}" contains spaces in its name.`),e}async function rq(t,e,r,n,i,s,o,a){let u=Ft();u.start("Preparing partial update with TUS protocol");let c=performance.now(),l=await wn(),{version:h,supportsBrotliV2:d}=await nhe(a);if(d)a.disableBrotli?w.info("Brotli compression disabled by user request"):(u.message(`Using .br extension for compatible files (updater ${h})`),a.noBrotliPatterns&&w.info(`Files matching patterns (${a.noBrotliPatterns}) will be excluded from brotli compression`),w.info(`Files smaller than ${Z6} bytes will be excluded from brotli compression (Brotli RFC minimum)`));else throw new Error(`Your project is using an older version of @capgo/capacitor-updater (${h||"unknown"}). To use Delta updates, please upgrade to version ${Q6} (v6) or ${eq} (v7) or higher.`);let f=e.filter(S=>S.file.includes(" "));if(f.length>0)throw new Error(`Files with spaces in their names (${f.map(S=>S.file).join(", ")}). Please rename the files.`);let m=0,g=e.length,b=0;try{let S=e.map(async y=>{let C=(0,cs.join)(r,y.file),k=ohe(y.file),v,R=!1;if(a.disableBrotli)v=await(0,nm.buffer)((0,su.createReadStream)(C)),R=!1;else{let G=await she(C,k,a);v=G.buffer,R=G.useBrotli}let P=v;o&&(P=eu(v,o.sessionKey,o.ivSessionKey));let F=k;R&&(F=`${k}.br`,b++);let j=ahe(F),U=`orgs/${s}/apps/${n}/delta/${y.hash}_${j}`;return await rhe(l,U)?(m++,Promise.resolve({file_name:j,s3_path:U,file_hash:y.hash})):new Promise((G,L)=>{new J6.Upload(P,{endpoint:`${l.hostFilesApi}/files/upload/attachments/`,chunkSize:a.tusChunkSize,metadata:{filename:U},headers:{Authorization:t},onError(T){w.info(`Failed to upload ${k}: ${T}`),L(T)},onProgress(){let T=(m/g*100).toFixed(2);u.message(`Uploading partial update: ${T}%`)},onSuccess(){m++,G({file_name:j,s3_path:U,file_hash:y.hash})}}).start()})}),A=await Promise.all(S),D=((performance.now()-c)/1e3).toFixed(2);return u.stop(`Partial update uploaded successfully \u{1F4AA} in (${D} seconds)`),b>0&&w.info(`${b} of ${g} files were compressed with brotli and use .br extension`),await Ae(t,{channel:"app",event:`App Partial TUS done${b>0?" with .br extension":""}`,icon:"\u23EB",user_id:s,tags:{"app-id":n},notify:!1}),await Ae(t,{channel:"performance",event:"Partial upload performance",icon:"\u{1F684}",user_id:s,tags:{"app-id":n,time:D},notify:!1}),A}catch(S){let p=((performance.now()-c)/1e3).toFixed(2);return u.stop(`Failed to upload Partial bundle (after ${p} seconds)`),w.info(`Error uploading partial update: ${S}, This is not a critical error, the bundle has been uploaded without the partial files`),null}}function gt(t){throw w.error(t),new Error(t)}async function uhe(t,e){let r=is("",e.packageJson),n=e.bundle||t?.plugins?.CapacitorUpdater?.version||r||`0.0.1-beta.${(0,nq.randomUUID)().split("-")[0]}`;return Wa.test(n)||gt(`Your bundle name ${n}, is not valid it should follow semver convention : https://semver.org/`),n}function che(t){let e=t.apikey||ne();return e||gt("Missing API key, you need to provide an API key to upload your bundle"),e}function lhe(t,e,r){let n=Pe(t,r),i=e.path||r?.webDir;return n||gt("Missing argument, you need to provide a appid or be in a capacitor project"),i||gt("Missing argument, you need to provide a path (--path), or be in a capacitor project"),(0,po.existsSync)(i)||gt(`Path ${i} does not exist, build your app first, or provide a valid path`),{appid:n,path:i}}function fhe(t,e){let r=t.codeCheck;(typeof r>"u"||r)&&(ul(e,"notifyAppReady")||gt(`notifyAppReady() is missing in the build folder of your app. see: https://capgo.app/docs/plugin/api/#notifyappready
|
|
328
|
+
`)}async function oE(t,e,r){let n=nE(t),i=await co("AWS4"+r,n),s=await co(i,e),o=await co(s,"s3");return await co(o,"aws4_request")}function aE(t,e,r){return`${t}/${iE(e,r)}`}async function co(t,e){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",t instanceof Uint8Array?t:r.encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"]),i=await crypto.subtle.sign("HMAC",n,e instanceof Uint8Array?e:r.encode(e));return new Uint8Array(i)}async function jM(t){if(!t.accessKey)throw new as;if(!t.secretKey)throw new ru;if(t.expirySeconds<1||t.expirySeconds>604800)throw new il;let e=new Date(t.date);e.setSeconds(e.getSeconds()+t.expirySeconds);let r=aE(t.accessKey,t.region,t.date),n=ao(t.date),i={"X-Amz-Algorithm":ol,"X-Amz-Credential":r,"X-Amz-Date":n,key:t.objectKey,...t.fields},s=[{bucket:t.bucket},{key:t.objectKey},{"X-Amz-Algorithm":ol},{"X-Amz-Credential":r},{"X-Amz-Date":n}];t.conditions&&s.push(...t.conditions);for(let[f,m]of Object.entries(t.fields||{}))["key","X-Amz-Algorithm","X-Amz-Credential","X-Amz-Date"].includes(f)||s.push({[f]:m});let o={expiration:e.toISOString(),conditions:s},a=new TextEncoder().encode(JSON.stringify(o)),u=btoa(String.fromCharCode(...a));i.policy=u;let c=u,l=await oE(t.date,t.region,t.secretKey),h=sl(await co(l,c)).toLowerCase();return i["X-Amz-Signature"]=h,{url:`${t.protocol}//${t.host}/${t.bucket}`,fields:i}}var jle=["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"],Ble=5*1024*1024,Mle=5*1024*1024*1024,uE=5*1024*1024*1024*1024,al=class{host;port;protocol;accessKey;#e;sessionToken;defaultBucket;region;userAgent="s3-lite-client";pathStyle;pathPrefix;constructor({endPoint:e,useSSL:r,port:n,pathPrefix:i,...s}){if(/^https?:\/\//i.test(e)){if(r!==void 0||n!==void 0||i!==void 0)throw new Yt("useSSL/port/pathPrefix cannot be specified if endPoint is a URL.");try{let a=new URL(e);e=a.hostname,r=a.protocol==="https:",n=a.port?parseInt(a.port,10):r?443:80,a.pathname&&a.pathname!=="/"&&(i=a.pathname.endsWith("/")?a.pathname.slice(0,-1):a.pathname)}catch{throw new nl(`Invalid endPoint URL: ${e}`)}}if(typeof e!="string"||e.length===0)throw new nl(`Invalid endPoint: ${e}`);if(r===void 0&&(r=!0),n!==void 0&&!IM(n))throw new Yt(`Invalid port: ${n}`);if(s.accessKey&&!s.secretKey)throw new Yt("If specifying access key, secret key must also be provided.");if(s.accessKey&&s.accessKey.startsWith("ASIA")&&!s.sessionToken)throw new Yt("If specifying temporary access key, session token must also be provided.");let o=r?443:80;if(this.port=n??o,this.host=e.toLowerCase()+(this.port!==o?`:${this.port}`:""),this.protocol=r?"https:":"http:",this.accessKey=s.accessKey,this.#e=s.secretKey??"",this.sessionToken=s.sessionToken,this.pathStyle=s.pathStyle??!0,this.pathPrefix=i??"",this.defaultBucket=s.bucket,this.region=s.region,this.pathPrefix){if(!this.pathStyle)throw new Yt("pathPrefix is incompatible with pathStyle=false");if(!this.pathPrefix.startsWith("/"))throw new Yt("pathPrefix should start with /");if(this.pathPrefix.endsWith("/"))throw new Yt("pathPrefix should not end with /")}}getBucketName(e){let r=e?.bucketName??this.defaultBucket;if(r===void 0||!kM(r))throw new zp(r??"");return r}buildRequestOptions(e){let r=this.getBucketName(e),n=this.pathStyle?this.host:`${r}.${this.host}`,i=e.headers??new Headers;i.set("host",n);let s=typeof e.query=="object"?new URLSearchParams(e.query).toString().replace("+","%20"):e.query,o=this.pathStyle?`${this.pathPrefix}/${r}/${e.objectName}`:`/${e.objectName}`,a=s?`?${s}`:"",u=o+a,c=o.split("/").map(l=>encodeURIComponent(l)).join("/")+a;return{headers:i,host:n,path:u,encodedPath:c}}async makeRequest({method:e,payload:r,...n}){let i=new Date,{headers:s,host:o,path:a,encodedPath:u}=this.buildRequestOptions(n),c=n.statusCode??200;if(e==="POST"||e==="PUT"||e==="DELETE")r===void 0?r=new Uint8Array:typeof r=="string"&&(r=new TextEncoder().encode(r)),s.set("Content-Length",String(r.length));else if(r)throw new Error(`Unexpected payload on ${e} request.`);let l=await Gp(r??new Uint8Array);s.set("x-amz-date",ao(i)),s.set("x-amz-content-sha256",l),this.accessKey&&(this.sessionToken&&s.set("x-amz-security-token",this.sessionToken),s.set("authorization",await PM({headers:s,method:e,path:a,accessKey:this.accessKey,secretKey:this.#e,region:this.region,date:i})));let h=`${this.protocol}//${o}${u}`,d=await fetch(h,{method:e,headers:s,body:r});if(d.status!==c)throw d.status>=400?await FM(d):d.status===301?new Di(d.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"'):new Di(d.status,"UnexpectedStatusCode",`Unexpected response code from the server (expected ${c}, got ${d.status} ${d.statusText}).`);return n.returnBody||await d.body?.getReader().read(),d}async deleteObject(e,r={}){let n=this.getBucketName(r);if(!us(e))throw new Bn(e);let i=r.versionId?{versionId:r.versionId}:{},s=new Headers;r.governanceBypass&&s.set("X-Amz-Bypass-Governance-Retention","true"),await this.makeRequest({method:"DELETE",bucketName:n,objectName:e,headers:s,query:i,statusCode:204})}async exists(e,r){try{return await this.statObject(e,r),!0}catch(n){if(n instanceof Di&&n.statusCode===404)return!1;throw n}}getObject(e,r){return this.getPartialObject(e,{...r,offset:0,length:0})}async getPartialObject(e,{offset:r,length:n,...i}){let s=this.getBucketName(i);if(!us(e))throw new Bn(e);let o=new Headers(Object.entries(i.metadata??{})),a=200;if(r||n){let c="";r?c=`bytes=${+r}-`:(c="bytes=0-",r=0),n&&(c+=`${+n+r-1}`),o.set("Range",c),a=206}let u={...i.responseParams,...i.versionId?{versionId:i.versionId}:{}};return await this.makeRequest({method:"GET",bucketName:s,objectName:e,headers:o,query:u,statusCode:a,returnBody:!0})}getPresignedUrl(e,r,n={}){if(!this.accessKey)throw new as;if(!us(r))throw new Bn(r);let{headers:i,path:s}=this.buildRequestOptions({objectName:r,bucketName:n.bucketName,query:n.parameters}),o=n.requestDate??new Date,a=n.expirySeconds??1440*60*7;return RM({protocol:this.protocol,headers:i,method:e,path:s,accessKey:this.accessKey,secretKey:this.#e,sessionToken:this.sessionToken,region:this.region,date:o,expirySeconds:a})}presignedGetObject(e,r={}){let{versionId:n,responseParams:i,...s}=r,o={...i,...n?{versionId:n}:{}};return this.getPresignedUrl("GET",e,{parameters:o,...s})}async*listObjects(e={}){for await(let r of this.listObjectsGrouped({...e,delimiter:""}))if(r.type==="Object")yield r;else throw new Error(`Unexpected result from listObjectsGrouped(): ${r}`)}async*listObjectsGrouped(e){let r=this.getBucketName(e),n="",i=e.pageSize??1e3;if(i<1||i>1e3)throw new Yt("pageSize must be between 1 and 1,000.");let s=0;for(;;){let o=e.maxResults?Math.min(i,e.maxResults-s):i;if(o===0)return;let u=await(await this.makeRequest({method:"GET",bucketName:r,objectName:"",query:{"list-type":"2",prefix:e.prefix??"",delimiter:e.delimiter,"max-keys":String(o),...n?{"continuation-token":n}:{}},returnBody:!0})).text(),c=os(u).root;if(!c||c.name!=="ListBucketResult")throw new Error(`Unexpected response: ${u}`);let l=c.children.filter(f=>f.name==="CommonPrefixes").flatMap(f=>f.children),h=[];for(let f of l)h.push({type:"CommonPrefix",prefix:f.content??""}),s++;for(let f of c.children.filter(m=>m.name==="Contents"))h.push({type:"Object",key:f.children.find(m=>m.name==="Key")?.content??"",etag:oo(f.children.find(m=>m.name==="ETag")?.content??""),size:parseInt(f.children.find(m=>m.name==="Size")?.content??"",10),lastModified:new Date(f.children.find(m=>m.name==="LastModified")?.content??"invalid")}),s++;h.sort((f,m)=>{let g=f.type==="Object"?f.key:f.prefix,b=m.type==="Object"?m.key:m.prefix;return g>b?1:g<b?-1:0});for(let f of h)yield f;if(c.children.find(f=>f.name==="IsTruncated")?.content==="true"){let f=c.children.find(m=>m.name==="NextContinuationToken")?.content;if(!f)throw new Error("Unexpectedly missing continuation token, but server said there are more results.");n=f}else return}}async putObject(e,r,n){let i=this.getBucketName(n);if(!us(e))throw new Bn(e);let s,o;if(typeof r=="string"){let l=new TextEncoder().encode(r);typeof ReadableStream.from<"u"?o=ReadableStream.from([l]):o=new ReadableStream({start(h){h.enqueue(l),h.close()}}),s=l.length}else if(r instanceof Uint8Array)typeof ReadableStream.from<"u"?o=ReadableStream.from([r]):o=new ReadableStream({start(l){l.enqueue(r),l.close()}}),s=r.byteLength;else if(r instanceof ReadableStream)o=r;else throw new Yt("Invalid stream/data type provided.");if(n?.size!==void 0){if(s!==void 0&&n?.size!==s)throw new Yt(`size was specified (${n.size}) but doesn't match auto-detected size (${s}).`);if(typeof n.size!="number"||n.size<0||isNaN(n.size))throw new Yt(`invalid size specified: ${n.size}`);s=n.size}let a=n?.partSize??this.calculatePartSize(s);if(a<Ble)throw new Yt("Part size should be greater than 5MB");if(a>Mle)throw new Yt("Part size should be less than 6MB");let u=new Vp(a),c=new Kp({client:this,bucketName:i,objectName:e,partSize:a,metadata:n?.metadata??{}});return await o.pipeThrough(u).pipeTo(c),c.getResult()}calculatePartSize(e){if(e===void 0&&(e=uE),e>uE)throw new TypeError(`size should not be more than ${uE}`);let r=64*1024*1024;for(;;){if(r*1e4>e)return r;r+=16*1024*1024}}async statObject(e,r){let n=this.getBucketName(r);if(!us(e))throw new Bn(e);let i={};r?.versionId&&(i.versionId=r.versionId);let s=await this.makeRequest({method:"HEAD",bucketName:n,objectName:e,query:i,headers:new Headers(r?.headers)}),o={};for(let a of jle)s.headers.has(a)&&(o[a]=s.headers.get(a));return s.headers.forEach((a,u)=>{u.startsWith("x-amz-meta-")&&(o[u]=s.headers.get(u))}),{type:"Object",key:e,size:parseInt(s.headers.get("content-length")??"",10),metadata:o,lastModified:new Date(s.headers.get("Last-Modified")??"error: missing last modified"),versionId:s.headers.get("x-amz-version-id")||null,etag:oo(s.headers.get("ETag")??"")}}async copyObject(e,r,n){let i=this.getBucketName(n),s=e.sourceBucketName??i;if(!us(r))throw new Bn(r);let o=`${s}/${e.sourceKey}`;e.sourceVersionId&&(o+=`?versionId=${e.sourceVersionId}`);let a=new Headers(n?.metadata);n?.metadata!==void 0&&a.set("x-amz-metadata-directive","REPLACE"),a.set("x-amz-copy-source",o);let u=await this.makeRequest({method:"PUT",bucketName:i,objectName:r,headers:a,returnBody:!0}),c=await u.text(),l=os(c).root;if(!l||l.name!=="CopyObjectResult")throw new Error(`Unexpected response: ${c}`);let h=l.children.find(f=>f.name==="ETag")?.content??"",d=l.children.find(f=>f.name==="LastModified")?.content;if(d===void 0)throw new Error("Unable to find <LastModified>...</LastModified> from the server.");return{copySourceVersionId:u.headers.get("x-amz-copy-source-version-id")||null,etag:oo(h),lastModified:new Date(d),versionId:u.headers.get("x-amz-version-id")||null}}async bucketExists(e){try{return await this.listObjects({bucketName:e}).next(),!0}catch(r){if(r instanceof Di&&r.statusCode===404)return!1;throw r}}async makeBucket(e){await this.makeRequest({method:"PUT",bucketName:this.getBucketName({bucketName:e}),objectName:"",statusCode:200})}async removeBucket(e){await this.makeRequest({method:"DELETE",bucketName:this.getBucketName({bucketName:e}),objectName:"",statusCode:204})}presignedPostObject(e,r={}){if(!us(e))throw new Bn(e);let n=this.getBucketName(r);if(!n)throw new Error("Bucket name is required for presignedPost, but none was provided either to this method nor to the client constructor");let i=r.requestDate||new Date,s=r.expirySeconds??3600;return jM({protocol:this.protocol,host:this.host,bucket:n,objectKey:e,accessKey:this.accessKey||"",secretKey:this.#e||"",region:this.region,date:i,expirySeconds:s,conditions:r.conditions,fields:r.fields})}};var lo=require("node:fs"),Wp=require("node:path");function qle(t,e){return(0,lo.readFileSync)(t,"utf8").includes(e)}function ul(t,e){let r=(0,lo.readdirSync)(t);for(let n of r){let i=(0,Wp.join)(t,n),s=(0,lo.statSync)(i);if(s.isDirectory()){if(ul(i,e))return!0}else if(s.isFile()&&(0,Wp.extname)(i)===".js"&&qle(i,e))return!0}return!1}function Xp(t){return(0,lo.readdirSync)(t).indexOf("index.html")>-1}var su=require("node:fs"),K6=require("node:os"),cs=require("node:path"),W6=require("node:process"),nm=require("node:stream/consumers"),X6=require("node:zlib");var Y6=xe(G6()),J6=xe(n0());async function rhe(t,e){try{return(await fetch(`${t.hostFilesApi}/files/read/attachments/${encodeURIComponent(e)}`,{method:"HEAD"})).ok}catch{return!1}}var Z6=8192,Q6="6.25.0",eq="7.0.35";async function nhe(t){let e=(0,cs.join)(Xr((0,W6.cwd)()),$n),n=(await Ln(void 0,t.packageJson||e)).get("@capgo/capacitor-updater"),i;try{i=n?Et(n):void 0}catch{i=void 0}if(!n||!i)return{version:null,supportsBrotliV2:!1};let s=i.major===6&&Ci(i,Et(Q6)),o=i.major>=7&&Ci(i,Et(eq)),a=s||o;return{version:`${i.major}.${i.minor}.${i.patch}`,supportsBrotliV2:a}}function ihe(t,e){if(!e)return!1;let r=e.split(",").map(n=>n.trim()).filter(n=>!!n);return r.length===0?!1:Y6.isMatch(t,r)}async function she(t,e,r){let i=(0,su.statSync)(t).size,s=await(0,nm.buffer)((0,su.createReadStream)(t));if(i===0)return{buffer:s,useBrotli:!1};if(ihe(e,r.noBrotliPatterns))return w.info(`Skipping brotli for excluded file: ${e}`),{buffer:s,useBrotli:!1};if(i<Z6)return{buffer:s,useBrotli:!1};try{let o=await(0,nm.buffer)((0,su.createReadStream)(t).pipe((0,X6.createBrotliCompress)({})));return o.length>=i-10?(w.info(`Brotli not effective for ${e} (${i} bytes), using original file`),{buffer:s,useBrotli:!1}):{buffer:o,useBrotli:!0}}catch(o){return w.warn(`Brotli compression failed for ${t}: ${o}, using original file`),{buffer:s,useBrotli:!1}}}async function tq(t,e,r,n,i,s){let o=Ft();o.start(i!=="v2"?"Generating the update manifest":"Generating the update manifest with v2 encryption");let a=await W8(t);if(i==="v2")for(let u of a)u.hash=tu(u.hash,s);return o.stop("Manifest generated successfully"),await Ae(e,{channel:"partial-update",event:"Generate manifest",icon:"\u{1F4C2}",user_id:r,tags:{"app-id":n},notify:!1}),a}function ohe(t){return(0,K6.platform)()!=="win32"?t:cs.win32.normalize(t).split(cs.win32.sep).join(cs.posix.sep)}function ahe(t){let e=t.split("/").map(r=>encodeURIComponent(r)).join("/");return t.includes(" ")&&w.warn(`File "${t}" contains spaces in its name.`),e}async function rq(t,e,r,n,i,s,o){let a=Ft();a.start("Preparing partial update with TUS protocol");let u=performance.now(),c=await wn(),l=!!(o.partial||o.delta||o.partialOnly||o.deltaOnly),{version:h,supportsBrotliV2:d}=await nhe(o);if(d)o.disableBrotli?w.info("Brotli compression disabled by user request"):(a.message(`Using .br extension for compatible files (updater ${h})`),o.noBrotliPatterns&&w.info(`Files matching patterns (${o.noBrotliPatterns}) will be excluded from brotli compression`),w.info(`Files smaller than ${Z6} bytes will be excluded from brotli compression (Brotli RFC minimum)`));else throw new Error(`Your project is using an older version of @capgo/capacitor-updater (${h||"unknown"}). To use Delta updates, please upgrade to version ${Q6} (v6) or ${eq} (v7) or higher.`);let f=e.filter(S=>S.file.includes(" "));if(f.length>0)throw new Error(`Files with spaces in their names (${f.map(S=>S.file).join(", ")}). Please rename the files.`);let m=0,g=e.length,b=0;try{let S=e.map(async y=>{let C=(0,cs.join)(r,y.file),k=ohe(y.file),v,R=!1;if(o.disableBrotli)v=await(0,nm.buffer)((0,su.createReadStream)(C)),R=!1;else{let G=await she(C,k,o);v=G.buffer,R=G.useBrotli}let P=v;s&&(P=eu(v,s.sessionKey,s.ivSessionKey));let F=k;R&&(F=`${k}.br`,b++);let j=ahe(F),U=`orgs/${i}/apps/${n}/delta/${y.hash}_${j}`;return await rhe(c,U)?(m++,Promise.resolve({file_name:j,s3_path:U,file_hash:y.hash})):new Promise((G,L)=>{let _=0,T=3,I=()=>{new J6.Upload(P,{endpoint:`${c.hostFilesApi}/files/upload/attachments/`,chunkSize:o.tusChunkSize,retryDelays:[0,1e3,3e3,5e3],removeFingerprintOnSuccess:!0,metadata:{filename:U},headers:{Authorization:t},onError:async M=>{let B=M.toString();if(B.includes("offset")||B.includes("409")||B.includes("conflict"))if(_++,_<=T){w.warn(`Offset mismatch for ${k}, retrying (attempt ${_}/${T})...`),await new Promise(K=>setTimeout(K,1e3*_)),I();return}else w.error(`Failed to upload ${k} after ${T} retries due to offset errors`),w.info("This may happen if the upload expired or there was a network issue. The file will be skipped.");else w.error(`Failed to upload ${k}: ${B}`);L(M)},onProgress(){let M=(m/g*100).toFixed(2);a.message(`Uploading partial update: ${M}%`)},onSuccess(){m++,G({file_name:j,s3_path:U,file_hash:y.hash})}}).start()};I()})}),A=await Promise.all(S),D=((performance.now()-u)/1e3).toFixed(2);return a.stop(`Partial update uploaded successfully \u{1F4AA} in (${D} seconds)`),b>0&&w.info(`${b} of ${g} files were compressed with brotli and use .br extension`),await Ae(t,{channel:"app",event:`App Partial TUS done${b>0?" with .br extension":""}`,icon:"\u23EB",user_id:i,tags:{"app-id":n},notify:!1}),await Ae(t,{channel:"performance",event:"Partial upload performance",icon:"\u{1F684}",user_id:i,tags:{"app-id":n,time:D},notify:!1}),A}catch(S){let p=((performance.now()-u)/1e3).toFixed(2);if(a.stop(`Failed to upload Partial bundle (after ${p} seconds)`),l)throw w.error(`Error uploading partial update: ${S}`),w.error("Delta/partial upload was explicitly requested but failed. Upload aborted."),S;return w.info(`Error uploading partial update: ${S}, This is not a critical error, the bundle has been uploaded without the partial files`),null}}function gt(t){throw w.error(t),new Error(t)}async function uhe(t,e){let r=is("",e.packageJson),n=e.bundle||t?.plugins?.CapacitorUpdater?.version||r||`0.0.1-beta.${(0,nq.randomUUID)().split("-")[0]}`;return Wa.test(n)||gt(`Your bundle name ${n}, is not valid it should follow semver convention : https://semver.org/`),n}function che(t){let e=t.apikey||ne();return e||gt("Missing API key, you need to provide an API key to upload your bundle"),e}function lhe(t,e,r){let n=Pe(t,r),i=e.path||r?.webDir;return n||gt("Missing argument, you need to provide a appid or be in a capacitor project"),i||gt("Missing argument, you need to provide a path (--path), or be in a capacitor project"),(0,po.existsSync)(i)||gt(`Path ${i} does not exist, build your app first, or provide a valid path`),{appid:n,path:i}}function fhe(t,e){let r=t.codeCheck;(typeof r>"u"||r)&&(ul(e,"notifyAppReady")||gt(`notifyAppReady() is missing in the build folder of your app. see: https://capgo.app/docs/plugin/api/#notifyappready
|
|
329
329
|
If you are sure your app has this code, you can use the --no-code-check option`),Xp(e)||gt(`index.html is missing in the root folder of ${e}`))}async function hhe(t,e,r,n,i,s){let o=r.ignoreMetadataCheck,a=r.autoMinUpdateVersion,u=r.minUpdateVersion,{data:c,error:l}=await t.from("channels").select("disable_auto_update, version ( min_update_version, native_packages )").eq("name",n).eq("app_id",i).single(),h=!!c&&c.disable_auto_update==="version_number",d,f;if(!l&&c&&c.version&&c.version.native_packages&&!o){let b=Ft();b.start(`Checking bundle compatibility with channel ${n}`);let{finalCompatibility:S,localDependencies:A}=await jp(t,i,n,r.packageJson,r.nodeModules);if(f=S,d=A,f.find(p=>!so(p)))b.stop(`Bundle NOT compatible with ${n} channel`),w.warn(`You can check compatibility with "${e.runner} @capgo/cli bundle compatibility"`),a&&(u=s,w.info(`Auto set min-update-version to ${u}`));else if(a)try{let{min_update_version:p}=c.version;(!p||!Wa.test(p))&>("Invalid remote min update version, skipping auto setting compatibility"),u=p,b.stop(`Auto set min-update-version to ${u}`)}catch{gt(`Cannot auto set compatibility, invalid data ${c}`)}else b.stop(`Bundle compatible with ${n} channel`)}else o||(w.warn(`Channel ${n} is new or it's your first upload with compatibility check, it will be ignored this time`),d=await Jv(r.packageJson,r.nodeModules),a&&(u=s,w.info(`Auto set min-update-version to ${u}`)));h&&!u&&!o&>("You need to provide a min-update-version to upload a bundle to this channel"),u&&(Wa.test(u)||gt(`Your minimal version update ${u}, is not valid it should follow semver convention : https://semver.org/`));let m=d?new Map(d.filter(b=>!!b.native&&b.native!==void 0).map(b=>[b.name,b])):new Map;return{nativePackages:m.size>0||!r.ignoreMetadataCheck?Array.from(m,([b,S])=>({name:b,version:S.version})):void 0,minUpdateVersion:u}}async function dhe(t,e,r){let{data:n,error:i}=await t.rpc("is_trial_org",{orgid:e}).single();(n&&n>0||i)&&(w.warn(`WARNING !!
|
|
330
330
|
Trial expires in ${n} days`),w.warn(`Upgrade here: ${r.hostWeb}/dashboard/settings/plans?oid=${e}`))}async function phe(t,e,r,n=!1){let{data:i,error:s}=await t.rpc("exist_app_versions",{appid:e,name_version:r}).single();if(i||s){if(n)return w.warn(`Version ${r} already exists - exiting gracefully due to --silent-fail option`),ce("Bundle version already exists - exiting gracefully \u{1F389}"),!0;gt(`Version ${r} already exists ${W(s)}`)}return!1}async function mhe(t,e,r,n,i,s,o){let a,u,c="",l=null,h="none",d="",f=e.keyV2,m=e.key===!1;l=await Np(t);let g=Ft();g.start("Calculating checksum");let b=(0,SE.join)(Xr((0,AE.cwd)()),$n),A=(await Ln(void 0,e.packageJson||b)).get("@capgo/capacitor-updater"),p=!1,D;try{D=A?Et(A):void 0}catch{D=void 0}if(A?D?p=Ci(D,Et("6.25.0")):(A==="link:@capgo/capacitor-updater"||A==="file:.."||A==="file:../")&&(w.warn("Using local @capgo/capacitor-updater. Assuming latest version for checksum calculation."),p=!0):gt("Cannot find @capgo/capacitor-updater in ./package.json, provide the package.json path with --package-json it's required for v7 CLI to work"),(f||e.keyDataV2||(0,po.existsSync)(Ir))&&!m||p?c=await Jn(l,"sha256"):c=await Jn(l,"crc32"),g.stop(`Checksum ${p?"SHA256":"CRC32"}: ${c}`),m)w.info("Encryption ignored");else if((f||(0,po.existsSync)(Ir)||e.keyDataV2)&&!e.oldEncryption){let k=typeof f=="string"?f:Ir,v=e.keyDataV2||"";!v&&!(0,po.existsSync)(k)&>(`Cannot find private key ${k}`),await Ae(r,{channel:"app",event:"App encryption v2",icon:"\u{1F511}",user_id:n,tags:{"app-id":i},notify:!1},e.verbose),v||(v=(0,po.readFileSync)(k).toString()),w.info("Encrypting your bundle with V2");let{sessionKey:R,ivSessionKey:P}=Hp(v),F=eu(l,R,P);c=tu(c,v),a=P,u=R,h="v2",d=v,e.displayIvSession&&w.info(`Your Iv Session key is ${a},
|
|
331
331
|
keep it safe, you will need it to decrypt your bundle.
|
|
@@ -334,7 +334,7 @@ Trial expires in ${n} days`),w.warn(`Upgrade here: ${r.hostWeb}/dashboard/settin
|
|
|
334
334
|
The bundle size is ${y} Mb, this may take a while to download for users
|
|
335
335
|
`),w.info(`Learn how to optimize your assets https://capgo.app/blog/optimise-your-images-for-updates/
|
|
336
336
|
`),e.verbose&&(w.info("[Verbose] Bundle size details:"),w.info(` - Actual size: ${y} MB (${l?.byteLength} bytes)`),w.info(` - Alert threshold: ${Math.floor(o/1024/1024)} MB`),w.info(` - Maximum allowed: ${C} MB`),w.info("[Verbose] Sending 'App Too Large' event to analytics...")),await Ae(r,{channel:"app-error",event:"App Too Large",icon:"\u{1F69B}",user_id:n,tags:{"app-id":i},notify:!1},e.verbose),e.verbose&&w.info("[Verbose] Event sent successfully")):e.verbose&&w.info(`[Verbose] Bundle size OK: ${y} MB (under ${Math.floor(o/1024/1024)} MB alert threshold)`),e.verbose&&w.info("[Verbose] Bundle preparation complete, returning bundle data"),{zipped:l,ivSessionKey:a,sessionKey:u,checksum:c,encryptionMethod:h,finalKeyData:d}}async function ghe(t,e,r,n,i,s,o,a){let u=Ft();u.start("Uploading Bundle");let c=performance.now(),l=!1;if(o.verbose&&(w.info("[Verbose] uploadBundleToCapgoCloud called:"),w.info(` - Bundle size: ${Math.floor(s.byteLength/1024)} KB`),w.info(` - App ID: ${r}`),w.info(` - Bundle version: ${n}`),w.info(` - Chunk size: ${Math.floor(a/1024/1024)} MB`)),o.dryUpload){u.stop(`Dry run, bundle not uploaded
|
|
337
|
-
Bundle uploaded \u{1F4AA} in 0 seconds`),o.verbose&&w.info("[Verbose] Dry upload mode - skipping actual upload");return}try{let f=await wn();if(o.verbose&&w.info("[Verbose] Local config retrieved for upload"),o.multipart!==void 0&&o.multipart||o.tus!==void 0&&o.tus){o.multipart?w.info("Uploading bundle with multipart is deprecated, we upload with TUS instead"):w.info("Uploading bundle with TUS protocol"),o.verbose&&(w.info("[Verbose] Starting TUS resumable upload..."),w.info(` - Host: ${f.hostWeb}`),w.info(` - Chunk size: ${Math.floor(a/1024/1024)} MB`)),await X8(t,s,i,r,n,u,f,a),l=!0,o.verbose&&w.info("[Verbose] TUS upload completed, updating database with R2 path...");let m=`orgs/${i}/apps/${r}/${n}.zip`,{error:g}=await e.from("app_versions").update({r2_path:m}).eq("name",n).eq("app_id",r);if(g)return w.error(`Cannot finish TUS upload ${W(g)}`),o.verbose&&w.info(`[Verbose] Database update failed: ${W(g)}`),Promise.reject(new Error("Cannot finish TUS upload"));o.verbose&&w.info(`[Verbose] Database updated with R2 path: ${m}`)}else{o.verbose&&w.info("[Verbose] Using standard upload (non-TUS), getting presigned URL...");let m=await G8(e,r,n);if(!m)return w.error("Cannot get upload url"),o.verbose&&w.info("[Verbose] Failed to retrieve presigned upload URL from database"),Promise.reject(new Error("Cannot get upload url"));o.verbose&&(w.info("[Verbose] Presigned URL obtained, uploading via HTTP PUT..."),w.info(` - Timeout: ${o.timeout||Xv}ms`),w.info(" - Retry attempts: 5"),w.info(" - Content-Type: application/zip"));let g=new AbortController,b=setTimeout(()=>g.abort(),o.timeout||Xv);try{let S=await fetch(m,{method:"PUT",body:s,headers:{"Content-Type":"application/zip"},signal:g.signal});if(!S.ok)throw new Error(`HTTP error! status: ${S.status}`)}finally{clearTimeout(b)}o.verbose&&w.info("[Verbose] HTTP PUT upload completed successfully")}}catch(f){let g=((performance.now()-c)/1e3).toFixed(2);if(u.stop(`Failed to upload bundle ( after ${g} seconds)`),o.verbose&&(w.info(`[Verbose] Upload failed after ${g} seconds`),w.info(`[Verbose] Error type: ${f instanceof Error?"Error":typeof f}`)),f instanceof Error&&f.message.includes("HTTP error"))try{let b=f.message.match(/status: (\d+)/),S=b?b[1]:"unknown";w.error(`Upload failed with status ${S}: ${f.message}`)}catch{w.error(`Upload failed: ${f.message}`)}else o.verbose&&w.info(`[Verbose] Non-HTTP error: ${W(f)}`),o.tus?w.error(`Cannot upload bundle please contact support if the issue persists ${W(f)}`):w.error(`Cannot upload bundle ( try again with --tus option) ${W(f)}`);throw o.verbose&&w.info("[Verbose] Cleaning up failed version from database..."),await Y8(e,r,n),o.verbose&&w.info("[Verbose] Failed version cleaned up"),f instanceof Error?f:new Error(String(f))}let d=((performance.now()-c)/1e3).toFixed(2);u.stop(`Bundle uploaded \u{1F4AA} in (${d} seconds)`),o.verbose&&(w.info("[Verbose] Upload successful:"),w.info(` - Upload time: ${d} seconds`),w.info(` - Upload method: ${l?"TUS (resumable)":"Standard HTTP PUT"}`),w.info(` - Bundle size: ${Math.floor(s.byteLength/1024)} KB`),w.info("[Verbose] Sending performance event...")),await Ae(t,{channel:"performance",event:l?"TUS upload zip performance":"Upload zip performance",icon:"\u{1F684}",user_id:i,tags:{"app-id":r,time:d},notify:!1},o.verbose),o.verbose&&w.info("[Verbose] Performance event sent successfully")}async function yhe(t,e,r){let{data:n,error:i}=await t.from("channels").select("version ( id, name, deleted )").eq("app_id",e).eq("name",r);if(i){w.error(`Cannot delete linked bundle on upload ${W(i)}`);return}if(n.length===0){w.warn("No linked bundle found in the channel you are trying to upload to");return}let s=n[0].version;if(s.deleted){w.warn("The linked bundle is already deleted");return}let{error:o}=await t.from("app_versions").update({deleted:!0}).eq("id",s.id);if(o){w.error(`Cannot delete linked bundle on upload ${W(o)}`);return}w.info("Linked bundle deleted")}async function Dhe(t,e,r,n,i,s,o,a,u,c){let{data:l}=await t.rpc("get_app_versions",{apikey:e,name_version:n,appid:a}).single();l||gt("Cannot get version id, cannot set channel");let{data:h}=await t.rpc("is_allowed_capgkey",{apikey:e,keymode:["write","all"]}).single();if(h){let{error:d,data:f}=await $p(t,{name:i,app_id:a,created_by:s,version:l,owner_org:o,...c?{allow_device_self_set:!0}:{}});d&>(`Cannot set channel, the upload key is not allowed to do that, use the "all" for this. ${W(d)}`);let m=`${u.hostWeb}/app/p/${a}/channel/${f.id}`;f?.public?w.info("Your update is now available in your public channel \u{1F389}"):f?.id&&w.info(`Link device to this bundle to try it: ${m}`),r&&w.info(`Bundle url: ${m}`)}else w.warn("The upload key is not allowed to set the version in the channel")}async function whe(t,e,r){let{error:n,data:i}=await e.from("apps").select("default_upload_channel").eq("app_id",t).single();return n?(w.warn("Cannot find default upload channel"),w.info(`You can set it here: ${r}/app/p/${t}/settings`),null):i.default_upload_channel}async function iq(t,e,r=!1){r||oe(`Uploading with CLI version ${Ri.version}`);let n,i=Nn();await ze();let{s3Region:s,s3Apikey:o,s3Apisecret:a,s3BucketName:u,s3Endpoint:c,s3Port:l,s3SSL:h}=e;e.verbose&&(w.info("[Verbose] Starting upload process with options:"),w.info(` - API key: ${e.apikey?"provided":"from saved key"}`),w.info(` - Path: ${e.path||"from capacitor config"}`),w.info(` - Channel: ${e.channel||"from default upload channel"}`),w.info(` - Bundle: ${e.bundle||"auto-detected"}`),w.info(` - External: ${e.external||"false"}`),w.info(` - Encryption: ${e.keyV2||e.keyDataV2?"v2":e.key===!1?"disabled":"auto"}`),w.info(` - Upload method: ${e.tus?"TUS":e.zip?"ZIP":"auto"}`),w.info(` - Delta updates: ${e.delta||e.partial?"enabled":"disabled"}`));let d=che(e);e.verbose&&w.info("[Verbose] API key retrieved successfully");let f=await de();e.verbose&&w.info("[Verbose] Capacitor config loaded successfully");let m=await B8();e.verbose&&(w.info("[Verbose] Remote file config retrieved:"),w.info(` - Max upload length: ${Math.floor(m.maxUploadLength/1024/1024)} MB`),w.info(` - Alert upload size: ${Math.floor(m.alertUploadSize/1024/1024)} MB`),w.info(` - TUS upload: ${m.TUSUpload?"enabled":"disabled"}`),w.info(` - TUS upload forced: ${m.TUSUploadForced?"yes":"no"}`),w.info(` - Partial upload: ${m.partialUpload?"enabled":"disabled"}`),w.info(` - Max chunk size: ${Math.floor(m.maxChunkSize/1024/1024)} MB`));let{appid:g,path:b}=lhe(t,e,f.config);e.verbose&&w.info(`[Verbose] App ID: ${g}, Build path: ${b}`);let S=await uhe(f.config,e);e.verbose&&w.info(`[Verbose] Bundle version: ${S}`);let A=e.external?"external":"r2-direct",p="none";e.autoSetBundle&&(await j8({version:S}),e.verbose&&w.info("[Verbose] Auto-set bundle version in capacitor.config.json")),fhe(e,b),e.verbose&&w.info("[Verbose] Code check passed (notifyAppReady found and index.html present)"),w.info(`Upload ${g}@${S} started from path "${b}" to Capgo cloud`);let D=await wn();e.verbose&&w.info(`[Verbose] Local config loaded: host=${D.hostWeb}`),e.supaHost&&e.supaAnon&&(w.info("Using custom supabase instance from provided options"),D.supaHost=e.supaHost,D.supaKey=e.supaAnon,e.verbose&&w.info(`[Verbose] Custom Supabase host: ${e.supaHost}`));let y=await pe(d,e.supaHost,e.supaAnon);e.verbose&&w.info("[Verbose] Supabase client created successfully");let C=await De(y,d,["write","all","upload"]);e.verbose&&w.info(`[Verbose] User verified successfully, user_id: ${C}`);let k=e.channel||await whe(g,y,D.hostWeb)||"dev";e.verbose&&w.info(`[Verbose] Target channel: ${k}`);let v=await sn(y,g);e.verbose&&w.info(`[Verbose] Organization ID: ${v}`),await H8(y,v,Ri.version),e.verbose&&w.info("[Verbose] Remote CLI messages checked"),await z8(y,v,d,g,!0),e.verbose&&w.info("[Verbose] Plan validation passed"),await dhe(y,v,D),e.verbose&&w.info("[Verbose] Trial check completed"),e.verbose&&w.info(`[Verbose] Checking compatibility with channel ${k}...`);let{nativePackages:R,minUpdateVersion:P}=await hhe(y,i,e,k,g,S);e.verbose&&(w.info("[Verbose] Compatibility check completed:"),w.info(` - Native packages: ${R?R.length:0}`),w.info(` - Min update version: ${P||"none"}`)),e.verbose&&w.info(`[Verbose] Checking if version ${S} already exists...`);let F=await phe(y,g,S,e.versionExistsOk);if(e.verbose&&w.info(`[Verbose] Version exists check: ${F?"yes (skipping)":"no (continuing)"}`),F)return{success:!0,skipped:!0,reason:"VERSION_EXISTS",bundle:S,checksum:null,encryptionMethod:p,storageProvider:A};e.external&&!e.external.startsWith("https://")&>(`External link should should start with "https://" current is "${e.external}"`),e.deleteLinkedBundleOnUpload&&(w.warn("Deleting linked bundle on upload is destructive, it will delete the currently linked bundle in the channel you are trying to upload to."),w.warn("Please make sure you want to do this, if you are not sure, please do not use this option."));let j={name:S,app_id:g,session_key:void 0,external_url:e.external,storage_provider:A,min_update_version:P,native_packages:R,owner_org:v,user_id:C,checksum:void 0,link:e.link||null,comment:e.comment||null},U=null,G="";if(e.external)e.verbose&&w.info(`[Verbose] Using external URL: ${e.external}`),await Ae(d,{channel:"app",event:"App external",icon:"\u{1F4E4}",user_id:v,tags:{"app-id":g},notify:!1},e.verbose),j.session_key=e.ivSessionKey,j.checksum=e.encryptedChecksum,e.verbose&&(w.info("[Verbose] External bundle configured:"),w.info(` - URL: ${e.external}`),w.info(` - IV Session Key: ${e.ivSessionKey?"provided":"none"}`),w.info(` - Encrypted Checksum: ${e.encryptedChecksum?"provided":"none"}`));else{e.verbose&&w.info(`[Verbose] Preparing bundle file from path: ${b}`);let{zipped:$,ivSessionKey:M,checksum:B,sessionKey:K,encryptionMethod:q,finalKeyData:V}=await mhe(b,e,d,v,g,m.maxUploadLength,m.alertUploadSize);j.session_key=M,j.checksum=B,n=K,U=$,p=q,G=V,e.verbose&&(w.info("[Verbose] Bundle prepared:"),w.info(` - Size: ${Math.floor(($?.byteLength??0)/1024)} KB`),w.info(` - Checksum: ${B}`),w.info(` - Encryption: ${q}`),w.info(` - IV Session Key: ${M?"present":"none"}`)),e.ignoreChecksumCheck||(e.verbose&&w.info("[Verbose] Checking for duplicate checksum..."),await Q8(y,g,k,B),e.verbose&&w.info("[Verbose] Checksum is unique"))}if(e.zip?(e.tus=!1,e.verbose&&w.info("[Verbose] Upload method: ZIP (explicitly set via --zip)")):!m.TUSUpload||e.external?(e.tus=!1,e.verbose&&w.info("[Verbose] Upload method: Standard (TUS not available or external URL)")):(e.tus=e.tus||m.TUSUploadForced,e.verbose&&w.info(`[Verbose] Upload method: ${e.tus?"TUS (resumable)":"Standard"}`)),!m.partialUpload||e.external?(e.delta=!1,e.verbose&&e.external&&w.info("[Verbose] Delta updates disabled (not available with external URLs)")):(e.delta=e.delta||e.partial||e.deltaOnly||e.partialOnly||m.partialUploadForced,e.verbose&&w.info(`[Verbose] Delta updates: ${e.delta?"enabled":"disabled"}`)),e.encryptPartial&&p==="v1"&>("You cannot encrypt the partial update if you are not using the v2 encryption method"),e.delta&&p==="v2"&&!e.encryptPartial){let $=(0,SE.join)(Xr((0,AE.cwd)()),$n),B=(await Ln(void 0,e.packageJson||$)).get("@capgo/capacitor-updater"),K;try{K=B?Et(B):void 0}catch{K=void 0}B&&K&&Ci(K,Et("6.14.4"))&&(w.info(`Auto-enabling partial update encryption for updater version ${K} (> 6.14.4)`),e.verbose&&w.info("[Verbose] Partial encryption auto-enabled for updater >= 6.14.4"),e.encryptPartial=!0)}e.verbose&&e.delta&&w.info("[Verbose] Preparing delta/partial update manifest...");let L=e.delta?await tq(b,d,v,g,e.encryptPartial?p:"none",G):[];e.verbose&&e.delta&&w.info(`[Verbose] Delta manifest prepared with ${L.length} files`),e.verbose&&w.info("[Verbose] Creating version record in database...");let{error:_}=await Yv(y,j);if(_&>(`Cannot add bundle ${W(_)}`),e.verbose&&w.info("[Verbose] Version record created successfully"),e.tusChunkSize&&e.tusChunkSize>m.maxChunkSize?(w.error(`Chunk size ${e.tusChunkSize} is greater than the maximum chunk size ${m.maxChunkSize}, using the maximum chunk size`),e.tusChunkSize=m.maxChunkSize):e.tusChunkSize||(e.tusChunkSize=m.maxChunkSize),e.verbose&&w.info(`[Verbose] TUS chunk size: ${Math.floor(e.tusChunkSize/1024/1024)} MB`),U&&(u||c||s||o||a||l||h)){(!u||!c||!s||!o||!a||!l)&>("Missing argument, for S3 upload you need to provide a bucket name, endpoint, region, port, API key, and API secret"),w.info("Uploading to S3"),e.verbose&&(w.info("[Verbose] S3 configuration:"),w.info(` - Endpoint: ${c}`),w.info(` - Region: ${s}`),w.info(` - Bucket: ${u}`),w.info(` - Port: ${l}`),w.info(` - SSL: ${h?"enabled":"disabled"}`));let $=h?`https://${c}`:`http://${c}`,M=new al({endPoint:c,region:s,port:l,pathStyle:!0,bucket:u,accessKey:o,secretKey:a}),B=`${g}-${S}`,K=encodeURIComponent(B);e.verbose&&w.info(`[Verbose] Uploading to S3 as: ${B}`),await M.putObject(B,Uint8Array.from(U)),j.external_url=`${$}/${K}`,j.storage_provider="external",e.verbose&&w.info(`[Verbose] S3 upload complete, external URL: ${j.external_url}`)}else if(U){!e.partialOnly&&!e.deltaOnly?(e.verbose&&w.info("[Verbose] Starting full bundle upload to Capgo Cloud..."),await ghe(d,y,g,S,v,U,e,e.tusChunkSize)):e.verbose&&w.info("[Verbose] Skipping full bundle upload (delta-only mode)");let $=null;try{e.dryUpload&&(e.delta=!1,e.verbose&&w.info("[Verbose] Dry upload mode: skipping delta upload"));let B=j.session_key&&e.encryptPartial&&n?{sessionKey:n,ivSessionKey:j.session_key}:void 0;e.verbose&&e.delta&&(w.info("[Verbose] Starting delta/partial file upload..."),w.info(` - Manifest entries: ${L.length}`),w.info(` - Encryption: ${B?"enabled":"disabled"}`)),$=e.delta?await rq(d,L,b,g,S,v,B,e):null,e.verbose&&$&&w.info(`[Verbose] Delta upload complete with ${$.length} files`)}catch(B){w.info(`Failed to upload partial files to capgo cloud. Error: ${W(B)}. This is not a critical error, the bundle has been uploaded without the partial files`),e.verbose&&w.info(`[Verbose] Delta upload error details: ${W(B)}`)}j.storage_provider="r2",j.manifest=$,e.verbose&&w.info("[Verbose] Updating version record with storage provider and manifest...");let{error:M}=await Yv(y,j);M&>(`Cannot update bundle ${W(M)}`),e.verbose&&w.info("[Verbose] Version record updated successfully")}e.verbose&&w.info("[Verbose] Checking app permissions...");let T=await mt(y,d,g,2);e.verbose&&(w.info("[Verbose] Permissions:"),w.info(` - Upload: ${Xa(T,2)?"yes":"no"}`),w.info(` - Write: ${Xa(T,3)?"yes":"no"}`),w.info(` - Admin: ${Xa(T,4)?"yes":"no"}`)),e.deleteLinkedBundleOnUpload&&Xa(T,3)?(e.verbose&&w.info(`[Verbose] Deleting linked bundle in channel ${k}...`),await yhe(y,g,k)):e.deleteLinkedBundleOnUpload&&w.warn("Cannot delete linked bundle on upload as a upload organization member"),Xa(T,3)?(e.verbose&&w.info(`[Verbose] Setting bundle ${S} to channel ${k}...`),await Dhe(y,d,!!e.bundleUrl,S,k,C,v,g,D,e.selfAssign),e.verbose&&w.info("[Verbose] Channel updated successfully")):w.warn("Cannot set channel as a upload organization member"),e.verbose&&w.info("[Verbose] Sending upload event..."),await Ae(d,{channel:"app",event:"App Uploaded",icon:"\u23EB",user_id:v,tags:{"app-id":g},notify:!1},e.verbose);let I={success:!0,bundle:S,checksum:j.checksum??null,encryptionMethod:p,sessionKey:n?n.toString("base64"):void 0,ivSessionKey:typeof j.session_key=="string"?j.session_key:void 0,storageProvider:j.storage_provider};return e.verbose&&(w.info("[Verbose] Upload completed successfully:"),w.info(` - Bundle: ${I.bundle}`),w.info(` - Checksum: ${I.checksum}`),w.info(` - Encryption: ${I.encryptionMethod}`),w.info(` - Storage: ${I.storageProvider}`)),r&&!I.skipped&&ce("Time to share your update to the world \u{1F30D}"),I}var sq=require("node:crypto"),im=require("node:fs"),oq=require("node:path"),aq=require("node:process");var bhe=20;function vhe(t){console.log(JSON.stringify(t,null,2))}function dl(t){console.error(W(t))}async function uq(t,e,r=!1){let{json:n}=e,{bundle:i,path:s}=e,o=!n&&!r;try{o&&await ze();let a=await de(),u=Pe(t,a?.config),c=(0,sq.randomUUID)().split("-")[0],l=is("",e.packageJson);if(i=i||l||`0.0.1-beta.${c}`,o&&oe(`Zipping ${u}@${i}`),i&&!Wa.test(i)){let k=`Your bundle name ${i}, is not valid it should follow semver convention : https://semver.org/`;throw r||(n?dl({error:"invalid_semver"}):w.error(k)),new Error("Invalid bundle version format")}if(s=s||a?.config?.webDir,!u||!i||!s){let k="Missing argument, you need to provide a appId and a bundle and a path, or be in a capacitor project";throw r||(n?dl({error:"missing_argument"}):w.error(k)),new Error(k)}if(o&&w.info(`Started from path "${s}"`),typeof e.codeCheck>"u"?!0:e.codeCheck){if(!ul(s,"notifyAppReady"))throw r||(n?dl({error:"notifyAppReady_not_in_source_code"}):w.error("notifyAppReady() is missing in the build folder of your app. see: https://capgo.app/docs/plugin/api/#notifyappready")),new Error("notifyAppReady() is missing in build folder");if(!Xp(s))throw r||(n?dl({error:"index_html_not_found"}):w.error(`index.html is missing in the root folder of ${s}`)),new Error("index.html is missing in root folder")}let d=await Np(s);o&&w.info(`Zipped ${d.byteLength} bytes`);let f=o?Ft():null;f&&f.start("Calculating checksum");let m=(0,oq.join)(Xr((0,aq.cwd)()),$n),b=(await Ln(void 0,e.packageJson||m)).get("@capgo/capacitor-updater");if(!b){let k="Cannot find @capgo/capacitor-updater in ./package.json, provide the package.json path with --package-json it's required for v7 CLI to work";throw r||w.warn(k),new Error(k)}let S=!1,A;try{A=b?Et(b):void 0}catch{A=void 0}if(A){let k=A.major===6&&Ci(A,Et("6.25.0")),v=A.major>=7;S=k||v}else b==="link:@capgo/capacitor-updater"&&(r||w.warn("Using local @capgo/capacitor-updater. Assuming v7"),S=!0);let p=await Jn(d,e.keyV2||(0,im.existsSync)(Ir)||S?"sha256":"crc32");f&&f.stop(`Checksum ${S?"SHA256":"CRC32"}: ${p}`);let D=Math.floor(d.byteLength/1024/1024);D>bhe&&o&&(w.warn(`WARNING !!
|
|
337
|
+
Bundle uploaded \u{1F4AA} in 0 seconds`),o.verbose&&w.info("[Verbose] Dry upload mode - skipping actual upload");return}try{let f=await wn();if(o.verbose&&w.info("[Verbose] Local config retrieved for upload"),o.multipart!==void 0&&o.multipart||o.tus!==void 0&&o.tus){o.multipart?w.info("Uploading bundle with multipart is deprecated, we upload with TUS instead"):w.info("Uploading bundle with TUS protocol"),o.verbose&&(w.info("[Verbose] Starting TUS resumable upload..."),w.info(` - Host: ${f.hostWeb}`),w.info(` - Chunk size: ${Math.floor(a/1024/1024)} MB`)),await X8(t,s,i,r,n,u,f,a),l=!0,o.verbose&&w.info("[Verbose] TUS upload completed, updating database with R2 path...");let m=`orgs/${i}/apps/${r}/${n}.zip`,{error:g}=await e.from("app_versions").update({r2_path:m}).eq("name",n).eq("app_id",r);if(g)return w.error(`Cannot finish TUS upload ${W(g)}`),o.verbose&&w.info(`[Verbose] Database update failed: ${W(g)}`),Promise.reject(new Error("Cannot finish TUS upload"));o.verbose&&w.info(`[Verbose] Database updated with R2 path: ${m}`)}else{o.verbose&&w.info("[Verbose] Using standard upload (non-TUS), getting presigned URL...");let m=await G8(e,r,n);if(!m)return w.error("Cannot get upload url"),o.verbose&&w.info("[Verbose] Failed to retrieve presigned upload URL from database"),Promise.reject(new Error("Cannot get upload url"));o.verbose&&(w.info("[Verbose] Presigned URL obtained, uploading via HTTP PUT..."),w.info(` - Timeout: ${o.timeout||Xv}ms`),w.info(" - Retry attempts: 5"),w.info(" - Content-Type: application/zip"));let g=new AbortController,b=setTimeout(()=>g.abort(),o.timeout||Xv);try{let S=await fetch(m,{method:"PUT",body:s,headers:{"Content-Type":"application/zip"},signal:g.signal});if(!S.ok)throw new Error(`HTTP error! status: ${S.status}`)}finally{clearTimeout(b)}o.verbose&&w.info("[Verbose] HTTP PUT upload completed successfully")}}catch(f){let g=((performance.now()-c)/1e3).toFixed(2);if(u.stop(`Failed to upload bundle ( after ${g} seconds)`),o.verbose&&(w.info(`[Verbose] Upload failed after ${g} seconds`),w.info(`[Verbose] Error type: ${f instanceof Error?"Error":typeof f}`)),f instanceof Error&&f.message.includes("HTTP error"))try{let b=f.message.match(/status: (\d+)/),S=b?b[1]:"unknown";w.error(`Upload failed with status ${S}: ${f.message}`)}catch{w.error(`Upload failed: ${f.message}`)}else o.verbose&&w.info(`[Verbose] Non-HTTP error: ${W(f)}`),o.tus?w.error(`Cannot upload bundle please contact support if the issue persists ${W(f)}`):w.error(`Cannot upload bundle ( try again with --tus option) ${W(f)}`);throw o.verbose&&w.info("[Verbose] Cleaning up failed version from database..."),await Y8(e,r,n),o.verbose&&w.info("[Verbose] Failed version cleaned up"),f instanceof Error?f:new Error(String(f))}let d=((performance.now()-c)/1e3).toFixed(2);u.stop(`Bundle uploaded \u{1F4AA} in (${d} seconds)`),o.verbose&&(w.info("[Verbose] Upload successful:"),w.info(` - Upload time: ${d} seconds`),w.info(` - Upload method: ${l?"TUS (resumable)":"Standard HTTP PUT"}`),w.info(` - Bundle size: ${Math.floor(s.byteLength/1024)} KB`),w.info("[Verbose] Sending performance event...")),await Ae(t,{channel:"performance",event:l?"TUS upload zip performance":"Upload zip performance",icon:"\u{1F684}",user_id:i,tags:{"app-id":r,time:d},notify:!1},o.verbose),o.verbose&&w.info("[Verbose] Performance event sent successfully")}async function yhe(t,e,r){let{data:n,error:i}=await t.from("channels").select("version ( id, name, deleted )").eq("app_id",e).eq("name",r);if(i){w.error(`Cannot delete linked bundle on upload ${W(i)}`);return}if(n.length===0){w.warn("No linked bundle found in the channel you are trying to upload to");return}let s=n[0].version;if(s.deleted){w.warn("The linked bundle is already deleted");return}let{error:o}=await t.from("app_versions").update({deleted:!0}).eq("id",s.id);if(o){w.error(`Cannot delete linked bundle on upload ${W(o)}`);return}w.info("Linked bundle deleted")}async function Dhe(t,e,r,n,i,s,o,a,u,c){let{data:l}=await t.rpc("get_app_versions",{apikey:e,name_version:n,appid:a}).single();l||gt("Cannot get version id, cannot set channel");let{data:h}=await t.rpc("is_allowed_capgkey",{apikey:e,keymode:["write","all"]}).single();if(h){let{error:d,data:f}=await $p(t,{name:i,app_id:a,created_by:s,version:l,owner_org:o,...c?{allow_device_self_set:!0}:{}});d&>(`Cannot set channel, the upload key is not allowed to do that, use the "all" for this. ${W(d)}`);let m=`${u.hostWeb}/app/p/${a}/channel/${f.id}`;f?.public?w.info("Your update is now available in your public channel \u{1F389}"):f?.id&&w.info(`Link device to this bundle to try it: ${m}`),r&&w.info(`Bundle url: ${m}`)}else w.warn("The upload key is not allowed to set the version in the channel")}async function whe(t,e,r){let{error:n,data:i}=await e.from("apps").select("default_upload_channel").eq("app_id",t).single();return n?(w.warn("Cannot find default upload channel"),w.info(`You can set it here: ${r}/app/p/${t}/settings`),null):i.default_upload_channel}async function iq(t,e,r=!1){r||oe(`Uploading with CLI version ${Ri.version}`);let n,i=Nn();await ze();let{s3Region:s,s3Apikey:o,s3Apisecret:a,s3BucketName:u,s3Endpoint:c,s3Port:l,s3SSL:h}=e;e.verbose&&(w.info("[Verbose] Starting upload process with options:"),w.info(` - API key: ${e.apikey?"provided":"from saved key"}`),w.info(` - Path: ${e.path||"from capacitor config"}`),w.info(` - Channel: ${e.channel||"from default upload channel"}`),w.info(` - Bundle: ${e.bundle||"auto-detected"}`),w.info(` - External: ${e.external||"false"}`),w.info(` - Encryption: ${e.keyV2||e.keyDataV2?"v2":e.key===!1?"disabled":"auto"}`),w.info(` - Upload method: ${e.tus?"TUS":e.zip?"ZIP":"auto"}`),w.info(` - Delta updates: ${e.delta||e.partial?"enabled":"disabled"}`));let d=che(e);e.verbose&&w.info("[Verbose] API key retrieved successfully");let f=await de();e.verbose&&w.info("[Verbose] Capacitor config loaded successfully");let m=await B8();e.verbose&&(w.info("[Verbose] Remote file config retrieved:"),w.info(` - Max upload length: ${Math.floor(m.maxUploadLength/1024/1024)} MB`),w.info(` - Alert upload size: ${Math.floor(m.alertUploadSize/1024/1024)} MB`),w.info(` - TUS upload: ${m.TUSUpload?"enabled":"disabled"}`),w.info(` - TUS upload forced: ${m.TUSUploadForced?"yes":"no"}`),w.info(` - Partial upload: ${m.partialUpload?"enabled":"disabled"}`),w.info(` - Max chunk size: ${Math.floor(m.maxChunkSize/1024/1024)} MB`));let{appid:g,path:b}=lhe(t,e,f.config);e.verbose&&w.info(`[Verbose] App ID: ${g}, Build path: ${b}`);let S=await uhe(f.config,e);e.verbose&&w.info(`[Verbose] Bundle version: ${S}`);let A=e.external?"external":"r2-direct",p="none";e.autoSetBundle&&(await j8({version:S}),e.verbose&&w.info("[Verbose] Auto-set bundle version in capacitor.config.json")),fhe(e,b),e.verbose&&w.info("[Verbose] Code check passed (notifyAppReady found and index.html present)"),w.info(`Upload ${g}@${S} started from path "${b}" to Capgo cloud`);let D=await wn();e.verbose&&w.info(`[Verbose] Local config loaded: host=${D.hostWeb}`),e.supaHost&&e.supaAnon&&(w.info("Using custom supabase instance from provided options"),D.supaHost=e.supaHost,D.supaKey=e.supaAnon,e.verbose&&w.info(`[Verbose] Custom Supabase host: ${e.supaHost}`));let y=await pe(d,e.supaHost,e.supaAnon);e.verbose&&w.info("[Verbose] Supabase client created successfully");let C=await De(y,d,["write","all","upload"]);e.verbose&&w.info(`[Verbose] User verified successfully, user_id: ${C}`);let k=e.channel||await whe(g,y,D.hostWeb)||"dev";e.verbose&&w.info(`[Verbose] Target channel: ${k}`);let v=await sn(y,g);e.verbose&&w.info(`[Verbose] Organization ID: ${v}`),await H8(y,v,Ri.version),e.verbose&&w.info("[Verbose] Remote CLI messages checked"),await z8(y,v,d,g,!0),e.verbose&&w.info("[Verbose] Plan validation passed"),await dhe(y,v,D),e.verbose&&w.info("[Verbose] Trial check completed"),e.verbose&&w.info(`[Verbose] Checking compatibility with channel ${k}...`);let{nativePackages:R,minUpdateVersion:P}=await hhe(y,i,e,k,g,S);e.verbose&&(w.info("[Verbose] Compatibility check completed:"),w.info(` - Native packages: ${R?R.length:0}`),w.info(` - Min update version: ${P||"none"}`)),e.verbose&&w.info(`[Verbose] Checking if version ${S} already exists...`);let F=await phe(y,g,S,e.versionExistsOk);if(e.verbose&&w.info(`[Verbose] Version exists check: ${F?"yes (skipping)":"no (continuing)"}`),F)return{success:!0,skipped:!0,reason:"VERSION_EXISTS",bundle:S,checksum:null,encryptionMethod:p,storageProvider:A};e.external&&!e.external.startsWith("https://")&>(`External link should should start with "https://" current is "${e.external}"`),e.deleteLinkedBundleOnUpload&&(w.warn("Deleting linked bundle on upload is destructive, it will delete the currently linked bundle in the channel you are trying to upload to."),w.warn("Please make sure you want to do this, if you are not sure, please do not use this option."));let j={name:S,app_id:g,session_key:void 0,external_url:e.external,storage_provider:A,min_update_version:P,native_packages:R,owner_org:v,user_id:C,checksum:void 0,link:e.link||null,comment:e.comment||null},U=null,G="";if(e.external)e.verbose&&w.info(`[Verbose] Using external URL: ${e.external}`),await Ae(d,{channel:"app",event:"App external",icon:"\u{1F4E4}",user_id:v,tags:{"app-id":g},notify:!1},e.verbose),j.session_key=e.ivSessionKey,j.checksum=e.encryptedChecksum,e.verbose&&(w.info("[Verbose] External bundle configured:"),w.info(` - URL: ${e.external}`),w.info(` - IV Session Key: ${e.ivSessionKey?"provided":"none"}`),w.info(` - Encrypted Checksum: ${e.encryptedChecksum?"provided":"none"}`));else{e.verbose&&w.info(`[Verbose] Preparing bundle file from path: ${b}`);let{zipped:$,ivSessionKey:M,checksum:B,sessionKey:K,encryptionMethod:q,finalKeyData:V}=await mhe(b,e,d,v,g,m.maxUploadLength,m.alertUploadSize);j.session_key=M,j.checksum=B,n=K,U=$,p=q,G=V,e.verbose&&(w.info("[Verbose] Bundle prepared:"),w.info(` - Size: ${Math.floor(($?.byteLength??0)/1024)} KB`),w.info(` - Checksum: ${B}`),w.info(` - Encryption: ${q}`),w.info(` - IV Session Key: ${M?"present":"none"}`)),e.ignoreChecksumCheck||(e.verbose&&w.info("[Verbose] Checking for duplicate checksum..."),await Q8(y,g,k,B),e.verbose&&w.info("[Verbose] Checksum is unique"))}if(e.zip?(e.tus=!1,e.verbose&&w.info("[Verbose] Upload method: ZIP (explicitly set via --zip)")):!m.TUSUpload||e.external?(e.tus=!1,e.verbose&&w.info("[Verbose] Upload method: Standard (TUS not available or external URL)")):(e.tus=e.tus||m.TUSUploadForced,e.verbose&&w.info(`[Verbose] Upload method: ${e.tus?"TUS (resumable)":"Standard"}`)),!m.partialUpload||e.external?(e.delta=!1,e.verbose&&e.external&&w.info("[Verbose] Delta updates disabled (not available with external URLs)")):(e.delta=e.delta||e.partial||e.deltaOnly||e.partialOnly||m.partialUploadForced,e.verbose&&w.info(`[Verbose] Delta updates: ${e.delta?"enabled":"disabled"}`)),e.encryptPartial&&p==="v1"&>("You cannot encrypt the partial update if you are not using the v2 encryption method"),e.delta&&p==="v2"&&!e.encryptPartial){let $=(0,SE.join)(Xr((0,AE.cwd)()),$n),B=(await Ln(void 0,e.packageJson||$)).get("@capgo/capacitor-updater"),K;try{K=B?Et(B):void 0}catch{K=void 0}B&&K&&Ci(K,Et("6.14.4"))&&(w.info(`Auto-enabling partial update encryption for updater version ${K} (> 6.14.4)`),e.verbose&&w.info("[Verbose] Partial encryption auto-enabled for updater >= 6.14.4"),e.encryptPartial=!0)}e.verbose&&e.delta&&w.info("[Verbose] Preparing delta/partial update manifest...");let L=e.delta?await tq(b,d,v,g,e.encryptPartial?p:"none",G):[];e.verbose&&e.delta&&w.info(`[Verbose] Delta manifest prepared with ${L.length} files`),e.verbose&&w.info("[Verbose] Creating version record in database...");let{error:_}=await Yv(y,j);if(_&>(`Cannot add bundle ${W(_)}`),e.verbose&&w.info("[Verbose] Version record created successfully"),e.tusChunkSize&&e.tusChunkSize>m.maxChunkSize?(w.error(`Chunk size ${e.tusChunkSize} is greater than the maximum chunk size ${m.maxChunkSize}, using the maximum chunk size`),e.tusChunkSize=m.maxChunkSize):e.tusChunkSize||(e.tusChunkSize=m.maxChunkSize),e.verbose&&w.info(`[Verbose] TUS chunk size: ${Math.floor(e.tusChunkSize/1024/1024)} MB`),U&&(u||c||s||o||a||l||h)){(!u||!c||!s||!o||!a||!l)&>("Missing argument, for S3 upload you need to provide a bucket name, endpoint, region, port, API key, and API secret"),w.info("Uploading to S3"),e.verbose&&(w.info("[Verbose] S3 configuration:"),w.info(` - Endpoint: ${c}`),w.info(` - Region: ${s}`),w.info(` - Bucket: ${u}`),w.info(` - Port: ${l}`),w.info(` - SSL: ${h?"enabled":"disabled"}`));let $=h?`https://${c}`:`http://${c}`,M=new al({endPoint:c,region:s,port:l,pathStyle:!0,bucket:u,accessKey:o,secretKey:a}),B=`${g}-${S}`,K=encodeURIComponent(B);e.verbose&&w.info(`[Verbose] Uploading to S3 as: ${B}`),await M.putObject(B,Uint8Array.from(U)),j.external_url=`${$}/${K}`,j.storage_provider="external",e.verbose&&w.info(`[Verbose] S3 upload complete, external URL: ${j.external_url}`)}else if(U){!e.partialOnly&&!e.deltaOnly?(e.verbose&&w.info("[Verbose] Starting full bundle upload to Capgo Cloud..."),await ghe(d,y,g,S,v,U,e,e.tusChunkSize)):e.verbose&&w.info("[Verbose] Skipping full bundle upload (delta-only mode)");let $=null;try{e.dryUpload&&(e.delta=!1,e.verbose&&w.info("[Verbose] Dry upload mode: skipping delta upload"));let B=j.session_key&&e.encryptPartial&&n?{sessionKey:n,ivSessionKey:j.session_key}:void 0;e.verbose&&e.delta&&(w.info("[Verbose] Starting delta/partial file upload..."),w.info(` - Manifest entries: ${L.length}`),w.info(` - Encryption: ${B?"enabled":"disabled"}`)),$=e.delta?await rq(d,L,b,g,v,B,e):null,e.verbose&&$&&w.info(`[Verbose] Delta upload complete with ${$.length} files`)}catch(B){if(!!(e.partial||e.delta||e.partialOnly||e.deltaOnly))throw B;w.info(`Failed to upload partial files to capgo cloud. Error: ${W(B)}. This is not a critical error, the bundle has been uploaded without the partial files`),e.verbose&&w.info(`[Verbose] Delta upload error details: ${W(B)}`)}j.storage_provider="r2",j.manifest=$,e.verbose&&w.info("[Verbose] Updating version record with storage provider and manifest...");let{error:M}=await Yv(y,j);M&>(`Cannot update bundle ${W(M)}`),e.verbose&&w.info("[Verbose] Version record updated successfully")}e.verbose&&w.info("[Verbose] Checking app permissions...");let T=await mt(y,d,g,2);e.verbose&&(w.info("[Verbose] Permissions:"),w.info(` - Upload: ${Xa(T,2)?"yes":"no"}`),w.info(` - Write: ${Xa(T,3)?"yes":"no"}`),w.info(` - Admin: ${Xa(T,4)?"yes":"no"}`)),e.deleteLinkedBundleOnUpload&&Xa(T,3)?(e.verbose&&w.info(`[Verbose] Deleting linked bundle in channel ${k}...`),await yhe(y,g,k)):e.deleteLinkedBundleOnUpload&&w.warn("Cannot delete linked bundle on upload as a upload organization member"),Xa(T,3)?(e.verbose&&w.info(`[Verbose] Setting bundle ${S} to channel ${k}...`),await Dhe(y,d,!!e.bundleUrl,S,k,C,v,g,D,e.selfAssign),e.verbose&&w.info("[Verbose] Channel updated successfully")):w.warn("Cannot set channel as a upload organization member"),e.verbose&&w.info("[Verbose] Sending upload event..."),await Ae(d,{channel:"app",event:"App Uploaded",icon:"\u23EB",user_id:v,tags:{"app-id":g},notify:!1},e.verbose);let I={success:!0,bundle:S,checksum:j.checksum??null,encryptionMethod:p,sessionKey:n?n.toString("base64"):void 0,ivSessionKey:typeof j.session_key=="string"?j.session_key:void 0,storageProvider:j.storage_provider};return e.verbose&&(w.info("[Verbose] Upload completed successfully:"),w.info(` - Bundle: ${I.bundle}`),w.info(` - Checksum: ${I.checksum}`),w.info(` - Encryption: ${I.encryptionMethod}`),w.info(` - Storage: ${I.storageProvider}`)),r&&!I.skipped&&ce("Time to share your update to the world \u{1F30D}"),I}var sq=require("node:crypto"),im=require("node:fs"),oq=require("node:path"),aq=require("node:process");var bhe=20;function vhe(t){console.log(JSON.stringify(t,null,2))}function dl(t){console.error(W(t))}async function uq(t,e,r=!1){let{json:n}=e,{bundle:i,path:s}=e,o=!n&&!r;try{o&&await ze();let a=await de(),u=Pe(t,a?.config),c=(0,sq.randomUUID)().split("-")[0],l=is("",e.packageJson);if(i=i||l||`0.0.1-beta.${c}`,o&&oe(`Zipping ${u}@${i}`),i&&!Wa.test(i)){let k=`Your bundle name ${i}, is not valid it should follow semver convention : https://semver.org/`;throw r||(n?dl({error:"invalid_semver"}):w.error(k)),new Error("Invalid bundle version format")}if(s=s||a?.config?.webDir,!u||!i||!s){let k="Missing argument, you need to provide a appId and a bundle and a path, or be in a capacitor project";throw r||(n?dl({error:"missing_argument"}):w.error(k)),new Error(k)}if(o&&w.info(`Started from path "${s}"`),typeof e.codeCheck>"u"?!0:e.codeCheck){if(!ul(s,"notifyAppReady"))throw r||(n?dl({error:"notifyAppReady_not_in_source_code"}):w.error("notifyAppReady() is missing in the build folder of your app. see: https://capgo.app/docs/plugin/api/#notifyappready")),new Error("notifyAppReady() is missing in build folder");if(!Xp(s))throw r||(n?dl({error:"index_html_not_found"}):w.error(`index.html is missing in the root folder of ${s}`)),new Error("index.html is missing in root folder")}let d=await Np(s);o&&w.info(`Zipped ${d.byteLength} bytes`);let f=o?Ft():null;f&&f.start("Calculating checksum");let m=(0,oq.join)(Xr((0,aq.cwd)()),$n),b=(await Ln(void 0,e.packageJson||m)).get("@capgo/capacitor-updater");if(!b){let k="Cannot find @capgo/capacitor-updater in ./package.json, provide the package.json path with --package-json it's required for v7 CLI to work";throw r||w.warn(k),new Error(k)}let S=!1,A;try{A=b?Et(b):void 0}catch{A=void 0}if(A){let k=A.major===6&&Ci(A,Et("6.25.0")),v=A.major>=7;S=k||v}else b==="link:@capgo/capacitor-updater"&&(r||w.warn("Using local @capgo/capacitor-updater. Assuming v7"),S=!0);let p=await Jn(d,e.keyV2||(0,im.existsSync)(Ir)||S?"sha256":"crc32");f&&f.stop(`Checksum ${S?"SHA256":"CRC32"}: ${p}`);let D=Math.floor(d.byteLength/1024/1024);D>bhe&&o&&(w.warn(`WARNING !!
|
|
338
338
|
The bundle size is ${D} Mb, this may take a while to download for users
|
|
339
339
|
`),w.warn(`Learn how to optimize your assets https://capgo.app/blog/optimise-your-images-for-updates/
|
|
340
340
|
`));let y=o?Ft():null,C=e.name||`${u}_${i}.zip`;return y&&y.start(`Saving to ${C}`),(0,im.writeFileSync)(C,d),y&&y.stop(`Saved to ${C}`),o&&ce("Done \u2705"),!r&&n&&vhe({bundle:i,filename:C,checksum:p}),{bundle:i,filename:C,checksum:p}}catch(a){throw r||(n?dl(a):w.error(W(a))),a instanceof Error?a:new Error(String(a))}}async function cq(t,e,r,n=!1){n||oe("Create channel"),r.apikey=r.apikey||ne();let i=await de().catch(()=>{});if(e=Pe(e,i?.config),!r.apikey)throw n||w.error("Missing API key, you need to provide an API key to upload your bundle"),new Error("Missing API key");if(!e)throw n||w.error("Missing argument, you need to provide a appId, or be in a capacitor project"),new Error("Missing appId");let s=await pe(r.apikey,r.supaHost,r.supaAnon);await De(s,r.apikey,["write","all"]),await mt(s,r.apikey,e,4,n),n||w.info(`Creating channel ${e}#${t} to Capgo`);let o=await Qv(s,e);if(!o)throw n||w.error("Cannot find default version for channel creation, please contact Capgo support \u{1F928}"),new Error("Cannot find default version for channel creation");let a=await sn(s,e),u=await De(s,r.apikey,["write","all"]),c=await rM(s,{name:t,app_id:e,version:o.id,created_by:u,owner_org:a,allow_device_self_set:r.selfAssign??!1,public:r.default??!1});if(c.error)throw n||w.error(`Cannot create Channel \u{1F640}
|