dashnex 0.5.88 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/dist/chunks/auth-ezwXxi-m.js +1 -0
- package/dist/chunks/dashnex-CRgjnfCu.js +1 -0
- package/dist/cli.js +1 -1
- package/dist/client.js +1 -1
- package/dist/commands/index.js +1 -1
- package/dist/server.js +1 -1
- package/dist/src/commands/login.d.ts +23 -8
- package/dist/src/lib/api.d.ts +3 -1
- package/dist/src/lib/browser.d.ts +7 -0
- package/dist/src/lib/pkce.d.ts +5 -0
- package/dist/src/services/auth.d.ts +10 -0
- package/dist/src/services/businesses.d.ts +25 -0
- package/dist/src/services/oauth.d.ts +29 -0
- package/package.json +1 -1
- package/dist/chunks/auth-28liVZ3c.js +0 -1
- package/dist/chunks/dashnex-DrnA-lqG.js +0 -1
package/README.md
CHANGED
|
@@ -41,10 +41,12 @@ dashnex <command> [options]
|
|
|
41
41
|
### Options
|
|
42
42
|
|
|
43
43
|
**login**:
|
|
44
|
-
- `--email <email>` — Email address
|
|
45
|
-
- `--password <password>` — Password
|
|
46
|
-
- `--code <code>` — 2FA code
|
|
47
44
|
- `--business <id>` — Business ID to select
|
|
45
|
+
- `--no-browser` — Print the sign-in URL instead of opening a browser
|
|
46
|
+
|
|
47
|
+
Sign-in goes through DashNex ID in your browser: approve the request, copy the
|
|
48
|
+
code you are shown, and paste it back into the CLI. Codes are valid for 10
|
|
49
|
+
minutes and can only be used once.
|
|
48
50
|
|
|
49
51
|
**dev**:
|
|
50
52
|
- `--https` — Run dev server with HTTPS
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"chalk";import s from"fs-extra";import n from"path";var r=e=>e instanceof Error&&("ExitPromptError"===e.name||("AbortError"===e.name||("User force closed the prompt"===e.message||!!e.message.includes("prompt was closed")))),t="Command interrupted.",o=e=>{const s=e.toLowerCase();return s.includes("token")||s.includes("password")||"auth_code"===s},a=e=>{if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(a);const s={};for(const[n,r]of Object.entries(e))o(n)?s[n]="[REDACTED]":s[n]=a(r);return s},i=s=>{process.env.DEBUG&&console.log(e.dim(s))},c=(s,n)=>{if(process.env.DEBUG){const r=a(n);console.log(e.dim(`${s}: ${JSON.stringify(r,null,2)}`))}},p=s=>{process.env.DEBUG&&s instanceof Error&&(console.log(e.dim(`Error: ${s.message}`)),s.stack&&console.log(e.dim(`Stack: ${s.stack}`)))},l=()=>"qa"===process.env.APPLICATION_ENV?"https://api.qa.dashnex.com":"https://api.dashnex.com",u=()=>process.env.DASHNEX_BUSINESS_API_URL?process.env.DASHNEX_BUSINESS_API_URL.replace(/\/+$/,""):"qa"===process.env.APPLICATION_ENV?"https://api.business.qa.dashnex.com":"https://api.business.dashnex.com",d={qa:"https://app.qa.dashnex.com",live:"https://app.dashnex.com"},f={qa:"hacmrrpg1wnjv12oq22p8lfm",live:"paijq1vhr6kxnbm22wjoftep"},h=()=>process.env.DASHNEX_ID_URL?process.env.DASHNEX_ID_URL.replace(/\/+$/,""):d[process.env.APPLICATION_ENV||"live"]||d.live,m=()=>process.env.DASHNEX_OAUTH_CLIENT_ID?process.env.DASHNEX_OAUTH_CLIENT_ID:f[process.env.APPLICATION_ENV||"live"]??"",v={qa:"https://3atfynmu2w.us-east-1.awsapprunner.com",live:"https://rkwbzvhcwh.us-east-1.awsapprunner.com"},k=()=>v[process.env.APPLICATION_ENV||"live"]||v.live,E=async(e,s={})=>{const n=await fetch(e,{...s,headers:{"Content-Type":"application/json",...s.headers}});return{response:n,body:await n.json().catch(()=>({}))}},N=process.env.DASHNEX_DIR||".dashnex",T=e=>n.join(e,N,"settings.json"),g=()=>{console.error(e.red("Please run 'dashnex login' to authenticate.")),console.error(e.green(`If you don't have an account yet, create one at ${h()}`))},w=e=>Boolean(e.idToken),x=async e=>{let r=n.resolve(e);for(;;){const e=T(r);if(await s.pathExists(e))return e;const t=n.dirname(r);if(t===r)return null;r=t}},y=e=>{try{const s=e.split(".");if(3!==s.length)return null;const n=JSON.parse(Buffer.from(s[1],"base64url").toString());return void 0!==n.id?String(n.id):null}catch{return null}},A=(e,s=30)=>{try{const n=e.split(".");if(3!==n.length)return!1;const r=JSON.parse(Buffer.from(n[1],"base64url").toString());if("number"!=typeof r.exp)return!1;const t=Math.floor(Date.now()/1e3),o=r.exp-s<=t;return o&&i(`Token expired or expiring soon (exp: ${r.exp}, now: ${t})`),o}catch{return!1}},S=async(e,n,r)=>{const t=w(r)?`${u()}/business/v1/token/refresh`:`${l()}/auth/v1/token/refresh`;i(`POST ${t}`);const{response:o,body:a}=await E(t,{method:"POST",body:JSON.stringify({refreshToken:e})});if(i(`Response: ${o.status}`),c("Refresh response",a),!o.ok)return i("Token refresh failed"),null;const p=a;if(!p.token||!p.refreshToken)return i("Refresh response missing tokens"),null;const d=await s.readJson(n);return d.token=p.token,d.refreshToken=p.refreshToken,await s.writeJson(n,d,{spaces:2}),i("Updated settings.json with new tokens"),_(p.token,p.refreshToken,n,{...d,token:p.token,refreshToken:p.refreshToken})},_=async(e,s,n,r)=>{if(A(e)){if(!s)return i("Token expired, no refreshToken available"),null;i("Token expired, refreshing proactively");try{return await S(s,n,r)}catch(o){return p(o),null}}const t=w(r)?`${u()}/business/v1/`:`${l()}/users/v1/`;i(`GET ${t}`);try{const{response:o,body:a}=await E(t,{headers:{Authorization:`Bearer ${e}`}});if(i(`Response: ${o.status}`),c("Validation response",a),o.ok){const s=a,n=s.name??s.companyName,t=r.businessId??(void 0!==s.id?String(s.id):void 0);if("string"==typeof n&&void 0!==t)return i(`Token valid, Already logged in as ${n}`),{token:e,businessId:String(t),userName:n}}return s?(i("Validation endpoint rejected token, refreshing"),await S(s,n,r)):(i("Token invalid, no refreshToken available"),null)}catch(o){return p(o),null}},I=async(e=process.cwd())=>{const n=await x(e);if(!n)return!1;try{return w(await s.readJson(n))}catch{return!1}},b=async(n={})=>{const{exitOnFailure:r=!0,dashnexPath:t}=n,o=process.env.DASHNEX_TOKEN;if(o)return A(o)?(i("DASHNEX_TOKEN is expired"),console.error(e.red("DASHNEX_TOKEN is expired. Provide a freshly issued token.")),r&&process.exit(1),null):(i("Using DASHNEX_TOKEN from environment"),{token:o,businessId:y(o)??""});const a=t??await x(process.cwd());if(!a||!(await s.pathExists(a)))return i(".dashnex/settings.json not found"),r&&(g(),process.exit(1)),null;let c;i(`Found settings at ${a}`);try{c=await s.readJson(a)}catch{return i("settings.json parse failed"),r&&(g(),process.exit(1)),null}const{token:p,refreshToken:l,businessId:u}=c;if(!p)return i("settings.json missing token"),r&&(g(),process.exit(1)),null;const d=await _(p,l,a,c);return d||(r&&(g(),process.exit(1)),null)};export{E as a,h as c,i as d,p as f,r as h,T as i,k as l,t as m,I as n,l as o,c as p,N as r,u as s,b as t,m as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e={$schema:"https://json.schemastore.org/package",name:"@dashnex/cli",version:"0.6.1",description:"Command-line interface for DashNex framework",homepage:"https://dashnex.io",type:"module",bin:{dashnex:"bin/dashnex"},engines:{node:">=22"},exports:{".":{types:"./dist/server.d.ts",default:"./dist/server.js"},"./client":{types:"./dist/client.d.ts",default:"./dist/client.js"}},scripts:{build:"vite build",dev:"vite build --watch --mode development",test:"vitest run"},keywords:["dashnex","cli"],author:"Dashnex Team",license:"UNLICENSED",dependencies:{"adm-zip":"^0.5.17",chalk:"^5.6.2",commander:"^14.0.3",diff:"^8.0.4",dotenv:"^17.4.2","fs-extra":"^11.3.5",ignore:"^7.0.5",inquirer:"^13.4.3",partysocket:"^1.3.0",ws:"^8.21.0"},devDependencies:{"@dashnex/types":"^1.4.4","@types/adm-zip":"^0.5.8","@types/fs-extra":"^11.0.4","@types/inquirer":"^9.0.9","@types/node":"^25.7.0","@types/ws":"^8.18.1",eslint:"^9.39.4","rollup-plugin-preserve-directives":"^0.4.0",terser:"^5.47.1",typescript:"^5.9.3",vite:"^8.0.12","vite-plugin-dts":"5.0.0-beta.6",vitest:"^4.1.6"},publishConfig:{registry:"https://npm.dashnex.com/"},files:["dist","bin","AGENTS.md","CLAUDE.md"]},s={};export{e as n,s as t};
|
package/dist/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{h as n,m as o,s,t as e}from"./chunks/auth-ezwXxi-m.js";import{Command as t}from"commander";import i from"chalk";import c from"fs-extra";import a from"path";import{fileURLToPath as r,pathToFileURL as d}from"url";import{execSync as l}from"child_process";import m from"dotenv";var p=new t,f=a.dirname(r(import.meta.url)),{version:u,description:h}=JSON.parse(c.readFileSync(a.resolve(f,"..","package.json"),"utf8"));p.name("dashnex").description(h).version(u).option("--ci","Disable spinner and interactive prompts (CI mode)").arguments("[command...]").action(n=>{if(n&&n.length>0){const o=n[0];if(!p.commands.map(n=>n.name()).includes(o)){console.error(i.red(`Unknown command: ${o}`));const n=process.cwd(),s=c.existsSync(a.join(n,"dashnex.json")),e=c.existsSync(a.join(n,"node_modules"));["build","router","bindings","env","db"].includes(o)?s&&!e?console.log(i.yellow(`\`${o}\` is provided by installed modules. Run \`dashnex install\` first.`)):s?console.log(i.green("Run `dashnex` to see available commands.")):console.log(i.yellow(`\`${o}\` must be run inside a DashNex application folder (containing dashnex.json).`)):console.log(i.green("Run `dashnex` to see available commands.")),process.exit(1)}}!function(n){const o=[];o.push("Usage: dashnex [options] [command]"),o.push(""),o.push(n.description()),o.push(""),o.push("Options:"),n.options.forEach(n=>{const s=n.flags.padEnd(20);o.push(` ${s} ${n.description}`)}),o.push(""),o.push("Commands:"),n.commands.forEach(n=>{const s=` ${n.name().padEnd(20)} ${n.description()}`;o.push(s),n.commands.length>0&&n.commands.forEach(n=>{const s=` ${n.name().padEnd(20)} ${n.description()}`;o.push(s)})}),console.log(o.join("\n"))}(p)});var g=null;async function y(n,o){const s=[];try{const e=function(n,o){const s=a.join(o,"package.json");if(c.existsSync(s))try{const e=JSON.parse(c.readFileSync(s,"utf8"));if(e.name===n)return o;const t={...e.dependencies,...e.devDependencies}[n];if(t&&(t.startsWith("link:")||t.startsWith("file:"))){const n=a.resolve(o,t.replace(/^(link:|file:)/,""));if(c.existsSync(n))return n}}catch{}const e=a.join(o,"node_modules",n);if(c.existsSync(e))return c.realpathSync(e);if(g){const o=a.join(g,n);if(c.existsSync(o))return o}return e}(n,o),t=[a.join(e,"dist","commands","index.js"),a.join(e,"src","commands","index.ts"),a.join(e,"src","commands","index.js")].find(n=>c.existsSync(n));if(t){const n=await import(d(t).href);let o=[];n.default?o=Array.isArray(n.default)?n.default:[]:n.commands&&(o=Array.isArray(n.commands)?n.commands:[]),o.length>0&&s.push(...o)}}catch(e){if(process.env.DEBUG){const o=e instanceof Error?e.message:String(e);console.log(i.yellow(`Module ${n} has no commands or failed to load: ${o}`))}}return s}function x(t,c,a={}){const r=t.command(c.name).description(c.description);c.arguments&&c.arguments.forEach(n=>{const o=n.required?`<${n.name}>`:`[${n.name}]`;void 0!==n.defaultValue?r.argument(o,n.description,n.defaultValue):r.argument(o,n.description)}),r.option("--ci","Disable spinner (CI mode)"),c.options&&c.options.forEach(n=>{void 0!==n.defaultValue?"number"==typeof n.defaultValue?r.option(n.flags,n.description,String(n.defaultValue)):r.option(n.flags,n.description,n.defaultValue):r.option(n.flags,n.description)}),c.subcommands&&c.subcommands.forEach(n=>{x(r,n,{...a,...c.options})}),c.subcommands&&c.subcommands.length>0?r.action(async()=>{r.outputHelp()}):r.action(async(...t)=>{try{const n=t[t.length-1],o=n.opts(),i=n.processedArgs,r={...a,...o};c.arguments?.forEach((n,o)=>{void 0!==i[o]&&(r[n.name]=i[o])}),r.context={auth:{getSession:()=>e()},businessApiBase:s()},await c.handler.execute(r)}catch(r){if(n(r))return void console.log(i.yellow(o));console.error(i.red(`❌ Command failed in ${c.name}:`),r),process.exit(1)}})}(async function(){m.config({quiet:!0}),process.env.DASHNEX_CLI="1",function(){try{g=l("npm root -g",{encoding:"utf8"}).trim()}catch{g=null}}(),process.argv.includes("--ci")&&(process.env.DASHNEX_CI="1");let n=process.cwd();const o=a.dirname(r(import.meta.url)),s=a.resolve(o,"..");process.env.DEBUG&&(console.log(`CLI started from directory: ${n}`),console.log(`CLI package directory: ${s}`),console.log(`Global node_modules: ${g??"not found"}`));const e=await async function(n){try{const s=[],e=/* @__PURE__ */new Set,t=n=>{e.has(n)||(e.add(n),s.push(n))},i=a.join(n,"dashnex.json");if(c.existsSync(i)){const o=a.join(n,"package.json");if(c.existsSync(o)){const n=JSON.parse(c.readFileSync(o,"utf8"));n.name&&t(n.name)}}const r=a.join(n,"package.json");if(c.existsSync(r)){const o=JSON.parse(c.readFileSync(r,"utf8")),s={...o.dependencies,...o.devDependencies,...o.optionalDependencies};for(const[e,i]of Object.entries(s)){if("string"==typeof i&&(i.startsWith("link:")||i.startsWith("file:"))){const o=a.resolve(n,i.replace(/^(link:|file:)/,""));if(c.existsSync(a.join(o,"dashnex.json"))){t(e);continue}}const o=a.join(n,"node_modules",e);c.existsSync(a.join(o,"dashnex.json"))&&t(e)}}if(g&&c.existsSync(g))try{const n=c.readdirSync(g);for(const o of n)if(o.startsWith("@")){const n=a.join(g,o);try{if(c.statSync(n).isDirectory()){const s=c.readdirSync(n);for(const n of s){const s=`${o}/${n}`,e=a.join(g,s);c.existsSync(a.join(e,"dashnex.json"))&&t(s)}}}catch{}}else{const n=a.join(g,o);c.existsSync(a.join(n,"dashnex.json"))&&t(o)}}catch(o){if(process.env.DEBUG){const n=o instanceof Error?o.message:String(o);console.log("⚠ Error scanning global node_modules:",n)}}return s}catch(o){if(process.env.DEBUG){const n=o instanceof Error?o.message:String(o);console.log("⚠ Error reading app package.json:",n)}return[]}}(n);e.includes("@dashnex/cli")||e.push("@dashnex/cli"),process.env.DEBUG&&(console.log(`CLI package directory: ${s}`),console.log(`Discovered modules: ${e.join(", ")}`));for(const r of e){let o=[];if("@dashnex/cli"===r)try{const n=a.join(s,"dist","commands","index.js");if(process.env.DEBUG&&console.log(`Loading @dashnex/cli commands from: ${n}`),await c.pathExists(n)){const s=await import(d(n).href);s.default?o=Array.isArray(s.default)?s.default:[]:s.commands&&(o=Array.isArray(s.commands)?s.commands:[]),process.env.DEBUG&&console.log(`Loaded ${o.length} commands from @dashnex/cli`)}}catch(f){if(process.env.DEBUG){const n=f instanceof Error?f.message:String(f);console.log(i.yellow(`Failed to load @dashnex/cli commands: ${n}`))}}else o=await y(r,n);for(const n of o)x(p,n)}const t=a.join(n,"dist","commands","index.js");if(await c.pathExists(t))try{const{default:n}=await import(d(t).href);if(n&&Array.isArray(n))for(const o of n)x(p,o)}catch(f){if(process.env.DEBUG){const n=f instanceof Error?f.message:String(f);console.error(i.yellow(`⚠ Failed to load application commands: ${n}`))}}p.parse(process.argv)})().catch(s=>{n(s)&&(console.log(i.yellow(o)),process.exit(0)),console.error(i.red("❌ CLI failed:"),s),process.exit(1)});
|
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-CRgjnfCu.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{a as e,c as t,d as s,f as o,i as n,l as a,n as r,o as i,r as c,s as l,t as p,u as d}from"../chunks/auth-28liVZ3c.js";import u from"chalk";import h from"fs-extra";import m from"path";import{fileURLToPath as g}from"url";import{spawn as f}from"child_process";import y from"fs";import w from"inquirer";import $ from"os";import v from"adm-zip";import{diffLines as k}from"diff";import{createHash as b}from"crypto";import x from"ignore";import{WebSocket as E}from"partysocket";import S from"ws";import{inspect as C}from"node:util";import{rm as D}from"node:fs/promises";var P=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],T=(e="")=>{if(process.env.DASHNEX_CI)return{start:()=>{},stop:()=>{},text:()=>{}};let t=null,s=0,o=e;const n=()=>{const e=P[s%P.length];process.stderr.write(`\r[K${e} ${o}`),s++};return{start:e=>{void 0!==e&&(o=e),t||(s=0,n(),t=setInterval(n,80))},stop:()=>{t&&(clearInterval(t),t=null),process.stderr.write("\r[K\n")},text:e=>{o=e,t&&n()}}},A=(e,t,s)=>{const o=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);let n=s;429===e.status?n="Too many requests. Please wait a moment and try again.":e.status>=500?n="DashNex API is temporarily unavailable. Please try again later.":o&&(n=o),console.error(u.red(n)),process.exit(1)},j=["Using vars defined in \\.env","\\(node:\\d+\\) MaxListenersExceededWarning:","\\(Use `node --trace-warnings","\\[WARNING\\].*You have defined bindings to the following internal Durable Objects","You have defined bindings to the following internal Durable Objects",'\\{"name":".+","class_name":".+"\\}',"These will not work in local development, but they should work in production","If you want to develop these locally, you can define your DO in a separate Worker","For detailed instructions, refer to the Durable Objects section here:","developers.cloudflare.com/workers/wrangler/api#supported-bindings","workerd/server/server\\.c\\+\\+.*warning:.*DurableObjectNamespace"],N=(e,t)=>t.length>0&&t.some(t=>t.test(e)),F=(e,s)=>{let o="";return{write:n=>{const a="string"==typeof n?n:n.toString();o+=a;const r=o.split(/\r?\n/);o=r.pop()??"";for(const o of r){const n=o.trim();n?N(n,s)?t(`Filtered: ${n}`):e.write(o+"\n"):t("Filtered: <empty line>")}},flush:()=>{const n=o.trim();if(n){if(N(n,s))return t(`Filtered: ${n}`),void(o="");e.write(o),o=""}else o=""}}},I=async(e,s={})=>{const o=m.join(e,"dashnex.json"),n=m.join(e,"package.json");if(t(`Checking for dashnex.json at: ${o}`),!(await h.pathExists(o)))throw new Error("Run this command in a DashNex Web application folder.");if(t("dashnex.json found, checking for package.json"),!(await h.pathExists(n)))throw new Error("package.json is missing.");let r;t("package.json found, checking for dev script");try{r=await h.readJson(n)}catch(l){throw a(l),new Error("Failed to read package.json.")}if(!r.scripts||!r.scripts.dev)throw new Error('The "dev" script is missing from package.json. Please add a "dev" script to package.json.');t("dev script found, checking for npm availability");const i=await(async e=>new Promise(t=>{const s=f(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>{t(!1)}),s.on("close",e=>{t(0===e)})}))("npm");if(t(`npm available: ${i}`),!i)throw new Error("npm is not available. Please install npm to continue.");const c=s.https?["--","--experimental-https"]:[];return t(`npm available, executing: npm run dev in ${e}${s.https?" -- --experimental-https":""}`),(async(e,t=[],s=process.cwd(),o=[])=>{const n=t.length?`${e} ${t.join(" ")}`:e,r=o.length>0;return new Promise((e,t)=>{const i=f(n,{stdio:r?["inherit","pipe","pipe"]:"inherit",cwd:s,shell:!0,env:{...process.env,NODE_ENV:"development",FORCE_COLOR:"1"}});if(i.on("error",e=>{a(e),t(e)}),r&&i.stdout&&i.stderr){const t=F(process.stdout,o),s=F(process.stderr,o);i.stdout.on("data",e=>t.write(e)),i.stderr.on("data",e=>s.write(e)),i.on("close",o=>{t.flush(),s.flush(),e(null===o?0:o)})}else i.on("close",t=>{e(null===t?0:t)})})})("npm run dev",c,e,(()=>{const e=[];for(const s of j)try{e.push(new RegExp(s))}catch{t(`Invalid dev output filter pattern ignored: ${s}`)}return e})())},O=async e=>new Promise(t=>{const s=f(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>{t(!1)}),s.on("close",e=>{t(0===e)})}),R=async e=>{let s;if(await O("pnpm"))s="pnpm install --config.strict-dep-builds=false",t("Using package manager: pnpm");else{if(!(await O("npm")))throw new Error("Neither pnpm nor npm is available. Install Node.js (which bundles npm) or pnpm to continue.");s="npm install --legacy-peer-deps",t("Using package manager: npm (with --legacy-peer-deps for DashNex peer-dep overlap)")}return t(`Executing: ${s} in ${e}`),new Promise((t,o)=>{const n=[],r=[],i=f(s,{stdio:["ignore","pipe","pipe"],cwd:e,shell:!0,env:{...process.env,NPM_CONFIG_LOGLEVEL:"error"}});i.stdout&&i.stdout.on("data",e=>n.push(e)),i.stderr&&i.stderr.on("data",e=>r.push(e)),i.on("error",e=>{a(e),o(e)}),i.on("close",e=>{const s=null===e?0:e;0!==s&&(n.length&&process.stdout.write(Buffer.concat(n)),r.length&&process.stderr.write(Buffer.concat(r))),t(s)})})},B="Run this command in a DashNex Web application folder.",L=e=>{const t=m.join(e,"dashnex.json");return h.pathExistsSync(t)},z=(e,t=!1)=>{t||console.log(u.cyan(e))},M=(e,s,o={})=>{const n=`${e} ${s.join(" ")}`,r=!0===o.silent;return new Promise((s,o)=>{t(`Running: ${n}`);const i=f(n,{stdio:r?["ignore","pipe","pipe"]:"inherit",cwd:process.cwd(),shell:!0});i.on("error",e=>{a(e),o(e)}),i.on("close",o=>{t(`${e} exited with code ${o}`),s(null===o?1:o)})})},U=(e,s)=>new Promise((o,n)=>{t(`Running: ${e} ${s.join(" ")}`);const r=f(e,s,{cwd:process.cwd()});let i="";r.stdout?.on("data",e=>{i+=e.toString()}),r.stderr?.on("data",e=>{i+=e.toString()}),r.on("error",e=>{a(e),n(e)}),r.on("close",s=>{t(`${e} exited with code ${s}`),o({exitCode:null===s?1:s,output:i})})}),W=async e=>{t("Running check: install");try{return 0===await R(process.cwd())}catch(s){return a(s),!e&&s instanceof Error&&console.error(u.red(s.message)),!1}},_=async()=>{try{const{output:e}=await U(process.execPath,[process.argv[1],"db","migrate","--help"]);return e.includes("Usage: dashnex db migrate")}catch(e){return a(e),!1}},J=async e=>{t("Running check: db migrate");try{const{exitCode:s,output:o}=await U(process.execPath,[process.argv[1],"db","migrate"]);return 0===s||(o.includes("Unknown command")?(t("db migrate command is not available, skipping"),!0):(!e&&o.trim().length>0&&process.stderr.write(o),!1))}catch(s){return a(s),!0}},G=e=>new Promise(t=>{const s=f(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>t(!1)),s.on("close",e=>t(0===e))}),q=[{name:"TypeScript",command:"npx",args:["tsc","--noEmit"],notFoundMessage:"TypeScript is not available. Please install it with: npm install -D typescript"}],X=class{async execute(){t("Check flow started"),L(process.cwd())||(console.error(u.red(B)),process.exit(1)),z("Checking dependencies..."),await W(!1)||(console.error(u.red("Check failed.")),process.exit(1)),t(`Running ${q.length} check(s)`);for(const s of q){t(`Running check: ${s.name}`),z(`Checking ${s.name}...`),await G(s.command)||(console.error(u.red(s.notFoundMessage)),process.exit(1));try{0!==await M(s.command,s.args)&&(console.error(u.red("Check failed.")),process.exit(1))}catch(e){a(e),console.error(u.red(s.notFoundMessage)),process.exit(1)}}await _()?(z("Checking database migrations..."),await J(!1)||(console.error(u.red("Check failed.")),process.exit(1))):t("db migrate command is not available, skipping"),console.log(u.green("All checks passed."))}async run(e=!1){if(t("Running checks (called from push)"),!L(process.cwd()))return e||console.error(u.red(B)),!1;if(z("Checking dependencies...",e),!(await W(e)))return!1;const s=e?{silent:!0}:void 0;for(const n of q){if(t(`Running check: ${n.name}`),z(`Checking ${n.name}...`,e),!(await G(n.command)))return console.error(u.red(n.notFoundMessage)),!1;try{if(0!==await M(n.command,n.args,s))return!1}catch(o){return a(o),console.error(u.red(n.notFoundMessage)),!1}}if(await _()){if(z("Checking database migrations...",e),!(await J(e)))return!1}else t("db migrate command is not available, skipping");return e||console.log(u.green("All checks passed.")),!0}},H=" │ ",Y=e=>e.subarray(0,8192).includes(0),V=e=>{const t=e.split("\n");return""===t[t.length-1]&&t.pop(),t},K=(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))}…`},Z=(e,t,s)=>{const o=Math.max(s??process.stdout.columns??120,43),n=Math.floor((o-3)/2),a=((e,t)=>{const s=[],o=k(e,t);for(let n=0;n<o.length;n+=1){const e=o[n];if(e.removed){const t=V(e.value),a=o[n+1],r=a?.added?V(a.value):[];a?.added&&(n+=1);const i=Math.max(t.length,r.length);for(let e=0;e<i;e+=1)s.push({left:t[e]??null,right:r[e]??null,changed:!0})}else if(e.added)for(const t of V(e.value))s.push({left:null,right:t,changed:!0});else for(const t of V(e.value))s.push({left:t,right:t,changed:!1})}return s})(e,t),r=/* @__PURE__ */new Set;a.forEach((e,t)=>{if(e.changed)for(let s=Math.max(0,t-3);s<=Math.min(a.length-1,t+3);s+=1)r.add(s)});const i=[];i.push(u.bold(K("local (current)",n))+u.dim(H)+u.bold("incoming"));let c=-1,l=0,p=0;for(let d=0;d<a.length;d+=1){if(!r.has(d))continue;if(l>=200){p+=1;continue}-1!==c&&d>c+1&&i.push(u.dim("···")),c=d,l+=1;const e=a[d],t=K(e.left,n),s=K(e.right,n);if(!e.changed){i.push(u.dim(t)+u.dim(H)+u.dim(s));continue}const o=null!==e.left?u.red(t):t,h=null!==e.right?u.green(s):s;i.push(o+u.dim(H)+h)}return p>0&&i.push(u.dim(`… ${p} more diff line(s) not shown`)),i.join("\n")},Q=[".dashnex",".git",".vinext",".wrangler","wrangler.jsonc","wrangler.toml",".dev.vars",".github"],ee=[".env","wrangler.jsonc"],te=e=>m.join(e,r,"sync.json"),se=e=>b("sha1").update(`blob ${e.length}\0`).update(e).digest("hex"),oe=e=>e.split(m.sep).join("/"),ne=e=>Q.some(t=>e===t||e.startsWith(`${t}/`)),ae=async e=>{const t=await(async e=>{const t=x();t.add(Q);const s=m.join(e,".gitignore");return await h.pathExists(s)&&t.add(await h.readFile(s,"utf8")),t})(e),s=[],o=async n=>{const a=await h.readdir(n,{withFileTypes:!0});for(const r of a){const a=m.join(n,r.name),i=oe(m.relative(e,a));ne(i)||t.ignores(r.isDirectory()?`${i}/`:i)||(r.isDirectory()?await o(a):r.isFile()&&s.push(i))}};return await o(e),s},re=async(e,t={})=>{const s={},o=await ae(e);for(const n of o)s[n]=se(await h.readFile(m.join(e,n)));if(t.includeGenerated)for(const n of ee){if(n in s)continue;const t=m.join(e,n);(await h.lstat(t).catch(()=>null))?.isFile()&&(s[n]=se(await h.readFile(t)))}return s},ie=async e=>{try{const t=await h.readFile(te(e),"utf8"),s=JSON.parse(t);return"string"!=typeof s?.commit||"object"!=typeof s?.manifest||null===s.manifest?null:s}catch{return null}},ce=async(e,s,o)=>{const n={commit:s,manifest:o,updatedAt:/* @__PURE__ */(new Date).toISOString()},a=te(e);try{await h.ensureDir(m.dirname(a)),await h.writeFile(a,`${JSON.stringify(n,null,2)}\n`),t(`Sync state written: commit ${s}, ${Object.keys(o).length} files`)}catch(r){t(`Failed to write sync state: ${r instanceof Error?r.message:"unknown"}`)}},le=1048576,pe=async(e,s)=>{const{install:o}=await w.prompt([{type:"confirm",name:"install",message:"Install dependencies?",default:!0}]);if(!o){if(m.resolve(e)!==m.resolve(s)){const t=m.relative(s,e);console.log(u.cyan(`Run "cd ${t}" to change to the application folder.`))}return}try{const s=T();s.start("Installing dependencies...");try{const o=await R(e);if(s.stop(),0!==o)return void t(`install exited with code ${o}`)}catch(i){throw s.stop(),i}}catch(i){return a(i),void console.error(u.red(i instanceof Error?i.message:"Failed to run install."))}const{migrate:n}=await w.prompt([{type:"confirm",name:"migrate",message:"Create or update database?",default:!0}]);if(!n)return;t(`Running dashnex db migrate in ${e}`);try{const s=T();s.start("Creating or updating database...");try{const o=await((e,t,s)=>{const o=`${m.join(e,"node_modules",".bin")}${m.delimiter}${process.env.PATH??""}`,n={...process.env,PATH:o};return new Promise((o,r)=>{const i=f(t,{cwd:e,shell:!0,stdio:"inherit",env:s?{...n,...s}:n});i.on("error",e=>{a(e),r(e)}),i.on("close",e=>{o(null===e?0:e)})})})(e,"dashnex db migrate");if(s.stop(),0!==o)return void t(`dashnex db migrate exited with code ${o}`)}catch(i){throw s.stop(),i}}catch(i){return a(i),void console.error(u.red("Failed to run dashnex db migrate."))}const{dev:r}=await w.prompt([{type:"confirm",name:"dev",message:"Run development server?",default:!0}]);if(r)try{await I(e)}catch(i){a(i),console.error(u.red(i instanceof Error?i.message:"Failed to run dev server."))}},de=(e,t)=>{if(e.length!==t.length)return`local ${e.length} bytes, incoming ${t.length} bytes`;const s=e.length;for(let o=0;o<s;o+=1)if(e[o]!==t[o]){return`size ${s} matches; first diff at byte ${o} (local=0x${e[o].toString(16).padStart(2,"0")} incoming=0x${t[o].toString(16).padStart(2,"0")})`}return`size ${s} matches; no byte difference (unexpected)`},ue=async(e,t)=>{let s;try{s=await h.lstat(e)}catch{return{kind:"new"}}if(s.isDirectory())return{kind:"different",reason:"target is a directory"};if(s.size!==t.length)return{kind:"different",reason:`local ${s.size} bytes, incoming ${t.length} bytes`};const o=await h.readFile(e);return 0===Buffer.compare(o,t)?{kind:"identical"}:{kind:"different",reason:de(o,t)}},he=async(e,t,s)=>{console.log(`\n${u.bold(t)}`);try{const t=await h.readFile(e);if(t.length>le||s.length>le||Y(t)||Y(s))return void console.log(u.dim(`(no preview: ${de(t,s)})`));console.log(Z(t.toString("utf8"),s.toString("utf8")))}catch(o){a(o),console.log(u.dim("(no preview available)"))}},me=async e=>{const{choice:t}=await w.prompt([{type:"expand",name:"choice",message:`Overwrite ${e}?`,default:"y",choices:[{key:"y",name:"yes (overwrite this file)",value:"yes"},{key:"n",name:"no (keep local version)",value:"no"},{key:"a",name:"overwrite all remaining differing files",value:"all"},{key:"s",name:"skip all remaining differing files",value:"skip"}]}]);return t},ge=async(e,t)=>{const s=t?u.yellow(" (has local changes!)"):"",{choice:o}=await w.prompt([{type:"expand",name:"choice",message:`Delete ${e}? It no longer exists in the application.${s}`,default:"y",choices:[{key:"y",name:"yes (delete this file)",value:"yes"},{key:"n",name:"no (keep this file)",value:"no"},{key:"a",name:"delete all remaining removed files",value:"all"},{key:"s",name:"keep all remaining removed files",value:"skip"}]}]);return o},fe=async(e,t)=>{let s=m.dirname(e);const o=m.resolve(t);for(;m.resolve(s)!==o;)try{if((await h.readdir(s)).length>0)return;await h.rmdir(s),s=m.dirname(s)}catch{return}},ye=(e,t)=>m.resolve(e)===m.resolve(t)?"Application is successfully pulled.":`Application is successfully pulled into ${m.relative(t,e)}.`,we=class{async execute(e={}){t("Pull flow started");const n=await p();if(!n)return;const r=process.cwd();let i;if(e.folder)i=e.folder.trim()||".",t(`Folder argument provided: ${i}`);else{t("No folder argument, prompting user");const{folder:e}=await w.prompt([{type:"input",name:"folder",message:"Which folder to pull the application to?",default:"."}]);i=e.trim()||"."}const c=m.resolve(r,i);t(`Target folder resolved: ${c}`);try{const e=await h.lstat(c).catch(()=>null);e&&!e.isDirectory()&&(console.error(u.red(`Cannot pull into ${c}: path exists and is not a directory.`)),process.exit(1)),await h.ensureDir(c),t(`Target folder ensured: ${c}`)}catch(g){a(g);const e=g instanceof Error?g.message:"Unknown error";console.error(u.red(`Cannot create folder ${c}: ${e}`)),process.exit(1)}const l=m.join($.tmpdir(),`dashnex-pull-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),d=T();d.start("Analyzing local files...");try{const s=await ie(c),o=await re(c,{includeGenerated:!0});t(`Local manifest has ${Object.keys(o).length} files`),d.text("Pulling application...");const i=await this.download(n.token,o);d.text("Downloading..."),await h.writeFile(l,i.buffer),t(`Zip written to temp file (${i.viaV2?"v2 diff":"legacy full"} pull)`),d.text("Extracting...");const p=new v(l).getEntries().filter(e=>!e.isDirectory);let f=null;const y=p.find(e=>".dashnex/pull.json"===e.entryName);if(y)try{f=JSON.parse(y.getData().toString("utf8"))}catch(g){a(g)}const w=p.filter(e=>".dashnex"!==e.entryName&&!e.entryName.startsWith(".dashnex/"));t(`Zip has ${w.length} file entries${f?`, meta commit ${f.commit}`:", no meta"}`);const $=e.yes||"1"===process.env.DASHNEX_CI;let k=$?"all":"prompt",b=!1,x=0,E=0,S=0,C=0,D=0;const P=async(e,t,s)=>{try{return await h.ensureDir(m.dirname(e)),await h.writeFile(e,t),s&&await h.chmod(e,s),!0}catch(g){return a(g),!1}};for(const e of w){const s=e.getData(),o=m.join(c,e.entryName),n=m.relative(c,o)||e.entryName,a=(e.header.attr??0)>>16&4095,r=await ue(o,s);if(t(`Entry ${e.entryName}: ${r.kind}${r.reason?` (${r.reason})`:""}`),"identical"===r.kind){C+=1;continue}if("new"===r.kind){await P(o,s,a)?x+=1:D+=1;continue}let i=!1;if("all"===k)i=!0;else if("none"===k)i=!1;else{d.stop(),await he(o,n,s),b||(console.log(u.dim("Y = yes (default), n = skip, a = overwrite all, s = skip all, h = help")),b=!0);const a=await me(n);t(`Entry ${e.entryName}: user chose ${a}`),"yes"===a?i=!0:"no"===a?i=!1:"all"===a?(k="all",i=!0):(k="none",i=!1),d.start("Extracting...")}i?await P(o,s,a)?E+=1:D+=1:S+=1}d.stop();let T=0,A=0;if(f&&f.deleted.length>0){const e=await this.applyDeletions(c,f.deleted,s,$);T=e.deleted,A=e.kept}f&&(C+=Math.max(0,Object.keys(f.manifest).length-w.length)),t(`Pull summary: ${x} new, ${E} overwritten, ${S} skipped, ${T} deleted, ${C} unchanged, ${D} failed`);const j=[`${x} new`,`${E} overwritten`,`${S} skipped`,`${C} unchanged`];if((T>0||A>0)&&j.splice(3,0,`${T} deleted`),D>0&&j.push(`${D} failed`),console.log(u.cyan(`Pulled: ${j.join(", ")}`)),f){const e=await re(c,{includeGenerated:!0});await ce(c,f.commit,e)}m.resolve(c)!==m.resolve(r)?(console.log(u.green(ye(c,r))),process.chdir(c),t(`Changed working directory to ${c}`)):console.log(u.green(ye(c,r))),D>0&&(console.error(u.red(`${D} file(s) failed to write. See DEBUG output for details.`)),process.exit(1)),$?t("Non-interactive mode (--yes or --ci), skipping post-pull child commands"):await pe(c,r)}catch(g){if(d.stop(),a(g),g instanceof Error&&g.message.startsWith("EXIT:"))throw g;if(o(g))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}finally{await h.remove(l).catch(()=>{}),t("Temp zip removed")}}async download(e,s){const o=`${i()}/business/v1/cli/v2/pull`;t(`POST ${o}`);const n=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:s})});if(t(`v2 pull response: ${n.status}`),n.ok)return{buffer:Buffer.from(await n.arrayBuffer()),viaV2:!0};const a=await n.json().catch(()=>({}));var r,c;r=n.status,c=a,404===r&&"string"==typeof c.message&&c.message.startsWith("Cannot ")||this.failFromResponse(n.status,a),t("v2 pull endpoint unavailable, falling back to legacy pull");const l=`${i()}/business/v1/cli/pull`;t(`GET ${l}`);const p=await fetch(l,{headers:{Authorization:`Bearer ${e}`}});if(t(`Legacy pull response: ${p.status}`),!p.ok){const e=await p.json().catch(()=>({}));this.failFromResponse(p.status,e)}return{buffer:Buffer.from(await p.arrayBuffer()),viaV2:!1}}failFromResponse(e,t){let s="Failed to pull application.";if(401===e||403===e)s="Please run 'dashnex login' to authenticate.";else if(404===e)s="Business has no application. Run 'dashnex app create' to create one.";else{const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);e&&(s=e)}console.error(u.red(s)),process.exit(1)}async applyDeletions(e,s,o,n){let r=0,i=0;if(!o){const e=s.slice(0,20);console.log(u.yellow("These local files do not exist in the application (kept — no sync state yet):"));for(const t of e)console.log(u.yellow(` ${t}`));return s.length>e.length&&console.log(u.yellow(` … and ${s.length-e.length} more`)),{deleted:r,kept:s.length}}let c=n?"all":"prompt";for(const p of s){if(!(p in o.manifest)){t(`Deletion candidate ${p} was never synced, keeping`);continue}const s=m.join(e,p),n=await h.readFile(s).catch(()=>null);if(null===n)continue;const d=se(n)!==o.manifest[p];let u=!1;if("all"===c)u=!0;else if("none"===c)u=!1;else{const e=await ge(p,d);t(`Deletion ${p}: user chose ${e}`),"yes"===e?u=!0:"no"===e?u=!1:"all"===e?(c="all",u=!0):(c="none",u=!1)}if(u)try{await h.remove(s),await fe(s,e),r+=1}catch(l){a(l),i+=1}else i+=1}return{deleted:r,kept:i}}},$e=async e=>{const s=`${i()}/business/v1/agreements/payment-processing/status`;t(`GET ${s}`);const o=await fetch(s,{headers:{Authorization:`Bearer ${e}`}});if(t(`Payment agreement response: ${o.status}`),!o.ok)return!0;if((await o.json().catch(()=>({}))).hasAccepted)return!0;const n=`${await(async()=>"qa"===process.env.APPLICATION_ENV?"https://business.qa.dashnex.com":"https://business.dashnex.com")()}/money/agreement/`;return console.error(u.red(`You need to accept Master Payment Processing Agreement first by visiting this link: ${n}`)),!1},ve=async(e,s={})=>{const o=s.ciMode??!1;return!!(await $e(e))&&!!(await(async(e,s)=>{const o=`${i()}/business/v1/tos/latest`;t(`GET ${o}`);const n=await fetch(o,{headers:{Authorization:`Bearer ${e}`}});if(t(`TOS latest response: ${n.status}`),n.ok)return!0;if(404!==n.status)return!0;const r=`${i()}/business/v1/tos/current`;t(`GET ${r}`);const c=await fetch(r,{headers:{Authorization:`Bearer ${e}`}});if(t(`TOS current response: ${c.status}`),!c.ok)return t("Could not fetch current TOS, skipping check"),!0;const l=await c.json().catch(()=>({})),p=l.version??"unknown";if(l.text&&(console.log(u.dim("─".repeat(60))),console.log(u.bold(`Terms of Service ${p}`)),console.log(u.dim("─".repeat(60))),console.log(l.text.replace(/<br\s*\/?>/gi,"\n").replace(/<\/p>/gi,"\n\n").replace(/<\/div>/gi,"\n").replace(/<\/li>/gi,"\n").replace(/<[^>]+>/g,"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/\n{3,}/g,"\n\n").trim()),console.log(u.dim("─".repeat(60)))),s)return console.log(u.yellow(`By proceeding you accept the Terms of Service ${p}.`)),!0;const{accept:d}=await w.prompt([{type:"confirm",name:"accept",message:`By creating an application you accept the Terms of Service ${p}. Continue?`,default:!0}]);if(!d)return console.log(u.yellow("Cancelled.")),!1;try{const s=`${i()}/business/v1/tos/${l.id}/accept`;t(`POST ${s}`),await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch(h){a(h)}return!0})(e,o))},ke=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,be=e=>new Promise(t=>setTimeout(t,e)),xe=e=>e.appFullCustomDomain?e.appFullCustomDomain:e.subdomain?"qa"===(process.env.APPLICATION_ENV??"")?`https://${e.subdomain}.dashnex.dev`:`https://${e.subdomain}.dashnexcloud.com`:null,Ee=3e5,Se=99,Ce=e=>new Promise(t=>setTimeout(t,e)),De=async(e,s,o,n)=>{const r=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${s}`,Accept:"text/event-stream"}});if(t(`SSE connection opened: ${r.status}`),!r.ok){const e=r.status;let t="Failed to start deployment.";if(401===e||403===e)t="Please run 'dashnex login' to authenticate.";else try{const e=await r.text(),s=JSON.parse(e);"string"==typeof s.error?t=s.error:"string"==typeof s.message&&(t=s.message)}catch{}throw console.error(u.red(t)),new Error(`HTTP ${e}: ${t}`)}if(!r.body)throw new Error("Response body is null");t("SSE connection established successfully"),n?.();const i=r.body.getReader();try{for await(const e of async function*(e){const t=new TextDecoder("utf-8");let s="";for(;;){const{value:o,done:n}=await e.read();if(n)break;s+=t.decode(o,{stream:!0});const a=s.split("\n");s=a.pop()||"";let r="";for(const e of a)e.startsWith("data: ")?r=e.slice(6):""===e&&r&&(yield{data:r},r="")}if(s.startsWith("data: ")){const e=s.slice(6);e&&(yield{data:e})}}(i))try{if(!e.data){t("Received empty SSE event");continue}const s=JSON.parse(e.data);t(`SSE message received: ${JSON.stringify(s)}`),o(s)}catch(c){a(c),t(`Failed to parse SSE event data: ${e.data}`)}}finally{i.releaseLock()}},Pe=class{async execute(e={}){t("Deploy flow started");const n=await p();if(!n)return;if(!1!==e.check?(t("Running pre-deploy checks"),await(new X).run(!1)||(console.error(u.red("Deploy aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):t("Skipping pre-deploy checks (--no-check)"),!(await ve(n.token,{ciMode:!0})))return;const r=`${l()}/business/v1/applications/deploy`;t(`GET ${r} (SSE)`);let i=0,c="",d=!1,h=0,m=!1;const g=T();let f=0,y=0,w=null;const $=(e,t)=>{const s=Math.round(e);g.text(`[${s}%] ${t}`)},v=()=>{k();const e=i,t=Date.now(),s=Ee*((Se-e)/Se);w=setInterval(()=>{const o=Date.now()-t;let n;if(y>t){const e=Date.now()-y,t=Se-f,s=3030.3030303030305*t;n=Math.min(f+e/s*t,Se)}else n=Math.min(e+o/s*(Se-e),Se);n>i&&(i=n,$(i,c))},200)},k=()=>{w&&(clearInterval(w),w=null)};let b=!1;const x=e=>{if(m=!0,"string"==typeof e.error)return k(),g.stop(),console.error(u.red(e.error)),d=!0,void(b=!0);"string"==typeof e.message&&(c=e.message),"number"==typeof e.progress&&(f=e.progress,y=Date.now(),e.progress>i&&(i=e.progress)),"string"!=typeof e.message&&"number"!=typeof e.progress||(i>=100?(k(),g.stop(),d=!0):$(i,c))};for(;h<=5;)try{return m?$(i,c):g.start("Connecting..."),v(),await De(r,n.token,x,()=>{m||(g.text(`[${Math.round(i)}%] Deployment in progress...`),c="Deployment in progress...")}),k(),g.stop(),t("SSE connection closed"),b&&process.exit(1),void(d&&await this.showDeployedUrl(n.token))}catch(E){if(k(),a(E),t(`SSE connection error: ${E}`),d)return g.stop(),void(b&&process.exit(1));if(o(E))return g.stop(),void console.log(u.yellow(s));E instanceof Error&&E.message.startsWith("HTTP")&&(g.stop(),console.error(u.red("Could not complete deployment. Check your connection and try again.")),process.exit(1)),h++,h>5&&(g.stop(),console.error(u.red("Deployment failed. Maximum reconnection attempts exceeded.")),process.exit(1));const e=Math.min(1e3*Math.pow(2,h-1),3e4);t(`Connection error. Reconnecting in ${e/1e3}s... (attempt ${h}/5)`),await Ce(e)}}async showDeployedUrl(e){try{const s=`${i()}/business/v1/applications`;t(`GET ${s} (for deployed URL)`);const o=await fetch(s,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)return;const n=await o.json().catch(()=>({})),a=xe({subdomain:n.subdomain,appFullCustomDomain:n.appFullCustomDomain});a&&console.log(`Application is deployed to ${u.cyan(a)}`)}catch(s){a(s)}}},Te=104857600,Ae=class extends Error{},je=class extends Error{},Ne=class extends Error{},Fe="/business/v1/cli/tail-token";async function Ie(e,t={}){const s=`${i()}${Fe}${t.debug?"?debug=1":""}`;try{await fetch(s,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})}catch{}}var Oe=["log","info","warn","error","debug"],Re={error:4,warn:3,log:2,info:2,debug:1};function Be(e){return"string"==typeof e&&Oe.includes(e)}function Le(e){return e.map(e=>"string"==typeof e?e:function(e){try{return JSON.stringify(e)}catch{return String(e)}}(e)).join(" ")}function ze(e){return e<10?`0${e}`:String(e)}function Me(e){const t=new Date(e);return`${ze(t.getHours())}:${ze(t.getMinutes())}:${ze(t.getSeconds())}.${s=t.getMilliseconds(),s<10?`00${s}`:s<100?`0${s}`:String(s)}`;var s}function Ue(e,t){if("string"==typeof e)return e;if("object"==typeof(s=e)&&null!==s&&"string"==typeof s.name&&"string"==typeof s.message&&Object.keys(s).every(e=>"name"===e||"message"===e||"stack"===e)){const t=`${e.name}: ${e.message}`;return e.stack?`${t}\n${e.stack}`:t}var s;return C(e,{colors:t,depth:2,breakLength:120})}var We={error:e=>u.red(e),warn:e=>u.yellow(e),debug:e=>u.dim(e),log:e=>e,info:e=>e};function _e(e,t){const s=t.color?u.dim(Me(e.ts)):Me(e.ts),o=e.level.toUpperCase().padEnd(5),n=[s,t.color?We[e.level](o):o];n.push(e.args.map(e=>Ue(e,t.color)).join(" "));let a=n.join(" ");if(e.truncated){const e=" …(truncated)";a+=t.color?u.dim(e):e}return a}function Je(e,t,s){let o;try{o=JSON.parse(e)}catch{return{kind:"malformed",raw:e}}if("object"!=typeof o||null===o||!Be(o.level))return{kind:"malformed",raw:e};const n=o;return Array.isArray(n.args)||(n.args=void 0===n.args?[]:[n.args]),a=n.level,r=t.minLevel,Re[a]>=Re[r]&&function(e,t){return!t||t.test(Le(e.args))}(n,t.filter)?{kind:"line",line:_e(n,s)}:{kind:"filtered"};var a,r}var Ge=new Set([4401,4403]);var qe=[{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"}],Xe={label:".wrangler",segments:[".wrangler"],description:"local database"},He=async e=>{await D(e,{recursive:!0,force:!0,maxRetries:5,retryDelay:100})},Ye={name:"app",description:"Manage DashNex applications (should be executed in application folder)",handler:{execute:async()=>{}},options:[],subcommands:[{name:"create",description:"Create a new DashNex application",handler:new class{async pollApplicationCreated(e,s,o=5e3,n=6e4){const r=Date.now();let i=0;for(;Date.now()-r<n;){i++,t(`Polling application status (attempt ${i})...`);try{const o=await fetch(e,{headers:{Authorization:`Bearer ${s}`}});if(t(`Poll response: ${o.status}`),200===o.status){const e=await o.json();if(t(`Poll response body status: ${e.status}`),"creating"!==e.status)return t(`Application status is "${e.status}", creation complete`),{ready:!0,status:e.status};t('Application status is still "creating", continuing to poll...')}}catch(c){a(c),t(`Poll attempt ${i} failed with network error`)}await be(o)}return{ready:!1}}async execute(e={}){t("Create flow started");const n=await p();if(!n)return;t("Auth valid, checking if business already has application");const r=T(),c=`${i()}/business/v1/applications`;t(`GET ${c}`),r.start("Checking application status...");try{const e=await fetch(c,{headers:{Authorization:`Bearer ${n.token}`}});r.stop(),t(`Applications response: ${e.status}`),t(`Applications response body: ${await e.text()}`),404!==e.status&&(console.error(u.red("Business already has an application. Run 'dashnex app pull' to pull the existing one.")),process.exit(1))}catch($){if(r.stop(),a($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(o($))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}t("No existing application, checking agreements");const l=void 0!==e.subdomain;if(!(await ve(n.token,{ciMode:l})))return;let d;t("Agreements checked, proceeding to subdomain prompt");const h=e=>`${i()}/business/v1/applications/check-subdomain?subdomain=${encodeURIComponent(e)}`;let m=e.subdomain?.trim();for(;;){if(m)d=m,m=void 0,t(`Subdomain provided via flag: ${d}`);else{if(l)return console.error(u.red("Subdomain is not available.")),void process.exit(1);{const{sub:e}=await w.prompt([{type:"input",name:"sub",message:"Pick your subdomain:",validate:e=>!!e.trim()||"Subdomain is required"}]);d=e.trim()}}t(`Checking subdomain: ${d}`);const e=h(d);t(`GET ${e}`),r.start("Checking subdomain...");try{const s=await fetch(e,{headers:{Authorization:`Bearer ${n.token}`}});r.stop(),t(`Check subdomain response: ${s.status}`);const o=await s.text();if(t(`Check subdomain response body: ${o}`),!s.ok){const e=s.headers.get("content-type")??"";let n="Failed to check subdomain availability.";if(401!==s.status&&403!==s.status||(n="Please run 'dashnex login' to authenticate.",console.error(u.red(n)),process.exit(1)),e.includes("application/json")){const e=JSON.parse(o);t(`Check subdomain error body: ${JSON.stringify(e)}`);const s=ke(e);s&&(n=s)}console.error(u.red(n));continue}const a=JSON.parse(o);if(t(`Check subdomain parsed body: ${JSON.stringify(a)}`),a.available){t(`Subdomain ${d} is available`);break}console.error(u.red("Subdomain is not available. Please choose a different one."))}catch($){if(r.stop(),a($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(o($))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}const g=`${i()}/business/v1/cli/create`;t(`POST ${g}`);const f={subdomain:d};e.template&&(f.template=e.template,t(`Template: ${e.template}`));const y=JSON.stringify(f);t(`Create request body: ${y}`),r.start("Creating application...");try{const c=await fetch(g,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:y});r.stop(),t(`Create response: ${c.status}`);const p=await c.text();if(t(`Create response body: ${p}`),503===c.status){t("Create returned 503, polling for application creation..."),r.start("Waiting for application to be ready...");const e=`${i()}/business/v1/applications`,s=await this.pollApplicationCreated(e,n.token);r.stop(),s.ready||(console.error(u.red("Application creation is taking longer than expected. Try again later or run 'dashnex app pull' to check.")),process.exit(1)),"failed"===s.status&&(console.error(u.red("Application creation failed. Please try again.")),process.exit(1)),t("Application found after polling")}else if(!c.ok){const e=c.headers.get("content-type")??"";let s="Failed to create application.";if(401===c.status||403===c.status)s="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=JSON.parse(p);t(`Create error body parsed: ${JSON.stringify(e)}`);const o=ke(e);o&&(s=o)}console.error(u.red(s)),process.exit(1)}let d;if(t("Application created successfully"),!0===e.pull?(d=!0,t("--pull flag set, pulling without prompting")):!1===e.pull?(d=!1,t("--no-pull flag set, skipping pull")):l?(d=!1,t("CI mode (--subdomain), skipping pull")):(d=(await w.prompt([{type:"confirm",name:"pull",message:"Pull the application locally?",default:!0}])).pull,t(`User chose to pull: ${d}`)),d){t("Running pull flow");try{await(new we).execute()}catch($){if(a($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(o($))return void console.log(u.yellow(s));console.error(u.red("Failed to pull application."))}}else console.log(u.green("Application is created successfully. Run 'dashnex app pull' to pull it to your computer or 'dashnex app deploy' to deploy it to the cloud."))}catch($){if(r.stop(),a($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(o($))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[{flags:"-t, --template <template>",description:"Template (name@branch-or-tag)",defaultValue:"webapp-base@live"},{flags:"--subdomain <subdomain>",description:"Subdomain (CI mode, skip prompts)"},{flags:"--pull",description:"Auto-pull after creation (skip prompt)"},{flags:"--no-pull",description:"Skip the pull prompt and show the success message"}]},{name:"pull",description:"Pull existing application to specified folder",handler:new we,arguments:[{name:"folder",description:"Target folder (defaults to interactive prompt)"}],options:[{flags:"-y, --yes",description:"Skip prompts and child commands (CI mode)"}]},{name:"push",description:"Push local application to DashNex",handler:new class{async execute(e={}){t("Push flow started"),await h.pathExists(m.join(process.cwd(),"dashnex.json"))||(console.error(u.red("Not a DashNex application folder (dashnex.json not found).")),console.error(u.red("Run this command from your application root.")),process.exit(1)),!1!==e.check?(t("Running pre-push checks"),await(new X).run(!1)||(console.error(u.red("Push aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):t("Skipping pre-push checks (--no-check)");const n=await p();if(!n)return;const r=process.cwd(),i=T();try{i.start("Analyzing local files...");const s=await ie(r),o=await re(r);t(`Local manifest has ${Object.keys(o).length} files`),i.text("Comparing with remote...");const a=await this.requestPlan(n.token,o,s?.commit);i.stop(),"legacy"===a?(t("v2 push endpoints unavailable, falling back to legacy zip push"),await this.pushLegacy(n.token,r,i)):await this.pushDiff(n.token,r,o,a,e,i),await this.promptAndDeploy(e)}catch(c){if(i.stop(),a(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(o(c))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}async requestPlan(e,s,o){const n=`${i()}/business/v1/cli/v2/push/plan`;t(`POST ${n}`);const a=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:s,lastSyncCommit:o})});if(t(`Plan response: ${a.status}`),a.ok)return await a.json();const r=await a.json().catch(()=>({}));if(((e,t)=>404===e&&"string"==typeof t.message&&t.message.startsWith("Cannot "))(a.status,r))return"legacy";this.failFromResponse(a.status,r,"Failed to push application.")}async pushDiff(e,s,o,n,a,r){let i=n;if(i.remoteChanged.length>0&&!a.force){console.error(u.red("Remote application has changes you don't have locally:"));for(const e of i.remoteChanged.slice(0,20))console.error(u.red(` ${e}`));i.remoteChanged.length>20&&console.error(u.red(` … and ${i.remoteChanged.length-20} more`)),console.error(u.red("Run 'dashnex app pull' first, or push anyway with --force.")),process.exit(1)}const c=i.upload.filter(e=>e in o);let l=i.delete;if(0!==c.length||0!==l.length){if(l.length>0){const e=await ie(s),o=a.yes||"1"===process.env.DASHNEX_CI;console.log(u.yellow(`${l.length} file(s) will be deleted from the application repository:`));for(const t of l.slice(0,20))console.log(u.yellow(` ${t}`));if(l.length>20&&console.log(u.yellow(` … and ${l.length-20} more`)),!o){const{confirmDelete:s}=await w.prompt([{type:"confirm",name:"confirmDelete",message:"Delete these files from the remote repository?",default:null!==e}]);s||(t("User declined remote deletions, pushing without them"),l=[])}}if(0!==c.length||0!==l.length)for(let n=1;;n+=1){r.start(1===n?"Uploading changes...":"Remote changed, retrying...");const p=await this.applyPush(e,s,c,l,i.baseCommit);if(r.stop(),"ok"===p.status){await ce(s,p.commit,o);const e=[`${c.length} file(s) updated`];return l.length>0&&e.push(`${l.length} deleted`),console.log(u.cyan(`Pushed: ${e.join(", ")}`)),void console.log(u.green("Application pushed successfully."))}n>=2&&(console.error(u.red("Remote repository keeps changing, please retry the push.")),process.exit(1)),t("Push apply conflicted, re-planning");const d=await ie(s),h=await this.requestPlan(e,o,d?.commit);"legacy"===h&&(console.error(u.red("Failed to push application.")),process.exit(1)),h.remoteChanged.length>0&&!a.force&&(console.error(u.red("Remote application changed during the push. Run 'dashnex app pull' first, or push with --force.")),process.exit(1)),i=h}else console.log(u.green("Everything up to date."))}else console.log(u.green("Everything up to date."))}async applyPush(e,s,o,n,a){const r=new v;for(const t of o){const e=m.join(s,...t.split("/")),o=m.posix.dirname(t);r.addLocalFile(e,"."===o?"":o,m.posix.basename(t))}const c=m.join($.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{r.writeZip(c),t(`Diff zip written to ${c} (${o.length} files, ${n.length} deletions)`),await this.ensureZipWithinLimit(c);const s=`${i()}/business/v1/cli/v2/push/apply`;t(`POST ${s}`);const l=await h.readFile(c),p=new FormData;p.append("file",new Blob([l],{type:"application/zip"}),"diff.zip"),p.append("baseCommit",a),p.append("deletions",JSON.stringify(n));const d=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:p});if(t(`Apply response: ${d.status}`),409===d.status)return{status:"conflict"};if(!d.ok){const e=await d.json().catch(()=>({}));this.failFromResponse(d.status,e,"Failed to push application.")}return{status:"ok",commit:(await d.json().catch(()=>({}))).commit??""}}finally{await h.remove(c).catch(()=>{})}}async pushLegacy(e,s,o){const n=await re(s),a=Object.keys(n);t(`Legacy push including ${a.length} files`);const r=new v;for(const t of a){const e=m.join(s,...t.split("/")),o=m.posix.dirname(t);r.addLocalFile(e,"."===o?"":o,m.posix.basename(t))}const c=m.join($.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{o.start("Packaging application..."),r.writeZip(c),t(`Zip written to ${c}`),await this.ensureZipWithinLimit(c);const s=`${i()}/business/v1/cli/push`;t(`POST ${s}`);const n=await h.readFile(c),a=new FormData;a.append("file",new Blob([n],{type:"application/zip"}),"archive.zip"),o.text("Uploading...");const l=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:a});if(o.stop(),t(`Response: ${l.status}`),!l.ok){const e=await l.json().catch(()=>({}));this.failFromResponse(l.status,e,"Failed to push application.")}console.log(u.green("Application pushed successfully."))}finally{await h.remove(c).catch(()=>{}),t("Temp zip removed")}}async ensureZipWithinLimit(e){const{size:t}=await h.stat(e);if(t>Te){const e=e=>(e/1048576).toFixed(1);console.error(u.red(`Push package is ${e(t)} MB — the maximum is ${e(Te)} MB.`)),console.error(u.red("Remove or .gitignore large files and try again.")),process.exit(1)}}failFromResponse(e,t,s){let o=s;if(401===e||403===e)o="Please run 'dashnex login' to authenticate.";else{const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);e&&(o=e)}console.error(u.red(o)),process.exit(1)}async promptAndDeploy(e){let s;void 0!==e.deploy?(s=e.deploy,t(`Deploy decided via flag: ${s}`)):"1"===process.env.DASHNEX_CI?(s=!1,t("CI mode: skipping deploy prompt (use --deploy to deploy)")):(s=(await w.prompt([{type:"confirm",name:"deploy",message:"Deploy the application?",default:!0}])).deploy,t(`User chose to deploy: ${s}`)),s&&(t("Running deploy flow"),await(new Pe).execute())}},options:[{flags:"--deploy",description:"Auto-deploy after push (skip prompt)"},{flags:"--no-deploy",description:"Skip deploy prompt"},{flags:"--no-check",description:"Skip pre-push checks"},{flags:"-f, --force",description:"Push even when the remote has changes you don't have locally"},{flags:"-y, --yes",description:"Skip prompts (CI mode)"}]},{name:"delete",description:"Delete application from DashNex",handler:new class{async execute(e={}){if(t("Delete flow started"),!e.yes){const{confirm:e}=await w.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to delete this application? This action cannot be undone.",default:!1}]);if(!e)return t("User cancelled deletion"),void console.log(u.yellow("Deletion cancelled."))}const n=await p();if(!n)return;const r=`${i()}/business/v1/applications`;t(`DELETE ${r}`);const c=T();c.start("Deleting application...");try{const e=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}});if(c.stop(),t(`Response: ${e.status}`),!e.ok){const t=e.headers.get("content-type")??"";let s="Failed to delete application.";if(401===e.status||403===e.status)s="Please run 'dashnex login' to authenticate.";else if(t.includes("application/json")){const t=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(await e.json().catch(()=>({})));t&&(s=t)}console.error(u.red(s)),process.exit(1)}const s=await e.json().catch(()=>({})),o="string"==typeof s.message?s.message:"Application deleted successfully.";t("Application deleted successfully"),console.log(u.green(o))}catch(l){if(c.stop(),a(l),l instanceof Error&&l.message.startsWith("EXIT:"))throw l;if(o(l))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[{flags:"-y, --yes",description:"Skip confirmation prompt"}]},{name:"deploy",description:"Deploy application to DashNex",handler:new Pe,options:[{flags:"--no-check",description:"Skip pre-deploy checks"}]},{name:"status",description:"Show current application status",handler:new class{async execute(){t("Status flow started");const e=await p();if(!e)return;const n=`${i()}/business/v1/applications`;t(`GET ${n}`);const r=T();r.start("Fetching application status...");try{const s=await fetch(n,{headers:{Authorization:`Bearer ${e.token}`}});if(r.stop(),t(`Response: ${s.status}`),404===s.status)return void console.log(u.yellow("Application not created"));if(!s.ok){const e=s.headers.get("content-type")??"";let t="Failed to fetch application status.";if(401===s.status||403===s.status)t="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=await s.json().catch(()=>({}));"string"==typeof e.error?t=e.error:"string"==typeof e.message&&(t=e.message)}console.error(u.red(t)),process.exit(1)}const o=await s.json().catch(()=>({}));t(`Application body: ${JSON.stringify(o)}`);const a=o.status??"unknown";console.log(`Status: ${u.cyan(a)}`);const i=xe(o);i&&console.log(`URL: ${u.cyan(i)}`)}catch(c){if(r.stop(),a(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(o(c))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]},{name:"clear",description:"Delete local dependencies, caches and build output",handler:new class{async execute(e={}){t("Clear flow started");const n=process.cwd();h.pathExistsSync(m.join(n,"dashnex.json"))||(console.error(u.red("Run this command in a DashNex Web application folder.")),process.exit(1));const r=e.yes||"1"===process.env.DASHNEX_CI;t(`Non-interactive: ${r}`);try{const e=await this.collectTargets(n),s=m.join(n,...Xe.segments),o=await h.pathExists(s),c=o&&!r;if(o&&r&&e.push(Xe),0===e.length&&!c)return void console.log(u.yellow("Nothing to clear."));const l=[];if(e.length>0){console.log("The following will be deleted:");for(const t of e)console.log(` ${u.cyan(t.label)} ${u.dim(`(${t.description})`)}`);if(!r){const{confirm:e}=await w.prompt([{type:"confirm",name:"confirm",message:"Delete these files?",default:!1}]);if(!e)return t("User cancelled clear"),void console.log(u.yellow("Cancelled."))}for(const s of e){const e=m.join(n,...s.segments);t(`Removing ${e}`);try{await He(e),console.log(u.green(`Removed ${s.label}`))}catch(i){a(i),l.push(s.label)}}}if(c){const{confirm:e}=await w.prompt([{type:"confirm",name:"confirm",message:"Delete the local database as well?",default:!1}]);if(e){t(`Removing ${s}`);try{await He(s),console.log(u.green(`Removed ${Xe.label}`))}catch(i){a(i),l.push(Xe.label)}}}if(l.length>0){for(const e of l)console.error(u.red(`Could not delete ${e} — it may be in use. Stop 'dashnex dev' and try again.`));process.exit(1)}console.log(u.green("Clear complete. Run 'dashnex install' to set the application up again."))}catch(i){if(i instanceof Error&&i.message.startsWith("EXIT:"))throw i;if(a(i),o(i))return void console.log(u.yellow(s));throw i}}async collectTargets(e){const t=[];for(const s of qe)await h.pathExists(m.join(e,...s.segments))&&t.push(s);return t.filter(s=>!t.some(t=>t!==s&&((e,t)=>{const s=m.relative(t,e);return""!==s&&!s.startsWith("..")&&!m.isAbsolute(s)})(m.join(e,...s.segments),m.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(e={}){const s=e.level??"log";Be(s)||(console.error(u.red(`Invalid --level '${e.level}'. Use one of: log, info, warn, error, debug.`)),process.exit(1));let o=null;if(e.filter)try{o=new RegExp(e.filter)}catch{console.error(u.red(`Invalid --filter regular expression: ${e.filter}`)),process.exit(1)}const n=await p();if(!n)return;const r=!!e.debug;let c;try{c=await async function(e,s={}){const o=`${i()}${Fe}`;t(`POST ${o}${s.debug?" (debug)":""}`);const n=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({debug:!!s.debug})});if(t(`Response: ${n.status}`),401===n.status||403===n.status)throw new Ae("Not authorised to tail this application.");if(404===n.status)throw new je("Business has no application, or the tail endpoint is unavailable.");if(!n.ok)throw new Ne(`Failed to start tail (status ${n.status}).`);const a=await n.json().catch(()=>({}));if(!a.token||!a.workerUrl)throw new Ne("Malformed tail-token response from the platform.");return{token:a.token,workerUrl:a.workerUrl,expiresAt:"number"==typeof a.expiresAt?a.expiresAt:0}}(n.token,{debug:r})}catch(k){a(k),k instanceof Ae&&(console.error(u.red(k.message)),process.exit(1)),k instanceof je&&(console.error(u.red(k.message)),process.exit(2)),console.error(u.red(k instanceof Error?k.message:"Could not start tail. Check your connection.")),process.exit(3)}const l={color:!!process.stdout.isTTY},d={minLevel:s,filter:o},h=(m=c.workerUrl,`${/^(localhost|127\.0\.0\.1)/.test(m)?"ws":"wss"}://${m}/api/realtime/tail`);var m;const g=`dashnex.tail.token.${c.token}`;console.log(u.dim(`Tailing ${c.workerUrl} — Ctrl+C to stop.`)),r&&console.log(u.dim("Debug logging enabled on the worker (DEBUG=1); may take a minute to take effect."));let f=!1,y=Date.now();const w=setInterval(()=>{f||Date.now()-y>=3e4&&(console.log(u.dim("(no logs in 30s)")),y=Date.now())},5e3),$=new E(h,g,{WebSocket:S,connectionTimeout:1e4,maxReconnectionDelay:16e3}),v=async e=>{if(!f){f=!0,clearInterval(w);try{$.close()}catch{}await Promise.race([Ie(n.token,{debug:r}),new Promise(e=>setTimeout(e,3e3))]),process.exit(e)}};process.on("SIGINT",()=>{console.log(),v(0)}),$.binaryType="arraybuffer",$.addEventListener("message",e=>{y=Date.now();const t=Je("string"==typeof e.data?e.data:"",d,l);"line"===t.kind?console.log(t.line):"malformed"===t.kind&&console.error(u.dim(`[malformed frame] ${t.raw}`))}),$.addEventListener("close",e=>{if(!f)return Ge.has(e.code)?(console.error(u.red("Tail token was rejected (auth). Exiting.")),void v(1)):void t(`socket closed (code ${e.code}); reconnecting…`)}),$.addEventListener("error",e=>{t(`socket error: ${e.message??"unknown"}`)}),await new Promise(()=>{})}},options:[{flags:"--level <level>",description:"Minimum level: log, info, warn, error, debug"},{flags:"--filter <regex>",description:"Only show records whose args match this regex"},{flags:"--debug",description:"Also enable DEBUG=1 on the worker so debug-gated logs are shown"}]}]},Ve={name:"secrets",description:"Manage DashNex secrets",handler:{execute:async()=>{}},options:[],subcommands:[{name:"list",description:"List all secret names bound to the worker",handler:new class{async execute(){t("Secrets list flow started");const e=await p();if(!e)return;const n=`${i()}/business/v1/cli/secrets`;t(`GET ${n}`);const r=T();r.start("Fetching secrets...");try{const s=await fetch(n,{headers:{Authorization:`Bearer ${e.token}`}});if(r.stop(),t(`Response: ${s.status}`),!s.ok){let e="Failed to fetch secrets.";401===s.status||403===s.status?e="Please run 'dashnex login' to authenticate.":404===s.status?e="Business has no application.":502===s.status&&(e="Error fetching secrets. Make sure your application is deployed."),console.error(u.red(e)),process.exit(1)}const o=(await s.json()).secrets??[];if(0===o.length)return void console.log(u.yellow("No secrets set."));console.log(u.bold(`\nSecrets (${o.length}):\n`)),o.forEach(({name:e})=>{console.log(` ${u.cyan(e)}`)}),console.log("")}catch(c){if(r.stop(),a(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(o(c))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]},{name:"set",description:"Create or update a secret (prompts for missing KEY/VALUE)",handler:new class{async execute(e={}){t("Secrets set flow started");let{name:n,value:r}=e;const c="1"===process.env.DASHNEX_CI;n||(c&&(console.error(u.red("--name is required in CI mode (--ci).")),process.exit(1)),n=(await w.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim()),r||(c&&(console.error(u.red("--value is required in CI mode (--ci).")),process.exit(1)),r=(await w.prompt([{type:"password",name:"value",message:`Enter value for ${n}:`,mask:"*",validate:e=>""!==e||"Value is required"}])).value);const l=await p();if(!l)return;const d=`${i()}/business/v1/cli/secrets`;t(`PUT ${d}`);const h=T();h.start(`Setting secret '${n}'...`);try{const e=await fetch(d,{method:"PUT",headers:{Authorization:`Bearer ${l.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:n,value:r})});if(h.stop(),t(`Response: ${e.status}`),!e.ok){let t="Failed to set secret.";401===e.status||403===e.status?t="Please run 'dashnex login' to authenticate.":400===e.status?t="Missing or empty name / value.":404===e.status?t="Business has no application.":502===e.status&&(t="Error setting secret. Make sure your application is deployed."),console.error(u.red(t)),process.exit(1)}t(`Secret '${n}' set successfully`),console.log(u.green(`Secret '${n}' set successfully.`))}catch(m){if(h.stop(),a(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(o(m))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},arguments:[{name:"name",description:"Secret name (KEY)"},{name:"value",description:"Secret value"}],options:[{flags:"--name <name>",description:"Secret name (alternative to positional KEY)"},{flags:"--value <value>",description:"Secret value (alternative to positional VALUE)"}]},{name:"delete",description:"Delete a secret (prompts for missing KEY)",handler:new class{async execute(e={}){t("Secrets delete flow started");let{name:n}=e;const r="1"===process.env.DASHNEX_CI;n||(r&&(console.error(u.red("--name is required in CI mode (--ci).")),process.exit(1)),n=(await w.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim());const c=await p();if(!c)return;const l=`${i()}/business/v1/cli/secrets/${encodeURIComponent(n)}`;t(`DELETE ${l}`);const d=T();d.start(`Deleting secret '${n}'...`);try{const e=await fetch(l,{method:"DELETE",headers:{Authorization:`Bearer ${c.token}`}});if(d.stop(),t(`Response: ${e.status}`),!e.ok){let t="Failed to delete secret.";401===e.status||403===e.status?t="Please run 'dashnex login' to authenticate.":404===e.status?t=`Secret '${n}' not found.`:502===e.status&&(t="Error deleting secret. Make sure your application is deployed."),console.error(u.red(t)),process.exit(1)}t(`Secret '${n}' deleted successfully`),console.log(u.green(`Secret '${n}' deleted.`))}catch(h){if(d.stop(),a(h),h instanceof Error&&h.message.startsWith("EXIT:"))throw h;if(o(h))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},arguments:[{name:"name",description:"Secret name (KEY)"}],options:[{flags:"--name <name>",description:"Secret name (alternative to positional KEY)"}]}]},Ke=[{name:"version",description:"Display the version of the CLI",handler:new class{async execute(e){const t=m.dirname(g(import.meta.url)),s=JSON.parse(y.readFileSync(m.resolve(t,"..","..","package.json"),"utf8"));console.log(s.version)}},options:[]},{name:"login",description:"Log in to your DashNex account",handler:new class{async execute(r={}){t("Login flow started");const i=c(process.cwd()),l=await p({exitOnFailure:!1,dashnexPath:i});if(l)console.log(u.green(`Already logged in as ${l.userName??"user"}`));else try{let s,o;if(r.email)s=r.email.trim(),t("Email provided via flag");else{const{username:e}=await w.prompt([{type:"input",name:"username",message:"Email:",validate:e=>!!e.trim()||"Email is required"}]);s=e.trim()}if(r.password)o=r.password,t("Password provided via flag");else{const{password:e}=await w.prompt([{type:"password",name:"password",message:"Password:",mask:"*",validate:e=>!!e||"Password is required"}]);o=e}t("Email provided");const c=T();c.start("Logging in..."),t(`POST ${e()}/auth/v1/login`);const{response:l,body:p}=await n(`${e()}/auth/v1/login`,{method:"POST",body:JSON.stringify({username:s,password:o})});c.stop(),t(`Response: ${l.status}`),d("Login response",p),l.ok||(a(/* @__PURE__ */new Error(`Login failed: ${l.status} ${JSON.stringify(p)}`)),401===l.status&&(console.error(u.red("Invalid username or password.")),process.exit(1)),A(l,p,"Login failed. Please try again."));const h=p;if(h.two_fa_required&&h.token){t(`2FA required, type: ${h.type||"unknown"}`);const e=await this.handle2FA(h.token,h.type,r.code);e||process.exit(1),await this.completeLogin(e,i,r.business)}else h.token&&h.refreshToken?await this.completeLogin({token:h.token,refreshToken:h.refreshToken},i,r.business):(console.error(u.red("Invalid response from server. Please try again.")),process.exit(1))}catch(h){if(a(h),o(h))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}async handle2FA(r,i,c){if("sms"===i){t(`POST ${e()}/auth/v1/two-fa/sms`);try{const{response:s}=await n(`${e()}/auth/v1/two-fa/sms`,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:JSON.stringify({})});t(`Response: ${s.status}`)}catch(h){return a(h),console.error(u.red("Could not send SMS code. Check your connection and try again.")),null}}const l="sms"===i?"Check your phone for the code":"Check your authenticator app for the code",p=c?1:3;for(let m=1;m<=p;m++){let i;c&&1===m?(i=c,t("2FA code provided via flag")):i=(await w.prompt([{type:"input",name:"auth_code",message:`Enter code (${l}):`,validate:e=>!!e.trim()||"Code is required"}])).auth_code,t(`POST ${e()}/auth/v1/2fa-check`);try{const{response:s,body:o}=await n(`${e()}/auth/v1/2fa-check`,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:JSON.stringify({auth_code:i.trim()})});if(t(`Response: ${s.status}`),d("2FA check response",o),s.ok){const e=o;if(e.token&&e.refreshToken)return{token:e.token,refreshToken:e.refreshToken}}if(s.status>=400&&s.status<500){if(console.error(u.red("Invalid code. Please try again.")),m<p){const{retry:e}=await w.prompt([{type:"confirm",name:"retry",message:"Try again?",default:!0}]);if(!e)return null}continue}A(s,o,"2FA verification failed. Please try again.")}catch(h){return a(h),o(h)?(console.log(u.yellow(s)),null):(console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),null)}}return null}async completeLogin(s,o,r){const c=T();c.start("Fetching businesses...");const l=e(),p={Authorization:`Bearer ${s.token}`};t(`GET ${l}/users/v1/business/my`);const{response:g,body:f}=await n(`${l}/users/v1/business/my`,{headers:p});t(`Response: ${g.status}`),d("Businesses response",f),g.ok||(c.stop(),a(/* @__PURE__ */new Error(`Business fetch failed: ${g.status}`)),A(g,f,"Failed to fetch businesses. Please try again."));const y=this.parseBusinesses(f),$=await this.fetchOtherBusinesses(s.token),v=this.mergeBusinesses(y,$);let k;if(c.stop(),t(`Businesses (my: ${y.length}, other: ${$.length}, merged: ${v.length})`),0===v.length&&(console.error(u.red("No businesses or teams found for your account!")),console.log(u.green("Create your first business at https://dashnex.io")),process.exit(1)),r){const e=v.find(e=>e.id===r);e||(console.error(u.red(`Business "${r}" not found.`)),process.exit(1)),k=e,t(`Selected business via flag: ${k.id} ${k.name}`)}else if(1===v.length)k=v[0],t(`Selected business: ${k.id} ${k.name}`);else{const{businessId:e}=await w.prompt([{type:"select",name:"businessId",message:"Select business:",choices:v.map(e=>({name:e.name,value:e.id}))}]);k=v.find(t=>t.id===e)||v[0],t(`Selected business: ${k.id} ${k.name}`)}c.start("Switching business..."),t(`GET ${l}/business/v1/login?_switch_business=${k.id}`);const{response:b,body:x}=await n(`${l}/business/v1/login?_switch_business=${k.id}`,{headers:p});c.stop(),t(`Response: ${b.status}`),d("Business login response",x),b.ok||(a(/* @__PURE__ */new Error(`Business login failed: ${b.status}`)),A(b,x,"Failed to switch to business. Please try again."));const E=x;E.token&&E.refreshToken||(console.error(u.red("Invalid response from server. Please try again.")),process.exit(1));const S={token:E.token,refreshToken:E.refreshToken,businessId:k.id},C={Authorization:`Bearer ${E.token}`};try{const e=i();t(`GET ${e}/business/v1/cli/settings`);const{response:s,body:o}=await n(`${e}/business/v1/cli/settings`,{headers:C});t(`Response: ${s.status}`),d("CLI settings response",o),s.ok&&o&&"object"==typeof o&&Object.assign(S,o)}catch(P){a(P)}const D=m.dirname(o);await h.pathExists(D)&&(await h.stat(D)).isFile()&&await h.remove(D),await h.ensureDir(D),await h.writeJson(o,S,{spaces:2}),t("Saved credentials to .dashnex/settings.json"),this.ensureGitignore(),console.log(u.green(`Logged in as ${k.name}`))}async fetchOtherBusinesses(s){const o=e();let r=1;const i=[];let c=0;do{const e=`${o}/users/v1/business/other?page=${r}&perPage=100`;t(`GET ${e}`);const{response:l,body:p}=await n(e,{headers:{Authorization:`Bearer ${s}`}});l.ok||(a(/* @__PURE__ */new Error(`Other businesses fetch failed: ${l.status}`)),A(l,p,"Failed to fetch teams. Please try again."));const d=this.parseBusinesses(p),u="number"==typeof p.total?p.total:d.length;if(i.push(...d),c=u,d.length<100||i.length>=c)break;r++}while(i.length<c);return i}mergeBusinesses(e,t){const s=/* @__PURE__ */new Map;for(const o of e)s.set(o.id,o);for(const o of t)s.has(o.id)||s.set(o.id,o);return[...s.values()]}parseBusinesses(e){const t=Array.isArray(e)?e:e.items??e.data??e.businesses??[];return Array.isArray(t)?t.map(e=>{if(e&&"object"==typeof e){const t=e,s=String(t.id??t.business_id??"").trim(),o=String(t.name??t.companyName??t.business_name??"Unknown").trim();if(s)return{id:s,name:o}}return null}).filter(e=>null!==e):[]}async ensureGitignore(){const e=m.join(process.cwd(),".gitignore");if(!(await h.pathExists(e)))return;let t=await h.readFile(e,"utf8");t.includes(".dashnex")||(t=t.trimEnd(),t.endsWith("\n")||(t+="\n"),t+="\n.dashnex\n",await h.writeFile(e,t))}},options:[{flags:"--email <email>",description:"Email address (skip prompt)"},{flags:"--password <password>",description:"Password (skip prompt)"},{flags:"--code <code>",description:"2FA code (skip prompt)"},{flags:"--business <id>",description:"Business ID to select (skip prompt)"}]},{name:"logout",description:"Log out and remove local credentials",handler:new class{async execute(){const e=c(process.cwd());if(await h.pathExists(e)){const t=await h.readJson(e);delete t.token,delete t.refreshToken,delete t.businessId,await h.writeJson(e,t,{spaces:2})}console.log(u.green("Logged out."))}},options:[]},{name:"whoami",description:"Show current logged-in business and user",handler:new class{async execute(){t("Whoami flow started");const n=await p();if(!n)return;const r=`${e()}/users/v1/`;t(`GET ${r}`);const i=T();i.start("Fetching user info...");try{const e=await fetch(r,{headers:{Authorization:`Bearer ${n.token}`}});if(i.stop(),t(`Response: ${e.status}`),!e.ok){const t=e.headers.get("content-type")??"";let s="Failed to fetch user info.";if(401===e.status||403===e.status)s="Please run 'dashnex login' to authenticate.";else if(t.includes("application/json")){const t="string"==typeof(c=await e.json().catch(()=>({}))).error?c.error:"string"==typeof c.message?c.message:void 0;t&&(s=t)}console.error(u.red(s)),process.exit(1)}const s=await e.json().catch(()=>({})),o="string"==typeof s.name?s.name:"string"==typeof s.companyName?s.companyName:"Unknown",a=s.memberUser,l=a&&"string"==typeof a.fullName?a.fullName:a&&"string"==typeof a.name?a.name:"Unknown";t(`Whoami: ${o} (${l})`),console.log(u.green(`You are logged in as ${o} (${l})`))}catch(l){if(i.stop(),a(l),l instanceof Error&&l.message.startsWith("EXIT:"))throw l;if(o(l))return void console.log(u.yellow(s));console.error(u.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}var c}},options:[]},{name:"dev",description:"Run the development server (run in DashNex application folder)",handler:new class{async execute(e={}){t("Dev flow started");try{const t=await I(process.cwd(),e);process.exit(t)}catch(s){if(s instanceof Error&&s.message.startsWith("EXIT:"))throw s;a(s),s instanceof Error?console.error(u.red(s.message)):console.error(u.red("Failed to run npm run dev")),process.exit(1)}}},options:[{flags:"--https",description:"Run dev server with HTTPS"}]},{name:"check",description:"Run build-time validations (run in DashNex application folder)",handler:new X,options:[]},{name:"install",description:"Install dependencies using pnpm (preferred) or npm (run in DashNex application folder)",handler:new class{async execute(){t("Install flow started");const e=m.join(process.cwd(),"dashnex.json");await h.pathExists(e)||(console.error(u.red("Run this command in a DashNex Web application folder.")),process.exit(1));const s=process.cwd(),o=T();o.start("Installing dependencies...");try{const e=await R(s);o.stop(),0!==e&&process.exit(e),console.log(u.green("Dependencies installed.")),process.exit(0)}catch(n){o.stop(),a(n),n instanceof Error?console.error(u.red(n.message)):console.error(u.red("Failed to run install")),process.exit(1)}}},options:[]},Ye,Ve];export{Ke as default};
|
|
1
|
+
import{a as e,c as t,d as o,f as s,h as n,i as r,l as a,m as i,n as c,o as l,p as d,r as p,s as u,t as h,u as g}from"../chunks/auth-ezwXxi-m.js";import m from"chalk";import f from"fs-extra";import y from"path";import{fileURLToPath as w}from"url";import{spawn as $}from"child_process";import v from"fs";import k from"inquirer";import{createHash as x,randomBytes as b}from"crypto";import S from"os";import E from"adm-zip";import{diffLines as D}from"diff";import C from"ignore";import{WebSocket as T}from"partysocket";import P from"ws";import{inspect as N}from"node:util";import{rm as A}from"node:fs/promises";var j=e=>e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),I=async e=>{const t=(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]}}})(e);return!!t&&new Promise(e=>{try{const n=$(t.command,t.args,{stdio:"ignore",detached:!0});n.on("error",t=>{s(t),e(!1)}),n.on("spawn",()=>{o(`Opened browser via ${t.command}`),n.unref(),e(!0)})}catch(n){s(n),e(!1)}})},R="urn:ietf:wg:oauth:2.0:oob",F=class extends Error{constructor(e,t){super(e),this.code=t,this.name="OAuthError"}},O=class extends Error{},B=class extends O{},z=e=>{const t=e.data;return t&&"object"==typeof t?t:e},L=e=>{const t=e.items??[];return Array.isArray(t)?t.map(e=>{if(!e||"object"!=typeof e)return null;const t=e,o=Number(t.id);return!Number.isFinite(o)||o<=0?null:{id:o,name:String(t.name??t.companyName??`Business ${o}`).trim()}}).filter(e=>null!==e):[]},_=async(s,n)=>{const r=[];let a=1,i=0;do{const c=`${t()}${s}?page=${a}&perPage=100`;o(`GET ${c}`);const{response:l,body:p}=await e(c,{headers:{Authorization:`Bearer ${n}`}});if(o(`Response: ${l.status}`),d(`Businesses response (${s})`,p),!l.ok){if(401===l.status)throw new B("Your DashNex ID session has expired.");if(404===l.status)throw new O(`Your DashNex ID account is not linked to a contact yet. Finish signing up at ${t()} and try again.`);throw new O("Failed to fetch businesses. Please try again.")}const u=z(p),h=L(u);if(i="number"==typeof u.total?u.total:h.length,r.push(...h),h.length<100||r.length>=i)break;a++}while(r.length<i);return r},U=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],M=(e="")=>{if(process.env.DASHNEX_CI)return{start:()=>{},stop:()=>{},text:()=>{}};let t=null,o=0,s=e;const n=()=>{const e=U[o%U.length];process.stderr.write(`\r[K${e} ${s}`),o++};return{start:e=>{void 0!==e&&(s=e),t||(o=0,n(),t=setInterval(n,80))},stop:()=>{t&&(clearInterval(t),t=null),process.stderr.write("\r[K\n")},text:e=>{s=e,t&&n()}}},W=class a{async execute(e={}){o("Login flow started");const t=r(process.cwd()),a=await h({exitOnFailure:!1,dashnexPath:t});if(a)console.log(m.green(`Already logged in as ${a.userName??"user"}`));else{g()||(console.error(m.red("No DashNex ID OAuth client is configured for this environment.")),console.error(m.yellow("Set DASHNEX_OAUTH_CLIENT_ID, or use APPLICATION_ENV=qa.")),process.exit(1));try{const s=await this.readSavedIdToken(t);if(s){o("Resuming with saved DashNex ID session");try{return void(await this.selectBusiness(s,t,e.business))}catch(c){if(!(c instanceof B))throw c;o("Saved DashNex ID session rejected, starting a new sign-in")}}const n=await this.authorize(!1!==e.browser);await this.writeConfig(t,{idToken:n.token,...n.refreshToken&&{idRefreshToken:n.refreshToken}}),await this.selectBusiness(n.token,t,e.business)}catch(c){if(s(c),n(c))return void console.log(m.yellow(i));if((c instanceof F||c instanceof O)&&(console.error(m.red(c.message)),process.exit(1)),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;console.error(m.red("Could not reach DashNex. Check your connection and try again.")),process.exit(1)}}}async authorize(s){const{verifier:n,challenge:r}=(()=>{const e=j(b(32));return{verifier:e,challenge:j(x("sha256").update(e).digest())}})(),a=(e=>{const o=new URL(`${t()}/api/oauth/authorize`);return o.searchParams.set("client_id",g()),o.searchParams.set("redirect_uri",R),o.searchParams.set("response_type","code"),o.searchParams.set("code_challenge",e),o.searchParams.set("code_challenge_method","S256"),o.toString()})(r);o(`Authorize URL: ${a}`);const i=!!s&&await I(a);console.log(""),i?(console.log(m.green("Opened your browser to finish signing in.")),console.log(m.dim("If nothing opened, use this URL:"))):console.log(m.bold("Open this URL to sign in:")),console.log(m.cyan(a)),console.log(""),console.log(m.dim("Approve the request, then copy the code shown and paste it below.")),console.log("");const{code:c}=await k.prompt([{type:"input",name:"code",message:"Paste the code:",validate:e=>!!e.trim()||"Code is required"}]),l=M();l.start("Verifying code...");try{return await(async(s,n)=>{const r=`${t()}/api/oauth/token`;o(`POST ${r}`);const{response:a,body:i}=await e(r,{method:"POST",body:JSON.stringify({grant_type:"authorization_code",client_id:g(),redirect_uri:R,code:s.trim(),code_verifier:n})});if(o(`Response: ${a.status}`),d("Token response",i),!a.ok){const e="string"==typeof i.error?i.error:void 0,t="string"==typeof i.error_description?i.error_description:void 0;if("invalid_grant"===e)throw new F("That code is not valid anymore. Codes expire 10 minutes after they are issued and can only be used once.",e);throw new F(t??"Could not exchange the code for a token.",e)}const c=i;if(!c.access_token)throw new F("The authorization server did not return an access token.");return{token:c.access_token,refreshToken:c.refresh_token,expiresIn:c.expires_in}})(c,n)}finally{l.stop()}}async selectBusiness(s,n,r){const a=M();let i;a.start("Fetching businesses...");try{i=await(async e=>{const t=await _("/api/businesses/my",e),s=await _("/api/businesses/other",e),n=/* @__PURE__ */new Map;for(const o of t)n.set(o.id,o);for(const o of s)n.has(o.id)||n.set(o.id,o);return o(`Businesses (my: ${t.length}, other: ${s.length}, merged: ${n.size})`),[...n.values()]})(s)}finally{a.stop()}0===i.length&&(console.error(m.red("No businesses or teams found for your account!")),console.log(m.green(`Create your first business at ${t()}`)),process.exit(1));const c=await this.pickBusiness(i,r);let l;a.start("Switching business...");try{l=await(async(s,n)=>{const r=`${t()}/api/businesses/${n}/switch`;o(`POST ${r}`);const{response:a,body:i}=await e(r,{method:"POST",headers:{Authorization:`Bearer ${s}`}});if(o(`Response: ${a.status}`),d("Switch response",i),!a.ok){if(401===a.status)throw new B("Your DashNex ID session has expired.");if(403===a.status)throw new O("You do not have access to that business.");throw new O("Failed to switch to business. Please try again.")}const c=z(i);if(!c.token||!c.refreshToken)throw new O("Invalid response from server. Please try again.");return{token:c.token,refreshToken:c.refreshToken,businessId:n}})(s,c.id)}finally{a.stop()}const p={token:l.token,refreshToken:l.refreshToken,businessId:l.businessId,...await this.fetchCliSettings(l.token)};await this.writeConfig(n,p),await this.ensureGitignore(),console.log(m.green(`Logged in as ${c.name}`))}async pickBusiness(e,t){if(t){const s=e.find(e=>String(e.id)===String(t).trim());return s||(console.error(m.red(`Business "${t}" not found.`)),process.exit(1)),o(`Selected business via flag: ${s.id} ${s.name}`),s}if(1===e.length)return o(`Selected business: ${e[0].id} ${e[0].name}`),e[0];const{businessId:s}=await k.prompt([{type:"select",name:"businessId",message:"Select business:",choices:e.map(e=>({name:e.name,value:e.id}))}]),n=e.find(e=>e.id===s)||e[0];return o(`Selected business: ${n.id} ${n.name}`),n}async readSavedIdToken(e){if(!(await f.pathExists(e)))return null;try{return(await f.readJson(e)).idToken??null}catch{return null}}async fetchCliSettings(t){try{const s=`${u()}/business/v1/cli/settings`;o(`GET ${s}`);const{response:n,body:r}=await e(s,{headers:{Authorization:`Bearer ${t}`}});if(o(`Response: ${n.status}`),d("CLI settings response",r),n.ok&&r&&"object"==typeof r)return r}catch(n){s(n)}return{}}static{this.OBSOLETE_KEYS=["issuer"]}async writeConfig(e,t){const s=y.dirname(e);await f.pathExists(s)&&(await f.stat(s)).isFile()&&await f.remove(s),await f.ensureDir(s);let n=t;if(await f.pathExists(e))try{n={...await f.readJson(e),...t};for(const e of a.OBSOLETE_KEYS)delete n[e]}catch{o("Existing settings.json could not be parsed, overwriting")}await f.writeJson(e,n,{spaces:2}),o("Saved credentials to .dashnex/settings.json")}async ensureGitignore(){const e=y.join(process.cwd(),".gitignore");if(!(await f.pathExists(e)))return;let t=await f.readFile(e,"utf8");t.includes(".dashnex")||(t=t.trimEnd(),t.endsWith("\n")||(t+="\n"),t+="\n.dashnex\n",await f.writeFile(e,t))}},J=["Using vars defined in \\.env","\\(node:\\d+\\) MaxListenersExceededWarning:","\\(Use `node --trace-warnings","\\[WARNING\\].*You have defined bindings to the following internal Durable Objects","You have defined bindings to the following internal Durable Objects",'\\{"name":".+","class_name":".+"\\}',"These will not work in local development, but they should work in production","If you want to develop these locally, you can define your DO in a separate Worker","For detailed instructions, refer to the Durable Objects section here:","developers.cloudflare.com/workers/wrangler/api#supported-bindings","workerd/server/server\\.c\\+\\+.*warning:.*DurableObjectNamespace"],G=(e,t)=>t.length>0&&t.some(t=>t.test(e)),X=(e,t)=>{let s="";return{write:n=>{const r="string"==typeof n?n:n.toString();s+=r;const a=s.split(/\r?\n/);s=a.pop()??"";for(const s of a){const n=s.trim();n?G(n,t)?o(`Filtered: ${n}`):e.write(s+"\n"):o("Filtered: <empty line>")}},flush:()=>{const n=s.trim();if(n){if(G(n,t))return o(`Filtered: ${n}`),void(s="");e.write(s),s=""}else s=""}}},q=async(e,t={})=>{const n=y.join(e,"dashnex.json"),r=y.join(e,"package.json");if(o(`Checking for dashnex.json at: ${n}`),!(await f.pathExists(n)))throw new Error("Run this command in a DashNex Web application folder.");if(o("dashnex.json found, checking for package.json"),!(await f.pathExists(r)))throw new Error("package.json is missing.");let a;o("package.json found, checking for dev script");try{a=await f.readJson(r)}catch(l){throw s(l),new Error("Failed to read package.json.")}if(!a.scripts||!a.scripts.dev)throw new Error('The "dev" script is missing from package.json. Please add a "dev" script to package.json.');o("dev script found, checking for npm availability");const i=await(async e=>new Promise(t=>{const o=$(`${e} --version`,{stdio:"ignore",shell:!0});o.on("error",()=>{t(!1)}),o.on("close",e=>{t(0===e)})}))("npm");if(o(`npm available: ${i}`),!i)throw new Error("npm is not available. Please install npm to continue.");const c=t.https?["--","--experimental-https"]:[];return o(`npm available, executing: npm run dev in ${e}${t.https?" -- --experimental-https":""}`),(async(e,t=[],o=process.cwd(),n=[])=>{const r=t.length?`${e} ${t.join(" ")}`:e,a=n.length>0;return new Promise((e,t)=>{const i=$(r,{stdio:a?["inherit","pipe","pipe"]:"inherit",cwd:o,shell:!0,env:{...process.env,NODE_ENV:"development",FORCE_COLOR:"1"}});if(i.on("error",e=>{s(e),t(e)}),a&&i.stdout&&i.stderr){const t=X(process.stdout,n),o=X(process.stderr,n);i.stdout.on("data",e=>t.write(e)),i.stderr.on("data",e=>o.write(e)),i.on("close",s=>{t.flush(),o.flush(),e(null===s?0:s)})}else i.on("close",t=>{e(null===t?0:t)})})})("npm run dev",c,e,(()=>{const e=[];for(const t of J)try{e.push(new RegExp(t))}catch{o(`Invalid dev output filter pattern ignored: ${t}`)}return e})())},Y=async e=>new Promise(t=>{const o=$(`${e} --version`,{stdio:"ignore",shell:!0});o.on("error",()=>{t(!1)}),o.on("close",e=>{t(0===e)})}),H=async e=>{let t;if(await Y("pnpm"))t="pnpm install --config.strict-dep-builds=false",o("Using package manager: pnpm");else{if(!(await Y("npm")))throw new Error("Neither pnpm nor npm is available. Install Node.js (which bundles npm) or pnpm to continue.");t="npm install --legacy-peer-deps",o("Using package manager: npm (with --legacy-peer-deps for DashNex peer-dep overlap)")}return o(`Executing: ${t} in ${e}`),new Promise((o,n)=>{const r=[],a=[],i=$(t,{stdio:["ignore","pipe","pipe"],cwd:e,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",e=>{s(e),n(e)}),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))),o(t)})})},V="Run this command in a DashNex Web application folder.",K=e=>{const t=y.join(e,"dashnex.json");return f.pathExistsSync(t)},Z=(e,t=!1)=>{t||console.log(m.cyan(e))},Q=(e,t,n={})=>{const r=`${e} ${t.join(" ")}`,a=!0===n.silent;return new Promise((t,n)=>{o(`Running: ${r}`);const i=$(r,{stdio:a?["ignore","pipe","pipe"]:"inherit",cwd:process.cwd(),shell:!0});i.on("error",e=>{s(e),n(e)}),i.on("close",s=>{o(`${e} exited with code ${s}`),t(null===s?1:s)})})},ee=(e,t)=>new Promise((n,r)=>{o(`Running: ${e} ${t.join(" ")}`);const a=$(e,t,{cwd:process.cwd()});let i="";a.stdout?.on("data",e=>{i+=e.toString()}),a.stderr?.on("data",e=>{i+=e.toString()}),a.on("error",e=>{s(e),r(e)}),a.on("close",t=>{o(`${e} exited with code ${t}`),n({exitCode:null===t?1:t,output:i})})}),te=async e=>{o("Running check: install");try{return 0===await H(process.cwd())}catch(t){return s(t),!e&&t instanceof Error&&console.error(m.red(t.message)),!1}},oe=async()=>{try{const{output:e}=await ee(process.execPath,[process.argv[1],"db","migrate","--help"]);return e.includes("Usage: dashnex db migrate")}catch(e){return s(e),!1}},se=async e=>{o("Running check: db migrate");try{const{exitCode:t,output:s}=await ee(process.execPath,[process.argv[1],"db","migrate"]);return 0===t||(s.includes("Unknown command")?(o("db migrate command is not available, skipping"),!0):(!e&&s.trim().length>0&&process.stderr.write(s),!1))}catch(t){return s(t),!0}},ne=e=>new Promise(t=>{const o=$(`${e} --version`,{stdio:"ignore",shell:!0});o.on("error",()=>t(!1)),o.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"}],ae=class{async execute(){o("Check flow started"),K(process.cwd())||(console.error(m.red(V)),process.exit(1)),Z("Checking dependencies..."),await te(!1)||(console.error(m.red("Check failed.")),process.exit(1)),o(`Running ${re.length} check(s)`);for(const t of re){o(`Running check: ${t.name}`),Z(`Checking ${t.name}...`),await ne(t.command)||(console.error(m.red(t.notFoundMessage)),process.exit(1));try{0!==await Q(t.command,t.args)&&(console.error(m.red("Check failed.")),process.exit(1))}catch(e){s(e),console.error(m.red(t.notFoundMessage)),process.exit(1)}}await oe()?(Z("Checking database migrations..."),await se(!1)||(console.error(m.red("Check failed.")),process.exit(1))):o("db migrate command is not available, skipping"),console.log(m.green("All checks passed."))}async run(e=!1){if(o("Running checks (called from push)"),!K(process.cwd()))return e||console.error(m.red(V)),!1;if(Z("Checking dependencies...",e),!(await te(e)))return!1;const t=e?{silent:!0}:void 0;for(const r of re){if(o(`Running check: ${r.name}`),Z(`Checking ${r.name}...`,e),!(await ne(r.command)))return console.error(m.red(r.notFoundMessage)),!1;try{if(0!==await Q(r.command,r.args,t))return!1}catch(n){return s(n),console.error(m.red(r.notFoundMessage)),!1}}if(await oe()){if(Z("Checking database migrations...",e),!(await se(e)))return!1}else o("db migrate command is not available, skipping");return e||console.log(m.green("All checks passed.")),!0}},ie=" │ ",ce=e=>e.subarray(0,8192).includes(0),le=e=>{const t=e.split("\n");return""===t[t.length-1]&&t.pop(),t},de=(e,t)=>{if(null===e)return" ".repeat(t);const o=e.replace(/\t/g," ");return o.length<=t?o.padEnd(t):`${o.slice(0,Math.max(0,t-1))}…`},pe=(e,t,o)=>{const s=Math.max(o??process.stdout.columns??120,43),n=Math.floor((s-3)/2),r=((e,t)=>{const o=[],s=D(e,t);for(let n=0;n<s.length;n+=1){const e=s[n];if(e.removed){const t=le(e.value),r=s[n+1],a=r?.added?le(r.value):[];r?.added&&(n+=1);const i=Math.max(t.length,a.length);for(let e=0;e<i;e+=1)o.push({left:t[e]??null,right:a[e]??null,changed:!0})}else if(e.added)for(const t of le(e.value))o.push({left:null,right:t,changed:!0});else for(const t of le(e.value))o.push({left:t,right:t,changed:!1})}return o})(e,t),a=/* @__PURE__ */new Set;r.forEach((e,t)=>{if(e.changed)for(let o=Math.max(0,t-3);o<=Math.min(r.length-1,t+3);o+=1)a.add(o)});const i=[];i.push(m.bold(de("local (current)",n))+m.dim(ie)+m.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(m.dim("···")),c=p,l+=1;const e=r[p],t=de(e.left,n),o=de(e.right,n);if(!e.changed){i.push(m.dim(t)+m.dim(ie)+m.dim(o));continue}const s=null!==e.left?m.red(t):t,u=null!==e.right?m.green(o):o;i.push(s+m.dim(ie)+u)}return d>0&&i.push(m.dim(`… ${d} more diff line(s) not shown`)),i.join("\n")},ue=[".dashnex",".git",".vinext",".wrangler","wrangler.jsonc","wrangler.toml",".dev.vars",".github"],he=[".env","wrangler.jsonc"],ge=e=>y.join(e,p,"sync.json"),me=e=>x("sha1").update(`blob ${e.length}\0`).update(e).digest("hex"),fe=e=>e.split(y.sep).join("/"),ye=e=>ue.some(t=>e===t||e.startsWith(`${t}/`)),we=async e=>{const t=await(async e=>{const t=C();t.add(ue);const o=y.join(e,".gitignore");return await f.pathExists(o)&&t.add(await f.readFile(o,"utf8")),t})(e),o=[],s=async n=>{const r=await f.readdir(n,{withFileTypes:!0});for(const a of r){const r=y.join(n,a.name),i=fe(y.relative(e,r));ye(i)||t.ignores(a.isDirectory()?`${i}/`:i)||(a.isDirectory()?await s(r):a.isFile()&&o.push(i))}};return await s(e),o},$e=async(e,t={})=>{const o={},s=await we(e);for(const n of s)o[n]=me(await f.readFile(y.join(e,n)));if(t.includeGenerated)for(const n of he){if(n in o)continue;const t=y.join(e,n);(await f.lstat(t).catch(()=>null))?.isFile()&&(o[n]=me(await f.readFile(t)))}return o},ve=async e=>{try{const t=await f.readFile(ge(e),"utf8"),o=JSON.parse(t);return"string"!=typeof o?.commit||"object"!=typeof o?.manifest||null===o.manifest?null:o}catch{return null}},ke=async(e,t,s)=>{const n={commit:t,manifest:s,updatedAt:/* @__PURE__ */(new Date).toISOString()},r=ge(e);try{await f.ensureDir(y.dirname(r)),await f.writeFile(r,`${JSON.stringify(n,null,2)}\n`),o(`Sync state written: commit ${t}, ${Object.keys(s).length} files`)}catch(a){o(`Failed to write sync state: ${a instanceof Error?a.message:"unknown"}`)}},xe=1048576,be=async(e,t)=>{const{install:n}=await k.prompt([{type:"confirm",name:"install",message:"Install dependencies?",default:!0}]);if(!n){if(y.resolve(e)!==y.resolve(t)){const o=y.relative(t,e);console.log(m.cyan(`Run "cd ${o}" to change to the application folder.`))}return}try{const t=M();t.start("Installing dependencies...");try{const s=await H(e);if(t.stop(),0!==s)return void o(`install exited with code ${s}`)}catch(i){throw t.stop(),i}}catch(i){return s(i),void console.error(m.red(i instanceof Error?i.message:"Failed to run install."))}const{migrate:r}=await k.prompt([{type:"confirm",name:"migrate",message:"Create or update database?",default:!0}]);if(!r)return;o(`Running dashnex db migrate in ${e}`);try{const t=M();t.start("Creating or updating database...");try{const n=await((e,t,o)=>{const n=`${y.join(e,"node_modules",".bin")}${y.delimiter}${process.env.PATH??""}`,r={...process.env,PATH:n};return new Promise((n,a)=>{const i=$(t,{cwd:e,shell:!0,stdio:"inherit",env:o?{...r,...o}:r});i.on("error",e=>{s(e),a(e)}),i.on("close",e=>{n(null===e?0:e)})})})(e,"dashnex db migrate");if(t.stop(),0!==n)return void o(`dashnex db migrate exited with code ${n}`)}catch(i){throw t.stop(),i}}catch(i){return s(i),void console.error(m.red("Failed to run dashnex db migrate."))}const{dev:a}=await k.prompt([{type:"confirm",name:"dev",message:"Run development server?",default:!0}]);if(a)try{await q(e)}catch(i){s(i),console.error(m.red(i instanceof Error?i.message:"Failed to run dev server."))}},Se=(e,t)=>{if(e.length!==t.length)return`local ${e.length} bytes, incoming ${t.length} bytes`;const o=e.length;for(let s=0;s<o;s+=1)if(e[s]!==t[s]){return`size ${o} matches; first diff at byte ${s} (local=0x${e[s].toString(16).padStart(2,"0")} incoming=0x${t[s].toString(16).padStart(2,"0")})`}return`size ${o} matches; no byte difference (unexpected)`},Ee=async(e,t)=>{let o;try{o=await f.lstat(e)}catch{return{kind:"new"}}if(o.isDirectory())return{kind:"different",reason:"target is a directory"};if(o.size!==t.length)return{kind:"different",reason:`local ${o.size} bytes, incoming ${t.length} bytes`};const s=await f.readFile(e);return 0===Buffer.compare(s,t)?{kind:"identical"}:{kind:"different",reason:Se(s,t)}},De=async(e,t,o)=>{console.log(`\n${m.bold(t)}`);try{const t=await f.readFile(e);if(t.length>xe||o.length>xe||ce(t)||ce(o))return void console.log(m.dim(`(no preview: ${Se(t,o)})`));console.log(pe(t.toString("utf8"),o.toString("utf8")))}catch(n){s(n),console.log(m.dim("(no preview available)"))}},Ce=async e=>{const{choice:t}=await k.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},Te=async(e,t)=>{const o=t?m.yellow(" (has local changes!)"):"",{choice:s}=await k.prompt([{type:"expand",name:"choice",message:`Delete ${e}? It no longer exists in the application.${o}`,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 s},Pe=async(e,t)=>{let o=y.dirname(e);const s=y.resolve(t);for(;y.resolve(o)!==s;)try{if((await f.readdir(o)).length>0)return;await f.rmdir(o),o=y.dirname(o)}catch{return}},Ne=(e,t)=>y.resolve(e)===y.resolve(t)?"Application is successfully pulled.":`Application is successfully pulled into ${y.relative(t,e)}.`,Ae=class{async execute(e={}){o("Pull flow started");const t=await h();if(!t)return;const r=process.cwd();let a;if(e.folder)a=e.folder.trim()||".",o(`Folder argument provided: ${a}`);else{o("No folder argument, prompting user");const{folder:e}=await k.prompt([{type:"input",name:"folder",message:"Which folder to pull the application to?",default:"."}]);a=e.trim()||"."}const c=y.resolve(r,a);o(`Target folder resolved: ${c}`);try{const e=await f.lstat(c).catch(()=>null);e&&!e.isDirectory()&&(console.error(m.red(`Cannot pull into ${c}: path exists and is not a directory.`)),process.exit(1)),await f.ensureDir(c),o(`Target folder ensured: ${c}`)}catch(p){s(p);const e=p instanceof Error?p.message:"Unknown error";console.error(m.red(`Cannot create folder ${c}: ${e}`)),process.exit(1)}const l=y.join(S.tmpdir(),`dashnex-pull-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),d=M();d.start("Analyzing local files...");try{const n=await ve(c),a=await $e(c,{includeGenerated:!0});o(`Local manifest has ${Object.keys(a).length} files`),d.text("Pulling application...");const i=await this.download(t.token,a);d.text("Downloading..."),await f.writeFile(l,i.buffer),o(`Zip written to temp file (${i.viaV2?"v2 diff":"legacy full"} pull)`),d.text("Extracting...");const u=new E(l).getEntries().filter(e=>!e.isDirectory);let h=null;const g=u.find(e=>".dashnex/pull.json"===e.entryName);if(g)try{h=JSON.parse(g.getData().toString("utf8"))}catch(p){s(p)}const w=u.filter(e=>".dashnex"!==e.entryName&&!e.entryName.startsWith(".dashnex/"));o(`Zip has ${w.length} file entries${h?`, meta commit ${h.commit}`:", no meta"}`);const $=e.yes||"1"===process.env.DASHNEX_CI;let v=$?"all":"prompt",k=!1,x=0,b=0,S=0,D=0,C=0;const T=async(e,t,o)=>{try{return await f.ensureDir(y.dirname(e)),await f.writeFile(e,t),o&&await f.chmod(e,o),!0}catch(p){return s(p),!1}};for(const e of w){const t=e.getData(),s=y.join(c,e.entryName),n=y.relative(c,s)||e.entryName,r=(e.header.attr??0)>>16&4095,a=await Ee(s,t);if(o(`Entry ${e.entryName}: ${a.kind}${a.reason?` (${a.reason})`:""}`),"identical"===a.kind){D+=1;continue}if("new"===a.kind){await T(s,t,r)?x+=1:C+=1;continue}let i=!1;if("all"===v)i=!0;else if("none"===v)i=!1;else{d.stop(),await De(s,n,t),k||(console.log(m.dim("Y = yes (default), n = skip, a = overwrite all, s = skip all, h = help")),k=!0);const r=await Ce(n);o(`Entry ${e.entryName}: user chose ${r}`),"yes"===r?i=!0:"no"===r?i=!1:"all"===r?(v="all",i=!0):(v="none",i=!1),d.start("Extracting...")}i?await T(s,t,r)?b+=1:C+=1:S+=1}d.stop();let P=0,N=0;if(h&&h.deleted.length>0){const e=await this.applyDeletions(c,h.deleted,n,$);P=e.deleted,N=e.kept}h&&(D+=Math.max(0,Object.keys(h.manifest).length-w.length)),o(`Pull summary: ${x} new, ${b} overwritten, ${S} skipped, ${P} deleted, ${D} unchanged, ${C} failed`);const A=[`${x} new`,`${b} overwritten`,`${S} skipped`,`${D} unchanged`];if((P>0||N>0)&&A.splice(3,0,`${P} deleted`),C>0&&A.push(`${C} failed`),console.log(m.cyan(`Pulled: ${A.join(", ")}`)),h){const e=await $e(c,{includeGenerated:!0});await ke(c,h.commit,e)}y.resolve(c)!==y.resolve(r)?(console.log(m.green(Ne(c,r))),process.chdir(c),o(`Changed working directory to ${c}`)):console.log(m.green(Ne(c,r))),C>0&&(console.error(m.red(`${C} file(s) failed to write. See DEBUG output for details.`)),process.exit(1)),$?o("Non-interactive mode (--yes or --ci), skipping post-pull child commands"):await be(c,r)}catch(p){if(d.stop(),s(p),p instanceof Error&&p.message.startsWith("EXIT:"))throw p;if(n(p))return void console.log(m.yellow(i));console.error(m.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}finally{await f.remove(l).catch(()=>{}),o("Temp zip removed")}}async download(e,t){const s=`${u()}/business/v1/cli/v2/pull`;o(`POST ${s}`);const n=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:t})});if(o(`v2 pull response: ${n.status}`),n.ok)return{buffer:Buffer.from(await n.arrayBuffer()),viaV2:!0};const r=await n.json().catch(()=>({}));var a,i;a=n.status,i=r,404===a&&"string"==typeof i.message&&i.message.startsWith("Cannot ")||this.failFromResponse(n.status,r),o("v2 pull endpoint unavailable, falling back to legacy pull");const c=`${u()}/business/v1/cli/pull`;o(`GET ${c}`);const l=await fetch(c,{headers:{Authorization:`Bearer ${e}`}});if(o(`Legacy pull response: ${l.status}`),!l.ok){const e=await l.json().catch(()=>({}));this.failFromResponse(l.status,e)}return{buffer:Buffer.from(await l.arrayBuffer()),viaV2:!1}}failFromResponse(e,t){let o="Failed to pull application.";if(401===e||403===e)o="Please run 'dashnex login' to authenticate.";else if(404===e)o="Business has no application. Run 'dashnex app create' to create one.";else{const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);e&&(o=e)}console.error(m.red(o)),process.exit(1)}async applyDeletions(e,t,n,r){let a=0,i=0;if(!n){const e=t.slice(0,20);console.log(m.yellow("These local files do not exist in the application (kept — no sync state yet):"));for(const t of e)console.log(m.yellow(` ${t}`));return t.length>e.length&&console.log(m.yellow(` … and ${t.length-e.length} more`)),{deleted:a,kept:t.length}}let c=r?"all":"prompt";for(const d of t){if(!(d in n.manifest)){o(`Deletion candidate ${d} was never synced, keeping`);continue}const t=y.join(e,d),r=await f.readFile(t).catch(()=>null);if(null===r)continue;const p=me(r)!==n.manifest[d];let u=!1;if("all"===c)u=!0;else if("none"===c)u=!1;else{const e=await Te(d,p);o(`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 f.remove(t),await Pe(t,e),a+=1}catch(l){s(l),i+=1}else i+=1}return{deleted:a,kept:i}}},je=async e=>{const t=`${u()}/business/v1/agreements/payment-processing/status`;o(`GET ${t}`);const s=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});if(o(`Payment agreement response: ${s.status}`),!s.ok)return!0;if((await s.json().catch(()=>({}))).hasAccepted)return!0;const n=`${await(async()=>"qa"===process.env.APPLICATION_ENV?"https://business.qa.dashnex.com":"https://business.dashnex.com")()}/money/agreement/`;return console.error(m.red(`You need to accept Master Payment Processing Agreement first by visiting this link: ${n}`)),!1},Ie=async(e,t={})=>{const n=t.ciMode??!1;return!!(await je(e))&&!!(await(async(e,t)=>{const n=`${u()}/business/v1/tos/latest`;o(`GET ${n}`);const r=await fetch(n,{headers:{Authorization:`Bearer ${e}`}});if(o(`TOS latest response: ${r.status}`),r.ok)return!0;if(404!==r.status)return!0;const a=`${u()}/business/v1/tos/current`;o(`GET ${a}`);const i=await fetch(a,{headers:{Authorization:`Bearer ${e}`}});if(o(`TOS current response: ${i.status}`),!i.ok)return o("Could not fetch current TOS, skipping check"),!0;const c=await i.json().catch(()=>({})),l=c.version??"unknown";if(c.text&&(console.log(m.dim("─".repeat(60))),console.log(m.bold(`Terms of Service ${l}`)),console.log(m.dim("─".repeat(60))),console.log(c.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(m.dim("─".repeat(60)))),t)return console.log(m.yellow(`By proceeding you accept the Terms of Service ${l}.`)),!0;const{accept:d}=await k.prompt([{type:"confirm",name:"accept",message:`By creating an application you accept the Terms of Service ${l}. Continue?`,default:!0}]);if(!d)return console.log(m.yellow("Cancelled.")),!1;try{const t=`${u()}/business/v1/tos/${c.id}/accept`;o(`POST ${t}`),await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch(p){s(p)}return!0})(e,n))},Re=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,Fe=e=>new Promise(t=>setTimeout(t,e)),Oe=e=>e.appFullCustomDomain?e.appFullCustomDomain:e.subdomain?"qa"===(process.env.APPLICATION_ENV??"")?`https://${e.subdomain}.dashnex.dev`:`https://${e.subdomain}.dashnexcloud.com`:null,Be=3e5,ze=99,Le=e=>new Promise(t=>setTimeout(t,e)),_e=async(e,t,n,r)=>{const a=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"text/event-stream"}});if(o(`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(),o=JSON.parse(e);"string"==typeof o.error?t=o.error:"string"==typeof o.message&&(t=o.message)}catch{}throw console.error(m.red(t)),new Error(`HTTP ${e}: ${t}`)}if(!a.body)throw new Error("Response body is null");o("SSE connection established successfully"),r?.();const i=a.body.getReader();try{for await(const e of async function*(e){const t=new TextDecoder("utf-8");let o="";for(;;){const{value:s,done:n}=await e.read();if(n)break;o+=t.decode(s,{stream:!0});const r=o.split("\n");o=r.pop()||"";let a="";for(const e of r)e.startsWith("data: ")?a=e.slice(6):""===e&&a&&(yield{data:a},a="")}if(o.startsWith("data: ")){const e=o.slice(6);e&&(yield{data:e})}}(i))try{if(!e.data){o("Received empty SSE event");continue}const t=JSON.parse(e.data);o(`SSE message received: ${JSON.stringify(t)}`),n(t)}catch(c){s(c),o(`Failed to parse SSE event data: ${e.data}`)}}finally{i.releaseLock()}},Ue=class{async execute(e={}){o("Deploy flow started");const t=await h();if(!t)return;if(!1!==e.check?(o("Running pre-deploy checks"),await(new ae).run(!1)||(console.error(m.red("Deploy aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):o("Skipping pre-deploy checks (--no-check)"),!(await Ie(t.token,{ciMode:!0})))return;const r=`${a()}/business/v1/applications/deploy`;o(`GET ${r} (SSE)`);let c=0,l="",d=!1,p=0,u=!1;const g=M();let f=0,y=0,w=null;const $=(e,t)=>{const o=Math.round(e);g.text(`[${o}%] ${t}`)},v=()=>{k();const e=c,t=Date.now(),o=Be*((ze-e)/ze);w=setInterval(()=>{const s=Date.now()-t;let n;if(y>t){const e=Date.now()-y,t=ze-f,o=3030.3030303030305*t;n=Math.min(f+e/o*t,ze)}else n=Math.min(e+s/o*(ze-e),ze);n>c&&(c=n,$(c,l))},200)},k=()=>{w&&(clearInterval(w),w=null)};let x=!1;const b=e=>{if(u=!0,"string"==typeof e.error)return k(),g.stop(),console.error(m.red(e.error)),d=!0,void(x=!0);"string"==typeof e.message&&(l=e.message),"number"==typeof e.progress&&(f=e.progress,y=Date.now(),e.progress>c&&(c=e.progress)),"string"!=typeof e.message&&"number"!=typeof e.progress||(c>=100?(k(),g.stop(),d=!0):$(c,l))};for(;p<=5;)try{return u?$(c,l):g.start("Connecting..."),v(),await _e(r,t.token,b,()=>{u||(g.text(`[${Math.round(c)}%] Deployment in progress...`),l="Deployment in progress...")}),k(),g.stop(),o("SSE connection closed"),x&&process.exit(1),void(d&&await this.showDeployedUrl(t.token))}catch(S){if(k(),s(S),o(`SSE connection error: ${S}`),d)return g.stop(),void(x&&process.exit(1));if(n(S))return g.stop(),void console.log(m.yellow(i));S instanceof Error&&S.message.startsWith("HTTP")&&(g.stop(),console.error(m.red("Could not complete deployment. Check your connection and try again.")),process.exit(1)),p++,p>5&&(g.stop(),console.error(m.red("Deployment failed. Maximum reconnection attempts exceeded.")),process.exit(1));const e=Math.min(1e3*Math.pow(2,p-1),3e4);o(`Connection error. Reconnecting in ${e/1e3}s... (attempt ${p}/5)`),await Le(e)}}async showDeployedUrl(e){try{const t=`${u()}/business/v1/applications`;o(`GET ${t} (for deployed URL)`);const s=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});if(!s.ok)return;const n=await s.json().catch(()=>({})),r=Oe({subdomain:n.subdomain,appFullCustomDomain:n.appFullCustomDomain});r&&console.log(`Application is deployed to ${m.cyan(r)}`)}catch(t){s(t)}}},Me=104857600,We=class extends Error{},Je=class extends Error{},Ge=class extends Error{},Xe="/business/v1/cli/tail-token";async function qe(e,t={}){const o=`${u()}${Xe}${t.debug?"?debug=1":""}`;try{await fetch(o,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})}catch{}}var Ye=["log","info","warn","error","debug"],He={error:4,warn:3,log:2,info:2,debug:1};function Ve(e){return"string"==typeof e&&Ye.includes(e)}function Ke(e){return e.map(e=>"string"==typeof e?e:function(e){try{return JSON.stringify(e)}catch{return String(e)}}(e)).join(" ")}function Ze(e){return e<10?`0${e}`:String(e)}function Qe(e){const t=new Date(e);return`${Ze(t.getHours())}:${Ze(t.getMinutes())}:${Ze(t.getSeconds())}.${o=t.getMilliseconds(),o<10?`00${o}`:o<100?`0${o}`:String(o)}`;var o}function et(e,t){if("string"==typeof e)return e;if("object"==typeof(o=e)&&null!==o&&"string"==typeof o.name&&"string"==typeof o.message&&Object.keys(o).every(e=>"name"===e||"message"===e||"stack"===e)){const t=`${e.name}: ${e.message}`;return e.stack?`${t}\n${e.stack}`:t}var o;return N(e,{colors:t,depth:2,breakLength:120})}var tt={error:e=>m.red(e),warn:e=>m.yellow(e),debug:e=>m.dim(e),log:e=>e,info:e=>e};function ot(e,t){const o=t.color?m.dim(Qe(e.ts)):Qe(e.ts),s=e.level.toUpperCase().padEnd(5),n=[o,t.color?tt[e.level](s):s];n.push(e.args.map(e=>et(e,t.color)).join(" "));let r=n.join(" ");if(e.truncated){const e=" …(truncated)";r+=t.color?m.dim(e):e}return r}function st(e,t,o){let s;try{s=JSON.parse(e)}catch{return{kind:"malformed",raw:e}}if("object"!=typeof s||null===s||!Ve(s.level))return{kind:"malformed",raw:e};const n=s;return Array.isArray(n.args)||(n.args=void 0===n.args?[]:[n.args]),r=n.level,a=t.minLevel,He[r]>=He[a]&&function(e,t){return!t||t.test(Ke(e.args))}(n,t.filter)?{kind:"line",line:ot(n,o)}:{kind:"filtered"};var r,a}var nt=new Set([4401,4403]);var rt=[{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"}],at={label:".wrangler",segments:[".wrangler"],description:"local database"},it=async e=>{await A(e,{recursive:!0,force:!0,maxRetries:5,retryDelay:100})},ct={name:"app",description:"Manage DashNex applications (should be executed in application folder)",handler:{execute:async()=>{}},options:[],subcommands:[{name:"create",description:"Create a new DashNex application",handler:new class{async pollApplicationCreated(e,t,n=5e3,r=6e4){const a=Date.now();let i=0;for(;Date.now()-a<r;){i++,o(`Polling application status (attempt ${i})...`);try{const s=await fetch(e,{headers:{Authorization:`Bearer ${t}`}});if(o(`Poll response: ${s.status}`),200===s.status){const e=await s.json();if(o(`Poll response body status: ${e.status}`),"creating"!==e.status)return o(`Application status is "${e.status}", creation complete`),{ready:!0,status:e.status};o('Application status is still "creating", continuing to poll...')}}catch(c){s(c),o(`Poll attempt ${i} failed with network error`)}await Fe(n)}return{ready:!1}}async execute(e={}){o("Create flow started");const t=await h();if(!t)return;o("Auth valid, checking if business already has application");const r=M(),a=`${u()}/business/v1/applications`;o(`GET ${a}`),r.start("Checking application status...");try{const e=await fetch(a,{headers:{Authorization:`Bearer ${t.token}`}});r.stop(),o(`Applications response: ${e.status}`),o(`Applications response body: ${await e.text()}`),404!==e.status&&(console.error(m.red("Business already has an application. Run 'dashnex app pull' to pull the existing one.")),process.exit(1))}catch(w){if(r.stop(),s(w),w instanceof Error&&w.message.startsWith("EXIT:"))throw w;if(n(w))return void console.log(m.yellow(i));console.error(m.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}o("No existing application, checking agreements");const c=void 0!==e.subdomain;if(!(await Ie(t.token,{ciMode:c})))return;let l;o("Agreements checked, proceeding to subdomain prompt");const d=e=>`${u()}/business/v1/applications/check-subdomain?subdomain=${encodeURIComponent(e)}`;let p=e.subdomain?.trim();for(;;){if(p)l=p,p=void 0,o(`Subdomain provided via flag: ${l}`);else{if(c)return console.error(m.red("Subdomain is not available.")),void process.exit(1);{const{sub:e}=await k.prompt([{type:"input",name:"sub",message:"Pick your subdomain:",validate:e=>!!e.trim()||"Subdomain is required"}]);l=e.trim()}}o(`Checking subdomain: ${l}`);const e=d(l);o(`GET ${e}`),r.start("Checking subdomain...");try{const s=await fetch(e,{headers:{Authorization:`Bearer ${t.token}`}});r.stop(),o(`Check subdomain response: ${s.status}`);const n=await s.text();if(o(`Check subdomain response body: ${n}`),!s.ok){const e=s.headers.get("content-type")??"";let t="Failed to check subdomain availability.";if(401!==s.status&&403!==s.status||(t="Please run 'dashnex login' to authenticate.",console.error(m.red(t)),process.exit(1)),e.includes("application/json")){const e=JSON.parse(n);o(`Check subdomain error body: ${JSON.stringify(e)}`);const s=Re(e);s&&(t=s)}console.error(m.red(t));continue}const a=JSON.parse(n);if(o(`Check subdomain parsed body: ${JSON.stringify(a)}`),a.available){o(`Subdomain ${l} is available`);break}console.error(m.red("Subdomain is not available. Please choose a different one."))}catch(w){if(r.stop(),s(w),w instanceof Error&&w.message.startsWith("EXIT:"))throw w;if(n(w))return void console.log(m.yellow(i));console.error(m.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}const g=`${u()}/business/v1/cli/create`;o(`POST ${g}`);const f={subdomain:l};e.template&&(f.template=e.template,o(`Template: ${e.template}`));const y=JSON.stringify(f);o(`Create request body: ${y}`),r.start("Creating application...");try{const a=await fetch(g,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:y});r.stop(),o(`Create response: ${a.status}`);const l=await a.text();if(o(`Create response body: ${l}`),503===a.status){o("Create returned 503, polling for application creation..."),r.start("Waiting for application to be ready...");const e=`${u()}/business/v1/applications`,s=await this.pollApplicationCreated(e,t.token);r.stop(),s.ready||(console.error(m.red("Application creation is taking longer than expected. Try again later or run 'dashnex app pull' to check.")),process.exit(1)),"failed"===s.status&&(console.error(m.red("Application creation failed. Please try again.")),process.exit(1)),o("Application found after polling")}else if(!a.ok){const e=a.headers.get("content-type")??"";let t="Failed to create application.";if(401===a.status||403===a.status)t="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=JSON.parse(l);o(`Create error body parsed: ${JSON.stringify(e)}`);const s=Re(e);s&&(t=s)}console.error(m.red(t)),process.exit(1)}let d;if(o("Application created successfully"),!0===e.pull?(d=!0,o("--pull flag set, pulling without prompting")):!1===e.pull?(d=!1,o("--no-pull flag set, skipping pull")):c?(d=!1,o("CI mode (--subdomain), skipping pull")):(d=(await k.prompt([{type:"confirm",name:"pull",message:"Pull the application locally?",default:!0}])).pull,o(`User chose to pull: ${d}`)),d){o("Running pull flow");try{await(new Ae).execute()}catch(w){if(s(w),w instanceof Error&&w.message.startsWith("EXIT:"))throw w;if(n(w))return void console.log(m.yellow(i));console.error(m.red("Failed to pull application."))}}else console.log(m.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(w){if(r.stop(),s(w),w instanceof Error&&w.message.startsWith("EXIT:"))throw w;if(n(w))return void console.log(m.yellow(i));console.error(m.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[{flags:"-t, --template <template>",description:"Template (name@branch-or-tag)",defaultValue:"webapp-base@live"},{flags:"--subdomain <subdomain>",description:"Subdomain (CI mode, skip prompts)"},{flags:"--pull",description:"Auto-pull after creation (skip prompt)"},{flags:"--no-pull",description:"Skip the pull prompt and show the success message"}]},{name:"pull",description:"Pull existing application to specified folder",handler:new Ae,arguments:[{name:"folder",description:"Target folder (defaults to interactive prompt)"}],options:[{flags:"-y, --yes",description:"Skip prompts and child commands (CI mode)"}]},{name:"push",description:"Push local application to DashNex",handler:new class{async execute(e={}){o("Push flow started"),await f.pathExists(y.join(process.cwd(),"dashnex.json"))||(console.error(m.red("Not a DashNex application folder (dashnex.json not found).")),console.error(m.red("Run this command from your application root.")),process.exit(1)),!1!==e.check?(o("Running pre-push checks"),await(new ae).run(!1)||(console.error(m.red("Push aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):o("Skipping pre-push checks (--no-check)");const t=await h();if(!t)return;const r=process.cwd(),a=M();try{a.start("Analyzing local files...");const s=await ve(r),n=await $e(r);o(`Local manifest has ${Object.keys(n).length} files`),a.text("Comparing with remote...");const i=await this.requestPlan(t.token,n,s?.commit);a.stop(),"legacy"===i?(o("v2 push endpoints unavailable, falling back to legacy zip push"),await this.pushLegacy(t.token,r,a)):await this.pushDiff(t.token,r,n,i,e,a),await this.promptAndDeploy(e)}catch(c){if(a.stop(),s(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(n(c))return void console.log(m.yellow(i));console.error(m.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}async requestPlan(e,t,s){const n=`${u()}/business/v1/cli/v2/push/plan`;o(`POST ${n}`);const r=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:t,lastSyncCommit:s})});if(o(`Plan response: ${r.status}`),r.ok)return await r.json();const a=await r.json().catch(()=>({}));if(((e,t)=>404===e&&"string"==typeof t.message&&t.message.startsWith("Cannot "))(r.status,a))return"legacy";this.failFromResponse(r.status,a,"Failed to push application.")}async pushDiff(e,t,s,n,r,a){let i=n;if(i.remoteChanged.length>0&&!r.force){console.error(m.red("Remote application has changes you don't have locally:"));for(const e of i.remoteChanged.slice(0,20))console.error(m.red(` ${e}`));i.remoteChanged.length>20&&console.error(m.red(` … and ${i.remoteChanged.length-20} more`)),console.error(m.red("Run 'dashnex app pull' first, or push anyway with --force.")),process.exit(1)}const c=i.upload.filter(e=>e in s);let l=i.delete;if(0!==c.length||0!==l.length){if(l.length>0){const e=await ve(t),s=r.yes||"1"===process.env.DASHNEX_CI;console.log(m.yellow(`${l.length} file(s) will be deleted from the application repository:`));for(const t of l.slice(0,20))console.log(m.yellow(` ${t}`));if(l.length>20&&console.log(m.yellow(` … and ${l.length-20} more`)),!s){const{confirmDelete:t}=await k.prompt([{type:"confirm",name:"confirmDelete",message:"Delete these files from the remote repository?",default:null!==e}]);t||(o("User declined remote deletions, pushing without them"),l=[])}}if(0!==c.length||0!==l.length)for(let n=1;;n+=1){a.start(1===n?"Uploading changes...":"Remote changed, retrying...");const d=await this.applyPush(e,t,c,l,i.baseCommit);if(a.stop(),"ok"===d.status){await ke(t,d.commit,s);const e=[`${c.length} file(s) updated`];return l.length>0&&e.push(`${l.length} deleted`),console.log(m.cyan(`Pushed: ${e.join(", ")}`)),void console.log(m.green("Application pushed successfully."))}n>=2&&(console.error(m.red("Remote repository keeps changing, please retry the push.")),process.exit(1)),o("Push apply conflicted, re-planning");const p=await ve(t),u=await this.requestPlan(e,s,p?.commit);"legacy"===u&&(console.error(m.red("Failed to push application.")),process.exit(1)),u.remoteChanged.length>0&&!r.force&&(console.error(m.red("Remote application changed during the push. Run 'dashnex app pull' first, or push with --force.")),process.exit(1)),i=u}else console.log(m.green("Everything up to date."))}else console.log(m.green("Everything up to date."))}async applyPush(e,t,s,n,r){const a=new E;for(const o of s){const e=y.join(t,...o.split("/")),s=y.posix.dirname(o);a.addLocalFile(e,"."===s?"":s,y.posix.basename(o))}const i=y.join(S.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{a.writeZip(i),o(`Diff zip written to ${i} (${s.length} files, ${n.length} deletions)`),await this.ensureZipWithinLimit(i);const t=`${u()}/business/v1/cli/v2/push/apply`;o(`POST ${t}`);const c=await f.readFile(i),l=new FormData;l.append("file",new Blob([c],{type:"application/zip"}),"diff.zip"),l.append("baseCommit",r),l.append("deletions",JSON.stringify(n));const d=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:l});if(o(`Apply response: ${d.status}`),409===d.status)return{status:"conflict"};if(!d.ok){const e=await d.json().catch(()=>({}));this.failFromResponse(d.status,e,"Failed to push application.")}return{status:"ok",commit:(await d.json().catch(()=>({}))).commit??""}}finally{await f.remove(i).catch(()=>{})}}async pushLegacy(e,t,s){const n=await $e(t),r=Object.keys(n);o(`Legacy push including ${r.length} files`);const a=new E;for(const o of r){const e=y.join(t,...o.split("/")),s=y.posix.dirname(o);a.addLocalFile(e,"."===s?"":s,y.posix.basename(o))}const i=y.join(S.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{s.start("Packaging application..."),a.writeZip(i),o(`Zip written to ${i}`),await this.ensureZipWithinLimit(i);const t=`${u()}/business/v1/cli/push`;o(`POST ${t}`);const n=await f.readFile(i),r=new FormData;r.append("file",new Blob([n],{type:"application/zip"}),"archive.zip"),s.text("Uploading...");const c=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:r});if(s.stop(),o(`Response: ${c.status}`),!c.ok){const e=await c.json().catch(()=>({}));this.failFromResponse(c.status,e,"Failed to push application.")}console.log(m.green("Application pushed successfully."))}finally{await f.remove(i).catch(()=>{}),o("Temp zip removed")}}async ensureZipWithinLimit(e){const{size:t}=await f.stat(e);if(t>Me){const e=e=>(e/1048576).toFixed(1);console.error(m.red(`Push package is ${e(t)} MB — the maximum is ${e(Me)} MB.`)),console.error(m.red("Remove or .gitignore large files and try again.")),process.exit(1)}}failFromResponse(e,t,o){let s=o;if(401===e||403===e)s="Please run 'dashnex login' to authenticate.";else{const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);e&&(s=e)}console.error(m.red(s)),process.exit(1)}async promptAndDeploy(e){let t;void 0!==e.deploy?(t=e.deploy,o(`Deploy decided via flag: ${t}`)):"1"===process.env.DASHNEX_CI?(t=!1,o("CI mode: skipping deploy prompt (use --deploy to deploy)")):(t=(await k.prompt([{type:"confirm",name:"deploy",message:"Deploy the application?",default:!0}])).deploy,o(`User chose to deploy: ${t}`)),t&&(o("Running deploy flow"),await(new Ue).execute())}},options:[{flags:"--deploy",description:"Auto-deploy after push (skip prompt)"},{flags:"--no-deploy",description:"Skip deploy prompt"},{flags:"--no-check",description:"Skip pre-push checks"},{flags:"-f, --force",description:"Push even when the remote has changes you don't have locally"},{flags:"-y, --yes",description:"Skip prompts (CI mode)"}]},{name:"delete",description:"Delete application from DashNex",handler:new class{async execute(e={}){if(o("Delete flow started"),!e.yes){const{confirm:e}=await k.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 o("User cancelled deletion"),void console.log(m.yellow("Deletion cancelled."))}const t=await h();if(!t)return;const r=`${u()}/business/v1/applications`;o(`DELETE ${r}`);const a=M();a.start("Deleting application...");try{const e=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}});if(a.stop(),o(`Response: ${e.status}`),!e.ok){const t=e.headers.get("content-type")??"";let o="Failed to delete application.";if(401===e.status||403===e.status)o="Please run 'dashnex login' to authenticate.";else if(t.includes("application/json")){const t=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(await e.json().catch(()=>({})));t&&(o=t)}console.error(m.red(o)),process.exit(1)}const s=await e.json().catch(()=>({})),n="string"==typeof s.message?s.message:"Application deleted successfully.";o("Application deleted successfully"),console.log(m.green(n))}catch(c){if(a.stop(),s(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(n(c))return void console.log(m.yellow(i));console.error(m.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[{flags:"-y, --yes",description:"Skip confirmation prompt"}]},{name:"deploy",description:"Deploy application to DashNex",handler:new Ue,options:[{flags:"--no-check",description:"Skip pre-deploy checks"}]},{name:"status",description:"Show current application status",handler:new class{async execute(){o("Status flow started");const e=await h();if(!e)return;const t=`${u()}/business/v1/applications`;o(`GET ${t}`);const r=M();r.start("Fetching application status...");try{const s=await fetch(t,{headers:{Authorization:`Bearer ${e.token}`}});if(r.stop(),o(`Response: ${s.status}`),404===s.status)return void console.log(m.yellow("Application not created"));if(!s.ok){const e=s.headers.get("content-type")??"";let t="Failed to fetch application status.";if(401===s.status||403===s.status)t="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=await s.json().catch(()=>({}));"string"==typeof e.error?t=e.error:"string"==typeof e.message&&(t=e.message)}console.error(m.red(t)),process.exit(1)}const n=await s.json().catch(()=>({}));o(`Application body: ${JSON.stringify(n)}`);const a=n.status??"unknown";console.log(`Status: ${m.cyan(a)}`);const i=Oe(n);i&&console.log(`URL: ${m.cyan(i)}`)}catch(a){if(r.stop(),s(a),a instanceof Error&&a.message.startsWith("EXIT:"))throw a;if(n(a))return void console.log(m.yellow(i));console.error(m.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]},{name:"clear",description:"Delete local dependencies, caches and build output",handler:new class{async execute(e={}){o("Clear flow started");const t=process.cwd();f.pathExistsSync(y.join(t,"dashnex.json"))||(console.error(m.red("Run this command in a DashNex Web application folder.")),process.exit(1));const r=e.yes||"1"===process.env.DASHNEX_CI;o(`Non-interactive: ${r}`);try{const e=await this.collectTargets(t),n=y.join(t,...at.segments),i=await f.pathExists(n),c=i&&!r;if(i&&r&&e.push(at),0===e.length&&!c)return void console.log(m.yellow("Nothing to clear."));const l=[];if(e.length>0){console.log("The following will be deleted:");for(const t of e)console.log(` ${m.cyan(t.label)} ${m.dim(`(${t.description})`)}`);if(!r){const{confirm:e}=await k.prompt([{type:"confirm",name:"confirm",message:"Delete these files?",default:!1}]);if(!e)return o("User cancelled clear"),void console.log(m.yellow("Cancelled."))}for(const n of e){const e=y.join(t,...n.segments);o(`Removing ${e}`);try{await it(e),console.log(m.green(`Removed ${n.label}`))}catch(a){s(a),l.push(n.label)}}}if(c){const{confirm:e}=await k.prompt([{type:"confirm",name:"confirm",message:"Delete the local database as well?",default:!1}]);if(e){o(`Removing ${n}`);try{await it(n),console.log(m.green(`Removed ${at.label}`))}catch(a){s(a),l.push(at.label)}}}if(l.length>0){for(const e of l)console.error(m.red(`Could not delete ${e} — it may be in use. Stop 'dashnex dev' and try again.`));process.exit(1)}console.log(m.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(s(a),n(a))return void console.log(m.yellow(i));throw a}}async collectTargets(e){const t=[];for(const o of rt)await f.pathExists(y.join(e,...o.segments))&&t.push(o);return t.filter(o=>!t.some(t=>t!==o&&((e,t)=>{const o=y.relative(t,e);return""!==o&&!o.startsWith("..")&&!y.isAbsolute(o)})(y.join(e,...o.segments),y.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(e={}){const t=e.level??"log";Ve(t)||(console.error(m.red(`Invalid --level '${e.level}'. Use one of: log, info, warn, error, debug.`)),process.exit(1));let n=null;if(e.filter)try{n=new RegExp(e.filter)}catch{console.error(m.red(`Invalid --filter regular expression: ${e.filter}`)),process.exit(1)}const r=await h();if(!r)return;const a=!!e.debug;let i;try{i=await async function(e,t={}){const s=`${u()}${Xe}`;o(`POST ${s}${t.debug?" (debug)":""}`);const n=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({debug:!!t.debug})});if(o(`Response: ${n.status}`),401===n.status||403===n.status)throw new We("Not authorised to tail this application.");if(404===n.status)throw new Je("Business has no application, or the tail endpoint is unavailable.");if(!n.ok)throw new Ge(`Failed to start tail (status ${n.status}).`);const r=await n.json().catch(()=>({}));if(!r.token||!r.workerUrl)throw new Ge("Malformed tail-token response from the platform.");return{token:r.token,workerUrl:r.workerUrl,expiresAt:"number"==typeof r.expiresAt?r.expiresAt:0}}(r.token,{debug:a})}catch(k){s(k),k instanceof We&&(console.error(m.red(k.message)),process.exit(1)),k instanceof Je&&(console.error(m.red(k.message)),process.exit(2)),console.error(m.red(k instanceof Error?k.message:"Could not start tail. Check your connection.")),process.exit(3)}const c={color:!!process.stdout.isTTY},l={minLevel:t,filter:n},d=(p=i.workerUrl,`${/^(localhost|127\.0\.0\.1)/.test(p)?"ws":"wss"}://${p}/api/realtime/tail`);var p;const g=`dashnex.tail.token.${i.token}`;console.log(m.dim(`Tailing ${i.workerUrl} — Ctrl+C to stop.`)),a&&console.log(m.dim("Debug logging enabled on the worker (DEBUG=1); may take a minute to take effect."));let f=!1,y=Date.now();const w=setInterval(()=>{f||Date.now()-y>=3e4&&(console.log(m.dim("(no logs in 30s)")),y=Date.now())},5e3),$=new T(d,g,{WebSocket:P,connectionTimeout:1e4,maxReconnectionDelay:16e3}),v=async e=>{if(!f){f=!0,clearInterval(w);try{$.close()}catch{}await Promise.race([qe(r.token,{debug:a}),new Promise(e=>setTimeout(e,3e3))]),process.exit(e)}};process.on("SIGINT",()=>{console.log(),v(0)}),$.binaryType="arraybuffer",$.addEventListener("message",e=>{y=Date.now();const t=st("string"==typeof e.data?e.data:"",l,c);"line"===t.kind?console.log(t.line):"malformed"===t.kind&&console.error(m.dim(`[malformed frame] ${t.raw}`))}),$.addEventListener("close",e=>{if(!f)return nt.has(e.code)?(console.error(m.red("Tail token was rejected (auth). Exiting.")),void v(1)):void o(`socket closed (code ${e.code}); reconnecting…`)}),$.addEventListener("error",e=>{o(`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"}]}]},lt={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(){o("Secrets list flow started");const e=await h();if(!e)return;const t=`${u()}/business/v1/cli/secrets`;o(`GET ${t}`);const r=M();r.start("Fetching secrets...");try{const s=await fetch(t,{headers:{Authorization:`Bearer ${e.token}`}});if(r.stop(),o(`Response: ${s.status}`),!s.ok){let e="Failed to fetch secrets.";401===s.status||403===s.status?e="Please run 'dashnex login' to authenticate.":404===s.status?e="Business has no application.":502===s.status&&(e="Error fetching secrets. Make sure your application is deployed."),console.error(m.red(e)),process.exit(1)}const n=(await s.json()).secrets??[];if(0===n.length)return void console.log(m.yellow("No secrets set."));console.log(m.bold(`\nSecrets (${n.length}):\n`)),n.forEach(({name:e})=>{console.log(` ${m.cyan(e)}`)}),console.log("")}catch(a){if(r.stop(),s(a),a instanceof Error&&a.message.startsWith("EXIT:"))throw a;if(n(a))return void console.log(m.yellow(i));console.error(m.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]},{name:"set",description:"Create or update a secret (prompts for missing KEY/VALUE)",handler:new class{async execute(e={}){o("Secrets set flow started");let{name:t,value:r}=e;const a="1"===process.env.DASHNEX_CI;t||(a&&(console.error(m.red("--name is required in CI mode (--ci).")),process.exit(1)),t=(await k.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim()),r||(a&&(console.error(m.red("--value is required in CI mode (--ci).")),process.exit(1)),r=(await k.prompt([{type:"password",name:"value",message:`Enter value for ${t}:`,mask:"*",validate:e=>""!==e||"Value is required"}])).value);const c=await h();if(!c)return;const l=`${u()}/business/v1/cli/secrets`;o(`PUT ${l}`);const d=M();d.start(`Setting secret '${t}'...`);try{const e=await fetch(l,{method:"PUT",headers:{Authorization:`Bearer ${c.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:t,value:r})});if(d.stop(),o(`Response: ${e.status}`),!e.ok){let t="Failed to set secret.";401===e.status||403===e.status?t="Please run 'dashnex login' to authenticate.":400===e.status?t="Missing or empty name / value.":404===e.status?t="Business has no application.":502===e.status&&(t="Error setting secret. Make sure your application is deployed."),console.error(m.red(t)),process.exit(1)}o(`Secret '${t}' set successfully`),console.log(m.green(`Secret '${t}' set successfully.`))}catch(p){if(d.stop(),s(p),p instanceof Error&&p.message.startsWith("EXIT:"))throw p;if(n(p))return void console.log(m.yellow(i));console.error(m.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},arguments:[{name:"name",description:"Secret name (KEY)"},{name:"value",description:"Secret value"}],options:[{flags:"--name <name>",description:"Secret name (alternative to positional KEY)"},{flags:"--value <value>",description:"Secret value (alternative to positional VALUE)"}]},{name:"delete",description:"Delete a secret (prompts for missing KEY)",handler:new class{async execute(e={}){o("Secrets delete flow started");let{name:t}=e;const r="1"===process.env.DASHNEX_CI;t||(r&&(console.error(m.red("--name is required in CI mode (--ci).")),process.exit(1)),t=(await k.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim());const a=await h();if(!a)return;const c=`${u()}/business/v1/cli/secrets/${encodeURIComponent(t)}`;o(`DELETE ${c}`);const l=M();l.start(`Deleting secret '${t}'...`);try{const e=await fetch(c,{method:"DELETE",headers:{Authorization:`Bearer ${a.token}`}});if(l.stop(),o(`Response: ${e.status}`),!e.ok){let o="Failed to delete secret.";401===e.status||403===e.status?o="Please run 'dashnex login' to authenticate.":404===e.status?o=`Secret '${t}' not found.`:502===e.status&&(o="Error deleting secret. Make sure your application is deployed."),console.error(m.red(o)),process.exit(1)}o(`Secret '${t}' deleted successfully`),console.log(m.green(`Secret '${t}' deleted.`))}catch(d){if(l.stop(),s(d),d instanceof Error&&d.message.startsWith("EXIT:"))throw d;if(n(d))return void console.log(m.yellow(i));console.error(m.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},arguments:[{name:"name",description:"Secret name (KEY)"}],options:[{flags:"--name <name>",description:"Secret name (alternative to positional KEY)"}]}]},dt=[{name:"version",description:"Display the version of the CLI",handler:new class{async execute(e){const t=y.dirname(w(import.meta.url)),o=JSON.parse(v.readFileSync(y.resolve(t,"..","..","package.json"),"utf8"));console.log(o.version)}},options:[]},{name:"login",description:"Log in to your DashNex account",handler:new W,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=r(process.cwd());if(await f.pathExists(e)){const t=await f.readJson(e);delete t.token,delete t.refreshToken,delete t.businessId,await f.writeJson(e,t,{spaces:2})}console.log(m.green("Logged out."))}},options:[]},{name:"whoami",description:"Show current logged-in business and user",handler:new class{async execute(){o("Whoami flow started");const e=await h();if(!e)return;const t=await c()?`${u()}/business/v1/`:`${l()}/users/v1/`;o(`GET ${t}`);const r=M();r.start("Fetching user info...");try{const s=await fetch(t,{headers:{Authorization:`Bearer ${e.token}`}});if(r.stop(),o(`Response: ${s.status}`),!s.ok){const e=s.headers.get("content-type")??"";let t="Failed to fetch user info.";if(401===s.status||403===s.status)t="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e="string"==typeof(a=await s.json().catch(()=>({}))).error?a.error:"string"==typeof a.message?a.message:void 0;e&&(t=e)}console.error(m.red(t)),process.exit(1)}const n=await s.json().catch(()=>({})),i="string"==typeof n.name?n.name:"string"==typeof n.companyName?n.companyName:"Unknown",c=n.memberUser,l=c&&"string"==typeof c.fullName?c.fullName:c&&"string"==typeof c.name?c.name:"Unknown";o(`Whoami: ${i} (${l})`),console.log(m.green(`You are logged in as ${i} (${l})`))}catch(d){if(r.stop(),s(d),d instanceof Error&&d.message.startsWith("EXIT:"))throw d;if(n(d))return void console.log(m.yellow(i));console.error(m.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}var a}},options:[]},{name:"dev",description:"Run the development server (run in DashNex application folder)",handler:new class{async execute(e={}){o("Dev flow started");try{const t=await q(process.cwd(),e);process.exit(t)}catch(t){if(t instanceof Error&&t.message.startsWith("EXIT:"))throw t;s(t),t instanceof Error?console.error(m.red(t.message)):console.error(m.red("Failed to run npm run dev")),process.exit(1)}}},options:[{flags:"--https",description:"Run dev server with HTTPS"}]},{name:"check",description:"Run build-time validations (run in DashNex application folder)",handler:new ae,options:[]},{name:"install",description:"Install dependencies using pnpm (preferred) or npm (run in DashNex application folder)",handler:new class{async execute(){o("Install flow started");const e=y.join(process.cwd(),"dashnex.json");await f.pathExists(e)||(console.error(m.red("Run this command in a DashNex Web application folder.")),process.exit(1));const t=process.cwd(),n=M();n.start("Installing dependencies...");try{const e=await H(t);n.stop(),0!==e&&process.exit(e),console.log(m.green("Dependencies installed.")),process.exit(0)}catch(r){n.stop(),s(r),r instanceof Error?console.error(m.red(r.message)):console.error(m.red("Failed to run install")),process.exit(1)}}},options:[]},ct,lt];export{dt 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-CRgjnfCu.js";var n={name:s.name,version:s.version,description:s.description,...e};export{n as default};
|
|
@@ -1,16 +1,31 @@
|
|
|
1
1
|
import { CliCommand } from '@dashnex/types';
|
|
2
2
|
export interface LoginCommandOptions {
|
|
3
|
-
email?: string;
|
|
4
|
-
password?: string;
|
|
5
|
-
code?: string;
|
|
6
3
|
business?: string;
|
|
4
|
+
browser?: boolean;
|
|
7
5
|
}
|
|
8
6
|
export declare class LoginCommand implements CliCommand {
|
|
9
7
|
execute(options?: LoginCommandOptions): Promise<void>;
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Authorization code flow with PKCE, using the out-of-band redirect: the code
|
|
10
|
+
* is displayed in the browser for the user to paste back here. No local port
|
|
11
|
+
* is opened, so this works the same over SSH as it does on a desktop.
|
|
12
|
+
*/
|
|
13
|
+
private authorize;
|
|
14
|
+
private selectBusiness;
|
|
15
|
+
private pickBusiness;
|
|
16
|
+
private readSavedIdToken;
|
|
17
|
+
private fetchCliSettings;
|
|
18
|
+
/**
|
|
19
|
+
* Keys this command used to write and no longer does. Merging preserves
|
|
20
|
+
* everything by default, so anything we retired has to be dropped explicitly
|
|
21
|
+
* or it lingers in every settings file that ever saw an older CLI.
|
|
22
|
+
*/
|
|
23
|
+
private static readonly OBSOLETE_KEYS;
|
|
24
|
+
/**
|
|
25
|
+
* Merges into settings.json rather than replacing it. The file also holds
|
|
26
|
+
* business CLI settings and anything an app or module put there, so a login
|
|
27
|
+
* must only ever add or update its own keys.
|
|
28
|
+
*/
|
|
29
|
+
private writeConfig;
|
|
15
30
|
private ensureGitignore;
|
|
16
31
|
}
|
package/dist/src/lib/api.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
declare const getApiBase: () => string;
|
|
2
2
|
declare const getBusinessApiBase: () => string;
|
|
3
|
+
declare const getDashnexIdBase: () => string;
|
|
4
|
+
declare const getOAuthClientId: () => string;
|
|
3
5
|
declare const getDeployerBase: () => string;
|
|
4
6
|
declare const apiFetch: (url: string, options?: RequestInit) => Promise<{
|
|
5
7
|
response: Response;
|
|
6
8
|
body: Record<string, unknown>;
|
|
7
9
|
}>;
|
|
8
|
-
export { getApiBase, getBusinessApiBase, getDeployerBase, apiFetch };
|
|
10
|
+
export { getApiBase, getBusinessApiBase, getDashnexIdBase, getOAuthClientId, getDeployerBase, apiFetch, };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Best-effort launch of the user's default browser. Returns false when the
|
|
3
|
+
* platform opener is missing or fails — headless boxes and bare SSH sessions
|
|
4
|
+
* are exactly where the manual-code flow earns its keep, so the caller always
|
|
5
|
+
* prints the URL as well and never treats this as fatal.
|
|
6
|
+
*/
|
|
7
|
+
export declare const openBrowser: (url: string) => Promise<boolean>;
|
|
@@ -7,4 +7,14 @@ export interface EnsureLoggedInOptions {
|
|
|
7
7
|
exitOnFailure?: boolean;
|
|
8
8
|
dashnexPath?: string;
|
|
9
9
|
}
|
|
10
|
+
/**
|
|
11
|
+
* Whether the stored credentials were minted through DashNex ID, i.e. whether a
|
|
12
|
+
* DashNex ID session token is on file. Commands use this to pick the API that
|
|
13
|
+
* issued the business token they are holding.
|
|
14
|
+
*
|
|
15
|
+
* DASHNEX_TOKEN deliberately does not count: it is minted externally by the
|
|
16
|
+
* deployment pipeline and its issuer is not ours to assume, so it keeps the
|
|
17
|
+
* behaviour it has always had.
|
|
18
|
+
*/
|
|
19
|
+
export declare const isDashnexIdSession: (startDir?: string) => Promise<boolean>;
|
|
10
20
|
export declare const ensureLoggedIn: (options?: EnsureLoggedInOptions) => Promise<EnsureLoggedInResult | null>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export interface Business {
|
|
2
|
+
id: number;
|
|
3
|
+
name: string;
|
|
4
|
+
}
|
|
5
|
+
export interface BusinessTokens {
|
|
6
|
+
token: string;
|
|
7
|
+
refreshToken: string;
|
|
8
|
+
businessId: number;
|
|
9
|
+
}
|
|
10
|
+
export declare class BusinessesError extends Error {
|
|
11
|
+
}
|
|
12
|
+
/** The DashNex ID session is gone or expired — the browser flow has to run again. */
|
|
13
|
+
export declare class UnauthorizedError extends BusinessesError {
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Businesses the user owns, plus the ones they are a team member of, deduped
|
|
17
|
+
* by id with the owned list winning.
|
|
18
|
+
*/
|
|
19
|
+
export declare const fetchBusinesses: (token: string) => Promise<Business[]>;
|
|
20
|
+
/**
|
|
21
|
+
* Exchanges the DashNex ID session token for a business-scoped token. The
|
|
22
|
+
* result is a KMS-signed JWT carrying ROLE_BUSINESS, which is what every other
|
|
23
|
+
* CLI command authenticates with against the business API.
|
|
24
|
+
*/
|
|
25
|
+
export declare const switchBusiness: (token: string, businessId: number) => Promise<BusinessTokens>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The out-of-band sentinel. Sent as `redirect_uri`, it asks the authorization
|
|
3
|
+
* server to display the code for the user to copy instead of redirecting to a
|
|
4
|
+
* callback. The server honours it only for public clients whose admin enabled
|
|
5
|
+
* `allowManualCode`, and it must be echoed back at the token endpoint — code
|
|
6
|
+
* redemption compares the two.
|
|
7
|
+
*/
|
|
8
|
+
export declare const OOB_REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
|
|
9
|
+
export interface OAuthTokens {
|
|
10
|
+
token: string;
|
|
11
|
+
refreshToken?: string;
|
|
12
|
+
expiresIn?: number;
|
|
13
|
+
}
|
|
14
|
+
export declare class OAuthError extends Error {
|
|
15
|
+
readonly code?: string | undefined;
|
|
16
|
+
constructor(message: string, code?: string | undefined);
|
|
17
|
+
}
|
|
18
|
+
export declare const buildAuthorizeUrl: (challenge: string) => string;
|
|
19
|
+
/**
|
|
20
|
+
* Redeems a manually entered authorization code.
|
|
21
|
+
*
|
|
22
|
+
* No `client_secret` is sent — this is a public client, and the server rejects
|
|
23
|
+
* the request outright if one is present.
|
|
24
|
+
*
|
|
25
|
+
* On DashNex ID the returned access token is not a plain OAuth token: the
|
|
26
|
+
* `oauth-session-bridge` module swaps in a real @dashnex/auth session token, so
|
|
27
|
+
* it works against the `roles: ['user']` routes the business picker needs.
|
|
28
|
+
*/
|
|
29
|
+
export declare const exchangeCode: (code: string, verifier: string) => Promise<OAuthTokens>;
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"chalk";import s from"fs-extra";import n from"path";var r=e=>e instanceof Error&&("ExitPromptError"===e.name||("AbortError"===e.name||("User force closed the prompt"===e.message||!!e.message.includes("prompt was closed")))),t="Command interrupted.",o=e=>{const s=e.toLowerCase();return s.includes("token")||s.includes("password")||"auth_code"===s},a=e=>{if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(a);const s={};for(const[n,r]of Object.entries(e))o(n)?s[n]="[REDACTED]":s[n]=a(r);return s},i=s=>{process.env.DEBUG&&console.log(e.dim(s))},c=(s,n)=>{if(process.env.DEBUG){const r=a(n);console.log(e.dim(`${s}: ${JSON.stringify(r,null,2)}`))}},u=s=>{process.env.DEBUG&&s instanceof Error&&(console.log(e.dim(`Error: ${s.message}`)),s.stack&&console.log(e.dim(`Stack: ${s.stack}`)))},l=()=>"qa"===process.env.APPLICATION_ENV?"https://api.qa.dashnex.com":"https://api.dashnex.com",p=()=>process.env.DASHNEX_BUSINESS_API_URL?process.env.DASHNEX_BUSINESS_API_URL.replace(/\/+$/,""):"qa"===process.env.APPLICATION_ENV?"https://api.business.qa.dashnex.com":"https://api.business.dashnex.com",f={qa:"https://3atfynmu2w.us-east-1.awsapprunner.com",live:"https://rkwbzvhcwh.us-east-1.awsapprunner.com"},d=()=>f[process.env.APPLICATION_ENV||"live"]||f.live,h=async(e,s={})=>{const n=await fetch(e,{...s,headers:{"Content-Type":"application/json",...s.headers}});return{response:n,body:await n.json().catch(()=>({}))}},m=process.env.DASHNEX_DIR||".dashnex",k=e=>n.join(e,m,"settings.json"),g=()=>{console.error(e.red("Please run 'dashnex login' to authenticate.")),console.error(e.green("If you don't have an account yet, create one at https://dashnex.io"))},x=e=>{try{const s=e.split(".");if(3!==s.length)return null;const n=JSON.parse(Buffer.from(s[1],"base64url").toString());return void 0!==n.id?String(n.id):null}catch{return null}},E=(e,s=30)=>{try{const n=e.split(".");if(3!==n.length)return!1;const r=JSON.parse(Buffer.from(n[1],"base64url").toString());if("number"!=typeof r.exp)return!1;const t=Math.floor(Date.now()/1e3),o=r.exp-s<=t;return o&&i(`Token expired or expiring soon (exp: ${r.exp}, now: ${t})`),o}catch{return!1}},v=async(e,n)=>{i(`POST ${l()}/auth/v1/token/refresh`);const{response:r,body:t}=await h(`${l()}/auth/v1/token/refresh`,{method:"POST",body:JSON.stringify({refreshToken:e})});if(i(`Response: ${r.status}`),c("Refresh response",t),!r.ok)return i("Token refresh failed"),null;const o=t;if(!o.token||!o.refreshToken)return i("Refresh response missing tokens"),null;const a=await s.readJson(n);return a.token=o.token,a.refreshToken=o.refreshToken,await s.writeJson(n,a,{spaces:2}),i("Updated settings.json with new tokens"),y(o.token,o.refreshToken,n,{...a,token:o.token,refreshToken:o.refreshToken})},y=async(e,s,n,r)=>{if(E(e)){if(!s)return i("Token expired, no refreshToken available"),null;i("Token expired, refreshing proactively");try{return await v(s,n)}catch(t){return u(t),null}}i(`GET ${l()}/users/v1/`);try{const{response:t,body:o}=await h(`${l()}/users/v1/`,{headers:{Authorization:`Bearer ${e}`}});if(i(`Response: ${t.status}`),c("Users response",o),t.ok){const s=o;if("string"==typeof s.name&&r.businessId)return i(`Token valid, Already logged in as ${s.name}`),{token:e,businessId:r.businessId,userName:s.name}}return s?(i("Users API rejected token, refreshing"),await v(s,n)):(i("Token invalid, no refreshToken available"),null)}catch(t){return u(t),null}},T=async(r={})=>{const{exitOnFailure:t=!0,dashnexPath:o}=r,a=process.env.DASHNEX_TOKEN;if(a)return E(a)?(i("DASHNEX_TOKEN is expired"),console.error(e.red("DASHNEX_TOKEN is expired. Provide a freshly issued token.")),t&&process.exit(1),null):(i("Using DASHNEX_TOKEN from environment"),{token:a,businessId:x(a)??""});const c=o??await(async e=>{let r=n.resolve(e);for(;;){const e=k(r);if(await s.pathExists(e))return e;const t=n.dirname(r);if(t===r)return null;r=t}})(process.cwd());if(!c||!(await s.pathExists(c)))return i(".dashnex/settings.json not found"),t&&(g(),process.exit(1)),null;let u;i(`Found settings at ${c}`);try{u=await s.readJson(c)}catch{return i("settings.json parse failed"),t&&(g(),process.exit(1)),null}const{token:l,refreshToken:p,businessId:f}=u;if(!l)return i("settings.json missing token"),t&&(g(),process.exit(1)),null;const d=await y(l,p,c,u);return d||(t&&(g(),process.exit(1)),null)};export{l as a,i as c,t as d,r as f,h as i,u as l,m as n,p as o,k as r,d as s,T as t,c as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e={$schema:"https://json.schemastore.org/package",name:"@dashnex/cli",version:"0.5.88",description:"Command-line interface for DashNex framework",homepage:"https://dashnex.io",type:"module",bin:{dashnex:"bin/dashnex"},engines:{node:">=22"},exports:{".":{types:"./dist/server.d.ts",default:"./dist/server.js"},"./client":{types:"./dist/client.d.ts",default:"./dist/client.js"}},scripts:{build:"vite build",dev:"vite build --watch --mode development",test:"vitest run"},keywords:["dashnex","cli"],author:"Dashnex Team",license:"UNLICENSED",dependencies:{"adm-zip":"^0.5.17",chalk:"^5.6.2",commander:"^14.0.3",diff:"^8.0.4",dotenv:"^17.4.2","fs-extra":"^11.3.5",ignore:"^7.0.5",inquirer:"^13.4.3",partysocket:"^1.3.0",ws:"^8.21.0"},devDependencies:{"@dashnex/types":"^1.4.4","@types/adm-zip":"^0.5.8","@types/fs-extra":"^11.0.4","@types/inquirer":"^9.0.9","@types/node":"^25.7.0","@types/ws":"^8.18.1",eslint:"^9.39.4","rollup-plugin-preserve-directives":"^0.4.0",terser:"^5.47.1",typescript:"^5.9.3",vite:"^8.0.12","vite-plugin-dts":"5.0.0-beta.6",vitest:"^4.1.6"},publishConfig:{registry:"https://npm.dashnex.com/"},files:["dist","bin","AGENTS.md","CLAUDE.md"]},s={};export{e as n,s as t};
|