deepspace 0.2.8 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +473 -5
- package/dist/cli.js.map +1 -1
- package/dist/worker.d.ts +453 -1
- package/dist/worker.js +444 -0
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli/cli.ts","../src/cli/commands/login.ts","../src/cli/env.ts","../src/cli/session.ts","../src/cli/commands/logout.ts","../src/cli/commands/dev.ts","../src/cli/auth.ts","../src/cli/commands/kill.ts","../src/cli/commands/test.ts","../src/cli/commands/test-accounts.ts","../src/cli/commands/deploy.ts","../src/cli/commands/undeploy.ts","../src/cli/commands/whoami.ts","../src/cli/commands/add.ts","../src/cli/commands/domain.ts","../src/cli/lib/app-context.ts","../src/cli/commands/integrations.ts","../src/cli/commands/_invoke-impl.ts","../src/cli/commands/invoke.ts"],"sourcesContent":["/**\n * DeepSpace CLI\n *\n * Commands:\n * login — authenticate with your DeepSpace account\n * deploy — build and deploy your app to *.app.space\n * undeploy — remove a deployed app\n * create — redirects to `npm create deepspace`\n */\n\nimport { defineCommand, runMain } from 'citty'\nimport { execSync } from 'node:child_process'\nimport { readFileSync, existsSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport login from './commands/login'\nimport logout from './commands/logout'\nimport dev from './commands/dev'\nimport kill from './commands/kill'\nimport test from './commands/test'\nimport testAccounts from './commands/test-accounts'\nimport deploy from './commands/deploy'\nimport undeploy from './commands/undeploy'\nimport whoami from './commands/whoami'\nimport add from './commands/add'\nimport domain from './commands/domain'\nimport integrations from './commands/integrations'\nimport invoke from './commands/invoke'\n\n// Read own version from package.json so the CLI banner stays in sync with publishes.\n// __dirname of the bundled output is <pkg>/dist; package.json sits one level up.\nconst __dirname = dirname(fileURLToPath(import.meta.url))\nconst pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'))\n\n// workerd doesn't auto-discover system CAs in containers — outbound HTTPS to the\n// auth/api workers fails with \"TLS peer's certificate is not trusted\" until we\n// point it at the standard Debian/Ubuntu cert bundle. Harmless on macOS (path\n// doesn't exist, env var not set).\nif (\n process.platform === 'linux' &&\n !process.env.SSL_CERT_FILE &&\n existsSync('/etc/ssl/certs/ca-certificates.crt')\n) {\n process.env.SSL_CERT_FILE = '/etc/ssl/certs/ca-certificates.crt'\n}\n\nconst create = defineCommand({\n meta: {\n name: 'create',\n description: 'Create a new DeepSpace app',\n },\n args: {\n name: {\n type: 'positional',\n description: 'App name',\n required: false,\n },\n },\n run({ args }) {\n const name = args.name ? ` ${args.name}` : ''\n console.log(`Running: npm create deepspace${name}\\n`)\n execSync(`npm create deepspace@latest${name}`, { stdio: 'inherit' })\n },\n})\n\nconst main = defineCommand({\n meta: {\n name: 'deepspace',\n version: pkg.version,\n description: 'DeepSpace SDK CLI',\n },\n subCommands: {\n create,\n login,\n logout,\n whoami,\n dev,\n kill,\n test,\n 'test-accounts': testAccounts,\n add,\n integrations,\n invoke,\n deploy,\n undeploy,\n domain,\n },\n // No `run()` here — citty cascades parent run() AFTER subcommand finishes,\n // which corrupts agent-friendly output (`--json`) and prints noise on every\n // command. Citty's default behavior when no subcommand matches is to print\n // help, which is what we want for `deepspace` with no args.\n})\n\nrunMain(main)\n","/**\n * deepspace login\n *\n * Opens the browser to sign in with GitHub or Google.\n * CLI polls the auth worker until login is complete.\n *\n * deepspace login # browser-based OAuth\n * deepspace login --email x --password y # non-interactive (CI/agents)\n */\n\nimport { defineCommand } from 'citty'\nimport { writeFileSync, mkdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\nimport { exec } from 'node:child_process'\nimport { platform } from 'node:os'\nimport * as p from '@clack/prompts'\n\nimport { ENVS } from '../env'\nimport { exchangeSession, SESSION_COOKIE } from '../session'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? ENVS.prod.auth\n\nexport default defineCommand({\n meta: {\n name: 'login',\n description: 'Log in to your DeepSpace account',\n },\n args: {\n email: {\n type: 'string',\n description: 'Email address (non-interactive mode)',\n required: false,\n },\n password: {\n type: 'string',\n description: 'Password (non-interactive mode)',\n required: false,\n },\n },\n async run({ args }) {\n // Non-interactive mode for CI/agents with email+password\n if (args.email && args.password) {\n console.log(`Signing in as ${args.email}...`)\n await doEmailLogin(args.email, args.password)\n console.log('Logged in')\n return\n }\n\n // Browser-based OAuth flow\n p.intro('DeepSpace Login')\n\n const s = p.spinner()\n s.start('Creating login session...')\n\n // 1. Create a CLI session\n const sessionRes = await fetch(`${AUTH_URL}/api/auth/cli/session`, { method: 'POST' })\n if (!sessionRes.ok) {\n s.stop('Failed')\n p.cancel('Could not create login session')\n process.exit(1)\n }\n const sessionData = (await sessionRes.json()) as { sessionId?: string; loginUrl?: string }\n if (!sessionData.sessionId || !sessionData.loginUrl) {\n s.stop('Failed')\n p.cancel('Could not create login session')\n process.exit(1)\n }\n\n const { sessionId, loginUrl } = sessionData as { sessionId: string; loginUrl: string }\n\n s.stop('Opening browser...')\n p.log.info(`If the browser doesn't open, visit:\\n ${loginUrl}`)\n\n // 2. Open browser\n openBrowser(loginUrl)\n\n // 3. Poll for completion\n s.start('Waiting for authentication...')\n const result = await pollForCompletion(sessionId)\n\n if (!result) {\n s.stop('Timed out')\n p.cancel('Login timed out. Run `deepspace login` to try again.')\n process.exit(1)\n }\n\n // 4. Store credentials\n storeCredentials(result.sessionToken, result.jwt)\n\n s.stop('Authenticated')\n p.outro(`Logged in as ${result.name ?? result.email}`)\n },\n})\n\ninterface LoginResult {\n sessionToken: string\n jwt: string\n email: string\n name: string | null\n}\n\nasync function pollForCompletion(sessionId: string): Promise<LoginResult | null> {\n const maxAttempts = 120 // 10 minutes at 5s intervals\n const interval = 5000\n\n for (let i = 0; i < maxAttempts; i++) {\n await sleep(interval)\n\n try {\n const res = await fetch(`${AUTH_URL}/api/auth/cli/status/${sessionId}`)\n\n if (res.status === 410 || res.status === 404) return null // expired / not found\n if (!res.ok) continue\n\n const data = (await res.json()) as {\n state?: string\n sessionToken?: string\n jwt?: string\n email?: string\n name?: string\n }\n\n if (data.state === 'complete' && data.sessionToken && data.jwt) {\n return {\n sessionToken: data.sessionToken,\n jwt: data.jwt,\n email: data.email ?? '',\n name: data.name ?? null,\n }\n }\n } catch {\n // Network error, keep polling\n }\n }\n\n return null\n}\n\nfunction storeCredentials(sessionToken: string, jwt: string) {\n const dir = join(homedir(), '.deepspace')\n mkdirSync(dir, { recursive: true })\n writeFileSync(join(dir, 'session'), sessionToken, { mode: 0o600 })\n writeFileSync(join(dir, 'token'), jwt, { mode: 0o600 })\n}\n\nfunction openBrowser(url: string) {\n const cmd =\n platform() === 'darwin'\n ? `open \"${url}\"`\n : platform() === 'win32'\n ? `start \"\" \"${url}\"`\n : `xdg-open \"${url}\"`\n\n exec(cmd, () => {\n // Ignore errors — we already showed the URL\n })\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n// ── Email/password login (for test accounts and CI) ────────────────\n\nasync function doEmailLogin(email: string, password: string): Promise<void> {\n const res = await fetch(`${AUTH_URL}/api/auth/sign-in/email`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Origin: AUTH_URL },\n body: JSON.stringify({ email, password }),\n redirect: 'manual',\n })\n\n if (!res.ok) {\n const body = (await res.json().catch(() => ({}))) as { message?: string }\n throw new Error(body.message ?? `Authentication failed (${res.status})`)\n }\n\n const setCookie = res.headers.get('set-cookie') ?? ''\n const cookieMatch = setCookie.match(new RegExp(`${SESSION_COOKIE}=([^;]+)`))\n if (!cookieMatch) {\n throw new Error('No session cookie returned')\n }\n const sessionToken = decodeURIComponent(cookieMatch[1])\n\n const jwt = await exchangeSession(AUTH_URL, sessionToken)\n if (!jwt) {\n throw new Error('JWT issuance failed')\n }\n\n storeCredentials(sessionToken, jwt)\n}\n","/**\n * DeepSpace environment configuration.\n *\n * Shared between `dev`, `test`, and `deploy` commands.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\n\nexport const ENVS = {\n dev: {\n auth: 'https://deepspace-auth.eudaimonicincorporated.workers.dev',\n api: 'https://deepspace-api.eudaimonicincorporated.workers.dev',\n platform: 'https://deepspace-platform-worker.eudaimonicincorporated.workers.dev',\n deploy: 'https://deepspace-deploy.eudaimonicincorporated.workers.dev',\n },\n prod: {\n auth: 'https://deepspace-auth.eudaimonicincorporated.workers.dev',\n api: 'https://deepspace-api.eudaimonicincorporated.workers.dev',\n platform: 'https://deepspace-platform-worker.eudaimonicincorporated.workers.dev',\n deploy: 'https://deepspace-deploy.eudaimonicincorporated.workers.dev',\n },\n} as const\n\nexport type EnvName = keyof typeof ENVS\n\n/**\n * Fetch the JWT public key from an auth worker's /api/auth/jwks endpoint.\n */\nexport async function fetchPublicKey(authUrl: string): Promise<string> {\n const res = await fetch(`${authUrl}/api/auth/jwks`)\n if (!res.ok) {\n throw new Error(`Failed to fetch JWT public key (${res.status})`)\n }\n const data = (await res.json()) as { publicKey?: string }\n if (!data.publicKey) {\n throw new Error('JWKS response missing publicKey')\n }\n return data.publicKey\n}\n\n/**\n * Read the app name from the app's wrangler.toml.\n * `deepspace dev` runs in an app directory; the name is required.\n */\nfunction readAppName(appDir: string): string {\n const wranglerPath = join(appDir, 'wrangler.toml')\n if (!existsSync(wranglerPath)) {\n throw new Error('No wrangler.toml found. Are you in a DeepSpace app directory?')\n }\n const parsed = parseToml(readFileSync(wranglerPath, 'utf-8')) as { name?: string }\n if (!parsed.name) {\n throw new Error('wrangler.toml has no `name` field')\n }\n return parsed.name\n}\n\n/**\n * Mint a long-lived app-owner JWT from the auth worker.\n *\n * The caller passes their own short-lived user JWT (obtained via\n * `ensureToken()` from auth.ts) and the target env's auth URL. The auth\n * worker verifies the caller, signs a 10-year owner-scoped token bound to\n * `appName`, and returns it. This same token is used in dev (written into\n * `.dev.vars`) and in production (injected as a secret at deploy time).\n */\nexport async function mintAppOwnerJwt(\n authUrl: string,\n callerJwt: string,\n appName: string,\n): Promise<string> {\n const res = await fetch(`${authUrl}/api/auth/mint-app-token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${callerJwt}`,\n },\n body: JSON.stringify({ appName }),\n })\n if (!res.ok) {\n const err = await res.text().catch(() => '')\n throw new Error(`Failed to mint APP_OWNER_JWT (${res.status}): ${err}`)\n }\n const body = (await res.json()) as { token?: string; error?: string }\n if (!body.token) {\n throw new Error(`Auth worker returned no token: ${body.error ?? 'unknown error'}`)\n }\n return body.token\n}\n\n/**\n * Write .dev.vars for an app, pointing to the specified environment's workers.\n *\n * Includes a freshly-minted `APP_OWNER_JWT` so server-side code in the app\n * (DO alarms, cron handlers, autonomous agents) can call the API worker\n * proxy without any further auth plumbing. Uses the same flow as production:\n * the auth-worker mints the token, we store it as an env var.\n */\nexport async function writeDevVars(\n appDir: string,\n env: EnvName,\n ownerId: string,\n callerJwt: string,\n): Promise<void> {\n const urls = ENVS[env]\n const publicKey = await fetchPublicKey(urls.auth)\n const appName = readAppName(appDir)\n const appOwnerJwt = await mintAppOwnerJwt(urls.auth, callerJwt, appName)\n\n // Wrangler's .dev.vars parser is dotenv-style: bare multi-line values are\n // truncated to the first line. The PEM public key spans multiple lines, so\n // it MUST be wrapped in double quotes (dotenv multi-line value syntax).\n // Without this, AUTH_JWT_PUBLIC_KEY ends up as just \"-----BEGIN PUBLIC KEY-----\"\n // and `importSPKI` throws `DataError: Invalid SPKI input`, which silently\n // breaks JWT verification on every WS connection (anonymous fallback).\n const devVars = [\n `AUTH_JWT_PUBLIC_KEY=\"${publicKey}\"`,\n `AUTH_JWT_ISSUER=${urls.auth}/api/auth`,\n `AUTH_WORKER_URL=${urls.auth}`,\n `API_WORKER_URL=${urls.api}`,\n `PLATFORM_WORKER_URL=${urls.platform}`,\n `OWNER_USER_ID=${ownerId}`,\n `APP_OWNER_JWT=${appOwnerJwt}`,\n `INTERNAL_STORAGE_HMAC_SECRET=dev-${Date.now()}`,\n // Open /api/debug/* (proxied to RecordRoom) for dev + tests only.\n // Production secrets never set this, so deployed apps 404 the route.\n `ALLOW_DEBUG_ROUTES=true`,\n ].join('\\n')\n\n writeFileSync(join(appDir, '.dev.vars'), devVars + '\\n')\n}\n","/**\n * CLI session helpers — exchange a Better Auth session cookie for a short-lived\n * JWT against the auth worker. Shared by `auth.ts` (token refresh for all\n * authenticated commands) and `login.ts` (email/password flow).\n */\n\nexport const SESSION_COOKIE = '__Secure-better-auth.session_token'\n\n/**\n * Exchange a Better Auth session token for a fresh JWT.\n * Returns null if the session is invalid or expired.\n */\nexport async function exchangeSession(\n authUrl: string,\n sessionToken: string,\n): Promise<string | null> {\n const res = await fetch(`${authUrl}/api/auth/token`, {\n method: 'POST',\n headers: {\n Cookie: `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}`,\n Origin: authUrl,\n },\n })\n if (!res.ok) return null\n const data = (await res.json()) as { token?: string | null }\n return data.token ?? null\n}\n","/**\n * deepspace logout\n *\n * Revokes the session on the auth worker, then removes the cached session\n * token and JWT from ~/.deepspace/. Test accounts (managed by `deepspace\n * test-accounts`) are not touched.\n */\n\nimport { defineCommand } from 'citty'\nimport { existsSync, readFileSync, rmSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\n\nimport { ENVS } from '../env'\nimport { SESSION_COOKIE } from '../session'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? ENVS.prod.auth\n\nconst DIR = join(homedir(), '.deepspace')\nconst SESSION_PATH = join(DIR, 'session')\nconst TOKEN_PATH = join(DIR, 'token')\n\nexport default defineCommand({\n meta: {\n name: 'logout',\n description: 'Sign out and remove cached credentials',\n },\n async run() {\n // Read the session token before deleting it so we can revoke server-side.\n const sessionToken = existsSync(SESSION_PATH)\n ? readFileSync(SESSION_PATH, 'utf-8').trim()\n : null\n\n if (sessionToken) {\n try {\n await fetch(`${AUTH_URL}/api/auth/sign-out`, {\n method: 'POST',\n headers: {\n Cookie: `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}`,\n Origin: AUTH_URL,\n },\n })\n } catch {\n // Network failure — still wipe local credentials so the user can\n // re-authenticate. Server-side session will expire on its own.\n }\n }\n\n let removed = 0\n for (const path of [SESSION_PATH, TOKEN_PATH]) {\n if (existsSync(path)) {\n rmSync(path)\n removed++\n }\n }\n\n if (removed === 0) {\n console.log('Already logged out.')\n return\n }\n console.log('Logged out.')\n },\n})\n","/**\n * deepspace dev [--prod] [--port N]\n *\n * Starts local development:\n * 1. Ensures you're logged in\n * 2. Writes .dev.vars pointing to dev or prod workers\n * 3. Starts vite dev (Cloudflare Vite plugin runs the worker in-process)\n *\n * deepspace dev # uses dev workers, port 5173 (strict)\n * deepspace dev --prod # uses production workers\n * deepspace dev --port 5180 # bind to a different port (multi-app dev)\n *\n * Port is `--port` > $DEEPSPACE_PORT > 5173. We always pass --strictPort to\n * vite so a busy port fails loudly instead of silently jumping to 5174 (which\n * would diverge from anything Playwright/test config is expecting).\n */\n\nimport { defineCommand } from 'citty'\nimport { existsSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { spawn } from 'node:child_process'\nimport { ensureToken } from '../auth'\nimport { writeDevVars } from '../env'\n\nconst DEFAULT_PORT = 5173\n\nexport default defineCommand({\n meta: {\n name: 'dev',\n description: 'Start local development server',\n },\n args: {\n dir: {\n type: 'positional',\n description: 'App directory (default: current directory)',\n required: false,\n },\n prod: {\n type: 'boolean',\n description: 'Use production workers (real auth, real API calls)',\n default: false,\n },\n port: {\n type: 'string',\n description: `Port to bind (default ${DEFAULT_PORT}, or $DEEPSPACE_PORT)`,\n required: false,\n },\n },\n async run({ args }) {\n const appDir = resolve(args.dir ?? '.')\n const env = args.prod ? 'prod' : 'dev'\n const port = resolvePort(args.port)\n\n if (!existsSync(join(appDir, 'wrangler.toml'))) {\n console.error('No wrangler.toml found. Are you in a DeepSpace app directory?')\n process.exit(1)\n }\n\n let token: string\n try {\n token = await ensureToken()\n } catch (err: any) {\n console.error(err.message)\n process.exit(1)\n }\n\n let payload: { sub: string; name?: string; email?: string }\n try {\n payload = JSON.parse(atob(token.split('.')[1]))\n } catch {\n console.error('Malformed session token. Run `npx deepspace login`.')\n process.exit(1)\n }\n console.log(`Logged in as ${payload.name ?? payload.email}`)\n console.log(`Environment: ${env}`)\n console.log(`Port: ${port}`)\n\n await writeDevVars(appDir, env, payload.sub, token)\n console.log('Starting dev server...\\n')\n\n const vite = spawn(\n 'npx',\n ['vite', '--port', String(port), '--strictPort', '--host'],\n {\n cwd: appDir,\n stdio: 'inherit',\n shell: process.platform === 'win32',\n env: { ...process.env, DEEPSPACE_PORT: String(port) },\n },\n )\n process.on('SIGINT', () => vite.kill())\n process.on('SIGTERM', () => vite.kill())\n vite.on('close', (code) => process.exit(code ?? 0))\n },\n})\n\nfunction resolvePort(arg?: string): number {\n const raw = arg ?? process.env.DEEPSPACE_PORT\n if (!raw) return DEFAULT_PORT\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 1 || n > 65535) {\n console.error(`Invalid port: ${raw}. Must be an integer between 1 and 65535.`)\n process.exit(1)\n }\n return n\n}\n","/**\n * CLI auth utilities — shared across all commands.\n *\n * Reads the session token from ~/.deepspace/session and ensures\n * a fresh JWT is available at ~/.deepspace/token.\n */\n\nimport { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\n\nimport { ENVS } from './env'\nimport { exchangeSession } from './session'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? ENVS.prod.auth\n\nconst DIR = join(homedir(), '.deepspace')\nexport const SESSION_PATH = join(DIR, 'session')\nconst TOKEN_PATH = join(DIR, 'token')\n\n/**\n * Ensure a valid JWT exists. Refreshes from the session token if expired.\n * Returns the JWT string or throws if not logged in / session expired.\n */\nexport async function ensureToken(): Promise<string> {\n if (!existsSync(SESSION_PATH)) {\n throw new Error('Not logged in. Run `deepspace login` first.')\n }\n\n const sessionToken = readFileSync(SESSION_PATH, 'utf-8').trim()\n\n // Try existing token first — if it's still valid, skip the refresh\n if (existsSync(TOKEN_PATH)) {\n const existing = readFileSync(TOKEN_PATH, 'utf-8').trim()\n if (isTokenValid(existing)) {\n return existing\n }\n }\n\n // Refresh from session\n const token = await exchangeSession(AUTH_URL, sessionToken)\n if (!token) {\n throw new Error('Session expired. Run `deepspace login` to re-authenticate.')\n }\n\n mkdirSync(DIR, { recursive: true })\n writeFileSync(TOKEN_PATH, token, { mode: 0o600 })\n\n return token\n}\n\n/** Check if a JWT has at least 30 seconds of validity remaining. */\nfunction isTokenValid(jwt: string): boolean {\n try {\n const payload = JSON.parse(atob(jwt.split('.')[1]))\n return payload.exp * 1000 > Date.now() + 30_000\n } catch {\n return false\n }\n}\n","/**\n * deepspace kill [--port N] [--all]\n *\n * Stops a local dev server bound to the given port, plus the workerd\n * child processes that wrangler/Vite would normally clean up but\n * sometimes leak when the parent dies ungracefully (Ctrl-C in a\n * detached terminal, IDE close, sandbox deny on signal, etc).\n *\n * deepspace kill # kill listener on 5173 + its workerd children\n * deepspace kill --port 5180 # kill listener on a different port\n * deepspace kill --all # also sweep ALL stray workerd/wrangler procs on the machine\n *\n * Cross-platform: uses lsof/pgrep on macOS and Linux, and PowerShell\n * (Get-NetTCPConnection / Get-CimInstance) on Windows. PowerShell ships\n * with every supported Windows version since 7; no extra install required.\n *\n * Always sends SIGTERM first, waits briefly, then SIGKILL anything\n * still alive — same shape as `vite`'s own shutdown handler so we\n * don't trample DO state mid-write. (On Windows, SIGTERM is best-effort:\n * Win32 has no real signals, so node maps both to TerminateProcess. We\n * still issue them in the same order for consistent log output.)\n */\n\nimport { defineCommand } from 'citty'\nimport { spawnSync } from 'node:child_process'\nimport { setTimeout as wait } from 'node:timers/promises'\n\nconst DEFAULT_PORT = 5173\nconst SIGTERM_GRACE_MS = 1500\nconst IS_WIN = process.platform === 'win32'\n\nexport default defineCommand({\n meta: {\n name: 'kill',\n description: 'Kill the local dev server and any orphaned workerd processes',\n },\n args: {\n port: {\n type: 'string',\n description: `Port the dev server is bound to (default ${DEFAULT_PORT}, or $DEEPSPACE_PORT)`,\n required: false,\n },\n all: {\n type: 'boolean',\n description: 'Also kill stray workerd/wrangler processes across all ports',\n default: false,\n },\n },\n async run({ args }) {\n const port = resolvePort(args.port)\n const targets = new Set<number>()\n\n // 1. Anything LISTENing on the dev port (vite + the workerd child it\n // publishes through, occasionally a stray inspector).\n for (const pid of listenerPids(port)) targets.add(pid)\n\n // 2. Children of those listeners — wrangler/vite tend to spawn workerd\n // as a sibling, but in some shells it ends up as a child instead.\n for (const pid of [...targets]) {\n for (const child of childPids(pid)) targets.add(child)\n }\n\n // 3. With --all, sweep workerd / wrangler / vite anywhere on the box.\n // Useful when port 5173 is \"free\" but a leftover workerd from a\n // previous run is still holding D1 / DO state in .wrangler/.\n if (args.all) {\n for (const pid of processPidsByName(['workerd', 'wrangler', 'vite'])) {\n targets.add(pid)\n }\n }\n\n if (targets.size === 0) {\n console.log(\n args.all\n ? `Nothing listening on :${port} and no stray workerd/wrangler/vite processes found.`\n : `Nothing listening on :${port}. (Pass --all to sweep stray workerd/wrangler.)`,\n )\n return\n }\n\n // SIGTERM pass.\n for (const pid of targets) {\n if (sendSignal(pid, 'SIGTERM')) {\n console.log(`SIGTERM → pid ${pid}`)\n }\n }\n await wait(SIGTERM_GRACE_MS)\n\n const stillAlive: number[] = []\n for (const pid of targets) {\n if (isAlive(pid)) stillAlive.push(pid)\n }\n\n // SIGKILL holdouts.\n for (const pid of stillAlive) {\n if (sendSignal(pid, 'SIGKILL')) {\n console.log(`SIGKILL → pid ${pid} (did not exit on SIGTERM)`)\n }\n }\n\n // Re-verify the port is free.\n await wait(200)\n const remaining = listenerPids(port)\n if (remaining.length > 0) {\n console.error(\n `Port ${port} is still held by pid(s) ${remaining.join(', ')} — try \\`deepspace kill --port ${port}\\` again, or kill manually.`,\n )\n process.exit(1)\n }\n\n console.log(`Port ${port} is free.`)\n },\n})\n\nfunction resolvePort(arg?: string): number {\n const raw = arg ?? process.env.DEEPSPACE_PORT\n if (!raw) return DEFAULT_PORT\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 1 || n > 65535) {\n console.error(`Invalid port: ${raw}. Must be an integer between 1 and 65535.`)\n process.exit(1)\n }\n return n\n}\n\n// ── Platform-specific helpers ─────────────────────────────────────────────\n\nfunction listenerPids(port: number): number[] {\n if (IS_WIN) {\n // Get-NetTCPConnection is the modern replacement for netstat -ano.\n // -ErrorAction SilentlyContinue swallows \"No matching connection\" so\n // the command exits 0 with empty stdout instead of a noisy red error.\n return runPowershell(\n `Get-NetTCPConnection -LocalPort ${port} -State Listen -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess`,\n )\n }\n // -t prints PIDs only, one per line; -nP avoids DNS / service lookups.\n return run(['lsof', '-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-t'])\n}\n\nfunction childPids(parentPid: number): number[] {\n if (IS_WIN) {\n return runPowershell(\n `Get-CimInstance Win32_Process -Filter \"ParentProcessId=${parentPid}\" | Select-Object -ExpandProperty ProcessId`,\n )\n }\n return run(['pgrep', '-P', String(parentPid)])\n}\n\nfunction processPidsByName(names: string[]): number[] {\n const all = new Set<number>()\n if (IS_WIN) {\n // Match against process Name (e.g. \"workerd\") AND CommandLine (catches\n // npx-launched scripts like \"vite\" that show up as node.exe with vite\n // in the args).\n const orClauses = names\n .map((n) => `($_.Name -like '*${n}*') -or ($_.CommandLine -like '*${n}*')`)\n .join(' -or ')\n const script = `Get-CimInstance Win32_Process | Where-Object { ${orClauses} } | Select-Object -ExpandProperty ProcessId`\n for (const pid of runPowershell(script)) {\n if (pid !== process.pid) all.add(pid)\n }\n return [...all]\n }\n for (const name of names) {\n for (const pid of run(['pgrep', '-f', name])) {\n if (pid !== process.pid) all.add(pid)\n }\n }\n return [...all]\n}\n\n// ── Process primitives ────────────────────────────────────────────────────\n\n/** Run a command and return whitespace-separated PIDs (empty array on failure). */\nfunction run(cmd: string[]): number[] {\n try {\n const r = spawnSync(cmd[0], cmd.slice(1), { encoding: 'utf-8' })\n if (r.status !== 0) return []\n return parsePidLines(r.stdout)\n } catch {\n return []\n }\n}\n\n/**\n * Run a PowerShell snippet. Prefers `pwsh` (PowerShell 7+) when available\n * and falls back to `powershell.exe` (Windows PowerShell 5.1, ships with\n * every Windows version we care about).\n */\nfunction runPowershell(script: string): number[] {\n const exe = pwshOrPowershell()\n try {\n const r = spawnSync(\n exe,\n ['-NoProfile', '-NonInteractive', '-Command', script],\n { encoding: 'utf-8' },\n )\n if (r.status !== 0) return []\n return parsePidLines(r.stdout)\n } catch {\n return []\n }\n}\n\nfunction pwshOrPowershell(): string {\n // `pwsh` is the modern cross-platform binary; `powershell.exe` is the\n // legacy Windows-only one. Try modern first, fall back if missing.\n const probe = spawnSync('pwsh', ['-NoProfile', '-Command', '$PSVersionTable.PSVersion.Major'], {\n encoding: 'utf-8',\n })\n if (probe.status === 0) return 'pwsh'\n return 'powershell.exe'\n}\n\nfunction parsePidLines(stdout: string): number[] {\n return stdout\n .split(/\\s+/)\n .map((s) => Number.parseInt(s, 10))\n .filter((n) => Number.isFinite(n) && n > 0)\n}\n\nfunction sendSignal(pid: number, signal: NodeJS.Signals): boolean {\n try {\n process.kill(pid, signal)\n return true\n } catch {\n return false\n }\n}\n\nfunction isAlive(pid: number): boolean {\n try {\n // signal 0 = \"do nothing, just check\"\n process.kill(pid, 0)\n return true\n } catch {\n return false\n }\n}\n","/**\n * deepspace test [suite] [--port N]\n *\n * Runs tests for a DeepSpace app. Always uses dev workers.\n *\n * deepspace test # smoke + api (quick check)\n * deepspace test smoke # smoke tests only\n * deepspace test api # API tests only\n * deepspace test e2e # all Playwright tests\n * deepspace test unit # vitest unit tests\n * deepspace test all # everything\n * deepspace test <file> # run specific test file\n *\n * Port is `--port` > $DEEPSPACE_PORT > 5173. The chosen port is exported as\n * DEEPSPACE_PORT to the Playwright child so the config + webServer both bind\n * to the same address. Pass a different port per app to run multiple apps\n * (and test suites) in parallel.\n */\n\nimport { defineCommand } from 'citty'\nimport { existsSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { execSync, spawnSync } from 'node:child_process'\nimport { ensureToken } from '../auth'\nimport { writeDevVars } from '../env'\n\nconst DEFAULT_PORT = 5173\n\nexport default defineCommand({\n meta: {\n name: 'test',\n description: 'Run tests for your DeepSpace app',\n },\n args: {\n suite: {\n type: 'positional',\n description: 'Test suite: smoke, api, e2e, unit, all (default: smoke+api)',\n required: false,\n },\n port: {\n type: 'string',\n description: `Port for vite/webServer (default ${DEFAULT_PORT}, or $DEEPSPACE_PORT)`,\n required: false,\n },\n },\n async run({ args }) {\n const appDir = resolve('.')\n const suite = args.suite ?? 'default'\n const port = resolvePort(args.port)\n\n if (!existsSync(join(appDir, 'wrangler.toml'))) {\n console.error('No wrangler.toml found. Are you in a DeepSpace app directory?')\n process.exit(1)\n }\n\n // Always write .dev.vars pointing to dev workers. A logged-in user is\n // required so writeDevVars can mint APP_OWNER_JWT via the auth-worker.\n let token: string\n let ownerId: string\n try {\n token = await ensureToken()\n const payload = JSON.parse(atob(token.split('.')[1]))\n ownerId = payload.sub\n } catch (err) {\n console.error('`deepspace test` requires you to be logged in. Run `deepspace login` first.')\n process.exit(1)\n }\n\n await writeDevVars(appDir, 'dev', ownerId, token)\n\n if (suite !== 'unit') {\n ensurePlaywright(appDir)\n }\n\n let exitCode = 0\n\n switch (suite) {\n case 'smoke':\n exitCode = runPlaywright(appDir, ['tests/smoke.spec.ts'], port)\n break\n case 'api':\n exitCode = runPlaywright(appDir, ['tests/api.spec.ts'], port)\n break\n case 'e2e':\n exitCode = runPlaywright(appDir, [], port)\n break\n case 'unit':\n exitCode = runVitest(appDir)\n break\n case 'all':\n exitCode = runVitest(appDir)\n if (exitCode === 0) exitCode = runPlaywright(appDir, [], port)\n break\n case 'default':\n exitCode = runPlaywright(appDir, ['tests/smoke.spec.ts', 'tests/api.spec.ts'], port)\n break\n default:\n if (suite.endsWith('.spec.ts')) {\n exitCode = runPlaywright(appDir, [suite], port)\n } else {\n console.error(`Unknown test suite: ${suite}`)\n console.error('Available: smoke, api, e2e, unit, all')\n process.exit(1)\n }\n }\n\n process.exit(exitCode)\n },\n})\n\nfunction runPlaywright(appDir: string, testFiles: string[], port: number): number {\n const result = spawnSync('npx', [\n 'playwright', 'test',\n '--config', 'tests/playwright.config.ts',\n ...testFiles,\n ], {\n cwd: appDir,\n stdio: 'inherit',\n shell: process.platform === 'win32',\n env: { ...process.env, DEEPSPACE_PORT: String(port) },\n })\n return result.status ?? 1\n}\n\nfunction runVitest(appDir: string): number {\n const result = spawnSync('npx', ['vitest', 'run', '--passWithNoTests'], {\n cwd: appDir, stdio: 'inherit', shell: process.platform === 'win32',\n })\n return result.status ?? 1\n}\n\nfunction ensurePlaywright(appDir: string) {\n try {\n execSync('npx playwright --version', { cwd: appDir, stdio: 'pipe' })\n } catch {\n console.log('Installing Playwright...')\n execSync('npm install -D @playwright/test', { cwd: appDir, stdio: 'pipe' })\n }\n // `playwright install` is idempotent — fast no-op if chromium already exists,\n // ~30s download on first run. The previous --dry-run check exited 0 even when\n // browsers were missing, so we'd silently skip install and tests would crash.\n // On Linux, --with-deps installs system libs (requires root); on macOS/Win it's\n // a no-op flag, but apt-get inside `--with-deps` errors out without sudo, so\n // only pass it when running as root on Linux.\n const isLinux = process.platform === 'linux'\n const isRoot = isLinux && typeof process.getuid === 'function' && process.getuid() === 0\n const args = isRoot ? ['install', '--with-deps', 'chromium'] : ['install', 'chromium']\n const result = spawnSync('npx', ['playwright', ...args], { cwd: appDir, stdio: 'inherit' })\n if (result.status !== 0) {\n console.error('\\nPlaywright install failed. On Linux, system libs may be missing — try:')\n console.error(' sudo npx playwright install --with-deps chromium')\n process.exit(1)\n }\n}\n\nfunction resolvePort(arg?: string): number {\n const raw = arg ?? process.env.DEEPSPACE_PORT\n if (!raw) return DEFAULT_PORT\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 1 || n > 65535) {\n console.error(`Invalid port: ${raw}. Must be an integer between 1 and 65535.`)\n process.exit(1)\n }\n return n\n}\n","/**\n * deepspace test-accounts\n *\n * Manage test accounts for local development and CI.\n * Test accounts use @deepspace.test emails and are clearly\n * demarcated in the database. Max 10 per developer.\n *\n * Credentials are saved to ~/.deepspace/test-accounts.json (0600)\n * so they persist across projects and sessions.\n *\n * deepspace test-accounts create --email bot@deepspace.test --password Pass123!\n * deepspace test-accounts list\n * deepspace test-accounts delete --email bot@deepspace.test\n * deepspace test-accounts delete --id <id>\n * deepspace test-accounts clear # delete all (with confirm)\n * deepspace test-accounts clear --label e2e # delete only label=e2e\n * deepspace test-accounts clear --yes # skip confirm (CI)\n */\n\nimport { defineCommand } from 'citty'\nimport * as p from '@clack/prompts'\nimport { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\nimport { ensureToken, SESSION_PATH } from '../auth'\nimport { ENVS } from '../env'\n\nconst SESSION_COOKIE = '__Secure-better-auth.session_token'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? ENVS.prod.auth\nconst DIR = join(homedir(), '.deepspace')\nconst ACCOUNTS_PATH = join(DIR, 'test-accounts.json')\n\n// ── Local credential store ─────────────────────────────────────────\n\ninterface StoredAccount {\n id: string\n email: string\n password: string\n userId: string\n name?: string\n label?: string | null\n createdAt: number\n}\n\nfunction loadAccounts(): StoredAccount[] {\n if (!existsSync(ACCOUNTS_PATH)) return []\n try {\n return JSON.parse(readFileSync(ACCOUNTS_PATH, 'utf-8'))\n } catch {\n return []\n }\n}\n\nfunction saveAccounts(accounts: StoredAccount[]) {\n mkdirSync(DIR, { recursive: true })\n writeFileSync(ACCOUNTS_PATH, JSON.stringify(accounts, null, 2), { mode: 0o600 })\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nfunction sessionCookie(): string {\n const token = readFileSync(SESSION_PATH, 'utf-8').trim()\n return `${SESSION_COOKIE}=${encodeURIComponent(token)}`\n}\n\ninterface RemoteAccount {\n id: string\n email: string\n userId: string\n label: string | null\n createdAt: number\n}\n\nasync function fetchRemoteAccounts(): Promise<RemoteAccount[]> {\n const res = await fetch(`${AUTH_URL}/api/auth/test-accounts`, {\n headers: { Cookie: sessionCookie(), Origin: AUTH_URL },\n })\n const data = (await res.json().catch(() => ({}))) as {\n accounts?: RemoteAccount[]\n error?: string\n }\n if (!res.ok || !data.accounts) {\n throw new Error(data.error ?? 'Failed to list test accounts')\n }\n return data.accounts\n}\n\nasync function deleteRemote(id: string): Promise<void> {\n const res = await fetch(`${AUTH_URL}/api/auth/test-accounts/${id}`, {\n method: 'DELETE',\n headers: { Cookie: sessionCookie(), Origin: AUTH_URL },\n })\n if (!res.ok) {\n const data = (await res.json().catch(() => ({}))) as { error?: string }\n throw new Error(data.error ?? `DELETE returned ${res.status}`)\n }\n}\n\n// ── Subcommands ────────────────────────────────────────────────────\n\nconst create = defineCommand({\n meta: {\n name: 'create',\n description: 'Create a test account',\n },\n args: {\n email: {\n type: 'string',\n description: 'Email (must end with @deepspace.test)',\n required: true,\n },\n password: {\n type: 'string',\n description: 'Password (min 8 characters)',\n required: true,\n },\n name: {\n type: 'string',\n description: 'Display name',\n required: false,\n },\n label: {\n type: 'string',\n description: 'Label for this test account',\n required: false,\n },\n },\n async run({ args }) {\n await ensureToken()\n\n const res = await fetch(`${AUTH_URL}/api/auth/test-accounts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Cookie: sessionCookie(),\n Origin: AUTH_URL,\n },\n body: JSON.stringify({\n email: args.email,\n password: args.password,\n name: args.name,\n label: args.label,\n }),\n })\n\n const data = (await res.json().catch(() => ({}))) as {\n id?: string\n email?: string\n userId?: string\n label?: string | null\n createdAt?: number\n error?: string\n }\n\n if (!res.ok || !data.id) {\n console.error(`Failed: ${data.error ?? 'Unknown error'}`)\n process.exit(1)\n }\n\n const account = data as { id: string; email: string; userId: string; label: string | null; createdAt: number }\n\n // Save credentials locally\n const accounts = loadAccounts()\n accounts.push({\n id: account.id,\n email: args.email,\n password: args.password,\n userId: account.userId,\n name: args.name,\n label: account.label,\n createdAt: account.createdAt,\n })\n saveAccounts(accounts)\n\n console.log(`Created test account:`)\n console.log(` ID: ${account.id}`)\n console.log(` Email: ${account.email}`)\n console.log(` Password: ${args.password}`)\n console.log(` UserID: ${account.userId}`)\n if (account.label) console.log(` Label: ${account.label}`)\n console.log(`\\nSaved to ${ACCOUNTS_PATH}`)\n },\n})\n\nconst list = defineCommand({\n meta: {\n name: 'list',\n description: 'List your test accounts',\n },\n async run() {\n await ensureToken()\n\n let remote: RemoteAccount[]\n try {\n remote = await fetchRemoteAccounts()\n } catch (err) {\n console.error(`Failed: ${(err as Error).message}`)\n process.exit(1)\n }\n\n if (remote.length === 0) {\n console.log('No test accounts. Create one with: deepspace test-accounts create --email <email> --password <password>')\n return\n }\n\n // Merge with local credentials (passwords are only stored locally)\n const local = loadAccounts()\n const localByEmail = new Map(local.map((a) => [a.email, a]))\n\n console.log(`Test accounts (${remote.length}/10):\\n`)\n for (const a of remote) {\n const stored = localByEmail.get(a.email)\n const date = new Date(a.createdAt).toLocaleDateString()\n console.log(` ${a.email}${a.label ? ` (${a.label})` : ''}`)\n console.log(` ID: ${a.id} UserID: ${a.userId} Created: ${date}`)\n if (stored?.password) {\n console.log(` Password: ${stored.password}`)\n } else {\n console.log(` Password: (not saved locally)`)\n }\n }\n },\n})\n\nconst del = defineCommand({\n meta: {\n name: 'delete',\n description: 'Delete a test account by --email or --id',\n },\n args: {\n email: {\n type: 'string',\n description: 'Email of the test account to delete',\n required: false,\n },\n id: {\n type: 'string',\n description: 'ID of the test account to delete',\n required: false,\n },\n },\n async run({ args }) {\n if (!args.email && !args.id) {\n console.error('Provide --email <email> or --id <id>.')\n process.exit(1)\n }\n if (args.email && args.id) {\n console.error('Provide either --email or --id, not both.')\n process.exit(1)\n }\n\n await ensureToken()\n\n let targetId = args.id as string | undefined\n let targetEmail = args.email as string | undefined\n\n if (targetEmail && !targetId) {\n let remote: RemoteAccount[]\n try {\n remote = await fetchRemoteAccounts()\n } catch (err) {\n console.error(`Failed: ${(err as Error).message}`)\n process.exit(1)\n }\n const match = remote.find((a) => a.email === targetEmail)\n if (!match) {\n console.error(`No test account with email ${targetEmail}.`)\n process.exit(1)\n }\n targetId = match.id\n }\n\n try {\n await deleteRemote(targetId!)\n } catch (err) {\n console.error(`Failed: ${(err as Error).message}`)\n process.exit(1)\n }\n\n // Remove from local store\n const accounts = loadAccounts().filter(\n (a) => a.id !== targetId && (!targetEmail || a.email !== targetEmail),\n )\n saveAccounts(accounts)\n\n console.log(`Test account deleted${targetEmail ? `: ${targetEmail}` : `: ${targetId}`}`)\n },\n})\n\nconst clear = defineCommand({\n meta: {\n name: 'clear',\n description: 'Delete all your test accounts (or those matching --label)',\n },\n args: {\n label: {\n type: 'string',\n description: 'Only delete accounts with this label (e.g. e2e, slack-clone)',\n required: false,\n },\n yes: {\n type: 'boolean',\n description: 'Skip confirmation prompt (for CI scripts)',\n default: false,\n },\n },\n async run({ args }) {\n await ensureToken()\n\n let remote: RemoteAccount[]\n try {\n remote = await fetchRemoteAccounts()\n } catch (err) {\n console.error(`Failed: ${(err as Error).message}`)\n process.exit(1)\n }\n\n const targets = args.label\n ? remote.filter((a) => a.label === args.label)\n : remote\n\n if (targets.length === 0) {\n const suffix = args.label ? ` with label '${args.label}'` : ''\n console.log(`No test accounts${suffix} to delete.`)\n return\n }\n\n if (!args.yes) {\n const subject = args.label\n ? `${targets.length} test account(s) labeled '${args.label}'`\n : `all ${targets.length} test account(s)`\n const confirmed = await p.confirm({\n message: `Delete ${subject}? This is not reversible.`,\n initialValue: false,\n })\n if (p.isCancel(confirmed) || !confirmed) {\n console.log('Cancelled.')\n return\n }\n }\n\n let ok = 0\n const failures: Array<{ email: string; error: string }> = []\n for (const a of targets) {\n try {\n await deleteRemote(a.id)\n ok++\n } catch (err) {\n failures.push({ email: a.email, error: (err as Error).message })\n }\n }\n\n // Sync local store with what's actually deleted.\n const deletedIds = new Set(\n targets.filter((t) => !failures.find((f) => f.email === t.email)).map((t) => t.id),\n )\n saveAccounts(loadAccounts().filter((a) => !deletedIds.has(a.id)))\n\n console.log(`Deleted ${ok}/${targets.length} test account(s).`)\n if (failures.length > 0) {\n console.error(`\\nFailed:`)\n for (const f of failures) console.error(` ${f.email}: ${f.error}`)\n process.exit(1)\n }\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'test-accounts',\n description: 'Manage test accounts for development',\n },\n subCommands: {\n create,\n list,\n delete: del,\n clear,\n },\n})\n","/**\n * deepspace deploy\n *\n * Builds the app with Vite (Cloudflare plugin bundles both client + worker),\n * then uploads to the deploy worker which handles Cloudflare WfP deployment.\n *\n * Uses the same build pipeline as dev for full fidelity. Reads the output\n * wrangler.json (via .wrangler/deploy/config.json) to find the built assets\n * and worker bundle — the same contract that `wrangler deploy` uses.\n */\n\nimport { defineCommand } from 'citty'\nimport { execSync } from 'node:child_process'\nimport { readFileSync, readdirSync, existsSync } from 'node:fs'\nimport { parse as parseToml } from 'smol-toml'\nimport { join, resolve, dirname } from 'node:path'\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\nimport { ENVS } from '../env'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? ENVS.prod.deploy\n\nexport default defineCommand({\n meta: {\n name: 'deploy',\n description: 'Build and deploy your DeepSpace app',\n },\n args: {\n dir: {\n type: 'positional',\n description: 'App directory (default: current directory)',\n required: false,\n },\n },\n async run({ args }) {\n const appDir = resolve(args.dir ?? '.')\n p.intro('Deploying DeepSpace app')\n\n // ── Read app name from wrangler.toml ──────────────────────\n const wranglerPath = join(appDir, 'wrangler.toml')\n if (!existsSync(wranglerPath)) {\n p.cancel('No wrangler.toml found. Are you in a DeepSpace app directory?')\n process.exit(1)\n }\n\n const wranglerConfig = parseToml(readFileSync(wranglerPath, 'utf-8')) as { name?: string }\n const appName = wranglerConfig.name\n if (!appName) {\n p.cancel('Could not find app name in wrangler.toml')\n process.exit(1)\n }\n p.log.info(`App: ${appName}`)\n\n // ── Ensure valid JWT ───────────────────────────────────────\n let token: string\n try {\n token = await ensureToken()\n } catch (err: any) {\n p.cancel(err.message)\n process.exit(1)\n }\n\n // ── Build with Vite (Cloudflare plugin bundles client + worker) ──\n const s = p.spinner()\n s.start('Building...')\n try {\n execSync('npx vite build', { cwd: appDir, stdio: 'pipe' })\n } catch (err: any) {\n s.stop('Build failed')\n console.error(err.stderr?.toString() ?? err.message)\n process.exit(1)\n }\n s.stop('Built')\n\n // ── Locate build output via .wrangler/deploy/config.json ──\n // This is the same contract that `wrangler deploy` uses after `vite build`.\n const deployConfigPath = join(appDir, '.wrangler', 'deploy', 'config.json')\n if (!existsSync(deployConfigPath)) {\n p.cancel('Build output config not found at .wrangler/deploy/config.json')\n process.exit(1)\n }\n\n const deployConfig = JSON.parse(readFileSync(deployConfigPath, 'utf-8')) as { configPath: string }\n const outputWranglerPath = resolve(dirname(deployConfigPath), deployConfig.configPath)\n\n if (!existsSync(outputWranglerPath)) {\n p.cancel(`Output wrangler.json not found at ${outputWranglerPath}`)\n process.exit(1)\n }\n\n const outputConfig = JSON.parse(readFileSync(outputWranglerPath, 'utf-8')) as {\n main: string\n assets?: { directory: string }\n durable_objects?: { bindings: Array<{ name: string; class_name: string }> }\n migrations?: Array<{ new_sqlite_classes?: string[] }>\n }\n\n const workerDir = dirname(outputWranglerPath)\n const workerBundlePath = join(workerDir, outputConfig.main)\n const clientDir = outputConfig.assets?.directory\n ? resolve(workerDir, outputConfig.assets.directory)\n : null\n\n if (!existsSync(workerBundlePath)) {\n p.cancel(`Worker bundle not found at ${workerBundlePath}`)\n process.exit(1)\n }\n if (!clientDir || !existsSync(clientDir)) {\n p.cancel(`Client assets not found at ${clientDir}`)\n process.exit(1)\n }\n\n // ── Collect assets ────────────────────────────────────────\n s.start('Collecting assets...')\n const assets = collectAssets(clientDir)\n s.stop(`Collected ${assets.length} assets`)\n\n const workerJs = readFileSync(workerBundlePath, 'utf-8')\n\n // ── Extract DO manifest from build output config ───────────\n const doBindings = outputConfig.durable_objects?.bindings as Array<{ name: string; class_name: string }> | undefined\n const sqliteClasses = new Set(\n (outputConfig.migrations as Array<{ new_sqlite_classes?: string[] }> | undefined)\n ?.flatMap(m => m.new_sqlite_classes ?? []) ?? []\n )\n const doManifest = doBindings?.map(b => ({\n binding: b.name,\n className: b.class_name,\n sqlite: sqliteClasses.has(b.class_name),\n }))\n if (doManifest?.length) {\n p.log.info(`DO manifest: ${doManifest.length} binding(s)`)\n }\n\n // ── Upload to deploy worker ───────────────────────────────\n s.start(`Deploying to ${appName}.app.space...`)\n\n const form = new FormData()\n form.append('worker', new Blob([workerJs], { type: 'application/javascript' }), 'worker.js')\n form.append('assets', JSON.stringify(assets))\n if (doManifest) {\n form.append('doManifest', JSON.stringify(doManifest))\n }\n\n const res = await fetch(`${DEPLOY_URL}/api/deploy/${appName}`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n body: form,\n })\n\n const body = (await res.json().catch(() => ({}))) as {\n success?: boolean\n url?: string\n error?: string\n }\n\n if (!res.ok || !body.success) {\n s.stop('Deploy failed')\n p.cancel(body.error ?? `Deployment error (${res.status})`)\n process.exit(1)\n }\n\n s.stop('Deployed!')\n p.log.success(`Live at: ${body.url}`)\n p.outro('Done')\n },\n})\n\nfunction collectAssets(dir: string): Array<{ path: string; contentBase64: string }> {\n const assets: Array<{ path: string; contentBase64: string }> = []\n function walk(d: string, prefix: string) {\n for (const entry of readdirSync(d, { withFileTypes: true })) {\n if (entry.name === '.assetsignore') continue\n const full = join(d, entry.name)\n const rel = prefix ? `${prefix}/${entry.name}` : entry.name\n if (entry.isDirectory()) {\n walk(full, rel)\n } else {\n assets.push({\n path: '/' + rel,\n contentBase64: readFileSync(full).toString('base64'),\n })\n }\n }\n }\n walk(dir, '')\n return assets\n}\n","/**\n * deepspace undeploy\n *\n * Removes a deployed app from *.app.space via the deploy worker.\n */\n\nimport { defineCommand } from 'citty'\nimport { readFileSync, existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\n\nimport { ENVS } from '../env'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? ENVS.prod.deploy\n\nexport default defineCommand({\n meta: {\n name: 'undeploy',\n description: 'Remove a deployed DeepSpace app',\n },\n args: {\n name: {\n type: 'positional',\n description: 'App name to undeploy (reads from wrangler.toml if omitted)',\n required: false,\n },\n },\n async run({ args }) {\n let appName = args.name\n\n // If no name given, try to read from wrangler.toml in cwd\n if (!appName) {\n const wranglerPath = join(process.cwd(), 'wrangler.toml')\n if (existsSync(wranglerPath)) {\n const config = parseToml(readFileSync(wranglerPath, 'utf-8')) as { name?: string }\n if (config.name) appName = config.name\n }\n }\n\n if (!appName) {\n p.cancel('Provide an app name or run from a DeepSpace app directory.')\n process.exit(1)\n }\n\n let token: string\n try {\n token = await ensureToken()\n } catch (err: any) {\n p.cancel(err.message)\n process.exit(1)\n }\n\n p.intro(`Undeploying ${appName}`)\n const s = p.spinner()\n s.start('Removing...')\n\n const res = await fetch(`${DEPLOY_URL}/api/deploy/${appName}`, {\n method: 'DELETE',\n headers: { Authorization: `Bearer ${token}` },\n })\n\n const body = (await res.json().catch(() => ({}))) as { success?: boolean; error?: string }\n\n if (!res.ok || !body.success) {\n s.stop('Failed')\n p.cancel(body.error ?? `Undeploy error (${res.status})`)\n process.exit(1)\n }\n\n s.stop('Removed')\n p.outro(`${appName}.app.space has been taken down`)\n },\n})\n","/**\n * deepspace whoami\n *\n * Shows the currently logged-in user. Auto-refreshes the JWT if expired.\n *\n * Prints all the identity fields a developer cares about (email, name,\n * userId, issuer) so you don't have to peek into ~/.deepspace/token.\n * Also flags whether the session is for a test account (`@deepspace.test`\n * email), since that's a meaningful distinction for who can do what — see\n * docs/auth/dev-vs-test-accounts.md.\n *\n * `--json` emits a parseable single-line JSON object for scripts.\n */\n\nimport { defineCommand } from 'citty'\nimport { ensureToken } from '../auth'\n\ninterface JwtPayload {\n sub?: string\n name?: string\n email?: string\n image?: string | null\n iss?: string\n iat?: number\n exp?: number\n}\n\nexport default defineCommand({\n meta: {\n name: 'whoami',\n description: 'Show the currently logged-in user',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Emit a single-line JSON object instead of human output',\n default: false,\n },\n },\n async run({ args }) {\n let jwt: string\n try {\n jwt = await ensureToken()\n } catch (err: any) {\n console.error(err.message ?? 'Not signed in. Run `deepspace login`.')\n process.exit(1)\n }\n\n let payload: JwtPayload\n try {\n payload = JSON.parse(atob(jwt.split('.')[1]))\n } catch {\n console.error('Malformed session token. Run `deepspace login` again.')\n process.exit(1)\n }\n\n const isTestAccount = !!payload.email?.endsWith('@deepspace.test')\n const accountType: 'developer' | 'test-account' | 'unknown' = isTestAccount\n ? 'test-account'\n : payload.email\n ? 'developer'\n : 'unknown'\n\n if (args.json) {\n console.log(JSON.stringify({\n name: payload.name ?? null,\n email: payload.email ?? null,\n userId: payload.sub ?? null,\n accountType,\n issuer: payload.iss ?? null,\n expiresAt: payload.exp ? new Date(payload.exp * 1000).toISOString() : null,\n }))\n return\n }\n\n console.log(`Name: ${payload.name ?? '(none)'}`)\n console.log(`Email: ${payload.email ?? '(none)'}`)\n console.log(`UserID: ${payload.sub ?? '(none)'}`)\n console.log(`Type: ${accountType}`)\n if (payload.iss) console.log(`Issuer: ${payload.iss}`)\n if (isTestAccount) {\n console.log('')\n console.log('Note: this is a test account, not a real OAuth developer.')\n console.log('See docs/auth/dev-vs-test-accounts.md.')\n }\n },\n})\n","/**\n * deepspace add <feature> [dir]\n *\n * Installs a DeepSpace feature into the current app.\n *\n * deepspace add --list # list available features\n * deepspace add messaging # install into current dir\n * deepspace add messaging ./my-app # install into specific dir\n * deepspace add --info messaging # show feature details\n */\n\nimport { defineCommand } from 'citty'\nimport { existsSync } from 'node:fs'\nimport { resolve, join } from 'node:path'\nimport { execSync } from 'node:child_process'\n\nfunction findScript(from: string): string | null {\n const candidate = join(from, '.deepspace', 'scripts', 'add-feature.cjs')\n if (existsSync(candidate)) return candidate\n return null\n}\n\nexport default defineCommand({\n meta: {\n name: 'add',\n description: 'Add a feature to your DeepSpace app',\n },\n args: {\n list: {\n type: 'boolean',\n alias: 'l',\n description: 'List available features',\n required: false,\n },\n info: {\n type: 'string',\n description: 'Show details about a feature',\n required: false,\n },\n feature: {\n type: 'positional',\n description: 'Feature to install',\n required: false,\n },\n dir: {\n type: 'positional',\n description: 'App directory (default: current directory)',\n required: false,\n },\n },\n run({ args }) {\n const appDir = resolve(args.dir ?? '.')\n const script = findScript(appDir)\n\n if (!script) {\n console.error('No .deepspace/scripts/add-feature.cjs found.')\n console.error('Are you in a DeepSpace app directory?')\n process.exit(1)\n }\n\n const passArgs: string[] = []\n\n if (args.list) {\n passArgs.push('--list')\n } else if (args.info) {\n passArgs.push('--info', args.info)\n } else if (args.feature) {\n passArgs.push(args.feature, appDir)\n } else {\n passArgs.push('--help')\n }\n\n execSync(`node ${JSON.stringify(script)} ${passArgs.map(a => JSON.stringify(a)).join(' ')}`, {\n stdio: 'inherit',\n cwd: appDir,\n })\n },\n})\n","/**\n * deepspace domain — purchase and manage custom domains for your apps.\n *\n * Designed to be both human-friendly and agent/script-friendly:\n * - All destructive commands accept `--yes` to skip prompts.\n * - All read commands accept `--json` for structured stdout.\n * - `--app` defaults to the cwd's wrangler.toml name (matches `deepspace deploy`).\n * - `domain buy` opens Stripe Checkout in a browser and polls until live;\n * pass `--no-open` to print the URL only, `--no-wait` to skip polling.\n *\n * Subcommands:\n * search <query> — find available domains and prices\n * buy <domain> — buy a domain via Stripe Checkout (browser)\n * list — list domains you own\n * status <domain> — detail view for one domain\n * attach <domain> — re-point a domain at a different app\n * detach <domain> — stop routing the domain (keeps registration)\n * renew <domain> --auto X — toggle auto-renew on/off at the registrar\n */\n\nimport { defineCommand } from 'citty'\nimport { execSync } from 'node:child_process'\nimport { ensureToken } from '../auth'\nimport { ENVS } from '../env'\nimport { requireAppName, detectAppName } from '../lib/app-context'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? ENVS.prod.api\n\ninterface SearchResult {\n name: string\n registrable: boolean\n registrar?: 'cloudflare' | 'namesilo'\n pricing?: { currency: string; registrationCost: string; renewalCost: string }\n registrationCost?: number\n renewalCost?: number\n chargedCents?: number | null\n costCents?: number | null\n reason?: string\n premium?: boolean\n}\n\ninterface DomainPurchase {\n id: string\n domain: string\n appName: string\n status: string\n statusError?: string | null\n registeredAt?: string | null\n expiresAt?: string | null\n chargedCents: number\n autoRenew: boolean\n registrar: string\n}\n\nasync function api<T>(token: string, path: string, init?: RequestInit): Promise<T> {\n const res = await fetch(`${API_URL}${path}`, {\n ...init,\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n ...(init?.headers ?? {}),\n },\n })\n const text = await res.text()\n if (!res.ok) {\n let msg = text\n try {\n msg = (JSON.parse(text) as { error?: string }).error ?? text\n } catch {\n // not JSON\n }\n throw new Error(`API ${path} (${res.status}): ${msg}`)\n }\n return JSON.parse(text) as T\n}\n\nfunction fmtCents(cents: number | null | undefined): string {\n if (cents === null || cents === undefined) return '—'\n return `$${(cents / 100).toFixed(2)}`\n}\n\nfunction fmtDate(iso: string | null | undefined): string {\n if (!iso) return '—'\n return iso.slice(0, 10)\n}\n\n/**\n * Plain stdin Y/N prompt — no clack, agent can pipe `yes` or pass --yes.\n */\nasync function confirm(message: string): Promise<boolean> {\n if (!process.stdin.isTTY) {\n // Non-interactive (piped, agent) — refuse rather than hang\n throw new Error(`${message} — pass --yes to confirm non-interactively`)\n }\n process.stdout.write(`${message} [y/N] `)\n return new Promise((resolve) => {\n process.stdin.setEncoding('utf-8')\n process.stdin.once('data', (data) => {\n const answer = data.toString().trim().toLowerCase()\n resolve(answer === 'y' || answer === 'yes')\n })\n })\n}\n\n// ============================================================================\n// search\n// ============================================================================\n\nconst search = defineCommand({\n meta: { name: 'search', description: 'Search for available domains' },\n args: {\n query: { type: 'positional', description: 'Domain or keyword', required: true },\n limit: { type: 'string', description: 'Max results (default 10)', default: '10' },\n json: { type: 'boolean', description: 'Emit JSON instead of a table' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const limit = parseInt(args.limit ?? '10', 10) || 10\n const result = await api<{ domains: SearchResult[] }>(\n token,\n `/api/domains/search?q=${encodeURIComponent(args.query)}&limit=${limit}`,\n )\n if (args.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n if (result.domains.length === 0) {\n console.log('No matches.')\n return\n }\n for (const d of result.domains) {\n const tag = d.registrable ? '✓' : '✗'\n const price = d.registrable ? `${fmtCents(d.chargedCents)}/yr` : d.reason ?? '—'\n // Annotate slow-path TLDs so users have realistic expectations.\n const slowFlag = d.registrar && d.registrar !== 'cloudflare' ? ' (15-60 min provisioning)' : ''\n console.log(`${tag} ${d.name.padEnd(40)} ${price}${slowFlag}`)\n }\n },\n})\n\n// ============================================================================\n// buy\n// ============================================================================\n\nconst buy = defineCommand({\n meta: { name: 'buy', description: 'Buy a domain and attach it to an app' },\n args: {\n domain: { type: 'positional', description: 'Domain to buy', required: true },\n app: { type: 'string', description: 'App to attach (defaults to ./wrangler.toml)' },\n yes: { type: 'boolean', description: 'Skip the confirmation prompt', default: false },\n 'no-open': { type: 'boolean', description: 'Do not open browser; print Stripe URL', default: false },\n 'no-wait': { type: 'boolean', description: 'Exit after creating session; do not poll until active', default: false },\n json: { type: 'boolean', description: 'Emit JSON to stdout', default: false },\n },\n async run({ args }) {\n const token = await ensureToken()\n const appName = requireAppName(args.app)\n\n // Re-check pricing\n const priceCheck = await api<{ domains: SearchResult[] }>(token, '/api/domains/check', {\n method: 'POST',\n body: JSON.stringify({ domains: [args.domain] }),\n })\n const result = priceCheck.domains[0]\n if (!result || !result.registrable) {\n console.error(`Not available: ${result?.reason ?? 'unknown'}`)\n process.exit(1)\n }\n\n const price = fmtCents(result.chargedCents)\n // Provisioning time depends on registrar:\n // CF Registrar (.com/.dev/.app/.xyz/etc): ~60-90s — registry publishes\n // CF nameservers atomically with registration.\n // Porkbun fallback (.ai/.io/.me/.co/etc + ccTLDs): 15-60 min — depends\n // on the destination registry (Verisign/.me, NIC.AI, etc) batch-\n // publishing our NS records to public DNS. The platform side is\n // done in <30s; the wait is registry-side.\n const expectedTime =\n result.registrar === 'cloudflare'\n ? '~60-90 seconds'\n : '15-60 minutes (registry NS propagation)'\n\n if (!args.yes) {\n const ok = await confirm(\n `Buy ${args.domain} for ${price}/yr (auto-renews; non-refundable), attach to ${appName}? Provisioning takes ${expectedTime}.`,\n )\n if (!ok) {\n console.log('Cancelled.')\n return\n }\n }\n\n const checkout = await api<{ purchaseId: string; sessionId: string; url: string; chargedCents: number }>(\n token,\n '/api/domains/checkout',\n {\n method: 'POST',\n body: JSON.stringify({ domain: args.domain, appName }),\n },\n )\n\n if (args.json) {\n process.stdout.write(JSON.stringify({ ...checkout, expectedTime, registrar: result.registrar }, null, 2) + '\\n')\n } else {\n console.log(`Stripe Checkout: ${checkout.url}`)\n }\n\n if (!args['no-open'] && process.stdin.isTTY) {\n openBrowser(checkout.url)\n }\n\n if (args['no-wait']) return\n\n // Poll until active or failed.\n // Timeout depends on registrar — CF can take 5 min worst case, Porkbun\n // up to 60 min for slow registries. User can Ctrl-C and resume polling\n // later via `deepspace domain status <domain>` — provisioning runs\n // server-side regardless.\n const timeoutMs = result.registrar === 'cloudflare' ? 5 * 60 * 1000 : 60 * 60 * 1000\n if (!args.json) {\n console.log(`Waiting for payment & provisioning (up to ${expectedTime}). Press Ctrl-C anytime —`)\n console.log(`provisioning continues server-side; check later with \\`deepspace domain status ${args.domain}\\`.`)\n }\n const deadline = Date.now() + timeoutMs\n let lastStatus = ''\n while (Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 5000))\n try {\n const detail = await api<{ domain: DomainPurchase }>(\n token,\n `/api/domains/${checkout.purchaseId}`,\n )\n if (detail.domain.status !== lastStatus) {\n lastStatus = detail.domain.status\n if (!args.json) console.log(` → ${lastStatus}`)\n }\n if (detail.domain.status === 'active') {\n if (args.json) {\n process.stdout.write(JSON.stringify({ ...checkout, status: 'active', domain: args.domain }, null, 2) + '\\n')\n } else {\n console.log(`✓ ${args.domain} is live and pointing at ${appName}`)\n }\n return\n }\n if (detail.domain.status.startsWith('failed:')) {\n console.error(`Provisioning failed: ${detail.domain.statusError ?? detail.domain.status}`)\n process.exit(1)\n }\n } catch (err) {\n // Transient — keep polling\n if (!args.json) console.error(`(poll error: ${err instanceof Error ? err.message : String(err)})`)\n }\n }\n console.error(`Polling timed out. Provisioning may still be in progress; check with:`)\n console.error(` deepspace domain status ${args.domain}`)\n process.exit(1)\n },\n})\n\n// ============================================================================\n// list\n// ============================================================================\n\nconst list = defineCommand({\n meta: { name: 'list', description: 'List your domains' },\n args: {\n json: { type: 'boolean', description: 'Emit JSON' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const result = await api<{ domains: DomainPurchase[] }>(token, '/api/domains')\n if (args.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n if (result.domains.length === 0) {\n console.log('No domains. Try `deepspace domain search <name>`.')\n return\n }\n console.log(`DOMAIN APP STATUS EXPIRES AUTO-RENEW`)\n for (const d of result.domains) {\n console.log(\n `${d.domain.padEnd(35)} ${d.appName.padEnd(20)} ${d.status.padEnd(20)} ${fmtDate(d.expiresAt).padEnd(12)} ${d.autoRenew ? 'on' : 'off'}`,\n )\n }\n },\n})\n\n// ============================================================================\n// status\n// ============================================================================\n\nconst status = defineCommand({\n meta: { name: 'status', description: 'Show details for one domain' },\n args: {\n domain: { type: 'positional', description: 'Domain', required: true },\n json: { type: 'boolean' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const all = await api<{ domains: DomainPurchase[] }>(token, '/api/domains')\n const found = all.domains.find((d) => d.domain === args.domain)\n if (!found) {\n console.error(`No domain ${args.domain} in your account`)\n process.exit(1)\n }\n if (args.json) {\n process.stdout.write(JSON.stringify(found, null, 2) + '\\n')\n return\n }\n console.log(`Domain: ${found.domain}`)\n console.log(`Status: ${found.status}${found.statusError ? ` (${found.statusError})` : ''}`)\n console.log(`Attached app: ${found.appName}`)\n console.log(`Registrar: ${found.registrar}`)\n console.log(`Registered: ${fmtDate(found.registeredAt)}`)\n console.log(`Expires: ${fmtDate(found.expiresAt)}`)\n console.log(`Auto-renew: ${found.autoRenew ? 'on' : 'off'}`)\n console.log(`Charged: ${fmtCents(found.chargedCents)}/yr`)\n },\n})\n\n// ============================================================================\n// attach\n// ============================================================================\n\nconst attach = defineCommand({\n meta: { name: 'attach', description: 'Re-point a domain at a different app' },\n args: {\n domain: { type: 'positional', description: 'Domain to re-point', required: true },\n app: { type: 'string', description: 'Target app (defaults to ./wrangler.toml)' },\n json: { type: 'boolean' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const targetApp = requireAppName(args.app)\n const all = await api<{ domains: DomainPurchase[] }>(token, '/api/domains')\n const found = all.domains.find((d) => d.domain === args.domain)\n if (!found) {\n console.error(`No domain ${args.domain} in your account`)\n process.exit(1)\n }\n const result = await api<{ success: boolean; appName: string }>(\n token,\n `/api/domains/${found.id}/reattach`,\n {\n method: 'POST',\n body: JSON.stringify({ appName: targetApp }),\n },\n )\n if (args.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n console.log(`✓ ${args.domain} now points at ${targetApp}`)\n },\n})\n\n// ============================================================================\n// detach\n// ============================================================================\n\nconst detach = defineCommand({\n meta: {\n name: 'detach',\n description: 'Stop routing the domain (keeps the registration; auto-renew unchanged)',\n },\n args: {\n domain: { type: 'positional', description: 'Domain to detach', required: true },\n yes: { type: 'boolean', description: 'Skip the confirmation prompt' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const all = await api<{ domains: DomainPurchase[] }>(token, '/api/domains')\n const found = all.domains.find((d) => d.domain === args.domain)\n if (!found) {\n console.error(`No domain ${args.domain} in your account`)\n process.exit(1)\n }\n if (!args.yes) {\n const ok = await confirm(\n `Detach ${args.domain}? Routing will stop; the domain stays registered (auto-renew is unchanged).`,\n )\n if (!ok) {\n console.log('Cancelled.')\n return\n }\n }\n await api(token, `/api/domains/${found.id}`, { method: 'DELETE' })\n console.log(`✓ ${args.domain} detached. Use \\`deepspace domain attach\\` to re-route, or \\`renew --auto off\\` to stop auto-renewal.`)\n },\n})\n\n// ============================================================================\n// renew\n// ============================================================================\n\nconst renew = defineCommand({\n meta: { name: 'renew', description: 'Toggle auto-renewal at the registrar' },\n args: {\n domain: { type: 'positional', description: 'Domain', required: true },\n auto: { type: 'string', description: '\"on\" or \"off\"', required: true },\n },\n async run({ args }) {\n if (args.auto !== 'on' && args.auto !== 'off') {\n console.error('--auto must be \"on\" or \"off\"')\n process.exit(1)\n }\n const token = await ensureToken()\n const all = await api<{ domains: DomainPurchase[] }>(token, '/api/domains')\n const found = all.domains.find((d) => d.domain === args.domain)\n if (!found) {\n console.error(`No domain ${args.domain} in your account`)\n process.exit(1)\n }\n const enabled = args.auto === 'on'\n await api(token, `/api/domains/${found.id}/auto-renew`, {\n method: 'POST',\n body: JSON.stringify({ autoRenew: enabled }),\n })\n console.log(`✓ ${args.domain} auto-renew ${enabled ? 'enabled' : 'disabled'}`)\n },\n})\n\n// ============================================================================\n// open in browser — best-effort\n// ============================================================================\n\nfunction openBrowser(url: string): void {\n try {\n if (process.platform === 'darwin') execSync(`open ${JSON.stringify(url)}`)\n else if (process.platform === 'win32') execSync(`start \"\" ${JSON.stringify(url)}`)\n else execSync(`xdg-open ${JSON.stringify(url)} 2>/dev/null || true`)\n } catch {\n // Best-effort — user can open the URL manually\n }\n}\n\n// ============================================================================\n// Top-level\n// ============================================================================\n\n// Note: no `run()` on the parent — citty otherwise calls it after every\n// subcommand finishes, which prints spurious help text.\n//\n// `detectAppName` is imported for type-checking the `--app` defaulting in\n// each subcommand; not used here directly.\nvoid detectAppName\n\nexport default defineCommand({\n meta: { name: 'domain', description: 'Buy and manage custom domains' },\n subCommands: { search, buy, list, status, attach, detach, renew },\n})\n","/**\n * Shared helper: read the current project's app name from `./wrangler.toml`.\n *\n * Used by commands that operate on \"the current app\" — `deploy`, `domain buy`,\n * `domain attach`, etc. Lets agents and scripts run from inside a project\n * directory without redundantly passing `--app <name>`.\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\n\n/**\n * Read the app name from `wrangler.toml` in the given directory (default cwd).\n * Returns null if no wrangler.toml exists or the file lacks a `name` field.\n */\nexport function detectAppName(cwd: string = process.cwd()): string | null {\n const wranglerPath = join(resolve(cwd), 'wrangler.toml')\n if (!existsSync(wranglerPath)) return null\n try {\n const cfg = parseToml(readFileSync(wranglerPath, 'utf-8')) as { name?: string }\n return typeof cfg.name === 'string' && cfg.name.length > 0 ? cfg.name : null\n } catch {\n return null\n }\n}\n\n/**\n * Resolve the app name from explicit arg or wrangler.toml.\n * Throws with a clear message if neither is available.\n */\nexport function requireAppName(explicit: string | undefined, cwd?: string): string {\n if (explicit) return explicit\n const detected = detectAppName(cwd)\n if (detected) return detected\n throw new Error(\n 'No app specified. Pass --app <name>, or run from an app directory with a wrangler.toml.',\n )\n}\n","/**\n * deepspace integrations <subcommand>\n *\n * Namespace for working with platform integrations from the command line.\n *\n * deepspace integrations # prints help\n * deepspace integrations list # list all\n * deepspace integrations info openai/chat-completion # schema + example\n * deepspace integrations invoke openai/chat-completion --body '{...}'\n *\n * `deepspace invoke ...` is a top-level alias for `integrations invoke ...`.\n * `deepspace invoke --list` is a shortcut for `integrations list`.\n *\n * All calls are made as the currently logged-in user (`deepspace whoami`).\n * That user is billed.\n *\n * No `run()` is defined on the parent — that matches the convention used\n * by `test-accounts` and prevents citty from firing both the parent and\n * a matched subcommand. Bare `deepspace integrations` (no subcommand)\n * prints citty's auto-generated help.\n */\n\nimport { defineCommand } from 'citty'\nimport { runInvoke, runInfo, runList } from './_invoke-impl'\n\nconst list = defineCommand({\n meta: {\n name: 'list',\n description: 'List all available integrations',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Print raw JSON (machine-readable)',\n default: false,\n },\n },\n async run({ args }) {\n try {\n await runList({ json: args.json })\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err))\n process.exit(1)\n }\n },\n})\n\nconst info = defineCommand({\n meta: {\n name: 'info',\n description: 'Print schema + example body for an integration endpoint',\n },\n args: {\n target: {\n type: 'positional',\n description: \"<integration>/<endpoint> (e.g. 'openai/chat-completion')\",\n required: true,\n },\n json: {\n type: 'boolean',\n description: 'Print raw JSON (machine-readable)',\n default: false,\n },\n },\n async run({ args }) {\n try {\n await runInfo({ target: args.target as string, json: args.json })\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err))\n process.exit(1)\n }\n },\n})\n\nconst invoke = defineCommand({\n meta: {\n name: 'invoke',\n description: 'Invoke a platform integration as the logged-in user',\n },\n args: {\n target: {\n type: 'positional',\n description: \"<integration>/<endpoint> (e.g. 'openai/chat-completion')\",\n required: true,\n },\n body: {\n type: 'string',\n alias: 'd',\n description: 'Inline JSON body',\n required: false,\n },\n 'body-file': {\n type: 'string',\n alias: 'f',\n description: 'Read JSON body from file (use - for stdin)',\n required: false,\n },\n json: {\n type: 'boolean',\n description: 'Print only the response JSON (machine-readable)',\n default: false,\n },\n timeout: {\n type: 'string',\n description: 'Request timeout in milliseconds (default: 120000)',\n required: false,\n },\n },\n async run({ args }) {\n try {\n const timeout = args.timeout != null ? Number(args.timeout) : undefined\n if (timeout != null && (!Number.isFinite(timeout) || timeout <= 0)) {\n throw new Error(`Invalid --timeout '${args.timeout}'. Must be a positive number of milliseconds.`)\n }\n await runInvoke({\n target: args.target as string,\n body: args.body,\n bodyFile: args['body-file'],\n json: args.json,\n timeout,\n })\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err))\n process.exit(1)\n }\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'integrations',\n description: 'List, inspect, and invoke platform integrations',\n },\n subCommands: {\n list,\n info,\n invoke,\n },\n})\n","/**\n * Shared implementation for `deepspace invoke` and `deepspace integrations *`.\n *\n * The CLI invokes platform integrations as the currently logged-in user\n * (the same identity shown by `deepspace whoami`). That user is billed.\n *\n * This module is the single source of truth for:\n * - listing the integration catalog\n * - showing per-endpoint info (schema + example body)\n * - making the actual POST call\n *\n * Both `commands/invoke.ts` (top-level alias) and `commands/integrations.ts`\n * (namespaced subcommands) delegate here so the behavior never drifts.\n *\n * Why `flushAndExit` is used (only on the --json paths):\n * After every subcommand runs, citty resumes the root command's run(),\n * which prints \"deepspace CLI — run `npx deepspace --help` for usage\" to\n * stdout. That trailing line corrupts --json output for any downstream\n * consumer that JSON.parses stdout (jq, file redirects, agent scripts,\n * the e2e tests). We can't suppress the root run() without modifying\n * cli.ts (out of scope), so on the --json paths we exit the process\n * before citty resumes — but we must wait for stdout to drain first,\n * because piped writes are async via libuv and large JSON outputs (the\n * full catalog is ~78KB) exceed the pipe buffer. See flushAndExit().\n *\n * Human-mode paths don't need this: the trailing line is just one more\n * line of prose, harmless. Those paths return / process.exit() normally.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { ensureToken } from '../auth'\nimport { ENVS } from '../env'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? ENVS.prod.api\nconst DEFAULT_TIMEOUT_MS = 120_000\n\ninterface EndpointInfo {\n endpoint: string\n billing: { model: string; baseCost: number; currency: string }\n inputSchema: Record<string, unknown> | null\n example: Record<string, unknown> | null\n}\n\ninterface Catalog {\n integrations: Record<string, EndpointInfo[]>\n}\n\nexport interface InvokeArgs {\n target: string\n body?: string\n bodyFile?: string\n json?: boolean\n timeout?: number\n}\n\nexport interface InfoArgs {\n target: string\n json?: boolean\n}\n\nexport interface ListArgs {\n json?: boolean\n}\n\n/**\n * Parse \"<integration>/<endpoint>\" into its two segments.\n * Throws on malformed input.\n */\nfunction parseTarget(target: string): { integration: string; endpoint: string } {\n if (!target || typeof target !== 'string') {\n throw new Error(\"Missing target. Expected '<integration>/<endpoint>' (e.g. 'openai/chat-completion').\")\n }\n const parts = target.split('/')\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new Error(`Bad target '${target}'. Expected '<integration>/<endpoint>' (e.g. 'openai/chat-completion').`)\n }\n return { integration: parts[0], endpoint: parts[1] }\n}\n\n/**\n * Resolve the request body from --body, --body-file, or default to '{}'.\n * Errors if both --body and --body-file are provided, or the body isn't\n * valid JSON.\n */\nfunction resolveBody(opts: { body?: string; bodyFile?: string }): string {\n if (opts.body != null && opts.bodyFile != null) {\n throw new Error('Pass either --body or --body-file, not both.')\n }\n\n let raw: string\n if (opts.body != null) {\n raw = opts.body\n } else if (opts.bodyFile != null) {\n raw = opts.bodyFile === '-' ? readFileSync(0, 'utf-8') : readFileSync(opts.bodyFile, 'utf-8')\n } else {\n return '{}'\n }\n\n // Validate it parses as JSON so we fail fast with a clear message.\n try {\n JSON.parse(raw)\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'invalid JSON'\n throw new Error(`Body is not valid JSON: ${msg}`)\n }\n return raw\n}\n\n/**\n * Exit the process after stdout has drained.\n *\n * Used only on --json paths. Two problems it solves:\n * 1. Plain `process.exit()` truncates piped stdout for outputs larger\n * than the pipe buffer (~64KB on macOS) — `integrations --json | jq`\n * would lose data because libuv flushes asynchronously.\n * 2. Plain `return` lets citty fire the root command's run(), which\n * appends a trailing prose line that breaks JSON.parse on stdout.\n *\n * The pattern: schedule a zero-byte write so its callback fires only\n * after all prior writes have been flushed, then exit from the callback.\n * Returns a Promise that never resolves so the caller can `await` it\n * with no chance of citty continuing past us.\n */\nfunction flushAndExit(code: number): Promise<never> {\n return new Promise<never>(() => {\n process.stdout.write('', () => process.exit(code))\n })\n}\n\nasync function fetchCatalog(): Promise<Catalog> {\n const res = await fetch(`${API_URL}/api/integrations`)\n if (!res.ok) {\n throw new Error(`Failed to fetch integration catalog (${res.status})`)\n }\n return (await res.json()) as Catalog\n}\n\nfunction findEndpoint(catalog: Catalog, integration: string, endpoint: string): EndpointInfo | null {\n const endpoints = catalog.integrations[integration]\n if (!endpoints) return null\n return endpoints.find((e) => e.endpoint === endpoint) ?? null\n}\n\nfunction formatCurrency(value: number, currency: string): string {\n if (currency === 'USD') return `$${value}`\n return `${value} ${currency}`\n}\n\n/**\n * `deepspace integrations` (default action) / `--list`\n * Prints the catalog grouped by integration.\n */\nexport async function runList(args: ListArgs): Promise<void> {\n const catalog = await fetchCatalog()\n\n if (args.json) {\n process.stdout.write(JSON.stringify(catalog) + '\\n')\n await flushAndExit(0)\n }\n\n const names = Object.keys(catalog.integrations).sort()\n if (names.length === 0) {\n console.log('No integrations available.')\n return\n }\n\n for (const name of names) {\n console.log(name)\n const endpoints = [...catalog.integrations[name]].sort((a, b) => a.endpoint.localeCompare(b.endpoint))\n const widest = Math.max(...endpoints.map((e) => e.endpoint.length))\n for (const ep of endpoints) {\n const pad = ep.endpoint.padEnd(widest)\n const cost = formatCurrency(ep.billing.baseCost, ep.billing.currency)\n console.log(` ${pad} ${ep.billing.model.padEnd(12)} ${cost}`)\n }\n console.log()\n }\n\n console.log(\"Run 'deepspace integrations info <integration>/<endpoint>' for the request schema.\")\n}\n\n/**\n * `deepspace integrations info <target>` / `--info`\n * Prints the schema + example body for a single endpoint.\n */\nexport async function runInfo(args: InfoArgs): Promise<void> {\n const { integration, endpoint } = parseTarget(args.target)\n const catalog = await fetchCatalog()\n const info = findEndpoint(catalog, integration, endpoint)\n\n if (!info) {\n const available = catalog.integrations[integration]\n if (!available) {\n const names = Object.keys(catalog.integrations).sort().join(', ')\n throw new Error(`Unknown integration '${integration}'. Available: ${names}`)\n }\n const endpoints = available.map((e) => e.endpoint).join(', ')\n throw new Error(`Unknown endpoint '${endpoint}' for '${integration}'. Available: ${endpoints}`)\n }\n\n if (args.json) {\n process.stdout.write(JSON.stringify(info) + '\\n')\n await flushAndExit(0)\n }\n\n console.log(`${integration}/${endpoint}`)\n console.log(` billing: ${info.billing.model}, ${formatCurrency(info.billing.baseCost, info.billing.currency)} per call`)\n console.log()\n console.log('Input schema:')\n console.log(info.inputSchema ? JSON.stringify(info.inputSchema, null, 2) : ' (no schema registered)')\n console.log()\n console.log('Example body:')\n console.log(info.example ? JSON.stringify(info.example, null, 2) : ' (no example available)')\n}\n\n/**\n * `deepspace invoke <target>` / `deepspace integrations invoke <target>`\n * Performs the actual integration call.\n */\nexport async function runInvoke(args: InvokeArgs): Promise<void> {\n const { integration, endpoint } = parseTarget(args.target)\n const body = resolveBody({ body: args.body, bodyFile: args.bodyFile })\n const timeoutMs = args.timeout ?? DEFAULT_TIMEOUT_MS\n\n let jwt: string\n try {\n jwt = await ensureToken()\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Error(msg)\n }\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n const startedAt = Date.now()\n\n let res: Response\n try {\n res = await fetch(`${API_URL}/api/integrations/${integration}/${endpoint}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${jwt}`,\n },\n body,\n signal: controller.signal,\n })\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') {\n throw new Error(`Request timed out after ${timeoutMs}ms`)\n }\n throw new Error(err instanceof Error ? err.message : 'Request failed')\n } finally {\n clearTimeout(timer)\n }\n\n const elapsed = Date.now() - startedAt\n let payload: Record<string, unknown>\n try {\n payload = (await res.json()) as Record<string, unknown>\n } catch {\n throw new Error(`Request failed (${res.status}) with non-JSON response`)\n }\n\n if (args.json) {\n process.stdout.write(JSON.stringify(payload) + '\\n')\n await flushAndExit(payload?.success === false || !res.ok ? 1 : 0)\n }\n\n const ok = payload?.success !== false && res.ok\n if (ok) {\n const data = 'data' in payload ? payload.data : payload\n console.log(JSON.stringify(data, null, 2))\n console.error(`\\n✓ ${integration}/${endpoint} (${elapsed}ms)`)\n return\n }\n\n // Error path\n const errMsg = (payload.error as string) ?? `Request failed (${res.status})`\n console.error(`✗ ${integration}/${endpoint} (${res.status}, ${elapsed}ms): ${errMsg}`)\n if (Array.isArray(payload.issues)) {\n for (const issue of payload.issues as Array<{ path?: string[]; message: string }>) {\n const path = issue.path?.length ? issue.path.join('.') : '(root)'\n console.error(` - ${path}: ${issue.message}`)\n }\n }\n if (res.status === 401) {\n console.error(\"\\nHint: run 'deepspace login' to authenticate.\")\n }\n process.exit(1)\n}\n","/**\n * deepspace invoke <integration>/<endpoint> [options]\n *\n * Top-level alias for `deepspace integrations invoke ...`. Calls a platform\n * integration as the currently logged-in user — the same identity shown by\n * `deepspace whoami`. That user is billed.\n *\n * deepspace invoke openai/chat-completion --body '{\"messages\":[...]}'\n * deepspace invoke openai/chat-completion --body-file req.json\n * cat req.json | deepspace invoke openai/chat-completion --body-file -\n * deepspace invoke openai/chat-completion --info\n * deepspace invoke --list\n */\n\nimport { defineCommand } from 'citty'\nimport { runInvoke, runInfo, runList } from './_invoke-impl'\n\nexport default defineCommand({\n meta: {\n name: 'invoke',\n description: 'Invoke a platform integration as the logged-in user',\n },\n args: {\n target: {\n type: 'positional',\n description: \"<integration>/<endpoint> (e.g. 'openai/chat-completion')\",\n required: false,\n },\n body: {\n type: 'string',\n alias: 'd',\n description: 'Inline JSON body',\n required: false,\n },\n 'body-file': {\n type: 'string',\n alias: 'f',\n description: 'Read JSON body from file (use - for stdin)',\n required: false,\n },\n json: {\n type: 'boolean',\n description: 'Print only the response JSON (machine-readable)',\n default: false,\n },\n info: {\n type: 'boolean',\n description: 'Print schema + example body for the endpoint, then exit',\n default: false,\n },\n list: {\n type: 'boolean',\n description: 'Print all available integrations, then exit',\n default: false,\n },\n timeout: {\n type: 'string',\n description: 'Request timeout in milliseconds (default: 120000)',\n required: false,\n },\n },\n async run({ args }) {\n try {\n if (args.list) {\n await runList({ json: args.json })\n return\n }\n if (args.info) {\n await runInfo({ target: args.target as string, json: args.json })\n return\n }\n const timeout = args.timeout != null ? Number(args.timeout) : undefined\n if (timeout != null && (!Number.isFinite(timeout) || timeout <= 0)) {\n throw new Error(`Invalid --timeout '${args.timeout}'. Must be a positive number of milliseconds.`)\n }\n await runInvoke({\n target: args.target as string,\n body: args.body,\n bodyFile: args['body-file'],\n json: args.json,\n timeout,\n })\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err))\n process.exit(1)\n }\n },\n})\n"],"mappings":";;;AAUA,SAAS,iBAAAA,iBAAe,eAAe;AACvC,SAAS,YAAAC,iBAAgB;AACzB,SAAS,gBAAAC,eAAc,cAAAC,oBAAkB;AACzC,SAAS,WAAAC,UAAS,QAAAC,cAAY;AAC9B,SAAS,qBAAqB;;;ACJ9B,SAAS,qBAAqB;AAC9B,SAAS,iBAAAC,gBAAe,iBAAiB;AACzC,SAAS,QAAAC,aAAY;AACrB,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,gBAAgB;AACzB,YAAY,OAAO;;;ACVnB,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,YAAY;AACrB,SAAS,SAAS,iBAAiB;AAE5B,IAAM,OAAO;AAAA,EAClB,KAAK;AAAA,IACH,MAAM;AAAA,IACN,KAAK;AAAA,IACL,UAAU;AAAA,IACV,QAAQ;AAAA,EACV;AAAA,EACA,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,KAAK;AAAA,IACL,UAAU;AAAA,IACV,QAAQ;AAAA,EACV;AACF;AAOA,eAAsB,eAAe,SAAkC;AACrE,QAAM,MAAM,MAAM,MAAM,GAAG,OAAO,gBAAgB;AAClD,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,IAAI,MAAM,mCAAmC,IAAI,MAAM,GAAG;AAAA,EAClE;AACA,QAAM,OAAQ,MAAM,IAAI,KAAK;AAC7B,MAAI,CAAC,KAAK,WAAW;AACnB,UAAM,IAAI,MAAM,iCAAiC;AAAA,EACnD;AACA,SAAO,KAAK;AACd;AAMA,SAAS,YAAY,QAA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I,gBAAgB;AAC9B;AAEA,IAAMC,UAASC,gBAAc;AAAA,EAC3B,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA,EACf;AAAA,EACA,MAAM;AAAA,IACJ,MAAM;AAAA,MACJ,MAAM;AAAA,MACN,aAAa;AAAA,MACb,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA,IAAI,EAAE,KAAK,GAAG;AACZ,UAAM,OAAO,KAAK,OAAO,IAAI,KAAK,IAAI,KAAK;AAC3C,YAAQ,IAAI,gCAAgC,IAAI;AAAA,CAAI;AACpD,IAAAC,UAAS,8BAA8B,IAAI,IAAI,EAAE,OAAO,UAAU,CAAC;AAAA,EACrE;AACF,CAAC;AAED,IAAM,OAAOD,gBAAc;AAAA,EACzB,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,SAAS,IAAI;AAAA,IACb,aAAa;AAAA,EACf;AAAA,EACA,aAAa;AAAA,IACX,QAAAD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,iBAAiB;AAAA,IACjB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAKF,CAAC;AAED,QAAQ,IAAI;","names":["defineCommand","execSync","readFileSync","existsSync","dirname","join","writeFileSync","join","join","writeFileSync","resolve","defineCommand","existsSync","readFileSync","join","homedir","AUTH_URL","join","homedir","defineCommand","existsSync","readFileSync","defineCommand","existsSync","join","readFileSync","writeFileSync","existsSync","mkdirSync","join","homedir","AUTH_URL","DIR","join","homedir","SESSION_PATH","TOKEN_PATH","existsSync","readFileSync","mkdirSync","writeFileSync","defineCommand","existsSync","join","defineCommand","DEFAULT_PORT","resolvePort","defineCommand","existsSync","join","resolve","spawnSync","DEFAULT_PORT","defineCommand","resolve","resolvePort","existsSync","join","spawnSync","defineCommand","p","readFileSync","writeFileSync","existsSync","mkdirSync","join","homedir","SESSION_COOKIE","AUTH_URL","DIR","join","homedir","existsSync","readFileSync","mkdirSync","writeFileSync","SESSION_PATH","defineCommand","defineCommand","execSync","readFileSync","existsSync","parseToml","join","resolve","p","defineCommand","resolve","join","existsSync","parseToml","readFileSync","execSync","defineCommand","readFileSync","existsSync","join","parseToml","p","DEPLOY_URL","defineCommand","join","existsSync","parseToml","readFileSync","defineCommand","defineCommand","defineCommand","existsSync","resolve","join","execSync","defineCommand","execSync","existsSync","readFileSync","join","resolve","parseToml","confirm","resolve","defineCommand","openBrowser","list","execSync","defineCommand","list","defineCommand","readFileSync","API_URL","readFileSync","info","list","defineCommand","defineCommand","defineCommand","dirname","readFileSync","join","existsSync","create","defineCommand","execSync"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli/cli.ts","../src/cli/commands/login.ts","../src/cli/env.ts","../src/cli/session.ts","../src/cli/commands/logout.ts","../src/cli/commands/dev.ts","../src/cli/auth.ts","../src/cli/commands/kill.ts","../src/cli/commands/test.ts","../src/cli/commands/test-accounts.ts","../src/cli/commands/deploy.ts","../src/server/rooms/binding-manifest.ts","../src/server/rooms/app-name.ts","../src/cli/commands/undeploy.ts","../src/cli/commands/whoami.ts","../src/cli/commands/add.ts","../src/cli/commands/domain.ts","../src/cli/lib/app-context.ts","../src/cli/commands/integrations.ts","../src/cli/commands/_invoke-impl.ts","../src/cli/commands/invoke.ts"],"sourcesContent":["/**\n * DeepSpace CLI\n *\n * Commands:\n * login — authenticate with your DeepSpace account\n * deploy — build and deploy your app to *.app.space\n * undeploy — remove a deployed app\n * create — redirects to `npm create deepspace`\n */\n\nimport { defineCommand, runMain } from 'citty'\nimport { execSync } from 'node:child_process'\nimport { readFileSync, existsSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport login from './commands/login'\nimport logout from './commands/logout'\nimport dev from './commands/dev'\nimport kill from './commands/kill'\nimport test from './commands/test'\nimport testAccounts from './commands/test-accounts'\nimport deploy from './commands/deploy'\nimport undeploy from './commands/undeploy'\nimport whoami from './commands/whoami'\nimport add from './commands/add'\nimport domain from './commands/domain'\nimport integrations from './commands/integrations'\nimport invoke from './commands/invoke'\n\n// Read own version from package.json so the CLI banner stays in sync with publishes.\n// __dirname of the bundled output is <pkg>/dist; package.json sits one level up.\nconst __dirname = dirname(fileURLToPath(import.meta.url))\nconst pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'))\n\n// workerd doesn't auto-discover system CAs in containers — outbound HTTPS to the\n// auth/api workers fails with \"TLS peer's certificate is not trusted\" until we\n// point it at the standard Debian/Ubuntu cert bundle. Harmless on macOS (path\n// doesn't exist, env var not set).\nif (\n process.platform === 'linux' &&\n !process.env.SSL_CERT_FILE &&\n existsSync('/etc/ssl/certs/ca-certificates.crt')\n) {\n process.env.SSL_CERT_FILE = '/etc/ssl/certs/ca-certificates.crt'\n}\n\nconst create = defineCommand({\n meta: {\n name: 'create',\n description: 'Create a new DeepSpace app',\n },\n args: {\n name: {\n type: 'positional',\n description: 'App name',\n required: false,\n },\n },\n run({ args }) {\n const name = args.name ? ` ${args.name}` : ''\n console.log(`Running: npm create deepspace${name}\\n`)\n execSync(`npm create deepspace@latest${name}`, { stdio: 'inherit' })\n },\n})\n\nconst main = defineCommand({\n meta: {\n name: 'deepspace',\n version: pkg.version,\n description: 'DeepSpace SDK CLI',\n },\n subCommands: {\n create,\n login,\n logout,\n whoami,\n dev,\n kill,\n test,\n 'test-accounts': testAccounts,\n add,\n integrations,\n invoke,\n deploy,\n undeploy,\n domain,\n },\n // No `run()` here — citty cascades parent run() AFTER subcommand finishes,\n // which corrupts agent-friendly output (`--json`) and prints noise on every\n // command. Citty's default behavior when no subcommand matches is to print\n // help, which is what we want for `deepspace` with no args.\n})\n\nrunMain(main)\n","/**\n * deepspace login\n *\n * Opens the browser to sign in with GitHub or Google.\n * CLI polls the auth worker until login is complete.\n *\n * deepspace login # browser-based OAuth\n * deepspace login --email x --password y # non-interactive (CI/agents)\n */\n\nimport { defineCommand } from 'citty'\nimport { writeFileSync, mkdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\nimport { exec } from 'node:child_process'\nimport { platform } from 'node:os'\nimport * as p from '@clack/prompts'\n\nimport { ENVS } from '../env'\nimport { exchangeSession, SESSION_COOKIE } from '../session'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? ENVS.prod.auth\n\nexport default defineCommand({\n meta: {\n name: 'login',\n description: 'Log in to your DeepSpace account',\n },\n args: {\n email: {\n type: 'string',\n description: 'Email address (non-interactive mode)',\n required: false,\n },\n password: {\n type: 'string',\n description: 'Password (non-interactive mode)',\n required: false,\n },\n },\n async run({ args }) {\n // Non-interactive mode for CI/agents with email+password\n if (args.email && args.password) {\n console.log(`Signing in as ${args.email}...`)\n await doEmailLogin(args.email, args.password)\n console.log('Logged in')\n return\n }\n\n // Browser-based OAuth flow\n p.intro('DeepSpace Login')\n\n const s = p.spinner()\n s.start('Creating login session...')\n\n // 1. Create a CLI session\n const sessionRes = await fetch(`${AUTH_URL}/api/auth/cli/session`, { method: 'POST' })\n if (!sessionRes.ok) {\n s.stop('Failed')\n p.cancel('Could not create login session')\n process.exit(1)\n }\n const sessionData = (await sessionRes.json()) as { sessionId?: string; loginUrl?: string }\n if (!sessionData.sessionId || !sessionData.loginUrl) {\n s.stop('Failed')\n p.cancel('Could not create login session')\n process.exit(1)\n }\n\n const { sessionId, loginUrl } = sessionData as { sessionId: string; loginUrl: string }\n\n s.stop('Opening browser...')\n p.log.info(`If the browser doesn't open, visit:\\n ${loginUrl}`)\n\n // 2. Open browser\n openBrowser(loginUrl)\n\n // 3. Poll for completion\n s.start('Waiting for authentication...')\n const result = await pollForCompletion(sessionId)\n\n if (!result) {\n s.stop('Timed out')\n p.cancel('Login timed out. Run `deepspace login` to try again.')\n process.exit(1)\n }\n\n // 4. Store credentials\n storeCredentials(result.sessionToken, result.jwt)\n\n s.stop('Authenticated')\n p.outro(`Logged in as ${result.name ?? result.email}`)\n },\n})\n\ninterface LoginResult {\n sessionToken: string\n jwt: string\n email: string\n name: string | null\n}\n\nasync function pollForCompletion(sessionId: string): Promise<LoginResult | null> {\n const maxAttempts = 120 // 10 minutes at 5s intervals\n const interval = 5000\n\n for (let i = 0; i < maxAttempts; i++) {\n await sleep(interval)\n\n try {\n const res = await fetch(`${AUTH_URL}/api/auth/cli/status/${sessionId}`)\n\n if (res.status === 410 || res.status === 404) return null // expired / not found\n if (!res.ok) continue\n\n const data = (await res.json()) as {\n state?: string\n sessionToken?: string\n jwt?: string\n email?: string\n name?: string\n }\n\n if (data.state === 'complete' && data.sessionToken && data.jwt) {\n return {\n sessionToken: data.sessionToken,\n jwt: data.jwt,\n email: data.email ?? '',\n name: data.name ?? null,\n }\n }\n } catch {\n // Network error, keep polling\n }\n }\n\n return null\n}\n\nfunction storeCredentials(sessionToken: string, jwt: string) {\n const dir = join(homedir(), '.deepspace')\n mkdirSync(dir, { recursive: true })\n writeFileSync(join(dir, 'session'), sessionToken, { mode: 0o600 })\n writeFileSync(join(dir, 'token'), jwt, { mode: 0o600 })\n}\n\nfunction openBrowser(url: string) {\n const cmd =\n platform() === 'darwin'\n ? `open \"${url}\"`\n : platform() === 'win32'\n ? `start \"\" \"${url}\"`\n : `xdg-open \"${url}\"`\n\n exec(cmd, () => {\n // Ignore errors — we already showed the URL\n })\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n// ── Email/password login (for test accounts and CI) ────────────────\n\nasync function doEmailLogin(email: string, password: string): Promise<void> {\n const res = await fetch(`${AUTH_URL}/api/auth/sign-in/email`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Origin: AUTH_URL },\n body: JSON.stringify({ email, password }),\n redirect: 'manual',\n })\n\n if (!res.ok) {\n const body = (await res.json().catch(() => ({}))) as { message?: string }\n throw new Error(body.message ?? `Authentication failed (${res.status})`)\n }\n\n const setCookie = res.headers.get('set-cookie') ?? ''\n const cookieMatch = setCookie.match(new RegExp(`${SESSION_COOKIE}=([^;]+)`))\n if (!cookieMatch) {\n throw new Error('No session cookie returned')\n }\n const sessionToken = decodeURIComponent(cookieMatch[1])\n\n const jwt = await exchangeSession(AUTH_URL, sessionToken)\n if (!jwt) {\n throw new Error('JWT issuance failed')\n }\n\n storeCredentials(sessionToken, jwt)\n}\n","/**\n * DeepSpace environment configuration.\n *\n * Shared between `dev`, `test`, and `deploy` commands.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\n\nexport const ENVS = {\n dev: {\n auth: 'https://deepspace-auth.eudaimonicincorporated.workers.dev',\n api: 'https://deepspace-api.eudaimonicincorporated.workers.dev',\n platform: 'https://deepspace-platform-worker.eudaimonicincorporated.workers.dev',\n deploy: 'https://deepspace-deploy.eudaimonicincorporated.workers.dev',\n },\n prod: {\n auth: 'https://deepspace-auth.eudaimonicincorporated.workers.dev',\n api: 'https://deepspace-api.eudaimonicincorporated.workers.dev',\n platform: 'https://deepspace-platform-worker.eudaimonicincorporated.workers.dev',\n deploy: 'https://deepspace-deploy.eudaimonicincorporated.workers.dev',\n },\n} as const\n\nexport type EnvName = keyof typeof ENVS\n\n/**\n * Fetch the JWT public key from an auth worker's /api/auth/jwks endpoint.\n */\nexport async function fetchPublicKey(authUrl: string): Promise<string> {\n const res = await fetch(`${authUrl}/api/auth/jwks`)\n if (!res.ok) {\n throw new Error(`Failed to fetch JWT public key (${res.status})`)\n }\n const data = (await res.json()) as { publicKey?: string }\n if (!data.publicKey) {\n throw new Error('JWKS response missing publicKey')\n }\n return data.publicKey\n}\n\n/**\n * Read the app name from the app's wrangler.toml.\n * `deepspace dev` runs in an app directory; the name is required.\n */\nfunction readAppName(appDir: string): string {\n const wranglerPath = join(appDir, 'wrangler.toml')\n if (!existsSync(wranglerPath)) {\n throw new Error('No wrangler.toml found. Are you in a DeepSpace app directory?')\n }\n const parsed = parseToml(readFileSync(wranglerPath, 'utf-8')) as { name?: string }\n if (!parsed.name) {\n throw new Error('wrangler.toml has no `name` field')\n }\n return parsed.name\n}\n\n/**\n * Mint a long-lived app-owner JWT from the auth worker.\n *\n * The caller passes their own short-lived user JWT (obtained via\n * `ensureToken()` from auth.ts) and the target env's auth URL. The auth\n * worker verifies the caller, signs a 10-year owner-scoped token bound to\n * `appName`, and returns it. This same token is used in dev (written into\n * `.dev.vars`) and in production (injected as a secret at deploy time).\n */\nexport async function mintAppOwnerJwt(\n authUrl: string,\n callerJwt: string,\n appName: string,\n): Promise<string> {\n const res = await fetch(`${authUrl}/api/auth/mint-app-token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${callerJwt}`,\n },\n body: JSON.stringify({ appName }),\n })\n if (!res.ok) {\n const err = await res.text().catch(() => '')\n throw new Error(`Failed to mint APP_OWNER_JWT (${res.status}): ${err}`)\n }\n const body = (await res.json()) as { token?: string; error?: string }\n if (!body.token) {\n throw new Error(`Auth worker returned no token: ${body.error ?? 'unknown error'}`)\n }\n return body.token\n}\n\n/**\n * Keys the SDK manages in .dev.vars. Anything else in the file is treated as\n * a user-owned custom var and preserved verbatim across dev/test runs.\n */\nconst SDK_MANAGED_KEYS = new Set([\n 'AUTH_JWT_PUBLIC_KEY',\n 'AUTH_JWT_ISSUER',\n 'AUTH_WORKER_URL',\n 'API_WORKER_URL',\n 'PLATFORM_WORKER_URL',\n 'OWNER_USER_ID',\n 'APP_OWNER_JWT',\n 'INTERNAL_STORAGE_HMAC_SECRET',\n 'ALLOW_DEBUG_ROUTES',\n])\n\n// Marker the SDK writes between its own keys and user-managed content. We\n// recognize and strip this line on read so it doesn't accumulate across runs.\nexport const DEV_VARS_DIVIDER =\n '# --- not managed by the SDK; preserved across dev/test runs ---'\n\n/**\n * Strip SDK-managed lines from an existing .dev.vars file, preserving all\n * other content (comments, blank lines, custom KEY=value pairs, multi-line\n * quoted values). Also strips the SDK divider marker so it doesn't double\n * up across runs.\n *\n * Exported for testing.\n */\nexport function extractCustomDevVars(content: string): string {\n const lines = content.split('\\n')\n const out: string[] = []\n let i = 0\n while (i < lines.length) {\n const line = lines[i]\n if (line.trim() === DEV_VARS_DIVIDER.trim()) {\n // Drop our own divider — writeDevVars will re-add a single one.\n i++\n continue\n }\n const eq = line.indexOf('=')\n const keyMatch = eq >= 0 ? line.slice(0, eq).match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*$/) : null\n if (!keyMatch) {\n // Comment, blank, or non-key line — preserve verbatim.\n out.push(line)\n i++\n continue\n }\n const key = keyMatch[1]\n const valStart = line.slice(eq + 1)\n const block: string[] = [line]\n // Multi-line quoted value: opens with `\"` and the rest of the line has no\n // closing quote. Keep accumulating until a closing `\"` lands.\n if (valStart.startsWith('\"') && !hasUnescapedQuote(valStart.slice(1))) {\n i++\n while (i < lines.length) {\n block.push(lines[i])\n const closed = hasUnescapedQuote(lines[i])\n i++\n if (closed) break\n }\n } else {\n i++\n }\n if (!SDK_MANAGED_KEYS.has(key)) {\n out.push(...block)\n }\n }\n // Trim trailing blanks so we don't accumulate them across runs.\n while (out.length && out[out.length - 1].trim() === '') out.pop()\n return out.join('\\n')\n}\n\nfunction hasUnescapedQuote(s: string): boolean {\n let escaped = false\n for (const ch of s) {\n if (escaped) {\n escaped = false\n continue\n }\n if (ch === '\\\\') {\n escaped = true\n continue\n }\n if (ch === '\"') return true\n }\n return false\n}\n\n/**\n * Parse a `.dev.vars` (dotenv) string into a key→value map.\n *\n * Handles:\n * - bare KEY=value\n * - KEY=\"quoted value\"\n * - multi-line KEY=\"-----BEGIN ...\\n-----END ...\"\n * - escaped quotes inside (`KEY=\"he said \\\"hi\\\"\"`)\n * - comments and blank lines (skipped)\n *\n * Used for two things:\n * 1. parsing the user-managed section of `.dev.vars` so the CLI can ship\n * app-defined secrets to production at deploy time (Option B,\n * `feedback_app_secrets_via_dev_vars`)\n * 2. round-tripping for tests\n *\n * Exported.\n */\nexport function parseDevVars(content: string): Record<string, string> {\n const result: Record<string, string> = {}\n const lines = content.split('\\n')\n let i = 0\n while (i < lines.length) {\n const line = lines[i]\n const trimmed = line.trim()\n if (!trimmed || trimmed.startsWith('#')) {\n i++\n continue\n }\n const eq = line.indexOf('=')\n if (eq < 0) {\n i++\n continue\n }\n const keyMatch = line.slice(0, eq).match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*$/)\n if (!keyMatch) {\n i++\n continue\n }\n const key = keyMatch[1]\n let value = line.slice(eq + 1)\n\n // Multi-line quoted value: opens with `\"` and the rest of the line has\n // no closing quote. Keep accumulating until a closing `\"` lands.\n let closed = !value.startsWith('\"') || hasUnescapedQuote(value.slice(1))\n if (!closed) {\n i++\n while (i < lines.length) {\n value += '\\n' + lines[i]\n if (hasUnescapedQuote(lines[i])) {\n closed = true\n i++\n break\n }\n i++\n }\n } else {\n i++\n }\n\n // Reject unterminated quoted values rather than silently corrupting the\n // secret. Without this guard, a `KEY=\"value with no closing quote` line\n // would round-trip through deploy as a literal leading `\"` in the value\n // — a near-impossible bug to debug in production.\n if (value.startsWith('\"') && !closed) {\n throw new Error(\n `parseDevVars: unterminated quoted value for key \"${key}\" — check your .dev.vars file for a missing closing quote.`,\n )\n }\n\n // Strip surrounding quotes (and unescape \\\" within) for quoted values.\n if (value.startsWith('\"') && value.endsWith('\"') && value.length >= 2) {\n value = value.slice(1, -1).replace(/\\\\\"/g, '\"')\n }\n\n result[key] = value\n }\n return result\n}\n\n/**\n * Write .dev.vars for an app, pointing to the specified environment's workers.\n *\n * Only the SDK-managed keys (see `SDK_MANAGED_KEYS`) are rewritten on each\n * call. Anything else in `.dev.vars` — third-party API tokens, R2 creds for\n * cross-account buckets, custom feature flags — is preserved verbatim.\n *\n * Includes a freshly-minted `APP_OWNER_JWT` so server-side code in the app\n * (DO alarms, cron handlers, autonomous agents) can call the API worker\n * proxy without any further auth plumbing. Uses the same flow as production:\n * the auth-worker mints the token, we store it as an env var.\n */\nexport async function writeDevVars(\n appDir: string,\n env: EnvName,\n ownerId: string,\n callerJwt: string,\n): Promise<void> {\n const urls = ENVS[env]\n const publicKey = await fetchPublicKey(urls.auth)\n const appName = readAppName(appDir)\n const appOwnerJwt = await mintAppOwnerJwt(urls.auth, callerJwt, appName)\n\n // Wrangler's .dev.vars parser is dotenv-style: bare multi-line values are\n // truncated to the first line. The PEM public key spans multiple lines, so\n // it MUST be wrapped in double quotes (dotenv multi-line value syntax).\n // Without this, AUTH_JWT_PUBLIC_KEY ends up as just \"-----BEGIN PUBLIC KEY-----\"\n // and `importSPKI` throws `DataError: Invalid SPKI input`, which silently\n // breaks JWT verification on every WS connection (anonymous fallback).\n const sdkVars = [\n `AUTH_JWT_PUBLIC_KEY=\"${publicKey}\"`,\n `AUTH_JWT_ISSUER=${urls.auth}/api/auth`,\n `AUTH_WORKER_URL=${urls.auth}`,\n `API_WORKER_URL=${urls.api}`,\n `PLATFORM_WORKER_URL=${urls.platform}`,\n `OWNER_USER_ID=${ownerId}`,\n `APP_OWNER_JWT=${appOwnerJwt}`,\n `INTERNAL_STORAGE_HMAC_SECRET=dev-${Date.now()}`,\n // Open /api/debug/* (proxied to RecordRoom) for dev + tests only.\n // Production secrets never set this, so deployed apps 404 the route.\n `ALLOW_DEBUG_ROUTES=true`,\n ].join('\\n')\n\n const devVarsPath = join(appDir, '.dev.vars')\n const existing = existsSync(devVarsPath) ? readFileSync(devVarsPath, 'utf-8') : ''\n const custom = extractCustomDevVars(existing)\n const body = custom\n ? `${sdkVars}\\n\\n${DEV_VARS_DIVIDER}\\n${custom}\\n`\n : `${sdkVars}\\n`\n\n writeFileSync(devVarsPath, body)\n}\n","/**\n * CLI session helpers — exchange a Better Auth session cookie for a short-lived\n * JWT against the auth worker. Shared by `auth.ts` (token refresh for all\n * authenticated commands) and `login.ts` (email/password flow).\n */\n\nexport const SESSION_COOKIE = '__Secure-better-auth.session_token'\n\n/**\n * Exchange a Better Auth session token for a fresh JWT.\n * Returns null if the session is invalid or expired.\n */\nexport async function exchangeSession(\n authUrl: string,\n sessionToken: string,\n): Promise<string | null> {\n const res = await fetch(`${authUrl}/api/auth/token`, {\n method: 'POST',\n headers: {\n Cookie: `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}`,\n Origin: authUrl,\n },\n })\n if (!res.ok) return null\n const data = (await res.json()) as { token?: string | null }\n return data.token ?? null\n}\n","/**\n * deepspace logout\n *\n * Revokes the session on the auth worker, then removes the cached session\n * token and JWT from ~/.deepspace/. Test accounts (managed by `deepspace\n * test-accounts`) are not touched.\n */\n\nimport { defineCommand } from 'citty'\nimport { existsSync, readFileSync, rmSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\n\nimport { ENVS } from '../env'\nimport { SESSION_COOKIE } from '../session'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? ENVS.prod.auth\n\nconst DIR = join(homedir(), '.deepspace')\nconst SESSION_PATH = join(DIR, 'session')\nconst TOKEN_PATH = join(DIR, 'token')\n\nexport default defineCommand({\n meta: {\n name: 'logout',\n description: 'Sign out and remove cached credentials',\n },\n async run() {\n // Read the session token before deleting it so we can revoke server-side.\n const sessionToken = existsSync(SESSION_PATH)\n ? readFileSync(SESSION_PATH, 'utf-8').trim()\n : null\n\n if (sessionToken) {\n try {\n await fetch(`${AUTH_URL}/api/auth/sign-out`, {\n method: 'POST',\n headers: {\n Cookie: `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}`,\n Origin: AUTH_URL,\n },\n })\n } catch {\n // Network failure — still wipe local credentials so the user can\n // re-authenticate. Server-side session will expire on its own.\n }\n }\n\n let removed = 0\n for (const path of [SESSION_PATH, TOKEN_PATH]) {\n if (existsSync(path)) {\n rmSync(path)\n removed++\n }\n }\n\n if (removed === 0) {\n console.log('Already logged out.')\n return\n }\n console.log('Logged out.')\n },\n})\n","/**\n * deepspace dev [--prod] [--port N]\n *\n * Starts local development:\n * 1. Ensures you're logged in\n * 2. Writes .dev.vars pointing to dev or prod workers\n * 3. Starts vite dev (Cloudflare Vite plugin runs the worker in-process)\n *\n * deepspace dev # uses dev workers, port 5173 (strict)\n * deepspace dev --prod # uses production workers\n * deepspace dev --port 5180 # bind to a different port (multi-app dev)\n *\n * Port is `--port` > $DEEPSPACE_PORT > 5173. We always pass --strictPort to\n * vite so a busy port fails loudly instead of silently jumping to 5174 (which\n * would diverge from anything Playwright/test config is expecting).\n */\n\nimport { defineCommand } from 'citty'\nimport { existsSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { spawn } from 'node:child_process'\nimport { ensureToken } from '../auth'\nimport { writeDevVars } from '../env'\n\nconst DEFAULT_PORT = 5173\n\nexport default defineCommand({\n meta: {\n name: 'dev',\n description: 'Start local development server',\n },\n args: {\n dir: {\n type: 'positional',\n description: 'App directory (default: current directory)',\n required: false,\n },\n prod: {\n type: 'boolean',\n description: 'Use production workers (real auth, real API calls)',\n default: false,\n },\n port: {\n type: 'string',\n description: `Port to bind (default ${DEFAULT_PORT}, or $DEEPSPACE_PORT)`,\n required: false,\n },\n },\n async run({ args }) {\n const appDir = resolve(args.dir ?? '.')\n const env = args.prod ? 'prod' : 'dev'\n const port = resolvePort(args.port)\n\n if (!existsSync(join(appDir, 'wrangler.toml'))) {\n console.error('No wrangler.toml found. Are you in a DeepSpace app directory?')\n process.exit(1)\n }\n\n let token: string\n try {\n token = await ensureToken()\n } catch (err: any) {\n console.error(err.message)\n process.exit(1)\n }\n\n let payload: { sub: string; name?: string; email?: string }\n try {\n payload = JSON.parse(atob(token.split('.')[1]))\n } catch {\n console.error('Malformed session token. Run `npx deepspace login`.')\n process.exit(1)\n }\n console.log(`Logged in as ${payload.name ?? payload.email}`)\n console.log(`Environment: ${env}`)\n console.log(`Port: ${port}`)\n\n await writeDevVars(appDir, env, payload.sub, token)\n console.log('Starting dev server...\\n')\n\n const vite = spawn(\n 'npx',\n ['vite', '--port', String(port), '--strictPort', '--host'],\n {\n cwd: appDir,\n stdio: 'inherit',\n shell: process.platform === 'win32',\n env: { ...process.env, DEEPSPACE_PORT: String(port) },\n },\n )\n process.on('SIGINT', () => vite.kill())\n process.on('SIGTERM', () => vite.kill())\n vite.on('close', (code) => process.exit(code ?? 0))\n },\n})\n\nfunction resolvePort(arg?: string): number {\n const raw = arg ?? process.env.DEEPSPACE_PORT\n if (!raw) return DEFAULT_PORT\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 1 || n > 65535) {\n console.error(`Invalid port: ${raw}. Must be an integer between 1 and 65535.`)\n process.exit(1)\n }\n return n\n}\n","/**\n * CLI auth utilities — shared across all commands.\n *\n * Reads the session token from ~/.deepspace/session and ensures\n * a fresh JWT is available at ~/.deepspace/token.\n */\n\nimport { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\n\nimport { ENVS } from './env'\nimport { exchangeSession } from './session'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? ENVS.prod.auth\n\nconst DIR = join(homedir(), '.deepspace')\nexport const SESSION_PATH = join(DIR, 'session')\nconst TOKEN_PATH = join(DIR, 'token')\n\n/**\n * Ensure a valid JWT exists. Refreshes from the session token if expired.\n * Returns the JWT string or throws if not logged in / session expired.\n */\nexport async function ensureToken(): Promise<string> {\n if (!existsSync(SESSION_PATH)) {\n throw new Error('Not logged in. Run `deepspace login` first.')\n }\n\n const sessionToken = readFileSync(SESSION_PATH, 'utf-8').trim()\n\n // Try existing token first — if it's still valid, skip the refresh\n if (existsSync(TOKEN_PATH)) {\n const existing = readFileSync(TOKEN_PATH, 'utf-8').trim()\n if (isTokenValid(existing)) {\n return existing\n }\n }\n\n // Refresh from session\n const token = await exchangeSession(AUTH_URL, sessionToken)\n if (!token) {\n throw new Error('Session expired. Run `deepspace login` to re-authenticate.')\n }\n\n mkdirSync(DIR, { recursive: true })\n writeFileSync(TOKEN_PATH, token, { mode: 0o600 })\n\n return token\n}\n\n/** Check if a JWT has at least 30 seconds of validity remaining. */\nfunction isTokenValid(jwt: string): boolean {\n try {\n const payload = JSON.parse(atob(jwt.split('.')[1]))\n return payload.exp * 1000 > Date.now() + 30_000\n } catch {\n return false\n }\n}\n","/**\n * deepspace kill [--port N] [--all]\n *\n * Stops a local dev server bound to the given port, plus the workerd\n * child processes that wrangler/Vite would normally clean up but\n * sometimes leak when the parent dies ungracefully (Ctrl-C in a\n * detached terminal, IDE close, sandbox deny on signal, etc).\n *\n * deepspace kill # kill listener on 5173 + its workerd children\n * deepspace kill --port 5180 # kill listener on a different port\n * deepspace kill --all # also sweep ALL stray workerd/wrangler procs on the machine\n *\n * Cross-platform: uses lsof/pgrep on macOS and Linux, and PowerShell\n * (Get-NetTCPConnection / Get-CimInstance) on Windows. PowerShell ships\n * with every supported Windows version since 7; no extra install required.\n *\n * Always sends SIGTERM first, waits briefly, then SIGKILL anything\n * still alive — same shape as `vite`'s own shutdown handler so we\n * don't trample DO state mid-write. (On Windows, SIGTERM is best-effort:\n * Win32 has no real signals, so node maps both to TerminateProcess. We\n * still issue them in the same order for consistent log output.)\n */\n\nimport { defineCommand } from 'citty'\nimport { spawnSync } from 'node:child_process'\nimport { setTimeout as wait } from 'node:timers/promises'\n\nconst DEFAULT_PORT = 5173\nconst SIGTERM_GRACE_MS = 1500\nconst IS_WIN = process.platform === 'win32'\n\nexport default defineCommand({\n meta: {\n name: 'kill',\n description: 'Kill the local dev server and any orphaned workerd processes',\n },\n args: {\n port: {\n type: 'string',\n description: `Port the dev server is bound to (default ${DEFAULT_PORT}, or $DEEPSPACE_PORT)`,\n required: false,\n },\n all: {\n type: 'boolean',\n description: 'Also kill stray workerd/wrangler processes across all ports',\n default: false,\n },\n },\n async run({ args }) {\n const port = resolvePort(args.port)\n const targets = new Set<number>()\n\n // 1. Anything LISTENing on the dev port (vite + the workerd child it\n // publishes through, occasionally a stray inspector).\n for (const pid of listenerPids(port)) targets.add(pid)\n\n // 2. Children of those listeners — wrangler/vite tend to spawn workerd\n // as a sibling, but in some shells it ends up as a child instead.\n for (const pid of [...targets]) {\n for (const child of childPids(pid)) targets.add(child)\n }\n\n // 3. With --all, sweep workerd / wrangler / vite anywhere on the box.\n // Useful when port 5173 is \"free\" but a leftover workerd from a\n // previous run is still holding D1 / DO state in .wrangler/.\n if (args.all) {\n for (const pid of processPidsByName(['workerd', 'wrangler', 'vite'])) {\n targets.add(pid)\n }\n }\n\n if (targets.size === 0) {\n console.log(\n args.all\n ? `Nothing listening on :${port} and no stray workerd/wrangler/vite processes found.`\n : `Nothing listening on :${port}. (Pass --all to sweep stray workerd/wrangler.)`,\n )\n return\n }\n\n // SIGTERM pass.\n for (const pid of targets) {\n if (sendSignal(pid, 'SIGTERM')) {\n console.log(`SIGTERM → pid ${pid}`)\n }\n }\n await wait(SIGTERM_GRACE_MS)\n\n const stillAlive: number[] = []\n for (const pid of targets) {\n if (isAlive(pid)) stillAlive.push(pid)\n }\n\n // SIGKILL holdouts.\n for (const pid of stillAlive) {\n if (sendSignal(pid, 'SIGKILL')) {\n console.log(`SIGKILL → pid ${pid} (did not exit on SIGTERM)`)\n }\n }\n\n // Re-verify the port is free.\n await wait(200)\n const remaining = listenerPids(port)\n if (remaining.length > 0) {\n console.error(\n `Port ${port} is still held by pid(s) ${remaining.join(', ')} — try \\`deepspace kill --port ${port}\\` again, or kill manually.`,\n )\n process.exit(1)\n }\n\n console.log(`Port ${port} is free.`)\n },\n})\n\nfunction resolvePort(arg?: string): number {\n const raw = arg ?? process.env.DEEPSPACE_PORT\n if (!raw) return DEFAULT_PORT\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 1 || n > 65535) {\n console.error(`Invalid port: ${raw}. Must be an integer between 1 and 65535.`)\n process.exit(1)\n }\n return n\n}\n\n// ── Platform-specific helpers ─────────────────────────────────────────────\n\nfunction listenerPids(port: number): number[] {\n if (IS_WIN) {\n // Get-NetTCPConnection is the modern replacement for netstat -ano.\n // -ErrorAction SilentlyContinue swallows \"No matching connection\" so\n // the command exits 0 with empty stdout instead of a noisy red error.\n return runPowershell(\n `Get-NetTCPConnection -LocalPort ${port} -State Listen -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess`,\n )\n }\n // -t prints PIDs only, one per line; -nP avoids DNS / service lookups.\n return run(['lsof', '-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-t'])\n}\n\nfunction childPids(parentPid: number): number[] {\n if (IS_WIN) {\n return runPowershell(\n `Get-CimInstance Win32_Process -Filter \"ParentProcessId=${parentPid}\" | Select-Object -ExpandProperty ProcessId`,\n )\n }\n return run(['pgrep', '-P', String(parentPid)])\n}\n\nfunction processPidsByName(names: string[]): number[] {\n const all = new Set<number>()\n if (IS_WIN) {\n // Match against process Name (e.g. \"workerd\") AND CommandLine (catches\n // npx-launched scripts like \"vite\" that show up as node.exe with vite\n // in the args).\n const orClauses = names\n .map((n) => `($_.Name -like '*${n}*') -or ($_.CommandLine -like '*${n}*')`)\n .join(' -or ')\n const script = `Get-CimInstance Win32_Process | Where-Object { ${orClauses} } | Select-Object -ExpandProperty ProcessId`\n for (const pid of runPowershell(script)) {\n if (pid !== process.pid) all.add(pid)\n }\n return [...all]\n }\n for (const name of names) {\n for (const pid of run(['pgrep', '-f', name])) {\n if (pid !== process.pid) all.add(pid)\n }\n }\n return [...all]\n}\n\n// ── Process primitives ────────────────────────────────────────────────────\n\n/** Run a command and return whitespace-separated PIDs (empty array on failure). */\nfunction run(cmd: string[]): number[] {\n try {\n const r = spawnSync(cmd[0], cmd.slice(1), { encoding: 'utf-8' })\n if (r.status !== 0) return []\n return parsePidLines(r.stdout)\n } catch {\n return []\n }\n}\n\n/**\n * Run a PowerShell snippet. Prefers `pwsh` (PowerShell 7+) when available\n * and falls back to `powershell.exe` (Windows PowerShell 5.1, ships with\n * every Windows version we care about).\n */\nfunction runPowershell(script: string): number[] {\n const exe = pwshOrPowershell()\n try {\n const r = spawnSync(\n exe,\n ['-NoProfile', '-NonInteractive', '-Command', script],\n { encoding: 'utf-8' },\n )\n if (r.status !== 0) return []\n return parsePidLines(r.stdout)\n } catch {\n return []\n }\n}\n\nfunction pwshOrPowershell(): string {\n // `pwsh` is the modern cross-platform binary; `powershell.exe` is the\n // legacy Windows-only one. Try modern first, fall back if missing.\n const probe = spawnSync('pwsh', ['-NoProfile', '-Command', '$PSVersionTable.PSVersion.Major'], {\n encoding: 'utf-8',\n })\n if (probe.status === 0) return 'pwsh'\n return 'powershell.exe'\n}\n\nfunction parsePidLines(stdout: string): number[] {\n return stdout\n .split(/\\s+/)\n .map((s) => Number.parseInt(s, 10))\n .filter((n) => Number.isFinite(n) && n > 0)\n}\n\nfunction sendSignal(pid: number, signal: NodeJS.Signals): boolean {\n try {\n process.kill(pid, signal)\n return true\n } catch {\n return false\n }\n}\n\nfunction isAlive(pid: number): boolean {\n try {\n // signal 0 = \"do nothing, just check\"\n process.kill(pid, 0)\n return true\n } catch {\n return false\n }\n}\n","/**\n * deepspace test [suite] [--port N]\n *\n * Runs tests for a DeepSpace app. Always uses dev workers.\n *\n * deepspace test # smoke + api (quick check)\n * deepspace test smoke # smoke tests only\n * deepspace test api # API tests only\n * deepspace test e2e # all Playwright tests\n * deepspace test unit # vitest unit tests\n * deepspace test all # everything\n * deepspace test <file> # run specific test file\n *\n * Port is `--port` > $DEEPSPACE_PORT > 5173. The chosen port is exported as\n * DEEPSPACE_PORT to the Playwright child so the config + webServer both bind\n * to the same address. Pass a different port per app to run multiple apps\n * (and test suites) in parallel.\n */\n\nimport { defineCommand } from 'citty'\nimport { existsSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { execSync, spawnSync } from 'node:child_process'\nimport { ensureToken } from '../auth'\nimport { writeDevVars } from '../env'\n\nconst DEFAULT_PORT = 5173\n\nexport default defineCommand({\n meta: {\n name: 'test',\n description: 'Run tests for your DeepSpace app',\n },\n args: {\n suite: {\n type: 'positional',\n description: 'Test suite: smoke, api, e2e, unit, all (default: smoke+api)',\n required: false,\n },\n port: {\n type: 'string',\n description: `Port for vite/webServer (default ${DEFAULT_PORT}, or $DEEPSPACE_PORT)`,\n required: false,\n },\n },\n async run({ args }) {\n const appDir = resolve('.')\n const suite = args.suite ?? 'default'\n const port = resolvePort(args.port)\n\n if (!existsSync(join(appDir, 'wrangler.toml'))) {\n console.error('No wrangler.toml found. Are you in a DeepSpace app directory?')\n process.exit(1)\n }\n\n // Always write .dev.vars pointing to dev workers. A logged-in user is\n // required so writeDevVars can mint APP_OWNER_JWT via the auth-worker.\n let token: string\n let ownerId: string\n try {\n token = await ensureToken()\n const payload = JSON.parse(atob(token.split('.')[1]))\n ownerId = payload.sub\n } catch (err) {\n console.error('`deepspace test` requires you to be logged in. Run `deepspace login` first.')\n process.exit(1)\n }\n\n await writeDevVars(appDir, 'dev', ownerId, token)\n\n if (suite !== 'unit') {\n ensurePlaywright(appDir)\n }\n\n let exitCode = 0\n\n switch (suite) {\n case 'smoke':\n exitCode = runPlaywright(appDir, ['tests/smoke.spec.ts'], port)\n break\n case 'api':\n exitCode = runPlaywright(appDir, ['tests/api.spec.ts'], port)\n break\n case 'e2e':\n exitCode = runPlaywright(appDir, [], port)\n break\n case 'unit':\n exitCode = runVitest(appDir)\n break\n case 'all':\n exitCode = runVitest(appDir)\n if (exitCode === 0) exitCode = runPlaywright(appDir, [], port)\n break\n case 'default':\n exitCode = runPlaywright(appDir, ['tests/smoke.spec.ts', 'tests/api.spec.ts'], port)\n break\n default:\n if (suite.endsWith('.spec.ts')) {\n exitCode = runPlaywright(appDir, [suite], port)\n } else {\n console.error(`Unknown test suite: ${suite}`)\n console.error('Available: smoke, api, e2e, unit, all')\n process.exit(1)\n }\n }\n\n process.exit(exitCode)\n },\n})\n\nfunction runPlaywright(appDir: string, testFiles: string[], port: number): number {\n const result = spawnSync('npx', [\n 'playwright', 'test',\n '--config', 'tests/playwright.config.ts',\n ...testFiles,\n ], {\n cwd: appDir,\n stdio: 'inherit',\n shell: process.platform === 'win32',\n env: { ...process.env, DEEPSPACE_PORT: String(port) },\n })\n return result.status ?? 1\n}\n\nfunction runVitest(appDir: string): number {\n const result = spawnSync('npx', ['vitest', 'run', '--passWithNoTests'], {\n cwd: appDir, stdio: 'inherit', shell: process.platform === 'win32',\n })\n return result.status ?? 1\n}\n\nfunction ensurePlaywright(appDir: string) {\n try {\n execSync('npx playwright --version', { cwd: appDir, stdio: 'pipe' })\n } catch {\n console.log('Installing Playwright...')\n execSync('npm install -D @playwright/test', { cwd: appDir, stdio: 'pipe' })\n }\n // `playwright install` is idempotent — fast no-op if chromium already exists,\n // ~30s download on first run. The previous --dry-run check exited 0 even when\n // browsers were missing, so we'd silently skip install and tests would crash.\n // On Linux, --with-deps installs system libs (requires root); on macOS/Win it's\n // a no-op flag, but apt-get inside `--with-deps` errors out without sudo, so\n // only pass it when running as root on Linux.\n const isLinux = process.platform === 'linux'\n const isRoot = isLinux && typeof process.getuid === 'function' && process.getuid() === 0\n const args = isRoot ? ['install', '--with-deps', 'chromium'] : ['install', 'chromium']\n const result = spawnSync('npx', ['playwright', ...args], { cwd: appDir, stdio: 'inherit' })\n if (result.status !== 0) {\n console.error('\\nPlaywright install failed. On Linux, system libs may be missing — try:')\n console.error(' sudo npx playwright install --with-deps chromium')\n process.exit(1)\n }\n}\n\nfunction resolvePort(arg?: string): number {\n const raw = arg ?? process.env.DEEPSPACE_PORT\n if (!raw) return DEFAULT_PORT\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 1 || n > 65535) {\n console.error(`Invalid port: ${raw}. Must be an integer between 1 and 65535.`)\n process.exit(1)\n }\n return n\n}\n","/**\n * deepspace test-accounts\n *\n * Manage test accounts for local development and CI.\n * Test accounts use @deepspace.test emails and are clearly\n * demarcated in the database. Max 10 per developer.\n *\n * Credentials are saved to ~/.deepspace/test-accounts.json (0600)\n * so they persist across projects and sessions.\n *\n * deepspace test-accounts create --email bot@deepspace.test --password Pass123!\n * deepspace test-accounts list\n * deepspace test-accounts delete --email bot@deepspace.test\n * deepspace test-accounts delete --id <id>\n * deepspace test-accounts clear # delete all (with confirm)\n * deepspace test-accounts clear --label e2e # delete only label=e2e\n * deepspace test-accounts clear --yes # skip confirm (CI)\n */\n\nimport { defineCommand } from 'citty'\nimport * as p from '@clack/prompts'\nimport { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\nimport { ensureToken, SESSION_PATH } from '../auth'\nimport { ENVS } from '../env'\n\nconst SESSION_COOKIE = '__Secure-better-auth.session_token'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? ENVS.prod.auth\nconst DIR = join(homedir(), '.deepspace')\nconst ACCOUNTS_PATH = join(DIR, 'test-accounts.json')\n\n// ── Local credential store ─────────────────────────────────────────\n\ninterface StoredAccount {\n id: string\n email: string\n password: string\n userId: string\n name?: string\n label?: string | null\n createdAt: number\n}\n\nfunction loadAccounts(): StoredAccount[] {\n if (!existsSync(ACCOUNTS_PATH)) return []\n try {\n return JSON.parse(readFileSync(ACCOUNTS_PATH, 'utf-8'))\n } catch {\n return []\n }\n}\n\nfunction saveAccounts(accounts: StoredAccount[]) {\n mkdirSync(DIR, { recursive: true })\n writeFileSync(ACCOUNTS_PATH, JSON.stringify(accounts, null, 2), { mode: 0o600 })\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nfunction sessionCookie(): string {\n const token = readFileSync(SESSION_PATH, 'utf-8').trim()\n return `${SESSION_COOKIE}=${encodeURIComponent(token)}`\n}\n\ninterface RemoteAccount {\n id: string\n email: string\n userId: string\n label: string | null\n createdAt: number\n}\n\nasync function fetchRemoteAccounts(): Promise<RemoteAccount[]> {\n const res = await fetch(`${AUTH_URL}/api/auth/test-accounts`, {\n headers: { Cookie: sessionCookie(), Origin: AUTH_URL },\n })\n const data = (await res.json().catch(() => ({}))) as {\n accounts?: RemoteAccount[]\n error?: string\n }\n if (!res.ok || !data.accounts) {\n throw new Error(data.error ?? 'Failed to list test accounts')\n }\n return data.accounts\n}\n\nasync function deleteRemote(id: string): Promise<void> {\n const res = await fetch(`${AUTH_URL}/api/auth/test-accounts/${id}`, {\n method: 'DELETE',\n headers: { Cookie: sessionCookie(), Origin: AUTH_URL },\n })\n if (!res.ok) {\n const data = (await res.json().catch(() => ({}))) as { error?: string }\n throw new Error(data.error ?? `DELETE returned ${res.status}`)\n }\n}\n\n// ── Subcommands ────────────────────────────────────────────────────\n\nconst create = defineCommand({\n meta: {\n name: 'create',\n description: 'Create a test account',\n },\n args: {\n email: {\n type: 'string',\n description: 'Email (must end with @deepspace.test)',\n required: true,\n },\n password: {\n type: 'string',\n description: 'Password (min 8 characters)',\n required: true,\n },\n name: {\n type: 'string',\n description: 'Display name',\n required: false,\n },\n label: {\n type: 'string',\n description: 'Label for this test account',\n required: false,\n },\n },\n async run({ args }) {\n await ensureToken()\n\n const res = await fetch(`${AUTH_URL}/api/auth/test-accounts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Cookie: sessionCookie(),\n Origin: AUTH_URL,\n },\n body: JSON.stringify({\n email: args.email,\n password: args.password,\n name: args.name,\n label: args.label,\n }),\n })\n\n const data = (await res.json().catch(() => ({}))) as {\n id?: string\n email?: string\n userId?: string\n label?: string | null\n createdAt?: number\n error?: string\n }\n\n if (!res.ok || !data.id) {\n console.error(`Failed: ${data.error ?? 'Unknown error'}`)\n process.exit(1)\n }\n\n const account = data as { id: string; email: string; userId: string; label: string | null; createdAt: number }\n\n // Save credentials locally\n const accounts = loadAccounts()\n accounts.push({\n id: account.id,\n email: args.email,\n password: args.password,\n userId: account.userId,\n name: args.name,\n label: account.label,\n createdAt: account.createdAt,\n })\n saveAccounts(accounts)\n\n console.log(`Created test account:`)\n console.log(` ID: ${account.id}`)\n console.log(` Email: ${account.email}`)\n console.log(` Password: ${args.password}`)\n console.log(` UserID: ${account.userId}`)\n if (account.label) console.log(` Label: ${account.label}`)\n console.log(`\\nSaved to ${ACCOUNTS_PATH}`)\n },\n})\n\nconst list = defineCommand({\n meta: {\n name: 'list',\n description: 'List your test accounts',\n },\n async run() {\n await ensureToken()\n\n let remote: RemoteAccount[]\n try {\n remote = await fetchRemoteAccounts()\n } catch (err) {\n console.error(`Failed: ${(err as Error).message}`)\n process.exit(1)\n }\n\n if (remote.length === 0) {\n console.log('No test accounts. Create one with: deepspace test-accounts create --email <email> --password <password>')\n return\n }\n\n // Merge with local credentials (passwords are only stored locally)\n const local = loadAccounts()\n const localByEmail = new Map(local.map((a) => [a.email, a]))\n\n console.log(`Test accounts (${remote.length}/10):\\n`)\n for (const a of remote) {\n const stored = localByEmail.get(a.email)\n const date = new Date(a.createdAt).toLocaleDateString()\n console.log(` ${a.email}${a.label ? ` (${a.label})` : ''}`)\n console.log(` ID: ${a.id} UserID: ${a.userId} Created: ${date}`)\n if (stored?.password) {\n console.log(` Password: ${stored.password}`)\n } else {\n console.log(` Password: (not saved locally)`)\n }\n }\n },\n})\n\nconst del = defineCommand({\n meta: {\n name: 'delete',\n description: 'Delete a test account by --email or --id',\n },\n args: {\n email: {\n type: 'string',\n description: 'Email of the test account to delete',\n required: false,\n },\n id: {\n type: 'string',\n description: 'ID of the test account to delete',\n required: false,\n },\n },\n async run({ args }) {\n if (!args.email && !args.id) {\n console.error('Provide --email <email> or --id <id>.')\n process.exit(1)\n }\n if (args.email && args.id) {\n console.error('Provide either --email or --id, not both.')\n process.exit(1)\n }\n\n await ensureToken()\n\n let targetId = args.id as string | undefined\n let targetEmail = args.email as string | undefined\n\n if (targetEmail && !targetId) {\n let remote: RemoteAccount[]\n try {\n remote = await fetchRemoteAccounts()\n } catch (err) {\n console.error(`Failed: ${(err as Error).message}`)\n process.exit(1)\n }\n const match = remote.find((a) => a.email === targetEmail)\n if (!match) {\n console.error(`No test account with email ${targetEmail}.`)\n process.exit(1)\n }\n targetId = match.id\n }\n\n try {\n await deleteRemote(targetId!)\n } catch (err) {\n console.error(`Failed: ${(err as Error).message}`)\n process.exit(1)\n }\n\n // Remove from local store\n const accounts = loadAccounts().filter(\n (a) => a.id !== targetId && (!targetEmail || a.email !== targetEmail),\n )\n saveAccounts(accounts)\n\n console.log(`Test account deleted${targetEmail ? `: ${targetEmail}` : `: ${targetId}`}`)\n },\n})\n\nconst clear = defineCommand({\n meta: {\n name: 'clear',\n description: 'Delete all your test accounts (or those matching --label)',\n },\n args: {\n label: {\n type: 'string',\n description: 'Only delete accounts with this label (e.g. e2e, slack-clone)',\n required: false,\n },\n yes: {\n type: 'boolean',\n description: 'Skip confirmation prompt (for CI scripts)',\n default: false,\n },\n },\n async run({ args }) {\n await ensureToken()\n\n let remote: RemoteAccount[]\n try {\n remote = await fetchRemoteAccounts()\n } catch (err) {\n console.error(`Failed: ${(err as Error).message}`)\n process.exit(1)\n }\n\n const targets = args.label\n ? remote.filter((a) => a.label === args.label)\n : remote\n\n if (targets.length === 0) {\n const suffix = args.label ? ` with label '${args.label}'` : ''\n console.log(`No test accounts${suffix} to delete.`)\n return\n }\n\n if (!args.yes) {\n const subject = args.label\n ? `${targets.length} test account(s) labeled '${args.label}'`\n : `all ${targets.length} test account(s)`\n const confirmed = await p.confirm({\n message: `Delete ${subject}? This is not reversible.`,\n initialValue: false,\n })\n if (p.isCancel(confirmed) || !confirmed) {\n console.log('Cancelled.')\n return\n }\n }\n\n let ok = 0\n const failures: Array<{ email: string; error: string }> = []\n for (const a of targets) {\n try {\n await deleteRemote(a.id)\n ok++\n } catch (err) {\n failures.push({ email: a.email, error: (err as Error).message })\n }\n }\n\n // Sync local store with what's actually deleted.\n const deletedIds = new Set(\n targets.filter((t) => !failures.find((f) => f.email === t.email)).map((t) => t.id),\n )\n saveAccounts(loadAccounts().filter((a) => !deletedIds.has(a.id)))\n\n console.log(`Deleted ${ok}/${targets.length} test account(s).`)\n if (failures.length > 0) {\n console.error(`\\nFailed:`)\n for (const f of failures) console.error(` ${f.email}: ${f.error}`)\n process.exit(1)\n }\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'test-accounts',\n description: 'Manage test accounts for development',\n },\n subCommands: {\n create,\n list,\n delete: del,\n clear,\n },\n})\n","/**\n * deepspace deploy\n *\n * Builds the app with Vite (Cloudflare plugin bundles both client + worker),\n * then uploads to the deploy worker which handles Cloudflare WfP deployment.\n *\n * Uses the same build pipeline as dev for full fidelity. Reads the output\n * wrangler.json (via .wrangler/deploy/config.json) to find the built assets\n * and worker bundle — the same contract that `wrangler deploy` uses.\n */\n\nimport { defineCommand } from 'citty'\nimport { execSync } from 'node:child_process'\nimport { readFileSync, readdirSync, existsSync } from 'node:fs'\nimport { parse as parseToml } from 'smol-toml'\nimport { join, resolve, dirname } from 'node:path'\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\nimport { ENVS, extractCustomDevVars, parseDevVars } from '../env'\nimport {\n bindingManifestFromOutputConfig,\n validateBindingManifest,\n RESERVED_BINDING_NAMES,\n} from '../../server/rooms/binding-manifest'\nimport { resolveAppName } from '../../server/rooms/app-name'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? ENVS.prod.deploy\n\nexport default defineCommand({\n meta: {\n name: 'deploy',\n description: 'Build and deploy your DeepSpace app',\n },\n args: {\n dir: {\n type: 'positional',\n description: 'App directory (default: current directory)',\n required: false,\n },\n },\n async run({ args }) {\n const appDir = resolve(args.dir ?? '.')\n p.intro('Deploying DeepSpace app')\n\n // ── Read app name from wrangler.toml ──────────────────────\n const wranglerPath = join(appDir, 'wrangler.toml')\n if (!existsSync(wranglerPath)) {\n p.cancel('No wrangler.toml found. Are you in a DeepSpace app directory?')\n process.exit(1)\n }\n\n const wranglerConfig = parseToml(readFileSync(wranglerPath, 'utf-8')) as { name?: string }\n const nameRes = resolveAppName(wranglerConfig.name)\n if (!nameRes.ok) {\n p.cancel(`wrangler.toml: ${nameRes.reason}`)\n process.exit(1)\n }\n if (nameRes.warning) p.log.warn(nameRes.warning)\n const appName = nameRes.name\n p.log.info(`App: ${appName}`)\n\n // ── Ensure valid JWT ───────────────────────────────────────\n let token: string\n try {\n token = await ensureToken()\n } catch (err: any) {\n p.cancel(err.message)\n process.exit(1)\n }\n\n // ── Build with Vite (Cloudflare plugin bundles client + worker) ──\n const s = p.spinner()\n s.start('Building...')\n try {\n execSync('npx vite build', { cwd: appDir, stdio: 'pipe' })\n } catch (err: any) {\n s.stop('Build failed')\n console.error(err.stderr?.toString() ?? err.message)\n process.exit(1)\n }\n s.stop('Built')\n\n // ── Locate build output via .wrangler/deploy/config.json ──\n // This is the same contract that `wrangler deploy` uses after `vite build`.\n const deployConfigPath = join(appDir, '.wrangler', 'deploy', 'config.json')\n if (!existsSync(deployConfigPath)) {\n p.cancel('Build output config not found at .wrangler/deploy/config.json')\n process.exit(1)\n }\n\n const deployConfig = JSON.parse(readFileSync(deployConfigPath, 'utf-8')) as { configPath: string }\n const outputWranglerPath = resolve(dirname(deployConfigPath), deployConfig.configPath)\n\n if (!existsSync(outputWranglerPath)) {\n p.cancel(`Output wrangler.json not found at ${outputWranglerPath}`)\n process.exit(1)\n }\n\n const outputConfig = JSON.parse(readFileSync(outputWranglerPath, 'utf-8')) as {\n main: string\n assets?: { directory: string }\n durable_objects?: { bindings: Array<{ name: string; class_name: string }> }\n migrations?: Array<{ new_sqlite_classes?: string[] }>\n }\n\n const workerDir = dirname(outputWranglerPath)\n const workerBundlePath = join(workerDir, outputConfig.main)\n const clientDir = outputConfig.assets?.directory\n ? resolve(workerDir, outputConfig.assets.directory)\n : null\n\n if (!existsSync(workerBundlePath)) {\n p.cancel(`Worker bundle not found at ${workerBundlePath}`)\n process.exit(1)\n }\n if (!clientDir || !existsSync(clientDir)) {\n p.cancel(`Client assets not found at ${clientDir}`)\n process.exit(1)\n }\n\n // ── Collect assets ────────────────────────────────────────\n s.start('Collecting assets...')\n const assets = collectAssets(clientDir)\n s.stop(`Collected ${assets.length} assets`)\n\n const workerJs = readFileSync(workerBundlePath, 'utf-8')\n\n // ── Extract DO manifest from build output config ───────────\n const doBindings = outputConfig.durable_objects?.bindings as Array<{ name: string; class_name: string }> | undefined\n const sqliteClasses = new Set(\n (outputConfig.migrations as Array<{ new_sqlite_classes?: string[] }> | undefined)\n ?.flatMap(m => m.new_sqlite_classes ?? []) ?? []\n )\n const doManifest = doBindings?.map(b => ({\n binding: b.name,\n className: b.class_name,\n sqlite: sqliteClasses.has(b.class_name),\n }))\n if (doManifest?.length) {\n p.log.info(`DO manifest: ${doManifest.length} binding(s)`)\n }\n\n // ── Extract custom (non-DO) bindings: Vectorize, AI, R2, KV, D1, etc.\n const customBindings = bindingManifestFromOutputConfig(outputConfig)\n const validation = validateBindingManifest(customBindings)\n if (!validation.valid) {\n p.cancel(\n `Invalid binding(s) in wrangler.toml:\\n` +\n validation.errors.map((e) => ` • ${e.reason}`).join('\\n'),\n )\n process.exit(1)\n }\n if (customBindings.length) {\n p.log.info(\n `Custom bindings: ${customBindings.map((b) => `${b.name} (${b.type})`).join(', ')}`,\n )\n }\n\n // ── Extract user-managed secrets from .dev.vars ───────────\n // The user-managed section of .dev.vars (everything below the SDK divider)\n // is the same set of values the dev server uses. Shipping them to prod as\n // secret_text bindings means a route that works against `deepspace dev`\n // also works after deploy without a separate `wrangler secret put` step.\n const devVarsPath = join(appDir, '.dev.vars')\n let userSecrets: Record<string, string> = {}\n if (existsSync(devVarsPath)) {\n const customSection = extractCustomDevVars(readFileSync(devVarsPath, 'utf-8'))\n if (customSection) {\n try {\n userSecrets = parseDevVars(customSection)\n } catch (err: any) {\n p.cancel(`.dev.vars: ${err.message}`)\n process.exit(1)\n }\n }\n }\n const userSecretNames = Object.keys(userSecrets)\n\n // Pre-flight: fail with a clear, file-pointing error rather than letting\n // the deploy-worker reject mid-deploy. Reserved names are platform-owned\n // (ASSETS, USAGE_EVENTS, …) and clashes with declared bindings would\n // otherwise produce duplicate-name metadata that CF rejects opaquely.\n const declaredBindingNames = new Set([\n ...customBindings.map((b) => b.name),\n ...(doManifest ?? []).map((d) => d.binding),\n ])\n for (const name of userSecretNames) {\n if (RESERVED_BINDING_NAMES.has(name)) {\n p.cancel(\n `.dev.vars: \"${name}\" is a reserved binding name and cannot be used as an app secret.`,\n )\n process.exit(1)\n }\n if (declaredBindingNames.has(name)) {\n p.cancel(\n `.dev.vars: \"${name}\" collides with a binding declared in wrangler.toml — rename one or the other.`,\n )\n process.exit(1)\n }\n }\n if (userSecretNames.length) {\n p.log.info(`App secrets (from .dev.vars): ${userSecretNames.join(', ')}`)\n }\n\n // ── Upload to deploy worker ───────────────────────────────\n s.start(`Deploying to ${appName}.app.space...`)\n\n const form = new FormData()\n form.append('worker', new Blob([workerJs], { type: 'application/javascript' }), 'worker.js')\n form.append('assets', JSON.stringify(assets))\n if (doManifest) {\n form.append('doManifest', JSON.stringify(doManifest))\n }\n if (customBindings.length) {\n form.append('bindingManifest', JSON.stringify(customBindings))\n }\n if (userSecretNames.length) {\n form.append('userSecrets', JSON.stringify(userSecrets))\n }\n\n const res = await fetch(`${DEPLOY_URL}/api/deploy/${appName}`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n body: form,\n })\n\n const body = (await res.json().catch(() => ({}))) as {\n success?: boolean\n url?: string\n error?: string\n }\n\n if (!res.ok || !body.success) {\n s.stop('Deploy failed')\n p.cancel(body.error ?? `Deployment error (${res.status})`)\n process.exit(1)\n }\n\n // ── Wait for assets propagation ───────────────────────────\n // Cloudflare's deploy API returns \"success\" once the script + bindings are\n // accepted, but the assets binding can still be indexing for ~10–60s.\n // During that window any request hits CF's transitional \"Assets have not\n // yet deployed\" page (HTML), even on `/api/*` routes that should run the\n // worker first. Block here until we see the worker actually serving so\n // CI / smoke checks that fire immediately don't hit the flake.\n if (body.url) {\n s.message('Waiting for edge propagation...')\n const ok = await waitForAssetsReady(body.url, 90_000)\n if (!ok) {\n s.stop('Deployed (edge propagation still in progress after 90s)')\n p.log.warn('First requests may briefly hit the assets transitional page; retry in a minute.')\n p.log.success(`Live at: ${body.url}`)\n p.outro('Done')\n return\n }\n }\n\n s.stop('Deployed!')\n p.log.success(`Live at: ${body.url}`)\n p.outro('Done')\n },\n})\n\n/**\n * Poll the deployed URL until it stops returning Cloudflare's\n * \"Assets have not yet deployed\" transitional page. Returns true when the\n * worker is actually serving, false on timeout.\n */\nasync function waitForAssetsReady(url: string, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs\n let attempt = 0\n while (Date.now() < deadline) {\n attempt++\n try {\n const res = await fetch(url, { redirect: 'manual' })\n const body = await res.text()\n // The transitional page is HTML with the literal phrase below. Any\n // other body — worker JSON, the app's index.html, even a 404 from the\n // worker's catch-all — means the deploy is live.\n if (!body.includes('Assets have not yet deployed')) {\n return true\n }\n } catch {\n // network blip — try again\n }\n // Exponential backoff capped at 8s: 1s → 2s → 4s → 8s → 8s …\n const wait = Math.min(8_000, 1_000 * 2 ** (attempt - 1))\n await new Promise((r) => setTimeout(r, wait))\n }\n return false\n}\n\nfunction collectAssets(dir: string): Array<{ path: string; contentBase64: string }> {\n const assets: Array<{ path: string; contentBase64: string }> = []\n function walk(d: string, prefix: string) {\n for (const entry of readdirSync(d, { withFileTypes: true })) {\n if (entry.name === '.assetsignore') continue\n const full = join(d, entry.name)\n const rel = prefix ? `${prefix}/${entry.name}` : entry.name\n if (entry.isDirectory()) {\n walk(full, rel)\n } else {\n assets.push({\n path: '/' + rel,\n contentBase64: readFileSync(full).toString('base64'),\n })\n }\n }\n }\n walk(dir, '')\n return assets\n}\n","/**\n * Binding Manifest — non-DO bindings declared by an app's wrangler.toml that\n * the deploy-worker should pass through to Cloudflare's WfP upload API.\n *\n * Apps don't export a `__BINDING_MANIFEST__`; the CLI extracts these from the\n * normalized vite/wrangler output config at deploy time. This file just owns\n * the types + validation so both sides (CLI client and deploy-worker server)\n * agree on the shape.\n */\n/// <reference types=\"@cloudflare/workers-types\" />\n\n/**\n * A single non-DO binding the app declares. Mirrors CF's WfP binding API.\n *\n * Provisionable resources (d1, kv_namespace, vectorize, r2_bucket, queue) accept\n * the literal string `\"auto\"` in their ID field to request platform-side\n * provisioning at deploy time. When `\"auto\"` is used, the deploy-worker creates\n * the resource on the platform CF account, persists the resulting CF ID in the\n * app registry, and substitutes the real ID before forwarding to WfP. The\n * sentinel sticks around in this type because:\n * 1. `wrangler` parsing requires a non-empty string in the id field\n * 2. The CLI passes the unresolved manifest through to the deploy-worker\n * 3. The deploy-worker is the only side with CF API credentials\n *\n * Companion fields (`database_name`, `title`, `dimensions`, `metric`) are only\n * used when `\"auto\"` is set — they tell the provisioner how to create the\n * resource. After provisioning these fields are still present on the wire but\n * ignored by WfP.\n */\nexport type CustomBinding =\n | {\n type: 'vectorize'\n name: string\n /** Either a pre-existing index name or the literal `\"auto\"`. */\n index_name: string\n /** Required when `index_name === \"auto\"`. */\n dimensions?: number\n /** Required when `index_name === \"auto\"`. */\n metric?: 'cosine' | 'euclidean' | 'dot-product'\n }\n | { type: 'ai'; name: string }\n | {\n type: 'r2_bucket'\n name: string\n /** Either a pre-existing bucket name or the literal `\"auto\"`. */\n bucket_name: string\n }\n | {\n type: 'kv_namespace'\n name: string\n /** Either a pre-existing KV namespace ID or the literal `\"auto\"`. */\n namespace_id: string\n /** Required when `namespace_id === \"auto\"`. Human-readable namespace title. */\n title?: string\n }\n | {\n type: 'd1'\n name: string\n /** Either a pre-existing D1 database UUID or the literal `\"auto\"`. */\n id: string\n /** Required when `id === \"auto\"`. Human-readable database name. */\n database_name?: string\n }\n | {\n type: 'queue'\n name: string\n /** Either a pre-existing queue name or the literal `\"auto\"`. */\n queue_name: string\n }\n | { type: 'browser_rendering'; name: string }\n | { type: 'analytics_engine'; name: string; dataset?: string }\n | { type: 'hyperdrive'; name: string; id: string }\n\nexport type CustomBindingManifest = CustomBinding[]\n\n/** Sentinel string in an ID field that requests platform-side provisioning. */\nexport const AUTO_PROVISION_SENTINEL = 'auto'\n\n/** Binding types whose ID field accepts the `\"auto\"` sentinel for provisioning. */\nexport const AUTO_PROVISIONABLE_TYPES = new Set([\n 'd1',\n 'kv_namespace',\n 'vectorize',\n 'r2_bucket',\n 'queue',\n])\n\n/** Vectorize metric values accepted by CF when creating an index. */\nconst VECTORIZE_METRICS = new Set(['cosine', 'euclidean', 'dot-product'])\n\n/**\n * True if a binding has the `\"auto\"` sentinel in its primary ID field. Used by\n * the deploy-worker to decide which entries need provisioning and by the\n * validator to enforce companion-field requirements.\n */\nexport function isAutoProvision(b: CustomBinding): boolean {\n switch (b.type) {\n case 'd1':\n return b.id === AUTO_PROVISION_SENTINEL\n case 'kv_namespace':\n return b.namespace_id === AUTO_PROVISION_SENTINEL\n case 'vectorize':\n return b.index_name === AUTO_PROVISION_SENTINEL\n case 'r2_bucket':\n return b.bucket_name === AUTO_PROVISION_SENTINEL\n case 'queue':\n return b.queue_name === AUTO_PROVISION_SENTINEL\n default:\n return false\n }\n}\n\n/** Binding `type` values an app is allowed to declare. */\nexport const ALLOWED_BINDING_TYPES = new Set([\n 'vectorize',\n 'ai',\n 'r2_bucket',\n 'kv_namespace',\n 'd1',\n 'queue',\n 'browser_rendering',\n 'analytics_engine',\n 'hyperdrive',\n])\n\n/**\n * Binding NAMES the SDK reserves on every app — apps may not redeclare them.\n *\n * Includes:\n * - Static-asset + service bindings the platform sets up automatically.\n * - SDK-managed env (auth, identity, owner JWT, HMAC secret).\n * - The auto-attached cost-tracking AE dataset (`USAGE_EVENTS`).\n *\n * DO binding names (RECORD_ROOMS, YJS_ROOMS, etc.) are NOT in this set\n * because they live in a separate manifest (`__DO_MANIFEST__`).\n */\nexport const RESERVED_BINDING_NAMES = new Set([\n 'ASSETS',\n 'PLATFORM_WORKER',\n 'API_WORKER',\n 'APP_NAME',\n 'OWNER_USER_ID',\n 'AUTH_JWT_PUBLIC_KEY',\n 'AUTH_JWT_ISSUER',\n 'AUTH_WORKER_URL',\n 'APP_IDENTITY_TOKEN',\n 'APP_OWNER_JWT',\n 'INTERNAL_STORAGE_HMAC_SECRET',\n 'USAGE_EVENTS',\n])\n\n/**\n * Per-binding validation error. `binding` is undefined for top-level\n * shape failures (e.g. manifest is not an array).\n */\nexport interface ValidationError {\n binding?: CustomBinding\n reason: string\n}\n\n/**\n * Validate a binding manifest. Returns errors; an empty array means valid.\n *\n * Used both client-side (CLI) for friendly fail-fast and server-side\n * (deploy-worker) as a security boundary — apps can't sneak in reserved\n * binding names by editing the wire format.\n */\nexport function validateBindingManifest(\n manifest: unknown,\n): { valid: true; bindings: CustomBindingManifest } | { valid: false; errors: ValidationError[] } {\n if (!Array.isArray(manifest)) {\n return { valid: false, errors: [{ reason: 'Manifest must be an array' }] }\n }\n const errors: ValidationError[] = []\n const seenNames = new Set<string>()\n for (const entry of manifest) {\n if (!entry || typeof entry !== 'object') {\n errors.push({ reason: `Entry must be an object (got ${entry === null ? 'null' : typeof entry})` })\n continue\n }\n const e = entry as Record<string, unknown>\n const type = e.type\n const name = e.name\n if (typeof type !== 'string' || !ALLOWED_BINDING_TYPES.has(type)) {\n errors.push({\n reason: `Disallowed binding type: ${typeof type === 'string' ? type : `(${typeof type})`}. Allowed: ${[...ALLOWED_BINDING_TYPES].sort().join(', ')}`,\n })\n continue\n }\n if (typeof name !== 'string' || !name) {\n errors.push({ reason: `Binding of type \"${type}\" missing 'name' (string)` })\n continue\n }\n if (RESERVED_BINDING_NAMES.has(name)) {\n errors.push({ reason: `Binding name \"${name}\" is reserved by the SDK` })\n continue\n }\n if (seenNames.has(name)) {\n errors.push({ reason: `Duplicate binding name \"${name}\"` })\n continue\n }\n seenNames.add(name)\n // Now safely typed: type is in ALLOWED_BINDING_TYPES + name is a string.\n const binding = entry as CustomBinding\n const fieldErr = requiredFieldError(binding)\n if (fieldErr) errors.push({ binding, reason: fieldErr })\n }\n if (errors.length) return { valid: false, errors }\n return { valid: true, bindings: manifest as CustomBindingManifest }\n}\n\nfunction requiredFieldError(b: CustomBinding): string | null {\n switch (b.type) {\n case 'vectorize': {\n if (!b.index_name) return `vectorize binding \"${b.name}\" missing index_name (or \"auto\")`\n if (b.index_name === AUTO_PROVISION_SENTINEL) {\n // Auto-provisioning needs the index shape upfront — CF requires both\n // dimensions and metric at index-create time.\n if (typeof b.dimensions !== 'number' || b.dimensions <= 0) {\n return `vectorize binding \"${b.name}\" with index_name=\"auto\" requires \"dimensions\" (positive number)`\n }\n if (!b.metric || !VECTORIZE_METRICS.has(b.metric)) {\n return `vectorize binding \"${b.name}\" with index_name=\"auto\" requires \"metric\" (one of: ${[...VECTORIZE_METRICS].join(', ')})`\n }\n }\n return null\n }\n case 'r2_bucket':\n return b.bucket_name ? null : `r2_bucket binding \"${b.name}\" missing bucket_name (or \"auto\")`\n case 'kv_namespace': {\n if (!b.namespace_id) return `kv_namespace binding \"${b.name}\" missing namespace_id (or \"auto\")`\n if (b.namespace_id === AUTO_PROVISION_SENTINEL && !b.title) {\n return `kv_namespace binding \"${b.name}\" with namespace_id=\"auto\" requires \"title\"`\n }\n return null\n }\n case 'd1': {\n if (!b.id) return `d1 binding \"${b.name}\" missing id (or \"auto\")`\n if (b.id === AUTO_PROVISION_SENTINEL && !b.database_name) {\n return `d1 binding \"${b.name}\" with id=\"auto\" requires \"database_name\"`\n }\n return null\n }\n case 'queue':\n return b.queue_name ? null : `queue binding \"${b.name}\" missing queue_name (or \"auto\")`\n case 'hyperdrive':\n // Hyperdrive auto-provisioning is out of scope for v1 (needs upstream\n // connection-string management). Only pre-existing IDs accepted.\n if (!b.id) return `hyperdrive binding \"${b.name}\" missing id`\n if (b.id === AUTO_PROVISION_SENTINEL) {\n return `hyperdrive binding \"${b.name}\": auto-provisioning not yet supported (provide a real id)`\n }\n return null\n case 'ai':\n case 'browser_rendering':\n case 'analytics_engine':\n return null // no required fields beyond `name`\n default: {\n // Exhaustiveness guard — adding a new variant without a case fails here.\n const _exhaustive: never = b\n void _exhaustive\n return null\n }\n }\n}\n\n/**\n * Convert vite/wrangler's normalized config (from `.wrangler/deploy/config.json`)\n * into a CustomBindingManifest.\n *\n * Vite normalizes wrangler.toml into object/array structures with shapes like\n * `{ ai: { binding: 'AI' } }`, `{ vectorize: [{ binding, index_name }] }`,\n * etc. We extract each known shape with explicit field plucks (no broad\n * `as` casts) and return a flat array.\n */\nexport function bindingManifestFromOutputConfig(\n outputConfig: Record<string, unknown>,\n): CustomBindingManifest {\n const out: CustomBindingManifest = []\n\n // ai: single object\n const aiBinding = pluckString(outputConfig.ai, 'binding')\n if (aiBinding) out.push({ type: 'ai', name: aiBinding })\n\n // vectorize: array of { binding, index_name, dimensions?, metric? }\n // `dimensions` and `metric` are only required when index_name === \"auto\"\n // (auto-provisioning); the validator enforces that, so we just pluck both\n // here and let it decide.\n for (const v of asObjectArray(outputConfig.vectorize)) {\n const name = pluckString(v, 'binding')\n const index_name = pluckString(v, 'index_name')\n if (!name || !index_name) continue\n const dimensions = pluckNumber(v, 'dimensions')\n const metric = pluckString(v, 'metric')\n out.push({\n type: 'vectorize',\n name,\n index_name,\n ...(dimensions != null && { dimensions }),\n ...(metric && (metric === 'cosine' || metric === 'euclidean' || metric === 'dot-product') && { metric }),\n })\n }\n\n // r2_buckets: array of { binding, bucket_name }\n for (const r of asObjectArray(outputConfig.r2_buckets)) {\n const name = pluckString(r, 'binding')\n const bucket_name = pluckString(r, 'bucket_name')\n if (name && bucket_name) out.push({ type: 'r2_bucket', name, bucket_name })\n }\n\n // kv_namespaces: array of { binding, id, title? }\n // `title` is only required when id === \"auto\"; pluck both here and let\n // the validator enforce the dependency.\n for (const k of asObjectArray(outputConfig.kv_namespaces)) {\n const name = pluckString(k, 'binding')\n const namespace_id = pluckString(k, 'id')\n if (!name || !namespace_id) continue\n const title = pluckString(k, 'title')\n out.push({\n type: 'kv_namespace',\n name,\n namespace_id,\n ...(title && { title }),\n })\n }\n\n // d1_databases: array of { binding, database_id, database_name? }\n // `database_name` is only required when database_id === \"auto\"; pluck both\n // and let the validator enforce.\n for (const d of asObjectArray(outputConfig.d1_databases)) {\n const name = pluckString(d, 'binding')\n const id = pluckString(d, 'database_id')\n if (!name || !id) continue\n const database_name = pluckString(d, 'database_name')\n out.push({\n type: 'd1',\n name,\n id,\n ...(database_name && { database_name }),\n })\n }\n\n // queues.producers: array of { binding, queue }\n const queues = isObject(outputConfig.queues) ? outputConfig.queues : null\n for (const q of asObjectArray(queues?.producers)) {\n const name = pluckString(q, 'binding')\n const queue_name = pluckString(q, 'queue')\n if (name && queue_name) out.push({ type: 'queue', name, queue_name })\n }\n\n // browser: { binding } (Cloudflare names this `browser` not `browser_rendering`)\n const browserBinding = pluckString(outputConfig.browser, 'binding')\n if (browserBinding) out.push({ type: 'browser_rendering', name: browserBinding })\n\n // analytics_engine_datasets: array of { binding, dataset? }\n for (const a of asObjectArray(outputConfig.analytics_engine_datasets)) {\n const name = pluckString(a, 'binding')\n const dataset = pluckString(a, 'dataset')\n if (name) out.push({ type: 'analytics_engine', name, dataset: dataset ?? undefined })\n }\n\n // hyperdrive: array of { binding, id }\n for (const h of asObjectArray(outputConfig.hyperdrive)) {\n const name = pluckString(h, 'binding')\n const id = pluckString(h, 'id')\n if (name && id) out.push({ type: 'hyperdrive', name, id })\n }\n\n return out\n}\n\n// ---- internal helpers (no broad `as` casts) ----\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === 'object' && !Array.isArray(v)\n}\n\nfunction pluckString(v: unknown, key: string): string | null {\n if (!isObject(v)) return null\n const val = v[key]\n return typeof val === 'string' && val.length > 0 ? val : null\n}\n\nfunction pluckNumber(v: unknown, key: string): number | null {\n if (!isObject(v)) return null\n const val = v[key]\n return typeof val === 'number' && Number.isFinite(val) ? val : null\n}\n\nfunction asObjectArray(v: unknown): Record<string, unknown>[] {\n if (!Array.isArray(v)) return []\n return v.filter(isObject)\n}\n","/**\n * App-name validation + sanitization helpers.\n *\n * Strategy: validate strictly so we have a precise definition of \"valid\",\n * but DON'T reject non-conforming names — sanitize them, warn the user, and\n * proceed. Hard rejection would break apps whose `wrangler.toml name` was\n * something like `My_App` (previously deployed as `my-app` via silent\n * server-side sanitization). The new behavior preserves \"still deploys,\"\n * but the CLI now surfaces a warning so the user can fix the name when\n * convenient instead of being silently surprised by their hostname.\n *\n * Rules track Cloudflare's WfP script-name constraints (RFC 1035 host label,\n * no consecutive dashes) plus our 2-char minimum so subdomains read sensibly.\n */\n\nexport const APP_NAME_RULES = {\n /** ^[a-z0-9](-?[a-z0-9])+$ — RFC 1035 host label, no consecutive dashes. */\n pattern: /^[a-z0-9](?:-?[a-z0-9])+$/,\n minLength: 2,\n maxLength: 63,\n} as const\n\nexport type AppNameValidation =\n | { valid: true; name: string }\n | { valid: false; reason: string }\n\n/**\n * Strict validation: returns valid only if the name already conforms.\n * Useful as a precondition test or for CI lints.\n */\nexport function validateAppName(raw: unknown): AppNameValidation {\n if (typeof raw !== 'string') {\n return { valid: false, reason: 'App name must be a string' }\n }\n const name = raw.trim()\n if (!name) {\n return { valid: false, reason: 'App name is required' }\n }\n if (name.length < APP_NAME_RULES.minLength) {\n return { valid: false, reason: `App name \"${name}\" is too short (min ${APP_NAME_RULES.minLength} chars)` }\n }\n if (name.length > APP_NAME_RULES.maxLength) {\n return { valid: false, reason: `App name \"${name}\" is too long (max ${APP_NAME_RULES.maxLength} chars)` }\n }\n if (!APP_NAME_RULES.pattern.test(name)) {\n return {\n valid: false,\n reason:\n `App name \"${name}\" is invalid. Use lowercase letters, digits, and single hyphens only ` +\n `(must start + end with alphanumeric). Examples: my-app, search-v2, unison-search.`,\n }\n }\n return { valid: true, name }\n}\n\nexport type AppNameResolution =\n | { ok: true; name: string; warning?: string }\n | { ok: false; reason: string }\n\n/**\n * Resolve an app name for deploy: prefer the input as-is if valid, otherwise\n * sanitize and warn. Hard-fail only if even sanitization can't produce a\n * valid name (empty, all-non-alphanumeric, too short, too long).\n *\n * The intent is \"what previously worked still works, with a friendly warning\n * about non-conforming names.\"\n */\nexport function resolveAppName(raw: unknown): AppNameResolution {\n const strict = validateAppName(raw)\n if (strict.valid) return { ok: true, name: strict.name }\n\n if (typeof raw !== 'string') return { ok: false, reason: strict.reason }\n const trimmed = raw.trim()\n if (!trimmed) return { ok: false, reason: 'App name is required' }\n\n const sanitized = sanitizeAppName(trimmed)\n const sanitizedStrict = validateAppName(sanitized)\n if (!sanitizedStrict.valid) {\n return {\n ok: false,\n reason: `App name \"${trimmed}\" can't be sanitized into a valid name (${sanitizedStrict.reason}). Pick something matching: lowercase letters, digits, single hyphens, ${APP_NAME_RULES.minLength}-${APP_NAME_RULES.maxLength} chars.`,\n }\n }\n return {\n ok: true,\n name: sanitized,\n warning:\n `App name \"${trimmed}\" doesn't conform to deploy rules — using \"${sanitized}\" instead. ` +\n `Update wrangler.toml's \\`name\\` to silence this warning.`,\n }\n}\n\n/**\n * Lossy normalization that mirrors what the deploy-worker historically did\n * server-side. Keep only [a-z0-9-], collapse consecutive dashes, trim leading\n * and trailing dashes.\n */\nfunction sanitizeAppName(raw: string): string {\n return raw\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/-{2,}/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n","/**\n * deepspace undeploy\n *\n * Removes a deployed app from *.app.space via the deploy worker.\n */\n\nimport { defineCommand } from 'citty'\nimport { readFileSync, existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\n\nimport { ENVS } from '../env'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? ENVS.prod.deploy\n\nexport default defineCommand({\n meta: {\n name: 'undeploy',\n description: 'Remove a deployed DeepSpace app',\n },\n args: {\n name: {\n type: 'positional',\n description: 'App name to undeploy (reads from wrangler.toml if omitted)',\n required: false,\n },\n },\n async run({ args }) {\n let appName = args.name\n\n // If no name given, try to read from wrangler.toml in cwd\n if (!appName) {\n const wranglerPath = join(process.cwd(), 'wrangler.toml')\n if (existsSync(wranglerPath)) {\n const config = parseToml(readFileSync(wranglerPath, 'utf-8')) as { name?: string }\n if (config.name) appName = config.name\n }\n }\n\n if (!appName) {\n p.cancel('Provide an app name or run from a DeepSpace app directory.')\n process.exit(1)\n }\n\n let token: string\n try {\n token = await ensureToken()\n } catch (err: any) {\n p.cancel(err.message)\n process.exit(1)\n }\n\n p.intro(`Undeploying ${appName}`)\n const s = p.spinner()\n s.start('Removing...')\n\n const res = await fetch(`${DEPLOY_URL}/api/deploy/${appName}`, {\n method: 'DELETE',\n headers: { Authorization: `Bearer ${token}` },\n })\n\n const body = (await res.json().catch(() => ({}))) as { success?: boolean; error?: string }\n\n if (!res.ok || !body.success) {\n s.stop('Failed')\n p.cancel(body.error ?? `Undeploy error (${res.status})`)\n process.exit(1)\n }\n\n s.stop('Removed')\n p.outro(`${appName}.app.space has been taken down`)\n },\n})\n","/**\n * deepspace whoami\n *\n * Shows the currently logged-in user. Auto-refreshes the JWT if expired.\n *\n * Prints all the identity fields a developer cares about (email, name,\n * userId, issuer) so you don't have to peek into ~/.deepspace/token.\n * Also flags whether the session is for a test account (`@deepspace.test`\n * email), since that's a meaningful distinction for who can do what — see\n * docs/auth/dev-vs-test-accounts.md.\n *\n * `--json` emits a parseable single-line JSON object for scripts.\n */\n\nimport { defineCommand } from 'citty'\nimport { ensureToken } from '../auth'\n\ninterface JwtPayload {\n sub?: string\n name?: string\n email?: string\n image?: string | null\n iss?: string\n iat?: number\n exp?: number\n}\n\nexport default defineCommand({\n meta: {\n name: 'whoami',\n description: 'Show the currently logged-in user',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Emit a single-line JSON object instead of human output',\n default: false,\n },\n },\n async run({ args }) {\n let jwt: string\n try {\n jwt = await ensureToken()\n } catch (err: any) {\n console.error(err.message ?? 'Not signed in. Run `deepspace login`.')\n process.exit(1)\n }\n\n let payload: JwtPayload\n try {\n payload = JSON.parse(atob(jwt.split('.')[1]))\n } catch {\n console.error('Malformed session token. Run `deepspace login` again.')\n process.exit(1)\n }\n\n const isTestAccount = !!payload.email?.endsWith('@deepspace.test')\n const accountType: 'developer' | 'test-account' | 'unknown' = isTestAccount\n ? 'test-account'\n : payload.email\n ? 'developer'\n : 'unknown'\n\n if (args.json) {\n console.log(JSON.stringify({\n name: payload.name ?? null,\n email: payload.email ?? null,\n userId: payload.sub ?? null,\n accountType,\n issuer: payload.iss ?? null,\n expiresAt: payload.exp ? new Date(payload.exp * 1000).toISOString() : null,\n }))\n return\n }\n\n console.log(`Name: ${payload.name ?? '(none)'}`)\n console.log(`Email: ${payload.email ?? '(none)'}`)\n console.log(`UserID: ${payload.sub ?? '(none)'}`)\n console.log(`Type: ${accountType}`)\n if (payload.iss) console.log(`Issuer: ${payload.iss}`)\n if (isTestAccount) {\n console.log('')\n console.log('Note: this is a test account, not a real OAuth developer.')\n console.log('See docs/auth/dev-vs-test-accounts.md.')\n }\n },\n})\n","/**\n * deepspace add <feature> [dir]\n *\n * Installs a DeepSpace feature into the current app.\n *\n * deepspace add --list # list available features\n * deepspace add messaging # install into current dir\n * deepspace add messaging ./my-app # install into specific dir\n * deepspace add --info messaging # show feature details\n */\n\nimport { defineCommand } from 'citty'\nimport { existsSync } from 'node:fs'\nimport { resolve, join } from 'node:path'\nimport { execSync } from 'node:child_process'\n\nfunction findScript(from: string): string | null {\n const candidate = join(from, '.deepspace', 'scripts', 'add-feature.cjs')\n if (existsSync(candidate)) return candidate\n return null\n}\n\nexport default defineCommand({\n meta: {\n name: 'add',\n description: 'Add a feature to your DeepSpace app',\n },\n args: {\n list: {\n type: 'boolean',\n alias: 'l',\n description: 'List available features',\n required: false,\n },\n info: {\n type: 'string',\n description: 'Show details about a feature',\n required: false,\n },\n feature: {\n type: 'positional',\n description: 'Feature to install',\n required: false,\n },\n dir: {\n type: 'positional',\n description: 'App directory (default: current directory)',\n required: false,\n },\n },\n run({ args }) {\n const appDir = resolve(args.dir ?? '.')\n const script = findScript(appDir)\n\n if (!script) {\n console.error('No .deepspace/scripts/add-feature.cjs found.')\n console.error('Are you in a DeepSpace app directory?')\n process.exit(1)\n }\n\n const passArgs: string[] = []\n\n if (args.list) {\n passArgs.push('--list')\n } else if (args.info) {\n passArgs.push('--info', args.info)\n } else if (args.feature) {\n passArgs.push(args.feature, appDir)\n } else {\n passArgs.push('--help')\n }\n\n execSync(`node ${JSON.stringify(script)} ${passArgs.map(a => JSON.stringify(a)).join(' ')}`, {\n stdio: 'inherit',\n cwd: appDir,\n })\n },\n})\n","/**\n * deepspace domain — purchase and manage custom domains for your apps.\n *\n * Designed to be both human-friendly and agent/script-friendly:\n * - All destructive commands accept `--yes` to skip prompts.\n * - All read commands accept `--json` for structured stdout.\n * - `--app` defaults to the cwd's wrangler.toml name (matches `deepspace deploy`).\n * - `domain buy` opens Stripe Checkout in a browser and polls until live;\n * pass `--no-open` to print the URL only, `--no-wait` to skip polling.\n *\n * Subcommands:\n * search <query> — find available domains and prices\n * buy <domain> — buy a domain via Stripe Checkout (browser)\n * list — list domains you own\n * status <domain> — detail view for one domain\n * attach <domain> — re-point a domain at a different app\n * detach <domain> — stop routing the domain (keeps registration)\n * renew <domain> --auto X — toggle auto-renew on/off at the registrar\n */\n\nimport { defineCommand } from 'citty'\nimport { execSync } from 'node:child_process'\nimport { ensureToken } from '../auth'\nimport { ENVS } from '../env'\nimport { requireAppName, detectAppName } from '../lib/app-context'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? ENVS.prod.api\n\ninterface SearchResult {\n name: string\n registrable: boolean\n registrar?: 'cloudflare' | 'namesilo'\n pricing?: { currency: string; registrationCost: string; renewalCost: string }\n registrationCost?: number\n renewalCost?: number\n chargedCents?: number | null\n costCents?: number | null\n reason?: string\n premium?: boolean\n}\n\ninterface DomainPurchase {\n id: string\n domain: string\n appName: string\n status: string\n statusError?: string | null\n registeredAt?: string | null\n expiresAt?: string | null\n chargedCents: number\n autoRenew: boolean\n registrar: string\n}\n\nasync function api<T>(token: string, path: string, init?: RequestInit): Promise<T> {\n const res = await fetch(`${API_URL}${path}`, {\n ...init,\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n ...(init?.headers ?? {}),\n },\n })\n const text = await res.text()\n if (!res.ok) {\n let msg = text\n try {\n msg = (JSON.parse(text) as { error?: string }).error ?? text\n } catch {\n // not JSON\n }\n throw new Error(`API ${path} (${res.status}): ${msg}`)\n }\n return JSON.parse(text) as T\n}\n\nfunction fmtCents(cents: number | null | undefined): string {\n if (cents === null || cents === undefined) return '—'\n return `$${(cents / 100).toFixed(2)}`\n}\n\nfunction fmtDate(iso: string | null | undefined): string {\n if (!iso) return '—'\n return iso.slice(0, 10)\n}\n\n/**\n * Plain stdin Y/N prompt — no clack, agent can pipe `yes` or pass --yes.\n */\nasync function confirm(message: string): Promise<boolean> {\n if (!process.stdin.isTTY) {\n // Non-interactive (piped, agent) — refuse rather than hang\n throw new Error(`${message} — pass --yes to confirm non-interactively`)\n }\n process.stdout.write(`${message} [y/N] `)\n return new Promise((resolve) => {\n process.stdin.setEncoding('utf-8')\n process.stdin.once('data', (data) => {\n const answer = data.toString().trim().toLowerCase()\n resolve(answer === 'y' || answer === 'yes')\n })\n })\n}\n\n// ============================================================================\n// search\n// ============================================================================\n\nconst search = defineCommand({\n meta: { name: 'search', description: 'Search for available domains' },\n args: {\n query: { type: 'positional', description: 'Domain or keyword', required: true },\n limit: { type: 'string', description: 'Max results (default 10)', default: '10' },\n json: { type: 'boolean', description: 'Emit JSON instead of a table' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const limit = parseInt(args.limit ?? '10', 10) || 10\n const result = await api<{ domains: SearchResult[] }>(\n token,\n `/api/domains/search?q=${encodeURIComponent(args.query)}&limit=${limit}`,\n )\n if (args.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n if (result.domains.length === 0) {\n console.log('No matches.')\n return\n }\n for (const d of result.domains) {\n const tag = d.registrable ? '✓' : '✗'\n const price = d.registrable ? `${fmtCents(d.chargedCents)}/yr` : d.reason ?? '—'\n // Annotate slow-path TLDs so users have realistic expectations.\n const slowFlag = d.registrar && d.registrar !== 'cloudflare' ? ' (15-60 min provisioning)' : ''\n console.log(`${tag} ${d.name.padEnd(40)} ${price}${slowFlag}`)\n }\n },\n})\n\n// ============================================================================\n// buy\n// ============================================================================\n\nconst buy = defineCommand({\n meta: { name: 'buy', description: 'Buy a domain and attach it to an app' },\n args: {\n domain: { type: 'positional', description: 'Domain to buy', required: true },\n app: { type: 'string', description: 'App to attach (defaults to ./wrangler.toml)' },\n yes: { type: 'boolean', description: 'Skip the confirmation prompt', default: false },\n 'no-open': { type: 'boolean', description: 'Do not open browser; print Stripe URL', default: false },\n 'no-wait': { type: 'boolean', description: 'Exit after creating session; do not poll until active', default: false },\n json: { type: 'boolean', description: 'Emit JSON to stdout', default: false },\n },\n async run({ args }) {\n const token = await ensureToken()\n const appName = requireAppName(args.app)\n\n // Re-check pricing\n const priceCheck = await api<{ domains: SearchResult[] }>(token, '/api/domains/check', {\n method: 'POST',\n body: JSON.stringify({ domains: [args.domain] }),\n })\n const result = priceCheck.domains[0]\n if (!result || !result.registrable) {\n console.error(`Not available: ${result?.reason ?? 'unknown'}`)\n process.exit(1)\n }\n\n const price = fmtCents(result.chargedCents)\n // Provisioning time depends on registrar:\n // CF Registrar (.com/.dev/.app/.xyz/etc): ~60-90s — registry publishes\n // CF nameservers atomically with registration.\n // Porkbun fallback (.ai/.io/.me/.co/etc + ccTLDs): 15-60 min — depends\n // on the destination registry (Verisign/.me, NIC.AI, etc) batch-\n // publishing our NS records to public DNS. The platform side is\n // done in <30s; the wait is registry-side.\n const expectedTime =\n result.registrar === 'cloudflare'\n ? '~60-90 seconds'\n : '15-60 minutes (registry NS propagation)'\n\n if (!args.yes) {\n const ok = await confirm(\n `Buy ${args.domain} for ${price}/yr (auto-renews; non-refundable), attach to ${appName}? Provisioning takes ${expectedTime}.`,\n )\n if (!ok) {\n console.log('Cancelled.')\n return\n }\n }\n\n const checkout = await api<{ purchaseId: string; sessionId: string; url: string; chargedCents: number }>(\n token,\n '/api/domains/checkout',\n {\n method: 'POST',\n body: JSON.stringify({ domain: args.domain, appName }),\n },\n )\n\n if (args.json) {\n process.stdout.write(JSON.stringify({ ...checkout, expectedTime, registrar: result.registrar }, null, 2) + '\\n')\n } else {\n console.log(`Stripe Checkout: ${checkout.url}`)\n }\n\n if (!args['no-open'] && process.stdin.isTTY) {\n openBrowser(checkout.url)\n }\n\n if (args['no-wait']) return\n\n // Poll until active or failed.\n // Timeout depends on registrar — CF can take 5 min worst case, Porkbun\n // up to 60 min for slow registries. User can Ctrl-C and resume polling\n // later via `deepspace domain status <domain>` — provisioning runs\n // server-side regardless.\n const timeoutMs = result.registrar === 'cloudflare' ? 5 * 60 * 1000 : 60 * 60 * 1000\n if (!args.json) {\n console.log(`Waiting for payment & provisioning (up to ${expectedTime}). Press Ctrl-C anytime —`)\n console.log(`provisioning continues server-side; check later with \\`deepspace domain status ${args.domain}\\`.`)\n }\n const deadline = Date.now() + timeoutMs\n let lastStatus = ''\n while (Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 5000))\n try {\n const detail = await api<{ domain: DomainPurchase }>(\n token,\n `/api/domains/${checkout.purchaseId}`,\n )\n if (detail.domain.status !== lastStatus) {\n lastStatus = detail.domain.status\n if (!args.json) console.log(` → ${lastStatus}`)\n }\n if (detail.domain.status === 'active') {\n if (args.json) {\n process.stdout.write(JSON.stringify({ ...checkout, status: 'active', domain: args.domain }, null, 2) + '\\n')\n } else {\n console.log(`✓ ${args.domain} is live and pointing at ${appName}`)\n }\n return\n }\n if (detail.domain.status.startsWith('failed:')) {\n console.error(`Provisioning failed: ${detail.domain.statusError ?? detail.domain.status}`)\n process.exit(1)\n }\n } catch (err) {\n // Transient — keep polling\n if (!args.json) console.error(`(poll error: ${err instanceof Error ? err.message : String(err)})`)\n }\n }\n console.error(`Polling timed out. Provisioning may still be in progress; check with:`)\n console.error(` deepspace domain status ${args.domain}`)\n process.exit(1)\n },\n})\n\n// ============================================================================\n// list\n// ============================================================================\n\nconst list = defineCommand({\n meta: { name: 'list', description: 'List your domains' },\n args: {\n json: { type: 'boolean', description: 'Emit JSON' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const result = await api<{ domains: DomainPurchase[] }>(token, '/api/domains')\n if (args.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n if (result.domains.length === 0) {\n console.log('No domains. Try `deepspace domain search <name>`.')\n return\n }\n console.log(`DOMAIN APP STATUS EXPIRES AUTO-RENEW`)\n for (const d of result.domains) {\n console.log(\n `${d.domain.padEnd(35)} ${d.appName.padEnd(20)} ${d.status.padEnd(20)} ${fmtDate(d.expiresAt).padEnd(12)} ${d.autoRenew ? 'on' : 'off'}`,\n )\n }\n },\n})\n\n// ============================================================================\n// status\n// ============================================================================\n\nconst status = defineCommand({\n meta: { name: 'status', description: 'Show details for one domain' },\n args: {\n domain: { type: 'positional', description: 'Domain', required: true },\n json: { type: 'boolean' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const all = await api<{ domains: DomainPurchase[] }>(token, '/api/domains')\n const found = all.domains.find((d) => d.domain === args.domain)\n if (!found) {\n console.error(`No domain ${args.domain} in your account`)\n process.exit(1)\n }\n if (args.json) {\n process.stdout.write(JSON.stringify(found, null, 2) + '\\n')\n return\n }\n console.log(`Domain: ${found.domain}`)\n console.log(`Status: ${found.status}${found.statusError ? ` (${found.statusError})` : ''}`)\n console.log(`Attached app: ${found.appName}`)\n console.log(`Registrar: ${found.registrar}`)\n console.log(`Registered: ${fmtDate(found.registeredAt)}`)\n console.log(`Expires: ${fmtDate(found.expiresAt)}`)\n console.log(`Auto-renew: ${found.autoRenew ? 'on' : 'off'}`)\n console.log(`Charged: ${fmtCents(found.chargedCents)}/yr`)\n },\n})\n\n// ============================================================================\n// attach\n// ============================================================================\n\nconst attach = defineCommand({\n meta: { name: 'attach', description: 'Re-point a domain at a different app' },\n args: {\n domain: { type: 'positional', description: 'Domain to re-point', required: true },\n app: { type: 'string', description: 'Target app (defaults to ./wrangler.toml)' },\n json: { type: 'boolean' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const targetApp = requireAppName(args.app)\n const all = await api<{ domains: DomainPurchase[] }>(token, '/api/domains')\n const found = all.domains.find((d) => d.domain === args.domain)\n if (!found) {\n console.error(`No domain ${args.domain} in your account`)\n process.exit(1)\n }\n const result = await api<{ success: boolean; appName: string }>(\n token,\n `/api/domains/${found.id}/reattach`,\n {\n method: 'POST',\n body: JSON.stringify({ appName: targetApp }),\n },\n )\n if (args.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n console.log(`✓ ${args.domain} now points at ${targetApp}`)\n },\n})\n\n// ============================================================================\n// detach\n// ============================================================================\n\nconst detach = defineCommand({\n meta: {\n name: 'detach',\n description: 'Stop routing the domain (keeps the registration; auto-renew unchanged)',\n },\n args: {\n domain: { type: 'positional', description: 'Domain to detach', required: true },\n yes: { type: 'boolean', description: 'Skip the confirmation prompt' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const all = await api<{ domains: DomainPurchase[] }>(token, '/api/domains')\n const found = all.domains.find((d) => d.domain === args.domain)\n if (!found) {\n console.error(`No domain ${args.domain} in your account`)\n process.exit(1)\n }\n if (!args.yes) {\n const ok = await confirm(\n `Detach ${args.domain}? Routing will stop; the domain stays registered (auto-renew is unchanged).`,\n )\n if (!ok) {\n console.log('Cancelled.')\n return\n }\n }\n await api(token, `/api/domains/${found.id}`, { method: 'DELETE' })\n console.log(`✓ ${args.domain} detached. Use \\`deepspace domain attach\\` to re-route, or \\`renew --auto off\\` to stop auto-renewal.`)\n },\n})\n\n// ============================================================================\n// renew\n// ============================================================================\n\nconst renew = defineCommand({\n meta: { name: 'renew', description: 'Toggle auto-renewal at the registrar' },\n args: {\n domain: { type: 'positional', description: 'Domain', required: true },\n auto: { type: 'string', description: '\"on\" or \"off\"', required: true },\n },\n async run({ args }) {\n if (args.auto !== 'on' && args.auto !== 'off') {\n console.error('--auto must be \"on\" or \"off\"')\n process.exit(1)\n }\n const token = await ensureToken()\n const all = await api<{ domains: DomainPurchase[] }>(token, '/api/domains')\n const found = all.domains.find((d) => d.domain === args.domain)\n if (!found) {\n console.error(`No domain ${args.domain} in your account`)\n process.exit(1)\n }\n const enabled = args.auto === 'on'\n await api(token, `/api/domains/${found.id}/auto-renew`, {\n method: 'POST',\n body: JSON.stringify({ autoRenew: enabled }),\n })\n console.log(`✓ ${args.domain} auto-renew ${enabled ? 'enabled' : 'disabled'}`)\n },\n})\n\n// ============================================================================\n// open in browser — best-effort\n// ============================================================================\n\nfunction openBrowser(url: string): void {\n try {\n if (process.platform === 'darwin') execSync(`open ${JSON.stringify(url)}`)\n else if (process.platform === 'win32') execSync(`start \"\" ${JSON.stringify(url)}`)\n else execSync(`xdg-open ${JSON.stringify(url)} 2>/dev/null || true`)\n } catch {\n // Best-effort — user can open the URL manually\n }\n}\n\n// ============================================================================\n// Top-level\n// ============================================================================\n\n// Note: no `run()` on the parent — citty otherwise calls it after every\n// subcommand finishes, which prints spurious help text.\n//\n// `detectAppName` is imported for type-checking the `--app` defaulting in\n// each subcommand; not used here directly.\nvoid detectAppName\n\nexport default defineCommand({\n meta: { name: 'domain', description: 'Buy and manage custom domains' },\n subCommands: { search, buy, list, status, attach, detach, renew },\n})\n","/**\n * Shared helper: read the current project's app name from `./wrangler.toml`.\n *\n * Used by commands that operate on \"the current app\" — `deploy`, `domain buy`,\n * `domain attach`, etc. Lets agents and scripts run from inside a project\n * directory without redundantly passing `--app <name>`.\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\n\n/**\n * Read the app name from `wrangler.toml` in the given directory (default cwd).\n * Returns null if no wrangler.toml exists or the file lacks a `name` field.\n */\nexport function detectAppName(cwd: string = process.cwd()): string | null {\n const wranglerPath = join(resolve(cwd), 'wrangler.toml')\n if (!existsSync(wranglerPath)) return null\n try {\n const cfg = parseToml(readFileSync(wranglerPath, 'utf-8')) as { name?: string }\n return typeof cfg.name === 'string' && cfg.name.length > 0 ? cfg.name : null\n } catch {\n return null\n }\n}\n\n/**\n * Resolve the app name from explicit arg or wrangler.toml.\n * Throws with a clear message if neither is available.\n */\nexport function requireAppName(explicit: string | undefined, cwd?: string): string {\n if (explicit) return explicit\n const detected = detectAppName(cwd)\n if (detected) return detected\n throw new Error(\n 'No app specified. Pass --app <name>, or run from an app directory with a wrangler.toml.',\n )\n}\n","/**\n * deepspace integrations <subcommand>\n *\n * Namespace for working with platform integrations from the command line.\n *\n * deepspace integrations # prints help\n * deepspace integrations list # list all\n * deepspace integrations info openai/chat-completion # schema + example\n * deepspace integrations invoke openai/chat-completion --body '{...}'\n *\n * `deepspace invoke ...` is a top-level alias for `integrations invoke ...`.\n * `deepspace invoke --list` is a shortcut for `integrations list`.\n *\n * All calls are made as the currently logged-in user (`deepspace whoami`).\n * That user is billed.\n *\n * No `run()` is defined on the parent — that matches the convention used\n * by `test-accounts` and prevents citty from firing both the parent and\n * a matched subcommand. Bare `deepspace integrations` (no subcommand)\n * prints citty's auto-generated help.\n */\n\nimport { defineCommand } from 'citty'\nimport { runInvoke, runInfo, runList } from './_invoke-impl'\n\nconst list = defineCommand({\n meta: {\n name: 'list',\n description: 'List all available integrations',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Print raw JSON (machine-readable)',\n default: false,\n },\n },\n async run({ args }) {\n try {\n await runList({ json: args.json })\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err))\n process.exit(1)\n }\n },\n})\n\nconst info = defineCommand({\n meta: {\n name: 'info',\n description: 'Print schema + example body for an integration endpoint',\n },\n args: {\n target: {\n type: 'positional',\n description: \"<integration>/<endpoint> (e.g. 'openai/chat-completion')\",\n required: true,\n },\n json: {\n type: 'boolean',\n description: 'Print raw JSON (machine-readable)',\n default: false,\n },\n },\n async run({ args }) {\n try {\n await runInfo({ target: args.target as string, json: args.json })\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err))\n process.exit(1)\n }\n },\n})\n\nconst invoke = defineCommand({\n meta: {\n name: 'invoke',\n description: 'Invoke a platform integration as the logged-in user',\n },\n args: {\n target: {\n type: 'positional',\n description: \"<integration>/<endpoint> (e.g. 'openai/chat-completion')\",\n required: true,\n },\n body: {\n type: 'string',\n alias: 'd',\n description: 'Inline JSON body',\n required: false,\n },\n 'body-file': {\n type: 'string',\n alias: 'f',\n description: 'Read JSON body from file (use - for stdin)',\n required: false,\n },\n json: {\n type: 'boolean',\n description: 'Print only the response JSON (machine-readable)',\n default: false,\n },\n timeout: {\n type: 'string',\n description: 'Request timeout in milliseconds (default: 120000)',\n required: false,\n },\n },\n async run({ args }) {\n try {\n const timeout = args.timeout != null ? Number(args.timeout) : undefined\n if (timeout != null && (!Number.isFinite(timeout) || timeout <= 0)) {\n throw new Error(`Invalid --timeout '${args.timeout}'. Must be a positive number of milliseconds.`)\n }\n await runInvoke({\n target: args.target as string,\n body: args.body,\n bodyFile: args['body-file'],\n json: args.json,\n timeout,\n })\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err))\n process.exit(1)\n }\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'integrations',\n description: 'List, inspect, and invoke platform integrations',\n },\n subCommands: {\n list,\n info,\n invoke,\n },\n})\n","/**\n * Shared implementation for `deepspace invoke` and `deepspace integrations *`.\n *\n * The CLI invokes platform integrations as the currently logged-in user\n * (the same identity shown by `deepspace whoami`). That user is billed.\n *\n * This module is the single source of truth for:\n * - listing the integration catalog\n * - showing per-endpoint info (schema + example body)\n * - making the actual POST call\n *\n * Both `commands/invoke.ts` (top-level alias) and `commands/integrations.ts`\n * (namespaced subcommands) delegate here so the behavior never drifts.\n *\n * Why `flushAndExit` is used (only on the --json paths):\n * After every subcommand runs, citty resumes the root command's run(),\n * which prints \"deepspace CLI — run `npx deepspace --help` for usage\" to\n * stdout. That trailing line corrupts --json output for any downstream\n * consumer that JSON.parses stdout (jq, file redirects, agent scripts,\n * the e2e tests). We can't suppress the root run() without modifying\n * cli.ts (out of scope), so on the --json paths we exit the process\n * before citty resumes — but we must wait for stdout to drain first,\n * because piped writes are async via libuv and large JSON outputs (the\n * full catalog is ~78KB) exceed the pipe buffer. See flushAndExit().\n *\n * Human-mode paths don't need this: the trailing line is just one more\n * line of prose, harmless. Those paths return / process.exit() normally.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { ensureToken } from '../auth'\nimport { ENVS } from '../env'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? ENVS.prod.api\nconst DEFAULT_TIMEOUT_MS = 120_000\n\ninterface EndpointInfo {\n endpoint: string\n billing: { model: string; baseCost: number; currency: string }\n inputSchema: Record<string, unknown> | null\n example: Record<string, unknown> | null\n}\n\ninterface Catalog {\n integrations: Record<string, EndpointInfo[]>\n}\n\nexport interface InvokeArgs {\n target: string\n body?: string\n bodyFile?: string\n json?: boolean\n timeout?: number\n}\n\nexport interface InfoArgs {\n target: string\n json?: boolean\n}\n\nexport interface ListArgs {\n json?: boolean\n}\n\n/**\n * Parse \"<integration>/<endpoint>\" into its two segments.\n * Throws on malformed input.\n */\nfunction parseTarget(target: string): { integration: string; endpoint: string } {\n if (!target || typeof target !== 'string') {\n throw new Error(\"Missing target. Expected '<integration>/<endpoint>' (e.g. 'openai/chat-completion').\")\n }\n const parts = target.split('/')\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new Error(`Bad target '${target}'. Expected '<integration>/<endpoint>' (e.g. 'openai/chat-completion').`)\n }\n return { integration: parts[0], endpoint: parts[1] }\n}\n\n/**\n * Resolve the request body from --body, --body-file, or default to '{}'.\n * Errors if both --body and --body-file are provided, or the body isn't\n * valid JSON.\n */\nfunction resolveBody(opts: { body?: string; bodyFile?: string }): string {\n if (opts.body != null && opts.bodyFile != null) {\n throw new Error('Pass either --body or --body-file, not both.')\n }\n\n let raw: string\n if (opts.body != null) {\n raw = opts.body\n } else if (opts.bodyFile != null) {\n raw = opts.bodyFile === '-' ? readFileSync(0, 'utf-8') : readFileSync(opts.bodyFile, 'utf-8')\n } else {\n return '{}'\n }\n\n // Validate it parses as JSON so we fail fast with a clear message.\n try {\n JSON.parse(raw)\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'invalid JSON'\n throw new Error(`Body is not valid JSON: ${msg}`)\n }\n return raw\n}\n\n/**\n * Exit the process after stdout has drained.\n *\n * Used only on --json paths. Two problems it solves:\n * 1. Plain `process.exit()` truncates piped stdout for outputs larger\n * than the pipe buffer (~64KB on macOS) — `integrations --json | jq`\n * would lose data because libuv flushes asynchronously.\n * 2. Plain `return` lets citty fire the root command's run(), which\n * appends a trailing prose line that breaks JSON.parse on stdout.\n *\n * The pattern: schedule a zero-byte write so its callback fires only\n * after all prior writes have been flushed, then exit from the callback.\n * Returns a Promise that never resolves so the caller can `await` it\n * with no chance of citty continuing past us.\n */\nfunction flushAndExit(code: number): Promise<never> {\n return new Promise<never>(() => {\n process.stdout.write('', () => process.exit(code))\n })\n}\n\nasync function fetchCatalog(): Promise<Catalog> {\n const res = await fetch(`${API_URL}/api/integrations`)\n if (!res.ok) {\n throw new Error(`Failed to fetch integration catalog (${res.status})`)\n }\n return (await res.json()) as Catalog\n}\n\nfunction findEndpoint(catalog: Catalog, integration: string, endpoint: string): EndpointInfo | null {\n const endpoints = catalog.integrations[integration]\n if (!endpoints) return null\n return endpoints.find((e) => e.endpoint === endpoint) ?? null\n}\n\nfunction formatCurrency(value: number, currency: string): string {\n if (currency === 'USD') return `$${value}`\n return `${value} ${currency}`\n}\n\n/**\n * `deepspace integrations` (default action) / `--list`\n * Prints the catalog grouped by integration.\n */\nexport async function runList(args: ListArgs): Promise<void> {\n const catalog = await fetchCatalog()\n\n if (args.json) {\n process.stdout.write(JSON.stringify(catalog) + '\\n')\n await flushAndExit(0)\n }\n\n const names = Object.keys(catalog.integrations).sort()\n if (names.length === 0) {\n console.log('No integrations available.')\n return\n }\n\n for (const name of names) {\n console.log(name)\n const endpoints = [...catalog.integrations[name]].sort((a, b) => a.endpoint.localeCompare(b.endpoint))\n const widest = Math.max(...endpoints.map((e) => e.endpoint.length))\n for (const ep of endpoints) {\n const pad = ep.endpoint.padEnd(widest)\n const cost = formatCurrency(ep.billing.baseCost, ep.billing.currency)\n console.log(` ${pad} ${ep.billing.model.padEnd(12)} ${cost}`)\n }\n console.log()\n }\n\n console.log(\"Run 'deepspace integrations info <integration>/<endpoint>' for the request schema.\")\n}\n\n/**\n * `deepspace integrations info <target>` / `--info`\n * Prints the schema + example body for a single endpoint.\n */\nexport async function runInfo(args: InfoArgs): Promise<void> {\n const { integration, endpoint } = parseTarget(args.target)\n const catalog = await fetchCatalog()\n const info = findEndpoint(catalog, integration, endpoint)\n\n if (!info) {\n const available = catalog.integrations[integration]\n if (!available) {\n const names = Object.keys(catalog.integrations).sort().join(', ')\n throw new Error(`Unknown integration '${integration}'. Available: ${names}`)\n }\n const endpoints = available.map((e) => e.endpoint).join(', ')\n throw new Error(`Unknown endpoint '${endpoint}' for '${integration}'. Available: ${endpoints}`)\n }\n\n if (args.json) {\n process.stdout.write(JSON.stringify(info) + '\\n')\n await flushAndExit(0)\n }\n\n console.log(`${integration}/${endpoint}`)\n console.log(` billing: ${info.billing.model}, ${formatCurrency(info.billing.baseCost, info.billing.currency)} per call`)\n console.log()\n console.log('Input schema:')\n console.log(info.inputSchema ? JSON.stringify(info.inputSchema, null, 2) : ' (no schema registered)')\n console.log()\n console.log('Example body:')\n console.log(info.example ? JSON.stringify(info.example, null, 2) : ' (no example available)')\n}\n\n/**\n * `deepspace invoke <target>` / `deepspace integrations invoke <target>`\n * Performs the actual integration call.\n */\nexport async function runInvoke(args: InvokeArgs): Promise<void> {\n const { integration, endpoint } = parseTarget(args.target)\n const body = resolveBody({ body: args.body, bodyFile: args.bodyFile })\n const timeoutMs = args.timeout ?? DEFAULT_TIMEOUT_MS\n\n let jwt: string\n try {\n jwt = await ensureToken()\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Error(msg)\n }\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n const startedAt = Date.now()\n\n let res: Response\n try {\n res = await fetch(`${API_URL}/api/integrations/${integration}/${endpoint}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${jwt}`,\n },\n body,\n signal: controller.signal,\n })\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') {\n throw new Error(`Request timed out after ${timeoutMs}ms`)\n }\n throw new Error(err instanceof Error ? err.message : 'Request failed')\n } finally {\n clearTimeout(timer)\n }\n\n const elapsed = Date.now() - startedAt\n let payload: Record<string, unknown>\n try {\n payload = (await res.json()) as Record<string, unknown>\n } catch {\n throw new Error(`Request failed (${res.status}) with non-JSON response`)\n }\n\n if (args.json) {\n process.stdout.write(JSON.stringify(payload) + '\\n')\n await flushAndExit(payload?.success === false || !res.ok ? 1 : 0)\n }\n\n const ok = payload?.success !== false && res.ok\n if (ok) {\n const data = 'data' in payload ? payload.data : payload\n console.log(JSON.stringify(data, null, 2))\n console.error(`\\n✓ ${integration}/${endpoint} (${elapsed}ms)`)\n return\n }\n\n // Error path\n const errMsg = (payload.error as string) ?? `Request failed (${res.status})`\n console.error(`✗ ${integration}/${endpoint} (${res.status}, ${elapsed}ms): ${errMsg}`)\n if (Array.isArray(payload.issues)) {\n for (const issue of payload.issues as Array<{ path?: string[]; message: string }>) {\n const path = issue.path?.length ? issue.path.join('.') : '(root)'\n console.error(` - ${path}: ${issue.message}`)\n }\n }\n if (res.status === 401) {\n console.error(\"\\nHint: run 'deepspace login' to authenticate.\")\n }\n process.exit(1)\n}\n","/**\n * deepspace invoke <integration>/<endpoint> [options]\n *\n * Top-level alias for `deepspace integrations invoke ...`. Calls a platform\n * integration as the currently logged-in user — the same identity shown by\n * `deepspace whoami`. That user is billed.\n *\n * deepspace invoke openai/chat-completion --body '{\"messages\":[...]}'\n * deepspace invoke openai/chat-completion --body-file req.json\n * cat req.json | deepspace invoke openai/chat-completion --body-file -\n * deepspace invoke openai/chat-completion --info\n * deepspace invoke --list\n */\n\nimport { defineCommand } from 'citty'\nimport { runInvoke, runInfo, runList } from './_invoke-impl'\n\nexport default defineCommand({\n meta: {\n name: 'invoke',\n description: 'Invoke a platform integration as the logged-in user',\n },\n args: {\n target: {\n type: 'positional',\n description: \"<integration>/<endpoint> (e.g. 'openai/chat-completion')\",\n required: false,\n },\n body: {\n type: 'string',\n alias: 'd',\n description: 'Inline JSON body',\n required: false,\n },\n 'body-file': {\n type: 'string',\n alias: 'f',\n description: 'Read JSON body from file (use - for stdin)',\n required: false,\n },\n json: {\n type: 'boolean',\n description: 'Print only the response JSON (machine-readable)',\n default: false,\n },\n info: {\n type: 'boolean',\n description: 'Print schema + example body for the endpoint, then exit',\n default: false,\n },\n list: {\n type: 'boolean',\n description: 'Print all available integrations, then exit',\n default: false,\n },\n timeout: {\n type: 'string',\n description: 'Request timeout in milliseconds (default: 120000)',\n required: false,\n },\n },\n async run({ args }) {\n try {\n if (args.list) {\n await runList({ json: args.json })\n return\n }\n if (args.info) {\n await runInfo({ target: args.target as string, json: args.json })\n return\n }\n const timeout = args.timeout != null ? Number(args.timeout) : undefined\n if (timeout != null && (!Number.isFinite(timeout) || timeout <= 0)) {\n throw new Error(`Invalid --timeout '${args.timeout}'. Must be a positive number of milliseconds.`)\n }\n await runInvoke({\n target: args.target as string,\n body: args.body,\n bodyFile: args['body-file'],\n json: args.json,\n timeout,\n })\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err))\n process.exit(1)\n }\n },\n})\n"],"mappings":";;;AAUA,SAAS,iBAAAA,iBAAe,eAAe;AACvC,SAAS,YAAAC,iBAAgB;AACzB,SAAS,gBAAAC,eAAc,cAAAC,oBAAkB;AACzC,SAAS,WAAAC,UAAS,QAAAC,cAAY;AAC9B,SAAS,qBAAqB;;;ACJ9B,SAAS,qBAAqB;AAC9B,SAAS,iBAAAC,gBAAe,iBAAiB;AACzC,SAAS,QAAAC,aAAY;AACrB,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,gBAAgB;AACzB,YAAY,OAAO;;;ACVnB,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,YAAY;AACrB,SAAS,SAAS,iBAAiB;AAE5B,IAAM,OAAO;AAAA,EAClB,KAAK;AAAA,IACH,MAAM;AAAA,IACN,KAAK;AAAA,IACL,UAAU;AAAA,IACV,QAAQ;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D;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,iBAAiB;AAAA,IACjB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAKF,CAAC;AAED,QAAQ,IAAI;","names":["defineCommand","execSync","readFileSync","existsSync","dirname","join","writeFileSync","join","join","writeFileSync","resolve","defineCommand","existsSync","readFileSync","join","homedir","AUTH_URL","join","homedir","defineCommand","existsSync","readFileSync","defineCommand","existsSync","join","readFileSync","writeFileSync","existsSync","mkdirSync","join","homedir","AUTH_URL","DIR","join","homedir","SESSION_PATH","TOKEN_PATH","existsSync","readFileSync","mkdirSync","writeFileSync","defineCommand","existsSync","join","defineCommand","DEFAULT_PORT","resolvePort","defineCommand","existsSync","join","resolve","spawnSync","DEFAULT_PORT","defineCommand","resolve","resolvePort","existsSync","join","spawnSync","defineCommand","p","readFileSync","writeFileSync","existsSync","mkdirSync","join","homedir","SESSION_COOKIE","AUTH_URL","DIR","join","homedir","existsSync","readFileSync","mkdirSync","writeFileSync","SESSION_PATH","defineCommand","defineCommand","execSync","readFileSync","existsSync","parseToml","join","resolve","p","defineCommand","resolve","join","existsSync","parseToml","readFileSync","execSync","wait","defineCommand","readFileSync","existsSync","join","parseToml","p","DEPLOY_URL","defineCommand","join","existsSync","parseToml","readFileSync","defineCommand","defineCommand","defineCommand","existsSync","resolve","join","execSync","defineCommand","execSync","existsSync","readFileSync","join","resolve","parseToml","confirm","resolve","defineCommand","openBrowser","list","execSync","defineCommand","list","defineCommand","readFileSync","API_URL","readFileSync","info","list","defineCommand","defineCommand","defineCommand","dirname","readFileSync","join","existsSync","create","defineCommand","execSync"]}
|