dashnex 0.8.2 → 0.8.3
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.8.
|
|
1
|
+
var e={$schema:"https://json.schemastore.org/package",name:"@dashnex/cli",version:"0.8.3",dashnex:{minAppVersion:"1.1.0"},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",jiti:"^2.7.0",partysocket:"^1.3.0",tar:"^7.5.22",ws:"^8.21.0"},devDependencies:{"@dashnex/types":"^1.6.1","@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.8","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-
|
|
1
|
+
import{n as s,t as e}from"./chunks/dashnex-CT3PnUmH.js";var n={name:s.name,version:s.version,description:s.description,...e};export{n as default};
|
package/dist/commands/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e,E as t,O as s,S as n,_ as o,a as r,b as a,c as i,d as c,f as l,g as d,h as p,i as u,k as h,l as m,m as g,n as f,o as w,p as y,r as $,s as v,t as b,u as k,v as x,w as S,x as E,y as D}from"../chunks/project-guard-CxCsFM9x.js";import T from"chalk";import j from"fs-extra";import C from"path";import{fileURLToPath as N}from"url";import{execFileSync as P,spawn as I,spawnSync as A}from"child_process";import F from"fs";import R from"inquirer";import{X509Certificate as O,createHash as B,createPrivateKey as _,randomBytes as z}from"crypto";import W from"net";import L from"os";import M from"adm-zip";import{diffLines as U}from"diff";import X from"ignore";import{WebSocket as H}from"partysocket";import J from"ws";import{inspect as G}from"node:util";import{rm as q}from"node:fs/promises";import*as Y from"tar";var V=e=>e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),K=async t=>{const s=(e=>{switch(process.platform){case"darwin":return{command:"open",args:[e]};case"win32":return{command:"cmd",args:["/c","start","",e]};default:return{command:"xdg-open",args:[e]}}})(t);return!!s&&new Promise(t=>{try{const o=I(s.command,s.args,{stdio:"ignore",detached:!0});o.on("error",s=>{e(s),t(!1)}),o.on("spawn",()=>{n(`Opened browser via ${s.command}`),o.unref(),t(!0)})}catch(o){e(o),t(!1)}})},Z="urn:ietf:wg:oauth:2.0:oob",Q=class extends Error{constructor(e,t){super(e),this.code=t,this.name="OAuthError"}},ee=class extends Error{},te=class extends ee{},se=(e,t)=>401===e||403===e&&"insufficient_scope"===t.error,ne=e=>{const t=e.data;return t&&"object"==typeof t?t:e},oe=e=>{const t=e.items??[];return Array.isArray(t)?t.map(e=>{if(!e||"object"!=typeof e)return null;const t=e,s=Number(t.id);return!Number.isFinite(s)||s<=0?null:{id:s,name:String(t.name??t.companyName??`Business ${s}`).trim()}}).filter(e=>null!==e):[]},re=async(e,t)=>{const s=[];let o=1,r=0;do{const a=`${D()}${e}?page=${o}&perPage=100`;n(`GET ${a}`);const{response:i,body:c}=await p(a,{headers:{Authorization:`Bearer ${t}`}});if(n(`Response: ${i.status}`),S(`Businesses response (${e})`,c),!i.ok){if(se(i.status,c))throw new te("Your DashNex ID session has expired.");if(404===i.status)throw new ee(`Your DashNex ID account is not linked to a contact yet. Finish signing up at ${D()} and try again.`);throw new ee("Failed to fetch businesses. Please try again.")}const l=ne(c),d=oe(l);if(r="number"==typeof l.total?l.total:d.length,s.push(...d),d.length<100||s.length>=r)break;o++}while(s.length<r);return s},ae=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],ie=(e="")=>{if(process.env.DASHNEX_CI)return{start:()=>{},stop:()=>{},text:()=>{}};let t=null,s=0,n=e;const o=()=>{const e=ae[s%ae.length];process.stderr.write(`\r[K${e} ${n}`),s++};return{start:e=>{void 0!==e&&(n=e),t||(s=0,o(),t=setInterval(o,80))},stop:()=>{t&&(clearInterval(t),t=null),process.stderr.write("\r[K\n")},text:e=>{n=e,t&&o()}}},ce=async(e,s,o={})=>{const r=ie();let a;r.start("Fetching businesses...");try{a=await(async e=>{const t=await re("/api/businesses/my",e),s=await re("/api/businesses/other",e),o=/* @__PURE__ */new Map;for(const n of t)o.set(n.id,n);for(const n of s)o.has(n.id)||o.set(n.id,n);return n(`Businesses (my: ${t.length}, other: ${s.length}, merged: ${o.size})`),[...o.values()]})(e)}finally{r.stop()}0===a.length&&(console.error(T.red("No businesses or teams found for your account!")),console.log(T.green(`Create your first business at ${D()}`)),t(1));const i=await le(a,o);let c;r.start("Switching business...");try{c=await(async(e,t)=>{const s=`${D()}/api/businesses/${t}/switch`;n(`POST ${s}`);const{response:o,body:r}=await p(s,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(n(`Response: ${o.status}`),S("Switch response",r),!o.ok){if(se(o.status,r))throw new te("Your DashNex ID session has expired.");if(403===o.status)throw new ee("You do not have access to that business.");throw new ee("Failed to switch to business. Please try again.")}const a=ne(r);if(!a.token||!a.refreshToken)throw new ee("Invalid response from server. Please try again.");return{token:a.token,refreshToken:a.refreshToken,businessId:t}})(e,i.id)}finally{r.stop()}return await pe(s,{...await de(c.token),business:{token:c.token,refreshToken:c.refreshToken,id:c.businessId}}),await ue(),i},le=async(e,s)=>{if(void 0!==s.businessId){const o=e.find(e=>String(e.id)===String(s.businessId).trim());return o||(console.error(T.red(`Business "${s.businessId}" not found.`)),t(1)),n(`Selected business via argument: ${o.id} ${o.name}`),o}if(1===e.length)return n(`Selected business: ${e[0].id} ${e[0].name}`),e[0];const o=e.find(e=>String(e.id)===String(s.currentBusinessId)),{businessId:r}=await R.prompt([{type:"select",name:"businessId",message:"Select business:",choices:e.map(e=>({name:e===o?`${e.name} ${T.dim("(current)")}`:e.name,value:e.id})),...o&&{default:o.id}}]),a=e.find(e=>e.id===r)||e[0];return n(`Selected business: ${a.id} ${a.name}`),a},de=async t=>{try{const e=`${o()}/business/v1/cli/settings`;n(`GET ${e}`);const{response:s,body:r}=await p(e,{headers:{Authorization:`Bearer ${t}`}});if(n(`Response: ${s.status}`),S("CLI settings response",r),s.ok&&r&&"object"==typeof r)return r}catch(s){e(s)}return{}},pe=async(e,t)=>{const s=C.dirname(e);await j.pathExists(s)&&(await j.stat(s)).isFile()&&await j.remove(s),await j.ensureDir(s),await l(e,e=>({...e,...t})),n("Saved credentials to .dashnex/settings.json")},ue=async()=>{const e=C.join(process.cwd(),".gitignore");if(!(await j.pathExists(e)))return;let t=await j.readFile(e,"utf8");t.includes(".dashnex")||(t=t.trimEnd(),t.endsWith("\n")||(t+="\n"),t+="\n.dashnex\n",await j.writeFile(e,t))},he="v1.4.4",me=C.join(y,"certificates"),ge=["localhost","127.0.0.1","::1"],fe="win32"===process.platform,we=()=>0===A("mkcert",["-version"],{stdio:"ignore",shell:fe}).status?"mkcert":null,ye=async(e={})=>{const t=(e.lookupPath??we)();if(t)return t;const s=e.cacheDir??C.join(L.homedir(),".dashnex","mkcert"),n=((e=process.platform,t=process.arch)=>{const s="x64"===t?"amd64":t;if("win32"===e)return`mkcert-${he}-windows-${s}.exe`;if("darwin"===e)return`mkcert-${he}-darwin-${s}`;if("linux"===e)return`mkcert-${he}-linux-${s}`;throw new Error(`Unsupported platform for mkcert: ${e}`)})(),o=C.join(s,n);if(await j.pathExists(o))return o;const r=`https://github.com/FiloSottile/mkcert/releases/download/${he}/${n}`;e.log?.(`mkcert not found, downloading ${he} to ${o}`);const a=await(e.fetchImpl??fetch)(r);if(!a.ok)throw new Error(`Failed to download mkcert from ${r}: HTTP ${a.status}`);await j.ensureDir(s);const i=`${o}.download`;return await j.writeFile(i,Buffer.from(await a.arrayBuffer())),await j.chmod(i,493),await j.move(i,o,{overwrite:!0}),o},$e=(e,t,s)=>{try{const n=new O(j.readFileSync(t)),o=_(j.readFileSync(e));return!!n.checkPrivateKey(o)&&(!(new Date(n.validTo).getTime()<=Date.now())&&s.every(e=>((e,t)=>W.isIP(t)?Boolean(e.checkIP(t)):Boolean(e.checkHost(t)))(n,e)))}catch{return!1}},ve=async(t,s={})=>{const n=s.log??(()=>{}),o=s.certDir??me,r=C.resolve(t,o),a=C.join(r,"localhost-key.pem"),i=C.join(r,"localhost.pem"),c=(e=>{const t=(e??"").trim();return t&&!ge.includes(t)?[...ge,t]:[...ge]})(s.host);try{if($e(a,i,c))return n(`Using existing local certificate from ${C.relative(t,r)||"."}`),{key:a,cert:i};const e=await(s.resolveMkcert??(()=>ye({log:n})))();if(await j.ensureDir(r),n("Generating a trusted local certificate with mkcert (this may prompt for your password once)..."),P(e,["-install","-key-file",a,"-cert-file",i,...c],{stdio:"inherit",shell:fe}),!(await j.pathExists(a))||!(await j.pathExists(i)))throw new Error("mkcert finished but the certificate files were not created");let l;await(async(e,t)=>{const s=C.join(e,".gitignore");if(!(await j.pathExists(s)))return!1;const n=await j.readFile(s,"utf8"),o=n.split(/\r?\n/).map(e=>e.trim()),r=new Set([t,`/${t}`,`${t}/`,`/${t}/`]);if(o.some(e=>r.has(e)))return!1;const a=0===n.length||n.endsWith("\n")?"":"\n";return await j.appendFile(s,`${a}${t}\n`),!0})(t,o.split(C.sep)[0]);try{const t=P(e,["-CAROOT"],{encoding:"utf8",shell:fe}).trim();t&&(l=C.join(t,"rootCA.pem"))}catch{}return n(`Certificates created in ${C.relative(t,r)||"."}`),{key:a,cert:i,...l?{rootCA:l}:{}}}catch(l){return e(l),n(`Failed to set up HTTPS certificates: ${l instanceof Error?l.message:String(l)}`),null}},be=["Using (vars|secrets) defined in ","\\(node:\\d+\\) MaxListenersExceededWarning:","\\(Use `node --trace-warnings","\\[DEP0205\\] DeprecationWarning:","\\(Use `node --trace-deprecation","Detected multiple renderers concurrently rendering the same context provider","\\[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"],ke=(e,t)=>t.length>0&&t.some(t=>t.test(e)),xe=(e,t)=>{let s="";return{write:o=>{const r="string"==typeof o?o:o.toString();s+=r;const a=s.split(/\r?\n/);s=a.pop()??"";for(const s of a){const o=s.trim();o?ke(o,t)?n(`Filtered: ${o}`):e.write(s+"\n"):n("Filtered: <empty line>")}},flush:()=>{const o=s.trim();if(o){if(ke(o,t))return n(`Filtered: ${o}`),void(s="");e.write(s),s=""}else s=""}}},Se=async(t,s={})=>{const o=C.join(t,"dashnex.json"),r=C.join(t,"package.json");if(n(`Checking for dashnex.json at: ${o}`),!(await j.pathExists(o)))throw new Error("Run this command in a DashNex Web application folder.");if(n("dashnex.json found, checking for package.json"),!(await j.pathExists(r)))throw new Error("package.json is missing.");let a;n("package.json found, checking for dev script");try{a=await j.readJson(r)}catch(h){throw e(h),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.');const i=((e,t=process.env)=>{const s=e.port??t.PORT;if(null==s||""===String(s).trim())return;const n=Number(s);if(!Number.isInteger(n)||n<1||n>65535)throw new Error(`Invalid port: ${s}. Use a number between 1 and 65535.`);return n})(s),c=((e,t=process.env)=>{const s=(e.host??t.HOST??"").trim();return""===s?void 0:s})(s);n("dev script found, checking for npm availability");const l=await(async e=>new Promise(t=>{const s=I(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>{t(!1)}),s.on("close",e=>{t(0===e)})}))("npm");if(n(`npm available: ${l}`),!l)throw new Error("npm is not available. Please install npm to continue.");const d={};if(s.https){const e=await ve(t,{host:c,log:e=>console.log(T.dim(e))});e?(d.DASHNEX_DEV_HTTPS_KEY=e.key,d.DASHNEX_DEV_HTTPS_CERT=e.cert,console.log(T.green("HTTPS enabled for the dev server"+(i?` on https://${c??"localhost"}:${i}`:""))),e.rootCA&&console.log(T.dim(`Local CA: ${e.rootCA} (import it in browsers on other machines, e.g. when the app runs in Docker)`))):console.log(T.yellow("HTTPS is not available, starting the dev server over HTTP instead."))}const p=[];void 0!==i&&p.push("--port",String(i)),void 0!==c&&p.push("--hostname",c);const u=p.length?["--",...p]:[];return n(`npm available, executing: npm run dev${u.length?` ${u.join(" ")}`:""} in ${t}`),(async(t,s=[],n=process.cwd(),o=[],r={})=>{const a=s.length?`${t} ${s.join(" ")}`:t,i=o.length>0;return new Promise((t,s)=>{const c=I(a,{stdio:i?["inherit","pipe","pipe"]:"inherit",cwd:n,shell:!0,env:{...process.env,NODE_ENV:"development",FORCE_COLOR:"1",...r}});if(c.on("error",t=>{e(t),s(t)}),i&&c.stdout&&c.stderr){const e=xe(process.stdout,o),s=xe(process.stderr,o);c.stdout.on("data",t=>e.write(t)),c.stderr.on("data",e=>s.write(e)),c.on("close",n=>{e.flush(),s.flush(),t(null===n?0:n)})}else c.on("close",e=>{t(null===e?0:e)})})})("npm run dev",u,t,(()=>{const e=[];for(const t of be)try{e.push(new RegExp(t))}catch{n(`Invalid dev output filter pattern ignored: ${t}`)}return e})(),d)},Ee=async e=>new Promise(t=>{const s=I(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>{t(!1)}),s.on("close",e=>{t(0===e)})}),De=async t=>{let s;if(await Ee("pnpm"))s="pnpm install --config.strict-dep-builds=false",n("Using package manager: pnpm");else{if(!(await Ee("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",n("Using package manager: npm (with --legacy-peer-deps for DashNex peer-dep overlap)")}return n(`Executing: ${s} in ${t}`),new Promise((n,o)=>{const r=[],a=[],i=I(s,{stdio:["ignore","pipe","pipe"],cwd:t,shell:!0,env:{...process.env,NPM_CONFIG_LOGLEVEL:"error"}});i.stdout&&i.stdout.on("data",e=>r.push(e)),i.stderr&&i.stderr.on("data",e=>a.push(e)),i.on("error",t=>{e(t),o(t)}),i.on("close",e=>{const t=null===e?0:e;0!==t&&(r.length&&process.stdout.write(Buffer.concat(r)),a.length&&process.stderr.write(Buffer.concat(a))),n(t)})})},Te="Run this command in a DashNex Web application folder.",je=e=>{const t=C.join(e,"dashnex.json");return j.pathExistsSync(t)},Ce=(e,t=!1)=>{t||console.log(T.cyan(e))},Ne=(t,s,o={})=>{const r=`${t} ${s.join(" ")}`,a=!0===o.silent;return new Promise((s,o)=>{n(`Running: ${r}`);const i=I(r,{stdio:a?["ignore","pipe","pipe"]:"inherit",cwd:process.cwd(),shell:!0});i.on("error",t=>{e(t),o(t)}),i.on("close",e=>{n(`${t} exited with code ${e}`),s(null===e?1:e)})})},Pe=(t,s)=>new Promise((o,r)=>{n(`Running: ${t} ${s.join(" ")}`);const a=I(t,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",t=>{e(t),r(t)}),a.on("close",e=>{n(`${t} exited with code ${e}`),o({exitCode:null===e?1:e,output:i})})}),Ie=async t=>{n("Running check: install");try{return 0===await De(process.cwd())}catch(s){return e(s),!t&&s instanceof Error&&console.error(T.red(s.message)),!1}},Ae=async()=>{try{const{output:e}=await Pe(process.execPath,[process.argv[1],"db","migrate","--help"]);return e.includes("Usage: dashnex db migrate")}catch(t){return e(t),!1}},Fe=async t=>{n("Running check: db migrate");try{const{exitCode:e,output:s}=await Pe(process.execPath,[process.argv[1],"db","migrate"]);return 0===e||(s.includes("Unknown command")?(n("db migrate command is not available, skipping"),!0):(!t&&s.trim().length>0&&process.stderr.write(s),!1))}catch(s){return e(s),!0}},Re=e=>new Promise(t=>{const s=I(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>t(!1)),s.on("close",e=>t(0===e))}),Oe=[{name:"TypeScript",command:"npx",args:["tsc","--noEmit"],notFoundMessage:"TypeScript is not available. Please install it with: npm install -D typescript"}],Be=class{async execute(){n("Check flow started"),je(process.cwd())||(console.error(T.red(Te)),t(1)),Ce("Checking dependencies..."),await Ie(!1)||(console.error(T.red("Check failed.")),t(1)),n(`Running ${Oe.length} check(s)`);for(const o of Oe){n(`Running check: ${o.name}`),Ce(`Checking ${o.name}...`),await Re(o.command)||(console.error(T.red(o.notFoundMessage)),t(1));try{0!==await Ne(o.command,o.args)&&(console.error(T.red("Check failed.")),t(1))}catch(s){if(s instanceof Error&&s.message.startsWith("EXIT:"))throw s;e(s),console.error(T.red(o.notFoundMessage)),t(1)}}await Ae()?(Ce("Checking database migrations..."),await Fe(!1)||(console.error(T.red("Check failed.")),t(1))):n("db migrate command is not available, skipping"),console.log(T.green("All checks passed."))}async run(t=!1){if(n("Running checks (called from push)"),!je(process.cwd()))return t||console.error(T.red(Te)),!1;if(Ce("Checking dependencies...",t),!(await Ie(t)))return!1;const s=t?{silent:!0}:void 0;for(const r of Oe){if(n(`Running check: ${r.name}`),Ce(`Checking ${r.name}...`,t),!(await Re(r.command)))return console.error(T.red(r.notFoundMessage)),!1;try{if(0!==await Ne(r.command,r.args,s))return!1}catch(o){return e(o),console.error(T.red(r.notFoundMessage)),!1}}if(await Ae()){if(Ce("Checking database migrations...",t),!(await Fe(t)))return!1}else n("db migrate command is not available, skipping");return t||console.log(T.green("All checks passed.")),!0}},_e=" │ ",ze=e=>e.subarray(0,8192).includes(0),We=e=>{const t=e.split("\n");return""===t[t.length-1]&&t.pop(),t},Le=(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))}…`},Me=(e,t,s)=>{const n=Math.max(s??process.stdout.columns??120,43),o=Math.floor((n-3)/2),r=((e,t)=>{const s=[],n=U(e,t);for(let o=0;o<n.length;o+=1){const e=n[o];if(e.removed){const t=We(e.value),r=n[o+1],a=r?.added?We(r.value):[];r?.added&&(o+=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 We(e.value))s.push({left:null,right:t,changed:!0});else for(const t of We(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(T.bold(Le("local (current)",o))+T.dim(_e)+T.bold("incoming"));let c=-1,l=0,d=0;for(let p=0;p<r.length;p+=1){if(!a.has(p))continue;if(l>=200){d+=1;continue}-1!==c&&p>c+1&&i.push(T.dim("···")),c=p,l+=1;const e=r[p],t=Le(e.left,o),s=Le(e.right,o);if(!e.changed){i.push(T.dim(t)+T.dim(_e)+T.dim(s));continue}const n=null!==e.left?T.red(t):t,u=null!==e.right?T.green(s):s;i.push(n+T.dim(_e)+u)}return d>0&&i.push(T.dim(`… ${d} more diff line(s) not shown`)),i.join("\n")},Ue=[".dashnex",".git",".vinext",".wrangler","wrangler.jsonc","wrangler.toml",".dev.vars",".github"],Xe=[".env","wrangler.jsonc"],He=e=>C.join(e,y,"sync.json"),Je=e=>B("sha1").update(`blob ${e.length}\0`).update(e).digest("hex"),Ge=async e=>{const t=X();t.add(Ue);const s=C.join(e,".gitignore");return await j.pathExists(s)&&t.add(await j.readFile(s,"utf8")),t},qe=e=>e.split(C.sep).join("/"),Ye=e=>Ue.some(t=>e===t||e.startsWith(`${t}/`)),Ve=async(e,t={})=>{const s={},n=await(async e=>{const t=await Ge(e),s=[],n=async o=>{const r=await j.readdir(o,{withFileTypes:!0});for(const a of r){const r=C.join(o,a.name),i=qe(C.relative(e,r));Ye(i)||t.ignores(a.isDirectory()?`${i}/`:i)||(a.isDirectory()?await n(r):a.isFile()&&s.push(i))}};return await n(e),s})(e);for(const o of n)s[o]=Je(await j.readFile(C.join(e,o)));if(t.includeGenerated)for(const o of Xe){if(o in s)continue;const t=C.join(e,o);(await j.lstat(t).catch(()=>null))?.isFile()&&(s[o]=Je(await j.readFile(t)))}return s},Ke=async e=>{try{const t=await j.readFile(He(e),"utf8"),s=JSON.parse(t);return"string"!=typeof s?.commit||"object"!=typeof s?.manifest||null===s.manifest?null:s}catch{return null}},Ze=async(e,t,s)=>{const o={commit:t,manifest:s,updatedAt:/* @__PURE__ */(new Date).toISOString()},r=He(e);try{await j.ensureDir(C.dirname(r)),await j.writeFile(r,`${JSON.stringify(o,null,2)}\n`),n(`Sync state written: commit ${t}, ${Object.keys(s).length} files`)}catch(a){n(`Failed to write sync state: ${a instanceof Error?a.message:"unknown"}`)}},Qe=1048576,et=async(t,s)=>{const{install:o}=await R.prompt([{type:"confirm",name:"install",message:"Install dependencies?",default:!0}]);if(!o){if(C.resolve(t)!==C.resolve(s)){const e=C.relative(s,t);console.log(T.cyan(`Run "cd ${e}" to change to the application folder.`))}return}try{const e=ie();e.start("Installing dependencies...");try{const s=await De(t);if(e.stop(),0!==s)return void n(`install exited with code ${s}`)}catch(i){throw e.stop(),i}}catch(i){return e(i),void console.error(T.red(i instanceof Error?i.message:"Failed to run install."))}const{migrate:r}=await R.prompt([{type:"confirm",name:"migrate",message:"Create or update database?",default:!0}]);if(!r)return;n(`Running dashnex db migrate in ${t}`);try{const s=ie();s.start("Creating or updating database...");try{const o=await((t,s,n)=>{const o=`${C.join(t,"node_modules",".bin")}${C.delimiter}${process.env.PATH??""}`,r={...process.env,PATH:o};return new Promise((o,a)=>{const i=I(s,{cwd:t,shell:!0,stdio:"inherit",env:n?{...r,...n}:r});i.on("error",t=>{e(t),a(t)}),i.on("close",e=>{o(null===e?0:e)})})})(t,"dashnex db migrate");if(s.stop(),0!==o)return void n(`dashnex db migrate exited with code ${o}`)}catch(i){throw s.stop(),i}}catch(i){return e(i),void console.error(T.red("Failed to run dashnex db migrate."))}const{dev:a}=await R.prompt([{type:"confirm",name:"dev",message:"Run development server?",default:!0}]);if(a)try{await Se(t)}catch(i){e(i),console.error(T.red(i instanceof Error?i.message:"Failed to run dev server."))}},tt=(e,t)=>{if(e.length!==t.length)return`local ${e.length} bytes, incoming ${t.length} bytes`;const s=e.length;for(let n=0;n<s;n+=1)if(e[n]!==t[n]){return`size ${s} matches; first diff at byte ${n} (local=0x${e[n].toString(16).padStart(2,"0")} incoming=0x${t[n].toString(16).padStart(2,"0")})`}return`size ${s} matches; no byte difference (unexpected)`},st=async(e,t)=>{let s;try{s=await j.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 n=await j.readFile(e);return 0===Buffer.compare(n,t)?{kind:"identical"}:{kind:"different",reason:tt(n,t)}},nt=async(t,s,n)=>{console.log(`\n${T.bold(s)}`);try{const e=await j.readFile(t);if(e.length>Qe||n.length>Qe||ze(e)||ze(n))return void console.log(T.dim(`(no preview: ${tt(e,n)})`));console.log(Me(e.toString("utf8"),n.toString("utf8")))}catch(o){e(o),console.log(T.dim("(no preview available)"))}},ot=async e=>{const{choice:t}=await R.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},rt=async(e,t)=>{const s=t?T.yellow(" (has local changes!)"):"",{choice:n}=await R.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 n},at=async(e,t)=>{let s=C.dirname(e);const n=C.resolve(t);for(;C.resolve(s)!==n;)try{if((await j.readdir(s)).length>0)return;await j.rmdir(s),s=C.dirname(s)}catch{return}},it=(e,t)=>C.resolve(e)===C.resolve(t)?"Application is successfully pulled.":`Application is successfully pulled into ${C.relative(t,e)}.`,ct=class{async execute(o={}){n("Pull flow started");const a=await r();if(!a)return;const i=process.cwd();let c;if(o.folder)c=o.folder.trim()||".",n(`Folder argument provided: ${c}`);else{n("No folder argument, prompting user");const{folder:e}=await R.prompt([{type:"input",name:"folder",message:"Which folder to pull the application to?",default:"."}]);c=e.trim()||"."}const l=C.resolve(i,c);n(`Target folder resolved: ${l}`),await b(a,{projectDir:l});try{const e=await j.lstat(l).catch(()=>null);e&&!e.isDirectory()&&(console.error(T.red(`Cannot pull into ${l}: path exists and is not a directory.`)),t(1)),await j.ensureDir(l),n(`Target folder ensured: ${l}`)}catch(u){if(u instanceof Error&&u.message.startsWith("EXIT:"))throw u;e(u);const s=u instanceof Error?u.message:"Unknown error";console.error(T.red(`Cannot create folder ${l}: ${s}`)),t(1)}const d=C.join(L.tmpdir(),`dashnex-pull-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),p=ie();p.start("Analyzing local files...");try{const s=await Ke(l),r=await Ve(l,{includeGenerated:!0});n(`Local manifest has ${Object.keys(r).length} files`),p.text("Pulling application...");const c=await this.download(a.token,r);p.text("Downloading..."),await j.writeFile(d,c.buffer),n(`Zip written to temp file (${c.viaV2?"v2 diff":"legacy full"} pull)`),p.text("Extracting...");const h=new M(d).getEntries().filter(e=>!e.isDirectory);let m=null;const g=h.find(e=>".dashnex/pull.json"===e.entryName);if(g)try{m=JSON.parse(g.getData().toString("utf8"))}catch(u){e(u)}const f=h.filter(e=>".dashnex"!==e.entryName&&!e.entryName.startsWith(".dashnex/"));n(`Zip has ${f.length} file entries${m?`, meta commit ${m.commit}`:", no meta"}`);const w=o.yes||"1"===process.env.DASHNEX_CI;let y=w?"all":"prompt",$=!1,v=0,b=0,k=0,x=0,S=0;const E=async(t,s,n)=>{try{return await j.ensureDir(C.dirname(t)),await j.writeFile(t,s),n&&await j.chmod(t,n),!0}catch(u){return e(u),!1}};for(const e of f){const t=e.getData(),s=C.join(l,e.entryName),o=C.relative(l,s)||e.entryName,r=(e.header.attr??0)>>16&4095,a=await st(s,t);if(n(`Entry ${e.entryName}: ${a.kind}${a.reason?` (${a.reason})`:""}`),"identical"===a.kind){x+=1;continue}if("new"===a.kind){await E(s,t,r)?v+=1:S+=1;continue}let i=!1;if("all"===y)i=!0;else if("none"===y)i=!1;else{p.stop(),await nt(s,o,t),$||(console.log(T.dim("Y = yes (default), n = skip, a = overwrite all, s = skip all, h = help")),$=!0);const r=await ot(o);n(`Entry ${e.entryName}: user chose ${r}`),"yes"===r?i=!0:"no"===r?i=!1:"all"===r?(y="all",i=!0):(y="none",i=!1),p.start("Extracting...")}i?await E(s,t,r)?b+=1:S+=1:k+=1}p.stop();let D=0,N=0;if(m&&m.deleted.length>0){const e=await this.applyDeletions(l,m.deleted,s,w);D=e.deleted,N=e.kept}m&&(x+=Math.max(0,Object.keys(m.manifest).length-f.length)),n(`Pull summary: ${v} new, ${b} overwritten, ${k} skipped, ${D} deleted, ${x} unchanged, ${S} failed`);const P=[`${v} new`,`${b} overwritten`,`${k} skipped`,`${x} unchanged`];if((D>0||N>0)&&P.splice(3,0,`${D} deleted`),S>0&&P.push(`${S} failed`),console.log(T.cyan(`Pulled: ${P.join(", ")}`)),m){const e=await Ve(l,{includeGenerated:!0});await Ze(l,m.commit,e)}C.resolve(l)!==C.resolve(i)?(console.log(T.green(it(l,i))),process.chdir(l),n(`Changed working directory to ${l}`)):console.log(T.green(it(l,i))),S>0&&(console.error(T.red(`${S} file(s) failed to write. See DEBUG output for details.`)),t(1)),w?n("Non-interactive mode (--yes or --ci), skipping post-pull child commands"):await et(l,i)}catch(u){if(p.stop(),e(u),u instanceof Error&&u.message.startsWith("EXIT:"))throw u;if(h(u))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}finally{await j.remove(d).catch(()=>{}),n("Temp zip removed")}}async download(e,t){const s=`${o()}/business/v1/cli/v2/pull`;n(`POST ${s}`);const r=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:t})});if(n(`v2 pull response: ${r.status}`),r.ok)return{buffer:Buffer.from(await r.arrayBuffer()),viaV2:!0};const a=await r.json().catch(()=>({}));var i,c;i=r.status,c=a,404===i&&"string"==typeof c.message&&c.message.startsWith("Cannot ")||this.failFromResponse(r.status,a),n("v2 pull endpoint unavailable, falling back to legacy pull");const l=`${o()}/business/v1/cli/pull`;n(`GET ${l}`);const d=await fetch(l,{headers:{Authorization:`Bearer ${e}`}});if(n(`Legacy pull response: ${d.status}`),!d.ok){const e=await d.json().catch(()=>({}));this.failFromResponse(d.status,e)}return{buffer:Buffer.from(await d.arrayBuffer()),viaV2:!1}}failFromResponse(e,s){let n="Failed to pull application.";if(401===e||403===e)n="Please run 'dashnex login' to authenticate.";else if(404===e)n="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)(s);e&&(n=e)}console.error(T.red(n)),t(1)}async applyDeletions(t,s,o,r){let a=0,i=0;if(!o){const e=s.slice(0,20);console.log(T.yellow("These local files do not exist in the application (kept — no sync state yet):"));for(const t of e)console.log(T.yellow(` ${t}`));return s.length>e.length&&console.log(T.yellow(` … and ${s.length-e.length} more`)),{deleted:a,kept:s.length}}let c=r?"all":"prompt";for(const d of s){if(!(d in o.manifest)){n(`Deletion candidate ${d} was never synced, keeping`);continue}const s=C.join(t,d),r=await j.readFile(s).catch(()=>null);if(null===r)continue;const p=Je(r)!==o.manifest[d];let u=!1;if("all"===c)u=!0;else if("none"===c)u=!1;else{const e=await rt(d,p);n(`Deletion ${d}: 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 j.remove(s),await at(s,t),a+=1}catch(l){e(l),i+=1}else i+=1}return{deleted:a,kept:i}}},lt=async e=>{const t=`${o()}/business/v1/agreements/payment-processing/status`;n(`GET ${t}`);const s=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});if(n(`Payment agreement response: ${s.status}`),!s.ok)return!0;if((await s.json().catch(()=>({}))).hasAccepted)return!0;const r=`${await(async()=>x())()}/money/agreement/`;return console.error(T.red(`You need to accept Master Payment Processing Agreement first by visiting this link: ${r}`)),!1},dt=async(t,s={})=>{const r=s.ciMode??!1;return!!(await lt(t))&&!!(await(async(t,s)=>{const r=`${o()}/business/v1/tos/latest`;n(`GET ${r}`);const a=await fetch(r,{headers:{Authorization:`Bearer ${t}`}});if(n(`TOS latest response: ${a.status}`),a.ok)return!0;if(404!==a.status)return!0;const i=`${o()}/business/v1/tos/current`;n(`GET ${i}`);const c=await fetch(i,{headers:{Authorization:`Bearer ${t}`}});if(n(`TOS current response: ${c.status}`),!c.ok)return n("Could not fetch current TOS, skipping check"),!0;const l=await c.json().catch(()=>({})),d=l.version??"unknown";if(l.text&&(console.log(T.dim("─".repeat(60))),console.log(T.bold(`Terms of Service ${d}`)),console.log(T.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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/\n{3,}/g,"\n\n").trim()),console.log(T.dim("─".repeat(60)))),s)return console.log(T.yellow(`By proceeding you accept the Terms of Service ${d}.`)),!0;const{accept:p}=await R.prompt([{type:"confirm",name:"accept",message:`By creating an application you accept the Terms of Service ${d}. Continue?`,default:!0}]);if(!p)return console.log(T.yellow("Cancelled.")),!1;try{const e=`${o()}/business/v1/tos/${l.id}/accept`;n(`POST ${e}`),await fetch(e,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch(u){e(u)}return!0})(t,r))},pt=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,ut=e=>new Promise(t=>setTimeout(t,e)),ht=e=>e.appFullCustomDomain?e.appFullCustomDomain:e.subdomain?"qa"===(process.env.APPLICATION_ENV??"")?`https://${e.subdomain}.dashnex.dev`:`https://${e.subdomain}.dashnexcloud.com`:null,mt=3e5,gt=99,ft=e=>new Promise(t=>setTimeout(t,e)),wt=async(t,s,o,r)=>{const a=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${s}`,Accept:"text/event-stream"}});if(n(`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(T.red(t)),new Error(`HTTP ${e}: ${t}`)}if(!a.body)throw new Error("Response body is null");n("SSE connection established successfully"),r?.();const i=a.body.getReader();try{for await(const t of async function*(e){const t=new TextDecoder("utf-8");let s="";for(;;){const{value:n,done:o}=await e.read();if(o)break;s+=t.decode(n,{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(!t.data){n("Received empty SSE event");continue}const e=JSON.parse(t.data);n(`SSE message received: ${JSON.stringify(e)}`),o(e)}catch(c){e(c),n(`Failed to parse SSE event data: ${t.data}`)}}finally{i.releaseLock()}},yt=class{async execute(){n("Deploy flow started");const o=await r();if(!o)return;if(await b(o,{checkApplication:!0}),!(await dt(o.token,{ciMode:!0})))return;const i=`${a()}/business/v1/applications/deploy`;n(`GET ${i} (SSE)`);let c=0,l="",d=!1,p=0,u=!1;const m=ie();let g=0,f=0,w=null;const y=(e,t)=>{const s=Math.round(e);m.text(`[${s}%] ${t}`)},$=()=>{v();const e=c,t=Date.now(),s=mt*((gt-e)/gt);w=setInterval(()=>{const n=Date.now()-t;let o;if(f>t){const e=Date.now()-f,t=gt-g,s=3030.3030303030305*t;o=Math.min(g+e/s*t,gt)}else o=Math.min(e+n/s*(gt-e),gt);o>c&&(c=o,y(c,l))},200)},v=()=>{w&&(clearInterval(w),w=null)};let k=!1;const x=e=>{if(u=!0,"string"==typeof e.error)return v(),m.stop(),console.error(T.red(e.error)),d=!0,void(k=!0);"string"==typeof e.message&&(l=e.message),"number"==typeof e.progress&&(g=e.progress,f=Date.now(),e.progress>c&&(c=e.progress)),"string"!=typeof e.message&&"number"!=typeof e.progress||(c>=100?(v(),m.stop(),d=!0):y(c,l))};for(;p<=5;)try{return u?y(c,l):m.start("Connecting..."),$(),await wt(i,o.token,x,()=>{u||(m.text(`[${Math.round(c)}%] Deployment in progress...`),l="Deployment in progress...")}),v(),m.stop(),n("SSE connection closed"),k&&t(1),void(d&&await this.showDeployedUrl(o.token))}catch(S){if(v(),S instanceof Error&&S.message.startsWith("EXIT:"))throw S;if(e(S),n(`SSE connection error: ${S}`),d)return m.stop(),void(k&&t(1));if(h(S))return m.stop(),void console.log(T.yellow(s));S instanceof Error&&S.message.startsWith("HTTP")&&(m.stop(),console.error(T.red("Could not complete deployment. Check your connection and try again.")),t(1)),p++,p>5&&(m.stop(),console.error(T.red("Deployment failed. Maximum reconnection attempts exceeded.")),t(1));const o=Math.min(1e3*Math.pow(2,p-1),3e4);n(`Connection error. Reconnecting in ${o/1e3}s... (attempt ${p}/5)`),await ft(o)}}async showDeployedUrl(t){try{const e=`${o()}/business/v1/applications`;n(`GET ${e} (for deployed URL)`);const s=await fetch(e,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok)return;const r=await s.json().catch(()=>({})),a=ht({subdomain:r.subdomain,appFullCustomDomain:r.appFullCustomDomain});a&&console.log(`Application is deployed to ${T.cyan(a)}`)}catch(s){e(s)}}},$t=104857600,vt=class extends Error{},bt=class extends Error{},kt=class extends Error{},xt="/business/v1/cli/tail-token";async function St(e,t={}){const s=`${o()}${xt}${t.debug?"?debug=1":""}`;try{await fetch(s,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})}catch{}}var Et=["log","info","warn","error","debug"],Dt={error:4,warn:3,log:2,info:2,debug:1};function Tt(e){return"string"==typeof e&&Et.includes(e)}function jt(e){return e.map(e=>"string"==typeof e?e:function(e){try{return JSON.stringify(e)}catch{return String(e)}}(e)).join(" ")}function Ct(e){return e<10?`0${e}`:String(e)}function Nt(e){const t=new Date(e);return`${Ct(t.getHours())}:${Ct(t.getMinutes())}:${Ct(t.getSeconds())}.${s=t.getMilliseconds(),s<10?`00${s}`:s<100?`0${s}`:String(s)}`;var s}function Pt(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 G(e,{colors:t,depth:2,breakLength:120})}var It={error:e=>T.red(e),warn:e=>T.yellow(e),debug:e=>T.dim(e),log:e=>e,info:e=>e};function At(e,t){const s=t.color?T.dim(Nt(e.ts)):Nt(e.ts),n=e.level.toUpperCase().padEnd(5),o=[s,t.color?It[e.level](n):n];o.push(e.args.map(e=>Pt(e,t.color)).join(" "));let r=o.join(" ");if(e.truncated){const e=" …(truncated)";r+=t.color?T.dim(e):e}return r}function Ft(e,t,s){let n;try{n=JSON.parse(e)}catch{return{kind:"malformed",raw:e}}if("object"!=typeof n||null===n||!Tt(n.level))return{kind:"malformed",raw:e};const o=n;return Array.isArray(o.args)||(o.args=void 0===o.args?[]:[o.args]),r=o.level,a=t.minLevel,Dt[r]>=Dt[a]&&function(e,t){return!t||t.test(jt(e.args))}(o,t.filter)?{kind:"line",line:At(o,s)}:{kind:"filtered"};var r,a}var Rt=new Set([4401,4403]);var Ot=[{label:"node_modules",segments:["node_modules"],description:"installed dependencies"},{label:"node_modules/.vite",segments:["node_modules",".vite"],description:"vite cache"},{label:"node_modules/.vite-temp",segments:["node_modules",".vite-temp"],description:"vite cache"},{label:"src/dashnex",segments:["src","dashnex"],description:"generated module registry"},{label:"dist",segments:["dist"],description:"build output"}],Bt={label:".wrangler",segments:[".wrangler"],description:"local database"},_t=async e=>{await q(e,{recursive:!0,force:!0,maxRetries:5,retryDelay:100})},zt={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(t,s,o=5e3,r=6e4){const a=Date.now();let i=0;for(;Date.now()-a<r;){i++,n(`Polling application status (attempt ${i})...`);try{const e=await fetch(t,{headers:{Authorization:`Bearer ${s}`}});if(n(`Poll response: ${e.status}`),200===e.status){const t=await e.json();if(n(`Poll response body status: ${t.status}`),"creating"!==t.status)return n(`Application status is "${t.status}", creation complete`),{ready:!0,status:t.status};n('Application status is still "creating", continuing to poll...')}}catch(c){e(c),n(`Poll attempt ${i} failed with network error`)}await ut(o)}return{ready:!1}}async execute(a={}){n("Create flow started");const i=await r();if(!i)return;n("Auth valid, checking if business already has application");const c=ie(),l=`${o()}/business/v1/applications`;n(`GET ${l}`),c.start("Checking application status...");try{const e=await fetch(l,{headers:{Authorization:`Bearer ${i.token}`}});c.stop(),n(`Applications response: ${e.status}`),n(`Applications response body: ${await e.text()}`),404!==e.status&&(console.error(T.red("Business already has an application. Run 'dashnex app pull' to pull the existing one.")),t(1))}catch(y){if(c.stop(),e(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(h(y))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}n("No existing application, checking agreements");const d=void 0!==a.subdomain;if(!(await dt(i.token,{ciMode:d})))return;let p;n("Agreements checked, proceeding to subdomain prompt");const u=e=>`${o()}/business/v1/applications/check-subdomain?subdomain=${encodeURIComponent(e)}`;let m=a.subdomain?.trim();for(;;){if(m)p=m,m=void 0,n(`Subdomain provided via flag: ${p}`);else{if(d)return console.error(T.red("Subdomain is not available.")),void t(1);{const{sub:e}=await R.prompt([{type:"input",name:"sub",message:"Pick your subdomain:",validate:e=>!!e.trim()||"Subdomain is required"}]);p=e.trim()}}n(`Checking subdomain: ${p}`);const o=u(p);n(`GET ${o}`),c.start("Checking subdomain...");try{const e=await fetch(o,{headers:{Authorization:`Bearer ${i.token}`}});c.stop(),n(`Check subdomain response: ${e.status}`);const s=await e.text();if(n(`Check subdomain response body: ${s}`),!e.ok){const o=e.headers.get("content-type")??"";let r="Failed to check subdomain availability.";if(401!==e.status&&403!==e.status||(r="Please run 'dashnex login' to authenticate.",console.error(T.red(r)),t(1)),o.includes("application/json")){const e=JSON.parse(s);n(`Check subdomain error body: ${JSON.stringify(e)}`);const t=pt(e);t&&(r=t)}console.error(T.red(r));continue}const r=JSON.parse(s);if(n(`Check subdomain parsed body: ${JSON.stringify(r)}`),r.available){n(`Subdomain ${p} is available`);break}console.error(T.red("Subdomain is not available. Please choose a different one."))}catch(y){if(c.stop(),e(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(h(y))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}}const g=`${o()}/business/v1/cli/create`;n(`POST ${g}`);const f={subdomain:p};a.template&&(f.template=a.template,n(`Template: ${a.template}`));const w=JSON.stringify(f);n(`Create request body: ${w}`),c.start("Creating application...");try{const r=await fetch(g,{method:"POST",headers:{Authorization:`Bearer ${i.token}`,"Content-Type":"application/json"},body:w});c.stop(),n(`Create response: ${r.status}`);const l=await r.text();if(n(`Create response body: ${l}`),503===r.status){n("Create returned 503, polling for application creation..."),c.start("Waiting for application to be ready...");const e=`${o()}/business/v1/applications`,s=await this.pollApplicationCreated(e,i.token);c.stop(),s.ready||(console.error(T.red("Application creation is taking longer than expected. Try again later or run 'dashnex app pull' to check.")),t(1)),"failed"===s.status&&(console.error(T.red("Application creation failed. Please try again.")),t(1)),n("Application found after polling")}else if(!r.ok){const e=r.headers.get("content-type")??"";let s="Failed to create application.";if(401===r.status||403===r.status)s="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=JSON.parse(l);n(`Create error body parsed: ${JSON.stringify(e)}`);const t=pt(e);t&&(s=t)}console.error(T.red(s)),t(1)}let p;if(n("Application created successfully"),!0===a.pull?(p=!0,n("--pull flag set, pulling without prompting")):!1===a.pull?(p=!1,n("--no-pull flag set, skipping pull")):d?(p=!1,n("CI mode (--subdomain), skipping pull")):(p=(await R.prompt([{type:"confirm",name:"pull",message:"Pull the application locally?",default:!0}])).pull,n(`User chose to pull: ${p}`)),p){n("Running pull flow");try{await(new ct).execute()}catch(y){if(e(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(h(y))return void console.log(T.yellow(s));console.error(T.red("Failed to pull application."))}}else console.log(T.green("Application is created successfully. Run 'dashnex app pull' to pull it to your computer or 'dashnex app deploy' to deploy it to the cloud."))}catch(y){if(c.stop(),e(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(h(y))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(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 ct,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(o={}){n("Push flow started"),await j.pathExists(C.join(process.cwd(),"dashnex.json"))||(console.error(T.red("Not a DashNex application folder (dashnex.json not found).")),console.error(T.red("Run this command from your application root.")),t(1)),!1!==o.check?(n("Running pre-push checks"),await(new Be).run(!1)||(console.error(T.red("Push aborted: checks failed. Re-run with --no-check to skip.")),t(1))):n("Skipping pre-push checks (--no-check)");const a=await r();if(!a)return;await b(a,{checkApplication:!0});const i=process.cwd(),c=ie();try{c.start("Analyzing local files...");const e=await Ke(i),t=await Ve(i);n(`Local manifest has ${Object.keys(t).length} files`),c.text("Comparing with remote...");const s=await this.requestPlan(a.token,t,e?.commit);c.stop(),"legacy"===s?(n("v2 push endpoints unavailable, falling back to legacy zip push"),await this.pushLegacy(a.token,i,c)):await this.pushDiff(a.token,i,t,s,o,c),await this.promptAndDeploy(o)}catch(l){if(c.stop(),e(l),l instanceof Error&&l.message.startsWith("EXIT:"))throw l;if(h(l))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}}async requestPlan(e,t,s){const r=`${o()}/business/v1/cli/v2/push/plan`;n(`POST ${r}`);const a=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:t,lastSyncCommit:s})});if(n(`Plan response: ${a.status}`),a.ok)return await a.json();const i=await a.json().catch(()=>({}));if(((e,t)=>404===e&&"string"==typeof t.message&&t.message.startsWith("Cannot "))(a.status,i))return"legacy";this.failFromResponse(a.status,i,"Failed to push application.")}async pushDiff(e,s,o,r,a,i){let c=r;if(c.remoteChanged.length>0&&!a.force){console.error(T.red("Remote application has changes you don't have locally:"));for(const e of c.remoteChanged.slice(0,20))console.error(T.red(` ${e}`));c.remoteChanged.length>20&&console.error(T.red(` … and ${c.remoteChanged.length-20} more`)),console.error(T.red("Run 'dashnex app pull' first, or push anyway with --force.")),t(1)}const l=c.upload.filter(e=>e in o),d=await Ge(s);let p=c.delete.filter(e=>!d.ignores(e));if(0!==l.length||0!==p.length){if(p.length>0){const e=await Ke(s),t=a.yes||"1"===process.env.DASHNEX_CI;console.log(T.yellow(`${p.length} file(s) will be deleted from the application repository:`));for(const s of p.slice(0,20))console.log(T.yellow(` ${s}`));if(p.length>20&&console.log(T.yellow(` … and ${p.length-20} more`)),!t){const{confirmDelete:t}=await R.prompt([{type:"confirm",name:"confirmDelete",message:"Delete these files from the remote repository?",default:null!==e}]);t||(n("User declined remote deletions, pushing without them"),p=[])}}if(0!==l.length||0!==p.length)for(let r=1;;r+=1){i.start(1===r?"Uploading changes...":"Remote changed, retrying...");const d=await this.applyPush(e,s,l,p,c.baseCommit);if(i.stop(),"ok"===d.status){await Ze(s,d.commit,o);const e=[`${l.length} file(s) updated`];return p.length>0&&e.push(`${p.length} deleted`),console.log(T.cyan(`Pushed: ${e.join(", ")}`)),void console.log(T.green("Application pushed successfully."))}r>=2&&(console.error(T.red("Remote repository keeps changing, please retry the push.")),t(1)),n("Push apply conflicted, re-planning");const u=await Ke(s),h=await this.requestPlan(e,o,u?.commit);"legacy"===h&&(console.error(T.red("Failed to push application.")),t(1)),h.remoteChanged.length>0&&!a.force&&(console.error(T.red("Remote application changed during the push. Run 'dashnex app pull' first, or push with --force.")),t(1)),c=h}else console.log(T.green("Everything up to date."))}else console.log(T.green("Everything up to date."))}async applyPush(e,t,s,r,a){const i=new M;for(const n of s){const e=C.join(t,...n.split("/")),s=C.posix.dirname(n);i.addLocalFile(e,"."===s?"":s,C.posix.basename(n))}const c=C.join(L.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{i.writeZip(c),n(`Diff zip written to ${c} (${s.length} files, ${r.length} deletions)`),await this.ensureZipWithinLimit(c);const t=`${o()}/business/v1/cli/v2/push/apply`;n(`POST ${t}`);const l=await j.readFile(c),d=new FormData;d.append("file",new Blob([l],{type:"application/zip"}),"diff.zip"),d.append("baseCommit",a),d.append("deletions",JSON.stringify(r));const p=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:d});if(n(`Apply response: ${p.status}`),409===p.status)return{status:"conflict"};if(!p.ok){const e=await p.json().catch(()=>({}));this.failFromResponse(p.status,e,"Failed to push application.")}return{status:"ok",commit:(await p.json().catch(()=>({}))).commit??""}}finally{await j.remove(c).catch(()=>{})}}async pushLegacy(e,t,s){const r=await Ve(t),a=Object.keys(r);n(`Legacy push including ${a.length} files`);const i=new M;for(const n of a){const e=C.join(t,...n.split("/")),s=C.posix.dirname(n);i.addLocalFile(e,"."===s?"":s,C.posix.basename(n))}const c=C.join(L.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{s.start("Packaging application..."),i.writeZip(c),n(`Zip written to ${c}`),await this.ensureZipWithinLimit(c);const t=`${o()}/business/v1/cli/push`;n(`POST ${t}`);const r=await j.readFile(c),a=new FormData;a.append("file",new Blob([r],{type:"application/zip"}),"archive.zip"),s.text("Uploading...");const l=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:a});if(s.stop(),n(`Response: ${l.status}`),!l.ok){const e=await l.json().catch(()=>({}));this.failFromResponse(l.status,e,"Failed to push application.")}console.log(T.green("Application pushed successfully."))}finally{await j.remove(c).catch(()=>{}),n("Temp zip removed")}}async ensureZipWithinLimit(e){const{size:s}=await j.stat(e);if(s>$t){const e=e=>(e/1048576).toFixed(1);console.error(T.red(`Push package is ${e(s)} MB — the maximum is ${e($t)} MB.`)),console.error(T.red("Remove or .gitignore large files and try again.")),t(1)}}failFromResponse(e,s,n){let o=n;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)(s);e&&(o=e)}console.error(T.red(o)),t(1)}async promptAndDeploy(e){let t;void 0!==e.deploy?(t=e.deploy,n(`Deploy decided via flag: ${t}`)):"1"===process.env.DASHNEX_CI?(t=!1,n("CI mode: skipping deploy prompt (use --deploy to deploy)")):(t=(await R.prompt([{type:"confirm",name:"deploy",message:"Deploy the application?",default:!0}])).deploy,n(`User chose to deploy: ${t}`)),t&&(n("Running deploy flow"),await(new yt).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(a={}){if(n("Delete flow started"),!a.yes){const{confirm:e}=await R.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 n("User cancelled deletion"),void console.log(T.yellow("Deletion cancelled."))}const i=await r();if(!i)return;await b(i,{checkApplication:!0});const c=`${o()}/business/v1/applications`;n(`DELETE ${c}`);const l=ie();l.start("Deleting application...");try{const e=await fetch(c,{method:"DELETE",headers:{Authorization:`Bearer ${i.token}`}});if(l.stop(),n(`Response: ${e.status}`),!e.ok){const s=e.headers.get("content-type")??"";let n="Failed to delete application.";if(401===e.status||403===e.status)n="Please run 'dashnex login' to authenticate.";else if(s.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&&(n=t)}console.error(T.red(n)),t(1)}const s=await e.json().catch(()=>({})),o="string"==typeof s.message?s.message:"Application deleted successfully.";n("Application deleted successfully"),console.log(T.green(o))}catch(d){if(l.stop(),e(d),d instanceof Error&&d.message.startsWith("EXIT:"))throw d;if(h(d))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}}},options:[{flags:"-y, --yes",description:"Skip confirmation prompt"}]},{name:"deploy",description:"Deploy application to DashNex",handler:new yt,options:[]},{name:"status",description:"Show current application status",handler:new class{async execute(){n("Status flow started");const a=await r();if(!a)return;const i=`${o()}/business/v1/applications`;n(`GET ${i}`);const c=ie();c.start("Fetching application status...");try{const e=await fetch(i,{headers:{Authorization:`Bearer ${a.token}`}});if(c.stop(),n(`Response: ${e.status}`),404===e.status)return void console.log(T.yellow("Application not created"));if(!e.ok){const s=e.headers.get("content-type")??"";let n="Failed to fetch application status.";if(401===e.status||403===e.status)n="Please run 'dashnex login' to authenticate.";else if(s.includes("application/json")){const t=await e.json().catch(()=>({}));"string"==typeof t.error?n=t.error:"string"==typeof t.message&&(n=t.message)}console.error(T.red(n)),t(1)}const s=await e.json().catch(()=>({}));n(`Application body: ${JSON.stringify(s)}`);const o=a.userName?`${a.userName} (${a.businessId})`:a.businessId;console.log(`Business: ${T.cyan(o||"unknown")}`);const r=void 0!==s.id?String(s.id):void 0;r&&console.log(`Application ID: ${T.cyan(r)}`);const l=s.status??"unknown";console.log(`Status: ${T.cyan(l)}`);const d=ht(s);d&&console.log(`URL: ${T.cyan(d)}`),console.log(`Session: ${T.cyan(a.settingsPath??"DASHNEX_TOKEN environment variable")}`),await f(a,r)}catch(l){if(c.stop(),e(l),l instanceof Error&&l.message.startsWith("EXIT:"))throw l;if(h(l))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}}},options:[]},{name:"clear",description:"Delete local dependencies, caches and build output",handler:new class{async execute(t={}){n("Clear flow started");const o=process.cwd();j.pathExistsSync(C.join(o,"dashnex.json"))||(console.error(T.red("Run this command in a DashNex Web application folder.")),process.exit(1));const r=t.yes||"1"===process.env.DASHNEX_CI;n(`Non-interactive: ${r}`),r||process.stdin.isTTY||(console.error(T.red("'dashnex app clear' needs confirmation. Run it in a terminal, or pass -y to clear without prompts (the local database is kept).")),process.exit(1));try{const t=await this.collectTargets(o),s=C.join(o,...Bt.segments),i=await j.pathExists(s)&&!r;if(0===t.length&&!i)return void console.log(T.yellow("Nothing to clear."));const c=[];let l=0;if(t.length>0){console.log("The following will be deleted:");for(const e of t)console.log(` ${T.cyan(e.label)} ${T.dim(`(${e.description})`)}`);if(!r){const{confirm:e}=await R.prompt([{type:"confirm",name:"confirm",message:"Delete these files?",default:!1}]);if(!e)return n("User cancelled clear"),void console.log(T.yellow("Cancelled."))}const s=[],i=ie();for(const r of t){const t=C.join(o,...r.segments);n(`Removing ${t}`),i.start(`Removing ${r.label}...`);try{await _t(t),s.push(r.label)}catch(a){e(a),c.push(r.label)}}i.stop();for(const e of s)console.log(T.green(`Removed ${e}`));l+=s.length}if(i){const{confirm:t}=await R.prompt([{type:"confirm",name:"confirm",message:"Delete the local database as well?",default:!1}]);if(t){n(`Removing ${s}`);try{await _t(s),console.log(T.green(`Removed ${Bt.label}`)),l++}catch(a){e(a),c.push(Bt.label)}}}if(c.length>0){for(const e of c)console.error(T.red(`Could not delete ${e} — it may be in use. Stop 'dashnex dev' and try again.`));process.exit(1)}if(0===l)return void console.log(T.yellow("Nothing was deleted."));console.log(T.green("Clear complete. Run 'dashnex install' to set the application up again."))}catch(a){if(a instanceof Error&&a.message.startsWith("EXIT:"))throw a;if(e(a),h(a))return void console.log(T.yellow(s));throw a}}async collectTargets(e){const t=[];for(const s of Ot)await j.pathExists(C.join(e,...s.segments))&&t.push(s);return t.filter(s=>!t.some(t=>t!==s&&((e,t)=>{const s=C.relative(t,e);return""!==s&&!s.startsWith("..")&&!C.isAbsolute(s)})(C.join(e,...s.segments),C.join(e,...t.segments))))}},options:[{flags:"-y, --yes",description:"Skip prompts and keep the local database (CI mode)"}]},{name:"tail",description:"Stream live console/debug logs from the deployed worker (Ctrl+C to stop)",handler:new class{async execute(t={}){const s=t.level??"log";Tt(s)||(console.error(T.red(`Invalid --level '${t.level}'. Use one of: log, info, warn, error, debug.`)),process.exit(1));let a=null;if(t.filter)try{a=new RegExp(t.filter)}catch{console.error(T.red(`Invalid --filter regular expression: ${t.filter}`)),process.exit(1)}const i=await r();if(!i)return;await b(i);const c=!!t.debug;let l;try{l=await async function(e,t={}){const s=`${o()}${xt}`;n(`POST ${s}${t.debug?" (debug)":""}`);const r=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({debug:!!t.debug})});if(n(`Response: ${r.status}`),401===r.status||403===r.status)throw new vt("Not authorised to tail this application.");if(404===r.status)throw new bt("Business has no application, or the tail endpoint is unavailable.");if(!r.ok)throw new kt(`Failed to start tail (status ${r.status}).`);const a=await r.json().catch(()=>({}));if(!a.token||!a.workerUrl)throw new kt("Malformed tail-token response from the platform.");return{token:a.token,workerUrl:a.workerUrl,expiresAt:"number"==typeof a.expiresAt?a.expiresAt:0}}(i.token,{debug:c})}catch(v){e(v),v instanceof vt&&(console.error(T.red(v.message)),process.exit(1)),v instanceof bt&&(console.error(T.red(v.message)),process.exit(2)),console.error(T.red(v instanceof Error?v.message:"Could not start tail. Check your connection.")),process.exit(3)}const d={color:!!process.stdout.isTTY},p={minLevel:s,filter:a},u=(h=l.workerUrl,`${/^(localhost|127\.0\.0\.1)/.test(h)?"ws":"wss"}://${h}/api/realtime/tail`);var h;const m=`dashnex.tail.token.${l.token}`;console.log(T.dim(`Tailing ${l.workerUrl} — Ctrl+C to stop.`)),c&&console.log(T.dim("Debug logging enabled on the worker (DEBUG=1); may take a minute to take effect."));let g=!1,f=Date.now();const w=setInterval(()=>{g||Date.now()-f>=3e4&&(console.log(T.dim("(no logs in 30s)")),f=Date.now())},5e3),y=new H(u,m,{WebSocket:J,connectionTimeout:1e4,maxReconnectionDelay:16e3}),$=async e=>{if(!g){g=!0,clearInterval(w);try{y.close()}catch{}await Promise.race([St(i.token,{debug:c}),new Promise(e=>setTimeout(e,3e3))]),process.exit(e)}};process.on("SIGINT",()=>{console.log(),$(0)}),y.binaryType="arraybuffer",y.addEventListener("message",e=>{f=Date.now();const t=Ft("string"==typeof e.data?e.data:"",p,d);"line"===t.kind?console.log(t.line):"malformed"===t.kind&&console.error(T.dim(`[malformed frame] ${t.raw}`))}),y.addEventListener("close",e=>{if(!g)return Rt.has(e.code)?(console.error(T.red("Tail token was rejected (auth). Exiting.")),void $(1)):void n(`socket closed (code ${e.code}); reconnecting…`)}),y.addEventListener("error",e=>{n(`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"}]}]},Wt={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(){n("Secrets list flow started");const a=await r();if(!a)return;await b(a);const i=`${o()}/business/v1/cli/secrets`;n(`GET ${i}`);const c=ie();c.start("Fetching secrets...");try{const e=await fetch(i,{headers:{Authorization:`Bearer ${a.token}`}});if(c.stop(),n(`Response: ${e.status}`),!e.ok){let s="Failed to fetch secrets.";401===e.status||403===e.status?s="Please run 'dashnex login' to authenticate.":404===e.status?s="Business has no application.":502===e.status&&(s="Error fetching secrets. Make sure your application is deployed."),console.error(T.red(s)),t(1)}const s=(await e.json()).secrets??[];if(0===s.length)return void console.log(T.yellow("No secrets set."));console.log(T.bold(`\nSecrets (${s.length}):\n`)),s.forEach(({name:e})=>{console.log(` ${T.cyan(e)}`)}),console.log("")}catch(l){if(c.stop(),e(l),l instanceof Error&&l.message.startsWith("EXIT:"))throw l;if(h(l))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}}},options:[]},{name:"set",description:"Create or update a secret (prompts for missing KEY/VALUE)",handler:new class{async execute(a={}){n("Secrets set flow started");let{name:i,value:c}=a;const l="1"===process.env.DASHNEX_CI;i||(l&&(console.error(T.red("--name is required in CI mode (--ci).")),t(1)),i=(await R.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim()),c||(l&&(console.error(T.red("--value is required in CI mode (--ci).")),t(1)),c=(await R.prompt([{type:"password",name:"value",message:`Enter value for ${i}:`,mask:"*",validate:e=>""!==e||"Value is required"}])).value);const d=await r();if(!d)return;await b(d);const p=`${o()}/business/v1/cli/secrets`;n(`PUT ${p}`);const u=ie();u.start(`Setting secret '${i}'...`);try{const e=await fetch(p,{method:"PUT",headers:{Authorization:`Bearer ${d.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i,value:c})});if(u.stop(),n(`Response: ${e.status}`),!e.ok){let s="Failed to set secret.";401===e.status||403===e.status?s="Please run 'dashnex login' to authenticate.":400===e.status?s="Missing or empty name / value.":404===e.status?s="Business has no application.":502===e.status&&(s="Error setting secret. Make sure your application is deployed."),console.error(T.red(s)),t(1)}n(`Secret '${i}' set successfully`),console.log(T.green(`Secret '${i}' set successfully.`))}catch(m){if(u.stop(),e(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(h(m))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(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(a={}){n("Secrets delete flow started");let{name:i}=a;const c="1"===process.env.DASHNEX_CI;i||(c&&(console.error(T.red("--name is required in CI mode (--ci).")),t(1)),i=(await R.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim());const l=await r();if(!l)return;await b(l);const d=`${o()}/business/v1/cli/secrets/${encodeURIComponent(i)}`;n(`DELETE ${d}`);const p=ie();p.start(`Deleting secret '${i}'...`);try{const e=await fetch(d,{method:"DELETE",headers:{Authorization:`Bearer ${l.token}`}});if(p.stop(),n(`Response: ${e.status}`),!e.ok){let s="Failed to delete secret.";401===e.status||403===e.status?s="Please run 'dashnex login' to authenticate.":404===e.status?s=`Secret '${i}' not found.`:502===e.status&&(s="Error deleting secret. Make sure your application is deployed."),console.error(T.red(s)),t(1)}n(`Secret '${i}' deleted successfully`),console.log(T.green(`Secret '${i}' deleted.`))}catch(u){if(p.stop(),e(u),u instanceof Error&&u.message.startsWith("EXIT:"))throw u;if(h(u))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}}},arguments:[{name:"name",description:"Secret name (KEY)"}],options:[{flags:"--name <name>",description:"Secret name (alternative to positional KEY)"}]}]},Lt=async(e,t)=>{const s=C.join(e,".npmrc");return!!(await j.pathExists(s))&&(await j.copy(s,C.join(t,".npmrc"),{overwrite:!0}),await(async e=>{const t=C.join(e,".gitignore"),s=await j.pathExists(t)?await j.readFile(t,"utf8"):"";if(s.split(/\r?\n/).some(e=>".npmrc"===e.trim()))return;const n=""===s||s.endsWith("\n")?s:`${s}\n`;await j.writeFile(t,`${n}.npmrc\n`)})(t),!0)},Mt=["node_modules","dist",".git","coverage"],Ut=e=>e.replace(/\\/g,"/").split("/").filter(e=>""!==e),Xt=async(e,t)=>{const s=await(async e=>{const t=/* @__PURE__ */new Set;return await Y.t({file:e,onReadEntry:e=>{const[s]=Ut(e.path);t.add(s??"")}}),1===t.size?1:0})(e);await j.ensureDir(t),await Y.x({file:e,cwd:t,strip:s,filter:e=>{const t=Ut(e),n=s>0?t.slice(s):t.filter(e=>"."!==e);return!(void 0!==n[0]&&Mt.includes(n[0]))}})},Ht=async(e,t,s)=>{const n=C.join(e,"package.json"),o=await j.readJson(n);o.name=`@dashnex/${t}`,o.description=s,o.version="0.1.0",await j.writeJson(n,o,{spaces:2})},Jt=async(e,t)=>{const s=C.join(e,"package.json"),n=await j.readJson(s),o={...n.dependencies??{},[`@dashnex/${t}`]:`link:packages/${t}`};n.dependencies=Object.fromEntries(Object.entries(o).sort(([e],[t])=>e<t?-1:e>t?1:0)),await j.writeJson(s,n,{spaces:2})},Gt="Run this command in a DashNex Web application folder.",qt="Could not reach DashNex API. Check your connection and try again.",Yt=class extends Error{},Vt=e=>(console.error(T.red(e)),t(1)),Kt=e=>e instanceof Error&&e.message.startsWith("EXIT:"),Zt=async t=>{try{return await t()}catch(s){if(Kt(s)||h(s))throw s;throw e(s),new Yt(s instanceof Error?s.message:String(s))}},Qt="@dashnex/",es=e=>{const t=e.trim();return(t.startsWith(Qt)?t.slice(9):t).toLowerCase()},ts=e=>`${Qt}${e}`,ss=()=>x().replace(/^https?:\/\//,""),ns=()=>`Join the Developers program first: ${ss()} → Developers.`,os=e=>`${ts(e)} isn't reserved by this business.`,rs=e=>`Bump the version (run pnpm version patch in packages/${e}) and submit again.`,as=(e,t)=>`${ts(e)}${t?` v${t}`:""} is already in review. Wait for the decision before submitting again.`,is=e=>(console.error(T.red(e)),t(1)),cs=e=>({Authorization:`Bearer ${e}`}),ls=(e,t)=>is(401===e||403===e?"Please run 'dashnex login' to authenticate.":t),ds=async e=>{const t=`${o()}/business/v1/cli/developers/access`;n(`GET ${t}`);const s=await fetch(t,{headers:cs(e)});if(n(`Developer access response: ${s.status}`),!s.ok)return{ok:!1,status:s.status};const r=await s.json().catch(()=>null);if("object"!=typeof r||null===r||Array.isArray(r))return{ok:!1,status:s.status};const a=r;return{ok:!0,access:{agreementAccepted:!0===a.agreementAccepted,reservations:Array.isArray(a.reservations)?a.reservations:[]}}},ps=e=>e.ok?e.access:ls(e.status,"Failed to check developer access."),us=(e,t)=>{if(!e.agreementAccepted)return is(ns());if(0===e.reservations.length)return is(`Reserve a module name first: ${ss()} → Developers.`);if(void 0===t)return;const s=es(t),n=e.reservations.find(e=>es(e.address)===s);return n||is(os(s))},hs=async(e,t)=>{const s=await(async e=>ps(await ds(e)))(e),n=us(s,t);return n?{access:s,reservation:n}:{access:s}},ms=["version_not_higher","not_reserved","in_review","agreement_required"],gs=e=>[`Created packages/${e} (${ts(e)}).`,"Next steps:",` 1. cd packages/${e} && pnpm install && pnpm build`," 2. dashnex install && dashnex dev (links the module into your app)",` 3. dashnex module submit ${e} (when it is ready for review)`].join("\n"),fs=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/,ws=(e,t)=>{const s=fs.exec(e),n=fs.exec(t);if(!s||!n)return null;for(let a=1;a<=3;a++){const e=Number(s[a])-Number(n[a]);if(0!==e)return e}const o=s[4],r=n[4];return o||r?o?r?((e,t)=>{const s=e.split("."),n=t.split("."),o=Math.min(s.length,n.length);for(let r=0;r<o;r++){const e=s[r],t=n[r],o=/^\d+$/.test(e),a=/^\d+$/.test(t);if(o&&a){const s=Number(e)-Number(t);if(0!==s)return s;continue}if(o!==a)return o?-1:1;if(e!==t)return e<t?-1:1}return s.length-n.length})(o,r):-1:1:0},ys=t=>new Promise(s=>{const n=t();n.on("error",t=>{e(t),s(1)}),n.on("close",e=>{s(e??1)})}),$s=(e,t,s)=>{switch(e.status){case"accepted":return void console.log(T.green(((e,t)=>`Submitted ${ts(e)} v${t} for review. Status: In review.`)(t,s)));case"version_not_higher":return Vt(rs(t));case"not_reserved":return Vt(os(t));case"in_review":return Vt(as(t));case"agreement_required":return Vt(ns());case"error":return Vt(e.message)}},vs={name:"module",description:"Develop marketplace modules (run in DashNex application folder)",handler:{execute:async()=>{}},options:[],subcommands:[{name:"init",description:"Create reserved modules in packages/ from the module template",handler:new class{async execute(a={}){n("Module init flow started");const i=!0===a.ci||"1"===process.env.DASHNEX_CI,c=process.cwd();if(!(await j.pathExists(C.join(c,"dashnex.json"))))return Vt(Gt);const l=C.join(L.tmpdir(),`dashnex-template-${z(6).toString("hex")}.tgz`),d=ie(),p=()=>j.remove(l).catch(()=>{});try{const t=await Zt(()=>r());if(!t)return;const{access:s,reservation:p}=await Zt(()=>hs(t.token,a.address)),g=C.join(c,"packages");let f;if(await j.ensureDir(g),p){if(await j.pathExists(C.join(g,p.address)))return Vt(`packages/${p.address} already exists.`);f=[p]}else{const e=[];for(const t of s.reservations)await j.pathExists(C.join(g,t.address))||e.push(t);if(0===e.length)return void console.log(T.yellow("All reserved modules already exist in packages/."));if(f=await(async(e,t,s)=>{if(t.all||1===e.length)return e;if(s)return Vt("Pass an address or --all in CI mode.");const{addresses:n}=await R.prompt([{type:"checkbox",name:"addresses",message:"Which modules do you want to create?",choices:e.map(e=>({name:`${e.moduleName} (${ts(e.address)})`,value:e.address,checked:!0}))}]);return e.filter(e=>n.includes(e.address))})(e,a,i),0===f.length)return void console.log(T.yellow("No modules selected."))}d.start("Downloading the module template...");const w=await Zt(()=>(async e=>{const t=`${o()}/business/v1/cli/developers/template`;n(`GET ${t}`);const s=await fetch(t,{headers:cs(e)});return n(`Module template response: ${s.status}`),s.ok?{ok:!0,bytes:Buffer.from(await s.arrayBuffer())}:{ok:!1,status:s.status}})(t.token));d.stop(),await j.writeFile(l,(u=w,u.ok?u.bytes:ls(u.status,"Failed to download the module template.")));let y=!1;for(const{address:n,moduleName:o}of f){const t=C.join(g,n);try{await j.ensureDir(t),await Xt(l,t),await Ht(t,n,o),await Lt(c,t)||(y=!0),await Jt(c,n)}catch(m){if(await j.remove(t).catch(()=>{}),Kt(m)||h(m))throw m;return e(m),Vt(`Failed to create packages/${n}: ${m instanceof Error?m.message:String(m)}`)}console.log(T.green(gs(n)))}y&&console.log(T.yellow("No DashNex registry token found (.npmrc). Deploy your app once, then run 'dashnex app pull' before building or submitting."))}catch(m){if(d.stop(),await p(),e(m),Kt(m))throw m;if(h(m))return void console.log(T.yellow(s));m instanceof Yt?console.error(T.red(qt)):console.error(T.red(`Module init failed: ${m instanceof Error?m.message:String(m)}`)),t(1)}finally{await p(),n("Temp template tarball removed")}var u}},arguments:[{name:"address",description:"Module address to create (prompts when several are missing)"}],options:[{flags:"--all",description:"Create every reserved module that is not in packages/ yet"}]},{name:"submit",description:"Build, publish and submit a module for review",handler:new class{async execute(a){n("Module submit flow started");const i=process.cwd(),c=es(a.address),l=ts(c);if(!(await j.pathExists(C.join(i,"dashnex.json"))))return Vt(Gt);const d=ie();try{const t=await Zt(()=>r());if(!t)return;d.start("Checking developer access...");const s=await Zt(()=>ds(t.token));d.stop();const a=us(ps(s),c),p=(e=>{const t=e?.inReview;if("object"!=typeof t||null===t)return;const{version:s}=t;return"string"==typeof s&&""!==s?s:void 0})(a);if(p)return Vt(as(c,p));const u=C.join(i,"packages",c);if(!(await j.pathExists(C.join(u,"package.json"))))return Vt(`packages/${c} not found. Run 'dashnex module init ${c}' first.`);const h=await(async(e,t)=>{const s=C.join(e,"package.json"),n=await j.readJson(s).catch(()=>null);return n?.name!==ts(t)?Vt(`packages/${t}/package.json must be named ${ts(t)}.`):"string"!=typeof n.version||""===n.version?Vt(`packages/${t}/package.json must have a version.`):n.version})(u,c),m=a?.lastSubmittedVersion;if(m&&!((e,t)=>{const s=ws(e,t);return null!==s&&s>0})(h,m))return Vt(rs(c));const g=await(async e=>{const t=C.join(e,".npmrc");if(!(await j.pathExists(t)))return null;const s=(e=>{const t={};for(const s of e.split(/\r?\n/)){const e=s.trim();if(!e||e.startsWith("#"))continue;const n=e.indexOf("=");-1!==n&&(t[e.slice(0,n).trim()]=e.slice(n+1).trim())}return t})(await j.readFile(t,"utf8")),n=s["@dashnex:registry"]||"https://npm.dashnex.com/";let o;try{o=new URL(n).host}catch{return null}const r=s[`//${o}/:_authToken`];return r?{registry:n,host:o,token:r}:null})(i);if(!g)return Vt("No DashNex registry token found (.npmrc). Deploy your app once, then run 'dashnex app pull' and submit again.");await Lt(i,u),d.start(`Installing dependencies for ${l}...`);const f=await De(u);if(d.stop(),0!==f)return Vt("Build failed.");if(console.log(`Building ${l}...`),0!==await(async(e,t)=>{const s=`${await Ee("pnpm")?"pnpm":"npm"} run ${t}`;return n(`Executing: ${s} in ${e}`),ys(()=>I(s,{cwd:e,shell:!0,stdio:"inherit"}))})(u,"build"))return Vt("Build failed.");if(await(async(t,s,o,r)=>{const a=`${t.replace(/\/+$/,"")}/@dashnex%2F${o}`;n(`GET ${a}`);try{const e=await fetch(a,{headers:{Authorization:`Bearer ${s}`}});if(n(`Registry responded ${e.status}`),200!==e.status)return!1;const t=await e.json();return Boolean(t.versions?.[r])}catch(i){return e(i),!1}})(g.registry,g.token,c,h))console.log(T.yellow(`v${h} is already in the registry, skipping publish.`));else if(0!==await(async(e,t)=>{const s=["publish","--registry",t,"--tag","review"],o={cwd:e,stdio:"inherit",shell:"win32"===process.platform};return n(`Executing: npm ${s.join(" ")} in ${e}`),ys(()=>I("npm",s,o))})(u,g.registry))return Vt(`Publishing ${l} v${h} failed.`);d.start("Submitting for review...");const w=await Zt(()=>(async(e,t,s)=>{const r=`${o()}/business/v1/cli/developers/submissions`;n(`POST ${r}`);const a=await fetch(r,{method:"POST",headers:{...cs(e),"Content-Type":"application/json"},body:JSON.stringify({address:t,version:s})});n(`Module submission response: ${a.status}`);const i=await a.json().catch(()=>({}));if(202===a.status)return{status:"accepted",submissionId:String(i.submissionId??"")};if(409===a.status)return{status:"agreement_required"};if(400===a.status){const e=ms.find(e=>e===i.code);if(e)return{status:e}}const c=i.message??i.error??"Failed to submit the module.";return{status:"error",message:String(c)}})(t.token,c,h));d.stop(),$s(w,c,h)}catch(p){if(d.stop(),e(p),Kt(p))throw p;if(h(p))return void console.log(T.yellow(s));p instanceof Yt?console.error(T.red(qt)):console.error(T.red(`Module submit failed: ${p instanceof Error?p.message:String(p)}`)),t(1)}}},arguments:[{name:"address",description:"Module address (the part after @dashnex/)",required:!0}],options:[]}]},bs=[{name:"version",description:"Display the version of the CLI",handler:new class{async execute(e){const t=C.dirname(N(import.meta.url)),s=JSON.parse(F.readFileSync(C.resolve(t,"..","..","package.json"),"utf8"));console.log(s.version)}},options:[]},{name:"login",description:"Log in to your DashNex account",handler:new class{async execute(o={}){n("Login flow started");const a=process.cwd(),c=await w(a)??g(a);n(`Settings file: ${c}`);const l=await $(a),d=o.business??l?.businessId,p=await r({exitOnFailure:!1,dashnexPath:c});if(p){if(!d||u(d,p.businessId))return console.log(T.green(`Already logged in as ${p.userName??"user"} (business ${p.businessId})`)),void console.log(T.dim(`Session: ${p.settingsPath??"DASHNEX_TOKEN environment variable"}`));!o.business&&l?.businessId&&console.log(T.yellow(`Signed in to business ${p.businessId}, but this folder belongs to business ${l.businessId}.`))}!o.business&&l?.businessId&&console.log(T.dim(`Using business ${l.businessId} from ${l.envPath} (--business picks another).`)),E()||(console.error(T.red("No DashNex ID OAuth client is configured for this environment.")),console.error(T.yellow("Set DASHNEX_OAUTH_CLIENT_ID, or use APPLICATION_ENV=qa.")),t(1));try{const e=await j.pathExists(c)?await i(c):null;if(e){n("Resuming with saved DashNex ID session");try{return void(await this.selectBusiness(e,c,d))}catch(f){if(!(f instanceof te))throw f;n("Saved DashNex ID session rejected, starting a new sign-in")}}const t=await this.authorize(!1!==o.browser);await pe(c,{id:{token:t.token,expiresAt:m(t.expiresIn),...t.refreshToken&&{refreshToken:t.refreshToken}}}),await this.selectBusiness(t.token,c,d)}catch(f){if(e(f),h(f))return void console.log(T.yellow(s));if((f instanceof Q||f instanceof ee)&&(console.error(T.red(f.message)),t(1)),f instanceof Error&&f.message.startsWith("EXIT:"))throw f;console.error(T.red("Could not reach DashNex. Check your connection and try again.")),t(1)}}async authorize(e){const{verifier:t,challenge:s}=(()=>{const e=V(z(32));return{verifier:e,challenge:V(B("sha256").update(e).digest())}})(),o=(e=>{const t=new URL(`${D()}/api/oauth/authorize`);return t.searchParams.set("client_id",E()),t.searchParams.set("redirect_uri",Z),t.searchParams.set("response_type","code"),t.searchParams.set("code_challenge",e),t.searchParams.set("code_challenge_method","S256"),t.searchParams.set("scope","business"),t.toString()})(s);n(`Authorize URL: ${o}`);const r=!!e&&await K(o);console.log(""),r?(console.log(T.green("Opened your browser to finish signing in.")),console.log(T.dim("If nothing opened, use this URL:"))):console.log(T.bold("Open this URL to sign in:")),console.log(T.cyan(o)),console.log(""),console.log(T.dim("Approve the request, then copy the code shown and paste it below.")),console.log("");const{code:a}=await R.prompt([{type:"input",name:"code",message:"Paste the code:",validate:e=>!!e.trim()||"Code is required"}]),i=ie();i.start("Verifying code...");try{return await(async(e,t)=>{const s=`${D()}/api/oauth/token`;n(`POST ${s}`);const{response:o,body:r}=await p(s,{method:"POST",body:JSON.stringify({grant_type:"authorization_code",client_id:E(),redirect_uri:Z,code:e.trim(),code_verifier:t})});if(n(`Response: ${o.status}`),S("Token response",r),!o.ok){const e="string"==typeof r.error?r.error:void 0,t="string"==typeof r.error_description?r.error_description:void 0;if("invalid_grant"===e)throw new Q("That code is not valid anymore. Codes expire 10 minutes after they are issued and can only be used once.",e);throw new Q(t??"Could not exchange the code for a token.",e)}const a=r;if(!a.access_token)throw new Q("The authorization server did not return an access token.");return{token:a.access_token,refreshToken:a.refresh_token,expiresIn:a.expires_in}})(a,t)}finally{i.stop()}}async selectBusiness(e,t,s){const n=await ce(e,t,{businessId:s});console.log(T.green(`Logged in as ${n.name} (business ${n.id})`)),console.log(T.dim(`Session: ${t}`))}},options:[{flags:"--business <id>",description:"Business ID to select (skip prompt)"},{flags:"--no-browser",description:"Print the sign-in URL instead of opening a browser"}]},{name:"logout",description:"Log out and remove local credentials",handler:new class{async execute(){const e=await w(process.cwd());e?(await l(e,e=>{delete e.business,delete e.id}),console.log(T.green("Logged out.")),console.log(T.dim(`Session removed from ${e}`))):console.log(T.green("Logged out."))}},options:[]},{name:"switch",description:"Switch to another business (prompts when no ID is given)",handler:new class{async execute(o={}){n("Switch flow started");const r=await w(process.cwd()),a=r?await c(r):null;r&&a?.business?.token||(console.error(T.red("Please run 'dashnex login' to authenticate.")),t(1));const l=a.id;l?.token||(console.error(T.red("Switching businesses requires signing in with DashNex ID.")),console.error(T.yellow("Run 'dashnex logout' and then 'dashnex login' to sign in again.")),t(1));const d=e=>ce(e,r,{businessId:o.businessId,currentBusinessId:a.business?.id});try{const e=await i(r)??l.token;let t;try{t=await d(e)}catch(p){if(!(p instanceof te))throw p;n("DashNex ID session rejected, refreshing");const e=await k(r);if(!e)throw p;t=await d(e)}console.log(T.green(`Switched to ${t.name} (business ${t.id})`)),console.log(T.dim(`Session: ${r}`));const s=await $();s?.businessId&&!u(s.businessId,t.id)&&console.warn(T.yellow(`Warning: this folder belongs to business ${s.businessId} (BUSINESS_ID in ${s.envPath}).`))}catch(p){if(e(p),h(p))return void console.log(T.yellow(s));if(p instanceof te&&(console.error(T.red(p.message)),console.error(T.yellow("Run 'dashnex logout' and then 'dashnex login' to sign in again.")),t(1)),p instanceof ee&&(console.error(T.red(p.message)),t(1)),p instanceof Error&&p.message.startsWith("EXIT:"))throw p;console.error(T.red("Could not reach DashNex. Check your connection and try again.")),t(1)}}},arguments:[{name:"businessId",description:"Business ID to switch to (skip prompt)"}],options:[]},{name:"whoami",description:"Show current logged-in business and user",handler:new class{async execute(){n("Whoami flow started");const a=await r();if(!a)return;const i=await v()?`${o()}/business/v1/`:`${d()}/users/v1/`;n(`GET ${i}`);const c=ie();c.start("Fetching user info...");try{const e=await fetch(i,{headers:{Authorization:`Bearer ${a.token}`}});if(c.stop(),n(`Response: ${e.status}`),!e.ok){const s=e.headers.get("content-type")??"";let n="Failed to fetch user info.";if(401===e.status||403===e.status)n="Please run 'dashnex login' to authenticate.";else if(s.includes("application/json")){const t="string"==typeof(l=await e.json().catch(()=>({}))).error?l.error:"string"==typeof l.message?l.message:void 0;t&&(n=t)}console.error(T.red(n)),t(1)}const s=await e.json().catch(()=>({})),o="string"==typeof s.name?s.name:"string"==typeof s.companyName?s.companyName:"Unknown",r=s.memberUser,d=r&&"string"==typeof r.fullName?r.fullName:r&&"string"==typeof r.name?r.name:"Unknown";n(`Whoami: ${o} (${d})`),console.log(T.green(`You are logged in as ${o} (${d})`)),console.log(`Business ID: ${T.cyan(a.businessId||"unknown")}`),console.log(`Session: ${T.cyan(a.settingsPath??"DASHNEX_TOKEN environment variable")}`),await f(a)}catch(p){if(c.stop(),e(p),p instanceof Error&&p.message.startsWith("EXIT:"))throw p;if(h(p))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}var l}},options:[]},{name:"dev",description:"Run the development server (run in DashNex application folder)",handler:new class{async execute(t={}){n("Dev flow started");try{const e=await Se(process.cwd(),t);process.exit(e)}catch(s){if(s instanceof Error&&s.message.startsWith("EXIT:"))throw s;e(s),s instanceof Error?console.error(T.red(s.message)):console.error(T.red("Failed to run npm run dev")),process.exit(1)}}},options:[{flags:"-p, --port <port>",description:"Port for the dev server (default: PORT env or 3000)"},{flags:"-H, --host <host>",description:"Host to bind, e.g. 0.0.0.0 inside Docker (default: HOST env or localhost)"},{flags:"--https",description:"Serve over HTTPS with a trusted local certificate (mkcert)"}]},{name:"check",description:"Run build-time validations (run in DashNex application folder)",handler:new Be,options:[]},{name:"install",description:"Install dependencies using pnpm (preferred) or npm (run in DashNex application folder)",handler:new class{async execute(){n("Install flow started");const t=C.join(process.cwd(),"dashnex.json");await j.pathExists(t)||(console.error(T.red("Run this command in a DashNex Web application folder.")),process.exit(1));const s=process.cwd(),o=ie();o.start("Installing dependencies...");try{const e=await De(s);o.stop(),0!==e&&process.exit(e),console.log(T.green("Dependencies installed.")),process.exit(0)}catch(r){o.stop(),e(r),r instanceof Error?console.error(T.red(r.message)):console.error(T.red("Failed to run install")),process.exit(1)}}},options:[]},zt,Wt,vs];export{bs as default};
|
|
1
|
+
import{C as e,E as t,O as s,S as n,_ as o,a as r,b as a,c as i,d as c,f as l,g as d,h as p,i as u,k as h,l as m,m as g,n as f,o as w,p as y,r as $,s as v,t as b,u as k,v as x,w as S,x as E,y as D}from"../chunks/project-guard-CxCsFM9x.js";import T from"chalk";import j from"fs-extra";import C from"path";import{fileURLToPath as P}from"url";import{execFileSync as N,spawn as A,spawnSync as I}from"child_process";import F from"fs";import O from"inquirer";import{X509Certificate as R,createHash as B,createPrivateKey as _,randomBytes as z}from"crypto";import W from"net";import L from"os";import M from"adm-zip";import{diffLines as U}from"diff";import X from"ignore";import{WebSocket as H}from"partysocket";import J from"ws";import{inspect as G}from"node:util";import{rm as q}from"node:fs/promises";import*as Y from"tar";var V=e=>e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),K=async t=>{const s=(e=>{switch(process.platform){case"darwin":return{command:"open",args:[e]};case"win32":return{command:"cmd",args:["/c","start","",e]};default:return{command:"xdg-open",args:[e]}}})(t);return!!s&&new Promise(t=>{try{const o=A(s.command,s.args,{stdio:"ignore",detached:!0});o.on("error",s=>{e(s),t(!1)}),o.on("spawn",()=>{n(`Opened browser via ${s.command}`),o.unref(),t(!0)})}catch(o){e(o),t(!1)}})},Z="urn:ietf:wg:oauth:2.0:oob",Q=class extends Error{constructor(e,t){super(e),this.code=t,this.name="OAuthError"}},ee=class extends Error{},te=class extends ee{},se=(e,t)=>401===e||403===e&&"insufficient_scope"===t.error,ne=e=>{const t=e.data;return t&&"object"==typeof t?t:e},oe=e=>{const t=e.items??[];return Array.isArray(t)?t.map(e=>{if(!e||"object"!=typeof e)return null;const t=e,s=Number(t.id);return!Number.isFinite(s)||s<=0?null:{id:s,name:String(t.name??t.companyName??`Business ${s}`).trim()}}).filter(e=>null!==e):[]},re=async(e,t)=>{const s=[];let o=1,r=0;do{const a=`${D()}${e}?page=${o}&perPage=100`;n(`GET ${a}`);const{response:i,body:c}=await p(a,{headers:{Authorization:`Bearer ${t}`}});if(n(`Response: ${i.status}`),S(`Businesses response (${e})`,c),!i.ok){if(se(i.status,c))throw new te("Your DashNex ID session has expired.");if(404===i.status)throw new ee(`Your DashNex ID account is not linked to a contact yet. Finish signing up at ${D()} and try again.`);throw new ee("Failed to fetch businesses. Please try again.")}const l=ne(c),d=oe(l);if(r="number"==typeof l.total?l.total:d.length,s.push(...d),d.length<100||s.length>=r)break;o++}while(s.length<r);return s},ae=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],ie=(e="")=>{if(process.env.DASHNEX_CI)return{start:()=>{},stop:()=>{},text:()=>{}};let t=null,s=0,n=e;const o=()=>{const e=ae[s%ae.length];process.stderr.write(`\r[K${e} ${n}`),s++};return{start:e=>{void 0!==e&&(n=e),t||(s=0,o(),t=setInterval(o,80))},stop:()=>{t&&(clearInterval(t),t=null),process.stderr.write("\r[K\n")},text:e=>{n=e,t&&o()}}},ce=async(e,s,o={})=>{const r=ie();let a;r.start("Fetching businesses...");try{a=await(async e=>{const t=await re("/api/businesses/my",e),s=await re("/api/businesses/other",e),o=/* @__PURE__ */new Map;for(const n of t)o.set(n.id,n);for(const n of s)o.has(n.id)||o.set(n.id,n);return n(`Businesses (my: ${t.length}, other: ${s.length}, merged: ${o.size})`),[...o.values()]})(e)}finally{r.stop()}0===a.length&&(console.error(T.red("No businesses or teams found for your account!")),console.log(T.green(`Create your first business at ${D()}`)),t(1));const i=await le(a,o);let c;r.start("Switching business...");try{c=await(async(e,t)=>{const s=`${D()}/api/businesses/${t}/switch`;n(`POST ${s}`);const{response:o,body:r}=await p(s,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(n(`Response: ${o.status}`),S("Switch response",r),!o.ok){if(se(o.status,r))throw new te("Your DashNex ID session has expired.");if(403===o.status)throw new ee("You do not have access to that business.");throw new ee("Failed to switch to business. Please try again.")}const a=ne(r);if(!a.token||!a.refreshToken)throw new ee("Invalid response from server. Please try again.");return{token:a.token,refreshToken:a.refreshToken,businessId:t}})(e,i.id)}finally{r.stop()}return await pe(s,{...await de(c.token),business:{token:c.token,refreshToken:c.refreshToken,id:c.businessId}}),await ue(),i},le=async(e,s)=>{if(void 0!==s.businessId){const o=e.find(e=>String(e.id)===String(s.businessId).trim());return o||(console.error(T.red(`Business "${s.businessId}" not found.`)),t(1)),n(`Selected business via argument: ${o.id} ${o.name}`),o}if(1===e.length)return n(`Selected business: ${e[0].id} ${e[0].name}`),e[0];const o=e.find(e=>String(e.id)===String(s.currentBusinessId)),{businessId:r}=await O.prompt([{type:"select",name:"businessId",message:"Select business:",choices:e.map(e=>({name:e===o?`${e.name} ${T.dim("(current)")}`:e.name,value:e.id})),...o&&{default:o.id}}]),a=e.find(e=>e.id===r)||e[0];return n(`Selected business: ${a.id} ${a.name}`),a},de=async t=>{try{const e=`${o()}/business/v1/cli/settings`;n(`GET ${e}`);const{response:s,body:r}=await p(e,{headers:{Authorization:`Bearer ${t}`}});if(n(`Response: ${s.status}`),S("CLI settings response",r),s.ok&&r&&"object"==typeof r)return r}catch(s){e(s)}return{}},pe=async(e,t)=>{const s=C.dirname(e);await j.pathExists(s)&&(await j.stat(s)).isFile()&&await j.remove(s),await j.ensureDir(s),await l(e,e=>({...e,...t})),n("Saved credentials to .dashnex/settings.json")},ue=async()=>{const e=C.join(process.cwd(),".gitignore");if(!(await j.pathExists(e)))return;let t=await j.readFile(e,"utf8");t.includes(".dashnex")||(t=t.trimEnd(),t.endsWith("\n")||(t+="\n"),t+="\n.dashnex\n",await j.writeFile(e,t))},he="v1.4.4",me=C.join(y,"certificates"),ge=["localhost","127.0.0.1","::1"],fe="win32"===process.platform,we=()=>0===I("mkcert",["-version"],{stdio:"ignore",shell:fe}).status?"mkcert":null,ye=async(e={})=>{const t=(e.lookupPath??we)();if(t)return t;const s=e.cacheDir??C.join(L.homedir(),".dashnex","mkcert"),n=((e=process.platform,t=process.arch)=>{const s="x64"===t?"amd64":t;if("win32"===e)return`mkcert-${he}-windows-${s}.exe`;if("darwin"===e)return`mkcert-${he}-darwin-${s}`;if("linux"===e)return`mkcert-${he}-linux-${s}`;throw new Error(`Unsupported platform for mkcert: ${e}`)})(),o=C.join(s,n);if(await j.pathExists(o))return o;const r=`https://github.com/FiloSottile/mkcert/releases/download/${he}/${n}`;e.log?.(`mkcert not found, downloading ${he} to ${o}`);const a=await(e.fetchImpl??fetch)(r);if(!a.ok)throw new Error(`Failed to download mkcert from ${r}: HTTP ${a.status}`);await j.ensureDir(s);const i=`${o}.download`;return await j.writeFile(i,Buffer.from(await a.arrayBuffer())),await j.chmod(i,493),await j.move(i,o,{overwrite:!0}),o},$e=(e,t,s)=>{try{const n=new R(j.readFileSync(t)),o=_(j.readFileSync(e));return!!n.checkPrivateKey(o)&&(!(new Date(n.validTo).getTime()<=Date.now())&&s.every(e=>((e,t)=>W.isIP(t)?Boolean(e.checkIP(t)):Boolean(e.checkHost(t)))(n,e)))}catch{return!1}},ve=async(t,s={})=>{const n=s.log??(()=>{}),o=s.certDir??me,r=C.resolve(t,o),a=C.join(r,"localhost-key.pem"),i=C.join(r,"localhost.pem"),c=(e=>{const t=(e??"").trim();return t&&!ge.includes(t)?[...ge,t]:[...ge]})(s.host);try{if($e(a,i,c))return n(`Using existing local certificate from ${C.relative(t,r)||"."}`),{key:a,cert:i};const e=await(s.resolveMkcert??(()=>ye({log:n})))();if(await j.ensureDir(r),n("Generating a trusted local certificate with mkcert (this may prompt for your password once)..."),N(e,["-install","-key-file",a,"-cert-file",i,...c],{stdio:"inherit",shell:fe}),!(await j.pathExists(a))||!(await j.pathExists(i)))throw new Error("mkcert finished but the certificate files were not created");let l;await(async(e,t)=>{const s=C.join(e,".gitignore");if(!(await j.pathExists(s)))return!1;const n=await j.readFile(s,"utf8"),o=n.split(/\r?\n/).map(e=>e.trim()),r=new Set([t,`/${t}`,`${t}/`,`/${t}/`]);if(o.some(e=>r.has(e)))return!1;const a=0===n.length||n.endsWith("\n")?"":"\n";return await j.appendFile(s,`${a}${t}\n`),!0})(t,o.split(C.sep)[0]);try{const t=N(e,["-CAROOT"],{encoding:"utf8",shell:fe}).trim();t&&(l=C.join(t,"rootCA.pem"))}catch{}return n(`Certificates created in ${C.relative(t,r)||"."}`),{key:a,cert:i,...l?{rootCA:l}:{}}}catch(l){return e(l),n(`Failed to set up HTTPS certificates: ${l instanceof Error?l.message:String(l)}`),null}},be=["Using (vars|secrets) defined in ","\\(node:\\d+\\) MaxListenersExceededWarning:","\\(Use `node --trace-warnings","\\[DEP0205\\] DeprecationWarning:","\\(Use `node --trace-deprecation","Detected multiple renderers concurrently rendering the same context provider","\\[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"],ke=(e,t)=>t.length>0&&t.some(t=>t.test(e)),xe=(e,t)=>{let s="";return{write:o=>{const r="string"==typeof o?o:o.toString();s+=r;const a=s.split(/\r?\n/);s=a.pop()??"";for(const s of a){const o=s.trim();o?ke(o,t)?n(`Filtered: ${o}`):e.write(s+"\n"):n("Filtered: <empty line>")}},flush:()=>{const o=s.trim();if(o){if(ke(o,t))return n(`Filtered: ${o}`),void(s="");e.write(s),s=""}else s=""}}},Se=async(t,s={})=>{const o=C.join(t,"dashnex.json"),r=C.join(t,"package.json");if(n(`Checking for dashnex.json at: ${o}`),!(await j.pathExists(o)))throw new Error("Run this command in a DashNex Web application folder.");if(n("dashnex.json found, checking for package.json"),!(await j.pathExists(r)))throw new Error("package.json is missing.");let a;n("package.json found, checking for dev script");try{a=await j.readJson(r)}catch(h){throw e(h),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.');const i=((e,t=process.env)=>{const s=e.port??t.PORT;if(null==s||""===String(s).trim())return;const n=Number(s);if(!Number.isInteger(n)||n<1||n>65535)throw new Error(`Invalid port: ${s}. Use a number between 1 and 65535.`);return n})(s),c=((e,t=process.env)=>{const s=(e.host??t.HOST??"").trim();return""===s?void 0:s})(s);n("dev script found, checking for npm availability");const l=await(async e=>new Promise(t=>{const s=A(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>{t(!1)}),s.on("close",e=>{t(0===e)})}))("npm");if(n(`npm available: ${l}`),!l)throw new Error("npm is not available. Please install npm to continue.");const d={};if(s.https){const e=await ve(t,{host:c,log:e=>console.log(T.dim(e))});e?(d.DASHNEX_DEV_HTTPS_KEY=e.key,d.DASHNEX_DEV_HTTPS_CERT=e.cert,console.log(T.green("HTTPS enabled for the dev server"+(i?` on https://${c??"localhost"}:${i}`:""))),e.rootCA&&console.log(T.dim(`Local CA: ${e.rootCA} (import it in browsers on other machines, e.g. when the app runs in Docker)`))):console.log(T.yellow("HTTPS is not available, starting the dev server over HTTP instead."))}const p=[];void 0!==i&&p.push("--port",String(i)),void 0!==c&&p.push("--hostname",c);const u=p.length?["--",...p]:[];return n(`npm available, executing: npm run dev${u.length?` ${u.join(" ")}`:""} in ${t}`),(async(t,s=[],n=process.cwd(),o=[],r={})=>{const a=s.length?`${t} ${s.join(" ")}`:t,i=o.length>0;return new Promise((t,s)=>{const c=A(a,{stdio:i?["inherit","pipe","pipe"]:"inherit",cwd:n,shell:!0,env:{...process.env,NODE_ENV:"development",FORCE_COLOR:"1",...r}});if(c.on("error",t=>{e(t),s(t)}),i&&c.stdout&&c.stderr){const e=xe(process.stdout,o),s=xe(process.stderr,o);c.stdout.on("data",t=>e.write(t)),c.stderr.on("data",e=>s.write(e)),c.on("close",n=>{e.flush(),s.flush(),t(null===n?0:n)})}else c.on("close",e=>{t(null===e?0:e)})})})("npm run dev",u,t,(()=>{const e=[];for(const t of be)try{e.push(new RegExp(t))}catch{n(`Invalid dev output filter pattern ignored: ${t}`)}return e})(),d)},Ee=async e=>new Promise(t=>{const s=A(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>{t(!1)}),s.on("close",e=>{t(0===e)})}),De=async t=>{let s;if(await Ee("pnpm"))s="pnpm install --config.strict-dep-builds=false",n("Using package manager: pnpm");else{if(!(await Ee("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",n("Using package manager: npm (with --legacy-peer-deps for DashNex peer-dep overlap)")}return n(`Executing: ${s} in ${t}`),new Promise((n,o)=>{const r=[],a=[],i=A(s,{stdio:["ignore","pipe","pipe"],cwd:t,shell:!0,env:{...process.env,NPM_CONFIG_LOGLEVEL:"error"}});i.stdout&&i.stdout.on("data",e=>r.push(e)),i.stderr&&i.stderr.on("data",e=>a.push(e)),i.on("error",t=>{e(t),o(t)}),i.on("close",e=>{const t=null===e?0:e;0!==t&&(r.length&&process.stdout.write(Buffer.concat(r)),a.length&&process.stderr.write(Buffer.concat(a))),n(t)})})},Te="Run this command in a DashNex Web application folder.",je=e=>{const t=C.join(e,"dashnex.json");return j.pathExistsSync(t)},Ce=(e,t=!1)=>{t||console.log(T.cyan(e))},Pe=(t,s,o={})=>{const r=`${t} ${s.join(" ")}`,a=!0===o.silent;return new Promise((s,o)=>{n(`Running: ${r}`);const i=A(r,{stdio:a?["ignore","pipe","pipe"]:"inherit",cwd:process.cwd(),shell:!0});i.on("error",t=>{e(t),o(t)}),i.on("close",e=>{n(`${t} exited with code ${e}`),s(null===e?1:e)})})},Ne=(t,s)=>new Promise((o,r)=>{n(`Running: ${t} ${s.join(" ")}`);const a=A(t,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",t=>{e(t),r(t)}),a.on("close",e=>{n(`${t} exited with code ${e}`),o({exitCode:null===e?1:e,output:i})})}),Ae=async t=>{n("Running check: install");try{return 0===await De(process.cwd())}catch(s){return e(s),!t&&s instanceof Error&&console.error(T.red(s.message)),!1}},Ie=async()=>{try{const{output:e}=await Ne(process.execPath,[process.argv[1],"db","migrate","--help"]);return e.includes("Usage: dashnex db migrate")}catch(t){return e(t),!1}},Fe=async t=>{n("Running check: db migrate");try{const{exitCode:e,output:s}=await Ne(process.execPath,[process.argv[1],"db","migrate"]);return 0===e||(s.includes("Unknown command")?(n("db migrate command is not available, skipping"),!0):(!t&&s.trim().length>0&&process.stderr.write(s),!1))}catch(s){return e(s),!0}},Oe=e=>new Promise(t=>{const s=A(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>t(!1)),s.on("close",e=>t(0===e))}),Re=[{name:"TypeScript",command:"npx",args:["tsc","--noEmit"],notFoundMessage:"TypeScript is not available. Please install it with: npm install -D typescript"}],Be=class{async execute(){n("Check flow started"),je(process.cwd())||(console.error(T.red(Te)),t(1)),Ce("Checking dependencies..."),await Ae(!1)||(console.error(T.red("Check failed.")),t(1)),n(`Running ${Re.length} check(s)`);for(const o of Re){n(`Running check: ${o.name}`),Ce(`Checking ${o.name}...`),await Oe(o.command)||(console.error(T.red(o.notFoundMessage)),t(1));try{0!==await Pe(o.command,o.args)&&(console.error(T.red("Check failed.")),t(1))}catch(s){if(s instanceof Error&&s.message.startsWith("EXIT:"))throw s;e(s),console.error(T.red(o.notFoundMessage)),t(1)}}await Ie()?(Ce("Checking database migrations..."),await Fe(!1)||(console.error(T.red("Check failed.")),t(1))):n("db migrate command is not available, skipping"),console.log(T.green("All checks passed."))}async run(t=!1){if(n("Running checks (called from push)"),!je(process.cwd()))return t||console.error(T.red(Te)),!1;if(Ce("Checking dependencies...",t),!(await Ae(t)))return!1;const s=t?{silent:!0}:void 0;for(const r of Re){if(n(`Running check: ${r.name}`),Ce(`Checking ${r.name}...`,t),!(await Oe(r.command)))return console.error(T.red(r.notFoundMessage)),!1;try{if(0!==await Pe(r.command,r.args,s))return!1}catch(o){return e(o),console.error(T.red(r.notFoundMessage)),!1}}if(await Ie()){if(Ce("Checking database migrations...",t),!(await Fe(t)))return!1}else n("db migrate command is not available, skipping");return t||console.log(T.green("All checks passed.")),!0}},_e=" │ ",ze=e=>e.subarray(0,8192).includes(0),We=e=>{const t=e.split("\n");return""===t[t.length-1]&&t.pop(),t},Le=(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))}…`},Me=(e,t,s)=>{const n=Math.max(s??process.stdout.columns??120,43),o=Math.floor((n-3)/2),r=((e,t)=>{const s=[],n=U(e,t);for(let o=0;o<n.length;o+=1){const e=n[o];if(e.removed){const t=We(e.value),r=n[o+1],a=r?.added?We(r.value):[];r?.added&&(o+=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 We(e.value))s.push({left:null,right:t,changed:!0});else for(const t of We(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(T.bold(Le("local (current)",o))+T.dim(_e)+T.bold("incoming"));let c=-1,l=0,d=0;for(let p=0;p<r.length;p+=1){if(!a.has(p))continue;if(l>=200){d+=1;continue}-1!==c&&p>c+1&&i.push(T.dim("···")),c=p,l+=1;const e=r[p],t=Le(e.left,o),s=Le(e.right,o);if(!e.changed){i.push(T.dim(t)+T.dim(_e)+T.dim(s));continue}const n=null!==e.left?T.red(t):t,u=null!==e.right?T.green(s):s;i.push(n+T.dim(_e)+u)}return d>0&&i.push(T.dim(`… ${d} more diff line(s) not shown`)),i.join("\n")},Ue=[".dashnex",".git",".vinext",".wrangler","wrangler.jsonc","wrangler.toml",".dev.vars",".github"],Xe=[".env","wrangler.jsonc"],He=e=>C.join(e,y,"sync.json"),Je=e=>B("sha1").update(`blob ${e.length}\0`).update(e).digest("hex"),Ge=async e=>{const t=X();t.add(Ue);const s=C.join(e,".gitignore");return await j.pathExists(s)&&t.add(await j.readFile(s,"utf8")),t},qe=e=>e.split(C.sep).join("/"),Ye=e=>Ue.some(t=>e===t||e.startsWith(`${t}/`)),Ve=async(e,t={})=>{const s={},n=await(async e=>{const t=await Ge(e),s=[],n=async o=>{const r=await j.readdir(o,{withFileTypes:!0});for(const a of r){const r=C.join(o,a.name),i=qe(C.relative(e,r));Ye(i)||t.ignores(a.isDirectory()?`${i}/`:i)||(a.isDirectory()?await n(r):a.isFile()&&s.push(i))}};return await n(e),s})(e);for(const o of n)s[o]=Je(await j.readFile(C.join(e,o)));if(t.includeGenerated)for(const o of Xe){if(o in s)continue;const t=C.join(e,o);(await j.lstat(t).catch(()=>null))?.isFile()&&(s[o]=Je(await j.readFile(t)))}return s},Ke=async e=>{try{const t=await j.readFile(He(e),"utf8"),s=JSON.parse(t);return"string"!=typeof s?.commit||"object"!=typeof s?.manifest||null===s.manifest?null:s}catch{return null}},Ze=async(e,t,s)=>{const o={commit:t,manifest:s,updatedAt:/* @__PURE__ */(new Date).toISOString()},r=He(e);try{await j.ensureDir(C.dirname(r)),await j.writeFile(r,`${JSON.stringify(o,null,2)}\n`),n(`Sync state written: commit ${t}, ${Object.keys(s).length} files`)}catch(a){n(`Failed to write sync state: ${a instanceof Error?a.message:"unknown"}`)}},Qe=1048576,et=async(t,s)=>{const{install:o}=await O.prompt([{type:"confirm",name:"install",message:"Install dependencies?",default:!0}]);if(!o){if(C.resolve(t)!==C.resolve(s)){const e=C.relative(s,t);console.log(T.cyan(`Run "cd ${e}" to change to the application folder.`))}return}try{const e=ie();e.start("Installing dependencies...");try{const s=await De(t);if(e.stop(),0!==s)return void n(`install exited with code ${s}`)}catch(i){throw e.stop(),i}}catch(i){return e(i),void console.error(T.red(i instanceof Error?i.message:"Failed to run install."))}const{migrate:r}=await O.prompt([{type:"confirm",name:"migrate",message:"Create or update database?",default:!0}]);if(!r)return;n(`Running dashnex db migrate in ${t}`);try{const s=ie();s.start("Creating or updating database...");try{const o=await((t,s,n)=>{const o=`${C.join(t,"node_modules",".bin")}${C.delimiter}${process.env.PATH??""}`,r={...process.env,PATH:o};return new Promise((o,a)=>{const i=A(s,{cwd:t,shell:!0,stdio:"inherit",env:n?{...r,...n}:r});i.on("error",t=>{e(t),a(t)}),i.on("close",e=>{o(null===e?0:e)})})})(t,"dashnex db migrate");if(s.stop(),0!==o)return void n(`dashnex db migrate exited with code ${o}`)}catch(i){throw s.stop(),i}}catch(i){return e(i),void console.error(T.red("Failed to run dashnex db migrate."))}const{dev:a}=await O.prompt([{type:"confirm",name:"dev",message:"Run development server?",default:!0}]);if(a)try{await Se(t)}catch(i){e(i),console.error(T.red(i instanceof Error?i.message:"Failed to run dev server."))}},tt=(e,t)=>404===e&&"string"==typeof t.message&&t.message.startsWith("Cannot "),st=(e,t)=>{if(e.length!==t.length)return`local ${e.length} bytes, incoming ${t.length} bytes`;const s=e.length;for(let n=0;n<s;n+=1)if(e[n]!==t[n]){return`size ${s} matches; first diff at byte ${n} (local=0x${e[n].toString(16).padStart(2,"0")} incoming=0x${t[n].toString(16).padStart(2,"0")})`}return`size ${s} matches; no byte difference (unexpected)`},nt=async(e,t)=>{let s;try{s=await j.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 n=await j.readFile(e);return 0===Buffer.compare(n,t)?{kind:"identical"}:{kind:"different",reason:st(n,t)}},ot=async(t,s,n)=>{console.log(`\n${T.bold(s)}`);try{const e=await j.readFile(t);if(e.length>Qe||n.length>Qe||ze(e)||ze(n))return void console.log(T.dim(`(no preview: ${st(e,n)})`));console.log(Me(e.toString("utf8"),n.toString("utf8")))}catch(o){e(o),console.log(T.dim("(no preview available)"))}},rt=async e=>{const{choice:t}=await O.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},at=async(e,t)=>{const s=t?T.yellow(" (has local changes!)"):"",{choice:n}=await O.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 n},it=async(e,t)=>{let s=C.dirname(e);const n=C.resolve(t);for(;C.resolve(s)!==n;)try{if((await j.readdir(s)).length>0)return;await j.rmdir(s),s=C.dirname(s)}catch{return}},ct=(e,t)=>C.resolve(e)===C.resolve(t)?"Application is successfully pulled.":`Application is successfully pulled into ${C.relative(t,e)}.`,lt=t=>{const s=t.getEntry(".dashnex/pull.json");if(!s)return null;try{return JSON.parse(s.getData().toString("utf8"))}catch(n){return e(n),null}},dt=(e,t)=>400===e&&Array.isArray(t.message)&&t.message.some(e=>"string"==typeof e&&/property (paged|offset|commit) should not exist/.test(e)),pt=class{async execute(o={}){n("Pull flow started");const a=await r();if(!a)return;const i=process.cwd();let c;if(o.folder)c=o.folder.trim()||".",n(`Folder argument provided: ${c}`);else{n("No folder argument, prompting user");const{folder:e}=await O.prompt([{type:"input",name:"folder",message:"Which folder to pull the application to?",default:"."}]);c=e.trim()||"."}const l=C.resolve(i,c);n(`Target folder resolved: ${l}`),await b(a,{projectDir:l});try{const e=await j.lstat(l).catch(()=>null);e&&!e.isDirectory()&&(console.error(T.red(`Cannot pull into ${l}: path exists and is not a directory.`)),t(1)),await j.ensureDir(l),n(`Target folder ensured: ${l}`)}catch(p){if(p instanceof Error&&p.message.startsWith("EXIT:"))throw p;e(p);const s=p instanceof Error?p.message:"Unknown error";console.error(T.red(`Cannot create folder ${l}: ${s}`)),t(1)}const d=ie();d.start("Analyzing local files...");try{const s=await Ke(l),r=await Ve(l,{includeGenerated:!0});n(`Local manifest has ${Object.keys(r).length} files`),d.text("Pulling application...");const c=await this.download(a.token,r,(e,t)=>d.text(`Pulling application (${e}/${t} files)...`));n(`Downloaded ${c.zips.length} zip(s) (${c.viaV2?"v2 diff":"legacy full"} pull)`),d.text("Extracting...");const u=c.zips.flatMap(e=>e.getEntries().filter(e=>!e.isDirectory)),h=c.meta,m=u.filter(e=>".dashnex"!==e.entryName&&!e.entryName.startsWith(".dashnex/"));n(`Zip has ${m.length} file entries${h?`, meta commit ${h.commit}`:", no meta"}`);const g=o.yes||"1"===process.env.DASHNEX_CI;let f=g?"all":"prompt",w=!1,y=0,$=0,v=0,b=0,k=0;const x=async(t,s,n)=>{try{return await j.ensureDir(C.dirname(t)),await j.writeFile(t,s),n&&await j.chmod(t,n),!0}catch(p){return e(p),!1}};for(const e of m){const t=e.getData(),s=C.join(l,e.entryName),o=C.relative(l,s)||e.entryName,r=(e.header.attr??0)>>16&4095,a=await nt(s,t);if(n(`Entry ${e.entryName}: ${a.kind}${a.reason?` (${a.reason})`:""}`),"identical"===a.kind){b+=1;continue}if("new"===a.kind){await x(s,t,r)?y+=1:k+=1;continue}let i=!1;if("all"===f)i=!0;else if("none"===f)i=!1;else{d.stop(),await ot(s,o,t),w||(console.log(T.dim("Y = yes (default), n = skip, a = overwrite all, s = skip all, h = help")),w=!0);const r=await rt(o);n(`Entry ${e.entryName}: user chose ${r}`),"yes"===r?i=!0:"no"===r?i=!1:"all"===r?(f="all",i=!0):(f="none",i=!1),d.start("Extracting...")}i?await x(s,t,r)?$+=1:k+=1:v+=1}d.stop();let S=0,E=0;if(h&&h.deleted.length>0){const e=await this.applyDeletions(l,h.deleted,s,g);S=e.deleted,E=e.kept}h&&(b+=Math.max(0,Object.keys(h.manifest).length-m.length)),n(`Pull summary: ${y} new, ${$} overwritten, ${v} skipped, ${S} deleted, ${b} unchanged, ${k} failed`);const D=[`${y} new`,`${$} overwritten`,`${v} skipped`,`${b} unchanged`];if((S>0||E>0)&&D.splice(3,0,`${S} deleted`),k>0&&D.push(`${k} failed`),console.log(T.cyan(`Pulled: ${D.join(", ")}`)),h){const e=await Ve(l,{includeGenerated:!0});await Ze(l,h.commit,e)}C.resolve(l)!==C.resolve(i)?(console.log(T.green(ct(l,i))),process.chdir(l),n(`Changed working directory to ${l}`)):console.log(T.green(ct(l,i))),k>0&&(console.error(T.red(`${k} file(s) failed to write. See DEBUG output for details.`)),t(1)),g?n("Non-interactive mode (--yes or --ci), skipping post-pull child commands"):await et(l,i)}catch(p){if(d.stop(),e(p),p instanceof Error&&p.message.startsWith("EXIT:"))throw p;if(h(p))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}}async download(e,t,s){const r=`${o()}/business/v1/cli/v2/pull`,a=t=>(n(`POST ${r} ${JSON.stringify({...t,manifest:void 0})}`),fetch(r,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)})),i=[];let c=null,l=0,d=!0;for(;;){const e=await a(d?{manifest:t,paged:!0,offset:l,commit:c?.commit}:{manifest:t});if(n(`v2 pull response: ${e.status}`),!e.ok){const t=await e.json().catch(()=>({}));if(d&&0===i.length&&dt(e.status,t)){n("Server does not support paged pull, retrying unpaged"),d=!1;continue}if(0===i.length&&tt(e.status,t))break;this.failFromResponse(e.status,t)}const o=new M(Buffer.from(await e.arrayBuffer()));i.push(o),c=lt(o)??c;const r=d?c?.page:void 0;if(!r||null===r.nextOffset||r.nextOffset<=l)return{zips:i,meta:c,viaV2:!0};s?.(r.nextOffset,r.total),l=r.nextOffset}n("v2 pull endpoint unavailable, falling back to legacy pull");const p=`${o()}/business/v1/cli/pull`;n(`GET ${p}`);const u=await fetch(p,{headers:{Authorization:`Bearer ${e}`}});if(n(`Legacy pull response: ${u.status}`),!u.ok){const e=await u.json().catch(()=>({}));this.failFromResponse(u.status,e)}const h=new M(Buffer.from(await u.arrayBuffer()));return{zips:[h],meta:lt(h),viaV2:!1}}failFromResponse(e,s){let n="Failed to pull application.";if(401===e||403===e)n="Please run 'dashnex login' to authenticate.";else if(404===e)n="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)(s);e&&(n=e)}console.error(T.red(n)),t(1)}async applyDeletions(t,s,o,r){let a=0,i=0;if(!o){const e=s.slice(0,20);console.log(T.yellow("These local files do not exist in the application (kept — no sync state yet):"));for(const t of e)console.log(T.yellow(` ${t}`));return s.length>e.length&&console.log(T.yellow(` … and ${s.length-e.length} more`)),{deleted:a,kept:s.length}}let c=r?"all":"prompt";for(const d of s){if(!(d in o.manifest)){n(`Deletion candidate ${d} was never synced, keeping`);continue}const s=C.join(t,d),r=await j.readFile(s).catch(()=>null);if(null===r)continue;const p=Je(r)!==o.manifest[d];let u=!1;if("all"===c)u=!0;else if("none"===c)u=!1;else{const e=await at(d,p);n(`Deletion ${d}: 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 j.remove(s),await it(s,t),a+=1}catch(l){e(l),i+=1}else i+=1}return{deleted:a,kept:i}}},ut=async e=>{const t=`${o()}/business/v1/agreements/payment-processing/status`;n(`GET ${t}`);const s=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});if(n(`Payment agreement response: ${s.status}`),!s.ok)return!0;if((await s.json().catch(()=>({}))).hasAccepted)return!0;const r=`${await(async()=>x())()}/money/agreement/`;return console.error(T.red(`You need to accept Master Payment Processing Agreement first by visiting this link: ${r}`)),!1},ht=async(t,s={})=>{const r=s.ciMode??!1;return!!(await ut(t))&&!!(await(async(t,s)=>{const r=`${o()}/business/v1/tos/latest`;n(`GET ${r}`);const a=await fetch(r,{headers:{Authorization:`Bearer ${t}`}});if(n(`TOS latest response: ${a.status}`),a.ok)return!0;if(404!==a.status)return!0;const i=`${o()}/business/v1/tos/current`;n(`GET ${i}`);const c=await fetch(i,{headers:{Authorization:`Bearer ${t}`}});if(n(`TOS current response: ${c.status}`),!c.ok)return n("Could not fetch current TOS, skipping check"),!0;const l=await c.json().catch(()=>({})),d=l.version??"unknown";if(l.text&&(console.log(T.dim("─".repeat(60))),console.log(T.bold(`Terms of Service ${d}`)),console.log(T.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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/\n{3,}/g,"\n\n").trim()),console.log(T.dim("─".repeat(60)))),s)return console.log(T.yellow(`By proceeding you accept the Terms of Service ${d}.`)),!0;const{accept:p}=await O.prompt([{type:"confirm",name:"accept",message:`By creating an application you accept the Terms of Service ${d}. Continue?`,default:!0}]);if(!p)return console.log(T.yellow("Cancelled.")),!1;try{const e=`${o()}/business/v1/tos/${l.id}/accept`;n(`POST ${e}`),await fetch(e,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch(u){e(u)}return!0})(t,r))},mt=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,gt=e=>new Promise(t=>setTimeout(t,e)),ft=e=>e.appFullCustomDomain?e.appFullCustomDomain:e.subdomain?"qa"===(process.env.APPLICATION_ENV??"")?`https://${e.subdomain}.dashnex.dev`:`https://${e.subdomain}.dashnexcloud.com`:null,wt=3e5,yt=99,$t=e=>new Promise(t=>setTimeout(t,e)),vt=async(t,s,o,r)=>{const a=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${s}`,Accept:"text/event-stream"}});if(n(`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(T.red(t)),new Error(`HTTP ${e}: ${t}`)}if(!a.body)throw new Error("Response body is null");n("SSE connection established successfully"),r?.();const i=a.body.getReader();try{for await(const t of async function*(e){const t=new TextDecoder("utf-8");let s="";for(;;){const{value:n,done:o}=await e.read();if(o)break;s+=t.decode(n,{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(!t.data){n("Received empty SSE event");continue}const e=JSON.parse(t.data);n(`SSE message received: ${JSON.stringify(e)}`),o(e)}catch(c){e(c),n(`Failed to parse SSE event data: ${t.data}`)}}finally{i.releaseLock()}},bt=class{async execute(){n("Deploy flow started");const o=await r();if(!o)return;if(await b(o,{checkApplication:!0}),!(await ht(o.token,{ciMode:!0})))return;const i=`${a()}/business/v1/applications/deploy`;n(`GET ${i} (SSE)`);let c=0,l="",d=!1,p=0,u=!1;const m=ie();let g=0,f=0,w=null;const y=(e,t)=>{const s=Math.round(e);m.text(`[${s}%] ${t}`)},$=()=>{v();const e=c,t=Date.now(),s=wt*((yt-e)/yt);w=setInterval(()=>{const n=Date.now()-t;let o;if(f>t){const e=Date.now()-f,t=yt-g,s=3030.3030303030305*t;o=Math.min(g+e/s*t,yt)}else o=Math.min(e+n/s*(yt-e),yt);o>c&&(c=o,y(c,l))},200)},v=()=>{w&&(clearInterval(w),w=null)};let k=!1;const x=e=>{if(u=!0,"string"==typeof e.error)return v(),m.stop(),console.error(T.red(e.error)),d=!0,void(k=!0);"string"==typeof e.message&&(l=e.message),"number"==typeof e.progress&&(g=e.progress,f=Date.now(),e.progress>c&&(c=e.progress)),"string"!=typeof e.message&&"number"!=typeof e.progress||(c>=100?(v(),m.stop(),d=!0):y(c,l))};for(;p<=5;)try{return u?y(c,l):m.start("Connecting..."),$(),await vt(i,o.token,x,()=>{u||(m.text(`[${Math.round(c)}%] Deployment in progress...`),l="Deployment in progress...")}),v(),m.stop(),n("SSE connection closed"),k&&t(1),void(d&&await this.showDeployedUrl(o.token))}catch(S){if(v(),S instanceof Error&&S.message.startsWith("EXIT:"))throw S;if(e(S),n(`SSE connection error: ${S}`),d)return m.stop(),void(k&&t(1));if(h(S))return m.stop(),void console.log(T.yellow(s));S instanceof Error&&S.message.startsWith("HTTP")&&(m.stop(),console.error(T.red("Could not complete deployment. Check your connection and try again.")),t(1)),p++,p>5&&(m.stop(),console.error(T.red("Deployment failed. Maximum reconnection attempts exceeded.")),t(1));const o=Math.min(1e3*Math.pow(2,p-1),3e4);n(`Connection error. Reconnecting in ${o/1e3}s... (attempt ${p}/5)`),await $t(o)}}async showDeployedUrl(t){try{const e=`${o()}/business/v1/applications`;n(`GET ${e} (for deployed URL)`);const s=await fetch(e,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok)return;const r=await s.json().catch(()=>({})),a=ft({subdomain:r.subdomain,appFullCustomDomain:r.appFullCustomDomain});a&&console.log(`Application is deployed to ${T.cyan(a)}`)}catch(s){e(s)}}},kt=104857600,xt=class extends Error{},St=class extends Error{},Et=class extends Error{},Dt="/business/v1/cli/tail-token";async function Tt(e,t={}){const s=`${o()}${Dt}${t.debug?"?debug=1":""}`;try{await fetch(s,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})}catch{}}var jt=["log","info","warn","error","debug"],Ct={error:4,warn:3,log:2,info:2,debug:1};function Pt(e){return"string"==typeof e&&jt.includes(e)}function Nt(e){return e.map(e=>"string"==typeof e?e:function(e){try{return JSON.stringify(e)}catch{return String(e)}}(e)).join(" ")}function At(e){return e<10?`0${e}`:String(e)}function It(e){const t=new Date(e);return`${At(t.getHours())}:${At(t.getMinutes())}:${At(t.getSeconds())}.${s=t.getMilliseconds(),s<10?`00${s}`:s<100?`0${s}`:String(s)}`;var s}function Ft(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 G(e,{colors:t,depth:2,breakLength:120})}var Ot={error:e=>T.red(e),warn:e=>T.yellow(e),debug:e=>T.dim(e),log:e=>e,info:e=>e};function Rt(e,t){const s=t.color?T.dim(It(e.ts)):It(e.ts),n=e.level.toUpperCase().padEnd(5),o=[s,t.color?Ot[e.level](n):n];o.push(e.args.map(e=>Ft(e,t.color)).join(" "));let r=o.join(" ");if(e.truncated){const e=" …(truncated)";r+=t.color?T.dim(e):e}return r}function Bt(e,t,s){let n;try{n=JSON.parse(e)}catch{return{kind:"malformed",raw:e}}if("object"!=typeof n||null===n||!Pt(n.level))return{kind:"malformed",raw:e};const o=n;return Array.isArray(o.args)||(o.args=void 0===o.args?[]:[o.args]),r=o.level,a=t.minLevel,Ct[r]>=Ct[a]&&function(e,t){return!t||t.test(Nt(e.args))}(o,t.filter)?{kind:"line",line:Rt(o,s)}:{kind:"filtered"};var r,a}var _t=new Set([4401,4403]);var zt=[{label:"node_modules",segments:["node_modules"],description:"installed dependencies"},{label:"node_modules/.vite",segments:["node_modules",".vite"],description:"vite cache"},{label:"node_modules/.vite-temp",segments:["node_modules",".vite-temp"],description:"vite cache"},{label:"src/dashnex",segments:["src","dashnex"],description:"generated module registry"},{label:"dist",segments:["dist"],description:"build output"}],Wt={label:".wrangler",segments:[".wrangler"],description:"local database"},Lt=async e=>{await q(e,{recursive:!0,force:!0,maxRetries:5,retryDelay:100})},Mt={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(t,s,o=5e3,r=6e4){const a=Date.now();let i=0;for(;Date.now()-a<r;){i++,n(`Polling application status (attempt ${i})...`);try{const e=await fetch(t,{headers:{Authorization:`Bearer ${s}`}});if(n(`Poll response: ${e.status}`),200===e.status){const t=await e.json();if(n(`Poll response body status: ${t.status}`),"creating"!==t.status)return n(`Application status is "${t.status}", creation complete`),{ready:!0,status:t.status};n('Application status is still "creating", continuing to poll...')}}catch(c){e(c),n(`Poll attempt ${i} failed with network error`)}await gt(o)}return{ready:!1}}async execute(a={}){n("Create flow started");const i=await r();if(!i)return;n("Auth valid, checking if business already has application");const c=ie(),l=`${o()}/business/v1/applications`;n(`GET ${l}`),c.start("Checking application status...");try{const e=await fetch(l,{headers:{Authorization:`Bearer ${i.token}`}});c.stop(),n(`Applications response: ${e.status}`),n(`Applications response body: ${await e.text()}`),404!==e.status&&(console.error(T.red("Business already has an application. Run 'dashnex app pull' to pull the existing one.")),t(1))}catch(y){if(c.stop(),e(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(h(y))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}n("No existing application, checking agreements");const d=void 0!==a.subdomain;if(!(await ht(i.token,{ciMode:d})))return;let p;n("Agreements checked, proceeding to subdomain prompt");const u=e=>`${o()}/business/v1/applications/check-subdomain?subdomain=${encodeURIComponent(e)}`;let m=a.subdomain?.trim();for(;;){if(m)p=m,m=void 0,n(`Subdomain provided via flag: ${p}`);else{if(d)return console.error(T.red("Subdomain is not available.")),void t(1);{const{sub:e}=await O.prompt([{type:"input",name:"sub",message:"Pick your subdomain:",validate:e=>!!e.trim()||"Subdomain is required"}]);p=e.trim()}}n(`Checking subdomain: ${p}`);const o=u(p);n(`GET ${o}`),c.start("Checking subdomain...");try{const e=await fetch(o,{headers:{Authorization:`Bearer ${i.token}`}});c.stop(),n(`Check subdomain response: ${e.status}`);const s=await e.text();if(n(`Check subdomain response body: ${s}`),!e.ok){const o=e.headers.get("content-type")??"";let r="Failed to check subdomain availability.";if(401!==e.status&&403!==e.status||(r="Please run 'dashnex login' to authenticate.",console.error(T.red(r)),t(1)),o.includes("application/json")){const e=JSON.parse(s);n(`Check subdomain error body: ${JSON.stringify(e)}`);const t=mt(e);t&&(r=t)}console.error(T.red(r));continue}const r=JSON.parse(s);if(n(`Check subdomain parsed body: ${JSON.stringify(r)}`),r.available){n(`Subdomain ${p} is available`);break}console.error(T.red("Subdomain is not available. Please choose a different one."))}catch(y){if(c.stop(),e(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(h(y))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}}const g=`${o()}/business/v1/cli/create`;n(`POST ${g}`);const f={subdomain:p};a.template&&(f.template=a.template,n(`Template: ${a.template}`));const w=JSON.stringify(f);n(`Create request body: ${w}`),c.start("Creating application...");try{const r=await fetch(g,{method:"POST",headers:{Authorization:`Bearer ${i.token}`,"Content-Type":"application/json"},body:w});c.stop(),n(`Create response: ${r.status}`);const l=await r.text();if(n(`Create response body: ${l}`),503===r.status){n("Create returned 503, polling for application creation..."),c.start("Waiting for application to be ready...");const e=`${o()}/business/v1/applications`,s=await this.pollApplicationCreated(e,i.token);c.stop(),s.ready||(console.error(T.red("Application creation is taking longer than expected. Try again later or run 'dashnex app pull' to check.")),t(1)),"failed"===s.status&&(console.error(T.red("Application creation failed. Please try again.")),t(1)),n("Application found after polling")}else if(!r.ok){const e=r.headers.get("content-type")??"";let s="Failed to create application.";if(401===r.status||403===r.status)s="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=JSON.parse(l);n(`Create error body parsed: ${JSON.stringify(e)}`);const t=mt(e);t&&(s=t)}console.error(T.red(s)),t(1)}let p;if(n("Application created successfully"),!0===a.pull?(p=!0,n("--pull flag set, pulling without prompting")):!1===a.pull?(p=!1,n("--no-pull flag set, skipping pull")):d?(p=!1,n("CI mode (--subdomain), skipping pull")):(p=(await O.prompt([{type:"confirm",name:"pull",message:"Pull the application locally?",default:!0}])).pull,n(`User chose to pull: ${p}`)),p){n("Running pull flow");try{await(new pt).execute()}catch(y){if(e(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(h(y))return void console.log(T.yellow(s));console.error(T.red("Failed to pull application."))}}else console.log(T.green("Application is created successfully. Run 'dashnex app pull' to pull it to your computer or 'dashnex app deploy' to deploy it to the cloud."))}catch(y){if(c.stop(),e(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(h(y))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(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 pt,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(o={}){n("Push flow started"),await j.pathExists(C.join(process.cwd(),"dashnex.json"))||(console.error(T.red("Not a DashNex application folder (dashnex.json not found).")),console.error(T.red("Run this command from your application root.")),t(1)),!1!==o.check?(n("Running pre-push checks"),await(new Be).run(!1)||(console.error(T.red("Push aborted: checks failed. Re-run with --no-check to skip.")),t(1))):n("Skipping pre-push checks (--no-check)");const a=await r();if(!a)return;await b(a,{checkApplication:!0});const i=process.cwd(),c=ie();try{c.start("Analyzing local files...");const e=await Ke(i),t=await Ve(i);n(`Local manifest has ${Object.keys(t).length} files`),c.text("Comparing with remote...");const s=await this.requestPlan(a.token,t,e?.commit);c.stop(),"legacy"===s?(n("v2 push endpoints unavailable, falling back to legacy zip push"),await this.pushLegacy(a.token,i,c)):await this.pushDiff(a.token,i,t,s,o,c),await this.promptAndDeploy(o)}catch(l){if(c.stop(),e(l),l instanceof Error&&l.message.startsWith("EXIT:"))throw l;if(h(l))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}}async requestPlan(e,t,s){const r=`${o()}/business/v1/cli/v2/push/plan`;n(`POST ${r}`);const a=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:t,lastSyncCommit:s})});if(n(`Plan response: ${a.status}`),a.ok)return await a.json();const i=await a.json().catch(()=>({}));if(((e,t)=>404===e&&"string"==typeof t.message&&t.message.startsWith("Cannot "))(a.status,i))return"legacy";this.failFromResponse(a.status,i,"Failed to push application.")}async pushDiff(e,s,o,r,a,i){let c=r;if(c.remoteChanged.length>0&&!a.force){console.error(T.red("Remote application has changes you don't have locally:"));for(const e of c.remoteChanged.slice(0,20))console.error(T.red(` ${e}`));c.remoteChanged.length>20&&console.error(T.red(` … and ${c.remoteChanged.length-20} more`)),console.error(T.red("Run 'dashnex app pull' first, or push anyway with --force.")),t(1)}const l=c.upload.filter(e=>e in o),d=await Ge(s);let p=c.delete.filter(e=>!d.ignores(e));if(0!==l.length||0!==p.length){if(p.length>0){const e=await Ke(s),t=a.yes||"1"===process.env.DASHNEX_CI;console.log(T.yellow(`${p.length} file(s) will be deleted from the application repository:`));for(const s of p.slice(0,20))console.log(T.yellow(` ${s}`));if(p.length>20&&console.log(T.yellow(` … and ${p.length-20} more`)),!t){const{confirmDelete:t}=await O.prompt([{type:"confirm",name:"confirmDelete",message:"Delete these files from the remote repository?",default:null!==e}]);t||(n("User declined remote deletions, pushing without them"),p=[])}}if(0!==l.length||0!==p.length)for(let r=1;;r+=1){i.start(1===r?"Uploading changes...":"Remote changed, retrying...");const d=await this.applyPush(e,s,l,p,c.baseCommit);if(i.stop(),"ok"===d.status){await Ze(s,d.commit,o);const e=[`${l.length} file(s) updated`];return p.length>0&&e.push(`${p.length} deleted`),console.log(T.cyan(`Pushed: ${e.join(", ")}`)),void console.log(T.green("Application pushed successfully."))}r>=2&&(console.error(T.red("Remote repository keeps changing, please retry the push.")),t(1)),n("Push apply conflicted, re-planning");const u=await Ke(s),h=await this.requestPlan(e,o,u?.commit);"legacy"===h&&(console.error(T.red("Failed to push application.")),t(1)),h.remoteChanged.length>0&&!a.force&&(console.error(T.red("Remote application changed during the push. Run 'dashnex app pull' first, or push with --force.")),t(1)),c=h}else console.log(T.green("Everything up to date."))}else console.log(T.green("Everything up to date."))}async applyPush(e,t,s,r,a){const i=new M;for(const n of s){const e=C.join(t,...n.split("/")),s=C.posix.dirname(n);i.addLocalFile(e,"."===s?"":s,C.posix.basename(n))}const c=C.join(L.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{i.writeZip(c),n(`Diff zip written to ${c} (${s.length} files, ${r.length} deletions)`),await this.ensureZipWithinLimit(c);const t=`${o()}/business/v1/cli/v2/push/apply`;n(`POST ${t}`);const l=await j.readFile(c),d=new FormData;d.append("file",new Blob([l],{type:"application/zip"}),"diff.zip"),d.append("baseCommit",a),d.append("deletions",JSON.stringify(r));const p=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:d});if(n(`Apply response: ${p.status}`),409===p.status)return{status:"conflict"};if(!p.ok){const e=await p.json().catch(()=>({}));this.failFromResponse(p.status,e,"Failed to push application.")}return{status:"ok",commit:(await p.json().catch(()=>({}))).commit??""}}finally{await j.remove(c).catch(()=>{})}}async pushLegacy(e,t,s){const r=await Ve(t),a=Object.keys(r);n(`Legacy push including ${a.length} files`);const i=new M;for(const n of a){const e=C.join(t,...n.split("/")),s=C.posix.dirname(n);i.addLocalFile(e,"."===s?"":s,C.posix.basename(n))}const c=C.join(L.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{s.start("Packaging application..."),i.writeZip(c),n(`Zip written to ${c}`),await this.ensureZipWithinLimit(c);const t=`${o()}/business/v1/cli/push`;n(`POST ${t}`);const r=await j.readFile(c),a=new FormData;a.append("file",new Blob([r],{type:"application/zip"}),"archive.zip"),s.text("Uploading...");const l=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:a});if(s.stop(),n(`Response: ${l.status}`),!l.ok){const e=await l.json().catch(()=>({}));this.failFromResponse(l.status,e,"Failed to push application.")}console.log(T.green("Application pushed successfully."))}finally{await j.remove(c).catch(()=>{}),n("Temp zip removed")}}async ensureZipWithinLimit(e){const{size:s}=await j.stat(e);if(s>kt){const e=e=>(e/1048576).toFixed(1);console.error(T.red(`Push package is ${e(s)} MB — the maximum is ${e(kt)} MB.`)),console.error(T.red("Remove or .gitignore large files and try again.")),t(1)}}failFromResponse(e,s,n){let o=n;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)(s);e&&(o=e)}console.error(T.red(o)),t(1)}async promptAndDeploy(e){let t;void 0!==e.deploy?(t=e.deploy,n(`Deploy decided via flag: ${t}`)):"1"===process.env.DASHNEX_CI?(t=!1,n("CI mode: skipping deploy prompt (use --deploy to deploy)")):(t=(await O.prompt([{type:"confirm",name:"deploy",message:"Deploy the application?",default:!0}])).deploy,n(`User chose to deploy: ${t}`)),t&&(n("Running deploy flow"),await(new bt).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(a={}){if(n("Delete flow started"),!a.yes){const{confirm:e}=await O.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 n("User cancelled deletion"),void console.log(T.yellow("Deletion cancelled."))}const i=await r();if(!i)return;await b(i,{checkApplication:!0});const c=`${o()}/business/v1/applications`;n(`DELETE ${c}`);const l=ie();l.start("Deleting application...");try{const e=await fetch(c,{method:"DELETE",headers:{Authorization:`Bearer ${i.token}`}});if(l.stop(),n(`Response: ${e.status}`),!e.ok){const s=e.headers.get("content-type")??"";let n="Failed to delete application.";if(401===e.status||403===e.status)n="Please run 'dashnex login' to authenticate.";else if(s.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&&(n=t)}console.error(T.red(n)),t(1)}const s=await e.json().catch(()=>({})),o="string"==typeof s.message?s.message:"Application deleted successfully.";n("Application deleted successfully"),console.log(T.green(o))}catch(d){if(l.stop(),e(d),d instanceof Error&&d.message.startsWith("EXIT:"))throw d;if(h(d))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}}},options:[{flags:"-y, --yes",description:"Skip confirmation prompt"}]},{name:"deploy",description:"Deploy application to DashNex",handler:new bt,options:[]},{name:"status",description:"Show current application status",handler:new class{async execute(){n("Status flow started");const a=await r();if(!a)return;const i=`${o()}/business/v1/applications`;n(`GET ${i}`);const c=ie();c.start("Fetching application status...");try{const e=await fetch(i,{headers:{Authorization:`Bearer ${a.token}`}});if(c.stop(),n(`Response: ${e.status}`),404===e.status)return void console.log(T.yellow("Application not created"));if(!e.ok){const s=e.headers.get("content-type")??"";let n="Failed to fetch application status.";if(401===e.status||403===e.status)n="Please run 'dashnex login' to authenticate.";else if(s.includes("application/json")){const t=await e.json().catch(()=>({}));"string"==typeof t.error?n=t.error:"string"==typeof t.message&&(n=t.message)}console.error(T.red(n)),t(1)}const s=await e.json().catch(()=>({}));n(`Application body: ${JSON.stringify(s)}`);const o=a.userName?`${a.userName} (${a.businessId})`:a.businessId;console.log(`Business: ${T.cyan(o||"unknown")}`);const r=void 0!==s.id?String(s.id):void 0;r&&console.log(`Application ID: ${T.cyan(r)}`);const l=s.status??"unknown";console.log(`Status: ${T.cyan(l)}`);const d=ft(s);d&&console.log(`URL: ${T.cyan(d)}`),console.log(`Session: ${T.cyan(a.settingsPath??"DASHNEX_TOKEN environment variable")}`),await f(a,r)}catch(l){if(c.stop(),e(l),l instanceof Error&&l.message.startsWith("EXIT:"))throw l;if(h(l))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}}},options:[]},{name:"clear",description:"Delete local dependencies, caches and build output",handler:new class{async execute(t={}){n("Clear flow started");const o=process.cwd();j.pathExistsSync(C.join(o,"dashnex.json"))||(console.error(T.red("Run this command in a DashNex Web application folder.")),process.exit(1));const r=t.yes||"1"===process.env.DASHNEX_CI;n(`Non-interactive: ${r}`),r||process.stdin.isTTY||(console.error(T.red("'dashnex app clear' needs confirmation. Run it in a terminal, or pass -y to clear without prompts (the local database is kept).")),process.exit(1));try{const t=await this.collectTargets(o),s=C.join(o,...Wt.segments),i=await j.pathExists(s)&&!r;if(0===t.length&&!i)return void console.log(T.yellow("Nothing to clear."));const c=[];let l=0;if(t.length>0){console.log("The following will be deleted:");for(const e of t)console.log(` ${T.cyan(e.label)} ${T.dim(`(${e.description})`)}`);if(!r){const{confirm:e}=await O.prompt([{type:"confirm",name:"confirm",message:"Delete these files?",default:!1}]);if(!e)return n("User cancelled clear"),void console.log(T.yellow("Cancelled."))}const s=[],i=ie();for(const r of t){const t=C.join(o,...r.segments);n(`Removing ${t}`),i.start(`Removing ${r.label}...`);try{await Lt(t),s.push(r.label)}catch(a){e(a),c.push(r.label)}}i.stop();for(const e of s)console.log(T.green(`Removed ${e}`));l+=s.length}if(i){const{confirm:t}=await O.prompt([{type:"confirm",name:"confirm",message:"Delete the local database as well?",default:!1}]);if(t){n(`Removing ${s}`);try{await Lt(s),console.log(T.green(`Removed ${Wt.label}`)),l++}catch(a){e(a),c.push(Wt.label)}}}if(c.length>0){for(const e of c)console.error(T.red(`Could not delete ${e} — it may be in use. Stop 'dashnex dev' and try again.`));process.exit(1)}if(0===l)return void console.log(T.yellow("Nothing was deleted."));console.log(T.green("Clear complete. Run 'dashnex install' to set the application up again."))}catch(a){if(a instanceof Error&&a.message.startsWith("EXIT:"))throw a;if(e(a),h(a))return void console.log(T.yellow(s));throw a}}async collectTargets(e){const t=[];for(const s of zt)await j.pathExists(C.join(e,...s.segments))&&t.push(s);return t.filter(s=>!t.some(t=>t!==s&&((e,t)=>{const s=C.relative(t,e);return""!==s&&!s.startsWith("..")&&!C.isAbsolute(s)})(C.join(e,...s.segments),C.join(e,...t.segments))))}},options:[{flags:"-y, --yes",description:"Skip prompts and keep the local database (CI mode)"}]},{name:"tail",description:"Stream live console/debug logs from the deployed worker (Ctrl+C to stop)",handler:new class{async execute(t={}){const s=t.level??"log";Pt(s)||(console.error(T.red(`Invalid --level '${t.level}'. Use one of: log, info, warn, error, debug.`)),process.exit(1));let a=null;if(t.filter)try{a=new RegExp(t.filter)}catch{console.error(T.red(`Invalid --filter regular expression: ${t.filter}`)),process.exit(1)}const i=await r();if(!i)return;await b(i);const c=!!t.debug;let l;try{l=await async function(e,t={}){const s=`${o()}${Dt}`;n(`POST ${s}${t.debug?" (debug)":""}`);const r=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({debug:!!t.debug})});if(n(`Response: ${r.status}`),401===r.status||403===r.status)throw new xt("Not authorised to tail this application.");if(404===r.status)throw new St("Business has no application, or the tail endpoint is unavailable.");if(!r.ok)throw new Et(`Failed to start tail (status ${r.status}).`);const a=await r.json().catch(()=>({}));if(!a.token||!a.workerUrl)throw new Et("Malformed tail-token response from the platform.");return{token:a.token,workerUrl:a.workerUrl,expiresAt:"number"==typeof a.expiresAt?a.expiresAt:0}}(i.token,{debug:c})}catch(v){e(v),v instanceof xt&&(console.error(T.red(v.message)),process.exit(1)),v instanceof St&&(console.error(T.red(v.message)),process.exit(2)),console.error(T.red(v instanceof Error?v.message:"Could not start tail. Check your connection.")),process.exit(3)}const d={color:!!process.stdout.isTTY},p={minLevel:s,filter:a},u=(h=l.workerUrl,`${/^(localhost|127\.0\.0\.1)/.test(h)?"ws":"wss"}://${h}/api/realtime/tail`);var h;const m=`dashnex.tail.token.${l.token}`;console.log(T.dim(`Tailing ${l.workerUrl} — Ctrl+C to stop.`)),c&&console.log(T.dim("Debug logging enabled on the worker (DEBUG=1); may take a minute to take effect."));let g=!1,f=Date.now();const w=setInterval(()=>{g||Date.now()-f>=3e4&&(console.log(T.dim("(no logs in 30s)")),f=Date.now())},5e3),y=new H(u,m,{WebSocket:J,connectionTimeout:1e4,maxReconnectionDelay:16e3}),$=async e=>{if(!g){g=!0,clearInterval(w);try{y.close()}catch{}await Promise.race([Tt(i.token,{debug:c}),new Promise(e=>setTimeout(e,3e3))]),process.exit(e)}};process.on("SIGINT",()=>{console.log(),$(0)}),y.binaryType="arraybuffer",y.addEventListener("message",e=>{f=Date.now();const t=Bt("string"==typeof e.data?e.data:"",p,d);"line"===t.kind?console.log(t.line):"malformed"===t.kind&&console.error(T.dim(`[malformed frame] ${t.raw}`))}),y.addEventListener("close",e=>{if(!g)return _t.has(e.code)?(console.error(T.red("Tail token was rejected (auth). Exiting.")),void $(1)):void n(`socket closed (code ${e.code}); reconnecting…`)}),y.addEventListener("error",e=>{n(`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"}]}]},Ut={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(){n("Secrets list flow started");const a=await r();if(!a)return;await b(a);const i=`${o()}/business/v1/cli/secrets`;n(`GET ${i}`);const c=ie();c.start("Fetching secrets...");try{const e=await fetch(i,{headers:{Authorization:`Bearer ${a.token}`}});if(c.stop(),n(`Response: ${e.status}`),!e.ok){let s="Failed to fetch secrets.";401===e.status||403===e.status?s="Please run 'dashnex login' to authenticate.":404===e.status?s="Business has no application.":502===e.status&&(s="Error fetching secrets. Make sure your application is deployed."),console.error(T.red(s)),t(1)}const s=(await e.json()).secrets??[];if(0===s.length)return void console.log(T.yellow("No secrets set."));console.log(T.bold(`\nSecrets (${s.length}):\n`)),s.forEach(({name:e})=>{console.log(` ${T.cyan(e)}`)}),console.log("")}catch(l){if(c.stop(),e(l),l instanceof Error&&l.message.startsWith("EXIT:"))throw l;if(h(l))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}}},options:[]},{name:"set",description:"Create or update a secret (prompts for missing KEY/VALUE)",handler:new class{async execute(a={}){n("Secrets set flow started");let{name:i,value:c}=a;const l="1"===process.env.DASHNEX_CI;i||(l&&(console.error(T.red("--name is required in CI mode (--ci).")),t(1)),i=(await O.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim()),c||(l&&(console.error(T.red("--value is required in CI mode (--ci).")),t(1)),c=(await O.prompt([{type:"password",name:"value",message:`Enter value for ${i}:`,mask:"*",validate:e=>""!==e||"Value is required"}])).value);const d=await r();if(!d)return;await b(d);const p=`${o()}/business/v1/cli/secrets`;n(`PUT ${p}`);const u=ie();u.start(`Setting secret '${i}'...`);try{const e=await fetch(p,{method:"PUT",headers:{Authorization:`Bearer ${d.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i,value:c})});if(u.stop(),n(`Response: ${e.status}`),!e.ok){let s="Failed to set secret.";401===e.status||403===e.status?s="Please run 'dashnex login' to authenticate.":400===e.status?s="Missing or empty name / value.":404===e.status?s="Business has no application.":502===e.status&&(s="Error setting secret. Make sure your application is deployed."),console.error(T.red(s)),t(1)}n(`Secret '${i}' set successfully`),console.log(T.green(`Secret '${i}' set successfully.`))}catch(m){if(u.stop(),e(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(h(m))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(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(a={}){n("Secrets delete flow started");let{name:i}=a;const c="1"===process.env.DASHNEX_CI;i||(c&&(console.error(T.red("--name is required in CI mode (--ci).")),t(1)),i=(await O.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim());const l=await r();if(!l)return;await b(l);const d=`${o()}/business/v1/cli/secrets/${encodeURIComponent(i)}`;n(`DELETE ${d}`);const p=ie();p.start(`Deleting secret '${i}'...`);try{const e=await fetch(d,{method:"DELETE",headers:{Authorization:`Bearer ${l.token}`}});if(p.stop(),n(`Response: ${e.status}`),!e.ok){let s="Failed to delete secret.";401===e.status||403===e.status?s="Please run 'dashnex login' to authenticate.":404===e.status?s=`Secret '${i}' not found.`:502===e.status&&(s="Error deleting secret. Make sure your application is deployed."),console.error(T.red(s)),t(1)}n(`Secret '${i}' deleted successfully`),console.log(T.green(`Secret '${i}' deleted.`))}catch(u){if(p.stop(),e(u),u instanceof Error&&u.message.startsWith("EXIT:"))throw u;if(h(u))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}}},arguments:[{name:"name",description:"Secret name (KEY)"}],options:[{flags:"--name <name>",description:"Secret name (alternative to positional KEY)"}]}]},Xt=async(e,t)=>{const s=C.join(e,".npmrc");return!!(await j.pathExists(s))&&(await j.copy(s,C.join(t,".npmrc"),{overwrite:!0}),await(async e=>{const t=C.join(e,".gitignore"),s=await j.pathExists(t)?await j.readFile(t,"utf8"):"";if(s.split(/\r?\n/).some(e=>".npmrc"===e.trim()))return;const n=""===s||s.endsWith("\n")?s:`${s}\n`;await j.writeFile(t,`${n}.npmrc\n`)})(t),!0)},Ht=["node_modules","dist",".git","coverage"],Jt=e=>e.replace(/\\/g,"/").split("/").filter(e=>""!==e),Gt=async(e,t)=>{const s=await(async e=>{const t=/* @__PURE__ */new Set;return await Y.t({file:e,onReadEntry:e=>{const[s]=Jt(e.path);t.add(s??"")}}),1===t.size?1:0})(e);await j.ensureDir(t),await Y.x({file:e,cwd:t,strip:s,filter:e=>{const t=Jt(e),n=s>0?t.slice(s):t.filter(e=>"."!==e);return!(void 0!==n[0]&&Ht.includes(n[0]))}})},qt=async(e,t,s)=>{const n=C.join(e,"package.json"),o=await j.readJson(n);o.name=`@dashnex/${t}`,o.description=s,o.version="0.1.0",await j.writeJson(n,o,{spaces:2})},Yt=async(e,t)=>{const s=C.join(e,"package.json"),n=await j.readJson(s),o={...n.dependencies??{},[`@dashnex/${t}`]:`link:packages/${t}`};n.dependencies=Object.fromEntries(Object.entries(o).sort(([e],[t])=>e<t?-1:e>t?1:0)),await j.writeJson(s,n,{spaces:2})},Vt="Run this command in a DashNex Web application folder.",Kt="Could not reach DashNex API. Check your connection and try again.",Zt=class extends Error{},Qt=e=>(console.error(T.red(e)),t(1)),es=e=>e instanceof Error&&e.message.startsWith("EXIT:"),ts=async t=>{try{return await t()}catch(s){if(es(s)||h(s))throw s;throw e(s),new Zt(s instanceof Error?s.message:String(s))}},ss="@dashnex/",ns=e=>{const t=e.trim();return(t.startsWith(ss)?t.slice(9):t).toLowerCase()},os=e=>`${ss}${e}`,rs=()=>x().replace(/^https?:\/\//,""),as=()=>`Join the Developers program first: ${rs()} → Developers.`,is=e=>`${os(e)} isn't reserved by this business.`,cs=e=>`Bump the version (run pnpm version patch in packages/${e}) and submit again.`,ls=(e,t)=>`${os(e)}${t?` v${t}`:""} is already in review. Wait for the decision before submitting again.`,ds=e=>(console.error(T.red(e)),t(1)),ps=e=>({Authorization:`Bearer ${e}`}),us=(e,t)=>ds(401===e||403===e?"Please run 'dashnex login' to authenticate.":t),hs=async e=>{const t=`${o()}/business/v1/cli/developers/access`;n(`GET ${t}`);const s=await fetch(t,{headers:ps(e)});if(n(`Developer access response: ${s.status}`),!s.ok)return{ok:!1,status:s.status};const r=await s.json().catch(()=>null);if("object"!=typeof r||null===r||Array.isArray(r))return{ok:!1,status:s.status};const a=r;return{ok:!0,access:{agreementAccepted:!0===a.agreementAccepted,reservations:Array.isArray(a.reservations)?a.reservations:[]}}},ms=e=>e.ok?e.access:us(e.status,"Failed to check developer access."),gs=(e,t)=>{if(!e.agreementAccepted)return ds(as());if(0===e.reservations.length)return ds(`Reserve a module name first: ${rs()} → Developers.`);if(void 0===t)return;const s=ns(t),n=e.reservations.find(e=>ns(e.address)===s);return n||ds(is(s))},fs=async(e,t)=>{const s=await(async e=>ms(await hs(e)))(e),n=gs(s,t);return n?{access:s,reservation:n}:{access:s}},ws=["version_not_higher","not_reserved","in_review","agreement_required"],ys=e=>[`Created packages/${e} (${os(e)}).`,"Next steps:",` 1. cd packages/${e} && pnpm install && pnpm build`," 2. dashnex install && dashnex dev (links the module into your app)",` 3. dashnex module submit ${e} (when it is ready for review)`].join("\n"),$s=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/,vs=(e,t)=>{const s=$s.exec(e),n=$s.exec(t);if(!s||!n)return null;for(let a=1;a<=3;a++){const e=Number(s[a])-Number(n[a]);if(0!==e)return e}const o=s[4],r=n[4];return o||r?o?r?((e,t)=>{const s=e.split("."),n=t.split("."),o=Math.min(s.length,n.length);for(let r=0;r<o;r++){const e=s[r],t=n[r],o=/^\d+$/.test(e),a=/^\d+$/.test(t);if(o&&a){const s=Number(e)-Number(t);if(0!==s)return s;continue}if(o!==a)return o?-1:1;if(e!==t)return e<t?-1:1}return s.length-n.length})(o,r):-1:1:0},bs=t=>new Promise(s=>{const n=t();n.on("error",t=>{e(t),s(1)}),n.on("close",e=>{s(e??1)})}),ks=(e,t,s)=>{switch(e.status){case"accepted":return void console.log(T.green(((e,t)=>`Submitted ${os(e)} v${t} for review. Status: In review.`)(t,s)));case"version_not_higher":return Qt(cs(t));case"not_reserved":return Qt(is(t));case"in_review":return Qt(ls(t));case"agreement_required":return Qt(as());case"error":return Qt(e.message)}},xs={name:"module",description:"Develop marketplace modules (run in DashNex application folder)",handler:{execute:async()=>{}},options:[],subcommands:[{name:"init",description:"Create reserved modules in packages/ from the module template",handler:new class{async execute(a={}){n("Module init flow started");const i=!0===a.ci||"1"===process.env.DASHNEX_CI,c=process.cwd();if(!(await j.pathExists(C.join(c,"dashnex.json"))))return Qt(Vt);const l=C.join(L.tmpdir(),`dashnex-template-${z(6).toString("hex")}.tgz`),d=ie(),p=()=>j.remove(l).catch(()=>{});try{const t=await ts(()=>r());if(!t)return;const{access:s,reservation:p}=await ts(()=>fs(t.token,a.address)),g=C.join(c,"packages");let f;if(await j.ensureDir(g),p){if(await j.pathExists(C.join(g,p.address)))return Qt(`packages/${p.address} already exists.`);f=[p]}else{const e=[];for(const t of s.reservations)await j.pathExists(C.join(g,t.address))||e.push(t);if(0===e.length)return void console.log(T.yellow("All reserved modules already exist in packages/."));if(f=await(async(e,t,s)=>{if(t.all||1===e.length)return e;if(s)return Qt("Pass an address or --all in CI mode.");const{addresses:n}=await O.prompt([{type:"checkbox",name:"addresses",message:"Which modules do you want to create?",choices:e.map(e=>({name:`${e.moduleName} (${os(e.address)})`,value:e.address,checked:!0}))}]);return e.filter(e=>n.includes(e.address))})(e,a,i),0===f.length)return void console.log(T.yellow("No modules selected."))}d.start("Downloading the module template...");const w=await ts(()=>(async e=>{const t=`${o()}/business/v1/cli/developers/template`;n(`GET ${t}`);const s=await fetch(t,{headers:ps(e)});return n(`Module template response: ${s.status}`),s.ok?{ok:!0,bytes:Buffer.from(await s.arrayBuffer())}:{ok:!1,status:s.status}})(t.token));d.stop(),await j.writeFile(l,(u=w,u.ok?u.bytes:us(u.status,"Failed to download the module template.")));let y=!1;for(const{address:n,moduleName:o}of f){const t=C.join(g,n);try{await j.ensureDir(t),await Gt(l,t),await qt(t,n,o),await Xt(c,t)||(y=!0),await Yt(c,n)}catch(m){if(await j.remove(t).catch(()=>{}),es(m)||h(m))throw m;return e(m),Qt(`Failed to create packages/${n}: ${m instanceof Error?m.message:String(m)}`)}console.log(T.green(ys(n)))}y&&console.log(T.yellow("No DashNex registry token found (.npmrc). Deploy your app once, then run 'dashnex app pull' before building or submitting."))}catch(m){if(d.stop(),await p(),e(m),es(m))throw m;if(h(m))return void console.log(T.yellow(s));m instanceof Zt?console.error(T.red(Kt)):console.error(T.red(`Module init failed: ${m instanceof Error?m.message:String(m)}`)),t(1)}finally{await p(),n("Temp template tarball removed")}var u}},arguments:[{name:"address",description:"Module address to create (prompts when several are missing)"}],options:[{flags:"--all",description:"Create every reserved module that is not in packages/ yet"}]},{name:"submit",description:"Build, publish and submit a module for review",handler:new class{async execute(a){n("Module submit flow started");const i=process.cwd(),c=ns(a.address),l=os(c);if(!(await j.pathExists(C.join(i,"dashnex.json"))))return Qt(Vt);const d=ie();try{const t=await ts(()=>r());if(!t)return;d.start("Checking developer access...");const s=await ts(()=>hs(t.token));d.stop();const a=gs(ms(s),c),p=(e=>{const t=e?.inReview;if("object"!=typeof t||null===t)return;const{version:s}=t;return"string"==typeof s&&""!==s?s:void 0})(a);if(p)return Qt(ls(c,p));const u=C.join(i,"packages",c);if(!(await j.pathExists(C.join(u,"package.json"))))return Qt(`packages/${c} not found. Run 'dashnex module init ${c}' first.`);const h=await(async(e,t)=>{const s=C.join(e,"package.json"),n=await j.readJson(s).catch(()=>null);return n?.name!==os(t)?Qt(`packages/${t}/package.json must be named ${os(t)}.`):"string"!=typeof n.version||""===n.version?Qt(`packages/${t}/package.json must have a version.`):n.version})(u,c),m=a?.lastSubmittedVersion;if(m&&!((e,t)=>{const s=vs(e,t);return null!==s&&s>0})(h,m))return Qt(cs(c));const g=await(async e=>{const t=C.join(e,".npmrc");if(!(await j.pathExists(t)))return null;const s=(e=>{const t={};for(const s of e.split(/\r?\n/)){const e=s.trim();if(!e||e.startsWith("#"))continue;const n=e.indexOf("=");-1!==n&&(t[e.slice(0,n).trim()]=e.slice(n+1).trim())}return t})(await j.readFile(t,"utf8")),n=s["@dashnex:registry"]||"https://npm.dashnex.com/";let o;try{o=new URL(n).host}catch{return null}const r=s[`//${o}/:_authToken`];return r?{registry:n,host:o,token:r}:null})(i);if(!g)return Qt("No DashNex registry token found (.npmrc). Deploy your app once, then run 'dashnex app pull' and submit again.");await Xt(i,u),d.start(`Installing dependencies for ${l}...`);const f=await De(u);if(d.stop(),0!==f)return Qt("Build failed.");if(console.log(`Building ${l}...`),0!==await(async(e,t)=>{const s=`${await Ee("pnpm")?"pnpm":"npm"} run ${t}`;return n(`Executing: ${s} in ${e}`),bs(()=>A(s,{cwd:e,shell:!0,stdio:"inherit"}))})(u,"build"))return Qt("Build failed.");if(await(async(t,s,o,r)=>{const a=`${t.replace(/\/+$/,"")}/@dashnex%2F${o}`;n(`GET ${a}`);try{const e=await fetch(a,{headers:{Authorization:`Bearer ${s}`}});if(n(`Registry responded ${e.status}`),200!==e.status)return!1;const t=await e.json();return Boolean(t.versions?.[r])}catch(i){return e(i),!1}})(g.registry,g.token,c,h))console.log(T.yellow(`v${h} is already in the registry, skipping publish.`));else if(0!==await(async(e,t)=>{const s=["publish","--registry",t,"--tag","review"],o={cwd:e,stdio:"inherit",shell:"win32"===process.platform};return n(`Executing: npm ${s.join(" ")} in ${e}`),bs(()=>A("npm",s,o))})(u,g.registry))return Qt(`Publishing ${l} v${h} failed.`);d.start("Submitting for review...");const w=await ts(()=>(async(e,t,s)=>{const r=`${o()}/business/v1/cli/developers/submissions`;n(`POST ${r}`);const a=await fetch(r,{method:"POST",headers:{...ps(e),"Content-Type":"application/json"},body:JSON.stringify({address:t,version:s})});n(`Module submission response: ${a.status}`);const i=await a.json().catch(()=>({}));if(202===a.status)return{status:"accepted",submissionId:String(i.submissionId??"")};if(409===a.status)return{status:"agreement_required"};if(400===a.status){const e=ws.find(e=>e===i.code);if(e)return{status:e}}const c=i.message??i.error??"Failed to submit the module.";return{status:"error",message:String(c)}})(t.token,c,h));d.stop(),ks(w,c,h)}catch(p){if(d.stop(),e(p),es(p))throw p;if(h(p))return void console.log(T.yellow(s));p instanceof Zt?console.error(T.red(Kt)):console.error(T.red(`Module submit failed: ${p instanceof Error?p.message:String(p)}`)),t(1)}}},arguments:[{name:"address",description:"Module address (the part after @dashnex/)",required:!0}],options:[]}]},Ss=[{name:"version",description:"Display the version of the CLI",handler:new class{async execute(e){const t=C.dirname(P(import.meta.url)),s=JSON.parse(F.readFileSync(C.resolve(t,"..","..","package.json"),"utf8"));console.log(s.version)}},options:[]},{name:"login",description:"Log in to your DashNex account",handler:new class{async execute(o={}){n("Login flow started");const a=process.cwd(),c=await w(a)??g(a);n(`Settings file: ${c}`);const l=await $(a),d=o.business??l?.businessId,p=await r({exitOnFailure:!1,dashnexPath:c});if(p){if(!d||u(d,p.businessId))return console.log(T.green(`Already logged in as ${p.userName??"user"} (business ${p.businessId})`)),void console.log(T.dim(`Session: ${p.settingsPath??"DASHNEX_TOKEN environment variable"}`));!o.business&&l?.businessId&&console.log(T.yellow(`Signed in to business ${p.businessId}, but this folder belongs to business ${l.businessId}.`))}!o.business&&l?.businessId&&console.log(T.dim(`Using business ${l.businessId} from ${l.envPath} (--business picks another).`)),E()||(console.error(T.red("No DashNex ID OAuth client is configured for this environment.")),console.error(T.yellow("Set DASHNEX_OAUTH_CLIENT_ID, or use APPLICATION_ENV=qa.")),t(1));try{const e=await j.pathExists(c)?await i(c):null;if(e){n("Resuming with saved DashNex ID session");try{return void(await this.selectBusiness(e,c,d))}catch(f){if(!(f instanceof te))throw f;n("Saved DashNex ID session rejected, starting a new sign-in")}}const t=await this.authorize(!1!==o.browser);await pe(c,{id:{token:t.token,expiresAt:m(t.expiresIn),...t.refreshToken&&{refreshToken:t.refreshToken}}}),await this.selectBusiness(t.token,c,d)}catch(f){if(e(f),h(f))return void console.log(T.yellow(s));if((f instanceof Q||f instanceof ee)&&(console.error(T.red(f.message)),t(1)),f instanceof Error&&f.message.startsWith("EXIT:"))throw f;console.error(T.red("Could not reach DashNex. Check your connection and try again.")),t(1)}}async authorize(e){const{verifier:t,challenge:s}=(()=>{const e=V(z(32));return{verifier:e,challenge:V(B("sha256").update(e).digest())}})(),o=(e=>{const t=new URL(`${D()}/api/oauth/authorize`);return t.searchParams.set("client_id",E()),t.searchParams.set("redirect_uri",Z),t.searchParams.set("response_type","code"),t.searchParams.set("code_challenge",e),t.searchParams.set("code_challenge_method","S256"),t.searchParams.set("scope","business"),t.toString()})(s);n(`Authorize URL: ${o}`);const r=!!e&&await K(o);console.log(""),r?(console.log(T.green("Opened your browser to finish signing in.")),console.log(T.dim("If nothing opened, use this URL:"))):console.log(T.bold("Open this URL to sign in:")),console.log(T.cyan(o)),console.log(""),console.log(T.dim("Approve the request, then copy the code shown and paste it below.")),console.log("");const{code:a}=await O.prompt([{type:"input",name:"code",message:"Paste the code:",validate:e=>!!e.trim()||"Code is required"}]),i=ie();i.start("Verifying code...");try{return await(async(e,t)=>{const s=`${D()}/api/oauth/token`;n(`POST ${s}`);const{response:o,body:r}=await p(s,{method:"POST",body:JSON.stringify({grant_type:"authorization_code",client_id:E(),redirect_uri:Z,code:e.trim(),code_verifier:t})});if(n(`Response: ${o.status}`),S("Token response",r),!o.ok){const e="string"==typeof r.error?r.error:void 0,t="string"==typeof r.error_description?r.error_description:void 0;if("invalid_grant"===e)throw new Q("That code is not valid anymore. Codes expire 10 minutes after they are issued and can only be used once.",e);throw new Q(t??"Could not exchange the code for a token.",e)}const a=r;if(!a.access_token)throw new Q("The authorization server did not return an access token.");return{token:a.access_token,refreshToken:a.refresh_token,expiresIn:a.expires_in}})(a,t)}finally{i.stop()}}async selectBusiness(e,t,s){const n=await ce(e,t,{businessId:s});console.log(T.green(`Logged in as ${n.name} (business ${n.id})`)),console.log(T.dim(`Session: ${t}`))}},options:[{flags:"--business <id>",description:"Business ID to select (skip prompt)"},{flags:"--no-browser",description:"Print the sign-in URL instead of opening a browser"}]},{name:"logout",description:"Log out and remove local credentials",handler:new class{async execute(){const e=await w(process.cwd());e?(await l(e,e=>{delete e.business,delete e.id}),console.log(T.green("Logged out.")),console.log(T.dim(`Session removed from ${e}`))):console.log(T.green("Logged out."))}},options:[]},{name:"switch",description:"Switch to another business (prompts when no ID is given)",handler:new class{async execute(o={}){n("Switch flow started");const r=await w(process.cwd()),a=r?await c(r):null;r&&a?.business?.token||(console.error(T.red("Please run 'dashnex login' to authenticate.")),t(1));const l=a.id;l?.token||(console.error(T.red("Switching businesses requires signing in with DashNex ID.")),console.error(T.yellow("Run 'dashnex logout' and then 'dashnex login' to sign in again.")),t(1));const d=e=>ce(e,r,{businessId:o.businessId,currentBusinessId:a.business?.id});try{const e=await i(r)??l.token;let t;try{t=await d(e)}catch(p){if(!(p instanceof te))throw p;n("DashNex ID session rejected, refreshing");const e=await k(r);if(!e)throw p;t=await d(e)}console.log(T.green(`Switched to ${t.name} (business ${t.id})`)),console.log(T.dim(`Session: ${r}`));const s=await $();s?.businessId&&!u(s.businessId,t.id)&&console.warn(T.yellow(`Warning: this folder belongs to business ${s.businessId} (BUSINESS_ID in ${s.envPath}).`))}catch(p){if(e(p),h(p))return void console.log(T.yellow(s));if(p instanceof te&&(console.error(T.red(p.message)),console.error(T.yellow("Run 'dashnex logout' and then 'dashnex login' to sign in again.")),t(1)),p instanceof ee&&(console.error(T.red(p.message)),t(1)),p instanceof Error&&p.message.startsWith("EXIT:"))throw p;console.error(T.red("Could not reach DashNex. Check your connection and try again.")),t(1)}}},arguments:[{name:"businessId",description:"Business ID to switch to (skip prompt)"}],options:[]},{name:"whoami",description:"Show current logged-in business and user",handler:new class{async execute(){n("Whoami flow started");const a=await r();if(!a)return;const i=await v()?`${o()}/business/v1/`:`${d()}/users/v1/`;n(`GET ${i}`);const c=ie();c.start("Fetching user info...");try{const e=await fetch(i,{headers:{Authorization:`Bearer ${a.token}`}});if(c.stop(),n(`Response: ${e.status}`),!e.ok){const s=e.headers.get("content-type")??"";let n="Failed to fetch user info.";if(401===e.status||403===e.status)n="Please run 'dashnex login' to authenticate.";else if(s.includes("application/json")){const t="string"==typeof(l=await e.json().catch(()=>({}))).error?l.error:"string"==typeof l.message?l.message:void 0;t&&(n=t)}console.error(T.red(n)),t(1)}const s=await e.json().catch(()=>({})),o="string"==typeof s.name?s.name:"string"==typeof s.companyName?s.companyName:"Unknown",r=s.memberUser,d=r&&"string"==typeof r.fullName?r.fullName:r&&"string"==typeof r.name?r.name:"Unknown";n(`Whoami: ${o} (${d})`),console.log(T.green(`You are logged in as ${o} (${d})`)),console.log(`Business ID: ${T.cyan(a.businessId||"unknown")}`),console.log(`Session: ${T.cyan(a.settingsPath??"DASHNEX_TOKEN environment variable")}`),await f(a)}catch(p){if(c.stop(),e(p),p instanceof Error&&p.message.startsWith("EXIT:"))throw p;if(h(p))return void console.log(T.yellow(s));console.error(T.red("Could not reach DashNex API. Check your connection and try again.")),t(1)}var l}},options:[]},{name:"dev",description:"Run the development server (run in DashNex application folder)",handler:new class{async execute(t={}){n("Dev flow started");try{const e=await Se(process.cwd(),t);process.exit(e)}catch(s){if(s instanceof Error&&s.message.startsWith("EXIT:"))throw s;e(s),s instanceof Error?console.error(T.red(s.message)):console.error(T.red("Failed to run npm run dev")),process.exit(1)}}},options:[{flags:"-p, --port <port>",description:"Port for the dev server (default: PORT env or 3000)"},{flags:"-H, --host <host>",description:"Host to bind, e.g. 0.0.0.0 inside Docker (default: HOST env or localhost)"},{flags:"--https",description:"Serve over HTTPS with a trusted local certificate (mkcert)"}]},{name:"check",description:"Run build-time validations (run in DashNex application folder)",handler:new Be,options:[]},{name:"install",description:"Install dependencies using pnpm (preferred) or npm (run in DashNex application folder)",handler:new class{async execute(){n("Install flow started");const t=C.join(process.cwd(),"dashnex.json");await j.pathExists(t)||(console.error(T.red("Run this command in a DashNex Web application folder.")),process.exit(1));const s=process.cwd(),o=ie();o.start("Installing dependencies...");try{const e=await De(s);o.stop(),0!==e&&process.exit(e),console.log(T.green("Dependencies installed.")),process.exit(0)}catch(r){o.stop(),e(r),r instanceof Error?console.error(T.red(r.message)):console.error(T.red("Failed to run install")),process.exit(1)}}},options:[]},Mt,Ut,xs];export{Ss as default};
|
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as s,t as e}from"./chunks/dashnex-
|
|
1
|
+
import{n as s,t as e}from"./chunks/dashnex-CT3PnUmH.js";var n={name:s.name,version:s.version,description:s.description,...e};export{n as default};
|