dashnex 0.5.86 → 0.5.87

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.
@@ -1 +1 @@
1
- var e={$schema:"https://json.schemastore.org/package",name:"@dashnex/cli",version:"0.5.86",description:"Command-line interface for DashNex framework",homepage:"https://dashnex.io",type:"module",bin:{dashnex:"bin/dashnex"},engines:{node:">=22"},exports:{".":{types:"./dist/server.d.ts",default:"./dist/server.js"},"./client":{types:"./dist/client.d.ts",default:"./dist/client.js"}},scripts:{build:"vite build",dev:"vite build --watch --mode development",test:"vitest run"},keywords:["dashnex","cli"],author:"Dashnex Team",license:"UNLICENSED",dependencies:{"adm-zip":"^0.5.17",chalk:"^5.6.2",commander:"^14.0.3",diff:"^8.0.4",dotenv:"^17.4.2","fs-extra":"^11.3.5",ignore:"^7.0.5",inquirer:"^13.4.3",partysocket:"^1.3.0",ws:"^8.21.0"},devDependencies:{"@dashnex/types":"^1.4.2","@types/adm-zip":"^0.5.8","@types/fs-extra":"^11.0.4","@types/inquirer":"^9.0.9","@types/node":"^25.7.0","@types/ws":"^8.18.1",eslint:"^9.39.4","rollup-plugin-preserve-directives":"^0.4.0",terser:"^5.47.1",typescript:"^5.9.3",vite:"^8.0.12","vite-plugin-dts":"5.0.0-beta.6",vitest:"^4.1.6"},publishConfig:{registry:"https://npm.dashnex.com/"},files:["dist","bin","AGENTS.md","CLAUDE.md"]},s={};export{e as n,s as t};
1
+ var e={$schema:"https://json.schemastore.org/package",name:"@dashnex/cli",version:"0.5.87",description:"Command-line interface for DashNex framework",homepage:"https://dashnex.io",type:"module",bin:{dashnex:"bin/dashnex"},engines:{node:">=22"},exports:{".":{types:"./dist/server.d.ts",default:"./dist/server.js"},"./client":{types:"./dist/client.d.ts",default:"./dist/client.js"}},scripts:{build:"vite build",dev:"vite build --watch --mode development",test:"vitest run"},keywords:["dashnex","cli"],author:"Dashnex Team",license:"UNLICENSED",dependencies:{"adm-zip":"^0.5.17",chalk:"^5.6.2",commander:"^14.0.3",diff:"^8.0.4",dotenv:"^17.4.2","fs-extra":"^11.3.5",ignore:"^7.0.5",inquirer:"^13.4.3",partysocket:"^1.3.0",ws:"^8.21.0"},devDependencies:{"@dashnex/types":"^1.4.2","@types/adm-zip":"^0.5.8","@types/fs-extra":"^11.0.4","@types/inquirer":"^9.0.9","@types/node":"^25.7.0","@types/ws":"^8.18.1",eslint:"^9.39.4","rollup-plugin-preserve-directives":"^0.4.0",terser:"^5.47.1",typescript:"^5.9.3",vite:"^8.0.12","vite-plugin-dts":"5.0.0-beta.6",vitest:"^4.1.6"},publishConfig:{registry:"https://npm.dashnex.com/"},files:["dist","bin","AGENTS.md","CLAUDE.md"]},s={};export{e as n,s as t};
package/dist/client.js CHANGED
@@ -1 +1 @@
1
- import{n as s,t as e}from"./chunks/dashnex-DMegPU38.js";var n={name:s.name,version:s.version,description:s.description,...e};export{n as default};
1
+ import{n as s,t as e}from"./chunks/dashnex-D2jglM0m.js";var n={name:s.name,version:s.version,description:s.description,...e};export{n as default};
@@ -1 +1 @@
1
- import{a as e,c as t,d as s,f as o,i as n,l as r,n as a,o as i,r as c,s as l,t as p,u as d}from"../chunks/auth-28liVZ3c.js";import u from"chalk";import h from"fs-extra";import m from"path";import{fileURLToPath as f}from"url";import{spawn as g}from"child_process";import y from"fs";import w from"inquirer";import $ from"os";import v from"adm-zip";import{diffLines as k}from"diff";import{createHash as b}from"crypto";import x from"ignore";import{WebSocket as S}from"partysocket";import E from"ws";import{inspect as C}from"node:util";var P=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],D=(e="")=>{if(process.env.DASHNEX_CI)return{start:()=>{},stop:()=>{},text:()=>{}};let t=null,s=0,o=e;const n=()=>{const e=P[s%P.length];process.stderr.write(`\r${e} ${o}`),s++};return{start:e=>{void 0!==e&&(o=e),t||(s=0,n(),t=setInterval(n,80))},stop:()=>{t&&(clearInterval(t),t=null),process.stderr.write("\r\n")},text:e=>{o=e,t&&n()}}},T=(e,t,s)=>{const o=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);let n=s;429===e.status?n="Too many requests. Please wait a moment and try again.":e.status>=500?n="DashNex API is temporarily unavailable. Please try again later.":o&&(n=o),console.error(u.red(n)),process.exit(1)},A=["Using vars defined in \\.env","\\(node:\\d+\\) MaxListenersExceededWarning:","\\(Use `node --trace-warnings","\\[WARNING\\].*You have defined bindings to the following internal Durable Objects","You have defined bindings to the following internal Durable Objects",'\\{"name":".+","class_name":".+"\\}',"These will not work in local development, but they should work in production","If you want to develop these locally, you can define your DO in a separate Worker","For detailed instructions, refer to the Durable Objects section here:","developers.cloudflare.com/workers/wrangler/api#supported-bindings","workerd/server/server\\.c\\+\\+.*warning:.*DurableObjectNamespace"],j=(e,t)=>t.length>0&&t.some(t=>t.test(e)),N=(e,s)=>{let o="";return{write:n=>{const r="string"==typeof n?n:n.toString();o+=r;const a=o.split(/\r?\n/);o=a.pop()??"";for(const o of a){const n=o.trim();n?j(n,s)?t(`Filtered: ${n}`):e.write(o+"\n"):t("Filtered: <empty line>")}},flush:()=>{const n=o.trim();if(n){if(j(n,s))return t(`Filtered: ${n}`),void(o="");e.write(o),o=""}else o=""}}},F=async(e,s={})=>{const o=m.join(e,"dashnex.json"),n=m.join(e,"package.json");if(t(`Checking for dashnex.json at: ${o}`),!(await h.pathExists(o)))throw new Error("Run this command in a DashNex Web application folder.");if(t("dashnex.json found, checking for package.json"),!(await h.pathExists(n)))throw new Error("package.json is missing.");let a;t("package.json found, checking for dev script");try{a=await h.readJson(n)}catch(l){throw r(l),new Error("Failed to read package.json.")}if(!a.scripts||!a.scripts.dev)throw new Error('The "dev" script is missing from package.json. Please add a "dev" script to package.json.');t("dev script found, checking for npm availability");const i=await(async e=>new Promise(t=>{const s=g(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>{t(!1)}),s.on("close",e=>{t(0===e)})}))("npm");if(t(`npm available: ${i}`),!i)throw new Error("npm is not available. Please install npm to continue.");const c=s.https?["--","--experimental-https"]:[];return t(`npm available, executing: npm run dev in ${e}${s.https?" -- --experimental-https":""}`),(async(e,t=[],s=process.cwd(),o=[])=>{const n=t.length?`${e} ${t.join(" ")}`:e,a=o.length>0;return new Promise((e,t)=>{const i=g(n,{stdio:a?["inherit","pipe","pipe"]:"inherit",cwd:s,shell:!0,env:{...process.env,NODE_ENV:"development",FORCE_COLOR:"1"}});if(i.on("error",e=>{r(e),t(e)}),a&&i.stdout&&i.stderr){const t=N(process.stdout,o),s=N(process.stderr,o);i.stdout.on("data",e=>t.write(e)),i.stderr.on("data",e=>s.write(e)),i.on("close",o=>{t.flush(),s.flush(),e(null===o?0:o)})}else i.on("close",t=>{e(null===t?0:t)})})})("npm run dev",c,e,(()=>{const e=[];for(const s of A)try{e.push(new RegExp(s))}catch{t(`Invalid dev output filter pattern ignored: ${s}`)}return e})())},I=async e=>new Promise(t=>{const s=g(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>{t(!1)}),s.on("close",e=>{t(0===e)})}),O=async e=>{let s;if(await I("pnpm"))s="pnpm install --config.strict-dep-builds=false",t("Using package manager: pnpm");else{if(!(await I("npm")))throw new Error("Neither pnpm nor npm is available. Install Node.js (which bundles npm) or pnpm to continue.");s="npm install --legacy-peer-deps",t("Using package manager: npm (with --legacy-peer-deps for DashNex peer-dep overlap)")}return t(`Executing: ${s} in ${e}`),new Promise((t,o)=>{const n=[],a=[],i=g(s,{stdio:["ignore","pipe","pipe"],cwd:e,shell:!0,env:{...process.env,NPM_CONFIG_LOGLEVEL:"error"}});i.stdout&&i.stdout.on("data",e=>n.push(e)),i.stderr&&i.stderr.on("data",e=>a.push(e)),i.on("error",e=>{r(e),o(e)}),i.on("close",e=>{const s=null===e?0:e;0!==s&&(n.length&&process.stdout.write(Buffer.concat(n)),a.length&&process.stderr.write(Buffer.concat(a))),t(s)})})},R="Run this command in a DashNex Web application folder.",B=e=>{const t=m.join(e,"dashnex.json");return h.pathExistsSync(t)},z=(e,t=!1)=>{t||console.log(u.cyan(e))},L=(e,s,o={})=>{const n=`${e} ${s.join(" ")}`,a=!0===o.silent;return new Promise((s,o)=>{t(`Running: ${n}`);const i=g(n,{stdio:a?["ignore","pipe","pipe"]:"inherit",cwd:process.cwd(),shell:!0});i.on("error",e=>{r(e),o(e)}),i.on("close",o=>{t(`${e} exited with code ${o}`),s(null===o?1:o)})})},M=(e,s)=>new Promise((o,n)=>{t(`Running: ${e} ${s.join(" ")}`);const a=g(e,s,{cwd:process.cwd()});let i="";a.stdout?.on("data",e=>{i+=e.toString()}),a.stderr?.on("data",e=>{i+=e.toString()}),a.on("error",e=>{r(e),n(e)}),a.on("close",s=>{t(`${e} exited with code ${s}`),o({exitCode:null===s?1:s,output:i})})}),U=async e=>{t("Running check: install");try{return 0===await O(process.cwd())}catch(s){return r(s),!e&&s instanceof Error&&console.error(u.red(s.message)),!1}},W=async()=>{try{const{output:e}=await M(process.execPath,[process.argv[1],"db","migrate","--help"]);return e.includes("Usage: dashnex db migrate")}catch(e){return r(e),!1}},J=async e=>{t("Running check: db migrate");try{const{exitCode:s,output:o}=await M(process.execPath,[process.argv[1],"db","migrate"]);return 0===s||(o.includes("Unknown command")?(t("db migrate command is not available, skipping"),!0):(!e&&o.trim().length>0&&process.stderr.write(o),!1))}catch(s){return r(s),!0}},G=e=>new Promise(t=>{const s=g(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>t(!1)),s.on("close",e=>t(0===e))}),_=[{name:"TypeScript",command:"npx",args:["tsc","--noEmit"],notFoundMessage:"TypeScript is not available. Please install it with: npm install -D typescript"}],q=class{async execute(){t("Check flow started"),B(process.cwd())||(console.error(u.red(R)),process.exit(1)),z("Checking dependencies..."),await U(!1)||(console.error(u.red("Check failed.")),process.exit(1)),t(`Running ${_.length} check(s)`);for(const s of _){t(`Running check: ${s.name}`),z(`Checking ${s.name}...`),await G(s.command)||(console.error(u.red(s.notFoundMessage)),process.exit(1));try{0!==await L(s.command,s.args)&&(console.error(u.red("Check failed.")),process.exit(1))}catch(e){r(e),console.error(u.red(s.notFoundMessage)),process.exit(1)}}await W()?(z("Checking database migrations..."),await J(!1)||(console.error(u.red("Check failed.")),process.exit(1))):t("db migrate command is not available, skipping"),console.log(u.green("All checks passed."))}async run(e=!1){if(t("Running checks (called from push)"),!B(process.cwd()))return e||console.error(u.red(R)),!1;if(z("Checking dependencies...",e),!(await U(e)))return!1;const s=e?{silent:!0}:void 0;for(const n of _){if(t(`Running check: ${n.name}`),z(`Checking ${n.name}...`,e),!(await G(n.command)))return console.error(u.red(n.notFoundMessage)),!1;try{if(0!==await L(n.command,n.args,s))return!1}catch(o){return r(o),console.error(u.red(n.notFoundMessage)),!1}}if(await W()){if(z("Checking database migrations...",e),!(await J(e)))return!1}else t("db migrate command is not available, skipping");return e||console.log(u.green("All checks passed.")),!0}},X=" │ ",H=e=>e.subarray(0,8192).includes(0),Y=e=>{const t=e.split("\n");return""===t[t.length-1]&&t.pop(),t},V=(e,t)=>{if(null===e)return" ".repeat(t);const s=e.replace(/\t/g," ");return s.length<=t?s.padEnd(t):`${s.slice(0,Math.max(0,t-1))}…`},K=(e,t,s)=>{const o=Math.max(s??process.stdout.columns??120,43),n=Math.floor((o-3)/2),r=((e,t)=>{const s=[],o=k(e,t);for(let n=0;n<o.length;n+=1){const e=o[n];if(e.removed){const t=Y(e.value),r=o[n+1],a=r?.added?Y(r.value):[];r?.added&&(n+=1);const i=Math.max(t.length,a.length);for(let e=0;e<i;e+=1)s.push({left:t[e]??null,right:a[e]??null,changed:!0})}else if(e.added)for(const t of Y(e.value))s.push({left:null,right:t,changed:!0});else for(const t of Y(e.value))s.push({left:t,right:t,changed:!1})}return s})(e,t),a=/* @__PURE__ */new Set;r.forEach((e,t)=>{if(e.changed)for(let s=Math.max(0,t-3);s<=Math.min(r.length-1,t+3);s+=1)a.add(s)});const i=[];i.push(u.bold(V("local (current)",n))+u.dim(X)+u.bold("incoming"));let c=-1,l=0,p=0;for(let d=0;d<r.length;d+=1){if(!a.has(d))continue;if(l>=200){p+=1;continue}-1!==c&&d>c+1&&i.push(u.dim("···")),c=d,l+=1;const e=r[d],t=V(e.left,n),s=V(e.right,n);if(!e.changed){i.push(u.dim(t)+u.dim(X)+u.dim(s));continue}const o=null!==e.left?u.red(t):t,h=null!==e.right?u.green(s):s;i.push(o+u.dim(X)+h)}return p>0&&i.push(u.dim(`… ${p} more diff line(s) not shown`)),i.join("\n")},Z=[".dashnex",".git",".vinext",".wrangler","wrangler.jsonc","wrangler.toml",".dev.vars",".github"],Q=[".env","wrangler.jsonc"],ee=e=>m.join(e,a,"sync.json"),te=e=>b("sha1").update(`blob ${e.length}\0`).update(e).digest("hex"),se=e=>e.split(m.sep).join("/"),oe=e=>Z.some(t=>e===t||e.startsWith(`${t}/`)),ne=async e=>{const t=await(async e=>{const t=x();t.add(Z);const s=m.join(e,".gitignore");return await h.pathExists(s)&&t.add(await h.readFile(s,"utf8")),t})(e),s=[],o=async n=>{const r=await h.readdir(n,{withFileTypes:!0});for(const a of r){const r=m.join(n,a.name),i=se(m.relative(e,r));oe(i)||t.ignores(a.isDirectory()?`${i}/`:i)||(a.isDirectory()?await o(r):a.isFile()&&s.push(i))}};return await o(e),s},re=async(e,t={})=>{const s={},o=await ne(e);for(const n of o)s[n]=te(await h.readFile(m.join(e,n)));if(t.includeGenerated)for(const n of Q){if(n in s)continue;const t=m.join(e,n);(await h.lstat(t).catch(()=>null))?.isFile()&&(s[n]=te(await h.readFile(t)))}return s},ae=async e=>{try{const t=await h.readFile(ee(e),"utf8"),s=JSON.parse(t);return"string"!=typeof s?.commit||"object"!=typeof s?.manifest||null===s.manifest?null:s}catch{return null}},ie=async(e,s,o)=>{const n={commit:s,manifest:o,updatedAt:/* @__PURE__ */(new Date).toISOString()},r=ee(e);try{await h.ensureDir(m.dirname(r)),await h.writeFile(r,`${JSON.stringify(n,null,2)}\n`),t(`Sync state written: commit ${s}, ${Object.keys(o).length} files`)}catch(a){t(`Failed to write sync state: ${a instanceof Error?a.message:"unknown"}`)}},ce=1048576,le=async(e,s)=>{const{install:o}=await w.prompt([{type:"confirm",name:"install",message:"Install dependencies?",default:!0}]);if(!o){if(m.resolve(e)!==m.resolve(s)){const t=m.relative(s,e);console.log(u.cyan(`Run "cd ${t}" to change to the application folder.`))}return}try{const s=D();s.start("Installing dependencies...");try{const o=await O(e);if(s.stop(),0!==o)return void t(`install exited with code ${o}`)}catch(i){throw s.stop(),i}}catch(i){return r(i),void console.error(u.red(i instanceof Error?i.message:"Failed to run install."))}const{migrate:n}=await w.prompt([{type:"confirm",name:"migrate",message:"Create or update database?",default:!0}]);if(!n)return;t(`Running dashnex db migrate in ${e}`);try{const s=D();s.start("Creating or updating database...");try{const o=await((e,t,s)=>{const o=`${m.join(e,"node_modules",".bin")}${m.delimiter}${process.env.PATH??""}`,n={...process.env,PATH:o};return new Promise((o,a)=>{const i=g(t,{cwd:e,shell:!0,stdio:"inherit",env:s?{...n,...s}:n});i.on("error",e=>{r(e),a(e)}),i.on("close",e=>{o(null===e?0:e)})})})(e,"dashnex db migrate");if(s.stop(),0!==o)return void t(`dashnex db migrate exited with code ${o}`)}catch(i){throw s.stop(),i}}catch(i){return r(i),void console.error(u.red("Failed to run dashnex db migrate."))}const{dev:a}=await w.prompt([{type:"confirm",name:"dev",message:"Run development server?",default:!0}]);if(a)try{await F(e)}catch(i){r(i),console.error(u.red(i instanceof Error?i.message:"Failed to run dev server."))}},pe=(e,t)=>{if(e.length!==t.length)return`local ${e.length} bytes, incoming ${t.length} bytes`;const s=e.length;for(let o=0;o<s;o+=1)if(e[o]!==t[o]){return`size ${s} matches; first diff at byte ${o} (local=0x${e[o].toString(16).padStart(2,"0")} incoming=0x${t[o].toString(16).padStart(2,"0")})`}return`size ${s} matches; no byte difference (unexpected)`},de=async(e,t)=>{let s;try{s=await h.lstat(e)}catch{return{kind:"new"}}if(s.isDirectory())return{kind:"different",reason:"target is a directory"};if(s.size!==t.length)return{kind:"different",reason:`local ${s.size} bytes, incoming ${t.length} bytes`};const o=await h.readFile(e);return 0===Buffer.compare(o,t)?{kind:"identical"}:{kind:"different",reason:pe(o,t)}},ue=async(e,t,s)=>{console.log(`\n${u.bold(t)}`);try{const t=await h.readFile(e);if(t.length>ce||s.length>ce||H(t)||H(s))return void console.log(u.dim(`(no preview: ${pe(t,s)})`));console.log(K(t.toString("utf8"),s.toString("utf8")))}catch(o){r(o),console.log(u.dim("(no preview available)"))}},he=async e=>{const{choice:t}=await w.prompt([{type:"expand",name:"choice",message:`Overwrite ${e}?`,default:"y",choices:[{key:"y",name:"yes (overwrite this file)",value:"yes"},{key:"n",name:"no (keep local version)",value:"no"},{key:"a",name:"overwrite all remaining differing files",value:"all"},{key:"s",name:"skip all remaining differing files",value:"skip"}]}]);return t},me=async(e,t)=>{const s=t?u.yellow(" (has local changes!)"):"",{choice:o}=await w.prompt([{type:"expand",name:"choice",message:`Delete ${e}? It no longer exists in the application.${s}`,default:"y",choices:[{key:"y",name:"yes (delete this file)",value:"yes"},{key:"n",name:"no (keep this file)",value:"no"},{key:"a",name:"delete all remaining removed files",value:"all"},{key:"s",name:"keep all remaining removed files",value:"skip"}]}]);return o},fe=async(e,t)=>{let s=m.dirname(e);const o=m.resolve(t);for(;m.resolve(s)!==o;)try{if((await h.readdir(s)).length>0)return;await h.rmdir(s),s=m.dirname(s)}catch{return}},ge=(e,t)=>m.resolve(e)===m.resolve(t)?"Application is successfully pulled.":`Application is successfully pulled into ${m.relative(t,e)}.`,ye=class{async execute(e={}){t("Pull flow started");const n=await p();if(!n)return;const a=process.cwd();let i;if(e.folder)i=e.folder.trim()||".",t(`Folder argument provided: ${i}`);else{t("No folder argument, prompting user");const{folder:e}=await w.prompt([{type:"input",name:"folder",message:"Which folder to pull the application to?",default:"."}]);i=e.trim()||"."}const c=m.resolve(a,i);t(`Target folder resolved: ${c}`);try{const e=await h.lstat(c).catch(()=>null);e&&!e.isDirectory()&&(console.error(u.red(`Cannot pull into ${c}: path exists and is not a directory.`)),process.exit(1)),await h.ensureDir(c),t(`Target folder ensured: ${c}`)}catch(f){r(f);const e=f instanceof Error?f.message:"Unknown error";console.error(u.red(`Cannot create folder ${c}: ${e}`)),process.exit(1)}const l=m.join($.tmpdir(),`dashnex-pull-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),d=D();d.start("Analyzing local files...");try{const s=await ae(c),o=await re(c,{includeGenerated:!0});t(`Local manifest has ${Object.keys(o).length} files`),d.text("Pulling application...");const i=await this.download(n.token,o);d.text("Downloading..."),await h.writeFile(l,i.buffer),t(`Zip written to temp file (${i.viaV2?"v2 diff":"legacy full"} pull)`),d.text("Extracting...");const p=new v(l).getEntries().filter(e=>!e.isDirectory);let g=null;const y=p.find(e=>".dashnex/pull.json"===e.entryName);if(y)try{g=JSON.parse(y.getData().toString("utf8"))}catch(f){r(f)}const w=p.filter(e=>".dashnex"!==e.entryName&&!e.entryName.startsWith(".dashnex/"));t(`Zip has ${w.length} file entries${g?`, meta commit ${g.commit}`:", no meta"}`);const $=e.yes||"1"===process.env.DASHNEX_CI;let k=$?"all":"prompt",b=!1,x=0,S=0,E=0,C=0,P=0;const D=async(e,t,s)=>{try{return await h.ensureDir(m.dirname(e)),await h.writeFile(e,t),s&&await h.chmod(e,s),!0}catch(f){return r(f),!1}};for(const e of w){const s=e.getData(),o=m.join(c,e.entryName),n=m.relative(c,o)||e.entryName,r=(e.header.attr??0)>>16&4095,a=await de(o,s);if(t(`Entry ${e.entryName}: ${a.kind}${a.reason?` (${a.reason})`:""}`),"identical"===a.kind){C+=1;continue}if("new"===a.kind){await D(o,s,r)?x+=1:P+=1;continue}let i=!1;if("all"===k)i=!0;else if("none"===k)i=!1;else{d.stop(),await ue(o,n,s),b||(console.log(u.dim("Y = yes (default), n = skip, a = overwrite all, s = skip all, h = help")),b=!0);const r=await he(n);t(`Entry ${e.entryName}: user chose ${r}`),"yes"===r?i=!0:"no"===r?i=!1:"all"===r?(k="all",i=!0):(k="none",i=!1),d.start("Extracting...")}i?await D(o,s,r)?S+=1:P+=1:E+=1}d.stop();let T=0,A=0;if(g&&g.deleted.length>0){const e=await this.applyDeletions(c,g.deleted,s,$);T=e.deleted,A=e.kept}g&&(C+=Math.max(0,Object.keys(g.manifest).length-w.length)),t(`Pull summary: ${x} new, ${S} overwritten, ${E} skipped, ${T} deleted, ${C} unchanged, ${P} failed`);const j=[`${x} new`,`${S} overwritten`,`${E} skipped`,`${C} unchanged`];if((T>0||A>0)&&j.splice(3,0,`${T} deleted`),P>0&&j.push(`${P} failed`),console.log(u.cyan(`Pulled: ${j.join(", ")}`)),g){const e=await re(c,{includeGenerated:!0});await ie(c,g.commit,e)}m.resolve(c)!==m.resolve(a)?(console.log(u.green(ge(c,a))),process.chdir(c),t(`Changed working directory to ${c}`)):console.log(u.green(ge(c,a))),P>0&&(console.error(u.red(`${P} file(s) failed to write. See DEBUG output for details.`)),process.exit(1)),$?t("Non-interactive mode (--yes or --ci), skipping post-pull child commands"):await le(c,a)}catch(f){if(d.stop(),r(f),f instanceof Error&&f.message.startsWith("EXIT:"))throw f;if(o(f))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}finally{await h.remove(l).catch(()=>{}),t("Temp zip removed")}}async download(e,s){const o=`${i()}/business/v1/cli/v2/pull`;t(`POST ${o}`);const n=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:s})});if(t(`v2 pull response: ${n.status}`),n.ok)return{buffer:Buffer.from(await n.arrayBuffer()),viaV2:!0};const r=await n.json().catch(()=>({}));var a,c;a=n.status,c=r,404===a&&"string"==typeof c.message&&c.message.startsWith("Cannot ")||this.failFromResponse(n.status,r),t("v2 pull endpoint unavailable, falling back to legacy pull");const l=`${i()}/business/v1/cli/pull`;t(`GET ${l}`);const p=await fetch(l,{headers:{Authorization:`Bearer ${e}`}});if(t(`Legacy pull response: ${p.status}`),!p.ok){const e=await p.json().catch(()=>({}));this.failFromResponse(p.status,e)}return{buffer:Buffer.from(await p.arrayBuffer()),viaV2:!1}}failFromResponse(e,t){let s="Failed to pull application.";if(401===e||403===e)s="Please run 'dashnex login' to authenticate.";else if(404===e)s="Business has no application. Run 'dashnex app create' to create one.";else{const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);e&&(s=e)}console.error(u.red(s)),process.exit(1)}async applyDeletions(e,s,o,n){let a=0,i=0;if(!o){const e=s.slice(0,20);console.log(u.yellow("These local files do not exist in the application (kept — no sync state yet):"));for(const t of e)console.log(u.yellow(` ${t}`));return s.length>e.length&&console.log(u.yellow(` … and ${s.length-e.length} more`)),{deleted:a,kept:s.length}}let c=n?"all":"prompt";for(const p of s){if(!(p in o.manifest)){t(`Deletion candidate ${p} was never synced, keeping`);continue}const s=m.join(e,p),n=await h.readFile(s).catch(()=>null);if(null===n)continue;const d=te(n)!==o.manifest[p];let u=!1;if("all"===c)u=!0;else if("none"===c)u=!1;else{const e=await me(p,d);t(`Deletion ${p}: user chose ${e}`),"yes"===e?u=!0:"no"===e?u=!1:"all"===e?(c="all",u=!0):(c="none",u=!1)}if(u)try{await h.remove(s),await fe(s,e),a+=1}catch(l){r(l),i+=1}else i+=1}return{deleted:a,kept:i}}},we=async e=>{const s=`${i()}/business/v1/agreements/payment-processing/status`;t(`GET ${s}`);const o=await fetch(s,{headers:{Authorization:`Bearer ${e}`}});if(t(`Payment agreement response: ${o.status}`),!o.ok)return!0;if((await o.json().catch(()=>({}))).hasAccepted)return!0;const n=`${await(async()=>"qa"===process.env.APPLICATION_ENV?"https://business.qa.dashnex.com":"https://business.dashnex.com")()}/money/agreement/`;return console.error(u.red(`You need to accept Master Payment Processing Agreement first by visiting this link: ${n}`)),!1},$e=async(e,s={})=>{const o=s.ciMode??!1;return!!(await we(e))&&!!(await(async(e,s)=>{const o=`${i()}/business/v1/tos/latest`;t(`GET ${o}`);const n=await fetch(o,{headers:{Authorization:`Bearer ${e}`}});if(t(`TOS latest response: ${n.status}`),n.ok)return!0;if(404!==n.status)return!0;const a=`${i()}/business/v1/tos/current`;t(`GET ${a}`);const c=await fetch(a,{headers:{Authorization:`Bearer ${e}`}});if(t(`TOS current response: ${c.status}`),!c.ok)return t("Could not fetch current TOS, skipping check"),!0;const l=await c.json().catch(()=>({})),p=l.version??"unknown";if(l.text&&(console.log(u.dim("─".repeat(60))),console.log(u.bold(`Terms of Service ${p}`)),console.log(u.dim("─".repeat(60))),console.log(l.text.replace(/<br\s*\/?>/gi,"\n").replace(/<\/p>/gi,"\n\n").replace(/<\/div>/gi,"\n").replace(/<\/li>/gi,"\n").replace(/<[^>]+>/g,"").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," ").replace(/\n{3,}/g,"\n\n").trim()),console.log(u.dim("─".repeat(60)))),s)return console.log(u.yellow(`By proceeding you accept the Terms of Service ${p}.`)),!0;const{accept:d}=await w.prompt([{type:"confirm",name:"accept",message:`By creating an application you accept the Terms of Service ${p}. Continue?`,default:!0}]);if(!d)return console.log(u.yellow("Cancelled.")),!1;try{const s=`${i()}/business/v1/tos/${l.id}/accept`;t(`POST ${s}`),await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch(h){r(h)}return!0})(e,o))},ve=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,ke=e=>new Promise(t=>setTimeout(t,e)),be=e=>e.appFullCustomDomain?e.appFullCustomDomain:e.subdomain?"qa"===(process.env.APPLICATION_ENV??"")?`https://${e.subdomain}.dashnex.dev`:`https://${e.subdomain}.dashnexcloud.com`:null,xe=3e5,Se=99,Ee=e=>new Promise(t=>setTimeout(t,e)),Ce=async(e,s,o,n)=>{const a=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${s}`,Accept:"text/event-stream"}});if(t(`SSE connection opened: ${a.status}`),!a.ok){const e=a.status;let t="Failed to start deployment.";if(401===e||403===e)t="Please run 'dashnex login' to authenticate.";else try{const e=await a.text(),s=JSON.parse(e);"string"==typeof s.error?t=s.error:"string"==typeof s.message&&(t=s.message)}catch{}throw console.error(u.red(t)),new Error(`HTTP ${e}: ${t}`)}if(!a.body)throw new Error("Response body is null");t("SSE connection established successfully"),n?.();const i=a.body.getReader();try{for await(const e of async function*(e){const t=new TextDecoder("utf-8");let s="";for(;;){const{value:o,done:n}=await e.read();if(n)break;s+=t.decode(o,{stream:!0});const r=s.split("\n");s=r.pop()||"";let a="";for(const e of r)e.startsWith("data: ")?a=e.slice(6):""===e&&a&&(yield{data:a},a="")}if(s.startsWith("data: ")){const e=s.slice(6);e&&(yield{data:e})}}(i))try{if(!e.data){t("Received empty SSE event");continue}const s=JSON.parse(e.data);t(`SSE message received: ${JSON.stringify(s)}`),o(s)}catch(c){r(c),t(`Failed to parse SSE event data: ${e.data}`)}}finally{i.releaseLock()}},Pe=class{async execute(e={}){t("Deploy flow started");const n=await p();if(!n)return;if(!1!==e.check?(t("Running pre-deploy checks"),await(new q).run(!1)||(console.error(u.red("Deploy aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):t("Skipping pre-deploy checks (--no-check)"),!(await $e(n.token,{ciMode:!0})))return;const a=`${l()}/business/v1/applications/deploy`;t(`GET ${a} (SSE)`);let i=0,c="",d=!1,h=0,m=!1;const f=D();let g=0,y=0,w=null;const $=(e,t)=>{const s=Math.round(e);f.text(`[${s}%] ${t}`)},v=()=>{k();const e=i,t=Date.now(),s=xe*((Se-e)/Se);w=setInterval(()=>{const o=Date.now()-t;let n;if(y>t){const e=Date.now()-y,t=Se-g,s=3030.3030303030305*t;n=Math.min(g+e/s*t,Se)}else n=Math.min(e+o/s*(Se-e),Se);n>i&&(i=n,$(i,c))},200)},k=()=>{w&&(clearInterval(w),w=null)};let b=!1;const x=e=>{if(m=!0,"string"==typeof e.error)return k(),f.stop(),console.error(u.red(e.error)),d=!0,void(b=!0);"string"==typeof e.message&&(c=e.message),"number"==typeof e.progress&&(g=e.progress,y=Date.now(),e.progress>i&&(i=e.progress)),"string"!=typeof e.message&&"number"!=typeof e.progress||(i>=100?(k(),f.stop(),d=!0):$(i,c))};for(;h<=5;)try{return m?$(i,c):f.start("Connecting..."),v(),await Ce(a,n.token,x,()=>{m||(f.text(`[${Math.round(i)}%] Deployment in progress...`),c="Deployment in progress...")}),k(),f.stop(),t("SSE connection closed"),b&&process.exit(1),void(d&&await this.showDeployedUrl(n.token))}catch(S){if(k(),r(S),t(`SSE connection error: ${S}`),d)return f.stop(),void(b&&process.exit(1));if(o(S))return f.stop(),void console.log(u.yellow(s));S instanceof Error&&S.message.startsWith("HTTP")&&(f.stop(),console.error(u.red("Could not complete deployment. Check your connection and try again.")),process.exit(1)),h++,h>5&&(f.stop(),console.error(u.red("Deployment failed. Maximum reconnection attempts exceeded.")),process.exit(1));const e=Math.min(1e3*Math.pow(2,h-1),3e4);t(`Connection error. Reconnecting in ${e/1e3}s... (attempt ${h}/5)`),await Ee(e)}}async showDeployedUrl(e){try{const s=`${i()}/business/v1/applications`;t(`GET ${s} (for deployed URL)`);const o=await fetch(s,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)return;const n=await o.json().catch(()=>({})),r=be({subdomain:n.subdomain,appFullCustomDomain:n.appFullCustomDomain});r&&console.log(`Application is deployed to ${u.cyan(r)}`)}catch(s){r(s)}}},De=class extends Error{},Te=class extends Error{},Ae=class extends Error{},je="/business/v1/cli/tail-token";async function Ne(e,t={}){const s=`${i()}${je}${t.debug?"?debug=1":""}`;try{await fetch(s,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})}catch{}}var Fe=["log","info","warn","error","debug"],Ie={error:4,warn:3,log:2,info:2,debug:1};function Oe(e){return"string"==typeof e&&Fe.includes(e)}function Re(e){return e.map(e=>"string"==typeof e?e:function(e){try{return JSON.stringify(e)}catch{return String(e)}}(e)).join(" ")}function Be(e){return e<10?`0${e}`:String(e)}function ze(e){const t=new Date(e);return`${Be(t.getHours())}:${Be(t.getMinutes())}:${Be(t.getSeconds())}.${s=t.getMilliseconds(),s<10?`00${s}`:s<100?`0${s}`:String(s)}`;var s}function Le(e,t){if("string"==typeof e)return e;if("object"==typeof(s=e)&&null!==s&&"string"==typeof s.name&&"string"==typeof s.message&&Object.keys(s).every(e=>"name"===e||"message"===e||"stack"===e)){const t=`${e.name}: ${e.message}`;return e.stack?`${t}\n${e.stack}`:t}var s;return C(e,{colors:t,depth:2,breakLength:120})}var Me={error:e=>u.red(e),warn:e=>u.yellow(e),debug:e=>u.dim(e),log:e=>e,info:e=>e};function Ue(e,t){const s=t.color?u.dim(ze(e.ts)):ze(e.ts),o=e.level.toUpperCase().padEnd(5),n=[s,t.color?Me[e.level](o):o];n.push(e.args.map(e=>Le(e,t.color)).join(" "));let r=n.join(" ");if(e.truncated){const e=" …(truncated)";r+=t.color?u.dim(e):e}return r}function We(e,t,s){let o;try{o=JSON.parse(e)}catch{return{kind:"malformed",raw:e}}if("object"!=typeof o||null===o||!Oe(o.level))return{kind:"malformed",raw:e};const n=o;return Array.isArray(n.args)||(n.args=void 0===n.args?[]:[n.args]),r=n.level,a=t.minLevel,Ie[r]>=Ie[a]&&function(e,t){return!t||t.test(Re(e.args))}(n,t.filter)?{kind:"line",line:Ue(n,s)}:{kind:"filtered"};var r,a}var Je=new Set([4401,4403]);var Ge={name:"app",description:"Manage DashNex applications (should be executed in application folder)",handler:{execute:async()=>{}},options:[],subcommands:[{name:"create",description:"Create a new DashNex application",handler:new class{async pollApplicationCreated(e,s,o=5e3,n=6e4){const a=Date.now();let i=0;for(;Date.now()-a<n;){i++,t(`Polling application status (attempt ${i})...`);try{const o=await fetch(e,{headers:{Authorization:`Bearer ${s}`}});if(t(`Poll response: ${o.status}`),200===o.status){const e=await o.json();if(t(`Poll response body status: ${e.status}`),"creating"!==e.status)return t(`Application status is "${e.status}", creation complete`),{ready:!0,status:e.status};t('Application status is still "creating", continuing to poll...')}}catch(c){r(c),t(`Poll attempt ${i} failed with network error`)}await ke(o)}return{ready:!1}}async execute(e={}){t("Create flow started");const n=await p();if(!n)return;t("Auth valid, checking if business already has application");const a=D(),c=`${i()}/business/v1/applications`;t(`GET ${c}`),a.start("Checking application status...");try{const e=await fetch(c,{headers:{Authorization:`Bearer ${n.token}`}});a.stop(),t(`Applications response: ${e.status}`),t(`Applications response body: ${await e.text()}`),404!==e.status&&(console.error(u.red("Business already has an application. Run 'dashnex app pull' to pull the existing one.")),process.exit(1))}catch($){if(a.stop(),r($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(o($))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}t("No existing application, checking agreements");const l=void 0!==e.subdomain;if(!(await $e(n.token,{ciMode:l})))return;let d;t("Agreements checked, proceeding to subdomain prompt");const h=e=>`${i()}/business/v1/applications/check-subdomain?subdomain=${encodeURIComponent(e)}`;let m=e.subdomain?.trim();for(;;){if(m)d=m,m=void 0,t(`Subdomain provided via flag: ${d}`);else{if(l)return console.error(u.red("Subdomain is not available.")),void process.exit(1);{const{sub:e}=await w.prompt([{type:"input",name:"sub",message:"Pick your subdomain:",validate:e=>!!e.trim()||"Subdomain is required"}]);d=e.trim()}}t(`Checking subdomain: ${d}`);const e=h(d);t(`GET ${e}`),a.start("Checking subdomain...");try{const s=await fetch(e,{headers:{Authorization:`Bearer ${n.token}`}});a.stop(),t(`Check subdomain response: ${s.status}`);const o=await s.text();if(t(`Check subdomain response body: ${o}`),!s.ok){const e=s.headers.get("content-type")??"";let n="Failed to check subdomain availability.";if(401!==s.status&&403!==s.status||(n="Please run 'dashnex login' to authenticate.",console.error(u.red(n)),process.exit(1)),e.includes("application/json")){const e=JSON.parse(o);t(`Check subdomain error body: ${JSON.stringify(e)}`);const s=ve(e);s&&(n=s)}console.error(u.red(n));continue}const r=JSON.parse(o);if(t(`Check subdomain parsed body: ${JSON.stringify(r)}`),r.available){t(`Subdomain ${d} is available`);break}console.error(u.red("Subdomain is not available. Please choose a different one."))}catch($){if(a.stop(),r($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(o($))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}const f=`${i()}/business/v1/cli/create`;t(`POST ${f}`);const g={subdomain:d};e.template&&(g.template=e.template,t(`Template: ${e.template}`));const y=JSON.stringify(g);t(`Create request body: ${y}`),a.start("Creating application...");try{const c=await fetch(f,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:y});a.stop(),t(`Create response: ${c.status}`);const p=await c.text();if(t(`Create response body: ${p}`),503===c.status){t("Create returned 503, polling for application creation..."),a.start("Waiting for application to be ready...");const e=`${i()}/business/v1/applications`,s=await this.pollApplicationCreated(e,n.token);a.stop(),s.ready||(console.error(u.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(u.red("Application creation failed. Please try again.")),process.exit(1)),t("Application found after polling")}else if(!c.ok){const e=c.headers.get("content-type")??"";let s="Failed to create application.";if(401===c.status||403===c.status)s="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=JSON.parse(p);t(`Create error body parsed: ${JSON.stringify(e)}`);const o=ve(e);o&&(s=o)}console.error(u.red(s)),process.exit(1)}let d;if(t("Application created successfully"),!0===e.pull?(d=!0,t("--pull flag set, pulling without prompting")):!1===e.pull?(d=!1,t("--no-pull flag set, skipping pull")):l?(d=!1,t("CI mode (--subdomain), skipping pull")):(d=(await w.prompt([{type:"confirm",name:"pull",message:"Pull the application locally?",default:!0}])).pull,t(`User chose to pull: ${d}`)),d){t("Running pull flow");try{await(new ye).execute()}catch($){if(r($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(o($))return void console.log(u.yellow(s));console.error(u.red("Failed to pull application."))}}else console.log(u.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(a.stop(),r($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(o($))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[{flags:"-t, --template <template>",description:"Template (name@branch-or-tag)",defaultValue:"webapp-base@live"},{flags:"--subdomain <subdomain>",description:"Subdomain (CI mode, skip prompts)"},{flags:"--pull",description:"Auto-pull after creation (skip prompt)"},{flags:"--no-pull",description:"Skip the pull prompt and show the success message"}]},{name:"pull",description:"Pull existing application to specified folder",handler:new ye,arguments:[{name:"folder",description:"Target folder (defaults to interactive prompt)"}],options:[{flags:"-y, --yes",description:"Skip prompts and child commands (CI mode)"}]},{name:"push",description:"Push local application to DashNex",handler:new class{async execute(e={}){t("Push flow started"),!1!==e.check?(t("Running pre-push checks"),await(new q).run(!1)||(console.error(u.red("Push aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):t("Skipping pre-push checks (--no-check)");const n=await p();if(!n)return;const a=process.cwd(),i=D();try{i.start("Analyzing local files...");const s=await ae(a),o=await re(a);t(`Local manifest has ${Object.keys(o).length} files`),i.text("Comparing with remote...");const r=await this.requestPlan(n.token,o,s?.commit);i.stop(),"legacy"===r?(t("v2 push endpoints unavailable, falling back to legacy zip push"),await this.pushLegacy(n.token,a,i)):await this.pushDiff(n.token,a,o,r,e,i),await this.promptAndDeploy(e)}catch(c){if(i.stop(),r(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(o(c))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}async requestPlan(e,s,o){const n=`${i()}/business/v1/cli/v2/push/plan`;t(`POST ${n}`);const r=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:s,lastSyncCommit:o})});if(t(`Plan response: ${r.status}`),r.ok)return await r.json();const a=await r.json().catch(()=>({}));if(((e,t)=>404===e&&"string"==typeof t.message&&t.message.startsWith("Cannot "))(r.status,a))return"legacy";this.failFromResponse(r.status,a,"Failed to push application.")}async pushDiff(e,s,o,n,r,a){let i=n;if(i.remoteChanged.length>0&&!r.force){console.error(u.red("Remote application has changes you don't have locally:"));for(const e of i.remoteChanged.slice(0,20))console.error(u.red(` ${e}`));i.remoteChanged.length>20&&console.error(u.red(` … and ${i.remoteChanged.length-20} more`)),console.error(u.red("Run 'dashnex app pull' first, or push anyway with --force.")),process.exit(1)}const c=i.upload.filter(e=>e in o);let l=i.delete;if(0!==c.length||0!==l.length){if(l.length>0){const e=await ae(s),o=r.yes||"1"===process.env.DASHNEX_CI;console.log(u.yellow(`${l.length} file(s) will be deleted from the application repository:`));for(const t of l.slice(0,20))console.log(u.yellow(` ${t}`));if(l.length>20&&console.log(u.yellow(` … and ${l.length-20} more`)),!o){const{confirmDelete:s}=await w.prompt([{type:"confirm",name:"confirmDelete",message:"Delete these files from the remote repository?",default:null!==e}]);s||(t("User declined remote deletions, pushing without them"),l=[])}}if(0!==c.length||0!==l.length)for(let n=1;;n+=1){a.start(1===n?"Uploading changes...":"Remote changed, retrying...");const p=await this.applyPush(e,s,c,l,i.baseCommit);if(a.stop(),"ok"===p.status){await ie(s,p.commit,o);const e=[`${c.length} file(s) updated`];return l.length>0&&e.push(`${l.length} deleted`),console.log(u.cyan(`Pushed: ${e.join(", ")}`)),void console.log(u.green("Application pushed successfully."))}n>=2&&(console.error(u.red("Remote repository keeps changing, please retry the push.")),process.exit(1)),t("Push apply conflicted, re-planning");const d=await ae(s),h=await this.requestPlan(e,o,d?.commit);"legacy"===h&&(console.error(u.red("Failed to push application.")),process.exit(1)),h.remoteChanged.length>0&&!r.force&&(console.error(u.red("Remote application changed during the push. Run 'dashnex app pull' first, or push with --force.")),process.exit(1)),i=h}else console.log(u.green("Everything up to date."))}else console.log(u.green("Everything up to date."))}async applyPush(e,s,o,n,r){const a=new v;for(const t of o){const e=m.join(s,...t.split("/")),o=m.posix.dirname(t);a.addLocalFile(e,"."===o?"":o,m.posix.basename(t))}const c=m.join($.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{a.writeZip(c),t(`Diff zip written to ${c} (${o.length} files, ${n.length} deletions)`);const s=`${i()}/business/v1/cli/v2/push/apply`;t(`POST ${s}`);const l=await h.readFile(c),p=new FormData;p.append("file",new Blob([l],{type:"application/zip"}),"diff.zip"),p.append("baseCommit",r),p.append("deletions",JSON.stringify(n));const d=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:p});if(t(`Apply response: ${d.status}`),409===d.status)return{status:"conflict"};if(!d.ok){const e=await d.json().catch(()=>({}));this.failFromResponse(d.status,e,"Failed to push application.")}return{status:"ok",commit:(await d.json().catch(()=>({}))).commit??""}}finally{await h.remove(c).catch(()=>{})}}async pushLegacy(e,s,o){const n=await re(s),r=Object.keys(n);t(`Legacy push including ${r.length} files`);const a=new v;for(const t of r){const e=m.join(s,...t.split("/")),o=m.posix.dirname(t);a.addLocalFile(e,"."===o?"":o,m.posix.basename(t))}const c=m.join($.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{o.start("Packaging application..."),a.writeZip(c),t(`Zip written to ${c}`);const s=`${i()}/business/v1/cli/push`;t(`POST ${s}`);const n=await h.readFile(c),r=new FormData;r.append("file",new Blob([n],{type:"application/zip"}),"archive.zip"),o.text("Uploading...");const l=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:r});if(o.stop(),t(`Response: ${l.status}`),!l.ok){const e=await l.json().catch(()=>({}));this.failFromResponse(l.status,e,"Failed to push application.")}console.log(u.green("Application pushed successfully."))}finally{await h.remove(c).catch(()=>{}),t("Temp zip removed")}}failFromResponse(e,t,s){let o=s;if(401===e||403===e)o="Please run 'dashnex login' to authenticate.";else{const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);e&&(o=e)}console.error(u.red(o)),process.exit(1)}async promptAndDeploy(e){let s;void 0!==e.deploy?(s=e.deploy,t(`Deploy decided via flag: ${s}`)):"1"===process.env.DASHNEX_CI?(s=!1,t("CI mode: skipping deploy prompt (use --deploy to deploy)")):(s=(await w.prompt([{type:"confirm",name:"deploy",message:"Deploy the application?",default:!0}])).deploy,t(`User chose to deploy: ${s}`)),s&&(t("Running deploy flow"),await(new Pe).execute())}},options:[{flags:"--deploy",description:"Auto-deploy after push (skip prompt)"},{flags:"--no-deploy",description:"Skip deploy prompt"},{flags:"--no-check",description:"Skip pre-push checks"},{flags:"-f, --force",description:"Push even when the remote has changes you don't have locally"},{flags:"-y, --yes",description:"Skip prompts (CI mode)"}]},{name:"delete",description:"Delete application from DashNex",handler:new class{async execute(e={}){if(t("Delete flow started"),!e.yes){const{confirm:e}=await w.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to delete this application? This action cannot be undone.",default:!1}]);if(!e)return t("User cancelled deletion"),void console.log(u.yellow("Deletion cancelled."))}const n=await p();if(!n)return;const a=`${i()}/business/v1/applications`;t(`DELETE ${a}`);const c=D();c.start("Deleting application...");try{const e=await fetch(a,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}});if(c.stop(),t(`Response: ${e.status}`),!e.ok){const t=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(t.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(u.red(s)),process.exit(1)}const s=await e.json().catch(()=>({})),o="string"==typeof s.message?s.message:"Application deleted successfully.";t("Application deleted successfully"),console.log(u.green(o))}catch(l){if(c.stop(),r(l),l instanceof Error&&l.message.startsWith("EXIT:"))throw l;if(o(l))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[{flags:"-y, --yes",description:"Skip confirmation prompt"}]},{name:"deploy",description:"Deploy application to DashNex",handler:new Pe,options:[{flags:"--no-check",description:"Skip pre-deploy checks"}]},{name:"status",description:"Show current application status",handler:new class{async execute(){t("Status flow started");const e=await p();if(!e)return;const n=`${i()}/business/v1/applications`;t(`GET ${n}`);const a=D();a.start("Fetching application status...");try{const s=await fetch(n,{headers:{Authorization:`Bearer ${e.token}`}});if(a.stop(),t(`Response: ${s.status}`),404===s.status)return void console.log(u.yellow("Application not created"));if(!s.ok){const e=s.headers.get("content-type")??"";let t="Failed to fetch application status.";if(401===s.status||403===s.status)t="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=await s.json().catch(()=>({}));"string"==typeof e.error?t=e.error:"string"==typeof e.message&&(t=e.message)}console.error(u.red(t)),process.exit(1)}const o=await s.json().catch(()=>({}));t(`Application body: ${JSON.stringify(o)}`);const r=o.status??"unknown";console.log(`Status: ${u.cyan(r)}`);const i=be(o);i&&console.log(`URL: ${u.cyan(i)}`)}catch(c){if(a.stop(),r(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(o(c))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]},{name:"tail",description:"Stream live console/debug logs from the deployed worker (Ctrl+C to stop)",handler:new class{async execute(e={}){const s=e.level??"log";Oe(s)||(console.error(u.red(`Invalid --level '${e.level}'. Use one of: log, info, warn, error, debug.`)),process.exit(1));let o=null;if(e.filter)try{o=new RegExp(e.filter)}catch{console.error(u.red(`Invalid --filter regular expression: ${e.filter}`)),process.exit(1)}const n=await p();if(!n)return;const a=!!e.debug;let c;try{c=await async function(e,s={}){const o=`${i()}${je}`;t(`POST ${o}${s.debug?" (debug)":""}`);const n=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({debug:!!s.debug})});if(t(`Response: ${n.status}`),401===n.status||403===n.status)throw new De("Not authorised to tail this application.");if(404===n.status)throw new Te("Business has no application, or the tail endpoint is unavailable.");if(!n.ok)throw new Ae(`Failed to start tail (status ${n.status}).`);const r=await n.json().catch(()=>({}));if(!r.token||!r.workerUrl)throw new Ae("Malformed tail-token response from the platform.");return{token:r.token,workerUrl:r.workerUrl,expiresAt:"number"==typeof r.expiresAt?r.expiresAt:0}}(n.token,{debug:a})}catch(k){r(k),k instanceof De&&(console.error(u.red(k.message)),process.exit(1)),k instanceof Te&&(console.error(u.red(k.message)),process.exit(2)),console.error(u.red(k instanceof Error?k.message:"Could not start tail. Check your connection.")),process.exit(3)}const l={color:!!process.stdout.isTTY},d={minLevel:s,filter:o},h=(m=c.workerUrl,`${/^(localhost|127\.0\.0\.1)/.test(m)?"ws":"wss"}://${m}/api/realtime/tail`);var m;const f=`dashnex.tail.token.${c.token}`;console.log(u.dim(`Tailing ${c.workerUrl} — Ctrl+C to stop.`)),a&&console.log(u.dim("Debug logging enabled on the worker (DEBUG=1); may take a minute to take effect."));let g=!1,y=Date.now();const w=setInterval(()=>{g||Date.now()-y>=3e4&&(console.log(u.dim("(no logs in 30s)")),y=Date.now())},5e3),$=new S(h,f,{WebSocket:E,connectionTimeout:1e4,maxReconnectionDelay:16e3}),v=async e=>{if(!g){g=!0,clearInterval(w);try{$.close()}catch{}await Promise.race([Ne(n.token,{debug:a}),new Promise(e=>setTimeout(e,3e3))]),process.exit(e)}};process.on("SIGINT",()=>{console.log(),v(0)}),$.binaryType="arraybuffer",$.addEventListener("message",e=>{y=Date.now();const t=We("string"==typeof e.data?e.data:"",d,l);"line"===t.kind?console.log(t.line):"malformed"===t.kind&&console.error(u.dim(`[malformed frame] ${t.raw}`))}),$.addEventListener("close",e=>{if(!g)return Je.has(e.code)?(console.error(u.red("Tail token was rejected (auth). Exiting.")),void v(1)):void t(`socket closed (code ${e.code}); reconnecting…`)}),$.addEventListener("error",e=>{t(`socket error: ${e.message??"unknown"}`)}),await new Promise(()=>{})}},options:[{flags:"--level <level>",description:"Minimum level: log, info, warn, error, debug"},{flags:"--filter <regex>",description:"Only show records whose args match this regex"},{flags:"--debug",description:"Also enable DEBUG=1 on the worker so debug-gated logs are shown"}]}]},_e={name:"secrets",description:"Manage DashNex secrets",handler:{execute:async()=>{}},options:[],subcommands:[{name:"list",description:"List all secret names bound to the worker",handler:new class{async execute(){t("Secrets list flow started");const e=await p();if(!e)return;const n=`${i()}/business/v1/cli/secrets`;t(`GET ${n}`);const a=D();a.start("Fetching secrets...");try{const s=await fetch(n,{headers:{Authorization:`Bearer ${e.token}`}});if(a.stop(),t(`Response: ${s.status}`),!s.ok){let e="Failed to fetch secrets.";401===s.status||403===s.status?e="Please run 'dashnex login' to authenticate.":404===s.status?e="Business has no application.":502===s.status&&(e="Error fetching secrets. Make sure your application is deployed."),console.error(u.red(e)),process.exit(1)}const o=(await s.json()).secrets??[];if(0===o.length)return void console.log(u.yellow("No secrets set."));console.log(u.bold(`\nSecrets (${o.length}):\n`)),o.forEach(({name:e})=>{console.log(` ${u.cyan(e)}`)}),console.log("")}catch(c){if(a.stop(),r(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(o(c))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]},{name:"set",description:"Create or update a secret (prompts for missing KEY/VALUE)",handler:new class{async execute(e={}){t("Secrets set flow started");let{name:n,value:a}=e;const c="1"===process.env.DASHNEX_CI;n||(c&&(console.error(u.red("--name is required in CI mode (--ci).")),process.exit(1)),n=(await w.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim()),a||(c&&(console.error(u.red("--value is required in CI mode (--ci).")),process.exit(1)),a=(await w.prompt([{type:"password",name:"value",message:`Enter value for ${n}:`,mask:"*",validate:e=>""!==e||"Value is required"}])).value);const l=await p();if(!l)return;const d=`${i()}/business/v1/cli/secrets`;t(`PUT ${d}`);const h=D();h.start(`Setting secret '${n}'...`);try{const e=await fetch(d,{method:"PUT",headers:{Authorization:`Bearer ${l.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:n,value:a})});if(h.stop(),t(`Response: ${e.status}`),!e.ok){let t="Failed to set secret.";401===e.status||403===e.status?t="Please run 'dashnex login' to authenticate.":400===e.status?t="Missing or empty name / value.":404===e.status?t="Business has no application.":502===e.status&&(t="Error setting secret. Make sure your application is deployed."),console.error(u.red(t)),process.exit(1)}t(`Secret '${n}' set successfully`),console.log(u.green(`Secret '${n}' set successfully.`))}catch(m){if(h.stop(),r(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(o(m))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},arguments:[{name:"name",description:"Secret name (KEY)"},{name:"value",description:"Secret value"}],options:[{flags:"--name <name>",description:"Secret name (alternative to positional KEY)"},{flags:"--value <value>",description:"Secret value (alternative to positional VALUE)"}]},{name:"delete",description:"Delete a secret (prompts for missing KEY)",handler:new class{async execute(e={}){t("Secrets delete flow started");let{name:n}=e;const a="1"===process.env.DASHNEX_CI;n||(a&&(console.error(u.red("--name is required in CI mode (--ci).")),process.exit(1)),n=(await w.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim());const c=await p();if(!c)return;const l=`${i()}/business/v1/cli/secrets/${encodeURIComponent(n)}`;t(`DELETE ${l}`);const d=D();d.start(`Deleting secret '${n}'...`);try{const e=await fetch(l,{method:"DELETE",headers:{Authorization:`Bearer ${c.token}`}});if(d.stop(),t(`Response: ${e.status}`),!e.ok){let t="Failed to delete secret.";401===e.status||403===e.status?t="Please run 'dashnex login' to authenticate.":404===e.status?t=`Secret '${n}' not found.`:502===e.status&&(t="Error deleting secret. Make sure your application is deployed."),console.error(u.red(t)),process.exit(1)}t(`Secret '${n}' deleted successfully`),console.log(u.green(`Secret '${n}' deleted.`))}catch(h){if(d.stop(),r(h),h instanceof Error&&h.message.startsWith("EXIT:"))throw h;if(o(h))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},arguments:[{name:"name",description:"Secret name (KEY)"}],options:[{flags:"--name <name>",description:"Secret name (alternative to positional KEY)"}]}]},qe=[{name:"version",description:"Display the version of the CLI",handler:new class{async execute(e){const t=m.dirname(f(import.meta.url)),s=JSON.parse(y.readFileSync(m.resolve(t,"..","..","package.json"),"utf8"));console.log(s.version)}},options:[]},{name:"login",description:"Log in to your DashNex account",handler:new class{async execute(a={}){t("Login flow started");const i=c(process.cwd()),l=await p({exitOnFailure:!1,dashnexPath:i});if(l)console.log(u.green(`Already logged in as ${l.userName??"user"}`));else try{let s,o;if(a.email)s=a.email.trim(),t("Email provided via flag");else{const{username:e}=await w.prompt([{type:"input",name:"username",message:"Email:",validate:e=>!!e.trim()||"Email is required"}]);s=e.trim()}if(a.password)o=a.password,t("Password provided via flag");else{const{password:e}=await w.prompt([{type:"password",name:"password",message:"Password:",mask:"*",validate:e=>!!e||"Password is required"}]);o=e}t("Email provided");const c=D();c.start("Logging in..."),t(`POST ${e()}/auth/v1/login`);const{response:l,body:p}=await n(`${e()}/auth/v1/login`,{method:"POST",body:JSON.stringify({username:s,password:o})});c.stop(),t(`Response: ${l.status}`),d("Login response",p),l.ok||(r(/* @__PURE__ */new Error(`Login failed: ${l.status} ${JSON.stringify(p)}`)),401===l.status&&(console.error(u.red("Invalid username or password.")),process.exit(1)),T(l,p,"Login failed. Please try again."));const h=p;if(h.two_fa_required&&h.token){t(`2FA required, type: ${h.type||"unknown"}`);const e=await this.handle2FA(h.token,h.type,a.code);e||process.exit(1),await this.completeLogin(e,i,a.business)}else h.token&&h.refreshToken?await this.completeLogin({token:h.token,refreshToken:h.refreshToken},i,a.business):(console.error(u.red("Invalid response from server. Please try again.")),process.exit(1))}catch(h){if(r(h),o(h))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}async handle2FA(a,i,c){if("sms"===i){t(`POST ${e()}/auth/v1/two-fa/sms`);try{const{response:s}=await n(`${e()}/auth/v1/two-fa/sms`,{method:"POST",headers:{Authorization:`Bearer ${a}`},body:JSON.stringify({})});t(`Response: ${s.status}`)}catch(h){return r(h),console.error(u.red("Could not send SMS code. Check your connection and try again.")),null}}const l="sms"===i?"Check your phone for the code":"Check your authenticator app for the code",p=c?1:3;for(let m=1;m<=p;m++){let i;c&&1===m?(i=c,t("2FA code provided via flag")):i=(await w.prompt([{type:"input",name:"auth_code",message:`Enter code (${l}):`,validate:e=>!!e.trim()||"Code is required"}])).auth_code,t(`POST ${e()}/auth/v1/2fa-check`);try{const{response:s,body:o}=await n(`${e()}/auth/v1/2fa-check`,{method:"POST",headers:{Authorization:`Bearer ${a}`},body:JSON.stringify({auth_code:i.trim()})});if(t(`Response: ${s.status}`),d("2FA check response",o),s.ok){const e=o;if(e.token&&e.refreshToken)return{token:e.token,refreshToken:e.refreshToken}}if(s.status>=400&&s.status<500){if(console.error(u.red("Invalid code. Please try again.")),m<p){const{retry:e}=await w.prompt([{type:"confirm",name:"retry",message:"Try again?",default:!0}]);if(!e)return null}continue}T(s,o,"2FA verification failed. Please try again.")}catch(h){return r(h),o(h)?(console.log(u.yellow(s)),null):(console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),null)}}return null}async completeLogin(s,o,a){const c=D();c.start("Fetching businesses...");const l=e(),p={Authorization:`Bearer ${s.token}`};t(`GET ${l}/users/v1/business/my`);const{response:f,body:g}=await n(`${l}/users/v1/business/my`,{headers:p});t(`Response: ${f.status}`),d("Businesses response",g),f.ok||(c.stop(),r(/* @__PURE__ */new Error(`Business fetch failed: ${f.status}`)),T(f,g,"Failed to fetch businesses. Please try again."));const y=this.parseBusinesses(g),$=await this.fetchOtherBusinesses(s.token),v=this.mergeBusinesses(y,$);let k;if(c.stop(),t(`Businesses (my: ${y.length}, other: ${$.length}, merged: ${v.length})`),0===v.length&&(console.error(u.red("No businesses or teams found for your account!")),console.log(u.green("Create your first business at https://dashnex.io")),process.exit(1)),a){const e=v.find(e=>e.id===a);e||(console.error(u.red(`Business "${a}" not found.`)),process.exit(1)),k=e,t(`Selected business via flag: ${k.id} ${k.name}`)}else if(1===v.length)k=v[0],t(`Selected business: ${k.id} ${k.name}`);else{const{businessId:e}=await w.prompt([{type:"select",name:"businessId",message:"Select business:",choices:v.map(e=>({name:e.name,value:e.id}))}]);k=v.find(t=>t.id===e)||v[0],t(`Selected business: ${k.id} ${k.name}`)}c.start("Switching business..."),t(`GET ${l}/business/v1/login?_switch_business=${k.id}`);const{response:b,body:x}=await n(`${l}/business/v1/login?_switch_business=${k.id}`,{headers:p});c.stop(),t(`Response: ${b.status}`),d("Business login response",x),b.ok||(r(/* @__PURE__ */new Error(`Business login failed: ${b.status}`)),T(b,x,"Failed to switch to business. Please try again."));const S=x;S.token&&S.refreshToken||(console.error(u.red("Invalid response from server. Please try again.")),process.exit(1));const E={token:S.token,refreshToken:S.refreshToken,businessId:k.id},C={Authorization:`Bearer ${S.token}`};try{const e=i();t(`GET ${e}/business/v1/cli/settings`);const{response:s,body:o}=await n(`${e}/business/v1/cli/settings`,{headers:C});t(`Response: ${s.status}`),d("CLI settings response",o),s.ok&&o&&"object"==typeof o&&Object.assign(E,o)}catch(A){r(A)}const P=m.dirname(o);await h.pathExists(P)&&(await h.stat(P)).isFile()&&await h.remove(P),await h.ensureDir(P),await h.writeJson(o,E,{spaces:2}),t("Saved credentials to .dashnex/settings.json"),this.ensureGitignore(),console.log(u.green(`Logged in as ${k.name}`))}async fetchOtherBusinesses(s){const o=e();let a=1;const i=[];let c=0;do{const e=`${o}/users/v1/business/other?page=${a}&perPage=100`;t(`GET ${e}`);const{response:l,body:p}=await n(e,{headers:{Authorization:`Bearer ${s}`}});l.ok||(r(/* @__PURE__ */new Error(`Other businesses fetch failed: ${l.status}`)),T(l,p,"Failed to fetch teams. Please try again."));const d=this.parseBusinesses(p),u="number"==typeof p.total?p.total:d.length;if(i.push(...d),c=u,d.length<100||i.length>=c)break;a++}while(i.length<c);return i}mergeBusinesses(e,t){const s=/* @__PURE__ */new Map;for(const o of e)s.set(o.id,o);for(const o of t)s.has(o.id)||s.set(o.id,o);return[...s.values()]}parseBusinesses(e){const t=Array.isArray(e)?e:e.items??e.data??e.businesses??[];return Array.isArray(t)?t.map(e=>{if(e&&"object"==typeof e){const t=e,s=String(t.id??t.business_id??"").trim(),o=String(t.name??t.companyName??t.business_name??"Unknown").trim();if(s)return{id:s,name:o}}return null}).filter(e=>null!==e):[]}async ensureGitignore(){const e=m.join(process.cwd(),".gitignore");if(!(await h.pathExists(e)))return;let t=await h.readFile(e,"utf8");t.includes(".dashnex")||(t=t.trimEnd(),t.endsWith("\n")||(t+="\n"),t+="\n.dashnex\n",await h.writeFile(e,t))}},options:[{flags:"--email <email>",description:"Email address (skip prompt)"},{flags:"--password <password>",description:"Password (skip prompt)"},{flags:"--code <code>",description:"2FA code (skip prompt)"},{flags:"--business <id>",description:"Business ID to select (skip prompt)"}]},{name:"logout",description:"Log out and remove local credentials",handler:new class{async execute(){const e=c(process.cwd());if(await h.pathExists(e)){const t=await h.readJson(e);delete t.token,delete t.refreshToken,delete t.businessId,await h.writeJson(e,t,{spaces:2})}console.log(u.green("Logged out."))}},options:[]},{name:"whoami",description:"Show current logged-in business and user",handler:new class{async execute(){t("Whoami flow started");const n=await p();if(!n)return;const a=`${e()}/users/v1/`;t(`GET ${a}`);const i=D();i.start("Fetching user info...");try{const e=await fetch(a,{headers:{Authorization:`Bearer ${n.token}`}});if(i.stop(),t(`Response: ${e.status}`),!e.ok){const t=e.headers.get("content-type")??"";let s="Failed to fetch user info.";if(401===e.status||403===e.status)s="Please run 'dashnex login' to authenticate.";else if(t.includes("application/json")){const t="string"==typeof(c=await e.json().catch(()=>({}))).error?c.error:"string"==typeof c.message?c.message:void 0;t&&(s=t)}console.error(u.red(s)),process.exit(1)}const s=await e.json().catch(()=>({})),o="string"==typeof s.name?s.name:"string"==typeof s.companyName?s.companyName:"Unknown",r=s.memberUser,l=r&&"string"==typeof r.fullName?r.fullName:r&&"string"==typeof r.name?r.name:"Unknown";t(`Whoami: ${o} (${l})`),console.log(u.green(`You are logged in as ${o} (${l})`))}catch(l){if(i.stop(),r(l),l instanceof Error&&l.message.startsWith("EXIT:"))throw l;if(o(l))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}var c}},options:[]},{name:"dev",description:"Run the development server (run in DashNex application folder)",handler:new class{async execute(e={}){t("Dev flow started");try{const t=await F(process.cwd(),e);process.exit(t)}catch(s){if(s instanceof Error&&s.message.startsWith("EXIT:"))throw s;r(s),s instanceof Error?console.error(u.red(s.message)):console.error(u.red("Failed to run npm run dev")),process.exit(1)}}},options:[{flags:"--https",description:"Run dev server with HTTPS"}]},{name:"check",description:"Run build-time validations (run in DashNex application folder)",handler:new q,options:[]},{name:"install",description:"Install dependencies using pnpm (preferred) or npm (run in DashNex application folder)",handler:new class{async execute(){t("Install flow started");const e=m.join(process.cwd(),"dashnex.json");await h.pathExists(e)||(console.error(u.red("Run this command in a DashNex Web application folder.")),process.exit(1));const s=process.cwd(),o=D();o.start("Installing dependencies...");try{const e=await O(s);o.stop(),0!==e&&process.exit(e),console.log(u.green("Dependencies installed.")),process.exit(0)}catch(n){o.stop(),r(n),n instanceof Error?console.error(u.red(n.message)):console.error(u.red("Failed to run install")),process.exit(1)}}},options:[]},Ge,_e];export{qe as default};
1
+ import{a as e,c as t,d as s,f as o,i as n,l as r,n as a,o as i,r as c,s as l,t as p,u as d}from"../chunks/auth-28liVZ3c.js";import u from"chalk";import h from"fs-extra";import m from"path";import{fileURLToPath as f}from"url";import{spawn as g}from"child_process";import y from"fs";import w from"inquirer";import $ from"os";import v from"adm-zip";import{diffLines as k}from"diff";import{createHash as b}from"crypto";import x from"ignore";import{WebSocket as S}from"partysocket";import E from"ws";import{inspect as C}from"node:util";var P=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],D=(e="")=>{if(process.env.DASHNEX_CI)return{start:()=>{},stop:()=>{},text:()=>{}};let t=null,s=0,o=e;const n=()=>{const e=P[s%P.length];process.stderr.write(`\r${e} ${o}`),s++};return{start:e=>{void 0!==e&&(o=e),t||(s=0,n(),t=setInterval(n,80))},stop:()=>{t&&(clearInterval(t),t=null),process.stderr.write("\r\n")},text:e=>{o=e,t&&n()}}},T=(e,t,s)=>{const o=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);let n=s;429===e.status?n="Too many requests. Please wait a moment and try again.":e.status>=500?n="DashNex API is temporarily unavailable. Please try again later.":o&&(n=o),console.error(u.red(n)),process.exit(1)},A=["Using vars defined in \\.env","\\(node:\\d+\\) MaxListenersExceededWarning:","\\(Use `node --trace-warnings","\\[WARNING\\].*You have defined bindings to the following internal Durable Objects","You have defined bindings to the following internal Durable Objects",'\\{"name":".+","class_name":".+"\\}',"These will not work in local development, but they should work in production","If you want to develop these locally, you can define your DO in a separate Worker","For detailed instructions, refer to the Durable Objects section here:","developers.cloudflare.com/workers/wrangler/api#supported-bindings","workerd/server/server\\.c\\+\\+.*warning:.*DurableObjectNamespace"],j=(e,t)=>t.length>0&&t.some(t=>t.test(e)),N=(e,s)=>{let o="";return{write:n=>{const r="string"==typeof n?n:n.toString();o+=r;const a=o.split(/\r?\n/);o=a.pop()??"";for(const o of a){const n=o.trim();n?j(n,s)?t(`Filtered: ${n}`):e.write(o+"\n"):t("Filtered: <empty line>")}},flush:()=>{const n=o.trim();if(n){if(j(n,s))return t(`Filtered: ${n}`),void(o="");e.write(o),o=""}else o=""}}},F=async(e,s={})=>{const o=m.join(e,"dashnex.json"),n=m.join(e,"package.json");if(t(`Checking for dashnex.json at: ${o}`),!(await h.pathExists(o)))throw new Error("Run this command in a DashNex Web application folder.");if(t("dashnex.json found, checking for package.json"),!(await h.pathExists(n)))throw new Error("package.json is missing.");let a;t("package.json found, checking for dev script");try{a=await h.readJson(n)}catch(l){throw r(l),new Error("Failed to read package.json.")}if(!a.scripts||!a.scripts.dev)throw new Error('The "dev" script is missing from package.json. Please add a "dev" script to package.json.');t("dev script found, checking for npm availability");const i=await(async e=>new Promise(t=>{const s=g(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>{t(!1)}),s.on("close",e=>{t(0===e)})}))("npm");if(t(`npm available: ${i}`),!i)throw new Error("npm is not available. Please install npm to continue.");const c=s.https?["--","--experimental-https"]:[];return t(`npm available, executing: npm run dev in ${e}${s.https?" -- --experimental-https":""}`),(async(e,t=[],s=process.cwd(),o=[])=>{const n=t.length?`${e} ${t.join(" ")}`:e,a=o.length>0;return new Promise((e,t)=>{const i=g(n,{stdio:a?["inherit","pipe","pipe"]:"inherit",cwd:s,shell:!0,env:{...process.env,NODE_ENV:"development",FORCE_COLOR:"1"}});if(i.on("error",e=>{r(e),t(e)}),a&&i.stdout&&i.stderr){const t=N(process.stdout,o),s=N(process.stderr,o);i.stdout.on("data",e=>t.write(e)),i.stderr.on("data",e=>s.write(e)),i.on("close",o=>{t.flush(),s.flush(),e(null===o?0:o)})}else i.on("close",t=>{e(null===t?0:t)})})})("npm run dev",c,e,(()=>{const e=[];for(const s of A)try{e.push(new RegExp(s))}catch{t(`Invalid dev output filter pattern ignored: ${s}`)}return e})())},I=async e=>new Promise(t=>{const s=g(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>{t(!1)}),s.on("close",e=>{t(0===e)})}),O=async e=>{let s;if(await I("pnpm"))s="pnpm install --config.strict-dep-builds=false",t("Using package manager: pnpm");else{if(!(await I("npm")))throw new Error("Neither pnpm nor npm is available. Install Node.js (which bundles npm) or pnpm to continue.");s="npm install --legacy-peer-deps",t("Using package manager: npm (with --legacy-peer-deps for DashNex peer-dep overlap)")}return t(`Executing: ${s} in ${e}`),new Promise((t,o)=>{const n=[],a=[],i=g(s,{stdio:["ignore","pipe","pipe"],cwd:e,shell:!0,env:{...process.env,NPM_CONFIG_LOGLEVEL:"error"}});i.stdout&&i.stdout.on("data",e=>n.push(e)),i.stderr&&i.stderr.on("data",e=>a.push(e)),i.on("error",e=>{r(e),o(e)}),i.on("close",e=>{const s=null===e?0:e;0!==s&&(n.length&&process.stdout.write(Buffer.concat(n)),a.length&&process.stderr.write(Buffer.concat(a))),t(s)})})},R="Run this command in a DashNex Web application folder.",B=e=>{const t=m.join(e,"dashnex.json");return h.pathExistsSync(t)},L=(e,t=!1)=>{t||console.log(u.cyan(e))},z=(e,s,o={})=>{const n=`${e} ${s.join(" ")}`,a=!0===o.silent;return new Promise((s,o)=>{t(`Running: ${n}`);const i=g(n,{stdio:a?["ignore","pipe","pipe"]:"inherit",cwd:process.cwd(),shell:!0});i.on("error",e=>{r(e),o(e)}),i.on("close",o=>{t(`${e} exited with code ${o}`),s(null===o?1:o)})})},M=(e,s)=>new Promise((o,n)=>{t(`Running: ${e} ${s.join(" ")}`);const a=g(e,s,{cwd:process.cwd()});let i="";a.stdout?.on("data",e=>{i+=e.toString()}),a.stderr?.on("data",e=>{i+=e.toString()}),a.on("error",e=>{r(e),n(e)}),a.on("close",s=>{t(`${e} exited with code ${s}`),o({exitCode:null===s?1:s,output:i})})}),U=async e=>{t("Running check: install");try{return 0===await O(process.cwd())}catch(s){return r(s),!e&&s instanceof Error&&console.error(u.red(s.message)),!1}},W=async()=>{try{const{output:e}=await M(process.execPath,[process.argv[1],"db","migrate","--help"]);return e.includes("Usage: dashnex db migrate")}catch(e){return r(e),!1}},J=async e=>{t("Running check: db migrate");try{const{exitCode:s,output:o}=await M(process.execPath,[process.argv[1],"db","migrate"]);return 0===s||(o.includes("Unknown command")?(t("db migrate command is not available, skipping"),!0):(!e&&o.trim().length>0&&process.stderr.write(o),!1))}catch(s){return r(s),!0}},G=e=>new Promise(t=>{const s=g(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>t(!1)),s.on("close",e=>t(0===e))}),_=[{name:"TypeScript",command:"npx",args:["tsc","--noEmit"],notFoundMessage:"TypeScript is not available. Please install it with: npm install -D typescript"}],q=class{async execute(){t("Check flow started"),B(process.cwd())||(console.error(u.red(R)),process.exit(1)),L("Checking dependencies..."),await U(!1)||(console.error(u.red("Check failed.")),process.exit(1)),t(`Running ${_.length} check(s)`);for(const s of _){t(`Running check: ${s.name}`),L(`Checking ${s.name}...`),await G(s.command)||(console.error(u.red(s.notFoundMessage)),process.exit(1));try{0!==await z(s.command,s.args)&&(console.error(u.red("Check failed.")),process.exit(1))}catch(e){r(e),console.error(u.red(s.notFoundMessage)),process.exit(1)}}await W()?(L("Checking database migrations..."),await J(!1)||(console.error(u.red("Check failed.")),process.exit(1))):t("db migrate command is not available, skipping"),console.log(u.green("All checks passed."))}async run(e=!1){if(t("Running checks (called from push)"),!B(process.cwd()))return e||console.error(u.red(R)),!1;if(L("Checking dependencies...",e),!(await U(e)))return!1;const s=e?{silent:!0}:void 0;for(const n of _){if(t(`Running check: ${n.name}`),L(`Checking ${n.name}...`,e),!(await G(n.command)))return console.error(u.red(n.notFoundMessage)),!1;try{if(0!==await z(n.command,n.args,s))return!1}catch(o){return r(o),console.error(u.red(n.notFoundMessage)),!1}}if(await W()){if(L("Checking database migrations...",e),!(await J(e)))return!1}else t("db migrate command is not available, skipping");return e||console.log(u.green("All checks passed.")),!0}},X=" │ ",H=e=>e.subarray(0,8192).includes(0),Y=e=>{const t=e.split("\n");return""===t[t.length-1]&&t.pop(),t},V=(e,t)=>{if(null===e)return" ".repeat(t);const s=e.replace(/\t/g," ");return s.length<=t?s.padEnd(t):`${s.slice(0,Math.max(0,t-1))}…`},K=(e,t,s)=>{const o=Math.max(s??process.stdout.columns??120,43),n=Math.floor((o-3)/2),r=((e,t)=>{const s=[],o=k(e,t);for(let n=0;n<o.length;n+=1){const e=o[n];if(e.removed){const t=Y(e.value),r=o[n+1],a=r?.added?Y(r.value):[];r?.added&&(n+=1);const i=Math.max(t.length,a.length);for(let e=0;e<i;e+=1)s.push({left:t[e]??null,right:a[e]??null,changed:!0})}else if(e.added)for(const t of Y(e.value))s.push({left:null,right:t,changed:!0});else for(const t of Y(e.value))s.push({left:t,right:t,changed:!1})}return s})(e,t),a=/* @__PURE__ */new Set;r.forEach((e,t)=>{if(e.changed)for(let s=Math.max(0,t-3);s<=Math.min(r.length-1,t+3);s+=1)a.add(s)});const i=[];i.push(u.bold(V("local (current)",n))+u.dim(X)+u.bold("incoming"));let c=-1,l=0,p=0;for(let d=0;d<r.length;d+=1){if(!a.has(d))continue;if(l>=200){p+=1;continue}-1!==c&&d>c+1&&i.push(u.dim("···")),c=d,l+=1;const e=r[d],t=V(e.left,n),s=V(e.right,n);if(!e.changed){i.push(u.dim(t)+u.dim(X)+u.dim(s));continue}const o=null!==e.left?u.red(t):t,h=null!==e.right?u.green(s):s;i.push(o+u.dim(X)+h)}return p>0&&i.push(u.dim(`… ${p} more diff line(s) not shown`)),i.join("\n")},Z=[".dashnex",".git",".vinext",".wrangler","wrangler.jsonc","wrangler.toml",".dev.vars",".github"],Q=[".env","wrangler.jsonc"],ee=e=>m.join(e,a,"sync.json"),te=e=>b("sha1").update(`blob ${e.length}\0`).update(e).digest("hex"),se=e=>e.split(m.sep).join("/"),oe=e=>Z.some(t=>e===t||e.startsWith(`${t}/`)),ne=async e=>{const t=await(async e=>{const t=x();t.add(Z);const s=m.join(e,".gitignore");return await h.pathExists(s)&&t.add(await h.readFile(s,"utf8")),t})(e),s=[],o=async n=>{const r=await h.readdir(n,{withFileTypes:!0});for(const a of r){const r=m.join(n,a.name),i=se(m.relative(e,r));oe(i)||t.ignores(a.isDirectory()?`${i}/`:i)||(a.isDirectory()?await o(r):a.isFile()&&s.push(i))}};return await o(e),s},re=async(e,t={})=>{const s={},o=await ne(e);for(const n of o)s[n]=te(await h.readFile(m.join(e,n)));if(t.includeGenerated)for(const n of Q){if(n in s)continue;const t=m.join(e,n);(await h.lstat(t).catch(()=>null))?.isFile()&&(s[n]=te(await h.readFile(t)))}return s},ae=async e=>{try{const t=await h.readFile(ee(e),"utf8"),s=JSON.parse(t);return"string"!=typeof s?.commit||"object"!=typeof s?.manifest||null===s.manifest?null:s}catch{return null}},ie=async(e,s,o)=>{const n={commit:s,manifest:o,updatedAt:/* @__PURE__ */(new Date).toISOString()},r=ee(e);try{await h.ensureDir(m.dirname(r)),await h.writeFile(r,`${JSON.stringify(n,null,2)}\n`),t(`Sync state written: commit ${s}, ${Object.keys(o).length} files`)}catch(a){t(`Failed to write sync state: ${a instanceof Error?a.message:"unknown"}`)}},ce=1048576,le=async(e,s)=>{const{install:o}=await w.prompt([{type:"confirm",name:"install",message:"Install dependencies?",default:!0}]);if(!o){if(m.resolve(e)!==m.resolve(s)){const t=m.relative(s,e);console.log(u.cyan(`Run "cd ${t}" to change to the application folder.`))}return}try{const s=D();s.start("Installing dependencies...");try{const o=await O(e);if(s.stop(),0!==o)return void t(`install exited with code ${o}`)}catch(i){throw s.stop(),i}}catch(i){return r(i),void console.error(u.red(i instanceof Error?i.message:"Failed to run install."))}const{migrate:n}=await w.prompt([{type:"confirm",name:"migrate",message:"Create or update database?",default:!0}]);if(!n)return;t(`Running dashnex db migrate in ${e}`);try{const s=D();s.start("Creating or updating database...");try{const o=await((e,t,s)=>{const o=`${m.join(e,"node_modules",".bin")}${m.delimiter}${process.env.PATH??""}`,n={...process.env,PATH:o};return new Promise((o,a)=>{const i=g(t,{cwd:e,shell:!0,stdio:"inherit",env:s?{...n,...s}:n});i.on("error",e=>{r(e),a(e)}),i.on("close",e=>{o(null===e?0:e)})})})(e,"dashnex db migrate");if(s.stop(),0!==o)return void t(`dashnex db migrate exited with code ${o}`)}catch(i){throw s.stop(),i}}catch(i){return r(i),void console.error(u.red("Failed to run dashnex db migrate."))}const{dev:a}=await w.prompt([{type:"confirm",name:"dev",message:"Run development server?",default:!0}]);if(a)try{await F(e)}catch(i){r(i),console.error(u.red(i instanceof Error?i.message:"Failed to run dev server."))}},pe=(e,t)=>{if(e.length!==t.length)return`local ${e.length} bytes, incoming ${t.length} bytes`;const s=e.length;for(let o=0;o<s;o+=1)if(e[o]!==t[o]){return`size ${s} matches; first diff at byte ${o} (local=0x${e[o].toString(16).padStart(2,"0")} incoming=0x${t[o].toString(16).padStart(2,"0")})`}return`size ${s} matches; no byte difference (unexpected)`},de=async(e,t)=>{let s;try{s=await h.lstat(e)}catch{return{kind:"new"}}if(s.isDirectory())return{kind:"different",reason:"target is a directory"};if(s.size!==t.length)return{kind:"different",reason:`local ${s.size} bytes, incoming ${t.length} bytes`};const o=await h.readFile(e);return 0===Buffer.compare(o,t)?{kind:"identical"}:{kind:"different",reason:pe(o,t)}},ue=async(e,t,s)=>{console.log(`\n${u.bold(t)}`);try{const t=await h.readFile(e);if(t.length>ce||s.length>ce||H(t)||H(s))return void console.log(u.dim(`(no preview: ${pe(t,s)})`));console.log(K(t.toString("utf8"),s.toString("utf8")))}catch(o){r(o),console.log(u.dim("(no preview available)"))}},he=async e=>{const{choice:t}=await w.prompt([{type:"expand",name:"choice",message:`Overwrite ${e}?`,default:"y",choices:[{key:"y",name:"yes (overwrite this file)",value:"yes"},{key:"n",name:"no (keep local version)",value:"no"},{key:"a",name:"overwrite all remaining differing files",value:"all"},{key:"s",name:"skip all remaining differing files",value:"skip"}]}]);return t},me=async(e,t)=>{const s=t?u.yellow(" (has local changes!)"):"",{choice:o}=await w.prompt([{type:"expand",name:"choice",message:`Delete ${e}? It no longer exists in the application.${s}`,default:"y",choices:[{key:"y",name:"yes (delete this file)",value:"yes"},{key:"n",name:"no (keep this file)",value:"no"},{key:"a",name:"delete all remaining removed files",value:"all"},{key:"s",name:"keep all remaining removed files",value:"skip"}]}]);return o},fe=async(e,t)=>{let s=m.dirname(e);const o=m.resolve(t);for(;m.resolve(s)!==o;)try{if((await h.readdir(s)).length>0)return;await h.rmdir(s),s=m.dirname(s)}catch{return}},ge=(e,t)=>m.resolve(e)===m.resolve(t)?"Application is successfully pulled.":`Application is successfully pulled into ${m.relative(t,e)}.`,ye=class{async execute(e={}){t("Pull flow started");const n=await p();if(!n)return;const a=process.cwd();let i;if(e.folder)i=e.folder.trim()||".",t(`Folder argument provided: ${i}`);else{t("No folder argument, prompting user");const{folder:e}=await w.prompt([{type:"input",name:"folder",message:"Which folder to pull the application to?",default:"."}]);i=e.trim()||"."}const c=m.resolve(a,i);t(`Target folder resolved: ${c}`);try{const e=await h.lstat(c).catch(()=>null);e&&!e.isDirectory()&&(console.error(u.red(`Cannot pull into ${c}: path exists and is not a directory.`)),process.exit(1)),await h.ensureDir(c),t(`Target folder ensured: ${c}`)}catch(f){r(f);const e=f instanceof Error?f.message:"Unknown error";console.error(u.red(`Cannot create folder ${c}: ${e}`)),process.exit(1)}const l=m.join($.tmpdir(),`dashnex-pull-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),d=D();d.start("Analyzing local files...");try{const s=await ae(c),o=await re(c,{includeGenerated:!0});t(`Local manifest has ${Object.keys(o).length} files`),d.text("Pulling application...");const i=await this.download(n.token,o);d.text("Downloading..."),await h.writeFile(l,i.buffer),t(`Zip written to temp file (${i.viaV2?"v2 diff":"legacy full"} pull)`),d.text("Extracting...");const p=new v(l).getEntries().filter(e=>!e.isDirectory);let g=null;const y=p.find(e=>".dashnex/pull.json"===e.entryName);if(y)try{g=JSON.parse(y.getData().toString("utf8"))}catch(f){r(f)}const w=p.filter(e=>".dashnex"!==e.entryName&&!e.entryName.startsWith(".dashnex/"));t(`Zip has ${w.length} file entries${g?`, meta commit ${g.commit}`:", no meta"}`);const $=e.yes||"1"===process.env.DASHNEX_CI;let k=$?"all":"prompt",b=!1,x=0,S=0,E=0,C=0,P=0;const D=async(e,t,s)=>{try{return await h.ensureDir(m.dirname(e)),await h.writeFile(e,t),s&&await h.chmod(e,s),!0}catch(f){return r(f),!1}};for(const e of w){const s=e.getData(),o=m.join(c,e.entryName),n=m.relative(c,o)||e.entryName,r=(e.header.attr??0)>>16&4095,a=await de(o,s);if(t(`Entry ${e.entryName}: ${a.kind}${a.reason?` (${a.reason})`:""}`),"identical"===a.kind){C+=1;continue}if("new"===a.kind){await D(o,s,r)?x+=1:P+=1;continue}let i=!1;if("all"===k)i=!0;else if("none"===k)i=!1;else{d.stop(),await ue(o,n,s),b||(console.log(u.dim("Y = yes (default), n = skip, a = overwrite all, s = skip all, h = help")),b=!0);const r=await he(n);t(`Entry ${e.entryName}: user chose ${r}`),"yes"===r?i=!0:"no"===r?i=!1:"all"===r?(k="all",i=!0):(k="none",i=!1),d.start("Extracting...")}i?await D(o,s,r)?S+=1:P+=1:E+=1}d.stop();let T=0,A=0;if(g&&g.deleted.length>0){const e=await this.applyDeletions(c,g.deleted,s,$);T=e.deleted,A=e.kept}g&&(C+=Math.max(0,Object.keys(g.manifest).length-w.length)),t(`Pull summary: ${x} new, ${S} overwritten, ${E} skipped, ${T} deleted, ${C} unchanged, ${P} failed`);const j=[`${x} new`,`${S} overwritten`,`${E} skipped`,`${C} unchanged`];if((T>0||A>0)&&j.splice(3,0,`${T} deleted`),P>0&&j.push(`${P} failed`),console.log(u.cyan(`Pulled: ${j.join(", ")}`)),g){const e=await re(c,{includeGenerated:!0});await ie(c,g.commit,e)}m.resolve(c)!==m.resolve(a)?(console.log(u.green(ge(c,a))),process.chdir(c),t(`Changed working directory to ${c}`)):console.log(u.green(ge(c,a))),P>0&&(console.error(u.red(`${P} file(s) failed to write. See DEBUG output for details.`)),process.exit(1)),$?t("Non-interactive mode (--yes or --ci), skipping post-pull child commands"):await le(c,a)}catch(f){if(d.stop(),r(f),f instanceof Error&&f.message.startsWith("EXIT:"))throw f;if(o(f))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}finally{await h.remove(l).catch(()=>{}),t("Temp zip removed")}}async download(e,s){const o=`${i()}/business/v1/cli/v2/pull`;t(`POST ${o}`);const n=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:s})});if(t(`v2 pull response: ${n.status}`),n.ok)return{buffer:Buffer.from(await n.arrayBuffer()),viaV2:!0};const r=await n.json().catch(()=>({}));var a,c;a=n.status,c=r,404===a&&"string"==typeof c.message&&c.message.startsWith("Cannot ")||this.failFromResponse(n.status,r),t("v2 pull endpoint unavailable, falling back to legacy pull");const l=`${i()}/business/v1/cli/pull`;t(`GET ${l}`);const p=await fetch(l,{headers:{Authorization:`Bearer ${e}`}});if(t(`Legacy pull response: ${p.status}`),!p.ok){const e=await p.json().catch(()=>({}));this.failFromResponse(p.status,e)}return{buffer:Buffer.from(await p.arrayBuffer()),viaV2:!1}}failFromResponse(e,t){let s="Failed to pull application.";if(401===e||403===e)s="Please run 'dashnex login' to authenticate.";else if(404===e)s="Business has no application. Run 'dashnex app create' to create one.";else{const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);e&&(s=e)}console.error(u.red(s)),process.exit(1)}async applyDeletions(e,s,o,n){let a=0,i=0;if(!o){const e=s.slice(0,20);console.log(u.yellow("These local files do not exist in the application (kept — no sync state yet):"));for(const t of e)console.log(u.yellow(` ${t}`));return s.length>e.length&&console.log(u.yellow(` … and ${s.length-e.length} more`)),{deleted:a,kept:s.length}}let c=n?"all":"prompt";for(const p of s){if(!(p in o.manifest)){t(`Deletion candidate ${p} was never synced, keeping`);continue}const s=m.join(e,p),n=await h.readFile(s).catch(()=>null);if(null===n)continue;const d=te(n)!==o.manifest[p];let u=!1;if("all"===c)u=!0;else if("none"===c)u=!1;else{const e=await me(p,d);t(`Deletion ${p}: user chose ${e}`),"yes"===e?u=!0:"no"===e?u=!1:"all"===e?(c="all",u=!0):(c="none",u=!1)}if(u)try{await h.remove(s),await fe(s,e),a+=1}catch(l){r(l),i+=1}else i+=1}return{deleted:a,kept:i}}},we=async e=>{const s=`${i()}/business/v1/agreements/payment-processing/status`;t(`GET ${s}`);const o=await fetch(s,{headers:{Authorization:`Bearer ${e}`}});if(t(`Payment agreement response: ${o.status}`),!o.ok)return!0;if((await o.json().catch(()=>({}))).hasAccepted)return!0;const n=`${await(async()=>"qa"===process.env.APPLICATION_ENV?"https://business.qa.dashnex.com":"https://business.dashnex.com")()}/money/agreement/`;return console.error(u.red(`You need to accept Master Payment Processing Agreement first by visiting this link: ${n}`)),!1},$e=async(e,s={})=>{const o=s.ciMode??!1;return!!(await we(e))&&!!(await(async(e,s)=>{const o=`${i()}/business/v1/tos/latest`;t(`GET ${o}`);const n=await fetch(o,{headers:{Authorization:`Bearer ${e}`}});if(t(`TOS latest response: ${n.status}`),n.ok)return!0;if(404!==n.status)return!0;const a=`${i()}/business/v1/tos/current`;t(`GET ${a}`);const c=await fetch(a,{headers:{Authorization:`Bearer ${e}`}});if(t(`TOS current response: ${c.status}`),!c.ok)return t("Could not fetch current TOS, skipping check"),!0;const l=await c.json().catch(()=>({})),p=l.version??"unknown";if(l.text&&(console.log(u.dim("─".repeat(60))),console.log(u.bold(`Terms of Service ${p}`)),console.log(u.dim("─".repeat(60))),console.log(l.text.replace(/<br\s*\/?>/gi,"\n").replace(/<\/p>/gi,"\n\n").replace(/<\/div>/gi,"\n").replace(/<\/li>/gi,"\n").replace(/<[^>]+>/g,"").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," ").replace(/\n{3,}/g,"\n\n").trim()),console.log(u.dim("─".repeat(60)))),s)return console.log(u.yellow(`By proceeding you accept the Terms of Service ${p}.`)),!0;const{accept:d}=await w.prompt([{type:"confirm",name:"accept",message:`By creating an application you accept the Terms of Service ${p}. Continue?`,default:!0}]);if(!d)return console.log(u.yellow("Cancelled.")),!1;try{const s=`${i()}/business/v1/tos/${l.id}/accept`;t(`POST ${s}`),await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch(h){r(h)}return!0})(e,o))},ve=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,ke=e=>new Promise(t=>setTimeout(t,e)),be=e=>e.appFullCustomDomain?e.appFullCustomDomain:e.subdomain?"qa"===(process.env.APPLICATION_ENV??"")?`https://${e.subdomain}.dashnex.dev`:`https://${e.subdomain}.dashnexcloud.com`:null,xe=3e5,Se=99,Ee=e=>new Promise(t=>setTimeout(t,e)),Ce=async(e,s,o,n)=>{const a=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${s}`,Accept:"text/event-stream"}});if(t(`SSE connection opened: ${a.status}`),!a.ok){const e=a.status;let t="Failed to start deployment.";if(401===e||403===e)t="Please run 'dashnex login' to authenticate.";else try{const e=await a.text(),s=JSON.parse(e);"string"==typeof s.error?t=s.error:"string"==typeof s.message&&(t=s.message)}catch{}throw console.error(u.red(t)),new Error(`HTTP ${e}: ${t}`)}if(!a.body)throw new Error("Response body is null");t("SSE connection established successfully"),n?.();const i=a.body.getReader();try{for await(const e of async function*(e){const t=new TextDecoder("utf-8");let s="";for(;;){const{value:o,done:n}=await e.read();if(n)break;s+=t.decode(o,{stream:!0});const r=s.split("\n");s=r.pop()||"";let a="";for(const e of r)e.startsWith("data: ")?a=e.slice(6):""===e&&a&&(yield{data:a},a="")}if(s.startsWith("data: ")){const e=s.slice(6);e&&(yield{data:e})}}(i))try{if(!e.data){t("Received empty SSE event");continue}const s=JSON.parse(e.data);t(`SSE message received: ${JSON.stringify(s)}`),o(s)}catch(c){r(c),t(`Failed to parse SSE event data: ${e.data}`)}}finally{i.releaseLock()}},Pe=class{async execute(e={}){t("Deploy flow started");const n=await p();if(!n)return;if(!1!==e.check?(t("Running pre-deploy checks"),await(new q).run(!1)||(console.error(u.red("Deploy aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):t("Skipping pre-deploy checks (--no-check)"),!(await $e(n.token,{ciMode:!0})))return;const a=`${l()}/business/v1/applications/deploy`;t(`GET ${a} (SSE)`);let i=0,c="",d=!1,h=0,m=!1;const f=D();let g=0,y=0,w=null;const $=(e,t)=>{const s=Math.round(e);f.text(`[${s}%] ${t}`)},v=()=>{k();const e=i,t=Date.now(),s=xe*((Se-e)/Se);w=setInterval(()=>{const o=Date.now()-t;let n;if(y>t){const e=Date.now()-y,t=Se-g,s=3030.3030303030305*t;n=Math.min(g+e/s*t,Se)}else n=Math.min(e+o/s*(Se-e),Se);n>i&&(i=n,$(i,c))},200)},k=()=>{w&&(clearInterval(w),w=null)};let b=!1;const x=e=>{if(m=!0,"string"==typeof e.error)return k(),f.stop(),console.error(u.red(e.error)),d=!0,void(b=!0);"string"==typeof e.message&&(c=e.message),"number"==typeof e.progress&&(g=e.progress,y=Date.now(),e.progress>i&&(i=e.progress)),"string"!=typeof e.message&&"number"!=typeof e.progress||(i>=100?(k(),f.stop(),d=!0):$(i,c))};for(;h<=5;)try{return m?$(i,c):f.start("Connecting..."),v(),await Ce(a,n.token,x,()=>{m||(f.text(`[${Math.round(i)}%] Deployment in progress...`),c="Deployment in progress...")}),k(),f.stop(),t("SSE connection closed"),b&&process.exit(1),void(d&&await this.showDeployedUrl(n.token))}catch(S){if(k(),r(S),t(`SSE connection error: ${S}`),d)return f.stop(),void(b&&process.exit(1));if(o(S))return f.stop(),void console.log(u.yellow(s));S instanceof Error&&S.message.startsWith("HTTP")&&(f.stop(),console.error(u.red("Could not complete deployment. Check your connection and try again.")),process.exit(1)),h++,h>5&&(f.stop(),console.error(u.red("Deployment failed. Maximum reconnection attempts exceeded.")),process.exit(1));const e=Math.min(1e3*Math.pow(2,h-1),3e4);t(`Connection error. Reconnecting in ${e/1e3}s... (attempt ${h}/5)`),await Ee(e)}}async showDeployedUrl(e){try{const s=`${i()}/business/v1/applications`;t(`GET ${s} (for deployed URL)`);const o=await fetch(s,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)return;const n=await o.json().catch(()=>({})),r=be({subdomain:n.subdomain,appFullCustomDomain:n.appFullCustomDomain});r&&console.log(`Application is deployed to ${u.cyan(r)}`)}catch(s){r(s)}}},De=104857600,Te=class extends Error{},Ae=class extends Error{},je=class extends Error{},Ne="/business/v1/cli/tail-token";async function Fe(e,t={}){const s=`${i()}${Ne}${t.debug?"?debug=1":""}`;try{await fetch(s,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})}catch{}}var Ie=["log","info","warn","error","debug"],Oe={error:4,warn:3,log:2,info:2,debug:1};function Re(e){return"string"==typeof e&&Ie.includes(e)}function Be(e){return e.map(e=>"string"==typeof e?e:function(e){try{return JSON.stringify(e)}catch{return String(e)}}(e)).join(" ")}function Le(e){return e<10?`0${e}`:String(e)}function ze(e){const t=new Date(e);return`${Le(t.getHours())}:${Le(t.getMinutes())}:${Le(t.getSeconds())}.${s=t.getMilliseconds(),s<10?`00${s}`:s<100?`0${s}`:String(s)}`;var s}function Me(e,t){if("string"==typeof e)return e;if("object"==typeof(s=e)&&null!==s&&"string"==typeof s.name&&"string"==typeof s.message&&Object.keys(s).every(e=>"name"===e||"message"===e||"stack"===e)){const t=`${e.name}: ${e.message}`;return e.stack?`${t}\n${e.stack}`:t}var s;return C(e,{colors:t,depth:2,breakLength:120})}var Ue={error:e=>u.red(e),warn:e=>u.yellow(e),debug:e=>u.dim(e),log:e=>e,info:e=>e};function We(e,t){const s=t.color?u.dim(ze(e.ts)):ze(e.ts),o=e.level.toUpperCase().padEnd(5),n=[s,t.color?Ue[e.level](o):o];n.push(e.args.map(e=>Me(e,t.color)).join(" "));let r=n.join(" ");if(e.truncated){const e=" …(truncated)";r+=t.color?u.dim(e):e}return r}function Je(e,t,s){let o;try{o=JSON.parse(e)}catch{return{kind:"malformed",raw:e}}if("object"!=typeof o||null===o||!Re(o.level))return{kind:"malformed",raw:e};const n=o;return Array.isArray(n.args)||(n.args=void 0===n.args?[]:[n.args]),r=n.level,a=t.minLevel,Oe[r]>=Oe[a]&&function(e,t){return!t||t.test(Be(e.args))}(n,t.filter)?{kind:"line",line:We(n,s)}:{kind:"filtered"};var r,a}var Ge=new Set([4401,4403]);var _e={name:"app",description:"Manage DashNex applications (should be executed in application folder)",handler:{execute:async()=>{}},options:[],subcommands:[{name:"create",description:"Create a new DashNex application",handler:new class{async pollApplicationCreated(e,s,o=5e3,n=6e4){const a=Date.now();let i=0;for(;Date.now()-a<n;){i++,t(`Polling application status (attempt ${i})...`);try{const o=await fetch(e,{headers:{Authorization:`Bearer ${s}`}});if(t(`Poll response: ${o.status}`),200===o.status){const e=await o.json();if(t(`Poll response body status: ${e.status}`),"creating"!==e.status)return t(`Application status is "${e.status}", creation complete`),{ready:!0,status:e.status};t('Application status is still "creating", continuing to poll...')}}catch(c){r(c),t(`Poll attempt ${i} failed with network error`)}await ke(o)}return{ready:!1}}async execute(e={}){t("Create flow started");const n=await p();if(!n)return;t("Auth valid, checking if business already has application");const a=D(),c=`${i()}/business/v1/applications`;t(`GET ${c}`),a.start("Checking application status...");try{const e=await fetch(c,{headers:{Authorization:`Bearer ${n.token}`}});a.stop(),t(`Applications response: ${e.status}`),t(`Applications response body: ${await e.text()}`),404!==e.status&&(console.error(u.red("Business already has an application. Run 'dashnex app pull' to pull the existing one.")),process.exit(1))}catch($){if(a.stop(),r($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(o($))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}t("No existing application, checking agreements");const l=void 0!==e.subdomain;if(!(await $e(n.token,{ciMode:l})))return;let d;t("Agreements checked, proceeding to subdomain prompt");const h=e=>`${i()}/business/v1/applications/check-subdomain?subdomain=${encodeURIComponent(e)}`;let m=e.subdomain?.trim();for(;;){if(m)d=m,m=void 0,t(`Subdomain provided via flag: ${d}`);else{if(l)return console.error(u.red("Subdomain is not available.")),void process.exit(1);{const{sub:e}=await w.prompt([{type:"input",name:"sub",message:"Pick your subdomain:",validate:e=>!!e.trim()||"Subdomain is required"}]);d=e.trim()}}t(`Checking subdomain: ${d}`);const e=h(d);t(`GET ${e}`),a.start("Checking subdomain...");try{const s=await fetch(e,{headers:{Authorization:`Bearer ${n.token}`}});a.stop(),t(`Check subdomain response: ${s.status}`);const o=await s.text();if(t(`Check subdomain response body: ${o}`),!s.ok){const e=s.headers.get("content-type")??"";let n="Failed to check subdomain availability.";if(401!==s.status&&403!==s.status||(n="Please run 'dashnex login' to authenticate.",console.error(u.red(n)),process.exit(1)),e.includes("application/json")){const e=JSON.parse(o);t(`Check subdomain error body: ${JSON.stringify(e)}`);const s=ve(e);s&&(n=s)}console.error(u.red(n));continue}const r=JSON.parse(o);if(t(`Check subdomain parsed body: ${JSON.stringify(r)}`),r.available){t(`Subdomain ${d} is available`);break}console.error(u.red("Subdomain is not available. Please choose a different one."))}catch($){if(a.stop(),r($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(o($))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}const f=`${i()}/business/v1/cli/create`;t(`POST ${f}`);const g={subdomain:d};e.template&&(g.template=e.template,t(`Template: ${e.template}`));const y=JSON.stringify(g);t(`Create request body: ${y}`),a.start("Creating application...");try{const c=await fetch(f,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:y});a.stop(),t(`Create response: ${c.status}`);const p=await c.text();if(t(`Create response body: ${p}`),503===c.status){t("Create returned 503, polling for application creation..."),a.start("Waiting for application to be ready...");const e=`${i()}/business/v1/applications`,s=await this.pollApplicationCreated(e,n.token);a.stop(),s.ready||(console.error(u.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(u.red("Application creation failed. Please try again.")),process.exit(1)),t("Application found after polling")}else if(!c.ok){const e=c.headers.get("content-type")??"";let s="Failed to create application.";if(401===c.status||403===c.status)s="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=JSON.parse(p);t(`Create error body parsed: ${JSON.stringify(e)}`);const o=ve(e);o&&(s=o)}console.error(u.red(s)),process.exit(1)}let d;if(t("Application created successfully"),!0===e.pull?(d=!0,t("--pull flag set, pulling without prompting")):!1===e.pull?(d=!1,t("--no-pull flag set, skipping pull")):l?(d=!1,t("CI mode (--subdomain), skipping pull")):(d=(await w.prompt([{type:"confirm",name:"pull",message:"Pull the application locally?",default:!0}])).pull,t(`User chose to pull: ${d}`)),d){t("Running pull flow");try{await(new ye).execute()}catch($){if(r($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(o($))return void console.log(u.yellow(s));console.error(u.red("Failed to pull application."))}}else console.log(u.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(a.stop(),r($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(o($))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[{flags:"-t, --template <template>",description:"Template (name@branch-or-tag)",defaultValue:"webapp-base@live"},{flags:"--subdomain <subdomain>",description:"Subdomain (CI mode, skip prompts)"},{flags:"--pull",description:"Auto-pull after creation (skip prompt)"},{flags:"--no-pull",description:"Skip the pull prompt and show the success message"}]},{name:"pull",description:"Pull existing application to specified folder",handler:new ye,arguments:[{name:"folder",description:"Target folder (defaults to interactive prompt)"}],options:[{flags:"-y, --yes",description:"Skip prompts and child commands (CI mode)"}]},{name:"push",description:"Push local application to DashNex",handler:new class{async execute(e={}){t("Push flow started"),await h.pathExists(m.join(process.cwd(),"dashnex.json"))||(console.error(u.red("Not a DashNex application folder (dashnex.json not found).")),console.error(u.red("Run this command from your application root.")),process.exit(1)),!1!==e.check?(t("Running pre-push checks"),await(new q).run(!1)||(console.error(u.red("Push aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):t("Skipping pre-push checks (--no-check)");const n=await p();if(!n)return;const a=process.cwd(),i=D();try{i.start("Analyzing local files...");const s=await ae(a),o=await re(a);t(`Local manifest has ${Object.keys(o).length} files`),i.text("Comparing with remote...");const r=await this.requestPlan(n.token,o,s?.commit);i.stop(),"legacy"===r?(t("v2 push endpoints unavailable, falling back to legacy zip push"),await this.pushLegacy(n.token,a,i)):await this.pushDiff(n.token,a,o,r,e,i),await this.promptAndDeploy(e)}catch(c){if(i.stop(),r(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(o(c))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}async requestPlan(e,s,o){const n=`${i()}/business/v1/cli/v2/push/plan`;t(`POST ${n}`);const r=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:s,lastSyncCommit:o})});if(t(`Plan response: ${r.status}`),r.ok)return await r.json();const a=await r.json().catch(()=>({}));if(((e,t)=>404===e&&"string"==typeof t.message&&t.message.startsWith("Cannot "))(r.status,a))return"legacy";this.failFromResponse(r.status,a,"Failed to push application.")}async pushDiff(e,s,o,n,r,a){let i=n;if(i.remoteChanged.length>0&&!r.force){console.error(u.red("Remote application has changes you don't have locally:"));for(const e of i.remoteChanged.slice(0,20))console.error(u.red(` ${e}`));i.remoteChanged.length>20&&console.error(u.red(` … and ${i.remoteChanged.length-20} more`)),console.error(u.red("Run 'dashnex app pull' first, or push anyway with --force.")),process.exit(1)}const c=i.upload.filter(e=>e in o);let l=i.delete;if(0!==c.length||0!==l.length){if(l.length>0){const e=await ae(s),o=r.yes||"1"===process.env.DASHNEX_CI;console.log(u.yellow(`${l.length} file(s) will be deleted from the application repository:`));for(const t of l.slice(0,20))console.log(u.yellow(` ${t}`));if(l.length>20&&console.log(u.yellow(` … and ${l.length-20} more`)),!o){const{confirmDelete:s}=await w.prompt([{type:"confirm",name:"confirmDelete",message:"Delete these files from the remote repository?",default:null!==e}]);s||(t("User declined remote deletions, pushing without them"),l=[])}}if(0!==c.length||0!==l.length)for(let n=1;;n+=1){a.start(1===n?"Uploading changes...":"Remote changed, retrying...");const p=await this.applyPush(e,s,c,l,i.baseCommit);if(a.stop(),"ok"===p.status){await ie(s,p.commit,o);const e=[`${c.length} file(s) updated`];return l.length>0&&e.push(`${l.length} deleted`),console.log(u.cyan(`Pushed: ${e.join(", ")}`)),void console.log(u.green("Application pushed successfully."))}n>=2&&(console.error(u.red("Remote repository keeps changing, please retry the push.")),process.exit(1)),t("Push apply conflicted, re-planning");const d=await ae(s),h=await this.requestPlan(e,o,d?.commit);"legacy"===h&&(console.error(u.red("Failed to push application.")),process.exit(1)),h.remoteChanged.length>0&&!r.force&&(console.error(u.red("Remote application changed during the push. Run 'dashnex app pull' first, or push with --force.")),process.exit(1)),i=h}else console.log(u.green("Everything up to date."))}else console.log(u.green("Everything up to date."))}async applyPush(e,s,o,n,r){const a=new v;for(const t of o){const e=m.join(s,...t.split("/")),o=m.posix.dirname(t);a.addLocalFile(e,"."===o?"":o,m.posix.basename(t))}const c=m.join($.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{a.writeZip(c),t(`Diff zip written to ${c} (${o.length} files, ${n.length} deletions)`),await this.ensureZipWithinLimit(c);const s=`${i()}/business/v1/cli/v2/push/apply`;t(`POST ${s}`);const l=await h.readFile(c),p=new FormData;p.append("file",new Blob([l],{type:"application/zip"}),"diff.zip"),p.append("baseCommit",r),p.append("deletions",JSON.stringify(n));const d=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:p});if(t(`Apply response: ${d.status}`),409===d.status)return{status:"conflict"};if(!d.ok){const e=await d.json().catch(()=>({}));this.failFromResponse(d.status,e,"Failed to push application.")}return{status:"ok",commit:(await d.json().catch(()=>({}))).commit??""}}finally{await h.remove(c).catch(()=>{})}}async pushLegacy(e,s,o){const n=await re(s),r=Object.keys(n);t(`Legacy push including ${r.length} files`);const a=new v;for(const t of r){const e=m.join(s,...t.split("/")),o=m.posix.dirname(t);a.addLocalFile(e,"."===o?"":o,m.posix.basename(t))}const c=m.join($.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{o.start("Packaging application..."),a.writeZip(c),t(`Zip written to ${c}`),await this.ensureZipWithinLimit(c);const s=`${i()}/business/v1/cli/push`;t(`POST ${s}`);const n=await h.readFile(c),r=new FormData;r.append("file",new Blob([n],{type:"application/zip"}),"archive.zip"),o.text("Uploading...");const l=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:r});if(o.stop(),t(`Response: ${l.status}`),!l.ok){const e=await l.json().catch(()=>({}));this.failFromResponse(l.status,e,"Failed to push application.")}console.log(u.green("Application pushed successfully."))}finally{await h.remove(c).catch(()=>{}),t("Temp zip removed")}}async ensureZipWithinLimit(e){const{size:t}=await h.stat(e);if(t>De){const e=e=>(e/1048576).toFixed(1);console.error(u.red(`Push package is ${e(t)} MB — the maximum is ${e(De)} MB.`)),console.error(u.red("Remove or .gitignore large files and try again.")),process.exit(1)}}failFromResponse(e,t,s){let o=s;if(401===e||403===e)o="Please run 'dashnex login' to authenticate.";else{const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);e&&(o=e)}console.error(u.red(o)),process.exit(1)}async promptAndDeploy(e){let s;void 0!==e.deploy?(s=e.deploy,t(`Deploy decided via flag: ${s}`)):"1"===process.env.DASHNEX_CI?(s=!1,t("CI mode: skipping deploy prompt (use --deploy to deploy)")):(s=(await w.prompt([{type:"confirm",name:"deploy",message:"Deploy the application?",default:!0}])).deploy,t(`User chose to deploy: ${s}`)),s&&(t("Running deploy flow"),await(new Pe).execute())}},options:[{flags:"--deploy",description:"Auto-deploy after push (skip prompt)"},{flags:"--no-deploy",description:"Skip deploy prompt"},{flags:"--no-check",description:"Skip pre-push checks"},{flags:"-f, --force",description:"Push even when the remote has changes you don't have locally"},{flags:"-y, --yes",description:"Skip prompts (CI mode)"}]},{name:"delete",description:"Delete application from DashNex",handler:new class{async execute(e={}){if(t("Delete flow started"),!e.yes){const{confirm:e}=await w.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to delete this application? This action cannot be undone.",default:!1}]);if(!e)return t("User cancelled deletion"),void console.log(u.yellow("Deletion cancelled."))}const n=await p();if(!n)return;const a=`${i()}/business/v1/applications`;t(`DELETE ${a}`);const c=D();c.start("Deleting application...");try{const e=await fetch(a,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}});if(c.stop(),t(`Response: ${e.status}`),!e.ok){const t=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(t.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(u.red(s)),process.exit(1)}const s=await e.json().catch(()=>({})),o="string"==typeof s.message?s.message:"Application deleted successfully.";t("Application deleted successfully"),console.log(u.green(o))}catch(l){if(c.stop(),r(l),l instanceof Error&&l.message.startsWith("EXIT:"))throw l;if(o(l))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[{flags:"-y, --yes",description:"Skip confirmation prompt"}]},{name:"deploy",description:"Deploy application to DashNex",handler:new Pe,options:[{flags:"--no-check",description:"Skip pre-deploy checks"}]},{name:"status",description:"Show current application status",handler:new class{async execute(){t("Status flow started");const e=await p();if(!e)return;const n=`${i()}/business/v1/applications`;t(`GET ${n}`);const a=D();a.start("Fetching application status...");try{const s=await fetch(n,{headers:{Authorization:`Bearer ${e.token}`}});if(a.stop(),t(`Response: ${s.status}`),404===s.status)return void console.log(u.yellow("Application not created"));if(!s.ok){const e=s.headers.get("content-type")??"";let t="Failed to fetch application status.";if(401===s.status||403===s.status)t="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=await s.json().catch(()=>({}));"string"==typeof e.error?t=e.error:"string"==typeof e.message&&(t=e.message)}console.error(u.red(t)),process.exit(1)}const o=await s.json().catch(()=>({}));t(`Application body: ${JSON.stringify(o)}`);const r=o.status??"unknown";console.log(`Status: ${u.cyan(r)}`);const i=be(o);i&&console.log(`URL: ${u.cyan(i)}`)}catch(c){if(a.stop(),r(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(o(c))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]},{name:"tail",description:"Stream live console/debug logs from the deployed worker (Ctrl+C to stop)",handler:new class{async execute(e={}){const s=e.level??"log";Re(s)||(console.error(u.red(`Invalid --level '${e.level}'. Use one of: log, info, warn, error, debug.`)),process.exit(1));let o=null;if(e.filter)try{o=new RegExp(e.filter)}catch{console.error(u.red(`Invalid --filter regular expression: ${e.filter}`)),process.exit(1)}const n=await p();if(!n)return;const a=!!e.debug;let c;try{c=await async function(e,s={}){const o=`${i()}${Ne}`;t(`POST ${o}${s.debug?" (debug)":""}`);const n=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({debug:!!s.debug})});if(t(`Response: ${n.status}`),401===n.status||403===n.status)throw new Te("Not authorised to tail this application.");if(404===n.status)throw new Ae("Business has no application, or the tail endpoint is unavailable.");if(!n.ok)throw new je(`Failed to start tail (status ${n.status}).`);const r=await n.json().catch(()=>({}));if(!r.token||!r.workerUrl)throw new je("Malformed tail-token response from the platform.");return{token:r.token,workerUrl:r.workerUrl,expiresAt:"number"==typeof r.expiresAt?r.expiresAt:0}}(n.token,{debug:a})}catch(k){r(k),k instanceof Te&&(console.error(u.red(k.message)),process.exit(1)),k instanceof Ae&&(console.error(u.red(k.message)),process.exit(2)),console.error(u.red(k instanceof Error?k.message:"Could not start tail. Check your connection.")),process.exit(3)}const l={color:!!process.stdout.isTTY},d={minLevel:s,filter:o},h=(m=c.workerUrl,`${/^(localhost|127\.0\.0\.1)/.test(m)?"ws":"wss"}://${m}/api/realtime/tail`);var m;const f=`dashnex.tail.token.${c.token}`;console.log(u.dim(`Tailing ${c.workerUrl} — Ctrl+C to stop.`)),a&&console.log(u.dim("Debug logging enabled on the worker (DEBUG=1); may take a minute to take effect."));let g=!1,y=Date.now();const w=setInterval(()=>{g||Date.now()-y>=3e4&&(console.log(u.dim("(no logs in 30s)")),y=Date.now())},5e3),$=new S(h,f,{WebSocket:E,connectionTimeout:1e4,maxReconnectionDelay:16e3}),v=async e=>{if(!g){g=!0,clearInterval(w);try{$.close()}catch{}await Promise.race([Fe(n.token,{debug:a}),new Promise(e=>setTimeout(e,3e3))]),process.exit(e)}};process.on("SIGINT",()=>{console.log(),v(0)}),$.binaryType="arraybuffer",$.addEventListener("message",e=>{y=Date.now();const t=Je("string"==typeof e.data?e.data:"",d,l);"line"===t.kind?console.log(t.line):"malformed"===t.kind&&console.error(u.dim(`[malformed frame] ${t.raw}`))}),$.addEventListener("close",e=>{if(!g)return Ge.has(e.code)?(console.error(u.red("Tail token was rejected (auth). Exiting.")),void v(1)):void t(`socket closed (code ${e.code}); reconnecting…`)}),$.addEventListener("error",e=>{t(`socket error: ${e.message??"unknown"}`)}),await new Promise(()=>{})}},options:[{flags:"--level <level>",description:"Minimum level: log, info, warn, error, debug"},{flags:"--filter <regex>",description:"Only show records whose args match this regex"},{flags:"--debug",description:"Also enable DEBUG=1 on the worker so debug-gated logs are shown"}]}]},qe={name:"secrets",description:"Manage DashNex secrets",handler:{execute:async()=>{}},options:[],subcommands:[{name:"list",description:"List all secret names bound to the worker",handler:new class{async execute(){t("Secrets list flow started");const e=await p();if(!e)return;const n=`${i()}/business/v1/cli/secrets`;t(`GET ${n}`);const a=D();a.start("Fetching secrets...");try{const s=await fetch(n,{headers:{Authorization:`Bearer ${e.token}`}});if(a.stop(),t(`Response: ${s.status}`),!s.ok){let e="Failed to fetch secrets.";401===s.status||403===s.status?e="Please run 'dashnex login' to authenticate.":404===s.status?e="Business has no application.":502===s.status&&(e="Error fetching secrets. Make sure your application is deployed."),console.error(u.red(e)),process.exit(1)}const o=(await s.json()).secrets??[];if(0===o.length)return void console.log(u.yellow("No secrets set."));console.log(u.bold(`\nSecrets (${o.length}):\n`)),o.forEach(({name:e})=>{console.log(` ${u.cyan(e)}`)}),console.log("")}catch(c){if(a.stop(),r(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(o(c))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]},{name:"set",description:"Create or update a secret (prompts for missing KEY/VALUE)",handler:new class{async execute(e={}){t("Secrets set flow started");let{name:n,value:a}=e;const c="1"===process.env.DASHNEX_CI;n||(c&&(console.error(u.red("--name is required in CI mode (--ci).")),process.exit(1)),n=(await w.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim()),a||(c&&(console.error(u.red("--value is required in CI mode (--ci).")),process.exit(1)),a=(await w.prompt([{type:"password",name:"value",message:`Enter value for ${n}:`,mask:"*",validate:e=>""!==e||"Value is required"}])).value);const l=await p();if(!l)return;const d=`${i()}/business/v1/cli/secrets`;t(`PUT ${d}`);const h=D();h.start(`Setting secret '${n}'...`);try{const e=await fetch(d,{method:"PUT",headers:{Authorization:`Bearer ${l.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:n,value:a})});if(h.stop(),t(`Response: ${e.status}`),!e.ok){let t="Failed to set secret.";401===e.status||403===e.status?t="Please run 'dashnex login' to authenticate.":400===e.status?t="Missing or empty name / value.":404===e.status?t="Business has no application.":502===e.status&&(t="Error setting secret. Make sure your application is deployed."),console.error(u.red(t)),process.exit(1)}t(`Secret '${n}' set successfully`),console.log(u.green(`Secret '${n}' set successfully.`))}catch(m){if(h.stop(),r(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(o(m))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},arguments:[{name:"name",description:"Secret name (KEY)"},{name:"value",description:"Secret value"}],options:[{flags:"--name <name>",description:"Secret name (alternative to positional KEY)"},{flags:"--value <value>",description:"Secret value (alternative to positional VALUE)"}]},{name:"delete",description:"Delete a secret (prompts for missing KEY)",handler:new class{async execute(e={}){t("Secrets delete flow started");let{name:n}=e;const a="1"===process.env.DASHNEX_CI;n||(a&&(console.error(u.red("--name is required in CI mode (--ci).")),process.exit(1)),n=(await w.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim());const c=await p();if(!c)return;const l=`${i()}/business/v1/cli/secrets/${encodeURIComponent(n)}`;t(`DELETE ${l}`);const d=D();d.start(`Deleting secret '${n}'...`);try{const e=await fetch(l,{method:"DELETE",headers:{Authorization:`Bearer ${c.token}`}});if(d.stop(),t(`Response: ${e.status}`),!e.ok){let t="Failed to delete secret.";401===e.status||403===e.status?t="Please run 'dashnex login' to authenticate.":404===e.status?t=`Secret '${n}' not found.`:502===e.status&&(t="Error deleting secret. Make sure your application is deployed."),console.error(u.red(t)),process.exit(1)}t(`Secret '${n}' deleted successfully`),console.log(u.green(`Secret '${n}' deleted.`))}catch(h){if(d.stop(),r(h),h instanceof Error&&h.message.startsWith("EXIT:"))throw h;if(o(h))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},arguments:[{name:"name",description:"Secret name (KEY)"}],options:[{flags:"--name <name>",description:"Secret name (alternative to positional KEY)"}]}]},Xe=[{name:"version",description:"Display the version of the CLI",handler:new class{async execute(e){const t=m.dirname(f(import.meta.url)),s=JSON.parse(y.readFileSync(m.resolve(t,"..","..","package.json"),"utf8"));console.log(s.version)}},options:[]},{name:"login",description:"Log in to your DashNex account",handler:new class{async execute(a={}){t("Login flow started");const i=c(process.cwd()),l=await p({exitOnFailure:!1,dashnexPath:i});if(l)console.log(u.green(`Already logged in as ${l.userName??"user"}`));else try{let s,o;if(a.email)s=a.email.trim(),t("Email provided via flag");else{const{username:e}=await w.prompt([{type:"input",name:"username",message:"Email:",validate:e=>!!e.trim()||"Email is required"}]);s=e.trim()}if(a.password)o=a.password,t("Password provided via flag");else{const{password:e}=await w.prompt([{type:"password",name:"password",message:"Password:",mask:"*",validate:e=>!!e||"Password is required"}]);o=e}t("Email provided");const c=D();c.start("Logging in..."),t(`POST ${e()}/auth/v1/login`);const{response:l,body:p}=await n(`${e()}/auth/v1/login`,{method:"POST",body:JSON.stringify({username:s,password:o})});c.stop(),t(`Response: ${l.status}`),d("Login response",p),l.ok||(r(/* @__PURE__ */new Error(`Login failed: ${l.status} ${JSON.stringify(p)}`)),401===l.status&&(console.error(u.red("Invalid username or password.")),process.exit(1)),T(l,p,"Login failed. Please try again."));const h=p;if(h.two_fa_required&&h.token){t(`2FA required, type: ${h.type||"unknown"}`);const e=await this.handle2FA(h.token,h.type,a.code);e||process.exit(1),await this.completeLogin(e,i,a.business)}else h.token&&h.refreshToken?await this.completeLogin({token:h.token,refreshToken:h.refreshToken},i,a.business):(console.error(u.red("Invalid response from server. Please try again.")),process.exit(1))}catch(h){if(r(h),o(h))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}async handle2FA(a,i,c){if("sms"===i){t(`POST ${e()}/auth/v1/two-fa/sms`);try{const{response:s}=await n(`${e()}/auth/v1/two-fa/sms`,{method:"POST",headers:{Authorization:`Bearer ${a}`},body:JSON.stringify({})});t(`Response: ${s.status}`)}catch(h){return r(h),console.error(u.red("Could not send SMS code. Check your connection and try again.")),null}}const l="sms"===i?"Check your phone for the code":"Check your authenticator app for the code",p=c?1:3;for(let m=1;m<=p;m++){let i;c&&1===m?(i=c,t("2FA code provided via flag")):i=(await w.prompt([{type:"input",name:"auth_code",message:`Enter code (${l}):`,validate:e=>!!e.trim()||"Code is required"}])).auth_code,t(`POST ${e()}/auth/v1/2fa-check`);try{const{response:s,body:o}=await n(`${e()}/auth/v1/2fa-check`,{method:"POST",headers:{Authorization:`Bearer ${a}`},body:JSON.stringify({auth_code:i.trim()})});if(t(`Response: ${s.status}`),d("2FA check response",o),s.ok){const e=o;if(e.token&&e.refreshToken)return{token:e.token,refreshToken:e.refreshToken}}if(s.status>=400&&s.status<500){if(console.error(u.red("Invalid code. Please try again.")),m<p){const{retry:e}=await w.prompt([{type:"confirm",name:"retry",message:"Try again?",default:!0}]);if(!e)return null}continue}T(s,o,"2FA verification failed. Please try again.")}catch(h){return r(h),o(h)?(console.log(u.yellow(s)),null):(console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),null)}}return null}async completeLogin(s,o,a){const c=D();c.start("Fetching businesses...");const l=e(),p={Authorization:`Bearer ${s.token}`};t(`GET ${l}/users/v1/business/my`);const{response:f,body:g}=await n(`${l}/users/v1/business/my`,{headers:p});t(`Response: ${f.status}`),d("Businesses response",g),f.ok||(c.stop(),r(/* @__PURE__ */new Error(`Business fetch failed: ${f.status}`)),T(f,g,"Failed to fetch businesses. Please try again."));const y=this.parseBusinesses(g),$=await this.fetchOtherBusinesses(s.token),v=this.mergeBusinesses(y,$);let k;if(c.stop(),t(`Businesses (my: ${y.length}, other: ${$.length}, merged: ${v.length})`),0===v.length&&(console.error(u.red("No businesses or teams found for your account!")),console.log(u.green("Create your first business at https://dashnex.io")),process.exit(1)),a){const e=v.find(e=>e.id===a);e||(console.error(u.red(`Business "${a}" not found.`)),process.exit(1)),k=e,t(`Selected business via flag: ${k.id} ${k.name}`)}else if(1===v.length)k=v[0],t(`Selected business: ${k.id} ${k.name}`);else{const{businessId:e}=await w.prompt([{type:"select",name:"businessId",message:"Select business:",choices:v.map(e=>({name:e.name,value:e.id}))}]);k=v.find(t=>t.id===e)||v[0],t(`Selected business: ${k.id} ${k.name}`)}c.start("Switching business..."),t(`GET ${l}/business/v1/login?_switch_business=${k.id}`);const{response:b,body:x}=await n(`${l}/business/v1/login?_switch_business=${k.id}`,{headers:p});c.stop(),t(`Response: ${b.status}`),d("Business login response",x),b.ok||(r(/* @__PURE__ */new Error(`Business login failed: ${b.status}`)),T(b,x,"Failed to switch to business. Please try again."));const S=x;S.token&&S.refreshToken||(console.error(u.red("Invalid response from server. Please try again.")),process.exit(1));const E={token:S.token,refreshToken:S.refreshToken,businessId:k.id},C={Authorization:`Bearer ${S.token}`};try{const e=i();t(`GET ${e}/business/v1/cli/settings`);const{response:s,body:o}=await n(`${e}/business/v1/cli/settings`,{headers:C});t(`Response: ${s.status}`),d("CLI settings response",o),s.ok&&o&&"object"==typeof o&&Object.assign(E,o)}catch(A){r(A)}const P=m.dirname(o);await h.pathExists(P)&&(await h.stat(P)).isFile()&&await h.remove(P),await h.ensureDir(P),await h.writeJson(o,E,{spaces:2}),t("Saved credentials to .dashnex/settings.json"),this.ensureGitignore(),console.log(u.green(`Logged in as ${k.name}`))}async fetchOtherBusinesses(s){const o=e();let a=1;const i=[];let c=0;do{const e=`${o}/users/v1/business/other?page=${a}&perPage=100`;t(`GET ${e}`);const{response:l,body:p}=await n(e,{headers:{Authorization:`Bearer ${s}`}});l.ok||(r(/* @__PURE__ */new Error(`Other businesses fetch failed: ${l.status}`)),T(l,p,"Failed to fetch teams. Please try again."));const d=this.parseBusinesses(p),u="number"==typeof p.total?p.total:d.length;if(i.push(...d),c=u,d.length<100||i.length>=c)break;a++}while(i.length<c);return i}mergeBusinesses(e,t){const s=/* @__PURE__ */new Map;for(const o of e)s.set(o.id,o);for(const o of t)s.has(o.id)||s.set(o.id,o);return[...s.values()]}parseBusinesses(e){const t=Array.isArray(e)?e:e.items??e.data??e.businesses??[];return Array.isArray(t)?t.map(e=>{if(e&&"object"==typeof e){const t=e,s=String(t.id??t.business_id??"").trim(),o=String(t.name??t.companyName??t.business_name??"Unknown").trim();if(s)return{id:s,name:o}}return null}).filter(e=>null!==e):[]}async ensureGitignore(){const e=m.join(process.cwd(),".gitignore");if(!(await h.pathExists(e)))return;let t=await h.readFile(e,"utf8");t.includes(".dashnex")||(t=t.trimEnd(),t.endsWith("\n")||(t+="\n"),t+="\n.dashnex\n",await h.writeFile(e,t))}},options:[{flags:"--email <email>",description:"Email address (skip prompt)"},{flags:"--password <password>",description:"Password (skip prompt)"},{flags:"--code <code>",description:"2FA code (skip prompt)"},{flags:"--business <id>",description:"Business ID to select (skip prompt)"}]},{name:"logout",description:"Log out and remove local credentials",handler:new class{async execute(){const e=c(process.cwd());if(await h.pathExists(e)){const t=await h.readJson(e);delete t.token,delete t.refreshToken,delete t.businessId,await h.writeJson(e,t,{spaces:2})}console.log(u.green("Logged out."))}},options:[]},{name:"whoami",description:"Show current logged-in business and user",handler:new class{async execute(){t("Whoami flow started");const n=await p();if(!n)return;const a=`${e()}/users/v1/`;t(`GET ${a}`);const i=D();i.start("Fetching user info...");try{const e=await fetch(a,{headers:{Authorization:`Bearer ${n.token}`}});if(i.stop(),t(`Response: ${e.status}`),!e.ok){const t=e.headers.get("content-type")??"";let s="Failed to fetch user info.";if(401===e.status||403===e.status)s="Please run 'dashnex login' to authenticate.";else if(t.includes("application/json")){const t="string"==typeof(c=await e.json().catch(()=>({}))).error?c.error:"string"==typeof c.message?c.message:void 0;t&&(s=t)}console.error(u.red(s)),process.exit(1)}const s=await e.json().catch(()=>({})),o="string"==typeof s.name?s.name:"string"==typeof s.companyName?s.companyName:"Unknown",r=s.memberUser,l=r&&"string"==typeof r.fullName?r.fullName:r&&"string"==typeof r.name?r.name:"Unknown";t(`Whoami: ${o} (${l})`),console.log(u.green(`You are logged in as ${o} (${l})`))}catch(l){if(i.stop(),r(l),l instanceof Error&&l.message.startsWith("EXIT:"))throw l;if(o(l))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}var c}},options:[]},{name:"dev",description:"Run the development server (run in DashNex application folder)",handler:new class{async execute(e={}){t("Dev flow started");try{const t=await F(process.cwd(),e);process.exit(t)}catch(s){if(s instanceof Error&&s.message.startsWith("EXIT:"))throw s;r(s),s instanceof Error?console.error(u.red(s.message)):console.error(u.red("Failed to run npm run dev")),process.exit(1)}}},options:[{flags:"--https",description:"Run dev server with HTTPS"}]},{name:"check",description:"Run build-time validations (run in DashNex application folder)",handler:new q,options:[]},{name:"install",description:"Install dependencies using pnpm (preferred) or npm (run in DashNex application folder)",handler:new class{async execute(){t("Install flow started");const e=m.join(process.cwd(),"dashnex.json");await h.pathExists(e)||(console.error(u.red("Run this command in a DashNex Web application folder.")),process.exit(1));const s=process.cwd(),o=D();o.start("Installing dependencies...");try{const e=await O(s);o.stop(),0!==e&&process.exit(e),console.log(u.green("Dependencies installed.")),process.exit(0)}catch(n){o.stop(),r(n),n instanceof Error?console.error(u.red(n.message)):console.error(u.red("Failed to run install")),process.exit(1)}}},options:[]},_e,qe];export{Xe as default};
package/dist/server.js CHANGED
@@ -1 +1 @@
1
- import{n as s,t as e}from"./chunks/dashnex-DMegPU38.js";var n={name:s.name,version:s.version,description:s.description,...e};export{n as default};
1
+ import{n as s,t as e}from"./chunks/dashnex-D2jglM0m.js";var n={name:s.name,version:s.version,description:s.description,...e};export{n as default};
@@ -11,6 +11,7 @@ export declare class PushCommand implements CliCommand {
11
11
  private pushDiff;
12
12
  private applyPush;
13
13
  private pushLegacy;
14
+ private ensureZipWithinLimit;
14
15
  private failFromResponse;
15
16
  private promptAndDeploy;
16
17
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "dashnex",
4
- "version": "0.5.86",
4
+ "version": "0.5.87",
5
5
  "description": "Command-line interface for DashNex framework",
6
6
  "homepage": "https://dashnex.io",
7
7
  "type": "module",