@dashnex/cli 0.5.23 → 0.5.24

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/README.md CHANGED
@@ -7,14 +7,13 @@ Each module can add a command to CLI. [Read more here](https://github.com/dashne
7
7
  ## Installation
8
8
 
9
9
  ```bash
10
- pnpm install -D @dashnex/cli
10
+ npm install -g @dashnex/cli
11
11
  ```
12
12
 
13
13
  ## Usage
14
14
 
15
15
  ```bash
16
- npx dashnex <command> [options]
17
- npx @dashnex/cli <command> [options]
16
+ dashnex <command> [options]
18
17
  ```
19
18
 
20
19
  ## Commands
@@ -24,13 +23,17 @@ npx @dashnex/cli <command> [options]
24
23
  | `version` | Display the version of the CLI |
25
24
  | `login` | Log in to your DashNex account |
26
25
  | `logout` | Log out and remove local credentials |
27
- | `create` | Create a new DashNex application |
28
- | `pull` | Pull existing application to current folder |
29
- | `push` | Push local application to DashNex |
30
- | `delete` | Delete application from DashNex |
31
26
  | `whoami` | Show current logged-in business and user |
32
-
27
+ | `select` | Switch to a different business |
28
+ | `app create` | Create a new DashNex application |
29
+ | `app pull` | Pull existing application to specified folder |
30
+ | `app push` | Push local application to DashNex |
31
+ | `app delete` | Delete application from DashNex |
32
+ | `app deploy` | Deploy application to DashNex |
33
+ | `app status` | Show current application status |
34
+ | `install` | Install dependencies using pnpm or npm |
35
+ | `dev` | Run the development server |
33
36
 
34
37
  ### Options
35
38
 
36
- - **create**: `-t, --template <template>` — Template (name@branch-or-tag, default: webapp-base@live)
39
+ - **app create**: `-t, --template <template>` — Template (name@branch-or-tag, default: webapp-base@live)
@@ -0,0 +1 @@
1
+ import e from"inquirer";import t from"chalk";import{debug as o,debugError as s}from"../../lib/debug.js";import{getBusinessApiBase as a}from"../../lib/api.js";import{ensureLoggedIn as i}from"../../services/auth.js";import{createSpinner as r}from"../../lib/spinner.js";import{isUserInterrupt as n,INTERRUPTED_MESSAGE as l}from"../../lib/errors.js";import{PullCommand as c}from"./pull.js";const p=e=>Array.isArray(e.message)&&e.message.length>0?e.message.join("\n"):"string"==typeof e.message?e.message:"string"==typeof e.error?e.error:void 0,u=e=>new Promise(t=>setTimeout(t,e));class d{async pollApplicationCreated(e,t,a=5e3,i=6e4){const r=Date.now();let n=0;for(;Date.now()-r<i;){n++,o(`Polling application status (attempt ${n})...`);try{const s=await fetch(e,{headers:{Authorization:`Bearer ${t}`}});if(o(`Poll response: ${s.status}`),200===s.status){const e=await s.json();if(o(`Poll response body status: ${e.status}`),"creating"!==e.status)return o(`Application status is "${e.status}", creation complete`),{ready:!0,status:e.status};o('Application status is still "creating", continuing to poll...')}}catch(l){s(l),o(`Poll attempt ${n} failed with network error`)}await u(a)}return{ready:!1}}async execute(u={}){o("Create flow started");const d=await i();if(!d)return;o("Auth valid, checking if business already has application");const h=r(),m=`${a()}/business/v1/applications`;o(`GET ${m}`),h.start("Checking application status...");try{const e=await fetch(m,{headers:{Authorization:`Bearer ${d.token}`}});h.stop(),o(`Applications response: ${e.status}`);const s=await e.text();o(`Applications response body: ${s}`),404!==e.status&&(console.error(t.red("Business already has an application. Run 'dashnex app pull' to pull the existing one.")),process.exit(1))}catch($){if(h.stop(),s($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(n($))return void console.log(t.yellow(l));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}let f;o("No existing application, proceeding to subdomain prompt");const y=e=>`${a()}/business/v1/applications/check-subdomain?subdomain=${encodeURIComponent(e)}`;for(;;){const{sub:a}=await e.prompt([{type:"input",name:"sub",message:"Pick your subdomain:",validate:e=>!!e.trim()||"Subdomain is required"}]);f=a.trim(),o(`Checking subdomain: ${f}`);const i=y(f);o(`GET ${i}`),h.start("Checking subdomain...");try{const e=await fetch(i,{headers:{Authorization:`Bearer ${d.token}`}});h.stop(),o(`Check subdomain response: ${e.status}`);const s=await e.text();if(o(`Check subdomain response body: ${s}`),!e.ok){const a=e.headers.get("content-type")??"";let i="Failed to check subdomain availability.";if(401!==e.status&&403!==e.status||(i="Please run 'dashnex login' to authenticate.",console.error(t.red(i)),process.exit(1)),a.includes("application/json")){const e=JSON.parse(s);o(`Check subdomain error body: ${JSON.stringify(e)}`);const t=p(e);t&&(i=t)}console.error(t.red(i));continue}const a=JSON.parse(s);if(o(`Check subdomain parsed body: ${JSON.stringify(a)}`),a.available){o(`Subdomain ${f} is available`);break}console.error(t.red("Subdomain is not available. Please choose a different one."))}catch($){if(h.stop(),s($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(n($))return void console.log(t.yellow(l));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}const g=`${a()}/business/v1/cli/create`;o(`POST ${g}`);const b={subdomain:f};u.template&&(b.template=u.template,o(`Template: ${u.template}`));const w=JSON.stringify(b);o(`Create request body: ${w}`),h.start("Creating application...");try{const i=await fetch(g,{method:"POST",headers:{Authorization:`Bearer ${d.token}`,"Content-Type":"application/json"},body:w});h.stop(),o(`Create response: ${i.status}`);const r=await i.text();if(o(`Create response body: ${r}`),503===i.status){o("Create returned 503, polling for application creation..."),console.log(t.yellow("Application is being created, please wait..."));const e=`${a()}/business/v1/applications`,s=await this.pollApplicationCreated(e,d.token);s.ready||(console.error(t.red("Application creation is taking longer than expected. Try again later or run 'dashnex app pull' to check.")),process.exit(1)),"failed"===s.status&&(console.error(t.red("Application creation failed. Please try again.")),process.exit(1)),o("Application found after polling")}else if(!i.ok){const e=i.headers.get("content-type")??"";let s="Failed to create application.";if(401===i.status||403===i.status)s="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=JSON.parse(r);o(`Create error body parsed: ${JSON.stringify(e)}`);const t=p(e);t&&(s=t)}console.error(t.red(s)),process.exit(1)}o("Application created successfully");const{pull:u}=await e.prompt([{type:"confirm",name:"pull",message:"Pull the application locally?",default:!0}]);if(o(`User chose to pull: ${u}`),u){o("Running pull flow");try{const e=new c;await e.execute()}catch($){if(s($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(n($))return void console.log(t.yellow(l));console.error(t.red("Failed to pull application."))}}else console.log(t.green("Application is created successfully. Run 'dashnex app pull' to pull it to your computer or 'dashnex app deploy' to deploy it to the cloud."))}catch($){if(h.stop(),s($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(n($))return void console.log(t.yellow(l));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}}export{d as CreateCommand};
@@ -0,0 +1 @@
1
+ import e from"inquirer";import t from"chalk";import{debug as o,debugError as s}from"../../lib/debug.js";import{getBusinessApiBase as r}from"../../lib/api.js";import{ensureLoggedIn as i}from"../../services/auth.js";import{createSpinner as n}from"../../lib/spinner.js";import{isUserInterrupt as a,INTERRUPTED_MESSAGE as c}from"../../lib/errors.js";class l{async execute(){o("Delete flow started");const{confirm:l}=await e.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to delete this application? This action cannot be undone.",default:!1}]);if(!l)return o("User cancelled deletion"),void console.log(t.yellow("Deletion cancelled."));const p=await i();if(!p)return;const d=`${r()}/business/v1/applications`;o(`DELETE ${d}`);const f=n();f.start("Deleting application...");try{const e=await fetch(d,{method:"DELETE",headers:{Authorization:`Bearer ${p.token}`}});if(f.stop(),o(`Response: ${e.status}`),!e.ok){const o=e.headers.get("content-type")??"";let s="Failed to delete application.";if(401===e.status||403===e.status)s="Please run 'dashnex login' to authenticate.";else if(o.includes("application/json")){const t=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(await e.json().catch(()=>({})));t&&(s=t)}console.error(t.red(s)),process.exit(1)}const s=await e.json().catch(()=>({})),r="string"==typeof s.message?s.message:"Application deleted successfully.";o("Application deleted successfully"),console.log(t.green(r))}catch(m){if(f.stop(),s(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(a(m))return void console.log(t.yellow(c));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}}export{l as DeleteCommand};
@@ -0,0 +1 @@
1
+ import e from"chalk";import{debug as t,debugError as o}from"../../lib/debug.js";import{getDeployerBase as s}from"../../lib/api.js";import{ensureLoggedIn as r}from"../../services/auth.js";import{createSpinner as n}from"../../lib/spinner.js";import{isUserInterrupt as a,INTERRUPTED_MESSAGE as i}from"../../lib/errors.js";const c=3e5,l=99,p=e=>new Promise(t=>setTimeout(t,e)),d=async(s,r,n,a)=>{const i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"text/event-stream"}});if(t(`SSE connection opened: ${i.status}`),!i.ok){const t=i.status;let o="Failed to start deployment.";if(401===t||403===t)o="Please run 'dashnex login' to authenticate.";else try{const e=await i.text(),t=JSON.parse(e);"string"==typeof t.error?o=t.error:"string"==typeof t.message&&(o=t.message)}catch{}throw console.error(e.red(o)),new Error(`HTTP ${t}: ${o}`)}if(!i.body)throw new Error("Response body is null");t("SSE connection established successfully"),a?.();const c=i.body.getReader();try{for await(const e of async function*(e){const t=new TextDecoder("utf-8");let o="";for(;;){const{value:s,done:r}=await e.read();if(r)break;o+=t.decode(s,{stream:!0});const n=o.split("\n");o=n.pop()||"";let a="";for(const e of n)e.startsWith("data: ")?a=e.slice(6):""===e&&a&&(yield{data:a},a="")}if(o.startsWith("data: ")){const e=o.slice(6);e&&(yield{data:e})}}(c))try{if(!e.data){t("Received empty SSE event");continue}const o=JSON.parse(e.data);t(`SSE message received: ${JSON.stringify(o)}`),n(o)}catch(l){o(l),t(`Failed to parse SSE event data: ${e.data}`)}}finally{c.releaseLock()}};class f{async execute(){t("Deploy flow started");const f=await r();if(!f)return;const m=`${s()}/business/v1/applications/deploy`;t(`GET ${m} (SSE)`);let y=0,u="",g=!1,h=0,w=!1;const S=n();let $=0,v=0,x=null;const b=(e,t)=>{const o=Math.round(e);S.text(`[${o}%] ${t}`)},E=()=>{D();const e=y,t=Date.now(),o=c*((l-e)/l);x=setInterval(()=>{const s=Date.now()-t;let r;if(v>t){const e=Date.now()-v,t=l-$,o=t*3030.3030303030305;r=Math.min($+e/o*t,l)}else r=Math.min(e+s/o*(l-e),l);r>y&&(y=r,b(y,u))},200)},D=()=>{x&&(clearInterval(x),x=null)};let T=!1;const M=t=>{if(w=!0,"string"==typeof t.error)return D(),S.stop(),console.error(e.red(t.error)),g=!0,void(T=!0);if("string"==typeof t.message&&(u=t.message),"number"==typeof t.progress&&($=t.progress,v=Date.now(),t.progress>y&&(y=t.progress)),"string"==typeof t.message||"number"==typeof t.progress)if(y>=100){D(),S.stop();const t=u||"Application is deployed";process.stdout.write(`${e.green(t)}\n`),g=!0}else b(y,u)};for(;h<=5;)try{return w?b(y,u):S.start("Connecting..."),E(),await d(m,f.token,M,()=>{w||(S.text(`[${Math.round(y)}%] Deployment in progress...`),u="Deployment in progress...")}),D(),S.stop(),t("SSE connection closed"),void(T&&process.exit(1))}catch(k){if(D(),o(k),t(`SSE connection error: ${k}`),g)return S.stop(),void(T&&process.exit(1));if(a(k))return S.stop(),void console.log(e.yellow(i));k instanceof Error&&k.message.startsWith("HTTP")&&(S.stop(),console.error(e.red("Could not complete deployment. Check your connection and try again.")),process.exit(1)),h++,h>5&&(S.stop(),console.error(e.red("Deployment failed. Maximum reconnection attempts exceeded.")),process.exit(1));const s=Math.min(1e3*Math.pow(2,h-1),3e4);t(`Connection error. Reconnecting in ${s/1e3}s... (attempt ${h}/5)`),await p(s)}}}export{f as DeployCommand};
@@ -0,0 +1 @@
1
+ import{CreateCommand as e}from"./create.js";import{PullCommand as a}from"./pull.js";import{PushCommand as t}from"./push.js";import{DeleteCommand as o}from"./delete.js";import{DeployCommand as n}from"./deploy.js";import{StatusCommand as p}from"./status.js";const i={name:"app",description:"Manage DashNex applications",handler:{execute:async()=>{}},options:[],subcommands:[{name:"create",description:"Create a new DashNex application",handler:new e,options:[{flags:"-t, --template <template>",description:"Template (name@branch-or-tag)",defaultValue:"webapp-base@live"}]},{name:"pull",description:"Pull existing application to specified folder",handler:new a,options:[]},{name:"push",description:"Push local application to DashNex",handler:new t,options:[]},{name:"delete",description:"Delete application from DashNex",handler:new o,options:[]},{name:"deploy",description:"Deploy application to DashNex",handler:new n,options:[]},{name:"status",description:"Show current application status",handler:new p,options:[]}]};export{i as default};
@@ -0,0 +1 @@
1
+ import e from"chalk";import t from"fs-extra";import o from"path";import r from"os";import{spawn as i}from"child_process";import n from"inquirer";import a from"adm-zip";import{debug as s,debugError as l}from"../../lib/debug.js";import{getBusinessApiBase as c}from"../../lib/api.js";import{ensureLoggedIn as d}from"../../services/auth.js";import{createSpinner as p}from"../../lib/spinner.js";import{isUserInterrupt as m,INTERRUPTED_MESSAGE as f}from"../../lib/errors.js";const u=(e,t)=>new Promise((o,r)=>{const n=i(t,{cwd:e,shell:!0,stdio:"inherit"});n.on("error",e=>{l(e),r(e)}),n.on("close",e=>{o(null===e?0:e)})}),g=async(t,r)=>{const{install:a}=await n.prompt([{type:"confirm",name:"install",message:"Install dependencies?",default:!0}]);if(!a){if(o.resolve(t)!==o.resolve(r)){const i=o.relative(r,t);console.log(e.cyan(`Run "cd ${i}" to change to the application folder.`))}return}if(a){const o=await(async()=>{const e=e=>new Promise(t=>{const o=i(e,["--version"],{stdio:"ignore",shell:!0});o.on("error",()=>t(!1)),o.on("close",e=>t(0===e))});return await e("pnpm")?"pnpm":(await e("npm"),"npm")})();s(`Running ${o} install in ${t}`);try{const e=await u(t,`${o} install`);if(0!==e)return void s(`${o} install exited with code ${e}`)}catch(p){return l(p),void console.error(e.red(`Failed to run ${o} install.`))}}const{migrate:c}=await n.prompt([{type:"confirm",name:"migrate",message:"Create local database?",default:!0}]);if(c){s(`Running dashnex db migrate in ${t}`);try{const e=await u(t,"dashnex db migrate");if(0!==e)return void s(`dashnex db migrate exited with code ${e}`)}catch(p){return l(p),void console.error(e.red("Failed to run dashnex db migrate."))}}const{dev:d}=await n.prompt([{type:"confirm",name:"dev",message:"Run development server?",default:!0}]);if(d){s(`Running npm run dev in ${t}`);try{await u(t,"npm run dev")}catch(p){l(p),console.error(e.red("Failed to run dev server."))}}},h='Application is successfully pulled. Run "npm install" or "pnpm install" to install dependencies and then "dashnex dev" to run it';class w{async execute(i={}){s("Pull flow started");const u=await d();if(!u)return;const w=process.cwd();let v;if(i.folder)v=i.folder.trim()||".",s(`Folder argument provided: ${v}`);else{s("No folder argument, prompting user");const{folder:e}=await n.prompt([{type:"input",name:"folder",message:"Which folder to pull the application to?",default:"."}]);v=e.trim()||"."}const y=o.resolve(w,v);s(`Target folder resolved: ${y}`);const x=await t.pathExists(y);let $=!1;if(x)try{$=(await t.readdir(y)).length>0,s(`Folder exists: ${x}, has files: ${$}`)}catch(R){s(`Error reading folder: ${R}`)}if($){const{confirm:t}=await n.prompt([{type:"confirm",name:"confirm",message:"Existing files will be overwritten. Continue?",default:!0}]);if(!t)return s("User declined confirmation, exiting"),void console.log(e.yellow("Pull cancelled."));s("User confirmed overwrite")}await t.ensureDir(y),s(`Target folder ensured: ${y}`);const b=`${c()}/business/v1/cli/pull`;s(`GET ${b}`);const j=o.join(r.tmpdir(),`dashnex-pull-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),E=p();E.start("Pulling application...");try{const r=await fetch(b,{headers:{Authorization:`Bearer ${u.token}`}});if(s(`Response: ${r.status}`),!r.ok){E.stop();const t=r.headers.get("content-type")??"";let o="Failed to pull application.";if(401===r.status||403===r.status)o="Please run 'dashnex login' to authenticate.";else if(404===r.status)o="Business has no application. Run 'dashnex app create' to create one.";else if(t.includes("application/json")){const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(await r.json().catch(()=>({})));e&&(o=e)}console.error(e.red(o)),process.exit(1)}E.text("Downloading...");const i=Buffer.from(await r.arrayBuffer());await t.writeFile(j,i),s("Zip written to temp file"),E.text("Extracting...");new a(j).extractAllTo(y,!0),E.stop(),s("Extracted to target folder"),o.resolve(y)!==o.resolve(w)?(console.log(e.green(((e,t)=>o.resolve(e)===o.resolve(t)?h:`Application is successfully pulled into ${o.relative(t,e)}.`)(y,w))),process.chdir(y),s(`Changed working directory to ${y}`)):console.log(e.green(h)),await g(y,w)}catch(R){if(E.stop(),l(R),R instanceof Error&&R.message.startsWith("EXIT:"))throw R;if(m(R))return void console.log(e.yellow(f));console.error(e.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}finally{await t.remove(j).catch(()=>{}),s("Temp zip removed")}}}export{w as PullCommand};
@@ -0,0 +1 @@
1
+ import e from"chalk";import t from"fs-extra";import o from"path";import i from"os";import s from"adm-zip";import r from"ignore";import n from"inquirer";import{debug as a,debugError as c}from"../../lib/debug.js";import{getBusinessApiBase as p}from"../../lib/api.js";import{ensureLoggedIn as l}from"../../services/auth.js";import{createSpinner as d}from"../../lib/spinner.js";import{isUserInterrupt as m,INTERRUPTED_MESSAGE as f}from"../../lib/errors.js";import{DeployCommand as h}from"./deploy.js";const u=[".dashnex",".git"],w=async(e,i)=>{const s=[],r=await t.readdir(e,{withFileTypes:!0});for(const t of r){const r=o.relative(process.cwd(),o.join(e,t.name)).split(o.sep).join("/");if(u.some(e=>r===e||r.startsWith(`${e}/`)))continue;if(i.ignores(r))continue;const n=o.join(e,t.name);if(t.isDirectory()){const e=await w(n,i);s.push(...e)}else t.isFile()&&s.push(n)}return s};class g{async execute(){a("Push flow started");const g=await l();if(!g)return;const y=process.cwd(),j=o.join(y,".gitignore"),x=r();if(x.add(u),await t.pathExists(j)){const e=await t.readFile(j,"utf8");x.add(e)}a("Building file list");const $=await w(y,x);a(`Including ${$.length} files`);const b=new s;for(const e of $){const t=o.relative(y,e).split(o.sep).join("/"),i="."===o.dirname(t)?"":o.dirname(t),s=o.basename(t);b.addLocalFile(e,i,s)}const v=o.join(i.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),F=d();try{F.start("Packaging application..."),b.writeZip(v),a(`Zip written to ${v}`);const o=`${p()}/business/v1/cli/push`;a(`POST ${o}`);const i=await t.readFile(v),s=new Blob([i],{type:"application/zip"}),r=new FormData;r.append("file",s,"archive.zip");const c=new Headers;c.set("Authorization",`Bearer ${g.token}`),F.text("Uploading...");const l=await fetch(o,{method:"POST",headers:c,body:r});if(F.stop(),a(`Response: ${l.status}`),!l.ok){const t=l.headers.get("content-type")??"";let o="Failed to push application.";if(401===l.status||403===l.status)o="Please run 'dashnex login' to authenticate.";else if(t.includes("application/json")){const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(await l.json().catch(()=>({})));e&&(o=e)}console.error(e.red(o)),process.exit(1)}console.log(e.green("Application pushed successfully."));const{deploy:d}=await n.prompt([{type:"confirm",name:"deploy",message:"Deploy the application?",default:!0}]);if(a(`User chose to deploy: ${d}`),d){a("Running deploy flow");const e=new h;await e.execute()}}catch(z){if(F.stop(),c(z),z instanceof Error&&z.message.startsWith("EXIT:"))throw z;if(m(z))return void console.log(e.yellow(f));console.error(e.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}finally{await t.remove(v).catch(()=>{}),a("Temp zip removed")}}}export{g as PushCommand};
@@ -0,0 +1 @@
1
+ import t from"chalk";import{debug as o,debugError as s}from"../../lib/debug.js";import{getBusinessApiBase as e}from"../../lib/api.js";import{ensureLoggedIn as a}from"../../services/auth.js";import{createSpinner as n}from"../../lib/spinner.js";import{isUserInterrupt as r,INTERRUPTED_MESSAGE as i}from"../../lib/errors.js";class c{async execute(){o("Status flow started");const c=await a();if(!c)return;const l=`${e()}/business/v1/applications`;o(`GET ${l}`);const p=n();p.start("Fetching application status...");try{const s=await fetch(l,{headers:{Authorization:`Bearer ${c.token}`}});if(p.stop(),o(`Response: ${s.status}`),404===s.status)return void console.log(t.yellow("Application not created"));if(!s.ok){const o=s.headers.get("content-type")??"";let e="Failed to fetch application status.";if(401===s.status||403===s.status)e="Please run 'dashnex login' to authenticate.";else if(o.includes("application/json")){const t=await s.json().catch(()=>({}));"string"==typeof t.error?e=t.error:"string"==typeof t.message&&(e=t.message)}console.error(t.red(e)),process.exit(1)}const e=await s.json().catch(()=>({}));o(`Application body: ${JSON.stringify(e)}`);const a=e.status??"unknown";console.log(`Status: ${t.cyan(a)}`),e.subdomain&&console.log(`Subdomain: ${t.cyan(e.subdomain+".dashnex.site")}`)}catch(u){if(p.stop(),s(u),u instanceof Error&&u.message.startsWith("EXIT:"))throw u;if(r(u))return void console.log(t.yellow(i));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}}export{c as StatusCommand};
@@ -1 +1 @@
1
- import e from"./version.js";import{LoginCommand as o}from"./login.js";import{LogoutCommand as n}from"./logout.js";import{CreateCommand as i}from"./create.js";import{PullCommand as t}from"./pull.js";import{PushCommand as a}from"./push.js";import{DeleteCommand as r}from"./delete.js";import{WhoamiCommand as p}from"./whoami.js";import{DeployCommand as s}from"./deploy.js";import{InstallCommand as l}from"./install.js";import{DevCommand as m}from"./dev.js";const d=[{name:"version",description:"Display the version of the CLI",handler:new e,options:[]},{name:"login",description:"Log in to your DashNex account",handler:new o,options:[]},{name:"logout",description:"Log out and remove local credentials",handler:new n,options:[]},{name:"create",description:"Create a new DashNex application",handler:new i,options:[{flags:"-t, --template <template>",description:"Template (name@branch-or-tag)",defaultValue:"webapp-base@live"}]},{name:"pull",description:"Pull existing application to specified folder",handler:new t,options:[]},{name:"push",description:"Push local application to DashNex",handler:new a,options:[]},{name:"delete",description:"Delete application from DashNex",handler:new r,options:[]},{name:"whoami",description:"Show current logged-in business and user",handler:new p,options:[]},{name:"deploy",description:"Deploy application to DashNex",handler:new s,options:[]},{name:"install",description:"Install dependencies using pnpm or npm",handler:new l,options:[]},{name:"dev",description:"Run the development server",handler:new m,options:[]}];export{d as default};
1
+ import e from"./version.js";import{LoginCommand as o}from"./login.js";import{LogoutCommand as n}from"./logout.js";import{WhoamiCommand as i}from"./whoami.js";import{InstallCommand as s}from"./install.js";import{DevCommand as r}from"./dev.js";import{SelectCommand as t}from"./select.js";import p from"./app/index.js";const a=[{name:"version",description:"Display the version of the CLI",handler:new e,options:[]},{name:"login",description:"Log in to your DashNex account",handler:new o,options:[]},{name:"logout",description:"Log out and remove local credentials",handler:new n,options:[]},{name:"whoami",description:"Show current logged-in business and user",handler:new i,options:[]},p,{name:"install",description:"Install dependencies using pnpm or npm",handler:new s,options:[]},{name:"dev",description:"Run the development server",handler:new r,options:[]},{name:"select",description:"Switch to a different business",handler:new t,options:[]}];export{a as default};
@@ -0,0 +1 @@
1
+ import e from"inquirer";import s from"chalk";import r from"fs-extra";import o from"path";import{debug as n,debugJson as t,debugError as i}from"../lib/debug.js";import{getApiBase as a,apiFetch as l}from"../lib/api.js";import{ensureLoggedIn as c}from"../services/auth.js";import{createSpinner as u}from"../lib/spinner.js";import{isUserInterrupt as d,INTERRUPTED_MESSAGE as m}from"../lib/errors.js";const p=e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0;class f{async execute(){n("Select flow started");const f=await c();if(!f)return;const h=await(async e=>{let s=o.resolve(e);for(;;){const e=o.join(s,".dashnex");if(await r.pathExists(e))return e;const n=o.dirname(s);if(n===s)return null;s=n}})(process.cwd());if(!h)return console.error(s.red("Please run 'dashnex login' to authenticate.")),void process.exit(1);const b=u();try{b.start("Fetching businesses..."),n(`GET ${a()}/users/v1/business/my`);const{response:o,body:i}=await l(`${a()}/users/v1/business/my`,{headers:{Authorization:`Bearer ${f.token}`}});if(b.stop(),n(`Response: ${o.status}`),t("Businesses response",i),!o.ok){const e=p(i),r=o.status>=500?"DashNex API is temporarily unavailable. Please try again later.":e||"Failed to fetch businesses. Please try again.";console.error(s.red(r)),process.exit(1)}const c=(e=>{const s=Array.isArray(e)?e:e.items??e.data??e.businesses??[];return Array.isArray(s)?s.map(e=>{if(e&&"object"==typeof e){const s=e,r=String(s.id??s.business_id??"").trim(),o=String(s.name??s.companyName??s.business_name??"Unknown").trim();if(r)return{id:r,name:o}}return null}).filter(e=>null!==e):[]})(i);if(n(`Businesses: ${c.length}`),0===c.length&&(console.error(s.red("No businesses found for your account.")),process.exit(1)),1===c.length)return void console.log(s.yellow(`No other businesses available. You are on ${c[0].name}.`));const{businessId:u}=await e.prompt([{type:"select",name:"businessId",message:"Select business:",choices:c.map(e=>({name:e.id===f.businessId?`${e.name} (current)`:e.name,value:e.id}))}]),d=c.find(e=>e.id===u)||c[0];if(n(`Selected business: ${d.id} ${d.name}`),d.id===f.businessId)return void console.log(s.yellow(`Already on ${d.name}.`));b.start("Switching business..."),n(`GET ${a()}/business/v1/login?_switch_business=${d.id}`);const{response:m,body:y}=await l(`${a()}/business/v1/login?_switch_business=${d.id}`,{headers:{Authorization:`Bearer ${f.token}`}});if(b.stop(),n(`Response: ${m.status}`),t("Business login response",y),!m.ok){const e=p(y),r=m.status>=500?"DashNex API is temporarily unavailable. Please try again later.":e||"Failed to switch to business. Please try again.";console.error(s.red(r)),process.exit(1)}const g=y;g.token&&g.refreshToken||(console.error(s.red("Invalid response from server. Please try again.")),process.exit(1));const w={token:g.token,refreshToken:g.refreshToken,businessId:d.id};await r.writeJson(h,w,{spaces:2}),n("Saved credentials to .dashnex"),console.log(s.green(`Switched to ${d.name}.`))}catch(y){if(b.stop(),i(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(d(y))return void console.log(s.yellow(m));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}}export{f as SelectCommand};
@@ -1 +1 @@
1
- import e from"chalk";import{debug as o,debugError as t}from"../lib/debug.js";import{getApiBase as s}from"../lib/api.js";import{ensureLoggedIn as r}from"../services/auth.js";import{createSpinner as n}from"../lib/spinner.js";import{isUserInterrupt as a,INTERRUPTED_MESSAGE as i}from"../lib/errors.js";class c{async execute(){o("Whoami flow started");const c=await r();if(!c)return;const m=`${s()}/users/v1/`;o(`GET ${m}`);const l=n();l.start("Fetching user info...");try{const t=await fetch(m,{headers:{Authorization:`Bearer ${c.token}`}});if(l.stop(),o(`Response: ${t.status}`),!t.ok){const o=t.headers.get("content-type")??"";let s="Failed to fetch user info.";if(401===t.status||403===t.status)s="Please run 'npx dashnex login' to authenticate.";else if(o.includes("application/json")){const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(await t.json().catch(()=>({})));e&&(s=e)}console.error(e.red(s)),process.exit(1)}const s=await t.json().catch(()=>({})),r="string"==typeof s.name?s.name:"string"==typeof s.companyName?s.companyName:"Unknown",n=s.memberUser,a=n&&"string"==typeof n.fullName?n.fullName:n&&"string"==typeof n.name?n.name:"Unknown";o(`Whoami: ${r} (${a})`),console.log(e.green(`You are logged in as ${r} (${a})`))}catch(f){if(l.stop(),t(f),f instanceof Error&&f.message.startsWith("EXIT:"))throw f;if(a(f))return void console.log(e.yellow(i));console.error(e.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}}export{c as WhoamiCommand};
1
+ import e from"chalk";import{debug as o,debugError as t}from"../lib/debug.js";import{getApiBase as s}from"../lib/api.js";import{ensureLoggedIn as r}from"../services/auth.js";import{createSpinner as n}from"../lib/spinner.js";import{isUserInterrupt as a,INTERRUPTED_MESSAGE as i}from"../lib/errors.js";class c{async execute(){o("Whoami flow started");const c=await r();if(!c)return;const m=`${s()}/users/v1/`;o(`GET ${m}`);const l=n();l.start("Fetching user info...");try{const t=await fetch(m,{headers:{Authorization:`Bearer ${c.token}`}});if(l.stop(),o(`Response: ${t.status}`),!t.ok){const o=t.headers.get("content-type")??"";let s="Failed to fetch user info.";if(401===t.status||403===t.status)s="Please run 'dashnex login' to authenticate.";else if(o.includes("application/json")){const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(await t.json().catch(()=>({})));e&&(s=e)}console.error(e.red(s)),process.exit(1)}const s=await t.json().catch(()=>({})),r="string"==typeof s.name?s.name:"string"==typeof s.companyName?s.companyName:"Unknown",n=s.memberUser,a=n&&"string"==typeof n.fullName?n.fullName:n&&"string"==typeof n.name?n.name:"Unknown";o(`Whoami: ${r} (${a})`),console.log(e.green(`You are logged in as ${r} (${a})`))}catch(f){if(l.stop(),t(f),f instanceof Error&&f.message.startsWith("EXIT:"))throw f;if(a(f))return void console.log(e.yellow(i));console.error(e.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}}export{c as WhoamiCommand};
@@ -1 +1 @@
1
- const e="@dashnex/cli",a="0.5.23",n="Command-line interface for DashNex framework",o={name:e,version:a,description:n};export{o as default,n as description,e as name,a as version};
1
+ const e="@dashnex/cli",a="0.5.24",n="Command-line interface for DashNex framework",o={name:e,version:a,description:n};export{o as default,n as description,e as name,a as version};
@@ -1 +1 @@
1
- import e from"chalk";import n from"fs-extra";import r from"path";import{debug as s,debugError as t,debugJson as o}from"../lib/debug.js";import{getApiBase as a,apiFetch as i}from"../lib/api.js";const u=async(e,r)=>{s(`POST ${a()}/auth/v1/token/refresh`);const{response:t,body:u}=await i(`${a()}/auth/v1/token/refresh`,{method:"POST",body:JSON.stringify({refreshToken:e})});if(s(`Response: ${t.status}`),o("Refresh response",u),!t.ok)return s("Token refresh failed"),null;const h=u;if(!h.token||!h.refreshToken)return s("Refresh response missing tokens"),null;const f=await n.readJson(r);return f.token=h.token,f.refreshToken=h.refreshToken,await n.writeJson(r,f,{spaces:2}),s("Updated .dashnex with new tokens"),l(h.token,h.refreshToken,r,{...f,token:h.token,refreshToken:h.refreshToken})},l=async(e,n,r,l)=>{if(((e,n=30)=>{try{const r=e.split(".");if(3!==r.length)return!1;const t=JSON.parse(Buffer.from(r[1],"base64url").toString());if("number"!=typeof t.exp)return!1;const o=Math.floor(Date.now()/1e3),a=t.exp-n<=o;return a&&s(`Token expired or expiring soon (exp: ${t.exp}, now: ${o})`),a}catch{return!1}})(e)){if(!n)return s("Token expired, no refreshToken available"),null;s("Token expired, refreshing proactively");try{return await u(n,r)}catch(h){return t(h),null}}s(`GET ${a()}/users/v1/`);try{const{response:t,body:h}=await i(`${a()}/users/v1/`,{headers:{Authorization:`Bearer ${e}`}});if(s(`Response: ${t.status}`),o("Users response",h),t.ok){const n=h;if("string"==typeof n.name&&l.businessId)return s(`Token valid, Already logged in as ${n.name}`),{token:e,businessId:l.businessId,userName:n.name}}return n?(s("Users API rejected token, refreshing"),await u(n,r)):(s("Token invalid, no refreshToken available"),null)}catch(h){return t(h),null}},h=async(t={})=>{const{exitOnFailure:o=!0,dashnexPath:a}=t,i=a??await(async e=>{let s=r.resolve(e);for(;;){const e=r.join(s,".dashnex");if(await n.pathExists(e))return e;const t=r.dirname(s);if(t===s)return null;s=t}})(process.cwd());if(!i||!(await n.pathExists(i)))return s(".dashnex not found"),o&&(console.error(e.red("Please run 'npx dashnex login' to authenticate.")),process.exit(1)),null;let u;s(`Found .dashnex at ${i}`);try{u=await n.readJson(i)}catch{return s(".dashnex parse failed"),o&&(console.error(e.red("Please run 'npx dashnex login' to authenticate.")),process.exit(1)),null}const{token:h,refreshToken:f,businessId:c}=u;if(!h)return s(".dashnex missing token"),o&&(console.error(e.red("Please run 'npx dashnex login' to authenticate.")),process.exit(1)),null;const d=await l(h,f,i,u);return d||(o&&(console.error(e.red("Please run 'npx dashnex login' to authenticate.")),process.exit(1)),null)};export{h as ensureLoggedIn};
1
+ import e from"chalk";import r from"fs-extra";import n from"path";import{debug as s,debugError as t,debugJson as o}from"../lib/debug.js";import{getApiBase as a,apiFetch as i}from"../lib/api.js";const u=async(e,n)=>{s(`POST ${a()}/auth/v1/token/refresh`);const{response:t,body:u}=await i(`${a()}/auth/v1/token/refresh`,{method:"POST",body:JSON.stringify({refreshToken:e})});if(s(`Response: ${t.status}`),o("Refresh response",u),!t.ok)return s("Token refresh failed"),null;const h=u;if(!h.token||!h.refreshToken)return s("Refresh response missing tokens"),null;const f=await r.readJson(n);return f.token=h.token,f.refreshToken=h.refreshToken,await r.writeJson(n,f,{spaces:2}),s("Updated .dashnex with new tokens"),l(h.token,h.refreshToken,n,{...f,token:h.token,refreshToken:h.refreshToken})},l=async(e,r,n,l)=>{if(((e,r=30)=>{try{const n=e.split(".");if(3!==n.length)return!1;const t=JSON.parse(Buffer.from(n[1],"base64url").toString());if("number"!=typeof t.exp)return!1;const o=Math.floor(Date.now()/1e3),a=t.exp-r<=o;return a&&s(`Token expired or expiring soon (exp: ${t.exp}, now: ${o})`),a}catch{return!1}})(e)){if(!r)return s("Token expired, no refreshToken available"),null;s("Token expired, refreshing proactively");try{return await u(r,n)}catch(h){return t(h),null}}s(`GET ${a()}/users/v1/`);try{const{response:t,body:h}=await i(`${a()}/users/v1/`,{headers:{Authorization:`Bearer ${e}`}});if(s(`Response: ${t.status}`),o("Users response",h),t.ok){const r=h;if("string"==typeof r.name&&l.businessId)return s(`Token valid, Already logged in as ${r.name}`),{token:e,businessId:l.businessId,userName:r.name}}return r?(s("Users API rejected token, refreshing"),await u(r,n)):(s("Token invalid, no refreshToken available"),null)}catch(h){return t(h),null}},h=async(t={})=>{const{exitOnFailure:o=!0,dashnexPath:a}=t,i=a??await(async e=>{let s=n.resolve(e);for(;;){const e=n.join(s,".dashnex");if(await r.pathExists(e))return e;const t=n.dirname(s);if(t===s)return null;s=t}})(process.cwd());if(!i||!(await r.pathExists(i)))return s(".dashnex not found"),o&&(console.error(e.red("Please run 'dashnex login' to authenticate.")),process.exit(1)),null;let u;s(`Found .dashnex at ${i}`);try{u=await r.readJson(i)}catch{return s(".dashnex parse failed"),o&&(console.error(e.red("Please run 'dashnex login' to authenticate.")),process.exit(1)),null}const{token:h,refreshToken:f,businessId:c}=u;if(!h)return s(".dashnex missing token"),o&&(console.error(e.red("Please run 'dashnex login' to authenticate.")),process.exit(1)),null;const d=await l(h,f,i,u);return d||(o&&(console.error(e.red("Please run 'dashnex login' to authenticate.")),process.exit(1)),null)};export{h as ensureLoggedIn};
@@ -0,0 +1,3 @@
1
+ import { CliCommandConfig } from '@dashnex/types';
2
+ declare const appCommand: CliCommandConfig;
3
+ export default appCommand;
@@ -0,0 +1,4 @@
1
+ import { CliCommand } from '@dashnex/types';
2
+ export declare class StatusCommand implements CliCommand {
3
+ execute(): Promise<void>;
4
+ }
@@ -0,0 +1,4 @@
1
+ import { CliCommand } from '@dashnex/types';
2
+ export declare class SelectCommand implements CliCommand {
3
+ execute(): Promise<void>;
4
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@dashnex/cli",
4
- "version": "0.5.23",
4
+ "version": "0.5.24",
5
5
  "description": "Command-line interface for DashNex framework",
6
6
  "homepage": "https://dashnex.io",
7
7
  "type": "module",
@@ -38,13 +38,13 @@
38
38
  "@types/adm-zip": "^0.5.7",
39
39
  "@types/fs-extra": "^11.0.4",
40
40
  "@types/inquirer": "^9.0.9",
41
- "@types/node": "^25.2.3",
41
+ "@types/node": "^20.14.0",
42
42
  "eslint": "^9.39.2",
43
43
  "rollup-plugin-preserve-directives": "^0.4.0",
44
44
  "terser": "^5.46.0",
45
45
  "typescript": "^5.9.3",
46
46
  "vite": "^7.3.1",
47
- "vite-plugin-dts": "^4.5.4",
47
+ "vite-plugin-dts": "5.0.0-beta.6",
48
48
  "vitest": "^4.0.18"
49
49
  },
50
50
  "publishConfig": {
@@ -1 +0,0 @@
1
- import e from"inquirer";import t from"chalk";import{debug as o,debugError as s}from"../lib/debug.js";import{getBusinessApiBase as a}from"../lib/api.js";import{ensureLoggedIn as i}from"../services/auth.js";import{createSpinner as r}from"../lib/spinner.js";import{isUserInterrupt as n,INTERRUPTED_MESSAGE as l}from"../lib/errors.js";import{PullCommand as c}from"./pull.js";const p=e=>Array.isArray(e.message)&&e.message.length>0?e.message.join("\n"):"string"==typeof e.message?e.message:"string"==typeof e.error?e.error:void 0,u=e=>new Promise(t=>setTimeout(t,e));class d{async pollApplicationCreated(e,t,a=5e3,i=6e4){const r=Date.now();let n=0;for(;Date.now()-r<i;){n++,o(`Polling application status (attempt ${n})...`);try{const s=await fetch(e,{headers:{Authorization:`Bearer ${t}`}});if(o(`Poll response: ${s.status}`),200===s.status){const e=await s.json();if(o(`Poll response body status: ${e.status}`),"creating"!==e.status)return o(`Application status is "${e.status}", creation complete`),{ready:!0,status:e.status};o('Application status is still "creating", continuing to poll...')}}catch(l){s(l),o(`Poll attempt ${n} failed with network error`)}await u(a)}return{ready:!1}}async execute(u={}){o("Create flow started");const d=await i();if(!d)return;o("Auth valid, checking if business already has application");const h=r(),m=`${a()}/business/v1/applications`;o(`GET ${m}`),h.start("Checking application status...");try{const e=await fetch(m,{headers:{Authorization:`Bearer ${d.token}`}});h.stop(),o(`Applications response: ${e.status}`);const s=await e.text();o(`Applications response body: ${s}`),404!==e.status&&(console.error(t.red("Business already has an application. Run 'npx dashnex pull' to pull the existing one.")),process.exit(1))}catch($){if(h.stop(),s($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(n($))return void console.log(t.yellow(l));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}let f;o("No existing application, proceeding to subdomain prompt");const y=e=>`${a()}/business/v1/applications/check-subdomain?subdomain=${encodeURIComponent(e)}`;for(;;){const{sub:a}=await e.prompt([{type:"input",name:"sub",message:"Pick your subdomain:",validate:e=>!!e.trim()||"Subdomain is required"}]);f=a.trim(),o(`Checking subdomain: ${f}`);const i=y(f);o(`GET ${i}`),h.start("Checking subdomain...");try{const e=await fetch(i,{headers:{Authorization:`Bearer ${d.token}`}});h.stop(),o(`Check subdomain response: ${e.status}`);const s=await e.text();if(o(`Check subdomain response body: ${s}`),!e.ok){const a=e.headers.get("content-type")??"";let i="Failed to check subdomain availability.";if(401!==e.status&&403!==e.status||(i="Please run 'npx dashnex login' to authenticate.",console.error(t.red(i)),process.exit(1)),a.includes("application/json")){const e=JSON.parse(s);o(`Check subdomain error body: ${JSON.stringify(e)}`);const t=p(e);t&&(i=t)}console.error(t.red(i));continue}const a=JSON.parse(s);if(o(`Check subdomain parsed body: ${JSON.stringify(a)}`),a.available){o(`Subdomain ${f} is available`);break}console.error(t.red("Subdomain is not available. Please choose a different one."))}catch($){if(h.stop(),s($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(n($))return void console.log(t.yellow(l));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}const g=`${a()}/business/v1/cli/create`;o(`POST ${g}`);const b={subdomain:f};u.template&&(b.template=u.template,o(`Template: ${u.template}`));const w=JSON.stringify(b);o(`Create request body: ${w}`),h.start("Creating application...");try{const i=await fetch(g,{method:"POST",headers:{Authorization:`Bearer ${d.token}`,"Content-Type":"application/json"},body:w});h.stop(),o(`Create response: ${i.status}`);const r=await i.text();if(o(`Create response body: ${r}`),503===i.status){o("Create returned 503, polling for application creation..."),console.log(t.yellow("Application is being created, please wait..."));const e=`${a()}/business/v1/applications`,s=await this.pollApplicationCreated(e,d.token);s.ready||(console.error(t.red("Application creation is taking longer than expected. Try again later or run 'npx dashnex pull' to check.")),process.exit(1)),"failed"===s.status&&(console.error(t.red("Application creation failed. Please try again.")),process.exit(1)),o("Application found after polling")}else if(!i.ok){const e=i.headers.get("content-type")??"";let s="Failed to create application.";if(401===i.status||403===i.status)s="Please run 'npx dashnex login' to authenticate.";else if(e.includes("application/json")){const e=JSON.parse(r);o(`Create error body parsed: ${JSON.stringify(e)}`);const t=p(e);t&&(s=t)}console.error(t.red(s)),process.exit(1)}o("Application created successfully");const{pull:u}=await e.prompt([{type:"confirm",name:"pull",message:"Pull the application locally?",default:!0}]);if(o(`User chose to pull: ${u}`),u){o("Running pull flow");try{const e=new c;await e.execute()}catch($){if(s($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(n($))return void console.log(t.yellow(l));console.error(t.red("Failed to pull application."))}}else console.log(t.green("Application is created successfully. Run 'dashnex pull' to pull it to your computer or 'dashnex deploy' to deploy it to the cloud."))}catch($){if(h.stop(),s($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(n($))return void console.log(t.yellow(l));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}}export{d as CreateCommand};
@@ -1 +0,0 @@
1
- import e from"inquirer";import t from"chalk";import{debug as o,debugError as s}from"../lib/debug.js";import{getBusinessApiBase as r}from"../lib/api.js";import{ensureLoggedIn as i}from"../services/auth.js";import{createSpinner as n}from"../lib/spinner.js";import{isUserInterrupt as a,INTERRUPTED_MESSAGE as c}from"../lib/errors.js";class l{async execute(){o("Delete flow started");const{confirm:l}=await e.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to delete this application? This action cannot be undone.",default:!1}]);if(!l)return o("User cancelled deletion"),void console.log(t.yellow("Deletion cancelled."));const p=await i();if(!p)return;const d=`${r()}/business/v1/applications`;o(`DELETE ${d}`);const f=n();f.start("Deleting application...");try{const e=await fetch(d,{method:"DELETE",headers:{Authorization:`Bearer ${p.token}`}});if(f.stop(),o(`Response: ${e.status}`),!e.ok){const o=e.headers.get("content-type")??"";let s="Failed to delete application.";if(401===e.status||403===e.status)s="Please run 'npx dashnex login' to authenticate.";else if(o.includes("application/json")){const t=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(await e.json().catch(()=>({})));t&&(s=t)}console.error(t.red(s)),process.exit(1)}const s=await e.json().catch(()=>({})),r="string"==typeof s.message?s.message:"Application deleted successfully.";o("Application deleted successfully"),console.log(t.green(r))}catch(m){if(f.stop(),s(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(a(m))return void console.log(t.yellow(c));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}}export{l as DeleteCommand};
@@ -1 +0,0 @@
1
- import e from"chalk";import{debug as t,debugError as o}from"../lib/debug.js";import{getDeployerBase as s}from"../lib/api.js";import{ensureLoggedIn as r}from"../services/auth.js";import{createSpinner as n}from"../lib/spinner.js";import{isUserInterrupt as a,INTERRUPTED_MESSAGE as i}from"../lib/errors.js";const c=3e5,l=99,p=e=>new Promise(t=>setTimeout(t,e)),d=async(s,r,n,a)=>{const i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"text/event-stream"}});if(t(`SSE connection opened: ${i.status}`),!i.ok){const t=i.status;let o="Failed to start deployment.";if(401===t||403===t)o="Please run 'npx dashnex login' to authenticate.";else try{const e=await i.text(),t=JSON.parse(e);"string"==typeof t.error?o=t.error:"string"==typeof t.message&&(o=t.message)}catch{}throw console.error(e.red(o)),new Error(`HTTP ${t}: ${o}`)}if(!i.body)throw new Error("Response body is null");t("SSE connection established successfully"),a?.();const c=i.body.getReader();try{for await(const e of async function*(e){const t=new TextDecoder("utf-8");let o="";for(;;){const{value:s,done:r}=await e.read();if(r)break;o+=t.decode(s,{stream:!0});const n=o.split("\n");o=n.pop()||"";let a="";for(const e of n)e.startsWith("data: ")?a=e.slice(6):""===e&&a&&(yield{data:a},a="")}if(o.startsWith("data: ")){const e=o.slice(6);e&&(yield{data:e})}}(c))try{if(!e.data){t("Received empty SSE event");continue}const o=JSON.parse(e.data);t(`SSE message received: ${JSON.stringify(o)}`),n(o)}catch(l){o(l),t(`Failed to parse SSE event data: ${e.data}`)}}finally{c.releaseLock()}};class f{async execute(){t("Deploy flow started");const f=await r();if(!f)return;const m=`${s()}/business/v1/applications/deploy`;t(`GET ${m} (SSE)`);let y=0,u="",g=!1,h=0,w=!1;const S=n();let x=0,$=0,v=null;const b=(e,t)=>{const o=Math.round(e);S.text(`[${o}%] ${t}`)},E=()=>{D();const e=y,t=Date.now(),o=c*((l-e)/l);v=setInterval(()=>{const s=Date.now()-t;let r;if($>t){const e=Date.now()-$,t=l-x,o=t*3030.3030303030305;r=Math.min(x+e/o*t,l)}else r=Math.min(e+s/o*(l-e),l);r>y&&(y=r,b(y,u))},200)},D=()=>{v&&(clearInterval(v),v=null)};let T=!1;const M=t=>{if(w=!0,"string"==typeof t.error)return D(),S.stop(),console.error(e.red(t.error)),g=!0,void(T=!0);if("string"==typeof t.message&&(u=t.message),"number"==typeof t.progress&&(x=t.progress,$=Date.now(),t.progress>y&&(y=t.progress)),"string"==typeof t.message||"number"==typeof t.progress)if(y>=100){D(),S.stop();const t=u||"Application is deployed";process.stdout.write(`${e.green(t)}\n`),g=!0}else b(y,u)};for(;h<=5;)try{return w?b(y,u):S.start("Connecting..."),E(),await d(m,f.token,M,()=>{w||(S.text(`[${Math.round(y)}%] Deployment in progress...`),u="Deployment in progress...")}),D(),S.stop(),t("SSE connection closed"),void(T&&process.exit(1))}catch(k){if(D(),o(k),t(`SSE connection error: ${k}`),g)return S.stop(),void(T&&process.exit(1));if(a(k))return S.stop(),void console.log(e.yellow(i));k instanceof Error&&k.message.startsWith("HTTP")&&(S.stop(),console.error(e.red("Could not complete deployment. Check your connection and try again.")),process.exit(1)),h++,h>5&&(S.stop(),console.error(e.red("Deployment failed. Maximum reconnection attempts exceeded.")),process.exit(1));const s=Math.min(1e3*Math.pow(2,h-1),3e4);t(`Connection error. Reconnecting in ${s/1e3}s... (attempt ${h}/5)`),await p(s)}}}export{f as DeployCommand};
@@ -1 +0,0 @@
1
- import e from"chalk";import t from"fs-extra";import o from"path";import r from"os";import{spawn as n}from"child_process";import i from"inquirer";import a from"adm-zip";import{debug as s,debugError as l}from"../lib/debug.js";import{getBusinessApiBase as c}from"../lib/api.js";import{ensureLoggedIn as d}from"../services/auth.js";import{createSpinner as p}from"../lib/spinner.js";import{isUserInterrupt as m,INTERRUPTED_MESSAGE as f}from"../lib/errors.js";const u=(e,t)=>new Promise((o,r)=>{const i=n(t,{cwd:e,shell:!0,stdio:"inherit"});i.on("error",e=>{l(e),r(e)}),i.on("close",e=>{o(null===e?0:e)})}),g=async(t,r)=>{const{install:a}=await i.prompt([{type:"confirm",name:"install",message:"Install dependencies?",default:!0}]);if(!a){if(o.resolve(t)!==o.resolve(r)){const n=o.relative(r,t);console.log(e.cyan(`Run "cd ${n}" to change to the application folder.`))}return}if(a){const o=await(async()=>{const e=e=>new Promise(t=>{const o=n(e,["--version"],{stdio:"ignore",shell:!0});o.on("error",()=>t(!1)),o.on("close",e=>t(0===e))});return await e("pnpm")?"pnpm":(await e("npm"),"npm")})();s(`Running ${o} install in ${t}`);try{const e=await u(t,`${o} install`);if(0!==e)return void s(`${o} install exited with code ${e}`)}catch(p){return l(p),void console.error(e.red(`Failed to run ${o} install.`))}}const{migrate:c}=await i.prompt([{type:"confirm",name:"migrate",message:"Create local database?",default:!0}]);if(c){s(`Running npx dashnex db migrate in ${t}`);try{const e=await u(t,"npx dashnex db migrate");if(0!==e)return void s(`dashnex db migrate exited with code ${e}`)}catch(p){return l(p),void console.error(e.red("Failed to run dashnex db migrate."))}}const{dev:d}=await i.prompt([{type:"confirm",name:"dev",message:"Run development server?",default:!0}]);if(d){s(`Running npm run dev in ${t}`);try{await u(t,"npm run dev")}catch(p){l(p),console.error(e.red("Failed to run dev server."))}}},h='Application is successfully pulled. Run "npm install" or "pnpm install" to install dependencies and then "npx dashnex dev" to run it';class w{async execute(n={}){s("Pull flow started");const u=await d();if(!u)return;const w=process.cwd();let v;if(n.folder)v=n.folder.trim()||".",s(`Folder argument provided: ${v}`);else{s("No folder argument, prompting user");const{folder:e}=await i.prompt([{type:"input",name:"folder",message:"Which folder to pull the application to?",default:"."}]);v=e.trim()||"."}const x=o.resolve(w,v);s(`Target folder resolved: ${x}`);const y=await t.pathExists(x);let $=!1;if(y)try{$=(await t.readdir(x)).length>0,s(`Folder exists: ${y}, has files: ${$}`)}catch(R){s(`Error reading folder: ${R}`)}if($){const{confirm:t}=await i.prompt([{type:"confirm",name:"confirm",message:"Existing files will be overwritten. Continue?",default:!0}]);if(!t)return s("User declined confirmation, exiting"),void console.log(e.yellow("Pull cancelled."));s("User confirmed overwrite")}await t.ensureDir(x),s(`Target folder ensured: ${x}`);const b=`${c()}/business/v1/cli/pull`;s(`GET ${b}`);const j=o.join(r.tmpdir(),`dashnex-pull-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),E=p();E.start("Pulling application...");try{const r=await fetch(b,{headers:{Authorization:`Bearer ${u.token}`}});if(s(`Response: ${r.status}`),!r.ok){E.stop();const t=r.headers.get("content-type")??"";let o="Failed to pull application.";if(401===r.status||403===r.status)o="Please run 'npx dashnex login' to authenticate.";else if(404===r.status)o="Business has no application. Run 'npx dashnex create' to create one.";else if(t.includes("application/json")){const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(await r.json().catch(()=>({})));e&&(o=e)}console.error(e.red(o)),process.exit(1)}E.text("Downloading...");const n=Buffer.from(await r.arrayBuffer());await t.writeFile(j,n),s("Zip written to temp file"),E.text("Extracting...");new a(j).extractAllTo(x,!0),E.stop(),s("Extracted to target folder"),o.resolve(x)!==o.resolve(w)?(console.log(e.green(((e,t)=>o.resolve(e)===o.resolve(t)?h:`Application is successfully pulled into ${o.relative(t,e)}.`)(x,w))),process.chdir(x),s(`Changed working directory to ${x}`)):console.log(e.green(h)),await g(x,w)}catch(R){if(E.stop(),l(R),R instanceof Error&&R.message.startsWith("EXIT:"))throw R;if(m(R))return void console.log(e.yellow(f));console.error(e.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}finally{await t.remove(j).catch(()=>{}),s("Temp zip removed")}}}export{w as PullCommand};
@@ -1 +0,0 @@
1
- import e from"chalk";import t from"fs-extra";import o from"path";import i from"os";import s from"adm-zip";import r from"ignore";import n from"inquirer";import{debug as a,debugError as p}from"../lib/debug.js";import{getBusinessApiBase as c}from"../lib/api.js";import{ensureLoggedIn as l}from"../services/auth.js";import{createSpinner as d}from"../lib/spinner.js";import{isUserInterrupt as m,INTERRUPTED_MESSAGE as f}from"../lib/errors.js";import{DeployCommand as h}from"./deploy.js";const u=[".dashnex",".git"],w=async(e,i)=>{const s=[],r=await t.readdir(e,{withFileTypes:!0});for(const t of r){const r=o.relative(process.cwd(),o.join(e,t.name)).split(o.sep).join("/");if(u.some(e=>r===e||r.startsWith(`${e}/`)))continue;if(i.ignores(r))continue;const n=o.join(e,t.name);if(t.isDirectory()){const e=await w(n,i);s.push(...e)}else t.isFile()&&s.push(n)}return s};class g{async execute(){a("Push flow started");const g=await l();if(!g)return;const y=process.cwd(),j=o.join(y,".gitignore"),x=r();if(x.add(u),await t.pathExists(j)){const e=await t.readFile(j,"utf8");x.add(e)}a("Building file list");const $=await w(y,x);a(`Including ${$.length} files`);const b=new s;for(const e of $){const t=o.relative(y,e).split(o.sep).join("/"),i="."===o.dirname(t)?"":o.dirname(t),s=o.basename(t);b.addLocalFile(e,i,s)}const v=o.join(i.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),F=d();try{F.start("Packaging application..."),b.writeZip(v),a(`Zip written to ${v}`);const o=`${c()}/business/v1/cli/push`;a(`POST ${o}`);const i=await t.readFile(v),s=new Blob([i],{type:"application/zip"}),r=new FormData;r.append("file",s,"archive.zip");const p=new Headers;p.set("Authorization",`Bearer ${g.token}`),F.text("Uploading...");const l=await fetch(o,{method:"POST",headers:p,body:r});if(F.stop(),a(`Response: ${l.status}`),!l.ok){const t=l.headers.get("content-type")??"";let o="Failed to push application.";if(401===l.status||403===l.status)o="Please run 'npx dashnex login' to authenticate.";else if(t.includes("application/json")){const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(await l.json().catch(()=>({})));e&&(o=e)}console.error(e.red(o)),process.exit(1)}console.log(e.green("Application pushed successfully."));const{deploy:d}=await n.prompt([{type:"confirm",name:"deploy",message:"Deploy the application?",default:!0}]);if(a(`User chose to deploy: ${d}`),d){a("Running deploy flow");const e=new h;await e.execute()}}catch(z){if(F.stop(),p(z),z instanceof Error&&z.message.startsWith("EXIT:"))throw z;if(m(z))return void console.log(e.yellow(f));console.error(e.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}finally{await t.remove(v).catch(()=>{}),a("Temp zip removed")}}}export{g as PushCommand};
File without changes
File without changes