@overlayed/cli 0.6.4 → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.mjs +4 -4
  2. package/package.json +5 -4
package/dist/cli.mjs CHANGED
@@ -1,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import{Builtins as e,Cli as t,Command as n,UsageError as r}from"clipanion";import{scope as i,type as a}from"arktype";import o,{createWriteStream as ee,existsSync as te,mkdirSync as ne,readdirSync as re,unlinkSync as ie,writeFileSync as s}from"fs";import{ensureDirSync as c,ensureFileSync as l}from"fs-extra";import u,{join as ae}from"path";import d from"node:path";import f from"chalk";import oe,{createReadStream as se,existsSync as p,lstatSync as ce,readFileSync as le}from"node:fs";import{glob as m}from"glob";import ue,{fileURLToPath as de}from"node:url";import{createJiti as fe}from"jiti";import{readdir as h}from"node:fs/promises";import g from"jszip";import _,{isXiorError as v}from"xior";import{checkbox as y,password as b}from"@inquirer/prompts";import{Listr as x}from"listr2";import{ListrInquirerPromptAdapter as S}from"@listr2/prompt-adapter-inquirer";import{exec as C}from"child_process";import{promisify as w}from"util";import T from"update-notifier";const E={deployment:`deployment`};function D(e){throw e}function O(e){return Object.prototype.toString.call(e)===`[object Object]`}function k(e){return e?Array.isArray(e)?e:[e]:[]}function A(e){return{all:e||=new Map,on:function(t,n){var r=e.get(t);r?r.push(n):e.set(t,[n])},off:function(t,n){var r=e.get(t);r&&(n?r.splice(r.indexOf(n)>>>0,1):e.set(t,[]))},emit:function(t,n){var r=e.get(t);r&&r.slice().map(function(e){e(n)}),(r=e.get(`*`))&&r.slice().map(function(e){e(t,n)})}}}var j=class{emitter;constructor(){this.emitter=A()}on(e,t){k(e).forEach(e=>{this.emitter.on(e,t)})}off(e,t){k(e).forEach(e=>{this.emitter.off(e,t)})}emit(e,t){k(e).forEach(e=>{this.emitter.emit(e,t)})}removeAllListeners(){this.emitter.all.clear()}};function M(e,...t){return class extends e{static _instance;static getInstance(){return this._instance||=new e(...t),this._instance}static clearInstance(){this._instance=void 0}}}const N=M(class extends j{destroy(){this.removeAllListeners()}fatal(e,t,n){this.emit(`fatal`,{code:t,message:e,data:n,timestamp:Date.now()})}error(e,t,n){this.emit(`error`,{code:t,message:e,data:n,timestamp:Date.now()})}warn(e,t,n){this.emit(`warning`,{code:t,message:e,data:n,timestamp:Date.now()})}});var P=class{data;_schema;_defaultValue;_path;constructor(e){let{schema:t,default:n,path:r}=e;this._schema=t,this._defaultValue=n,this._path=r}set(e){let t=this._schema[`~standard`].validate(e);if(t instanceof Promise)throw Error(`StructuredConfigFile does not support async validation`);if(t.issues){this.reportInvalidConfigFile(t.issues);return}this.data=this.onBeforeSave(e),this.save(e)}get(){return this.data?this.data:this.load()}getKey(e){return this.get()[e]}save(e){let t=this.onBeforeSave(e);try{l(this.getFilePath()),o.writeFileSync(this.getFilePath(),JSON.stringify(t,void 0,2))}catch{return}return this.data=t}load(){if(!this.fileExists(this.getFilePath())||!this.canReadWriteFile(this.getFilePath())){this.save(this._defaultValue);let e=this.onAfterLoad(this._defaultValue);return this.data=e,e}try{let e=o.readFileSync(this.getFilePath(),`utf8`),t=this.onAfterLoad(this.parseStoredData(e));return this.data=t,t}catch{return this.data=this._defaultValue}}onBeforeSave(e){return e}onAfterLoad(e){return e}getFilePath(){return this._path}parseStoredData(e){try{let t=a(`string.json.parse`).to(`object`)(e);if(t instanceof a.errors)return this._defaultValue;let n=this._schema[`~standard`].validate(t);if(n instanceof Promise)throw Error(`StructuredConfigFile does not support async validation`);return n.issues?this.migrate(t,this._defaultValue):this.migrate(n.value,this._defaultValue)}catch{return this._defaultValue}}canReadWriteFile(e){try{return o.accessSync(e,o.constants.R_OK|o.constants.W_OK),!0}catch{return!1}}fileExists(e){try{return o.accessSync(e,o.constants.F_OK),!0}catch{return!1}}migrate(e,t){let n={...e};for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(r in e?e[r]!==null&&t[r]!==null&&typeof e[r]==`object`&&typeof t[r]==`object`&&!Array.isArray(e[r])&&!Array.isArray(t[r])?n[r]=this.migrate(e[r],t[r]):Array.isArray(t[r])&&(n[r]=e[r]):n[r]=t[r]);return n}reportInvalidConfigFile(e){N.getInstance().error(`Invalid config file`,`INVALID_CONFIG_FILE`,{issues:e.map(e=>e.message),filePath:this._path,data:this.data})}};const F=`**/overlayed.config.{js,ts,mts}`;async function I(){let e=R(),t=fe(import.meta.url);return(await Promise.all(e.map(async e=>e.endsWith(`.ts`)?[await t.import(e,{default:!0}),e]:[(await import(ue.pathToFileURL(e).toString())).default,e]))).filter(([e])=>L(e)).map(([e,t])=>[e,t])}function L(e){return O(e)&&`app`in e}function R(){return m.globSync(F,{absolute:!0,cwd:process.cwd()})}var z=class{pattern;options;constructor(e,t){this.pattern=e,this.options=t}},B=class{defaultIgnore=[`overlayed.config.ts`];patterns=[];constructor(e){this.config=e}addGlobPattern(e,t){let n=this.resolveOptions(t),r=k(e);this.patterns.push(new z(r,n))}async bundle(){let e=new g;for(let t of this.patterns){let n={...t.options},r;r=n.cwd?typeof n.cwd==`string`?n.cwd:de(n.cwd):process.cwd(),d.isAbsolute(r)||(r=d.resolve(r)),n.absolute=!0,n.cwd=r;let i=await m(t.pattern,n),a=await this.getFilesPathsFromPaths(i);await Promise.all(a.map(async t=>{await this.zipFile(r,e,t)}))}return e}async validateFilePath(e){return Promise.resolve(!0)}async zipFile(e,t,n){let r=d.relative(e,n);if(r=r.replace(/^(\.\.\\|\.\.\/)+/,``),!p(n)){t.file(r,``,{compression:`DEFLATE`});return}if(!await this.validateFilePath(n))return;let i=se(n,`binary`);t.file(r,i,{compression:`DEFLATE`})}resolveOptions(e){return{...e,ignore:[...k(e?.ignore),...this.defaultIgnore]}}async getFilesPathsFromPaths(e){return Promise.all(e.map(async e=>await this.getFilePathsFromPathRecursive(e))).then(e=>e.flat())}async getFilePathsFromPathRecursive(e){if(!p(e)||!ce(e).isDirectory())return[e];let t=await h(e,{withFileTypes:!0});return(await Promise.all(t.map(async t=>{let n=d.join(e,t.name);return t.isDirectory()?await this.getFilePathsFromPathRecursive(n):[n]}))).flat()}},V=class extends B{defaultIgnore=[`overlayed.config.ts`,`**/installer/**`];mainFile;constructor(e){super(e),this.addGlobPattern(`package.json`)}async bundle(){let e=await super.bundle();return await this.validateZip(e),e}async validateFilePath(e){return e.endsWith(`package.json`)&&!e.includes(`node_modules`)&&await this.validatePackageJson(e),!0}async validateZip(e){await Promise.all([this.validateNoInstallFolder(e),this.validateMainFile(e)])}async validatePackageJson(e){if(!e)throw new H;let t=oe.readFileSync(e,`utf-8`),n=a(`string.json.parse`).to({main:`string`,devDependencies:{"@overlayed/electron":`string`}})(t);if(n instanceof a.errors)throw new pe(n.summary);this.mainFile=n.main}async validateMainFile(e){if(!this.mainFile)throw new H;if(!e.file(u.normalize(this.mainFile)))throw new U(this.mainFile)}async validateNoInstallFolder(e){let t=e.folder(`install`);if(t&&t.length>0)throw new W}},H=class extends Error{constructor(){super(`package.json not found in bundle`),this.name=`PackageJsonNotFoundError`}},pe=class extends Error{constructor(e){super(`package.json is invalid: ${e}`),this.name=`PackageJsonInvalidError`}},U=class extends Error{constructor(e){super(`referenced package.json main file ${e} not found in bundle`),this.name=`MainFileNotFoundError`}},W=class extends Error{constructor(){super("folder `install` found in bundle is not allowed and is reserved for the installer"),this.name=`InstallFolderFoundError`}};_.create({baseURL:`https://updater.stats.cc`,headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}}).interceptors.request.use(e=>e);const G=_.create({baseURL:`https://api.overlayed.gg`,headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}});let K;function q(e){K=e}G.interceptors.request.use(e=>{let t=K?.();return e.headers??={},t&&(e.headers[`X-Api-Key`]=t),e});function me(e){return e}function he(e){return e?t=>(e(t),t):me}function ge(e,t){return G.post(`/v1/applications/${e}/bundles/tasks/upload`,t)}function _e(e,t){return G.post(`/v1/applications/${e}/bundles/tasks/queue`,{name:t})}function ve(e,t){return G.get(`/v1/applications/${e}/bundles/tasks/${t}`)}function ye(e,t){return G.put(e.url,t,{headers:{...e.headers,"Content-Length":t.length}})}const be=he();function J(){return G.get(`/v1/auth/me`)}const Y=new P({path:u.normalize(`${process.env.APPDATA||process.env.HOME||`.`}/.overlayed/config.json`),default:void 0,schema:i({Account:a({email:`string`,apiKey:`string`})}).type({currentAccount:`Account | undefined`,accounts:`Account[]`}).or(`undefined`)});async function X(){if(!Y.get()?.currentAccount)throw new r(`Not authenticated. Run 'overlayed login' to authenticate.`);try{return(await J()).data.email}catch(e){if(!v(e))throw e;switch(e.response?.status){case 401:case 403:throw new r(`Authentication failed. Your API key may be invalid or expired. Run 'overlayed login' to re-authenticate.`);default:throw Error(`API error occurred. Please try again later.`)}}}async function xe(e){let t=await I();if(t.length===0)throw new r(`No config file found matching `+F);return t.length>1&&e.stdout.write(f.yellow(`
2
+ import{Builtins as e,Cli as t,Command as n,UsageError as r}from"clipanion";import{scope as i,type as a}from"arktype";import o,{createWriteStream as ee,existsSync as te,mkdirSync as ne,readdirSync as re,unlinkSync as ie,writeFileSync as s}from"fs";import{ensureDirSync as c,ensureFileSync as l}from"fs-extra";import u,{join as ae}from"path";import d from"node:path";import f from"picocolors";import oe,{createReadStream as se,existsSync as p,lstatSync as ce,readFileSync as le}from"node:fs";import{glob as m}from"glob";import ue,{fileURLToPath as de}from"node:url";import{createJiti as fe}from"jiti";import{readdir as h}from"node:fs/promises";import g from"jszip";import _,{isXiorError as v}from"xior";import{checkbox as y,password as b}from"@inquirer/prompts";import{Listr as x}from"listr2";import{ListrInquirerPromptAdapter as S}from"@listr2/prompt-adapter-inquirer";import{exec as C}from"child_process";import{promisify as w}from"util";import T from"update-notifier";const E={deployment:`deployment`};function D(e){throw e}function O(e){return Object.prototype.toString.call(e)===`[object Object]`}function k(e){return e?Array.isArray(e)?e:[e]:[]}function A(e){return{all:e||=new Map,on:function(t,n){var r=e.get(t);r?r.push(n):e.set(t,[n])},off:function(t,n){var r=e.get(t);r&&(n?r.splice(r.indexOf(n)>>>0,1):e.set(t,[]))},emit:function(t,n){var r=e.get(t);r&&r.slice().map(function(e){e(n)}),(r=e.get(`*`))&&r.slice().map(function(e){e(t,n)})}}}var j=class{emitter;constructor(){this.emitter=A()}on(e,t){k(e).forEach(e=>{this.emitter.on(e,t)})}off(e,t){k(e).forEach(e=>{this.emitter.off(e,t)})}emit(e,t){k(e).forEach(e=>{this.emitter.emit(e,t)})}removeAllListeners(){this.emitter.all.clear()}};function M(e,...t){return class extends e{static _instance;static getInstance(){return this._instance||=new e(...t),this._instance}static clearInstance(){this._instance=void 0}}}const N=M(class extends j{destroy(){this.removeAllListeners()}fatal(e,t,n){this.emit(`fatal`,{code:t,message:e,data:n,timestamp:Date.now()})}error(e,t,n){this.emit(`error`,{code:t,message:e,data:n,timestamp:Date.now()})}warn(e,t,n){this.emit(`warning`,{code:t,message:e,data:n,timestamp:Date.now()})}});var P=class{data;_schema;_defaultValue;_path;constructor(e){let{schema:t,default:n,path:r}=e;this._schema=t,this._defaultValue=n,this._path=r}set(e){let t=this._schema[`~standard`].validate(e);if(t instanceof Promise)throw Error(`StructuredConfigFile does not support async validation`);if(t.issues){this.reportInvalidConfigFile(t.issues);return}this.data=this.onBeforeSave(e),this.save(e)}get(){return this.data?this.data:this.load()}getKey(e){return this.get()[e]}save(e){let t=this.onBeforeSave(e);try{l(this.getFilePath()),o.writeFileSync(this.getFilePath(),JSON.stringify(t,void 0,2))}catch{return}return this.data=t}load(){if(!this.fileExists(this.getFilePath())||!this.canReadWriteFile(this.getFilePath())){this.save(this._defaultValue);let e=this.onAfterLoad(this._defaultValue);return this.data=e,e}try{let e=o.readFileSync(this.getFilePath(),`utf8`),t=this.onAfterLoad(this.parseStoredData(e));return this.data=t,t}catch{return this.data=this._defaultValue}}onBeforeSave(e){return e}onAfterLoad(e){return e}getFilePath(){return this._path}parseStoredData(e){try{let t=a(`string.json.parse`).to(`object`)(e);if(t instanceof a.errors)return this._defaultValue;let n=this._schema[`~standard`].validate(t);if(n instanceof Promise)throw Error(`StructuredConfigFile does not support async validation`);return n.issues?this.migrate(t,this._defaultValue):this.migrate(n.value,this._defaultValue)}catch{return this._defaultValue}}canReadWriteFile(e){try{return o.accessSync(e,o.constants.R_OK|o.constants.W_OK),!0}catch{return!1}}fileExists(e){try{return o.accessSync(e,o.constants.F_OK),!0}catch{return!1}}migrate(e,t){let n={...e};for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(r in e?e[r]!==null&&t[r]!==null&&typeof e[r]==`object`&&typeof t[r]==`object`&&!Array.isArray(e[r])&&!Array.isArray(t[r])?n[r]=this.migrate(e[r],t[r]):Array.isArray(t[r])&&(n[r]=e[r]):n[r]=t[r]);return n}reportInvalidConfigFile(e){N.getInstance().error(`Invalid config file`,`INVALID_CONFIG_FILE`,{issues:e.map(e=>e.message),filePath:this._path,data:this.data})}};const F=`**/overlayed.config.{js,ts,mts}`;async function I(){let e=R(),t=fe(import.meta.url);return(await Promise.all(e.map(async e=>e.endsWith(`.ts`)?[await t.import(e,{default:!0}),e]:[(await import(ue.pathToFileURL(e).toString())).default,e]))).filter(([e])=>L(e)).map(([e,t])=>[e,t])}function L(e){return O(e)&&`app`in e}function R(){return m.globSync(F,{absolute:!0,cwd:process.cwd()})}var z=class{pattern;options;constructor(e,t){this.pattern=e,this.options=t}},B=class{defaultIgnore=[`overlayed.config.ts`];patterns=[];constructor(e){this.config=e}addGlobPattern(e,t){let n=this.resolveOptions(t),r=k(e);this.patterns.push(new z(r,n))}async bundle(){let e=new g;for(let t of this.patterns){let n={...t.options},r;r=n.cwd?typeof n.cwd==`string`?n.cwd:de(n.cwd):process.cwd(),d.isAbsolute(r)||(r=d.resolve(r)),n.absolute=!0,n.cwd=r;let i=await m(t.pattern,n),a=await this.getFilesPathsFromPaths(i);await Promise.all(a.map(async t=>{await this.zipFile(r,e,t)}))}return e}async validateFilePath(e){return Promise.resolve(!0)}async zipFile(e,t,n){let r=d.relative(e,n);if(r=r.replace(/^(\.\.\\|\.\.\/)+/,``),!p(n)){t.file(r,``,{compression:`DEFLATE`});return}if(!await this.validateFilePath(n))return;let i=se(n,`binary`);t.file(r,i,{compression:`DEFLATE`})}resolveOptions(e){return{...e,ignore:[...k(e?.ignore),...this.defaultIgnore]}}async getFilesPathsFromPaths(e){return Promise.all(e.map(async e=>await this.getFilePathsFromPathRecursive(e))).then(e=>e.flat())}async getFilePathsFromPathRecursive(e){if(!p(e)||!ce(e).isDirectory())return[e];let t=await h(e,{withFileTypes:!0});return(await Promise.all(t.map(async t=>{let n=d.join(e,t.name);return t.isDirectory()?await this.getFilePathsFromPathRecursive(n):[n]}))).flat()}},V=class extends B{defaultIgnore=[`overlayed.config.ts`,`**/installer/**`];mainFile;constructor(e){super(e),this.addGlobPattern(`package.json`)}async bundle(){let e=await super.bundle();return await this.validateZip(e),e}async validateFilePath(e){return e.endsWith(`package.json`)&&!e.includes(`node_modules`)&&await this.validatePackageJson(e),!0}async validateZip(e){await Promise.all([this.validateNoInstallFolder(e),this.validateMainFile(e)])}async validatePackageJson(e){if(!e)throw new H;let t=oe.readFileSync(e,`utf-8`),n=a(`string.json.parse`).to({main:`string`,devDependencies:{"@overlayed/electron":`string`}})(t);if(n instanceof a.errors)throw new pe(n.summary);this.mainFile=n.main}async validateMainFile(e){if(!this.mainFile)throw new H;if(!e.file(u.normalize(this.mainFile)))throw new U(this.mainFile)}async validateNoInstallFolder(e){let t=e.folder(`install`);if(t&&t.length>0)throw new W}},H=class extends Error{constructor(){super(`package.json not found in bundle`),this.name=`PackageJsonNotFoundError`}},pe=class extends Error{constructor(e){super(`package.json is invalid: ${e}`),this.name=`PackageJsonInvalidError`}},U=class extends Error{constructor(e){super(`referenced package.json main file ${e} not found in bundle`),this.name=`MainFileNotFoundError`}},W=class extends Error{constructor(){super("folder `install` found in bundle is not allowed and is reserved for the installer"),this.name=`InstallFolderFoundError`}};_.create({baseURL:`https://updater.stats.cc`,headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}}).interceptors.request.use(e=>e);const G=_.create({baseURL:`https://api.overlayed.gg`,headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}});let K;function q(e){K=e}G.interceptors.request.use(e=>{let t=K?.();return e.headers??={},t&&(e.headers[`X-Api-Key`]=t),e});function me(e){return e}function he(e){return e?t=>(e(t),t):me}function ge(e,t){return G.post(`/v1/applications/${e}/bundles/tasks/upload`,t)}function _e(e,t){return G.post(`/v1/applications/${e}/bundles/tasks/queue`,{name:t})}function ve(e,t){return G.get(`/v1/applications/${e}/bundles/tasks/${t}`)}function ye(e,t){return G.put(e.url,t,{headers:{...e.headers,"Content-Length":t.length}})}const be=he();function J(){return G.get(`/v1/auth/me`)}const Y=new P({path:u.normalize(`${process.env.APPDATA||process.env.HOME||`.`}/.overlayed/config.json`),default:void 0,schema:i({Account:a({email:`string`,apiKey:`string`})}).type({currentAccount:`Account | undefined`,accounts:`Account[]`}).or(`undefined`)});async function X(){if(!Y.get()?.currentAccount)throw new r(`Not authenticated. Run 'overlayed login' to authenticate.`);try{return(await J()).data.email}catch(e){if(!v(e))throw e;switch(e.response?.status){case 401:case 403:throw new r(`Authentication failed. Your API key may be invalid or expired. Run 'overlayed login' to re-authenticate.`);default:throw Error(`API error occurred. Please try again later.`)}}}async function xe(e){let t=await I();if(t.length===0)throw new r(`No config file found matching `+F);return t.length>1&&e.stdout.write(f.yellow(`
3
3
  Multiple config files found matching ${F}, using the first one.
4
4
  `)),t.at(0)}var Se=class extends B{defaultIgnore=[`overlayed.config.ts`];constructor(e){super(e)}async bundle(){let e=await super.bundle();if(!Object.keys(e.files).some(e=>e.endsWith(`.html`)))throw new Ce;return e}},Ce=class extends Error{constructor(){super(`Site bundle must contain at least one HTML file`)}},we=class extends n{static paths=[[`bundle`]];static usage=n.Usage({category:E.deployment,description:`Bundle the app and site for deployment.`,details:`
5
5
  Bundle the app and site for deployment.
6
6
 
7
7
  [Docs](http://docs.overlayed.gg/cli/bundle)
8
- `,examples:[[`Basic usage`,`$0 bundle`]]});async execute(){await X();let e=await new x([{title:`Authenticating`,task:X},{title:`Locating overlayed.config.ts`,task:async e=>e.config=await this.resolveConfig()},{task:async(e,t)=>{let n=await t.prompt(S).run(...this.getTargetBundles(e.config));e.targetBundles=n,this.context.stdout.write(f.green(`Selected bundles: `)+f.bold(n.join(`, `)))}}]).run();function t(e){return`${e.map(e=>`taskId=${e}`).join(`&`)}`}await new x([{title:`Uploading bundles`,task:e=>new x(e.targetBundles.map((e,t)=>({title:`Uploading ${e} bundle`,task:async n=>{n.taskIds??=[];let r=await this.uploadBundle(n.config,e);r&&(n.taskIds[t]=r)}})),{concurrent:!0,rendererOptions:{collapseSubtasks:!1}})},{title:`Waiting for bundles to be processed.`,task:e=>new x(e.taskIds.map((n,r)=>({title:`Waiting for ${f.bold(e.targetBundles[r])} bundle to be processed. This may take some time - you can wait for the bundles to appear in the dashboard here: ${f.blue(`https://overlay.dev/bundles?applicationId=${e.config.applicationId}&${t(e.taskIds)}`)}`,task:async e=>{let t=0,r;for(;;){if(t++>100)throw Error(`Processing is taking longer than expected. Open the link below and it should be done soon. If the issue persists, please contact Overlayed.`);if(r=await ve(e.config.applicationId,n),r.data.status!==`in_progress`)break;await new Promise(e=>setTimeout(e,3e3))}if(r.data.status===`failed`)throw Error(r.data.message)}})),{concurrent:!0,rendererOptions:{collapseSubtasks:!1}})}]).run(e)}async uploadBundle(e,t){let n=await ge(e.applicationId,{type:t}),r=await e[t]?.bundle()??D(Error(`No bundle found for `+t));e.debug&&r.forEach(e=>{console.log(`Zipping: `,e)});let i=await r.generateAsync({type:`nodebuffer`});if(e.debug){let e=`.overlayed/tmp`;c(e),s(`${e}/debug-${t}.zip`,i);return}return await ye(n.data.upload_request,i),(await _e(e.applicationId,n.data.asset_bundle_name)).data.task_id}getTargetBundles(e){let t=e=>`(Disabled: No config found for "${e}" in overlayed.config.ts)`;return[y,{message:`Select your desired bundles to create and upload.`,shortcuts:{all:`a`,invert:`i`},choices:[{name:`App`,value:`app`,disabled:e.app?void 0:t(`app`)},{name:`Site`,value:`site`,disabled:e.site?void 0:t(`site`)}]}]}async resolveConfig(){let[e,t]=await xe(this.context);return{...e,applicationId:be(e.applicationId),app:this.getAppBundler(e,t),site:this.getSiteBundler(e,t)}}getAppBundler(e,t){let n=new V(e),r=this.resolveCwd(t,e.app.baseDir);return e.debug&&console.log(`[App] Bundling files from: `,r),n.addGlobPattern(e.app.include,{ignore:e.app.exclude,cwd:r}),n}getSiteBundler(e,t){if(!e.site)return;let n=new Se(e),r=this.resolveCwd(t,e.site.baseDir);return e.debug&&console.log(`[Site] Bundling files from: `,r),n.addGlobPattern(e.site.include,{ignore:e.site.exclude,cwd:r}),n}resolveCwd(e,t){return t?u.resolve(u.dirname(e),t):u.dirname(e)}async catch(e){if(v(e)){let t=e.response?.status,n=(e.config?.baseURL??``)+(e.config?.url??``);throw Error(`Request to ${n} failed with status ${t}. ${e.response?.data}`)}throw e}};function Te(e){return`https://overlay.dev${e}`}const Z={normal:Ee,success:De,error:Oe,warning:ke,info:Ae};function Ee(...e){return f.gray(e,`
9
- `)}function De(...e){return[f.green(`✔`),...e,`
8
+ `,examples:[[`Basic usage`,`$0 bundle`]]});async execute(){await X();let e=await new x([{title:`Authenticating`,task:X},{title:`Locating overlayed.config.ts`,task:async e=>e.config=await this.resolveConfig()},{task:async(e,t)=>{let n=await t.prompt(S).run(...this.getTargetBundles(e.config));e.targetBundles=n,this.context.stdout.write(f.green(`Selected bundles: `)+f.bold(n.join(`, `)))}}]).run();function t(e){return`${e.map(e=>`taskId=${e}`).join(`&`)}`}await new x([{title:`Uploading bundles`,task:e=>new x(e.targetBundles.map((e,t)=>({title:`Uploading ${e} bundle`,task:async n=>{n.taskIds??=[];let r=await this.uploadBundle(n.config,e);r&&(n.taskIds[t]=r)}})),{concurrent:!0,rendererOptions:{collapseSubtasks:!1}})},{title:`Waiting for bundles to be processed.`,task:e=>new x(e.taskIds.map((n,r)=>({title:`Waiting for ${f.bold(e.targetBundles[r])} bundle to be processed. This may take some time - you can wait for the bundles to appear in the dashboard here: ${f.blue(`https://overlay.dev/bundles?applicationId=${e.config.applicationId}&${t(e.taskIds)}`)}`,task:async e=>{let t=0,r;for(;;){if(t++>100)throw Error(`Processing is taking longer than expected. Open the link below and it should be done soon. If the issue persists, please contact Overlayed.`);if(r=await ve(e.config.applicationId,n),r.data.status!==`in_progress`)break;await new Promise(e=>setTimeout(e,3e3))}if(r.data.status===`failed`)throw Error(r.data.message)}})),{concurrent:!0,rendererOptions:{collapseSubtasks:!1}})}]).run(e)}async uploadBundle(e,t){let n=await ge(e.applicationId,{type:t}),r=await e[t]?.bundle()??D(Error(`No bundle found for `+t));e.debug&&r.forEach(e=>{console.log(`Zipping: `,e)});let i=await r.generateAsync({type:`nodebuffer`});if(e.debug){let e=`.overlayed/tmp`;c(e),s(`${e}/debug-${t}.zip`,i);return}return await ye(n.data.upload_request,i),(await _e(e.applicationId,n.data.asset_bundle_name)).data.task_id}getTargetBundles(e){let t=e=>`(Disabled: No config found for "${e}" in overlayed.config.ts)`;return[y,{message:`Select your desired bundles to create and upload.`,shortcuts:{all:`a`,invert:`i`},choices:[{name:`App`,value:`app`,disabled:e.app?void 0:t(`app`)},{name:`Site`,value:`site`,disabled:e.site?void 0:t(`site`)}]}]}async resolveConfig(){let[e,t]=await xe(this.context);return{...e,applicationId:be(e.applicationId),app:this.getAppBundler(e,t),site:this.getSiteBundler(e,t)}}getAppBundler(e,t){let n=new V(e),r=this.resolveCwd(t,e.app.baseDir);return e.debug&&console.log(`[App] Bundling files from: `,r),n.addGlobPattern(e.app.include,{ignore:e.app.exclude,cwd:r}),n}getSiteBundler(e,t){if(!e.site)return;let n=new Se(e),r=this.resolveCwd(t,e.site.baseDir);return e.debug&&console.log(`[Site] Bundling files from: `,r),n.addGlobPattern(e.site.include,{ignore:e.site.exclude,cwd:r}),n}resolveCwd(e,t){return t?u.resolve(u.dirname(e),t):u.dirname(e)}async catch(e){if(v(e)){let t=e.response?.status,n=(e.config?.baseURL??``)+(e.config?.url??``);throw Error(`Request to ${n} failed with status ${t}. ${e.response?.data}`)}throw e}};function Te(e){return`https://overlay.dev${e}`}const Z={normal:Ee,success:De,error:Oe,warning:ke,info:Ae};function Ee(...e){return f.gray([...e,`
9
+ `].join(` `))}function De(...e){return[f.green(`✔`),...e,`
10
10
  `].join(` `)}function Oe(...e){return[f.red(`✘`),...e,`
11
11
  `].join(` `)}function ke(...e){return[f.yellow(`⚠`),...e,`
12
12
  `].join(` `)}function Ae(...e){return[f.blue(`ℹ`),...e,`
13
13
  `].join(` `)}const je=w(C);var Q=class extends n{static paths=[[`login`]];static usage=n.Usage({description:`Authenticate with the Overlayed platform.`,details:`
14
14
  Authenticate with the Overlayed platform.
15
- `,examples:[[`Basic usage`,`$0 login`]]});async execute(){let e=Te(`/settings/api-keys?cli=true`);if(await this.openUrl(e),!await b({message:`To authenticate, you'll need an API Key. We've opened the page to create one in your browser.\n\n${Z.info(e)}\n\nOnce you have it, enter it here:`,async validate(e){q(()=>e);try{let t={email:(await J()).data.email,apiKey:e},n=Y.get();Y.set({...n,currentAccount:t,accounts:n?.accounts.concat(t)??[t]})}catch(e){if(!v(e))return`Unknown error has occurred: ${e}`;switch(e.response?.status){case 401:case 403:return`Invalid API key, please try again.`;default:return`API error, please try again later.`}}return q(()=>Y.get()?.currentAccount?.apiKey),!0}}))throw Error(`Login unknown error - this should never happen`);let t=Y.get();if(!t?.currentAccount)throw Error(`Could not get config after login`);let n=t.currentAccount.email;this.context.stdout.write(Z.success(`Authentication Complete - Logged in as ${n}`))}async openUrl(e){let t=process.platform,n;switch(t){case`darwin`:n=`open "${e}"`;break;case`win32`:n=`start "" "${e}"`;break;default:n=`xdg-open "${e}"`;break}try{await je(n)}catch{}}},Me=class extends n{static paths=[[`logout`]];static usage=n.Usage({description:`Log out of the currently authenticated account.`,details:`
15
+ `,examples:[[`Basic usage`,`$0 login`]]});async execute(){let e=Te(`/user-settings/api-keys?cli=true`);if(await this.openUrl(e),!await b({message:`To authenticate, you'll need an API Key. We've opened the page to create one in your browser.\n\n${Z.info(e)}\n\nOnce you have it, enter it here:`,async validate(e){q(()=>e);try{let t={email:(await J()).data.email,apiKey:e},n=Y.get();Y.set({...n,currentAccount:t,accounts:n?.accounts.concat(t)??[t]})}catch(e){if(!v(e))return`Unknown error has occurred: ${e}`;switch(e.response?.status){case 401:case 403:return`Invalid API key, please try again.`;default:return`API error, please try again later.`}}return q(()=>Y.get()?.currentAccount?.apiKey),!0}}))throw Error(`Login unknown error - this should never happen`);let t=Y.get();if(!t?.currentAccount)throw Error(`Could not get config after login`);let n=t.currentAccount.email;this.context.stdout.write(Z.success(`Authentication Complete - Logged in as ${n}`))}async openUrl(e){let t=process.platform,n;switch(t){case`darwin`:n=`open "${e}"`;break;case`win32`:n=`start "" "${e}"`;break;default:n=`xdg-open "${e}"`;break}try{await je(n)}catch{}}},Me=class extends n{static paths=[[`logout`]];static usage=n.Usage({description:`Log out of the currently authenticated account.`,details:`
16
16
  Log out of the currently authenticated account.
17
17
  `,examples:[[`Basic usage`,`$0 logout`]]});async execute(){let e=await X(),t=Y.get();if(!t){this.context.stdout.write(Z.normal(`Not currently logged in.`));return}let n=t.accounts.filter(t=>t.email!==e);Y.set({...t,currentAccount:void 0,accounts:n}),this.context.stdout.write(Z.normal(`Logged out from ${e}`))}},Ne=class extends n{static paths=[[`whoami`]];static usage=n.Usage({description:`Display information about the currently authenticated user.`,details:`
18
18
  Display information about the currently authenticated user.
package/package.json CHANGED
@@ -10,11 +10,11 @@
10
10
  "keywords": [
11
11
  "typescript"
12
12
  ],
13
- "version": "0.6.4",
13
+ "version": "0.6.6",
14
14
  "description": "Overlayed CLI",
15
15
  "type": "module",
16
16
  "bin": {
17
- "overlayed": "./dist/cli.js"
17
+ "overlayed": "./dist/cli.mjs"
18
18
  },
19
19
  "files": [
20
20
  "dist/**/*"
@@ -31,13 +31,14 @@
31
31
  "vitest": "^3.2.4",
32
32
  "@overlayed/api": "0.0.5",
33
33
  "@overlayed/utils": "0.0.4",
34
- "@overlayed/utils-node": "0.0.4"
34
+ "@overlayed/utils-node": "0.0.4",
35
+ "@overlayed/shared-node": "0.0.4"
35
36
  },
36
37
  "dependencies": {
37
38
  "@inquirer/prompts": "^7.10.1",
38
39
  "@listr2/prompt-adapter-inquirer": "^3.0.5",
39
40
  "arktype": "^2.1.29",
40
- "chalk": "^5.6.2",
41
+ "picocolors": "^1.1.1",
41
42
  "clipanion": "4.0.0-rc.4",
42
43
  "fs-extra": "^11.3.2",
43
44
  "glob": "^11.1.0",