@dashnex/cli 0.5.77 → 0.5.79
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/AGENTS.md +18 -0
- package/README.md +62 -0
- package/dist/chunks/dashnex-BJg_oM6X.js +1 -0
- package/dist/client.js +1 -1
- package/dist/commands/index.js +1 -1
- package/dist/server.js +1 -1
- package/dist/src/commands/app/tail.d.ts +9 -0
- package/dist/src/lib/log-format.d.ts +40 -0
- package/dist/src/services/tail.d.ts +31 -0
- package/package.json +16 -11
- package/dist/chunks/dashnex-DtLhLOw7.js +0 -1
package/AGENTS.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
<!-- OPENSPEC:START -->
|
|
2
|
+
# OpenSpec Instructions
|
|
3
|
+
|
|
4
|
+
These instructions are for AI assistants working in this project.
|
|
5
|
+
|
|
6
|
+
Always open `@/openspec/AGENTS.md` when the request:
|
|
7
|
+
- Mentions planning or proposals (words like proposal, spec, change, plan)
|
|
8
|
+
- Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work
|
|
9
|
+
- Sounds ambiguous and you need the authoritative spec before coding
|
|
10
|
+
|
|
11
|
+
Use `@/openspec/AGENTS.md` to learn:
|
|
12
|
+
- How to create and apply change proposals
|
|
13
|
+
- Spec format and conventions
|
|
14
|
+
- Project structure and guidelines
|
|
15
|
+
|
|
16
|
+
Keep this managed block so 'openspec update' can refresh the instructions.
|
|
17
|
+
|
|
18
|
+
<!-- OPENSPEC:END -->
|
package/README.md
CHANGED
|
@@ -68,3 +68,65 @@ dashnex <command> [options]
|
|
|
68
68
|
|
|
69
69
|
**secrets delete**:
|
|
70
70
|
- `--name <name>` — Secret name (prompted if omitted)
|
|
71
|
+
|
|
72
|
+
## Creating your own command
|
|
73
|
+
|
|
74
|
+
The CLI auto-discovers commands from every installed `@dashnex/*` module (and your app). To add a command, a module exports a **default array of `CliCommandConfig`** from `src/commands/index.ts`. On startup the CLI looks for the command file in each module, in this order:
|
|
75
|
+
|
|
76
|
+
1. `dist/commands/index.js` — the built package (published modules)
|
|
77
|
+
2. `src/commands/index.ts` — linked / in-development modules
|
|
78
|
+
3. `src/commands/index.js`
|
|
79
|
+
|
|
80
|
+
It imports the file and reads its **`default`** export (an array), or a named **`commands`** export as a fallback. Discovered commands are registered at the top level, so a command named `report` is invoked as `dashnex report`.
|
|
81
|
+
|
|
82
|
+
### 1. Write a handler
|
|
83
|
+
|
|
84
|
+
A handler is a `CliCommand` — any object with an `async execute(options)` method. `options` is a single object merging the parsed flags (by their long name), positional arguments (by `name`), and inherited parent options.
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
// src/commands/index.ts
|
|
88
|
+
import type { CliCommand, CliCommandConfig } from '@dashnex/types'
|
|
89
|
+
|
|
90
|
+
class ReportCommand implements CliCommand {
|
|
91
|
+
async execute(options: { format: string; out?: string; name?: string; ci?: boolean }) {
|
|
92
|
+
console.log(`Generating ${options.format} report for ${options.name ?? 'all'}…`)
|
|
93
|
+
// ...do the work
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const commands: CliCommandConfig[] = [
|
|
98
|
+
{
|
|
99
|
+
name: 'report',
|
|
100
|
+
description: 'Generate a report',
|
|
101
|
+
arguments: [
|
|
102
|
+
{ name: 'name', description: 'Target name', required: false },
|
|
103
|
+
],
|
|
104
|
+
options: [
|
|
105
|
+
{ flags: '-f, --format <format>', description: 'Output format', defaultValue: 'json' },
|
|
106
|
+
{ flags: '-o, --out <path>', description: 'Write to a file' },
|
|
107
|
+
],
|
|
108
|
+
handler: new ReportCommand(),
|
|
109
|
+
},
|
|
110
|
+
]
|
|
111
|
+
|
|
112
|
+
export default commands
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Now `dashnex report acme --format csv -o ./acme.csv` calls `execute({ name: 'acme', format: 'csv', out: './acme.csv', ci: false })`.
|
|
116
|
+
|
|
117
|
+
### 2. `CliCommandConfig` shape
|
|
118
|
+
|
|
119
|
+
| Field | Type | Description |
|
|
120
|
+
|-------|------|-------------|
|
|
121
|
+
| `name` | `string` | The command word (`dashnex <name>`). **Required.** |
|
|
122
|
+
| `description` | `string` | Shown in `--help`. **Required.** |
|
|
123
|
+
| `handler` | `CliCommand` | Object with `execute(options): Promise<void>`. **Required** (use a no-op when the command only groups subcommands). |
|
|
124
|
+
| `arguments` | `CliArgument[]` | Positional args: `{ name, description, required?, defaultValue? }`. Rendered as `<name>` (required) or `[name]` (optional). |
|
|
125
|
+
| `options` | `CliOption[]` | Flags: `{ flags, description, defaultValue? }` — `flags` uses commander syntax, e.g. `-f, --format <format>`. |
|
|
126
|
+
| `subcommands` | `CliCommandConfig[]` | Nested commands (e.g. `dashnex mymodule sync`). A parent with subcommands prints help when run alone. |
|
|
127
|
+
|
|
128
|
+
Notes:
|
|
129
|
+
|
|
130
|
+
- A **`--ci`** flag is added to every command automatically (disables spinners / interactive prompts); read it as `options.ci`.
|
|
131
|
+
- Errors thrown from `execute` are reported and exit with code `1`; throwing a user-interrupt is handled gracefully.
|
|
132
|
+
- **Publish step:** make sure your build emits `dist/commands/index.js` and that `dist` is in the package's `files`, so the command ships with the module.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e={$schema:"https://json.schemastore.org/package",name:"@dashnex/cli",version:"0.5.79",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",dotenv:"^17.4.2","fs-extra":"^11.3.5",ignore:"^7.0.5",inquirer:"^13.4.3",partysocket:"^1.3.0",ws:"^8.21.0"},devDependencies:{"@dashnex/types":"^1.4.2","@types/adm-zip":"^0.5.8","@types/fs-extra":"^11.0.4","@types/inquirer":"^9.0.9","@types/node":"^25.7.0","@types/ws":"^8.18.1",eslint:"^9.39.4","rollup-plugin-preserve-directives":"^0.4.0",terser:"^5.47.1",typescript:"^5.9.3",vite:"^8.0.12","vite-plugin-dts":"5.0.0-beta.6",vitest:"^4.1.6"},publishConfig:{registry:"https://npm.dashnex.com/"},files:["dist","bin","AGENTS.md","CLAUDE.md"]},s={};export{e as n,s as t};
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as s,t as e}from"./chunks/dashnex-
|
|
1
|
+
import{n as s,t as e}from"./chunks/dashnex-BJg_oM6X.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{n as e,t}from"../chunks/errors-7HJEDWYU.js";import s from"chalk";import o from"fs-extra";import n from"path";import{fileURLToPath as r}from"url";import{spawn as a}from"child_process";import i from"fs";import c from"inquirer";import l from"os";import p from"adm-zip";import d from"ignore";var u=process.env.DASHNEX_DIR||".dashnex",h=e=>n.join(e,u,"settings.json"),f=e=>{const t=e.toLowerCase();return t.includes("token")||t.includes("password")||"auth_code"===t},m=e=>{if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(m);const t={};for(const[s,o]of Object.entries(e))f(s)?t[s]="[REDACTED]":t[s]=m(o);return t},g=e=>{process.env.DEBUG&&console.log(s.dim(e))},y=(e,t)=>{if(process.env.DEBUG){const o=m(t);console.log(s.dim(`${e}: ${JSON.stringify(o,null,2)}`))}},w=e=>{process.env.DEBUG&&e instanceof Error&&(console.log(s.dim(`Error: ${e.message}`)),e.stack&&console.log(s.dim(`Stack: ${e.stack}`)))},$=()=>"qa"===process.env.APPLICATION_ENV?"https://api.qa.dashnex.com":"https://api.dashnex.com",v=()=>"qa"===process.env.APPLICATION_ENV?"https://api.business.qa.dashnex.com":"https://api.business.dashnex.com",k={qa:"https://3atfynmu2w.us-east-1.awsapprunner.com",live:"https://rkwbzvhcwh.us-east-1.awsapprunner.com"},x=async(e,t={})=>{const s=await fetch(e,{...t,headers:{"Content-Type":"application/json",...t.headers}});return{response:s,body:await s.json().catch(()=>({}))}},b=()=>{console.error(s.red("Please run 'dashnex login' to authenticate.")),console.error(s.green("If you don't have an account yet, create one at https://dashnex.io"))},E=async(e,t)=>{g(`POST ${$()}/auth/v1/token/refresh`);const{response:s,body:n}=await x(`${$()}/auth/v1/token/refresh`,{method:"POST",body:JSON.stringify({refreshToken:e})});if(g(`Response: ${s.status}`),y("Refresh response",n),!s.ok)return g("Token refresh failed"),null;const r=n;if(!r.token||!r.refreshToken)return g("Refresh response missing tokens"),null;const a=await o.readJson(t);return a.token=r.token,a.refreshToken=r.refreshToken,await o.writeJson(t,a,{spaces:2}),g("Updated settings.json with new tokens"),S(r.token,r.refreshToken,t,{...a,token:r.token,refreshToken:r.refreshToken})},S=async(e,t,s,o)=>{if(((e,t=30)=>{try{const s=e.split(".");if(3!==s.length)return!1;const o=JSON.parse(Buffer.from(s[1],"base64url").toString());if("number"!=typeof o.exp)return!1;const n=Math.floor(Date.now()/1e3),r=o.exp-t<=n;return r&&g(`Token expired or expiring soon (exp: ${o.exp}, now: ${n})`),r}catch{return!1}})(e)){if(!t)return g("Token expired, no refreshToken available"),null;g("Token expired, refreshing proactively");try{return await E(t,s)}catch(n){return w(n),null}}g(`GET ${$()}/users/v1/`);try{const{response:n,body:r}=await x(`${$()}/users/v1/`,{headers:{Authorization:`Bearer ${e}`}});if(g(`Response: ${n.status}`),y("Users response",r),n.ok){const t=r;if("string"==typeof t.name&&o.businessId)return g(`Token valid, Already logged in as ${t.name}`),{token:e,businessId:o.businessId,userName:t.name}}return t?(g("Users API rejected token, refreshing"),await E(t,s)):(g("Token invalid, no refreshToken available"),null)}catch(n){return w(n),null}},T=async(e={})=>{const{exitOnFailure:t=!0,dashnexPath:s}=e,r=s??await(async e=>{let t=n.resolve(e);for(;;){const e=h(t);if(await o.pathExists(e))return e;const s=n.dirname(t);if(s===t)return null;t=s}})(process.cwd());if(!r||!(await o.pathExists(r)))return g(".dashnex/settings.json not found"),t&&(b(),process.exit(1)),null;let a;g(`Found settings at ${r}`);try{a=await o.readJson(r)}catch{return g("settings.json parse failed"),t&&(b(),process.exit(1)),null}const{token:i,refreshToken:c,businessId:l}=a;if(!i)return g("settings.json missing token"),t&&(b(),process.exit(1)),null;const p=await S(i,c,r,a);return p||(t&&(b(),process.exit(1)),null)},P=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],A=(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()}}},C=(e,t,o)=>{const n=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);let r=o;429===e.status?r="Too many requests. Please wait a moment and try again.":e.status>=500?r="DashNex API is temporarily unavailable. Please try again later.":n&&(r=n),console.error(s.red(r)),process.exit(1)},D=["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)),I=(e,t)=>{let s="";return{write:o=>{const n="string"==typeof o?o:o.toString();s+=n;const r=s.split(/\r?\n/);s=r.pop()??"";for(const s of r){const o=s.trim();o?N(o,t)?g(`Filtered: ${o}`):e.write(s+"\n"):g("Filtered: <empty line>")}},flush:()=>{const o=s.trim();if(o){if(N(o,t))return g(`Filtered: ${o}`),void(s="");e.write(s),s=""}else s=""}}},j=async(e,t={})=>{const s=n.join(e,"dashnex.json"),r=n.join(e,"package.json");if(g(`Checking for dashnex.json at: ${s}`),!(await o.pathExists(s)))throw new Error("Run this command in a DashNex Web application folder.");if(g("dashnex.json found, checking for package.json"),!(await o.pathExists(r)))throw new Error("package.json is missing.");let i;g("package.json found, checking for dev script");try{i=await o.readJson(r)}catch(p){throw w(p),new Error("Failed to read package.json.")}if(!i.scripts||!i.scripts.dev)throw new Error('The "dev" script is missing from package.json. Please add a "dev" script to package.json.');g("dev script found, checking for npm availability");const c=await(async e=>new Promise(t=>{const s=a(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>{t(!1)}),s.on("close",e=>{t(0===e)})}))("npm");if(g(`npm available: ${c}`),!c)throw new Error("npm is not available. Please install npm to continue.");const l=t.https?["--","--experimental-https"]:[];return g(`npm available, executing: npm run dev in ${e}${t.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=a(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=>{w(e),t(e)}),r&&i.stdout&&i.stderr){const t=I(process.stdout,o),s=I(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",l,e,(()=>{const e=[];for(const t of D)try{e.push(new RegExp(t))}catch{g(`Invalid dev output filter pattern ignored: ${t}`)}return e})())},F="Run this command in a DashNex Web application folder.",O=e=>{const t=n.join(e,"dashnex.json");return o.pathExistsSync(t)},B=(e,t,s={})=>{const o=`${e} ${t.join(" ")}`,n=!0===s.silent;return new Promise((t,s)=>{g(`Running: ${o}`);const r=a(o,{stdio:n?["ignore","pipe","pipe"]:"inherit",cwd:process.cwd(),shell:!0});r.on("error",e=>{w(e),s(e)}),r.on("close",s=>{g(`${e} exited with code ${s}`),t(null===s?1:s)})})},R=e=>new Promise(t=>{const s=a(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>t(!1)),s.on("close",e=>t(0===e))}),z=[{name:"TypeScript",command:"npx",args:["tsc","--noEmit"],notFoundMessage:"TypeScript is not available. Please install it with: npm install -D typescript"}],L=class{async execute(){g("Check flow started"),O(process.cwd())||(console.error(s.red(F)),process.exit(1)),g(`Running ${z.length} check(s)`);for(const t of z){g(`Running check: ${t.name}`),await R(t.command)||(console.error(s.red(t.notFoundMessage)),process.exit(1));try{0!==await B(t.command,t.args)&&(console.error(s.red("Check failed.")),process.exit(1))}catch(e){w(e),console.error(s.red(t.notFoundMessage)),process.exit(1)}}console.log(s.green("All checks passed."))}async run(e=!1){if(g("Running checks (called from push)"),!O(process.cwd()))return e||console.error(s.red(F)),!1;const t=e?{silent:!0}:void 0;for(const n of z){if(g(`Running check: ${n.name}`),!(await R(n.command)))return console.error(s.red(n.notFoundMessage)),!1;try{if(0!==await B(n.command,n.args,t))return!1}catch(o){return w(o),console.error(s.red(n.notFoundMessage)),!1}}return e||console.log(s.green("All checks passed.")),!0}},M=async e=>new Promise(t=>{const s=a(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>{t(!1)}),s.on("close",e=>{t(0===e)})}),W=async e=>{let t;if(await M("pnpm"))t="pnpm install",g("Using package manager: pnpm");else{if(!(await M("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",g("Using package manager: npm (with --legacy-peer-deps for DashNex peer-dep overlap)")}return g(`Executing: ${t} in ${e}`),new Promise((s,o)=>{const n=[],r=[],i=a(t,{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=>{w(e),o(e)}),i.on("close",e=>{const t=null===e?0:e;0!==t&&(n.length&&process.stdout.write(Buffer.concat(n)),r.length&&process.stderr.write(Buffer.concat(r))),s(t)})})},_=async(e,t)=>{const{install:o}=await c.prompt([{type:"confirm",name:"install",message:"Install dependencies?",default:!0}]);if(!o){if(n.resolve(e)!==n.resolve(t)){const o=n.relative(t,e);console.log(s.cyan(`Run "cd ${o}" to change to the application folder.`))}return}try{const t=A();t.start("Installing dependencies...");try{const s=await W(e);if(t.stop(),0!==s)return void g(`install exited with code ${s}`)}catch(l){throw t.stop(),l}}catch(l){return w(l),void console.error(s.red(l instanceof Error?l.message:"Failed to run install."))}const{migrate:r}=await c.prompt([{type:"confirm",name:"migrate",message:"Create or update database?",default:!0}]);if(!r)return;g(`Running dashnex db migrate in ${e}`);try{const t=A();t.start("Creating or updating database...");try{const s=await((e,t,s)=>{const o=`${n.join(e,"node_modules",".bin")}${n.delimiter}${process.env.PATH??""}`,r={...process.env,PATH:o};return new Promise((o,n)=>{const i=a(t,{cwd:e,shell:!0,stdio:"inherit",env:s?{...r,...s}:r});i.on("error",e=>{w(e),n(e)}),i.on("close",e=>{o(null===e?0:e)})})})(e,"dashnex db migrate");if(t.stop(),0!==s)return void g(`dashnex db migrate exited with code ${s}`)}catch(l){throw t.stop(),l}}catch(l){return w(l),void console.error(s.red("Failed to run dashnex db migrate."))}const{dev:i}=await c.prompt([{type:"confirm",name:"dev",message:"Run development server?",default:!0}]);if(i)try{await j(e)}catch(l){w(l),console.error(s.red(l instanceof Error?l.message:"Failed to run dev server."))}},J=(e,t)=>{if(e.length!==t.length)return`local ${e.length} bytes, zip ${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")} zip=0x${t[o].toString(16).padStart(2,"0")})`}return`size ${s} matches; no byte difference (unexpected)`},U=async(e,t)=>{let s;try{s=await o.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, zip ${t.length} bytes`};const n=await o.readFile(e);return 0===Buffer.compare(n,t)?{kind:"identical"}:{kind:"different",reason:J(n,t)}},G=async e=>{const{choice:t}=await c.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},q=(e,t)=>n.resolve(e)===n.resolve(t)?"Application is successfully pulled.":`Application is successfully pulled into ${n.relative(t,e)}.`,X=class{async execute(r={}){g("Pull flow started");const a=await T();if(!a)return;const i=process.cwd();let d;if(r.folder)d=r.folder.trim()||".",g(`Folder argument provided: ${d}`);else{g("No folder argument, prompting user");const{folder:e}=await c.prompt([{type:"input",name:"folder",message:"Which folder to pull the application to?",default:"."}]);d=e.trim()||"."}const u=n.resolve(i,d);g(`Target folder resolved: ${u}`);try{const e=await o.lstat(u).catch(()=>null);e&&!e.isDirectory()&&(console.error(s.red(`Cannot pull into ${u}: path exists and is not a directory.`)),process.exit(1)),await o.ensureDir(u),g(`Target folder ensured: ${u}`)}catch($){w($);const e=$ instanceof Error?$.message:"Unknown error";console.error(s.red(`Cannot create folder ${u}: ${e}`)),process.exit(1)}const h=`${v()}/business/v1/cli/pull`;g(`GET ${h}`);const f=n.join(l.tmpdir(),`dashnex-pull-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),m=A();m.start("Pulling application...");try{const e=await fetch(h,{headers:{Authorization:`Bearer ${a.token}`}});if(g(`Response: ${e.status}`),!e.ok){m.stop();const t=e.headers.get("content-type")??"";let o="Failed to pull application.";if(401===e.status||403===e.status)o="Please run 'dashnex login' to authenticate.";else if(404===e.status)o="Business has no application. Run 'dashnex app create' to create one.";else if(t.includes("application/json")){const t="string"==typeof(y=await e.json().catch(()=>({}))).error?y.error:"string"==typeof y.message?y.message:void 0;t&&(o=t)}console.error(s.red(o)),process.exit(1)}m.text("Downloading...");const t=Buffer.from(await e.arrayBuffer());await o.writeFile(f,t),g("Zip written to temp file"),m.text("Extracting...");const c=new p(f).getEntries().filter(e=>!e.isDirectory);g(`Zip has ${c.length} file entries`);const l=r.yes||"1"===process.env.DASHNEX_CI;let d=l?"all":"prompt",v=!1,k=0,x=0,b=0,E=0,S=0;const T=async(e,t,s)=>{try{return await o.ensureDir(n.dirname(e)),await o.writeFile(e,t),s&&await o.chmod(e,s),!0}catch($){return w($),!1}};for(const o of c){const e=o.getData(),t=n.join(u,o.entryName),r=n.relative(u,t)||o.entryName,a=(o.header.attr??0)>>16&4095,i=await U(t,e);if(g(`Entry ${o.entryName}: ${i.kind}${i.reason?` (${i.reason})`:""}`),"identical"===i.kind){E+=1;continue}if("new"===i.kind){await T(t,e,a)?k+=1:S+=1;continue}let c=!1;if("all"===d)c=!0;else if("none"===d)c=!1;else{m.stop(),v||(console.log(s.dim("Y = yes (default), n = skip, a = overwrite all, s = skip all, h = help")),v=!0);const e=await G(r);g(`Entry ${o.entryName}: user chose ${e}`),"yes"===e?c=!0:"no"===e?c=!1:"all"===e?(d="all",c=!0):(d="none",c=!1),m.start("Extracting...")}c?await T(t,e,a)?x+=1:S+=1:b+=1}m.stop(),g(`Pull summary: ${k} new, ${x} overwritten, ${b} skipped, ${E} unchanged, ${S} failed`);const P=[`${k} new`,`${x} overwritten`,`${b} skipped`,`${E} unchanged`];S>0&&P.push(`${S} failed`),console.log(s.cyan(`Pulled: ${P.join(", ")}`)),n.resolve(u)!==n.resolve(i)?(console.log(s.green(q(u,i))),process.chdir(u),g(`Changed working directory to ${u}`)):console.log(s.green(q(u,i))),S>0&&(console.error(s.red(`${S} file(s) failed to write. See DEBUG output for details.`)),process.exit(1)),l?g("Non-interactive mode (--yes or --ci), skipping post-pull child commands"):await _(u,i)}catch($){if(m.stop(),w($),$ instanceof Error&&$.message.startsWith("EXIT:"))throw $;if(e($))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}finally{await o.remove(f).catch(()=>{}),g("Temp zip removed")}var y}},H=async e=>{const t=`${v()}/business/v1/agreements/payment-processing/status`;g(`GET ${t}`);const o=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});if(g(`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(s.red(`You need to accept Master Payment Processing Agreement first by visiting this link: ${n}`)),!1},V=async(e,t={})=>{const o=t.ciMode??!1;return!!(await H(e))&&!!(await(async(e,t)=>{const o=`${v()}/business/v1/tos/latest`;g(`GET ${o}`);const n=await fetch(o,{headers:{Authorization:`Bearer ${e}`}});if(g(`TOS latest response: ${n.status}`),n.ok)return!0;if(404!==n.status)return!0;const r=`${v()}/business/v1/tos/current`;g(`GET ${r}`);const a=await fetch(r,{headers:{Authorization:`Bearer ${e}`}});if(g(`TOS current response: ${a.status}`),!a.ok)return g("Could not fetch current TOS, skipping check"),!0;const i=await a.json().catch(()=>({})),l=i.version??"unknown";if(i.text&&(console.log(s.dim("─".repeat(60))),console.log(s.bold(`Terms of Service ${l}`)),console.log(s.dim("─".repeat(60))),console.log(i.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(s.dim("─".repeat(60)))),t)return console.log(s.yellow(`By proceeding you accept the Terms of Service ${l}.`)),!0;const{accept:p}=await c.prompt([{type:"confirm",name:"accept",message:`By creating an application you accept the Terms of Service ${l}. Continue?`,default:!0}]);if(!p)return console.log(s.yellow("Cancelled.")),!1;try{const t=`${v()}/business/v1/tos/${i.id}/accept`;g(`POST ${t}`),await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch(d){w(d)}return!0})(e,o))},Y=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,Z=e=>new Promise(t=>setTimeout(t,e)),K=e=>e.appFullCustomDomain?e.appFullCustomDomain:e.subdomain?"qa"===(process.env.APPLICATION_ENV??"")?`https://${e.subdomain}.dashnex.dev`:`https://${e.subdomain}.dashnexcloud.com`:null,Q=3e5,ee=99,te=e=>new Promise(t=>setTimeout(t,e)),se=async(e,t,o,n)=>{const r=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"text/event-stream"}});if(g(`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(s.red(t)),new Error(`HTTP ${e}: ${t}`)}if(!r.body)throw new Error("Response body is null");g("SSE connection established successfully"),n?.();const a=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 r=s.split("\n");s=r.pop()||"";let a="";for(const e of r)e.startsWith("data: ")?a=e.slice(6):""===e&&a&&(yield{data:a},a="")}if(s.startsWith("data: ")){const e=s.slice(6);e&&(yield{data:e})}}(a))try{if(!e.data){g("Received empty SSE event");continue}const t=JSON.parse(e.data);g(`SSE message received: ${JSON.stringify(t)}`),o(t)}catch(i){w(i),g(`Failed to parse SSE event data: ${e.data}`)}}finally{a.releaseLock()}},oe=class{async execute(o={}){g("Deploy flow started");const n=await T();if(!n)return;if(!1!==o.check?(g("Running pre-deploy checks"),await(new L).run(!1)||(console.error(s.red("Deploy aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):g("Skipping pre-deploy checks (--no-check)"),!(await V(n.token,{ciMode:!0})))return;const r=`${k[process.env.APPLICATION_ENV||"live"]||k.live}/business/v1/applications/deploy`;g(`GET ${r} (SSE)`);let a=0,i="",c=!1,l=0,p=!1;const d=A();let u=0,h=0,f=null;const m=(e,t)=>{const s=Math.round(e);d.text(`[${s}%] ${t}`)},y=()=>{$();const e=a,t=Date.now(),s=Q*((ee-e)/ee);f=setInterval(()=>{const o=Date.now()-t;let n;if(h>t){const e=Date.now()-h,t=ee-u,s=3030.3030303030305*t;n=Math.min(u+e/s*t,ee)}else n=Math.min(e+o/s*(ee-e),ee);n>a&&(a=n,m(a,i))},200)},$=()=>{f&&(clearInterval(f),f=null)};let v=!1;const x=e=>{if(p=!0,"string"==typeof e.error)return $(),d.stop(),console.error(s.red(e.error)),c=!0,void(v=!0);"string"==typeof e.message&&(i=e.message),"number"==typeof e.progress&&(u=e.progress,h=Date.now(),e.progress>a&&(a=e.progress)),"string"!=typeof e.message&&"number"!=typeof e.progress||(a>=100?($(),d.stop(),c=!0):m(a,i))};for(;l<=5;)try{return p?m(a,i):d.start("Connecting..."),y(),await se(r,n.token,x,()=>{p||(d.text(`[${Math.round(a)}%] Deployment in progress...`),i="Deployment in progress...")}),$(),d.stop(),g("SSE connection closed"),v&&process.exit(1),void(c&&await this.showDeployedUrl(n.token))}catch(b){if($(),w(b),g(`SSE connection error: ${b}`),c)return d.stop(),void(v&&process.exit(1));if(e(b))return d.stop(),void console.log(s.yellow(t));b instanceof Error&&b.message.startsWith("HTTP")&&(d.stop(),console.error(s.red("Could not complete deployment. Check your connection and try again.")),process.exit(1)),l++,l>5&&(d.stop(),console.error(s.red("Deployment failed. Maximum reconnection attempts exceeded.")),process.exit(1));const o=Math.min(1e3*Math.pow(2,l-1),3e4);g(`Connection error. Reconnecting in ${o/1e3}s... (attempt ${l}/5)`),await te(o)}}async showDeployedUrl(e){try{const t=`${v()}/business/v1/applications`;g(`GET ${t} (for deployed URL)`);const o=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)return;const n=await o.json().catch(()=>({})),r=K({subdomain:n.subdomain,appFullCustomDomain:n.appFullCustomDomain});r&&console.log(`Application is deployed to ${s.cyan(r)}`)}catch(t){w(t)}}},ne=[".dashnex",".git",".vinext",".wrangler","wrangler.jsonc"],re=async(e,t)=>{const s=[],r=await o.readdir(e,{withFileTypes:!0});for(const o of r){const r=n.relative(process.cwd(),n.join(e,o.name)).split(n.sep).join("/");if(ne.some(e=>r===e||r.startsWith(`${e}/`)||r.endsWith(`/${e}`)))continue;if(t.ignores(r))continue;const a=n.join(e,o.name);if(o.isDirectory()){const e=await re(a,t);s.push(...e)}else o.isFile()&&s.push(a)}return s},ae={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,s=5e3,o=6e4){const n=Date.now();let r=0;for(;Date.now()-n<o;){r++,g(`Polling application status (attempt ${r})...`);try{const s=await fetch(e,{headers:{Authorization:`Bearer ${t}`}});if(g(`Poll response: ${s.status}`),200===s.status){const e=await s.json();if(g(`Poll response body status: ${e.status}`),"creating"!==e.status)return g(`Application status is "${e.status}", creation complete`),{ready:!0,status:e.status};g('Application status is still "creating", continuing to poll...')}}catch(a){w(a),g(`Poll attempt ${r} failed with network error`)}await Z(s)}return{ready:!1}}async execute(o={}){g("Create flow started");const n=await T();if(!n)return;g("Auth valid, checking if business already has application");const r=A(),a=`${v()}/business/v1/applications`;g(`GET ${a}`),r.start("Checking application status...");try{const e=await fetch(a,{headers:{Authorization:`Bearer ${n.token}`}});r.stop(),g(`Applications response: ${e.status}`),g(`Applications response body: ${await e.text()}`),404!==e.status&&(console.error(s.red("Business already has an application. Run 'dashnex app pull' to pull the existing one.")),process.exit(1))}catch(m){if(r.stop(),w(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(e(m))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}g("No existing application, checking agreements");const i=void 0!==o.subdomain;if(!(await V(n.token,{ciMode:i})))return;let l;g("Agreements checked, proceeding to subdomain prompt");const p=e=>`${v()}/business/v1/applications/check-subdomain?subdomain=${encodeURIComponent(e)}`;let d=o.subdomain?.trim();for(;;){if(d)l=d,d=void 0,g(`Subdomain provided via flag: ${l}`);else{if(i)return console.error(s.red("Subdomain is not available.")),void process.exit(1);{const{sub:e}=await c.prompt([{type:"input",name:"sub",message:"Pick your subdomain:",validate:e=>!!e.trim()||"Subdomain is required"}]);l=e.trim()}}g(`Checking subdomain: ${l}`);const o=p(l);g(`GET ${o}`),r.start("Checking subdomain...");try{const e=await fetch(o,{headers:{Authorization:`Bearer ${n.token}`}});r.stop(),g(`Check subdomain response: ${e.status}`);const t=await e.text();if(g(`Check subdomain response body: ${t}`),!e.ok){const o=e.headers.get("content-type")??"";let n="Failed to check subdomain availability.";if(401!==e.status&&403!==e.status||(n="Please run 'dashnex login' to authenticate.",console.error(s.red(n)),process.exit(1)),o.includes("application/json")){const e=JSON.parse(t);g(`Check subdomain error body: ${JSON.stringify(e)}`);const s=Y(e);s&&(n=s)}console.error(s.red(n));continue}const a=JSON.parse(t);if(g(`Check subdomain parsed body: ${JSON.stringify(a)}`),a.available){g(`Subdomain ${l} is available`);break}console.error(s.red("Subdomain is not available. Please choose a different one."))}catch(m){if(r.stop(),w(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(e(m))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}const u=`${v()}/business/v1/cli/create`;g(`POST ${u}`);const h={subdomain:l};o.template&&(h.template=o.template,g(`Template: ${o.template}`));const f=JSON.stringify(h);g(`Create request body: ${f}`),r.start("Creating application...");try{const a=await fetch(u,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:f});r.stop(),g(`Create response: ${a.status}`);const l=await a.text();if(g(`Create response body: ${l}`),503===a.status){g("Create returned 503, polling for application creation..."),r.start("Waiting for application to be ready...");const e=`${v()}/business/v1/applications`,t=await this.pollApplicationCreated(e,n.token);r.stop(),t.ready||(console.error(s.red("Application creation is taking longer than expected. Try again later or run 'dashnex app pull' to check.")),process.exit(1)),"failed"===t.status&&(console.error(s.red("Application creation failed. Please try again.")),process.exit(1)),g("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);g(`Create error body parsed: ${JSON.stringify(e)}`);const s=Y(e);s&&(t=s)}console.error(s.red(t)),process.exit(1)}let p;if(g("Application created successfully"),!0===o.pull?(p=!0,g("--pull flag set, pulling without prompting")):!1===o.pull?(p=!1,g("--no-pull flag set, skipping pull")):i?(p=!1,g("CI mode (--subdomain), skipping pull")):(p=(await c.prompt([{type:"confirm",name:"pull",message:"Pull the application locally?",default:!0}])).pull,g(`User chose to pull: ${p}`)),p){g("Running pull flow");try{await(new X).execute()}catch(m){if(w(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(e(m))return void console.log(s.yellow(t));console.error(s.red("Failed to pull application."))}}else console.log(s.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(m){if(r.stop(),w(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(e(m))return void console.log(s.yellow(t));console.error(s.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 X,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(r={}){g("Push flow started"),!1!==r.check?(g("Running pre-push checks"),await(new L).run(!1)||(console.error(s.red("Push aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):g("Skipping pre-push checks (--no-check)");const a=await T();if(!a)return;const i=process.cwd(),u=n.join(i,".gitignore"),h=d();if(h.add(ne),await o.pathExists(u)){const e=await o.readFile(u,"utf8");h.add(e)}g("Building file list");const f=await re(i,h);g(`Including ${f.length} files`);const m=new p;for(const e of f){const t=n.relative(i,e).split(n.sep).join("/"),s="."===n.dirname(t)?"":n.dirname(t),o=n.basename(t);m.addLocalFile(e,s,o)}const y=n.join(l.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),$=A();try{$.start("Packaging application..."),m.writeZip(y),g(`Zip written to ${y}`);const e=`${v()}/business/v1/cli/push`;g(`POST ${e}`);const t=await o.readFile(y),n=new Blob([t],{type:"application/zip"}),i=new FormData;i.append("file",n,"archive.zip");const l=new Headers;l.set("Authorization",`Bearer ${a.token}`),$.text("Uploading...");const p=await fetch(e,{method:"POST",headers:l,body:i});if($.stop(),g(`Response: ${p.status}`),!p.ok){const e=p.headers.get("content-type")??"";let t="Failed to push application.";if(401===p.status||403===p.status)t="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e="string"==typeof(k=await p.json().catch(()=>({}))).error?k.error:"string"==typeof k.message?k.message:void 0;e&&(t=e)}console.error(s.red(t)),process.exit(1)}let d;console.log(s.green("Application pushed successfully.")),void 0!==r.deploy?(d=r.deploy,g(`Deploy decided via flag: ${d}`)):(d=(await c.prompt([{type:"confirm",name:"deploy",message:"Deploy the application?",default:!0}])).deploy,g(`User chose to deploy: ${d}`)),d&&(g("Running deploy flow"),await(new oe).execute())}catch(x){if($.stop(),w(x),x instanceof Error&&x.message.startsWith("EXIT:"))throw x;if(e(x))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}finally{await o.remove(y).catch(()=>{}),g("Temp zip removed")}var k}},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"}]},{name:"delete",description:"Delete application from DashNex",handler:new class{async execute(o={}){if(g("Delete flow started"),!o.yes){const{confirm:e}=await c.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 g("User cancelled deletion"),void console.log(s.yellow("Deletion cancelled."))}const n=await T();if(!n)return;const r=`${v()}/business/v1/applications`;g(`DELETE ${r}`);const a=A();a.start("Deleting application...");try{const e=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}});if(a.stop(),g(`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(s.red(o)),process.exit(1)}const t=await e.json().catch(()=>({})),o="string"==typeof t.message?t.message:"Application deleted successfully.";g("Application deleted successfully"),console.log(s.green(o))}catch(i){if(a.stop(),w(i),i instanceof Error&&i.message.startsWith("EXIT:"))throw i;if(e(i))return void console.log(s.yellow(t));console.error(s.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 oe,options:[{flags:"--no-check",description:"Skip pre-deploy checks"}]},{name:"status",description:"Show current application status",handler:new class{async execute(){g("Status flow started");const o=await T();if(!o)return;const n=`${v()}/business/v1/applications`;g(`GET ${n}`);const r=A();r.start("Fetching application status...");try{const e=await fetch(n,{headers:{Authorization:`Bearer ${o.token}`}});if(r.stop(),g(`Response: ${e.status}`),404===e.status)return void console.log(s.yellow("Application not created"));if(!e.ok){const t=e.headers.get("content-type")??"";let o="Failed to fetch application status.";if(401===e.status||403===e.status)o="Please run 'dashnex login' to authenticate.";else if(t.includes("application/json")){const t=await e.json().catch(()=>({}));"string"==typeof t.error?o=t.error:"string"==typeof t.message&&(o=t.message)}console.error(s.red(o)),process.exit(1)}const t=await e.json().catch(()=>({}));g(`Application body: ${JSON.stringify(t)}`);const a=t.status??"unknown";console.log(`Status: ${s.cyan(a)}`);const i=K(t);i&&console.log(`URL: ${s.cyan(i)}`)}catch(a){if(r.stop(),w(a),a instanceof Error&&a.message.startsWith("EXIT:"))throw a;if(e(a))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]}]},ie={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(){g("Secrets list flow started");const o=await T();if(!o)return;const n=`${v()}/business/v1/cli/secrets`;g(`GET ${n}`);const r=A();r.start("Fetching secrets...");try{const e=await fetch(n,{headers:{Authorization:`Bearer ${o.token}`}});if(r.stop(),g(`Response: ${e.status}`),!e.ok){let t="Failed to fetch secrets.";401===e.status||403===e.status?t="Please run 'dashnex login' to authenticate.":404===e.status?t="Business has no application.":502===e.status&&(t="Error fetching secrets. Make sure your application is deployed."),console.error(s.red(t)),process.exit(1)}const t=(await e.json()).secrets??[];if(0===t.length)return void console.log(s.yellow("No secrets set."));console.log(s.bold(`\nSecrets (${t.length}):\n`)),t.forEach(({name:e})=>{console.log(` ${s.cyan(e)}`)}),console.log("")}catch(a){if(r.stop(),w(a),a instanceof Error&&a.message.startsWith("EXIT:"))throw a;if(e(a))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]},{name:"set",description:"Create or update a secret",handler:new class{async execute(o={}){g("Secrets set flow started");let{name:n,value:r}=o;const a="1"===process.env.DASHNEX_CI;n||(a&&(console.error(s.red("--name is required in CI mode (--ci).")),process.exit(1)),n=(await c.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim()),r||(a&&(console.error(s.red("--value is required in CI mode (--ci).")),process.exit(1)),r=(await c.prompt([{type:"password",name:"value",message:`Enter value for ${n}:`,mask:"*",validate:e=>""!==e||"Value is required"}])).value);const i=await T();if(!i)return;const l=`${v()}/business/v1/cli/secrets`;g(`PUT ${l}`);const p=A();p.start(`Setting secret '${n}'...`);try{const e=await fetch(l,{method:"PUT",headers:{Authorization:`Bearer ${i.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:n,value:r})});if(p.stop(),g(`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(s.red(t)),process.exit(1)}g(`Secret '${n}' set successfully`),console.log(s.green(`Secret '${n}' set successfully.`))}catch(d){if(p.stop(),w(d),d instanceof Error&&d.message.startsWith("EXIT:"))throw d;if(e(d))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[{flags:"--name <name>",description:"Secret name"},{flags:"--value <value>",description:"Secret value"}]},{name:"delete",description:"Delete a secret",handler:new class{async execute(o={}){g("Secrets delete flow started");let{name:n}=o;const r="1"===process.env.DASHNEX_CI;n||(r&&(console.error(s.red("--name is required in CI mode (--ci).")),process.exit(1)),n=(await c.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim());const a=await T();if(!a)return;const i=`${v()}/business/v1/cli/secrets/${encodeURIComponent(n)}`;g(`DELETE ${i}`);const l=A();l.start(`Deleting secret '${n}'...`);try{const e=await fetch(i,{method:"DELETE",headers:{Authorization:`Bearer ${a.token}`}});if(l.stop(),g(`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(s.red(t)),process.exit(1)}g(`Secret '${n}' deleted successfully`),console.log(s.green(`Secret '${n}' deleted.`))}catch(p){if(l.stop(),w(p),p instanceof Error&&p.message.startsWith("EXIT:"))throw p;if(e(p))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[{flags:"--name <name>",description:"Secret name"}]}]},ce=[{name:"version",description:"Display the version of the CLI",handler:new class{async execute(e){const t=n.dirname(r(import.meta.url)),s=JSON.parse(i.readFileSync(n.resolve(t,"..","..","package.json"),"utf8"));console.log(s.version)}},options:[]},{name:"login",description:"Log in to your DashNex account",handler:new class{async execute(o={}){g("Login flow started");const n=h(process.cwd()),r=await T({exitOnFailure:!1,dashnexPath:n});if(r)console.log(s.green(`Already logged in as ${r.userName??"user"}`));else try{let e,t;if(o.email)e=o.email.trim(),g("Email provided via flag");else{const{username:t}=await c.prompt([{type:"input",name:"username",message:"Email:",validate:e=>!!e.trim()||"Email is required"}]);e=t.trim()}if(o.password)t=o.password,g("Password provided via flag");else{const{password:e}=await c.prompt([{type:"password",name:"password",message:"Password:",mask:"*",validate:e=>!!e||"Password is required"}]);t=e}g("Email provided");const r=A();r.start("Logging in..."),g(`POST ${$()}/auth/v1/login`);const{response:a,body:i}=await x(`${$()}/auth/v1/login`,{method:"POST",body:JSON.stringify({username:e,password:t})});r.stop(),g(`Response: ${a.status}`),y("Login response",i),a.ok||(w(/* @__PURE__ */new Error(`Login failed: ${a.status} ${JSON.stringify(i)}`)),401===a.status&&(console.error(s.red("Invalid username or password.")),process.exit(1)),C(a,i,"Login failed. Please try again."));const l=i;if(l.two_fa_required&&l.token){g(`2FA required, type: ${l.type||"unknown"}`);const e=await this.handle2FA(l.token,l.type,o.code);e||process.exit(1),await this.completeLogin(e,n,o.business)}else l.token&&l.refreshToken?await this.completeLogin({token:l.token,refreshToken:l.refreshToken},n,o.business):(console.error(s.red("Invalid response from server. Please try again.")),process.exit(1))}catch(a){if(w(a),e(a))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}async handle2FA(o,n,r){if("sms"===n){g(`POST ${$()}/auth/v1/two-fa/sms`);try{const{response:e}=await x(`${$()}/auth/v1/two-fa/sms`,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:JSON.stringify({})});g(`Response: ${e.status}`)}catch(l){return w(l),console.error(s.red("Could not send SMS code. Check your connection and try again.")),null}}const a="sms"===n?"Check your phone for the code":"Check your authenticator app for the code",i=r?1:3;for(let p=1;p<=i;p++){let n;r&&1===p?(n=r,g("2FA code provided via flag")):n=(await c.prompt([{type:"input",name:"auth_code",message:`Enter code (${a}):`,validate:e=>!!e.trim()||"Code is required"}])).auth_code,g(`POST ${$()}/auth/v1/2fa-check`);try{const{response:e,body:t}=await x(`${$()}/auth/v1/2fa-check`,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:JSON.stringify({auth_code:n.trim()})});if(g(`Response: ${e.status}`),y("2FA check response",t),e.ok){const e=t;if(e.token&&e.refreshToken)return{token:e.token,refreshToken:e.refreshToken}}if(e.status>=400&&e.status<500){if(console.error(s.red("Invalid code. Please try again.")),p<i){const{retry:e}=await c.prompt([{type:"confirm",name:"retry",message:"Try again?",default:!0}]);if(!e)return null}continue}C(e,t,"2FA verification failed. Please try again.")}catch(l){return w(l),e(l)?(console.log(s.yellow(t)),null):(console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),null)}}return null}async completeLogin(e,t,r){const a=A();a.start("Fetching businesses...");const i=$(),l={Authorization:`Bearer ${e.token}`};g(`GET ${i}/users/v1/business/my`);const{response:p,body:d}=await x(`${i}/users/v1/business/my`,{headers:l});g(`Response: ${p.status}`),y("Businesses response",d),p.ok||(a.stop(),w(/* @__PURE__ */new Error(`Business fetch failed: ${p.status}`)),C(p,d,"Failed to fetch businesses. Please try again."));const u=this.parseBusinesses(d),h=await this.fetchOtherBusinesses(e.token),f=this.mergeBusinesses(u,h);let m;if(a.stop(),g(`Businesses (my: ${u.length}, other: ${h.length}, merged: ${f.length})`),0===f.length&&(console.error(s.red("No businesses or teams found for your account!")),console.log(s.green("Create your first business at https://dashnex.io")),process.exit(1)),r){const e=f.find(e=>e.id===r);e||(console.error(s.red(`Business "${r}" not found.`)),process.exit(1)),m=e,g(`Selected business via flag: ${m.id} ${m.name}`)}else if(1===f.length)m=f[0],g(`Selected business: ${m.id} ${m.name}`);else{const{businessId:e}=await c.prompt([{type:"select",name:"businessId",message:"Select business:",choices:f.map(e=>({name:e.name,value:e.id}))}]);m=f.find(t=>t.id===e)||f[0],g(`Selected business: ${m.id} ${m.name}`)}a.start("Switching business..."),g(`GET ${i}/business/v1/login?_switch_business=${m.id}`);const{response:k,body:b}=await x(`${i}/business/v1/login?_switch_business=${m.id}`,{headers:l});a.stop(),g(`Response: ${k.status}`),y("Business login response",b),k.ok||(w(/* @__PURE__ */new Error(`Business login failed: ${k.status}`)),C(k,b,"Failed to switch to business. Please try again."));const E=b;E.token&&E.refreshToken||(console.error(s.red("Invalid response from server. Please try again.")),process.exit(1));const S={token:E.token,refreshToken:E.refreshToken,businessId:m.id},T={Authorization:`Bearer ${E.token}`};try{const e=v();g(`GET ${e}/business/v1/cli/settings`);const{response:t,body:s}=await x(`${e}/business/v1/cli/settings`,{headers:T});g(`Response: ${t.status}`),y("CLI settings response",s),t.ok&&s&&"object"==typeof s&&Object.assign(S,s)}catch(D){w(D)}const P=n.dirname(t);await o.pathExists(P)&&(await o.stat(P)).isFile()&&await o.remove(P),await o.ensureDir(P),await o.writeJson(t,S,{spaces:2}),g("Saved credentials to .dashnex/settings.json"),this.ensureGitignore(),console.log(s.green(`Logged in as ${m.name}`))}async fetchOtherBusinesses(e){const t=$();let s=1;const o=[];let n=0;do{const r=`${t}/users/v1/business/other?page=${s}&perPage=100`;g(`GET ${r}`);const{response:a,body:i}=await x(r,{headers:{Authorization:`Bearer ${e}`}});a.ok||(w(/* @__PURE__ */new Error(`Other businesses fetch failed: ${a.status}`)),C(a,i,"Failed to fetch teams. Please try again."));const c=this.parseBusinesses(i),l="number"==typeof i.total?i.total:c.length;if(o.push(...c),n=l,c.length<100||o.length>=n)break;s++}while(o.length<n);return o}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=n.join(process.cwd(),".gitignore");if(!(await o.pathExists(e)))return;let t=await o.readFile(e,"utf8");t.includes(".dashnex")||(t=t.trimEnd(),t.endsWith("\n")||(t+="\n"),t+="\n.dashnex\n",await o.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=h(process.cwd());if(await o.pathExists(e)){const t=await o.readJson(e);delete t.token,delete t.refreshToken,delete t.businessId,await o.writeJson(e,t,{spaces:2})}console.log(s.green("Logged out."))}},options:[]},{name:"whoami",description:"Show current logged-in business and user",handler:new class{async execute(){g("Whoami flow started");const o=await T();if(!o)return;const n=`${$()}/users/v1/`;g(`GET ${n}`);const r=A();r.start("Fetching user info...");try{const e=await fetch(n,{headers:{Authorization:`Bearer ${o.token}`}});if(r.stop(),g(`Response: ${e.status}`),!e.ok){const t=e.headers.get("content-type")??"";let o="Failed to fetch user info.";if(401===e.status||403===e.status)o="Please run 'dashnex login' to authenticate.";else if(t.includes("application/json")){const t="string"==typeof(a=await e.json().catch(()=>({}))).error?a.error:"string"==typeof a.message?a.message:void 0;t&&(o=t)}console.error(s.red(o)),process.exit(1)}const t=await e.json().catch(()=>({})),i="string"==typeof t.name?t.name:"string"==typeof t.companyName?t.companyName:"Unknown",c=t.memberUser,l=c&&"string"==typeof c.fullName?c.fullName:c&&"string"==typeof c.name?c.name:"Unknown";g(`Whoami: ${i} (${l})`),console.log(s.green(`You are logged in as ${i} (${l})`))}catch(i){if(r.stop(),w(i),i instanceof Error&&i.message.startsWith("EXIT:"))throw i;if(e(i))return void console.log(s.yellow(t));console.error(s.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={}){g("Dev flow started");try{const t=await j(process.cwd(),e);process.exit(t)}catch(t){if(t instanceof Error&&t.message.startsWith("EXIT:"))throw t;w(t),t instanceof Error?console.error(s.red(t.message)):console.error(s.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 L,options:[]},{name:"install",description:"Install dependencies using pnpm (preferred) or npm (run in DashNex application folder)",handler:new class{async execute(){g("Install flow started");const e=n.join(process.cwd(),"dashnex.json");await o.pathExists(e)||(console.error(s.red("Run this command in a DashNex Web application folder.")),process.exit(1));const t=process.cwd(),r=A();r.start("Installing dependencies...");try{const e=await W(t);r.stop(),0!==e&&process.exit(e),console.log(s.green("Dependencies installed.")),process.exit(0)}catch(a){r.stop(),w(a),a instanceof Error?console.error(s.red(a.message)):console.error(s.red("Failed to run install")),process.exit(1)}}},options:[]},ae,ie];export{ce as default};
|
|
1
|
+
import{n as e,t}from"../chunks/errors-7HJEDWYU.js";import s from"chalk";import o from"fs-extra";import n from"path";import{fileURLToPath as r}from"url";import{spawn as a}from"child_process";import i from"fs";import c from"inquirer";import l from"os";import p from"adm-zip";import d from"ignore";import{WebSocket as u}from"partysocket";import h from"ws";import{inspect as f}from"node:util";var m=process.env.DASHNEX_DIR||".dashnex",g=e=>n.join(e,m,"settings.json"),y=e=>{const t=e.toLowerCase();return t.includes("token")||t.includes("password")||"auth_code"===t},w=e=>{if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(w);const t={};for(const[s,o]of Object.entries(e))y(s)?t[s]="[REDACTED]":t[s]=w(o);return t},$=e=>{process.env.DEBUG&&console.log(s.dim(e))},v=(e,t)=>{if(process.env.DEBUG){const o=w(t);console.log(s.dim(`${e}: ${JSON.stringify(o,null,2)}`))}},k=e=>{process.env.DEBUG&&e instanceof Error&&(console.log(s.dim(`Error: ${e.message}`)),e.stack&&console.log(s.dim(`Stack: ${e.stack}`)))},x=()=>"qa"===process.env.APPLICATION_ENV?"https://api.qa.dashnex.com":"https://api.dashnex.com",b=()=>"qa"===process.env.APPLICATION_ENV?"https://api.business.qa.dashnex.com":"https://api.business.dashnex.com",E={qa:"https://3atfynmu2w.us-east-1.awsapprunner.com",live:"https://rkwbzvhcwh.us-east-1.awsapprunner.com"},S=async(e,t={})=>{const s=await fetch(e,{...t,headers:{"Content-Type":"application/json",...t.headers}});return{response:s,body:await s.json().catch(()=>({}))}},T=()=>{console.error(s.red("Please run 'dashnex login' to authenticate.")),console.error(s.green("If you don't have an account yet, create one at https://dashnex.io"))},P=async(e,t)=>{$(`POST ${x()}/auth/v1/token/refresh`);const{response:s,body:n}=await S(`${x()}/auth/v1/token/refresh`,{method:"POST",body:JSON.stringify({refreshToken:e})});if($(`Response: ${s.status}`),v("Refresh response",n),!s.ok)return $("Token refresh failed"),null;const r=n;if(!r.token||!r.refreshToken)return $("Refresh response missing tokens"),null;const a=await o.readJson(t);return a.token=r.token,a.refreshToken=r.refreshToken,await o.writeJson(t,a,{spaces:2}),$("Updated settings.json with new tokens"),C(r.token,r.refreshToken,t,{...a,token:r.token,refreshToken:r.refreshToken})},C=async(e,t,s,o)=>{if(((e,t=30)=>{try{const s=e.split(".");if(3!==s.length)return!1;const o=JSON.parse(Buffer.from(s[1],"base64url").toString());if("number"!=typeof o.exp)return!1;const n=Math.floor(Date.now()/1e3),r=o.exp-t<=n;return r&&$(`Token expired or expiring soon (exp: ${o.exp}, now: ${n})`),r}catch{return!1}})(e)){if(!t)return $("Token expired, no refreshToken available"),null;$("Token expired, refreshing proactively");try{return await P(t,s)}catch(n){return k(n),null}}$(`GET ${x()}/users/v1/`);try{const{response:n,body:r}=await S(`${x()}/users/v1/`,{headers:{Authorization:`Bearer ${e}`}});if($(`Response: ${n.status}`),v("Users response",r),n.ok){const t=r;if("string"==typeof t.name&&o.businessId)return $(`Token valid, Already logged in as ${t.name}`),{token:e,businessId:o.businessId,userName:t.name}}return t?($("Users API rejected token, refreshing"),await P(t,s)):($("Token invalid, no refreshToken available"),null)}catch(n){return k(n),null}},A=async(e={})=>{const{exitOnFailure:t=!0,dashnexPath:s}=e,r=s??await(async e=>{let t=n.resolve(e);for(;;){const e=g(t);if(await o.pathExists(e))return e;const s=n.dirname(t);if(s===t)return null;t=s}})(process.cwd());if(!r||!(await o.pathExists(r)))return $(".dashnex/settings.json not found"),t&&(T(),process.exit(1)),null;let a;$(`Found settings at ${r}`);try{a=await o.readJson(r)}catch{return $("settings.json parse failed"),t&&(T(),process.exit(1)),null}const{token:i,refreshToken:c,businessId:l}=a;if(!i)return $("settings.json missing token"),t&&(T(),process.exit(1)),null;const p=await C(i,c,r,a);return p||(t&&(T(),process.exit(1)),null)},D=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],N=(e="")=>{if(process.env.DASHNEX_CI)return{start:()=>{},stop:()=>{},text:()=>{}};let t=null,s=0,o=e;const n=()=>{const e=D[s%D.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()}}},I=(e,t,o)=>{const n=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);let r=o;429===e.status?r="Too many requests. Please wait a moment and try again.":e.status>=500?r="DashNex API is temporarily unavailable. Please try again later.":n&&(r=n),console.error(s.red(r)),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"],O=(e,t)=>t.length>0&&t.some(t=>t.test(e)),F=(e,t)=>{let s="";return{write:o=>{const n="string"==typeof o?o:o.toString();s+=n;const r=s.split(/\r?\n/);s=r.pop()??"";for(const s of r){const o=s.trim();o?O(o,t)?$(`Filtered: ${o}`):e.write(s+"\n"):$("Filtered: <empty line>")}},flush:()=>{const o=s.trim();if(o){if(O(o,t))return $(`Filtered: ${o}`),void(s="");e.write(s),s=""}else s=""}}},B=async(e,t={})=>{const s=n.join(e,"dashnex.json"),r=n.join(e,"package.json");if($(`Checking for dashnex.json at: ${s}`),!(await o.pathExists(s)))throw new Error("Run this command in a DashNex Web application folder.");if($("dashnex.json found, checking for package.json"),!(await o.pathExists(r)))throw new Error("package.json is missing.");let i;$("package.json found, checking for dev script");try{i=await o.readJson(r)}catch(p){throw k(p),new Error("Failed to read package.json.")}if(!i.scripts||!i.scripts.dev)throw new Error('The "dev" script is missing from package.json. Please add a "dev" script to package.json.');$("dev script found, checking for npm availability");const c=await(async e=>new Promise(t=>{const s=a(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>{t(!1)}),s.on("close",e=>{t(0===e)})}))("npm");if($(`npm available: ${c}`),!c)throw new Error("npm is not available. Please install npm to continue.");const l=t.https?["--","--experimental-https"]:[];return $(`npm available, executing: npm run dev in ${e}${t.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=a(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=>{k(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",l,e,(()=>{const e=[];for(const t of j)try{e.push(new RegExp(t))}catch{$(`Invalid dev output filter pattern ignored: ${t}`)}return e})())},R=async e=>new Promise(t=>{const s=a(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>{t(!1)}),s.on("close",e=>{t(0===e)})}),L=async e=>{let t;if(await R("pnpm"))t="pnpm install",$("Using package manager: pnpm");else{if(!(await R("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",$("Using package manager: npm (with --legacy-peer-deps for DashNex peer-dep overlap)")}return $(`Executing: ${t} in ${e}`),new Promise((s,o)=>{const n=[],r=[],i=a(t,{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=>{k(e),o(e)}),i.on("close",e=>{const t=null===e?0:e;0!==t&&(n.length&&process.stdout.write(Buffer.concat(n)),r.length&&process.stderr.write(Buffer.concat(r))),s(t)})})},z="Run this command in a DashNex Web application folder.",U=e=>{const t=n.join(e,"dashnex.json");return o.pathExistsSync(t)},M=(e,t=!1)=>{t||console.log(s.cyan(e))},J=(e,t,s={})=>{const o=`${e} ${t.join(" ")}`,n=!0===s.silent;return new Promise((t,s)=>{$(`Running: ${o}`);const r=a(o,{stdio:n?["ignore","pipe","pipe"]:"inherit",cwd:process.cwd(),shell:!0});r.on("error",e=>{k(e),s(e)}),r.on("close",s=>{$(`${e} exited with code ${s}`),t(null===s?1:s)})})},W=(e,t)=>new Promise((s,o)=>{$(`Running: ${e} ${t.join(" ")}`);const n=a(e,t,{cwd:process.cwd()});let r="";n.stdout?.on("data",e=>{r+=e.toString()}),n.stderr?.on("data",e=>{r+=e.toString()}),n.on("error",e=>{k(e),o(e)}),n.on("close",t=>{$(`${e} exited with code ${t}`),s({exitCode:null===t?1:t,output:r})})}),G=async e=>{$("Running check: install");try{return 0===await L(process.cwd())}catch(t){return k(t),!e&&t instanceof Error&&console.error(s.red(t.message)),!1}},_=async()=>{try{const{output:e}=await W(process.execPath,[process.argv[1],"db","migrate","--help"]);return e.includes("Usage: dashnex db migrate")}catch(e){return k(e),!1}},q=async e=>{$("Running check: db migrate");try{const{exitCode:t,output:s}=await W(process.execPath,[process.argv[1],"db","migrate"]);return 0===t||(s.includes("Unknown command")?($("db migrate command is not available, skipping"),!0):(!e&&s.trim().length>0&&process.stderr.write(s),!1))}catch(t){return k(t),!0}},X=e=>new Promise(t=>{const s=a(`${e} --version`,{stdio:"ignore",shell:!0});s.on("error",()=>t(!1)),s.on("close",e=>t(0===e))}),H=[{name:"TypeScript",command:"npx",args:["tsc","--noEmit"],notFoundMessage:"TypeScript is not available. Please install it with: npm install -D typescript"}],Y=class{async execute(){$("Check flow started"),U(process.cwd())||(console.error(s.red(z)),process.exit(1)),M("Checking dependencies..."),await G(!1)||(console.error(s.red("Check failed.")),process.exit(1)),$(`Running ${H.length} check(s)`);for(const t of H){$(`Running check: ${t.name}`),M(`Checking ${t.name}...`),await X(t.command)||(console.error(s.red(t.notFoundMessage)),process.exit(1));try{0!==await J(t.command,t.args)&&(console.error(s.red("Check failed.")),process.exit(1))}catch(e){k(e),console.error(s.red(t.notFoundMessage)),process.exit(1)}}await _()?(M("Checking database migrations..."),await q(!1)||(console.error(s.red("Check failed.")),process.exit(1))):$("db migrate command is not available, skipping"),console.log(s.green("All checks passed."))}async run(e=!1){if($("Running checks (called from push)"),!U(process.cwd()))return e||console.error(s.red(z)),!1;if(M("Checking dependencies...",e),!(await G(e)))return!1;const t=e?{silent:!0}:void 0;for(const n of H){if($(`Running check: ${n.name}`),M(`Checking ${n.name}...`,e),!(await X(n.command)))return console.error(s.red(n.notFoundMessage)),!1;try{if(0!==await J(n.command,n.args,t))return!1}catch(o){return k(o),console.error(s.red(n.notFoundMessage)),!1}}if(await _()){if(M("Checking database migrations...",e),!(await q(e)))return!1}else $("db migrate command is not available, skipping");return e||console.log(s.green("All checks passed.")),!0}},V=async(e,t)=>{const{install:o}=await c.prompt([{type:"confirm",name:"install",message:"Install dependencies?",default:!0}]);if(!o){if(n.resolve(e)!==n.resolve(t)){const o=n.relative(t,e);console.log(s.cyan(`Run "cd ${o}" to change to the application folder.`))}return}try{const t=N();t.start("Installing dependencies...");try{const s=await L(e);if(t.stop(),0!==s)return void $(`install exited with code ${s}`)}catch(l){throw t.stop(),l}}catch(l){return k(l),void console.error(s.red(l instanceof Error?l.message:"Failed to run install."))}const{migrate:r}=await c.prompt([{type:"confirm",name:"migrate",message:"Create or update database?",default:!0}]);if(!r)return;$(`Running dashnex db migrate in ${e}`);try{const t=N();t.start("Creating or updating database...");try{const s=await((e,t,s)=>{const o=`${n.join(e,"node_modules",".bin")}${n.delimiter}${process.env.PATH??""}`,r={...process.env,PATH:o};return new Promise((o,n)=>{const i=a(t,{cwd:e,shell:!0,stdio:"inherit",env:s?{...r,...s}:r});i.on("error",e=>{k(e),n(e)}),i.on("close",e=>{o(null===e?0:e)})})})(e,"dashnex db migrate");if(t.stop(),0!==s)return void $(`dashnex db migrate exited with code ${s}`)}catch(l){throw t.stop(),l}}catch(l){return k(l),void console.error(s.red("Failed to run dashnex db migrate."))}const{dev:i}=await c.prompt([{type:"confirm",name:"dev",message:"Run development server?",default:!0}]);if(i)try{await B(e)}catch(l){k(l),console.error(s.red(l instanceof Error?l.message:"Failed to run dev server."))}},K=(e,t)=>{if(e.length!==t.length)return`local ${e.length} bytes, zip ${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")} zip=0x${t[o].toString(16).padStart(2,"0")})`}return`size ${s} matches; no byte difference (unexpected)`},Z=async(e,t)=>{let s;try{s=await o.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, zip ${t.length} bytes`};const n=await o.readFile(e);return 0===Buffer.compare(n,t)?{kind:"identical"}:{kind:"different",reason:K(n,t)}},Q=async e=>{const{choice:t}=await c.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},ee=(e,t)=>n.resolve(e)===n.resolve(t)?"Application is successfully pulled.":`Application is successfully pulled into ${n.relative(t,e)}.`,te=class{async execute(r={}){$("Pull flow started");const a=await A();if(!a)return;const i=process.cwd();let d;if(r.folder)d=r.folder.trim()||".",$(`Folder argument provided: ${d}`);else{$("No folder argument, prompting user");const{folder:e}=await c.prompt([{type:"input",name:"folder",message:"Which folder to pull the application to?",default:"."}]);d=e.trim()||"."}const u=n.resolve(i,d);$(`Target folder resolved: ${u}`);try{const e=await o.lstat(u).catch(()=>null);e&&!e.isDirectory()&&(console.error(s.red(`Cannot pull into ${u}: path exists and is not a directory.`)),process.exit(1)),await o.ensureDir(u),$(`Target folder ensured: ${u}`)}catch(y){k(y);const e=y instanceof Error?y.message:"Unknown error";console.error(s.red(`Cannot create folder ${u}: ${e}`)),process.exit(1)}const h=`${b()}/business/v1/cli/pull`;$(`GET ${h}`);const f=n.join(l.tmpdir(),`dashnex-pull-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),m=N();m.start("Pulling application...");try{const e=await fetch(h,{headers:{Authorization:`Bearer ${a.token}`}});if($(`Response: ${e.status}`),!e.ok){m.stop();const t=e.headers.get("content-type")??"";let o="Failed to pull application.";if(401===e.status||403===e.status)o="Please run 'dashnex login' to authenticate.";else if(404===e.status)o="Business has no application. Run 'dashnex app create' to create one.";else if(t.includes("application/json")){const t="string"==typeof(g=await e.json().catch(()=>({}))).error?g.error:"string"==typeof g.message?g.message:void 0;t&&(o=t)}console.error(s.red(o)),process.exit(1)}m.text("Downloading...");const t=Buffer.from(await e.arrayBuffer());await o.writeFile(f,t),$("Zip written to temp file"),m.text("Extracting...");const c=new p(f).getEntries().filter(e=>!e.isDirectory);$(`Zip has ${c.length} file entries`);const l=r.yes||"1"===process.env.DASHNEX_CI;let d=l?"all":"prompt",w=!1,v=0,x=0,b=0,E=0,S=0;const T=async(e,t,s)=>{try{return await o.ensureDir(n.dirname(e)),await o.writeFile(e,t),s&&await o.chmod(e,s),!0}catch(y){return k(y),!1}};for(const o of c){const e=o.getData(),t=n.join(u,o.entryName),r=n.relative(u,t)||o.entryName,a=(o.header.attr??0)>>16&4095,i=await Z(t,e);if($(`Entry ${o.entryName}: ${i.kind}${i.reason?` (${i.reason})`:""}`),"identical"===i.kind){E+=1;continue}if("new"===i.kind){await T(t,e,a)?v+=1:S+=1;continue}let c=!1;if("all"===d)c=!0;else if("none"===d)c=!1;else{m.stop(),w||(console.log(s.dim("Y = yes (default), n = skip, a = overwrite all, s = skip all, h = help")),w=!0);const e=await Q(r);$(`Entry ${o.entryName}: user chose ${e}`),"yes"===e?c=!0:"no"===e?c=!1:"all"===e?(d="all",c=!0):(d="none",c=!1),m.start("Extracting...")}c?await T(t,e,a)?x+=1:S+=1:b+=1}m.stop(),$(`Pull summary: ${v} new, ${x} overwritten, ${b} skipped, ${E} unchanged, ${S} failed`);const P=[`${v} new`,`${x} overwritten`,`${b} skipped`,`${E} unchanged`];S>0&&P.push(`${S} failed`),console.log(s.cyan(`Pulled: ${P.join(", ")}`)),n.resolve(u)!==n.resolve(i)?(console.log(s.green(ee(u,i))),process.chdir(u),$(`Changed working directory to ${u}`)):console.log(s.green(ee(u,i))),S>0&&(console.error(s.red(`${S} file(s) failed to write. See DEBUG output for details.`)),process.exit(1)),l?$("Non-interactive mode (--yes or --ci), skipping post-pull child commands"):await V(u,i)}catch(y){if(m.stop(),k(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(e(y))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}finally{await o.remove(f).catch(()=>{}),$("Temp zip removed")}var g}},se=async e=>{const t=`${b()}/business/v1/agreements/payment-processing/status`;$(`GET ${t}`);const o=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});if($(`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(s.red(`You need to accept Master Payment Processing Agreement first by visiting this link: ${n}`)),!1},oe=async(e,t={})=>{const o=t.ciMode??!1;return!!(await se(e))&&!!(await(async(e,t)=>{const o=`${b()}/business/v1/tos/latest`;$(`GET ${o}`);const n=await fetch(o,{headers:{Authorization:`Bearer ${e}`}});if($(`TOS latest response: ${n.status}`),n.ok)return!0;if(404!==n.status)return!0;const r=`${b()}/business/v1/tos/current`;$(`GET ${r}`);const a=await fetch(r,{headers:{Authorization:`Bearer ${e}`}});if($(`TOS current response: ${a.status}`),!a.ok)return $("Could not fetch current TOS, skipping check"),!0;const i=await a.json().catch(()=>({})),l=i.version??"unknown";if(i.text&&(console.log(s.dim("─".repeat(60))),console.log(s.bold(`Terms of Service ${l}`)),console.log(s.dim("─".repeat(60))),console.log(i.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(s.dim("─".repeat(60)))),t)return console.log(s.yellow(`By proceeding you accept the Terms of Service ${l}.`)),!0;const{accept:p}=await c.prompt([{type:"confirm",name:"accept",message:`By creating an application you accept the Terms of Service ${l}. Continue?`,default:!0}]);if(!p)return console.log(s.yellow("Cancelled.")),!1;try{const t=`${b()}/business/v1/tos/${i.id}/accept`;$(`POST ${t}`),await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch(d){k(d)}return!0})(e,o))},ne=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,re=e=>new Promise(t=>setTimeout(t,e)),ae=e=>e.appFullCustomDomain?e.appFullCustomDomain:e.subdomain?"qa"===(process.env.APPLICATION_ENV??"")?`https://${e.subdomain}.dashnex.dev`:`https://${e.subdomain}.dashnexcloud.com`:null,ie=3e5,ce=99,le=e=>new Promise(t=>setTimeout(t,e)),pe=async(e,t,o,n)=>{const r=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"text/event-stream"}});if($(`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(s.red(t)),new Error(`HTTP ${e}: ${t}`)}if(!r.body)throw new Error("Response body is null");$("SSE connection established successfully"),n?.();const a=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 r=s.split("\n");s=r.pop()||"";let a="";for(const e of r)e.startsWith("data: ")?a=e.slice(6):""===e&&a&&(yield{data:a},a="")}if(s.startsWith("data: ")){const e=s.slice(6);e&&(yield{data:e})}}(a))try{if(!e.data){$("Received empty SSE event");continue}const t=JSON.parse(e.data);$(`SSE message received: ${JSON.stringify(t)}`),o(t)}catch(i){k(i),$(`Failed to parse SSE event data: ${e.data}`)}}finally{a.releaseLock()}},de=class{async execute(o={}){$("Deploy flow started");const n=await A();if(!n)return;if(!1!==o.check?($("Running pre-deploy checks"),await(new Y).run(!1)||(console.error(s.red("Deploy aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):$("Skipping pre-deploy checks (--no-check)"),!(await oe(n.token,{ciMode:!0})))return;const r=`${E[process.env.APPLICATION_ENV||"live"]||E.live}/business/v1/applications/deploy`;$(`GET ${r} (SSE)`);let a=0,i="",c=!1,l=0,p=!1;const d=N();let u=0,h=0,f=null;const m=(e,t)=>{const s=Math.round(e);d.text(`[${s}%] ${t}`)},g=()=>{y();const e=a,t=Date.now(),s=ie*((ce-e)/ce);f=setInterval(()=>{const o=Date.now()-t;let n;if(h>t){const e=Date.now()-h,t=ce-u,s=3030.3030303030305*t;n=Math.min(u+e/s*t,ce)}else n=Math.min(e+o/s*(ce-e),ce);n>a&&(a=n,m(a,i))},200)},y=()=>{f&&(clearInterval(f),f=null)};let w=!1;const v=e=>{if(p=!0,"string"==typeof e.error)return y(),d.stop(),console.error(s.red(e.error)),c=!0,void(w=!0);"string"==typeof e.message&&(i=e.message),"number"==typeof e.progress&&(u=e.progress,h=Date.now(),e.progress>a&&(a=e.progress)),"string"!=typeof e.message&&"number"!=typeof e.progress||(a>=100?(y(),d.stop(),c=!0):m(a,i))};for(;l<=5;)try{return p?m(a,i):d.start("Connecting..."),g(),await pe(r,n.token,v,()=>{p||(d.text(`[${Math.round(a)}%] Deployment in progress...`),i="Deployment in progress...")}),y(),d.stop(),$("SSE connection closed"),w&&process.exit(1),void(c&&await this.showDeployedUrl(n.token))}catch(x){if(y(),k(x),$(`SSE connection error: ${x}`),c)return d.stop(),void(w&&process.exit(1));if(e(x))return d.stop(),void console.log(s.yellow(t));x instanceof Error&&x.message.startsWith("HTTP")&&(d.stop(),console.error(s.red("Could not complete deployment. Check your connection and try again.")),process.exit(1)),l++,l>5&&(d.stop(),console.error(s.red("Deployment failed. Maximum reconnection attempts exceeded.")),process.exit(1));const o=Math.min(1e3*Math.pow(2,l-1),3e4);$(`Connection error. Reconnecting in ${o/1e3}s... (attempt ${l}/5)`),await le(o)}}async showDeployedUrl(e){try{const t=`${b()}/business/v1/applications`;$(`GET ${t} (for deployed URL)`);const o=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)return;const n=await o.json().catch(()=>({})),r=ae({subdomain:n.subdomain,appFullCustomDomain:n.appFullCustomDomain});r&&console.log(`Application is deployed to ${s.cyan(r)}`)}catch(t){k(t)}}},ue=[".dashnex",".git",".vinext",".wrangler","wrangler.jsonc"],he=async(e,t)=>{const s=[],r=await o.readdir(e,{withFileTypes:!0});for(const o of r){const r=n.relative(process.cwd(),n.join(e,o.name)).split(n.sep).join("/");if(ue.some(e=>r===e||r.startsWith(`${e}/`)||r.endsWith(`/${e}`)))continue;if(t.ignores(r))continue;const a=n.join(e,o.name);if(o.isDirectory()){const e=await he(a,t);s.push(...e)}else o.isFile()&&s.push(a)}return s},fe=class extends Error{},me=class extends Error{},ge=class extends Error{},ye="/business/v1/cli/tail-token";async function we(e,t={}){const s=`${b()}${ye}${t.debug?"?debug=1":""}`;try{await fetch(s,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})}catch{}}var $e=["log","info","warn","error","debug"],ve={error:4,warn:3,log:2,info:2,debug:1};function ke(e){return"string"==typeof e&&$e.includes(e)}function xe(e){return e.map(e=>"string"==typeof e?e:function(e){try{return JSON.stringify(e)}catch{return String(e)}}(e)).join(" ")}function be(e){return e<10?`0${e}`:String(e)}function Ee(e){const t=new Date(e);return`${be(t.getHours())}:${be(t.getMinutes())}:${be(t.getSeconds())}.${s=t.getMilliseconds(),s<10?`00${s}`:s<100?`0${s}`:String(s)}`;var s}function Se(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 f(e,{colors:t,depth:2,breakLength:120})}var Te={error:e=>s.red(e),warn:e=>s.yellow(e),debug:e=>s.dim(e),log:e=>e,info:e=>e};function Pe(e,t){const o=t.color?s.dim(Ee(e.ts)):Ee(e.ts),n=e.level.toUpperCase().padEnd(5),r=[o,t.color?Te[e.level](n):n];r.push(e.args.map(e=>Se(e,t.color)).join(" "));let a=r.join(" ");if(e.truncated){const e=" …(truncated)";a+=t.color?s.dim(e):e}return a}function Ce(e,t,s){let o;try{o=JSON.parse(e)}catch{return{kind:"malformed",raw:e}}if("object"!=typeof o||null===o||!ke(o.level))return{kind:"malformed",raw:e};const n=o;return Array.isArray(n.args)||(n.args=void 0===n.args?[]:[n.args]),r=n.level,a=t.minLevel,ve[r]>=ve[a]&&function(e,t){return!t||t.test(xe(e.args))}(n,t.filter)?{kind:"line",line:Pe(n,s)}:{kind:"filtered"};var r,a}var Ae=new Set([4401,4403]);var De={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,s=5e3,o=6e4){const n=Date.now();let r=0;for(;Date.now()-n<o;){r++,$(`Polling application status (attempt ${r})...`);try{const s=await fetch(e,{headers:{Authorization:`Bearer ${t}`}});if($(`Poll response: ${s.status}`),200===s.status){const e=await s.json();if($(`Poll response body status: ${e.status}`),"creating"!==e.status)return $(`Application status is "${e.status}", creation complete`),{ready:!0,status:e.status};$('Application status is still "creating", continuing to poll...')}}catch(a){k(a),$(`Poll attempt ${r} failed with network error`)}await re(s)}return{ready:!1}}async execute(o={}){$("Create flow started");const n=await A();if(!n)return;$("Auth valid, checking if business already has application");const r=N(),a=`${b()}/business/v1/applications`;$(`GET ${a}`),r.start("Checking application status...");try{const e=await fetch(a,{headers:{Authorization:`Bearer ${n.token}`}});r.stop(),$(`Applications response: ${e.status}`),$(`Applications response body: ${await e.text()}`),404!==e.status&&(console.error(s.red("Business already has an application. Run 'dashnex app pull' to pull the existing one.")),process.exit(1))}catch(m){if(r.stop(),k(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(e(m))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}$("No existing application, checking agreements");const i=void 0!==o.subdomain;if(!(await oe(n.token,{ciMode:i})))return;let l;$("Agreements checked, proceeding to subdomain prompt");const p=e=>`${b()}/business/v1/applications/check-subdomain?subdomain=${encodeURIComponent(e)}`;let d=o.subdomain?.trim();for(;;){if(d)l=d,d=void 0,$(`Subdomain provided via flag: ${l}`);else{if(i)return console.error(s.red("Subdomain is not available.")),void process.exit(1);{const{sub:e}=await c.prompt([{type:"input",name:"sub",message:"Pick your subdomain:",validate:e=>!!e.trim()||"Subdomain is required"}]);l=e.trim()}}$(`Checking subdomain: ${l}`);const o=p(l);$(`GET ${o}`),r.start("Checking subdomain...");try{const e=await fetch(o,{headers:{Authorization:`Bearer ${n.token}`}});r.stop(),$(`Check subdomain response: ${e.status}`);const t=await e.text();if($(`Check subdomain response body: ${t}`),!e.ok){const o=e.headers.get("content-type")??"";let n="Failed to check subdomain availability.";if(401!==e.status&&403!==e.status||(n="Please run 'dashnex login' to authenticate.",console.error(s.red(n)),process.exit(1)),o.includes("application/json")){const e=JSON.parse(t);$(`Check subdomain error body: ${JSON.stringify(e)}`);const s=ne(e);s&&(n=s)}console.error(s.red(n));continue}const a=JSON.parse(t);if($(`Check subdomain parsed body: ${JSON.stringify(a)}`),a.available){$(`Subdomain ${l} is available`);break}console.error(s.red("Subdomain is not available. Please choose a different one."))}catch(m){if(r.stop(),k(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(e(m))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}const u=`${b()}/business/v1/cli/create`;$(`POST ${u}`);const h={subdomain:l};o.template&&(h.template=o.template,$(`Template: ${o.template}`));const f=JSON.stringify(h);$(`Create request body: ${f}`),r.start("Creating application...");try{const a=await fetch(u,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:f});r.stop(),$(`Create response: ${a.status}`);const l=await a.text();if($(`Create response body: ${l}`),503===a.status){$("Create returned 503, polling for application creation..."),r.start("Waiting for application to be ready...");const e=`${b()}/business/v1/applications`,t=await this.pollApplicationCreated(e,n.token);r.stop(),t.ready||(console.error(s.red("Application creation is taking longer than expected. Try again later or run 'dashnex app pull' to check.")),process.exit(1)),"failed"===t.status&&(console.error(s.red("Application creation failed. Please try again.")),process.exit(1)),$("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);$(`Create error body parsed: ${JSON.stringify(e)}`);const s=ne(e);s&&(t=s)}console.error(s.red(t)),process.exit(1)}let p;if($("Application created successfully"),!0===o.pull?(p=!0,$("--pull flag set, pulling without prompting")):!1===o.pull?(p=!1,$("--no-pull flag set, skipping pull")):i?(p=!1,$("CI mode (--subdomain), skipping pull")):(p=(await c.prompt([{type:"confirm",name:"pull",message:"Pull the application locally?",default:!0}])).pull,$(`User chose to pull: ${p}`)),p){$("Running pull flow");try{await(new te).execute()}catch(m){if(k(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(e(m))return void console.log(s.yellow(t));console.error(s.red("Failed to pull application."))}}else console.log(s.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(m){if(r.stop(),k(m),m instanceof Error&&m.message.startsWith("EXIT:"))throw m;if(e(m))return void console.log(s.yellow(t));console.error(s.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 te,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(r={}){$("Push flow started"),!1!==r.check?($("Running pre-push checks"),await(new Y).run(!1)||(console.error(s.red("Push aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):$("Skipping pre-push checks (--no-check)");const a=await A();if(!a)return;const i=process.cwd(),u=n.join(i,".gitignore"),h=d();if(h.add(ue),await o.pathExists(u)){const e=await o.readFile(u,"utf8");h.add(e)}$("Building file list");const f=await he(i,h);$(`Including ${f.length} files`);const m=new p;for(const e of f){const t=n.relative(i,e).split(n.sep).join("/"),s="."===n.dirname(t)?"":n.dirname(t),o=n.basename(t);m.addLocalFile(e,s,o)}const g=n.join(l.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),y=N();try{y.start("Packaging application..."),m.writeZip(g),$(`Zip written to ${g}`);const e=`${b()}/business/v1/cli/push`;$(`POST ${e}`);const t=await o.readFile(g),n=new Blob([t],{type:"application/zip"}),i=new FormData;i.append("file",n,"archive.zip");const l=new Headers;l.set("Authorization",`Bearer ${a.token}`),y.text("Uploading...");const p=await fetch(e,{method:"POST",headers:l,body:i});if(y.stop(),$(`Response: ${p.status}`),!p.ok){const e=p.headers.get("content-type")??"";let t="Failed to push application.";if(401===p.status||403===p.status)t="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e="string"==typeof(w=await p.json().catch(()=>({}))).error?w.error:"string"==typeof w.message?w.message:void 0;e&&(t=e)}console.error(s.red(t)),process.exit(1)}let d;console.log(s.green("Application pushed successfully.")),void 0!==r.deploy?(d=r.deploy,$(`Deploy decided via flag: ${d}`)):(d=(await c.prompt([{type:"confirm",name:"deploy",message:"Deploy the application?",default:!0}])).deploy,$(`User chose to deploy: ${d}`)),d&&($("Running deploy flow"),await(new de).execute())}catch(v){if(y.stop(),k(v),v instanceof Error&&v.message.startsWith("EXIT:"))throw v;if(e(v))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}finally{await o.remove(g).catch(()=>{}),$("Temp zip removed")}var w}},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"}]},{name:"delete",description:"Delete application from DashNex",handler:new class{async execute(o={}){if($("Delete flow started"),!o.yes){const{confirm:e}=await c.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 $("User cancelled deletion"),void console.log(s.yellow("Deletion cancelled."))}const n=await A();if(!n)return;const r=`${b()}/business/v1/applications`;$(`DELETE ${r}`);const a=N();a.start("Deleting application...");try{const e=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}});if(a.stop(),$(`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(s.red(o)),process.exit(1)}const t=await e.json().catch(()=>({})),o="string"==typeof t.message?t.message:"Application deleted successfully.";$("Application deleted successfully"),console.log(s.green(o))}catch(i){if(a.stop(),k(i),i instanceof Error&&i.message.startsWith("EXIT:"))throw i;if(e(i))return void console.log(s.yellow(t));console.error(s.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 de,options:[{flags:"--no-check",description:"Skip pre-deploy checks"}]},{name:"status",description:"Show current application status",handler:new class{async execute(){$("Status flow started");const o=await A();if(!o)return;const n=`${b()}/business/v1/applications`;$(`GET ${n}`);const r=N();r.start("Fetching application status...");try{const e=await fetch(n,{headers:{Authorization:`Bearer ${o.token}`}});if(r.stop(),$(`Response: ${e.status}`),404===e.status)return void console.log(s.yellow("Application not created"));if(!e.ok){const t=e.headers.get("content-type")??"";let o="Failed to fetch application status.";if(401===e.status||403===e.status)o="Please run 'dashnex login' to authenticate.";else if(t.includes("application/json")){const t=await e.json().catch(()=>({}));"string"==typeof t.error?o=t.error:"string"==typeof t.message&&(o=t.message)}console.error(s.red(o)),process.exit(1)}const t=await e.json().catch(()=>({}));$(`Application body: ${JSON.stringify(t)}`);const a=t.status??"unknown";console.log(`Status: ${s.cyan(a)}`);const i=ae(t);i&&console.log(`URL: ${s.cyan(i)}`)}catch(a){if(r.stop(),k(a),a instanceof Error&&a.message.startsWith("EXIT:"))throw a;if(e(a))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]},{name:"tail",description:"Stream live console/debug logs from the deployed worker (Ctrl+C to stop)",handler:new class{async execute(e={}){const t=e.level??"log";ke(t)||(console.error(s.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(s.red(`Invalid --filter regular expression: ${e.filter}`)),process.exit(1)}const n=await A();if(!n)return;const r=!!e.debug;let a;try{a=await async function(e,t={}){const s=`${b()}${ye}`;$(`POST ${s}${t.debug?" (debug)":""}`);const o=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({debug:!!t.debug})});if($(`Response: ${o.status}`),401===o.status||403===o.status)throw new fe("Not authorised to tail this application.");if(404===o.status)throw new me("Business has no application, or the tail endpoint is unavailable.");if(!o.ok)throw new ge(`Failed to start tail (status ${o.status}).`);const n=await o.json().catch(()=>({}));if(!n.token||!n.workerUrl)throw new ge("Malformed tail-token response from the platform.");return{token:n.token,workerUrl:n.workerUrl,expiresAt:"number"==typeof n.expiresAt?n.expiresAt:0}}(n.token,{debug:r})}catch(v){k(v),v instanceof fe&&(console.error(s.red(v.message)),process.exit(1)),v instanceof me&&(console.error(s.red(v.message)),process.exit(2)),console.error(s.red(v instanceof Error?v.message:"Could not start tail. Check your connection.")),process.exit(3)}const i={color:!!process.stdout.isTTY},c={minLevel:t,filter:o},l=(p=a.workerUrl,`${/^(localhost|127\.0\.0\.1)/.test(p)?"ws":"wss"}://${p}/api/realtime/tail`);var p;const d=`dashnex.tail.token.${a.token}`;console.log(s.dim(`Tailing ${a.workerUrl} — Ctrl+C to stop.`)),r&&console.log(s.dim("Debug logging enabled on the worker (DEBUG=1); may take a minute to take effect."));let f=!1,m=Date.now();const g=setInterval(()=>{f||Date.now()-m>=3e4&&(console.log(s.dim("(no logs in 30s)")),m=Date.now())},5e3),y=new u(l,d,{WebSocket:h,connectionTimeout:1e4,maxReconnectionDelay:16e3}),w=async e=>{if(!f){f=!0,clearInterval(g);try{y.close()}catch{}await Promise.race([we(n.token,{debug:r}),new Promise(e=>setTimeout(e,3e3))]),process.exit(e)}};process.on("SIGINT",()=>{console.log(),w(0)}),y.binaryType="arraybuffer",y.addEventListener("message",e=>{m=Date.now();const t=Ce("string"==typeof e.data?e.data:"",c,i);"line"===t.kind?console.log(t.line):"malformed"===t.kind&&console.error(s.dim(`[malformed frame] ${t.raw}`))}),y.addEventListener("close",e=>{if(!f)return Ae.has(e.code)?(console.error(s.red("Tail token was rejected (auth). Exiting.")),void w(1)):void $(`socket closed (code ${e.code}); reconnecting…`)}),y.addEventListener("error",e=>{$(`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"}]}]},Ne={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(){$("Secrets list flow started");const o=await A();if(!o)return;const n=`${b()}/business/v1/cli/secrets`;$(`GET ${n}`);const r=N();r.start("Fetching secrets...");try{const e=await fetch(n,{headers:{Authorization:`Bearer ${o.token}`}});if(r.stop(),$(`Response: ${e.status}`),!e.ok){let t="Failed to fetch secrets.";401===e.status||403===e.status?t="Please run 'dashnex login' to authenticate.":404===e.status?t="Business has no application.":502===e.status&&(t="Error fetching secrets. Make sure your application is deployed."),console.error(s.red(t)),process.exit(1)}const t=(await e.json()).secrets??[];if(0===t.length)return void console.log(s.yellow("No secrets set."));console.log(s.bold(`\nSecrets (${t.length}):\n`)),t.forEach(({name:e})=>{console.log(` ${s.cyan(e)}`)}),console.log("")}catch(a){if(r.stop(),k(a),a instanceof Error&&a.message.startsWith("EXIT:"))throw a;if(e(a))return void console.log(s.yellow(t));console.error(s.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(o={}){$("Secrets set flow started");let{name:n,value:r}=o;const a="1"===process.env.DASHNEX_CI;n||(a&&(console.error(s.red("--name is required in CI mode (--ci).")),process.exit(1)),n=(await c.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim()),r||(a&&(console.error(s.red("--value is required in CI mode (--ci).")),process.exit(1)),r=(await c.prompt([{type:"password",name:"value",message:`Enter value for ${n}:`,mask:"*",validate:e=>""!==e||"Value is required"}])).value);const i=await A();if(!i)return;const l=`${b()}/business/v1/cli/secrets`;$(`PUT ${l}`);const p=N();p.start(`Setting secret '${n}'...`);try{const e=await fetch(l,{method:"PUT",headers:{Authorization:`Bearer ${i.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:n,value:r})});if(p.stop(),$(`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(s.red(t)),process.exit(1)}$(`Secret '${n}' set successfully`),console.log(s.green(`Secret '${n}' set successfully.`))}catch(d){if(p.stop(),k(d),d instanceof Error&&d.message.startsWith("EXIT:"))throw d;if(e(d))return void console.log(s.yellow(t));console.error(s.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(o={}){$("Secrets delete flow started");let{name:n}=o;const r="1"===process.env.DASHNEX_CI;n||(r&&(console.error(s.red("--name is required in CI mode (--ci).")),process.exit(1)),n=(await c.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim());const a=await A();if(!a)return;const i=`${b()}/business/v1/cli/secrets/${encodeURIComponent(n)}`;$(`DELETE ${i}`);const l=N();l.start(`Deleting secret '${n}'...`);try{const e=await fetch(i,{method:"DELETE",headers:{Authorization:`Bearer ${a.token}`}});if(l.stop(),$(`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(s.red(t)),process.exit(1)}$(`Secret '${n}' deleted successfully`),console.log(s.green(`Secret '${n}' deleted.`))}catch(p){if(l.stop(),k(p),p instanceof Error&&p.message.startsWith("EXIT:"))throw p;if(e(p))return void console.log(s.yellow(t));console.error(s.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)"}]}]},Ie=[{name:"version",description:"Display the version of the CLI",handler:new class{async execute(e){const t=n.dirname(r(import.meta.url)),s=JSON.parse(i.readFileSync(n.resolve(t,"..","..","package.json"),"utf8"));console.log(s.version)}},options:[]},{name:"login",description:"Log in to your DashNex account",handler:new class{async execute(o={}){$("Login flow started");const n=g(process.cwd()),r=await A({exitOnFailure:!1,dashnexPath:n});if(r)console.log(s.green(`Already logged in as ${r.userName??"user"}`));else try{let e,t;if(o.email)e=o.email.trim(),$("Email provided via flag");else{const{username:t}=await c.prompt([{type:"input",name:"username",message:"Email:",validate:e=>!!e.trim()||"Email is required"}]);e=t.trim()}if(o.password)t=o.password,$("Password provided via flag");else{const{password:e}=await c.prompt([{type:"password",name:"password",message:"Password:",mask:"*",validate:e=>!!e||"Password is required"}]);t=e}$("Email provided");const r=N();r.start("Logging in..."),$(`POST ${x()}/auth/v1/login`);const{response:a,body:i}=await S(`${x()}/auth/v1/login`,{method:"POST",body:JSON.stringify({username:e,password:t})});r.stop(),$(`Response: ${a.status}`),v("Login response",i),a.ok||(k(/* @__PURE__ */new Error(`Login failed: ${a.status} ${JSON.stringify(i)}`)),401===a.status&&(console.error(s.red("Invalid username or password.")),process.exit(1)),I(a,i,"Login failed. Please try again."));const l=i;if(l.two_fa_required&&l.token){$(`2FA required, type: ${l.type||"unknown"}`);const e=await this.handle2FA(l.token,l.type,o.code);e||process.exit(1),await this.completeLogin(e,n,o.business)}else l.token&&l.refreshToken?await this.completeLogin({token:l.token,refreshToken:l.refreshToken},n,o.business):(console.error(s.red("Invalid response from server. Please try again.")),process.exit(1))}catch(a){if(k(a),e(a))return void console.log(s.yellow(t));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}async handle2FA(o,n,r){if("sms"===n){$(`POST ${x()}/auth/v1/two-fa/sms`);try{const{response:e}=await S(`${x()}/auth/v1/two-fa/sms`,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:JSON.stringify({})});$(`Response: ${e.status}`)}catch(l){return k(l),console.error(s.red("Could not send SMS code. Check your connection and try again.")),null}}const a="sms"===n?"Check your phone for the code":"Check your authenticator app for the code",i=r?1:3;for(let p=1;p<=i;p++){let n;r&&1===p?(n=r,$("2FA code provided via flag")):n=(await c.prompt([{type:"input",name:"auth_code",message:`Enter code (${a}):`,validate:e=>!!e.trim()||"Code is required"}])).auth_code,$(`POST ${x()}/auth/v1/2fa-check`);try{const{response:e,body:t}=await S(`${x()}/auth/v1/2fa-check`,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:JSON.stringify({auth_code:n.trim()})});if($(`Response: ${e.status}`),v("2FA check response",t),e.ok){const e=t;if(e.token&&e.refreshToken)return{token:e.token,refreshToken:e.refreshToken}}if(e.status>=400&&e.status<500){if(console.error(s.red("Invalid code. Please try again.")),p<i){const{retry:e}=await c.prompt([{type:"confirm",name:"retry",message:"Try again?",default:!0}]);if(!e)return null}continue}I(e,t,"2FA verification failed. Please try again.")}catch(l){return k(l),e(l)?(console.log(s.yellow(t)),null):(console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),null)}}return null}async completeLogin(e,t,r){const a=N();a.start("Fetching businesses...");const i=x(),l={Authorization:`Bearer ${e.token}`};$(`GET ${i}/users/v1/business/my`);const{response:p,body:d}=await S(`${i}/users/v1/business/my`,{headers:l});$(`Response: ${p.status}`),v("Businesses response",d),p.ok||(a.stop(),k(/* @__PURE__ */new Error(`Business fetch failed: ${p.status}`)),I(p,d,"Failed to fetch businesses. Please try again."));const u=this.parseBusinesses(d),h=await this.fetchOtherBusinesses(e.token),f=this.mergeBusinesses(u,h);let m;if(a.stop(),$(`Businesses (my: ${u.length}, other: ${h.length}, merged: ${f.length})`),0===f.length&&(console.error(s.red("No businesses or teams found for your account!")),console.log(s.green("Create your first business at https://dashnex.io")),process.exit(1)),r){const e=f.find(e=>e.id===r);e||(console.error(s.red(`Business "${r}" not found.`)),process.exit(1)),m=e,$(`Selected business via flag: ${m.id} ${m.name}`)}else if(1===f.length)m=f[0],$(`Selected business: ${m.id} ${m.name}`);else{const{businessId:e}=await c.prompt([{type:"select",name:"businessId",message:"Select business:",choices:f.map(e=>({name:e.name,value:e.id}))}]);m=f.find(t=>t.id===e)||f[0],$(`Selected business: ${m.id} ${m.name}`)}a.start("Switching business..."),$(`GET ${i}/business/v1/login?_switch_business=${m.id}`);const{response:g,body:y}=await S(`${i}/business/v1/login?_switch_business=${m.id}`,{headers:l});a.stop(),$(`Response: ${g.status}`),v("Business login response",y),g.ok||(k(/* @__PURE__ */new Error(`Business login failed: ${g.status}`)),I(g,y,"Failed to switch to business. Please try again."));const w=y;w.token&&w.refreshToken||(console.error(s.red("Invalid response from server. Please try again.")),process.exit(1));const E={token:w.token,refreshToken:w.refreshToken,businessId:m.id},T={Authorization:`Bearer ${w.token}`};try{const e=b();$(`GET ${e}/business/v1/cli/settings`);const{response:t,body:s}=await S(`${e}/business/v1/cli/settings`,{headers:T});$(`Response: ${t.status}`),v("CLI settings response",s),t.ok&&s&&"object"==typeof s&&Object.assign(E,s)}catch(C){k(C)}const P=n.dirname(t);await o.pathExists(P)&&(await o.stat(P)).isFile()&&await o.remove(P),await o.ensureDir(P),await o.writeJson(t,E,{spaces:2}),$("Saved credentials to .dashnex/settings.json"),this.ensureGitignore(),console.log(s.green(`Logged in as ${m.name}`))}async fetchOtherBusinesses(e){const t=x();let s=1;const o=[];let n=0;do{const r=`${t}/users/v1/business/other?page=${s}&perPage=100`;$(`GET ${r}`);const{response:a,body:i}=await S(r,{headers:{Authorization:`Bearer ${e}`}});a.ok||(k(/* @__PURE__ */new Error(`Other businesses fetch failed: ${a.status}`)),I(a,i,"Failed to fetch teams. Please try again."));const c=this.parseBusinesses(i),l="number"==typeof i.total?i.total:c.length;if(o.push(...c),n=l,c.length<100||o.length>=n)break;s++}while(o.length<n);return o}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=n.join(process.cwd(),".gitignore");if(!(await o.pathExists(e)))return;let t=await o.readFile(e,"utf8");t.includes(".dashnex")||(t=t.trimEnd(),t.endsWith("\n")||(t+="\n"),t+="\n.dashnex\n",await o.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=g(process.cwd());if(await o.pathExists(e)){const t=await o.readJson(e);delete t.token,delete t.refreshToken,delete t.businessId,await o.writeJson(e,t,{spaces:2})}console.log(s.green("Logged out."))}},options:[]},{name:"whoami",description:"Show current logged-in business and user",handler:new class{async execute(){$("Whoami flow started");const o=await A();if(!o)return;const n=`${x()}/users/v1/`;$(`GET ${n}`);const r=N();r.start("Fetching user info...");try{const e=await fetch(n,{headers:{Authorization:`Bearer ${o.token}`}});if(r.stop(),$(`Response: ${e.status}`),!e.ok){const t=e.headers.get("content-type")??"";let o="Failed to fetch user info.";if(401===e.status||403===e.status)o="Please run 'dashnex login' to authenticate.";else if(t.includes("application/json")){const t="string"==typeof(a=await e.json().catch(()=>({}))).error?a.error:"string"==typeof a.message?a.message:void 0;t&&(o=t)}console.error(s.red(o)),process.exit(1)}const t=await e.json().catch(()=>({})),i="string"==typeof t.name?t.name:"string"==typeof t.companyName?t.companyName:"Unknown",c=t.memberUser,l=c&&"string"==typeof c.fullName?c.fullName:c&&"string"==typeof c.name?c.name:"Unknown";$(`Whoami: ${i} (${l})`),console.log(s.green(`You are logged in as ${i} (${l})`))}catch(i){if(r.stop(),k(i),i instanceof Error&&i.message.startsWith("EXIT:"))throw i;if(e(i))return void console.log(s.yellow(t));console.error(s.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={}){$("Dev flow started");try{const t=await B(process.cwd(),e);process.exit(t)}catch(t){if(t instanceof Error&&t.message.startsWith("EXIT:"))throw t;k(t),t instanceof Error?console.error(s.red(t.message)):console.error(s.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 Y,options:[]},{name:"install",description:"Install dependencies using pnpm (preferred) or npm (run in DashNex application folder)",handler:new class{async execute(){$("Install flow started");const e=n.join(process.cwd(),"dashnex.json");await o.pathExists(e)||(console.error(s.red("Run this command in a DashNex Web application folder.")),process.exit(1));const t=process.cwd(),r=N();r.start("Installing dependencies...");try{const e=await L(t);r.stop(),0!==e&&process.exit(e),console.log(s.green("Dependencies installed.")),process.exit(0)}catch(a){r.stop(),k(a),a instanceof Error?console.error(s.red(a.message)):console.error(s.red("Failed to run install")),process.exit(1)}}},options:[]},De,Ne];export{Ie 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-BJg_oM6X.js";var n={name:s.name,version:s.version,description:s.description,...e};export{n as default};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export type LogStreamLevel = 'log' | 'info' | 'warn' | 'error' | 'debug';
|
|
2
|
+
export interface LogStreamRecord {
|
|
3
|
+
ts: number;
|
|
4
|
+
level: LogStreamLevel;
|
|
5
|
+
args: unknown[];
|
|
6
|
+
requestId?: string;
|
|
7
|
+
truncated?: true;
|
|
8
|
+
}
|
|
9
|
+
export declare function isLogStreamLevel(value: unknown): value is LogStreamLevel;
|
|
10
|
+
/** A record passes when its level rank is >= the minimum level's rank. */
|
|
11
|
+
export declare function passesLevel(recordLevel: LogStreamLevel, minLevel: LogStreamLevel): boolean;
|
|
12
|
+
/** Space-joined, stringified args used as the regex-filter haystack. */
|
|
13
|
+
export declare function argsHaystack(args: unknown[]): string;
|
|
14
|
+
export declare function matchesFilter(record: LogStreamRecord, filter: RegExp | null): boolean;
|
|
15
|
+
/** `HH:MM:SS.mmm` in local time from a millisecond timestamp. */
|
|
16
|
+
export declare function formatTimestamp(ts: number): string;
|
|
17
|
+
export interface FormatOptions {
|
|
18
|
+
/** Emit ANSI colour codes. Callers pass `process.stdout.isTTY`. */
|
|
19
|
+
color: boolean;
|
|
20
|
+
}
|
|
21
|
+
/** Render a record as one terminal line (may contain embedded newlines). */
|
|
22
|
+
export declare function formatRecord(record: LogStreamRecord, opts: FormatOptions): string;
|
|
23
|
+
export interface FrameFilters {
|
|
24
|
+
minLevel: LogStreamLevel;
|
|
25
|
+
filter: RegExp | null;
|
|
26
|
+
}
|
|
27
|
+
export type FrameResult = {
|
|
28
|
+
kind: 'line';
|
|
29
|
+
line: string;
|
|
30
|
+
} | {
|
|
31
|
+
kind: 'filtered';
|
|
32
|
+
} | {
|
|
33
|
+
kind: 'malformed';
|
|
34
|
+
raw: string;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Pure frame pipeline: parse a raw text frame, apply filters, and format. Keeps
|
|
38
|
+
* the WebSocket wiring in the command thin and this logic unit-testable.
|
|
39
|
+
*/
|
|
40
|
+
export declare function processFrame(raw: string, filters: FrameFilters, opts: FormatOptions): FrameResult;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export interface TailToken {
|
|
2
|
+
token: string;
|
|
3
|
+
/** Public worker hostname (no scheme). */
|
|
4
|
+
workerUrl: string;
|
|
5
|
+
/** Advisory expiry, Unix ms. */
|
|
6
|
+
expiresAt: number;
|
|
7
|
+
}
|
|
8
|
+
export declare class TailAuthError extends Error {
|
|
9
|
+
}
|
|
10
|
+
export declare class TailNotFoundError extends Error {
|
|
11
|
+
}
|
|
12
|
+
export declare class TailUnavailableError extends Error {
|
|
13
|
+
}
|
|
14
|
+
export interface IssueTailTokenOptions {
|
|
15
|
+
/**
|
|
16
|
+
* Also set the worker `DEBUG` secret to `1`, so logs gated behind
|
|
17
|
+
* `process.env.DEBUG && console.log(...)` fire and get captured.
|
|
18
|
+
*/
|
|
19
|
+
debug?: boolean;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Ask the platform to provision a tail token and set the worker secret.
|
|
23
|
+
* Throws a typed error the command maps to an exit code.
|
|
24
|
+
*/
|
|
25
|
+
export declare function issueTailToken(bearer: string, opts?: IssueTailTokenOptions): Promise<TailToken>;
|
|
26
|
+
/**
|
|
27
|
+
* Best-effort clear of the worker tail secret. Never throws. When `debug` is
|
|
28
|
+
* set, also asks the platform to clear the `DEBUG` secret it enabled for this
|
|
29
|
+
* session (so verbose logging doesn't linger on the worker).
|
|
30
|
+
*/
|
|
31
|
+
export declare function revokeTailToken(bearer: string, opts?: IssueTailTokenOptions): Promise<void>;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@dashnex/cli",
|
|
4
|
-
"version": "0.5.
|
|
4
|
+
"version": "0.5.79",
|
|
5
5
|
"description": "Command-line interface for DashNex framework",
|
|
6
6
|
"homepage": "https://dashnex.io",
|
|
7
7
|
"type": "module",
|
|
@@ -21,6 +21,11 @@
|
|
|
21
21
|
"default": "./dist/client.js"
|
|
22
22
|
}
|
|
23
23
|
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "vite build",
|
|
26
|
+
"dev": "vite build --watch --mode development",
|
|
27
|
+
"test": "vitest run"
|
|
28
|
+
},
|
|
24
29
|
"keywords": [
|
|
25
30
|
"dashnex",
|
|
26
31
|
"cli"
|
|
@@ -34,14 +39,17 @@
|
|
|
34
39
|
"dotenv": "^17.4.2",
|
|
35
40
|
"fs-extra": "^11.3.5",
|
|
36
41
|
"ignore": "^7.0.5",
|
|
37
|
-
"inquirer": "^13.4.3"
|
|
42
|
+
"inquirer": "^13.4.3",
|
|
43
|
+
"partysocket": "^1.3.0",
|
|
44
|
+
"ws": "^8.21.0"
|
|
38
45
|
},
|
|
39
46
|
"devDependencies": {
|
|
40
|
-
"@dashnex/types": "^1.2
|
|
47
|
+
"@dashnex/types": "^1.4.2",
|
|
41
48
|
"@types/adm-zip": "^0.5.8",
|
|
42
49
|
"@types/fs-extra": "^11.0.4",
|
|
43
50
|
"@types/inquirer": "^9.0.9",
|
|
44
51
|
"@types/node": "^25.7.0",
|
|
52
|
+
"@types/ws": "^8.18.1",
|
|
45
53
|
"eslint": "^9.39.4",
|
|
46
54
|
"rollup-plugin-preserve-directives": "^0.4.0",
|
|
47
55
|
"terser": "^5.47.1",
|
|
@@ -55,11 +63,8 @@
|
|
|
55
63
|
},
|
|
56
64
|
"files": [
|
|
57
65
|
"dist",
|
|
58
|
-
"bin"
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
"test": "vitest run"
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
+
"bin",
|
|
67
|
+
"AGENTS.md",
|
|
68
|
+
"CLAUDE.md"
|
|
69
|
+
]
|
|
70
|
+
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e={$schema:"https://json.schemastore.org/package",name:"@dashnex/cli",version:"0.5.77",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",dotenv:"^17.4.2","fs-extra":"^11.3.5",ignore:"^7.0.5",inquirer:"^13.4.3"},devDependencies:{"@dashnex/types":"^1.2.6","@types/adm-zip":"^0.5.8","@types/fs-extra":"^11.0.4","@types/inquirer":"^9.0.9","@types/node":"^25.7.0",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"]},s={};export{e as n,s as t};
|