deepspace 0.4.1 → 0.4.2

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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli/cli.ts","../src/cli/commands/login.ts","../src/cli/lib/spinner.ts","../src/cli/env.ts","../src/server/rooms/app-name.ts","../src/cli/session.ts","../src/cli/commands/logout.ts","../src/cli/commands/dev.ts","../src/cli/auth.ts","../src/cli/jwt.ts","../src/cli/lib/install-status.ts","../src/cli/lib/preflight.ts","../src/cli/commands/kill.ts","../src/cli/commands/test.ts","../src/cli/lib/playwright.ts","../src/cli/commands/screenshot.ts","../src/cli/commands/test-accounts.ts","../src/cli/commands/deploy.ts","../src/server/rooms/binding-manifest.ts","../src/cli/commands/undeploy.ts","../src/cli/commands/whoami.ts","../src/cli/commands/add.ts","../src/cli/commands/skills.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","../src/cli/commands/managed-repos.ts","../src/cli/commands/library.ts","../src/cli/commands/admin.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 * managed-repos — manage DeepSpace-owned GitHub repos\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 screenshot from './commands/screenshot'\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 skills from './commands/skills'\nimport domain from './commands/domain'\nimport integrations from './commands/integrations'\nimport invoke from './commands/invoke'\nimport managedRepos from './commands/managed-repos'\nimport library from './commands/library'\nimport admin from './commands/admin'\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 screenshot,\n 'test-accounts': testAccounts,\n add,\n skills,\n integrations,\n 'managed-repos': managedRepos,\n invoke,\n deploy,\n undeploy,\n domain,\n library,\n admin,\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 { randomBytes, createHash } from 'node:crypto'\nimport * as p from '@clack/prompts'\n\nimport { createSpinner } from '../lib/spinner'\nimport { DASHBOARD_URL, 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 = createSpinner()\n s.start('Creating login session...')\n\n // PKCE: generate a random verifier and send only its SHA-256 hash to the\n // server. The verifier never leaves this process, so the loginUrl alone\n // can't be used to drain credentials at /status — only this CLI can.\n const codeVerifier = base64url(randomBytes(32))\n const codeChallenge = base64url(createHash('sha256').update(codeVerifier).digest())\n\n // 1. Create a CLI session\n const sessionRes = await fetch(`${AUTH_URL}/api/auth/cli/session`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ code_challenge: codeChallenge }),\n })\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 {\n sessionId?: string\n loginUrl?: string\n }\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 {\n sessionId: string\n loginUrl: string\n }\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, codeVerifier)\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.log.success(`Logged in as ${result.name ?? result.email}`)\n p.note(\n `Manage your account, deployed apps, billing, and subscription\\nplans on the web dashboard:\\n\\n ${DASHBOARD_URL}`,\n 'Dashboard',\n )\n p.outro('Done')\n },\n})\n\ninterface LoginResult {\n sessionToken: string\n jwt: string\n email: string\n name: string | null\n}\n\nasync function pollForCompletion(\n sessionId: string,\n codeVerifier: string,\n): 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 headers: { 'x-code-verifier': codeVerifier },\n })\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, mode: 0o700 })\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\nfunction base64url(bytes: Buffer): string {\n return bytes.toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\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","import * as p from '@clack/prompts'\n\n// In a real terminal, @clack/prompts repaints the spinner by writing `\\r`\n// to overwrite the previous frame. In non-TTY contexts (agents, CI logs,\n// pipes, `tee`-ed output) `\\r` does nothing and every frame becomes a new\n// line — a single long phase floods the log with thousands of repeats.\n// When stdout is not a TTY we fall back to one static line per phase.\nexport function createSpinner(): {\n start: (msg?: string) => void\n stop: (msg?: string) => void\n message: (msg?: string) => void\n} {\n if (process.stdout.isTTY) return p.spinner()\n return {\n start: (msg?: string) => { if (msg) console.log(msg) },\n stop: (msg?: string) => { if (msg) console.log(msg) },\n message: (msg?: string) => { if (msg) console.log(msg) },\n }\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'\nimport { resolveAppName } from '../server/rooms/app-name'\n\nconst ENV_URLS = {\n auth: 'https://auth.deep.space',\n api: 'https://api-worker.deep.space',\n platform: 'https://platform-worker.deep.space',\n deploy: 'https://deploy-worker.deep.space',\n} as const\n\nexport const ENVS = {\n dev: ENV_URLS,\n prod: ENV_URLS,\n} as const\n\nexport type EnvName = keyof typeof ENVS\n\n/**\n * Web dashboard for managing deployed apps, billing, subscription plans,\n * earnings, etc. Linked from `login` and `whoami` so developers\n * discover it (the CLI alone gives no hint that it exists).\n */\nexport const DASHBOARD_URL = 'https://dashboard.deep.space'\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. A non-canonical `name`\n * (e.g. `My_App` vs. `my-app`) is rejected with a clear error so wrangler.toml\n * stays the single source of truth — otherwise the canonical form would land\n * on deployed bindings and the registry while the raw form persisted in\n * `[vars].APP_NAME` and the client `SCOPE_ID`, splitting identity across\n * surfaces.\n *\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 const resolved = resolveAppName(parsed.name)\n if (!resolved.ok) {\n throw new Error(`wrangler.toml: ${resolved.reason}`)\n }\n // Refuse to proceed when wrangler.toml's name doesn't already match the\n // canonical form. Otherwise the canonical name lands on deployed bindings\n // and the registry, while the raw name persists in `[vars].APP_NAME` and\n // client-side `SCOPE_ID = app:${APP_NAME}` — splitting the identity across\n // surfaces. Failing here forces the dev to fix wrangler.toml once, after\n // which every surface reads from the same source of truth.\n if (parsed.name !== resolved.name) {\n throw new Error(\n `wrangler.toml: name \"${parsed.name}\" is not in canonical form. ` +\n `Update \\`name\\` to \"${resolved.name}\" and re-run.`,\n )\n }\n return resolved.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 * Fetch the per-app HMAC identity token from the deploy worker. The starter's\n * /_deepspace/* proxy attaches this token on every call to the API worker so\n * the platform can verify the request originated from a known app. In\n * production this is minted at deploy time and injected as a Worker binding;\n * in local dev we fetch it via this endpoint, which is gated by app ownership.\n */\nexport async function fetchAppIdentityToken(\n deployUrl: string,\n callerJwt: string,\n appName: string,\n): Promise<string | null> {\n const res = await fetch(\n `${deployUrl}/api/apps/${encodeURIComponent(appName)}/identity-token`,\n {\n method: 'POST',\n headers: { Authorization: `Bearer ${callerJwt}` },\n },\n )\n if (res.status === 404) {\n // App hasn't been deployed yet — pre-deploy dev workflow. The proxy will\n // 401 calls under /_deepspace/* until first deploy registers the app.\n return null\n }\n if (!res.ok) {\n const err = await res.text().catch(() => '')\n throw new Error(`Failed to fetch APP_IDENTITY_TOKEN (${res.status}): ${err}`)\n }\n const body = (await res.json()) as { token?: string; error?: string }\n if (!body.token) {\n throw new Error(`Deploy 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 'APP_IDENTITY_TOKEN',\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 // Pre-first-deploy this returns null (the app isn't in the registry yet)\n // — that's expected. The /_deepspace/* proxy will start working after the\n // first `deepspace deploy` registers the app and a follow-up\n // `deepspace dev` re-runs this writer.\n const appIdentityToken = await fetchAppIdentityToken(urls.deploy, 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 ...(appIdentityToken ? [`APP_IDENTITY_TOKEN=${appIdentityToken}`] : []),\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 * 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 * 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 'cross-spawn'\nimport { ensureToken } from '../auth'\nimport { writeDevVars } from '../env'\nimport { decodeJwtPayload } from '../jwt'\nimport { ensureInstallReady } from '../lib/install-status'\nimport { preflightWindowsWorkerd } from '../lib/preflight'\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 ensureInstallReady(appDir)\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 = decodeJwtPayload<{ sub: string; name?: string; email?: string }>(token)\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 preflightWindowsWorkerd(appDir)\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 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 { decodeJwtPayload } from './jwt'\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')\nexport const 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 // 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 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 // 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, mode: 0o700 })\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 = decodeJwtPayload<{ exp?: number }>(jwt)\n return typeof payload.exp === 'number' && payload.exp * 1000 > Date.now() + 30_000\n } catch {\n return false\n }\n}\n","export function decodeJwtPayload<T = Record<string, unknown>>(token: string): T {\n const payloadSegment = token.split('.')[1]\n if (!payloadSegment) {\n throw new Error('JWT payload is missing')\n }\n return JSON.parse(Buffer.from(payloadSegment, 'base64url').toString('utf8')) as T\n}\n","/**\n * Verifies the app's dependencies are installed before running a command that\n * needs them (dev, test, deploy, add).\n *\n * `create-deepspace` runs `npm install` (and `deepspace skills add`) in a\n * detached background process so the user gets their prompt back immediately.\n * The background worker writes three sentinels under `<appDir>/.deepspace/`:\n *\n * install.started — created before the worker is spawned\n * install.done — written on successful completion\n * install.err — written on failure (contains the error message)\n * install.log — combined stdout/stderr of the install\n *\n * The presence of `node_modules/deepspace/package.json` is the ground truth\n * for \"ready\"; the sentinels only shape the error message.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport function ensureInstallReady(appDir: string): void {\n if (existsSync(join(appDir, 'node_modules', 'deepspace', 'package.json'))) return\n\n const sentinelDir = join(appDir, '.deepspace')\n const errPath = join(sentinelDir, 'install.err')\n const startedPath = join(sentinelDir, 'install.started')\n const donePath = join(sentinelDir, 'install.done')\n const logPath = join(sentinelDir, 'install.log')\n\n if (existsSync(errPath)) {\n console.error('Background install failed:')\n console.error(readFileSync(errPath, 'utf-8').trimEnd())\n if (existsSync(logPath)) console.error(`\\nFull log: ${logPath}`)\n console.error('\\nRun `npm install` (or `bun install`) manually, then retry.')\n process.exit(1)\n }\n\n if (existsSync(startedPath) && !existsSync(donePath)) {\n console.error('Dependencies are still installing in the background.')\n if (existsSync(logPath)) console.error(`Tail progress: tail -f ${logPath}`)\n console.error('Retry once it finishes.')\n process.exit(1)\n }\n\n console.error('Dependencies not installed. Run `npm install` (or `bun install`) first.')\n process.exit(1)\n}\n","import { execFileSync } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\n// 0xC0000135 = STATUS_DLL_NOT_FOUND on Windows. Node reports it as a signed int.\nconst DLL_NOT_FOUND = -1073741515\n\n/**\n * On Windows, the Cloudflare Workers runtime (`workerd.exe`) is built with\n * MSVC and links against `vcruntime140.dll`. A bare Windows install (Server\n * 2022, Server Core, minimal Windows 11) does not ship those DLLs, so workerd\n * exits immediately with STATUS_DLL_NOT_FOUND. Miniflare then surfaces this as\n * \"Error: write EOF\" because workerd closed the stdin pipe before reading its\n * config — an error with no JS stack trace and no hint at the cause.\n *\n * This preflight catches the case and prints the actual fix (install VC++\n * Redistributable). Skip silently if workerd isn't installed yet or runs fine.\n */\nexport function preflightWindowsWorkerd(appDir: string): void {\n if (process.platform !== 'win32') return\n\n const workerdExe = resolve(\n appDir,\n 'node_modules',\n '@cloudflare',\n 'workerd-windows-64',\n 'bin',\n 'workerd.exe',\n )\n if (!existsSync(workerdExe)) return\n\n try {\n execFileSync(workerdExe, ['--help'], { stdio: 'pipe', timeout: 10_000 })\n return\n } catch (err: unknown) {\n const status = (err as { status?: number }).status\n if (status !== DLL_NOT_FOUND) return\n\n console.error('')\n console.error(' workerd (Cloudflare Workers runtime) cannot start on this system.')\n console.error(' It needs the Microsoft Visual C++ Redistributable, which is not installed.')\n console.error('')\n console.error(' Install it with any of:')\n console.error(' winget install Microsoft.VCRedist.2015+.x64')\n console.error(' choco install -y vcredist140')\n console.error(' https://aka.ms/vs/17/release/vc_redist.x64.exe')\n console.error('')\n console.error(' Then restart this terminal and re-run the command.')\n console.error('')\n process.exit(1)\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 { sync as spawnSync } from 'cross-spawn'\nimport { ensureToken } from '../auth'\nimport { writeDevVars } from '../env'\nimport { decodeJwtPayload } from '../jwt'\nimport { ensureInstallReady } from '../lib/install-status'\nimport { ensurePlaywright } from '../lib/playwright'\nimport { preflightWindowsWorkerd } from '../lib/preflight'\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 ensureInstallReady(appDir)\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 = decodeJwtPayload<{ sub: string }>(token)\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 preflightWindowsWorkerd(appDir)\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 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',\n })\n return result.status ?? 1\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","import { execSync } from 'node:child_process'\nimport { sync as spawnSync } from 'cross-spawn'\n\nexport function ensurePlaywright(appDir: string) {\n try {\n // execSync interprets the command via shell, so it handles npx/npx.cmd\n // resolution on its own. Only spawn()/spawnSync() need cross-spawn.\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\n // `playwright install` is idempotent: a fast no-op when Chromium already\n // exists, and the first real browser download only when a browser command\n // actually needs it.\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], {\n cwd: appDir,\n stdio: 'inherit',\n })\n\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","/**\n * deepspace screenshot <url> <output> [--full-page] [--wait-for-timeout ms]\n *\n * Takes a Playwright Chromium screenshot, installing the browser on demand.\n */\n\nimport { defineCommand } from 'citty'\nimport { sync as spawnSync } from 'cross-spawn'\nimport { resolve } from 'node:path'\nimport { ensurePlaywright } from '../lib/playwright'\n\nexport default defineCommand({\n meta: {\n name: 'screenshot',\n description: 'Take a Playwright screenshot, installing Chromium on demand',\n },\n args: {\n url: {\n type: 'positional',\n description: 'URL to capture, for example http://localhost:5173/',\n required: true,\n },\n output: {\n type: 'positional',\n description: 'Output image path, for example screenshot.png',\n required: true,\n },\n 'full-page': {\n type: 'boolean',\n description: 'Capture the full scrollable page',\n required: false,\n },\n 'wait-for-timeout': {\n type: 'string',\n description: 'Milliseconds to wait before capture',\n required: false,\n },\n },\n run({ args }) {\n const appDir = resolve('.')\n ensurePlaywright(appDir)\n\n const playwrightArgs = ['playwright', 'screenshot', args.url, args.output]\n if (args['full-page']) playwrightArgs.push('--full-page')\n if (args['wait-for-timeout']) {\n playwrightArgs.push('--wait-for-timeout', String(args['wait-for-timeout']))\n }\n\n const result = spawnSync('npx', playwrightArgs, {\n cwd: appDir,\n stdio: 'inherit',\n })\n\n process.exit(result.status ?? 1)\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 { pathToFileURL } from 'node:url'\nimport * as p from '@clack/prompts'\nimport { createSpinner } from '../lib/spinner'\nimport { ensureInstallReady } from '../lib/install-status'\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\nconst API_URL = process.env.DEEPSPACE_API_URL ?? ENVS.prod.api\n\nconst CLOUDFLARE_DEPLOY_ERROR_HINT =\n 'Deployment reached the DeepSpace deploy worker, but Cloudflare\\'s deployment ' +\n 'control-plane API failed. This is often caused by a Cloudflare Dashboard/API ' +\n 'incident or Workers for Platforms entitlement outage. Already deployed apps ' +\n 'should keep serving; wait for Cloudflare to recover and retry.'\n\n/**\n * SDK-reserved `run_worker_first` prefixes. Apps can't override or\n * shadow these; only declare additional patterns. The CLI strips the\n * reserved ones before forwarding so the platform never sees them\n * twice — keeps the deploy-side merge a clean set-union.\n */\nconst RESERVED_RUN_WORKER_FIRST = new Set([\n '/api/*',\n '/ws/*',\n '/internal/*',\n '/v1/*',\n '/_deepspace/*',\n])\n\nfunction extractRunWorkerFirst(cfg: { assets?: { run_worker_first?: unknown } }): string[] {\n const raw = cfg.assets?.run_worker_first\n if (!Array.isArray(raw)) return []\n const out: string[] = []\n const seen = new Set<string>()\n for (const entry of raw) {\n if (typeof entry !== 'string') continue\n const trimmed = entry.trim()\n if (!trimmed.startsWith('/')) continue\n if (RESERVED_RUN_WORKER_FIRST.has(trimmed)) continue\n if (seen.has(trimmed)) continue\n seen.add(trimmed)\n out.push(trimmed)\n }\n return out\n}\n\nfunction isLikelyCloudflareDeployFailure(status: number, error: string | undefined): boolean {\n if (status >= 500) return true\n if (!error) return false\n return [\n 'Upload session failed',\n 'Asset upload failed',\n 'Worker deploy failed',\n 'entitlements.not_available',\n 'Internal Server Error',\n ].some((needle) => error.includes(needle))\n}\n\nfunction formatDeployWorkerError(status: number, error: string | undefined): string {\n const detail = error ?? `Deployment error (${status})`\n if (!isLikelyCloudflareDeployFailure(status, error)) return detail\n return `${CLOUDFLARE_DEPLOY_ERROR_HINT}\\n\\nUnderlying error: ${detail}`\n}\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\n // ── Read app name from wrangler.toml ──────────────────────\n const wranglerPath = join(appDir, 'wrangler.toml')\n if (!existsSync(wranglerPath)) {\n console.error('No wrangler.toml found. Are you in a DeepSpace app directory?')\n process.exit(1)\n }\n\n ensureInstallReady(appDir)\n\n p.intro('Deploying DeepSpace app')\n\n const wranglerConfig = parseToml(readFileSync(wranglerPath, 'utf-8')) as {\n name?: string\n assets?: { run_worker_first?: unknown }\n }\n const nameRes = resolveAppName(wranglerConfig.name)\n if (!nameRes.ok) {\n p.cancel(`wrangler.toml: ${nameRes.reason}`)\n process.exit(1)\n }\n // Refuse noncanonical names the same way `deepspace dev` does. Without\n // this, deploy would canonicalize server bindings while client constants\n // (`SCOPE_ID = app:${APP_NAME}`) and `[vars].APP_NAME` continued to use\n // the raw name — splitting identity across surfaces. Fail-fast so the\n // dev fixes wrangler.toml once and every surface reads from the same\n // source of truth.\n if (wranglerConfig.name !== nameRes.name) {\n p.cancel(\n `wrangler.toml: name \"${wranglerConfig.name}\" is not in canonical form. ` +\n `Update \\`name\\` to \"${nameRes.name}\" and re-run.`,\n )\n process.exit(1)\n }\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 = createSpinner()\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 // ── Forward custom worker-first asset routes ───────────────\n // CF Workers `[assets]` config supports a `run_worker_first` array\n // that wins over the SPA 404 fallback for matching paths. We always\n // reserve the SDK baseline (/api/*, /ws/*, /internal/*, /v1/*,\n // /_deepspace/*) on the platform side, but apps can declare extra\n // dynamic routes (e.g. /preview/*, /oauth/*, /.well-known/*) in\n // their wrangler.toml under `[assets] run_worker_first`. Pass those\n // through so the platform merges them into the deployed metadata.\n const extraRoutes = extractRunWorkerFirst(wranglerConfig)\n if (extraRoutes.length) {\n form.append('extraRunWorkerFirst', JSON.stringify(extraRoutes))\n p.log.info(`Custom worker-first routes: ${extraRoutes.join(', ')}`)\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(formatDeployWorkerError(res.status, body.error))\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 await syncSubscriptionPlans(appDir, appName, token)\n await syncOneTimeProducts(appDir, appName, token)\n p.outro('Done')\n return\n }\n }\n\n s.stop('Deployed!')\n p.log.success(`Live at: ${body.url}`)\n\n // ── Reconcile subscription plans + one-time products (optional files) ──\n // Each surfaces its own result inline but never fails the deploy — a\n // developer who hasn't finished Stripe Connect onboarding still gets a\n // working deploy; they just see a warning telling them to connect first.\n await syncSubscriptionPlans(appDir, appName, token)\n await syncOneTimeProducts(appDir, appName, token)\n\n p.outro('Done')\n },\n})\n\n/**\n * Bundle the app's `src/subscriptions.ts` with esbuild, dynamic-import the\n * resulting ESM, and POST the declarations to /api/subscriptions/sync.\n * No-op when the file is absent.\n */\nasync function syncSubscriptionPlans(appDir: string, appName: string, token: string): Promise<void> {\n const subsPath = join(appDir, 'src', 'subscriptions.ts')\n if (!existsSync(subsPath)) return\n\n const s = createSpinner()\n s.start('Syncing subscription plans...')\n\n let plans: unknown\n try {\n const esbuild = await import('esbuild')\n const outDir = join(appDir, '.wrangler', 'deploy')\n const outFile = join(outDir, 'subscriptions.bundle.mjs')\n await esbuild.build({\n entryPoints: [subsPath],\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'node18',\n outfile: outFile,\n logLevel: 'silent',\n write: true,\n })\n // Cache-bust the import — repeat deploys in the same Node process would\n // otherwise reuse a stale module from the loader cache.\n const mod = (await import(`${pathToFileURL(outFile).href}?t=${Date.now()}`)) as {\n subscriptionPlans?: unknown\n }\n plans = mod.subscriptionPlans\n } catch (err: any) {\n s.stop('Plan sync skipped')\n p.log.warn(`Could not load src/subscriptions.ts: ${err.message}`)\n return\n }\n\n if (!Array.isArray(plans)) {\n s.stop('Plan sync skipped')\n p.log.warn(\n 'src/subscriptions.ts must `export const subscriptionPlans = [...] as const`',\n )\n return\n }\n\n // The deploy has already succeeded by the time we get here — a network blip\n // or malformed response on /sync must NOT throw, or the user sees a stack\n // trace after their app is live. Anything unexpected becomes a warning.\n let res: Response\n try {\n res = await fetch(`${API_URL}/api/subscriptions/sync`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ appName, plans }),\n })\n } catch (err: any) {\n s.stop('Plan sync skipped')\n p.log.warn(`Plan sync request failed (network): ${err.message ?? err}`)\n return\n }\n const body = (await res.json().catch(() => ({}))) as {\n ok?: boolean\n error?: string\n hint?: string\n onboardingUrl?: string\n planChanges?: PlanChange[]\n connectMissing?: boolean\n }\n\n if (res.ok && body.ok) {\n s.stop(`Synced ${plans.length} plan${plans.length === 1 ? '' : 's'} to Stripe`)\n // Connect-not-yet-set-up is no longer a sync-blocking error. Plans land\n // in Stripe normally; the warning tells the developer their earnings\n // will queue in the platform balance until they finish Stripe Connect\n // onboarding. Once they connect, the first payout sweeps everything.\n if (body.connectMissing) {\n p.log.warn(\n 'Stripe Connect not yet set up. Customers can subscribe and earnings ' +\n 'will queue in your platform balance until you finish onboarding at ' +\n '/earnings on the dashboard. The first payout after you connect ' +\n 'will sweep everything that accumulated in the meantime.',\n )\n }\n // Any plan change that stranded existing subscribers — whether the plan\n // was removed entirely or just had its price swapped — flows through one\n // prompt. The platform has no way to know whether the developer wants\n // those subscribers cancelled or grandfathered; this is the moment they\n // get to decide. Skipping is fine (silent grandfathering is the safe\n // default); they can always cancel later via the SDK helper.\n const changes = (body.planChanges ?? []).filter((c) => c.affectedSubscribers > 0)\n if (changes.length > 0) {\n await promptAndCancelChangedPlans(appName, token, changes)\n }\n return\n }\n\n s.stop('Plan sync skipped')\n p.log.warn(\n `Plan sync failed: ${body.error ?? `HTTP ${res.status}`}${\n body.hint ? ` — ${body.hint}` : ''\n }`,\n )\n}\n\n// Plan-change events the deploy CLI surfaces to the developer. Mirrors the\n// /sync response shape on the platform side; kept inline here so the helper\n// is self-contained.\ninterface PlanChange {\n slug: string\n reason: 'removed' | 'repriced'\n affectedSubscribers: number\n intervals?: Array<{ interval: 'month' | 'year'; oldCents: number; newCents: number }>\n}\n\nfunction formatCents(c: number): string {\n return c === 0 ? 'free' : `$${(c / 100).toFixed(2)}`\n}\n\nfunction summaryLine(c: PlanChange): string {\n const n = c.affectedSubscribers\n const suffix = `${n} subscriber${n === 1 ? '' : 's'}`\n if (c.reason === 'removed') {\n return ` • ${c.slug} — removed (${suffix} still on it)`\n }\n // repriced: include the interval diffs for context.\n const diffs = (c.intervals ?? [])\n .map((i) => `${i.interval}: ${formatCents(i.oldCents)} → ${formatCents(i.newCents)}`)\n .join('; ')\n return ` • ${c.slug} — repriced (${diffs}; ${suffix} grandfathered on old price)`\n}\n\n/**\n * After /sync reports plans that stranded existing subscribers (removed\n * outright OR repriced with grandfathered customers), ask the developer\n * whether to cancel those subscriptions at the end of their current billing\n * period. Skipping is fine — they can run their own cleanup later via the\n * SDK's `cancelSubscription` helper.\n *\n * One yes/no prompt covers every affected plan. Granular per-plan control\n * is intentionally not surfaced; if a developer wants to cancel for plan A\n * but keep plan B, they can re-declare A in their next deploy.\n *\n * Errors here are warnings, never deploy failures: the deploy itself\n * succeeded; cleanup is the polite-but-optional tail.\n */\nasync function promptAndCancelChangedPlans(\n appName: string,\n token: string,\n changes: PlanChange[],\n): Promise<void> {\n const summary = changes.map(summaryLine).join('\\n')\n p.log.warn(\n `Plan change${changes.length === 1 ? '' : 's'} from this deploy left subscribers stranded:\\n${summary}\\n\\n` +\n 'Stripe will keep charging them until you cancel. Cancel at the end of their\\n' +\n 'current billing period? (Skip to leave them grandfathered.)',\n )\n const choice = await p.confirm({\n message: `Cancel ${changes.length === 1 ? 'these subscribers' : 'all of them'} at period end?`,\n initialValue: false,\n })\n if (p.isCancel(choice) || !choice) {\n p.log.info('Skipped — existing subscribers stay on their current plan/price.')\n return\n }\n\n // The admin-cancel endpoint batches at 50 and returns `hasMore` when there\n // are more rows to process. Loop until done so a plan with hundreds of\n // stranded subscribers gets fully cleaned up — without this, the deploy\n // prompt's confirmation (\"cancel these subscribers\") would silently leave\n // the tail being charged. The cap on iterations is a safety net for the\n // unlikely \"nothing makes progress\" path; a fresh deploy can resume.\n const MAX_ITERATIONS = 100 // 50/batch × 100 = 5000 subs/plan max per deploy\n for (const c of changes) {\n const s = createSpinner()\n s.start(`Canceling ${c.affectedSubscribers} subscriber${c.affectedSubscribers === 1 ? '' : 's'} on ${c.slug}...`)\n let totalCanceled = 0\n let totalFailed = 0\n let iteration = 0\n let lastError: string | null = null\n let stopped = false\n try {\n while (iteration < MAX_ITERATIONS) {\n const res = await fetch(`${API_URL}/api/subscriptions/admin-cancel`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n appName,\n planSlug: c.slug,\n atPeriodEnd: true,\n reason: `plan ${c.reason} via deploy`,\n }),\n })\n const body = (await res.json().catch(() => ({}))) as {\n success?: boolean\n canceled?: number\n failures?: Array<{ stripeSubscriptionId: string; error: string }>\n hasMore?: boolean\n error?: string\n }\n if (!res.ok || !body.success) {\n // Genuine failure (auth, 5xx, etc.) — surface and stop. The empty-\n // match case returns 200 with hasMore=false, not an error, so this\n // branch only fires for real problems.\n lastError = body.error ?? `HTTP ${res.status}`\n s.stop(`Cancel failed for ${c.slug}: ${lastError}`)\n stopped = true\n break\n }\n const batchCanceled = body.canceled ?? 0\n totalCanceled += batchCanceled\n totalFailed += body.failures?.length ?? 0\n if (!body.hasMore) break\n // Progress guard: if a batch returned hasMore=true but canceled=0\n // (every row failed), we'd loop forever. Stop and report.\n if (batchCanceled === 0) {\n lastError = 'no progress (all rows failed this batch)'\n break\n }\n iteration++\n }\n if (!stopped) {\n const tail =\n totalFailed > 0\n ? `; ${totalFailed} failed (see Stripe)`\n : ''\n const cap =\n iteration >= MAX_ITERATIONS\n ? ` (batch cap reached — re-run deploy to finish remaining)`\n : ''\n const errSuffix = lastError ? ` — ${lastError}` : ''\n s.stop(`Canceled ${totalCanceled} on ${c.slug}${tail}${cap}${errSuffix}`)\n }\n } catch (err: any) {\n s.stop(`Cancel failed for ${c.slug}: ${err.message}`)\n }\n }\n}\n\n/**\n * Bundle the app's `src/products.ts` with esbuild, dynamic-import the\n * resulting ESM, and POST the declarations to /api/charges/products/sync.\n * No-op when the file is absent. Mirrors syncSubscriptionPlans — products are\n * the one-time-charge equivalent of subscription plans, and the platform\n * resolves amount/name from this catalog at checkout time so the browser\n * can't pick (productId, amount) together.\n */\nasync function syncOneTimeProducts(appDir: string, appName: string, token: string): Promise<void> {\n const productsPath = join(appDir, 'src', 'products.ts')\n if (!existsSync(productsPath)) return\n\n const s = createSpinner()\n s.start('Syncing one-time products...')\n\n let products: unknown\n try {\n const esbuild = await import('esbuild')\n const outDir = join(appDir, '.wrangler', 'deploy')\n const outFile = join(outDir, 'products.bundle.mjs')\n await esbuild.build({\n entryPoints: [productsPath],\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'node18',\n outfile: outFile,\n logLevel: 'silent',\n write: true,\n })\n const mod = (await import(`${pathToFileURL(outFile).href}?t=${Date.now()}`)) as {\n oneTimeProducts?: unknown\n }\n products = mod.oneTimeProducts\n } catch (err: any) {\n s.stop('Product sync skipped')\n p.log.warn(`Could not load src/products.ts: ${err.message}`)\n return\n }\n\n if (!Array.isArray(products)) {\n s.stop('Product sync skipped')\n p.log.warn(\n 'src/products.ts must `export const oneTimeProducts = [...] as const`',\n )\n return\n }\n\n // See syncSubscriptionPlans for rationale — the deploy is already live by\n // the time we get here, so network/parse failures degrade to warnings.\n let res: Response\n try {\n res = await fetch(`${API_URL}/api/charges/products/sync`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ appName, products }),\n })\n } catch (err: any) {\n s.stop('Product sync skipped')\n p.log.warn(`Product sync request failed (network): ${err.message ?? err}`)\n return\n }\n const body = (await res.json().catch(() => ({}))) as {\n ok?: boolean\n count?: number\n error?: string\n details?: unknown\n }\n\n if (res.ok && body.ok) {\n const n = body.count ?? products.length\n s.stop(`Synced ${n} one-time product${n === 1 ? '' : 's'}`)\n return\n }\n\n s.stop('Product sync skipped')\n p.log.warn(\n `Product sync failed: ${body.error ?? `HTTP ${res.status}`}${\n body.details ? ` — ${JSON.stringify(body.details)}` : ''\n }`,\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).\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 '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 * 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 { createSpinner } from '../lib/spinner'\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 = createSpinner()\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'\nimport { DASHBOARD_URL } from '../env'\nimport { decodeJwtPayload } from '../jwt'\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 = decodeJwtPayload<JwtPayload>(jwt)\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 console.log(`Dashboard: ${DASHBOARD_URL}`)\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'\nimport { ensureInstallReady } from '../lib/install-status'\n\nfunction findScript(from: string): string | null {\n // Preferred: ships inside the deepspace npm package at\n // node_modules/deepspace/scripts/add-feature.cjs, so the script and its\n // sibling features/ dir are delivered by `npm install`.\n const inNodeModules = join(from, 'node_modules', 'deepspace', 'scripts', 'add-feature.cjs')\n if (existsSync(inNodeModules)) return inNodeModules\n // Fallback for apps scaffolded before features moved into the SDK; their\n // .deepspace/ folder still works with newer deepspace versions.\n const inDotDeepspace = join(from, '.deepspace', 'scripts', 'add-feature.cjs')\n if (existsSync(inDotDeepspace)) return inDotDeepspace\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 ensureInstallReady(appDir)\n const script = findScript(appDir)\n\n if (!script) {\n console.error('Could not find the deepspace feature installer.')\n console.error('Looked in:')\n console.error(` ${join(appDir, 'node_modules', 'deepspace', 'scripts', 'add-feature.cjs')}`)\n console.error(` ${join(appDir, '.deepspace', 'scripts', 'add-feature.cjs')}`)\n console.error('Are you in a DeepSpace app directory? Try `npm install` first.')\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 skills <subcommand>\n *\n * Wraps `npx skills@latest add deepdotspace/deepspace-skill` so installation\n * lives under our verb (mirrors `npx remotion skills add`). The upstream\n * `skills` CLI owns repo fetch, idempotency, and agent layouts.\n *\n * deepspace skills add # multi-agent install\n * deepspace skills add -g # install globally\n * deepspace skills add --agent codex # single agent\n * deepspace skills add -y # non-interactive\n *\n * Pre-install fixup for vercel-labs/skills#1138: upstream's project-local\n * install silently skips the Claude Code symlink when `.claude/` doesn't\n * already exist. Pre-creating `.claude/` lets the upstream CLI do the right\n * thing itself, so we don't have to know its layout.\n */\n\nimport { defineCommand } from 'citty'\nimport spawn from 'cross-spawn'\nimport { mkdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\n\nconst SKILL_REPO = 'deepdotspace/deepspace-skill'\nconst SKILL_NAME = 'deepspace'\n\n/**\n * Run `npx -y skills@latest add <repo> [extraArgs]`. Inherits stdio so the\n * `skills` CLI's own prompts / progress bars show through.\n */\nfunction runSkillsAdd(extraArgs: string[]): Promise<number> {\n return new Promise((resolve) => {\n const child = spawn(\n 'npx',\n ['-y', 'skills@latest', 'add', SKILL_REPO, ...extraArgs],\n { stdio: 'inherit' },\n )\n child.on('close', (code) => resolve(code ?? 1))\n child.on('error', (err) => {\n console.error(`Failed to invoke npx: ${err.message}`)\n console.error('Is Node.js installed and on PATH?')\n resolve(1)\n })\n })\n}\n\n/**\n * Workaround for https://github.com/vercel-labs/skills/issues/1138 — the\n * upstream installer's project-local branch silently returns success without\n * creating the Claude Code symlink when `<baseDir>/.claude/` doesn't exist.\n * Pre-creating an empty `.claude/` flips that check and lets the upstream CLI\n * create the symlink itself. Idempotent.\n *\n * @param baseDir cwd for project-local install, $HOME for `-g` global.\n */\nfunction precreateClaudeDir(baseDir: string): void {\n mkdirSync(join(baseDir, '.claude'), { recursive: true })\n}\n\nconst add = defineCommand({\n meta: {\n name: 'add',\n description: 'Install the DeepSpace skill for your coding agent',\n },\n args: {\n global: {\n type: 'boolean',\n alias: 'g',\n description: 'Install globally (~/.agents/skills/) instead of into the current directory',\n default: false,\n },\n yes: {\n type: 'boolean',\n alias: 'y',\n description: 'Skip prompts (assume yes for any confirmation)',\n default: false,\n },\n agent: {\n type: 'string',\n description: 'Target a single agent (e.g. claude-code, codex, opencode). Default: install for all detected agents.',\n required: false,\n },\n },\n async run({ args }) {\n const extra: string[] = []\n if (args.global) extra.push('-g')\n if (args.yes) extra.push('-y')\n if (args.agent) extra.push('--agent', args.agent)\n\n // Pre-create .claude/ so upstream's install picks up Claude Code.\n // Skip when --agent targets a non-claude agent — no point creating\n // an empty .claude/ the user doesn't want.\n if (!args.agent || args.agent === 'claude-code') {\n const baseDir = args.global ? homedir() : process.cwd()\n try {\n precreateClaudeDir(baseDir)\n } catch (err: any) {\n // Non-fatal: upstream will still install for other agents.\n console.warn(`\\n Note: could not pre-create .claude/ for Claude Code: ${err?.message ?? err}`)\n }\n }\n\n const code = await runSkillsAdd(extra)\n if (code !== 0) process.exit(code)\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'skills',\n description: 'Manage the DeepSpace agent skill (Claude Code, Codex, OpenCode, Cursor, ...)',\n },\n subCommands: {\n add,\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\n/**\n * Strip internal-only pricing fields from any value before emitting it to\n * stdout. The api-worker exposes both the user-facing `chargedCents` and the\n * platform's at-cost `costCents`; only the former should reach the CLI user.\n */\nfunction scrubInternal<T>(value: T): T {\n if (Array.isArray(value)) return value.map(scrubInternal) as unknown as T\n if (value && typeof value === 'object') {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (k === 'costCents') continue\n out[k] = scrubInternal(v)\n }\n return out as T\n }\n return value\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(scrubInternal(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 open: { type: 'boolean', description: 'Open browser at Stripe URL (use --no-open to print URL only)', default: true },\n wait: { type: 'boolean', description: 'Poll until provisioning completes (use --no-wait to exit after session creation)', default: true },\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(scrubInternal({ ...checkout, expectedTime, registrar: result.registrar }), null, 2) + '\\n')\n } else {\n console.log(`Stripe Checkout: ${checkout.url}`)\n }\n\n if (args.open && process.stdin.isTTY) {\n openBrowser(checkout.url)\n }\n\n if (!args.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(scrubInternal({ ...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(scrubInternal(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(scrubInternal(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","/**\n * deepspace managed-repos\n *\n * Manage DeepSpace-owned GitHub repos. These are private repositories in the\n * DeepSpace-managed GitHub org, intended for users who do not have or do not\n * want to connect their own GitHub account.\n */\n\nimport { defineCommand } from 'citty'\nimport { ensureToken } from '../auth'\nimport { ENVS } from '../env'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? ENVS.prod.api\nconst SIMPLE_APP_ID = /^[a-z0-9][a-z0-9_.:-]{0,119}$/i\nconst SIMPLE_APP_NAME = /^[a-z0-9][a-z0-9_-]{0,119}$/i\n\ntype ManagedRepo = {\n id: string\n appId: string\n appName: string\n fullName: string\n owner: string\n name: string\n htmlUrl: string\n cloneUrl: string\n}\n\ntype RepoQuota = {\n limit: number\n activeCount: number\n remaining: number\n}\n\ntype RepoToken = {\n token: string\n expiresAt: string\n permissions?: Record<string, string>\n repositorySelection?: string\n}\n\ntype DeletionQuota = {\n limit: number\n deletedCount: number\n remaining: number\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 defaultAppId(appName: string): string {\n return `cli-${slugId(appName)}`\n}\n\nfunction slugId(raw: string): string {\n return raw\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'app'\n}\n\nfunction assertSimple(value: string, pattern: RegExp, label: string): void {\n if (!pattern.test(value)) {\n throw new Error(`${label} must start with a letter or number and contain only simple identifier characters.`)\n }\n}\n\nfunction printQuota(quota: RepoQuota): void {\n console.log(`Repo quota: ${quota.activeCount} / ${quota.limit} active (${quota.remaining} remaining)`)\n}\n\nfunction printRepo(repo: ManagedRepo): void {\n console.log(`${repo.fullName}`)\n console.log(` ID: ${repo.id}`)\n console.log(` App: ${repo.appName}`)\n console.log(` App ID: ${repo.appId}`)\n console.log(` URL: ${repo.htmlUrl}`)\n console.log(` Clone: ${repo.cloneUrl}`)\n}\n\nasync function confirm(message: string): Promise<boolean> {\n if (!process.stdin.isTTY) {\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\nconst list = defineCommand({\n meta: {\n name: 'list',\n description: 'List your DeepSpace-managed repos and quota',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Emit JSON instead of human output',\n default: false,\n },\n },\n async run({ args }) {\n const token = await ensureToken()\n const result = await api<{ repos: ManagedRepo[]; quota: RepoQuota }>(token, '/api/github/repos')\n\n if (args.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n\n printQuota(result.quota)\n if (result.repos.length === 0) {\n console.log('No DeepSpace-managed repos. Create one with `deepspace managed-repos create <app-name>`.')\n return\n }\n\n console.log('')\n for (const repo of result.repos) {\n printRepo(repo)\n }\n },\n})\n\nconst create = defineCommand({\n meta: {\n name: 'create',\n description: 'Create a private DeepSpace-managed GitHub repo',\n },\n args: {\n appName: {\n type: 'positional',\n description: 'Working app name for this repo',\n required: true,\n },\n appId: {\n type: 'string',\n description: 'Stable DeepSpace repo app id (defaults to cli-<app-name>)',\n required: false,\n },\n nameHint: {\n type: 'string',\n description: 'Repo-name hint (defaults to app name)',\n required: false,\n },\n json: {\n type: 'boolean',\n description: 'Emit JSON instead of human output',\n default: false,\n },\n },\n async run({ args }) {\n const appName = String(args.appName)\n const appId = args.appId ? String(args.appId) : defaultAppId(appName)\n const nameHint = args.nameHint ? String(args.nameHint) : undefined\n\n try {\n assertSimple(appName, SIMPLE_APP_NAME, 'appName')\n assertSimple(appId, SIMPLE_APP_ID, 'appId')\n if (nameHint) assertSimple(nameHint, SIMPLE_APP_NAME, 'nameHint')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n\n const token = await ensureToken()\n const result = await api<{ repo: ManagedRepo; alreadyExists: boolean }>(token, '/api/github/repos', {\n method: 'POST',\n body: JSON.stringify({ appName, appId, ...(nameHint ? { nameHint } : {}) }),\n })\n\n if (args.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n\n console.log(result.alreadyExists ? 'Existing DeepSpace-managed repo:' : 'Created DeepSpace-managed repo:')\n printRepo(result.repo)\n },\n})\n\nconst token = defineCommand({\n meta: {\n name: 'token',\n description: 'Mint a short-lived GitHub token for a DeepSpace-managed repo',\n },\n args: {\n repoId: {\n type: 'positional',\n description: 'Repo id from `deepspace managed-repos list`',\n required: true,\n },\n json: {\n type: 'boolean',\n description: 'Emit JSON instead of human output',\n default: false,\n },\n },\n async run({ args }) {\n const jwt = await ensureToken()\n const result = await api<{ repo: ManagedRepo; token: RepoToken }>(\n jwt,\n `/api/github/repos/${encodeURIComponent(String(args.repoId))}/agent-token`,\n { method: 'POST' },\n )\n\n if (args.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n\n console.log(`Repo: ${result.repo.fullName}`)\n console.log(`Expires: ${result.token.expiresAt}`)\n console.log(`Token: ${result.token.token}`)\n console.log('')\n console.log(`Clone: git clone https://x-access-token:${encodeURIComponent(result.token.token)}@github.com/${result.repo.fullName}.git`)\n },\n})\n\nconst remove = defineCommand({\n meta: {\n name: 'delete',\n description: 'Delete a DeepSpace-managed GitHub repo',\n },\n args: {\n repoId: {\n type: 'positional',\n description: 'Repo id from `deepspace managed-repos list`',\n required: true,\n },\n yes: {\n type: 'boolean',\n description: 'Skip the confirmation prompt',\n default: false,\n },\n json: {\n type: 'boolean',\n description: 'Emit JSON instead of human output',\n default: false,\n },\n },\n async run({ args }) {\n if (!args.yes) {\n try {\n const ok = await confirm(\n 'Delete this DeepSpace-managed GitHub repo? This removes the GitHub repository and counts against your daily delete quota.',\n )\n if (!ok) {\n console.log('Cancelled.')\n return\n }\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n }\n\n const jwt = await ensureToken()\n const result = await api<{ repo: ManagedRepo; deletionQuota: DeletionQuota }>(\n jwt,\n `/api/github/repos/${encodeURIComponent(String(args.repoId))}`,\n { method: 'DELETE' },\n )\n\n if (args.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n\n console.log(`Deleted ${result.repo.fullName}`)\n console.log(\n `Delete quota: ${result.deletionQuota.deletedCount} / ${result.deletionQuota.limit} used today (${result.deletionQuota.remaining} remaining)`,\n )\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'managed-repos',\n description: 'Create and manage DeepSpace-owned GitHub repos',\n },\n subCommands: {\n list,\n create,\n token,\n delete: remove,\n },\n})\n","/**\n * deepspace library [publish|unpublish] [options]\n *\n * Manage entries in the DeepSpace community library (lives at\n * deepdotspace-site.app.space by default; override with --library-app\n * or DEEPSPACE_LIBRARY_HOST). Subcommands POST to that app's\n * `library.publish` / `library.unpublish` actions as the currently\n * logged-in user.\n *\n * The publish action verifies the caller owns the deployed app (by\n * checking the deploy worker's `/api/apps` registry) before writing\n * the row, so publishing another user's app is rejected server-side.\n *\n * Usage:\n * deepspace library publish (uses wrangler.toml)\n * deepspace library publish --app my-cool-app --name \"My Cool App\"\n * deepspace library publish --description \"...\" --category Productivity\n * deepspace library publish --tags utility,ai --visibility unlisted\n * deepspace library unpublish <handle>\n */\n\nimport { defineCommand } from 'citty'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport * as p from '@clack/prompts'\n\nimport { ensureToken } from '../auth'\nimport { resolveAppName } from '../../server/rooms/app-name'\n\nconst DEFAULT_LIBRARY_APP = 'deepdotspace-site'\n\nconst publish = defineCommand({\n meta: {\n name: 'publish',\n description: 'Publish the current app to the DeepSpace library',\n },\n args: {\n dir: {\n type: 'string',\n description: 'App directory (default: current directory)',\n required: false,\n },\n app: {\n type: 'string',\n description: 'App name (default: read from wrangler.toml)',\n required: false,\n },\n name: {\n type: 'string',\n description: 'Display name (default: app name)',\n required: false,\n },\n description: {\n type: 'string',\n description: 'Short description',\n required: false,\n },\n category: {\n type: 'string',\n description: 'Category (e.g. Productivity, Finance, AI). Default: General',\n required: false,\n },\n tags: {\n type: 'string',\n description: 'Comma-separated tags',\n required: false,\n },\n visibility: {\n type: 'string',\n description: \"'public' (default), 'unlisted', or 'private'\",\n required: false,\n },\n screenshot: {\n type: 'string',\n description: 'Override the auto-captured preview with a public PNG URL',\n required: false,\n },\n 'library-app': {\n type: 'string',\n description: `Target library app subdomain (default: ${DEFAULT_LIBRARY_APP})`,\n required: false,\n },\n json: {\n type: 'boolean',\n description: 'Print only the JSON response (machine-readable)',\n default: false,\n },\n },\n async run({ args }) {\n const json = !!args.json\n const intro = (s: string) => { if (!json) p.intro(s) }\n const info = (s: string) => { if (!json) p.log.info(s) }\n const die = (msg: string) => {\n if (json) console.error(JSON.stringify({ ok: false, error: msg }))\n else p.cancel(msg)\n process.exit(1)\n }\n\n intro('Publishing to the DeepSpace library')\n\n let appName = typeof args.app === 'string' && args.app.trim() ? args.app.trim() : undefined\n if (!appName) {\n const appDir = resolve(typeof args.dir === 'string' && args.dir ? args.dir : '.')\n const wranglerPath = join(appDir, 'wrangler.toml')\n if (!existsSync(wranglerPath)) {\n return die(\"No --app provided and no wrangler.toml found. Either pass --app <name> or run from your app's directory.\")\n }\n const cfg = parseToml(readFileSync(wranglerPath, 'utf-8')) as { name?: string }\n const nameRes = resolveAppName(cfg.name)\n if (!nameRes.ok) return die(`wrangler.toml: ${nameRes.reason}`)\n appName = nameRes.name\n }\n info(`App: ${appName}`)\n\n const visibility = (args.visibility ?? 'public') as string\n if (!['public', 'private', 'unlisted'].includes(visibility)) {\n return die(\"--visibility must be 'public', 'unlisted', or 'private'.\")\n }\n\n const tags = typeof args.tags === 'string' && args.tags\n ? args.tags.split(',').map((t) => t.trim()).filter(Boolean)\n : undefined\n\n const libraryApp = typeof args['library-app'] === 'string' && args['library-app']\n ? args['library-app']\n : DEFAULT_LIBRARY_APP\n const libraryHost = process.env.DEEPSPACE_LIBRARY_HOST ?? `https://${libraryApp}.app.space`\n\n let token: string\n try {\n token = await ensureToken()\n } catch (err) {\n return die(err instanceof Error ? err.message : String(err))\n }\n\n const payload: Record<string, unknown> = {\n appName,\n ...(args.name ? { name: args.name } : {}),\n ...(args.description ? { description: args.description } : {}),\n ...(args.category ? { category: args.category } : {}),\n ...(tags ? { tags } : {}),\n visibility,\n ...(args.screenshot ? { screenshotUrl: args.screenshot } : {}),\n }\n\n const url = `${libraryHost}/api/actions/library.publish`\n let res: Response\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(payload),\n })\n } catch (err) {\n return die(`Network error reaching ${url}: ${err instanceof Error ? err.message : String(err)}`)\n }\n\n const body = await res.text()\n let parsed: { success?: boolean; data?: { templateHandle?: string; url?: string; version?: number }; error?: string }\n try {\n parsed = JSON.parse(body)\n } catch {\n return die(`Server returned non-JSON (${res.status}): ${body.slice(0, 400)}`)\n }\n\n if (json) {\n console.log(JSON.stringify(parsed))\n process.exit(parsed.success ? 0 : 1)\n }\n\n if (!parsed.success) {\n return die(parsed.error ?? `Publish failed (HTTP ${res.status}).`)\n }\n\n p.log.success(`Published ${appName} as ${parsed.data?.templateHandle} (v${parsed.data?.version})`)\n if (parsed.data?.url) p.log.message(parsed.data.url)\n p.outro('Done')\n },\n})\n\nconst unpublish = defineCommand({\n meta: {\n name: 'unpublish',\n description: 'Remove a library entry (owner or admin only)',\n },\n args: {\n handle: {\n type: 'positional',\n description: 'templateHandle to remove (usually your app name)',\n required: true,\n },\n 'library-app': {\n type: 'string',\n description: `Target library app subdomain (default: ${DEFAULT_LIBRARY_APP})`,\n required: false,\n },\n json: {\n type: 'boolean',\n description: 'Print only the JSON response',\n default: false,\n },\n },\n async run({ args }) {\n const json = !!args.json\n const die = (msg: string) => {\n if (json) console.error(JSON.stringify({ ok: false, error: msg }))\n else p.cancel(msg)\n process.exit(1)\n }\n if (!json) p.intro('Unpublishing library entry')\n\n let token: string\n try { token = await ensureToken() } catch (err) {\n return die(err instanceof Error ? err.message : String(err))\n }\n\n const libraryApp = typeof args['library-app'] === 'string' && args['library-app']\n ? args['library-app']\n : DEFAULT_LIBRARY_APP\n const libraryHost = process.env.DEEPSPACE_LIBRARY_HOST ?? `https://${libraryApp}.app.space`\n\n const res = await fetch(`${libraryHost}/api/actions/library.unpublish`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },\n body: JSON.stringify({ templateHandle: String(args.handle) }),\n })\n const body = await res.text()\n let parsed: { success?: boolean; error?: string; data?: { templateHandle?: string } }\n try { parsed = JSON.parse(body) } catch {\n return die(`Server returned non-JSON (${res.status}): ${body.slice(0, 400)}`)\n }\n if (json) { console.log(JSON.stringify(parsed)); process.exit(parsed.success ? 0 : 1) }\n if (!parsed.success) return die(parsed.error ?? `HTTP ${res.status}`)\n p.log.success(`Unpublished ${parsed.data?.templateHandle}`)\n p.outro('Done')\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'library',\n description: 'Manage your DeepSpace library entries',\n },\n subCommands: {\n publish,\n unpublish,\n },\n})\n","/**\n * deepspace admin\n *\n * Maintainer-only operations gated by DEEPSPACE_ADMIN_SECRET.\n */\n\nimport { defineCommand } from 'citty'\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { ENVS } from '../env'\nimport { TOKEN_PATH } from '../auth'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? ENVS.prod.auth\n\nconst impersonate = defineCommand({\n meta: {\n name: 'impersonate',\n description: 'Store a short-lived CLI token for another user',\n },\n args: {\n email: {\n type: 'string',\n description: 'Target user email',\n required: false,\n },\n userId: {\n type: 'string',\n description: 'Target user id',\n required: false,\n },\n secret: {\n type: 'string',\n description: 'Admin secret; defaults to DEEPSPACE_ADMIN_SECRET',\n required: false,\n },\n },\n async run({ args }) {\n const secret = args.secret ?? process.env.DEEPSPACE_ADMIN_SECRET\n if (!secret) {\n console.error('Missing admin secret. Set DEEPSPACE_ADMIN_SECRET or pass --secret.')\n process.exit(1)\n }\n if (!args.email && !args.userId) {\n console.error('Pass --email or --userId.')\n process.exit(1)\n }\n\n const res = await fetch(`${AUTH_URL}/api/auth/admin/impersonate`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${secret}`,\n },\n body: JSON.stringify({\n email: args.email,\n userId: args.userId,\n }),\n })\n\n const data = (await res.json().catch(() => ({}))) as {\n token?: string\n user?: { id: string; name?: string | null; email?: string | null }\n error?: string\n }\n\n if (!res.ok || !data.token || !data.user) {\n console.error(`Failed: ${data.error ?? `HTTP ${res.status}`}`)\n process.exit(1)\n }\n\n const dir = join(homedir(), '.deepspace')\n mkdirSync(dir, { recursive: true })\n writeFileSync(TOKEN_PATH, data.token, { mode: 0o600 })\n\n console.log(`Impersonating ${data.user.name ?? data.user.email ?? data.user.id}`)\n console.log(`Email: ${data.user.email ?? '(none)'}`)\n console.log(`UserID: ${data.user.id}`)\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'admin',\n description: 'Maintainer-only admin commands',\n },\n subCommands: {\n impersonate,\n },\n})\n"],"mappings":";;;AAWA,SAAS,iBAAAA,iBAAe,eAAe;AACvC,SAAS,YAAAC,iBAAgB;AACzB,SAAS,gBAAAC,gBAAc,cAAAC,oBAAkB;AACzC,SAAS,WAAAC,UAAS,QAAAC,cAAY;AAC9B,SAAS,qBAAqB;;;ACL9B,SAAS,qBAAqB;AAC9B,SAAS,iBAAAC,gBAAe,iBAAiB;AACzC,SAAS,QAAAC,aAAY;AACrB,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB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AAA,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;AAAA,IACA,iBAAiB;AAAA,IACjB;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","p","join","writeFileSync","resolve","defineCommand","existsSync","readFileSync","join","homedir","AUTH_URL","join","homedir","defineCommand","existsSync","readFileSync","defineCommand","existsSync","join","resolve","readFileSync","writeFileSync","existsSync","mkdirSync","join","homedir","token","AUTH_URL","DIR","join","homedir","SESSION_PATH","TOKEN_PATH","existsSync","readFileSync","token","mkdirSync","writeFileSync","existsSync","readFileSync","join","existsSync","status","defineCommand","resolve","existsSync","join","token","defineCommand","DEFAULT_PORT","resolvePort","defineCommand","existsSync","join","resolve","spawnSync","spawnSync","DEFAULT_PORT","defineCommand","resolve","resolvePort","existsSync","join","token","spawnSync","defineCommand","spawnSync","resolve","defineCommand","resolve","spawnSync","defineCommand","p","readFileSync","writeFileSync","existsSync","mkdirSync","join","homedir","SESSION_COOKIE","AUTH_URL","DIR","join","homedir","existsSync","readFileSync","mkdirSync","writeFileSync","token","SESSION_PATH","defineCommand","defineCommand","execSync","readFileSync","existsSync","parseToml","join","resolve","p","status","defineCommand","resolve","join","existsSync","parseToml","readFileSync","token","execSync","wait","defineCommand","readFileSync","existsSync","join","parseToml","p","DEPLOY_URL","defineCommand","join","existsSync","parseToml","readFileSync","token","defineCommand","defineCommand","defineCommand","existsSync","resolve","join","execSync","join","existsSync","defineCommand","resolve","execSync","defineCommand","spawn","mkdirSync","join","homedir","resolve","spawn","mkdirSync","join","defineCommand","homedir","defineCommand","execSync","existsSync","readFileSync","join","resolve","parseToml","API_URL","token","confirm","resolve","defineCommand","openBrowser","list","execSync","defineCommand","list","defineCommand","readFileSync","API_URL","readFileSync","info","list","defineCommand","defineCommand","defineCommand","defineCommand","API_URL","api","token","confirm","resolve","list","defineCommand","create","defineCommand","existsSync","readFileSync","join","resolve","parseToml","p","defineCommand","intro","info","resolve","join","existsSync","parseToml","readFileSync","token","defineCommand","mkdirSync","writeFileSync","homedir","join","AUTH_URL","defineCommand","join","homedir","mkdirSync","writeFileSync","TOKEN_PATH","dirname","readFileSync","join","existsSync","create","defineCommand","execSync"]}
1
+ {"version":3,"sources":["../src/cli/cli.ts","../src/cli/commands/login.ts","../src/cli/lib/spinner.ts","../src/cli/env.ts","../src/server/rooms/app-name.ts","../src/cli/session.ts","../src/cli/commands/logout.ts","../src/cli/commands/dev.ts","../src/cli/auth.ts","../src/cli/jwt.ts","../src/cli/lib/install-status.ts","../src/cli/lib/preflight.ts","../src/cli/commands/kill.ts","../src/cli/commands/test.ts","../src/cli/lib/playwright.ts","../src/cli/commands/screenshot.ts","../src/cli/commands/test-accounts.ts","../src/cli/commands/deploy.ts","../src/server/rooms/binding-manifest.ts","../src/cli/commands/undeploy.ts","../src/cli/commands/whoami.ts","../src/cli/commands/add.ts","../src/cli/commands/skills.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","../src/cli/commands/managed-repos.ts","../src/cli/commands/library.ts","../src/cli/commands/admin.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 * managed-repos — manage DeepSpace-owned GitHub repos\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 screenshot from './commands/screenshot'\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 skills from './commands/skills'\nimport domain from './commands/domain'\nimport integrations from './commands/integrations'\nimport invoke from './commands/invoke'\nimport managedRepos from './commands/managed-repos'\nimport library from './commands/library'\nimport admin from './commands/admin'\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 screenshot,\n 'test-accounts': testAccounts,\n add,\n skills,\n integrations,\n 'managed-repos': managedRepos,\n invoke,\n deploy,\n undeploy,\n domain,\n library,\n admin,\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 { randomBytes, createHash } from 'node:crypto'\nimport * as p from '@clack/prompts'\n\nimport { createSpinner } from '../lib/spinner'\nimport { DASHBOARD_URL, 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 = createSpinner()\n s.start('Creating login session...')\n\n // PKCE: generate a random verifier and send only its SHA-256 hash to the\n // server. The verifier never leaves this process, so the loginUrl alone\n // can't be used to drain credentials at /status — only this CLI can.\n const codeVerifier = base64url(randomBytes(32))\n const codeChallenge = base64url(createHash('sha256').update(codeVerifier).digest())\n\n // 1. Create a CLI session\n const sessionRes = await fetch(`${AUTH_URL}/api/auth/cli/session`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ code_challenge: codeChallenge }),\n })\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 {\n sessionId?: string\n loginUrl?: string\n }\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 {\n sessionId: string\n loginUrl: string\n }\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, codeVerifier)\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.log.success(`Logged in as ${result.name ?? result.email}`)\n p.note(\n `Manage your account, deployed apps, billing, and subscription\\nplans on the web dashboard:\\n\\n ${DASHBOARD_URL}`,\n 'Dashboard',\n )\n p.outro('Done')\n },\n})\n\ninterface LoginResult {\n sessionToken: string\n jwt: string\n email: string\n name: string | null\n}\n\nasync function pollForCompletion(\n sessionId: string,\n codeVerifier: string,\n): 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 headers: { 'x-code-verifier': codeVerifier },\n })\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, mode: 0o700 })\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\nfunction base64url(bytes: Buffer): string {\n return bytes.toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\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","import * as p from '@clack/prompts'\n\n// In a real terminal, @clack/prompts repaints the spinner by writing `\\r`\n// to overwrite the previous frame. In non-TTY contexts (agents, CI logs,\n// pipes, `tee`-ed output) `\\r` does nothing and every frame becomes a new\n// line — a single long phase floods the log with thousands of repeats.\n// When stdout is not a TTY we fall back to one static line per phase.\nexport function createSpinner(): {\n start: (msg?: string) => void\n stop: (msg?: string) => void\n message: (msg?: string) => void\n} {\n if (process.stdout.isTTY) return p.spinner()\n return {\n start: (msg?: string) => { if (msg) console.log(msg) },\n stop: (msg?: string) => { if (msg) console.log(msg) },\n message: (msg?: string) => { if (msg) console.log(msg) },\n }\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'\nimport { resolveAppName } from '../server/rooms/app-name'\n\nconst ENV_URLS = {\n auth: 'https://auth.deep.space',\n api: 'https://api-worker.deep.space',\n platform: 'https://platform-worker.deep.space',\n deploy: 'https://deploy-worker.deep.space',\n} as const\n\nexport const ENVS = {\n dev: ENV_URLS,\n prod: ENV_URLS,\n} as const\n\nexport type EnvName = keyof typeof ENVS\n\n/**\n * Web dashboard for managing deployed apps, billing, subscription plans,\n * earnings, etc. Linked from `login` and `whoami` so developers\n * discover it (the CLI alone gives no hint that it exists).\n */\nexport const DASHBOARD_URL = 'https://dashboard.deep.space'\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. A non-canonical `name`\n * (e.g. `My_App` vs. `my-app`) is rejected with a clear error so wrangler.toml\n * stays the single source of truth — otherwise the canonical form would land\n * on deployed bindings and the registry while the raw form persisted in\n * `[vars].APP_NAME` and the client `SCOPE_ID`, splitting identity across\n * surfaces.\n *\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 const resolved = resolveAppName(parsed.name)\n if (!resolved.ok) {\n throw new Error(`wrangler.toml: ${resolved.reason}`)\n }\n // Refuse to proceed when wrangler.toml's name doesn't already match the\n // canonical form. Otherwise the canonical name lands on deployed bindings\n // and the registry, while the raw name persists in `[vars].APP_NAME` and\n // client-side `SCOPE_ID = app:${APP_NAME}` — splitting the identity across\n // surfaces. Failing here forces the dev to fix wrangler.toml once, after\n // which every surface reads from the same source of truth.\n if (parsed.name !== resolved.name) {\n throw new Error(\n `wrangler.toml: name \"${parsed.name}\" is not in canonical form. ` +\n `Update \\`name\\` to \"${resolved.name}\" and re-run.`,\n )\n }\n return resolved.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 * Fetch the per-app HMAC identity token from the deploy worker. The starter's\n * /_deepspace/* proxy attaches this token on every call to the API worker so\n * the platform can verify the request originated from a known app. In\n * production this is minted at deploy time and injected as a Worker binding;\n * in local dev we fetch it via this endpoint, which is gated by app ownership.\n */\nexport async function fetchAppIdentityToken(\n deployUrl: string,\n callerJwt: string,\n appName: string,\n): Promise<string | null> {\n const res = await fetch(\n `${deployUrl}/api/apps/${encodeURIComponent(appName)}/identity-token`,\n {\n method: 'POST',\n headers: { Authorization: `Bearer ${callerJwt}` },\n },\n )\n if (res.status === 404) {\n // App hasn't been deployed yet — pre-deploy dev workflow. The proxy will\n // 401 calls under /_deepspace/* until first deploy registers the app.\n return null\n }\n if (!res.ok) {\n const err = await res.text().catch(() => '')\n throw new Error(`Failed to fetch APP_IDENTITY_TOKEN (${res.status}): ${err}`)\n }\n const body = (await res.json()) as { token?: string; error?: string }\n if (!body.token) {\n throw new Error(`Deploy worker returned no token: ${body.error ?? 'unknown error'}`)\n }\n return body.token\n}\n\n/**\n * Keys the SDK manages in the top section of .dev.vars. They're rewritten\n * on every `deepspace dev`/`test`/`deploy` run from the platform's truth\n * (auth URL, owner JWT, identity token, etc.). Keys that match this set\n * are stripped from the top section on read so they don't double-write.\n *\n * Critically: this set is only consulted ABOVE the user-managed divider.\n * Once we cross the divider into the \"user owns it\" section, EVERYTHING\n * is preserved — including a user-supplied `ALLOW_DEBUG_ROUTES=true`,\n * which is how an app opts /api/debug/* into prod (the value lands as a\n * secret_text binding on the deployed worker). See extractCustomDevVars.\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 'APP_IDENTITY_TOKEN',\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 // SDK-managed keys are only stripped ABOVE the divider. Once we cross\n // into the user-owned section, every line is preserved verbatim — so\n // an app can opt into shipping a key the SDK happens to also write\n // (today: `ALLOW_DEBUG_ROUTES=true`) by setting it in that section.\n let belowDivider = false\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 belowDivider = true\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 (belowDivider || !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 // Pre-first-deploy this returns null (the app isn't in the registry yet)\n // — that's expected. The /_deepspace/* proxy will start working after the\n // first `deepspace deploy` registers the app and a follow-up\n // `deepspace dev` re-runs this writer.\n const appIdentityToken = await fetchAppIdentityToken(urls.deploy, 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 ...(appIdentityToken ? [`APP_IDENTITY_TOKEN=${appIdentityToken}`] : []),\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 * 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 * 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 'cross-spawn'\nimport { ensureToken } from '../auth'\nimport { writeDevVars } from '../env'\nimport { decodeJwtPayload } from '../jwt'\nimport { ensureInstallReady } from '../lib/install-status'\nimport { preflightWindowsWorkerd } from '../lib/preflight'\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 ensureInstallReady(appDir)\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 = decodeJwtPayload<{ sub: string; name?: string; email?: string }>(token)\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 preflightWindowsWorkerd(appDir)\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 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 { decodeJwtPayload } from './jwt'\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')\nexport const 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 // 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 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 // 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, mode: 0o700 })\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 = decodeJwtPayload<{ exp?: number }>(jwt)\n return typeof payload.exp === 'number' && payload.exp * 1000 > Date.now() + 30_000\n } catch {\n return false\n }\n}\n","export function decodeJwtPayload<T = Record<string, unknown>>(token: string): T {\n const payloadSegment = token.split('.')[1]\n if (!payloadSegment) {\n throw new Error('JWT payload is missing')\n }\n return JSON.parse(Buffer.from(payloadSegment, 'base64url').toString('utf8')) as T\n}\n","/**\n * Verifies the app's dependencies are installed before running a command that\n * needs them (dev, test, deploy, add).\n *\n * `create-deepspace` runs `npm install` (and `deepspace skills add`) in a\n * detached background process so the user gets their prompt back immediately.\n * The background worker writes three sentinels under `<appDir>/.deepspace/`:\n *\n * install.started — created before the worker is spawned\n * install.done — written on successful completion\n * install.err — written on failure (contains the error message)\n * install.log — combined stdout/stderr of the install\n *\n * The presence of `node_modules/deepspace/package.json` is the ground truth\n * for \"ready\"; the sentinels only shape the error message.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport function ensureInstallReady(appDir: string): void {\n if (existsSync(join(appDir, 'node_modules', 'deepspace', 'package.json'))) return\n\n const sentinelDir = join(appDir, '.deepspace')\n const errPath = join(sentinelDir, 'install.err')\n const startedPath = join(sentinelDir, 'install.started')\n const donePath = join(sentinelDir, 'install.done')\n const logPath = join(sentinelDir, 'install.log')\n\n if (existsSync(errPath)) {\n console.error('Background install failed:')\n console.error(readFileSync(errPath, 'utf-8').trimEnd())\n if (existsSync(logPath)) console.error(`\\nFull log: ${logPath}`)\n console.error('\\nRun `npm install` (or `bun install`) manually, then retry.')\n process.exit(1)\n }\n\n if (existsSync(startedPath) && !existsSync(donePath)) {\n console.error('Dependencies are still installing in the background.')\n if (existsSync(logPath)) console.error(`Tail progress: tail -f ${logPath}`)\n console.error('Retry once it finishes.')\n process.exit(1)\n }\n\n console.error('Dependencies not installed. Run `npm install` (or `bun install`) first.')\n process.exit(1)\n}\n","import { execFileSync } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\n// 0xC0000135 = STATUS_DLL_NOT_FOUND on Windows. Node reports it as a signed int.\nconst DLL_NOT_FOUND = -1073741515\n\n/**\n * On Windows, the Cloudflare Workers runtime (`workerd.exe`) is built with\n * MSVC and links against `vcruntime140.dll`. A bare Windows install (Server\n * 2022, Server Core, minimal Windows 11) does not ship those DLLs, so workerd\n * exits immediately with STATUS_DLL_NOT_FOUND. Miniflare then surfaces this as\n * \"Error: write EOF\" because workerd closed the stdin pipe before reading its\n * config — an error with no JS stack trace and no hint at the cause.\n *\n * This preflight catches the case and prints the actual fix (install VC++\n * Redistributable). Skip silently if workerd isn't installed yet or runs fine.\n */\nexport function preflightWindowsWorkerd(appDir: string): void {\n if (process.platform !== 'win32') return\n\n const workerdExe = resolve(\n appDir,\n 'node_modules',\n '@cloudflare',\n 'workerd-windows-64',\n 'bin',\n 'workerd.exe',\n )\n if (!existsSync(workerdExe)) return\n\n try {\n execFileSync(workerdExe, ['--help'], { stdio: 'pipe', timeout: 10_000 })\n return\n } catch (err: unknown) {\n const status = (err as { status?: number }).status\n if (status !== DLL_NOT_FOUND) return\n\n console.error('')\n console.error(' workerd (Cloudflare Workers runtime) cannot start on this system.')\n console.error(' It needs the Microsoft Visual C++ Redistributable, which is not installed.')\n console.error('')\n console.error(' Install it with any of:')\n console.error(' winget install Microsoft.VCRedist.2015+.x64')\n console.error(' choco install -y vcredist140')\n console.error(' https://aka.ms/vs/17/release/vc_redist.x64.exe')\n console.error('')\n console.error(' Then restart this terminal and re-run the command.')\n console.error('')\n process.exit(1)\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 { sync as spawnSync } from 'cross-spawn'\nimport { ensureToken } from '../auth'\nimport { writeDevVars } from '../env'\nimport { decodeJwtPayload } from '../jwt'\nimport { ensureInstallReady } from '../lib/install-status'\nimport { ensurePlaywright } from '../lib/playwright'\nimport { preflightWindowsWorkerd } from '../lib/preflight'\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 ensureInstallReady(appDir)\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 = decodeJwtPayload<{ sub: string }>(token)\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 preflightWindowsWorkerd(appDir)\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 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',\n })\n return result.status ?? 1\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","import { execSync } from 'node:child_process'\nimport { sync as spawnSync } from 'cross-spawn'\n\nexport function ensurePlaywright(appDir: string) {\n try {\n // execSync interprets the command via shell, so it handles npx/npx.cmd\n // resolution on its own. Only spawn()/spawnSync() need cross-spawn.\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\n // `playwright install` is idempotent: a fast no-op when Chromium already\n // exists, and the first real browser download only when a browser command\n // actually needs it.\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], {\n cwd: appDir,\n stdio: 'inherit',\n })\n\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","/**\n * deepspace screenshot <url> <output> [--full-page] [--wait-for-timeout ms]\n *\n * Takes a Playwright Chromium screenshot, installing the browser on demand.\n */\n\nimport { defineCommand } from 'citty'\nimport { sync as spawnSync } from 'cross-spawn'\nimport { resolve } from 'node:path'\nimport { ensurePlaywright } from '../lib/playwright'\n\nexport default defineCommand({\n meta: {\n name: 'screenshot',\n description: 'Take a Playwright screenshot, installing Chromium on demand',\n },\n args: {\n url: {\n type: 'positional',\n description: 'URL to capture, for example http://localhost:5173/',\n required: true,\n },\n output: {\n type: 'positional',\n description: 'Output image path, for example screenshot.png',\n required: true,\n },\n 'full-page': {\n type: 'boolean',\n description: 'Capture the full scrollable page',\n required: false,\n },\n 'wait-for-timeout': {\n type: 'string',\n description: 'Milliseconds to wait before capture',\n required: false,\n },\n },\n run({ args }) {\n const appDir = resolve('.')\n ensurePlaywright(appDir)\n\n const playwrightArgs = ['playwright', 'screenshot', args.url, args.output]\n if (args['full-page']) playwrightArgs.push('--full-page')\n if (args['wait-for-timeout']) {\n playwrightArgs.push('--wait-for-timeout', String(args['wait-for-timeout']))\n }\n\n const result = spawnSync('npx', playwrightArgs, {\n cwd: appDir,\n stdio: 'inherit',\n })\n\n process.exit(result.status ?? 1)\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 { randomUUID } from 'node:crypto'\nimport { readFileSync, readdirSync, existsSync } from 'node:fs'\nimport { parse as parseToml } from 'smol-toml'\nimport { join, resolve, dirname } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport * as p from '@clack/prompts'\nimport { createSpinner } from '../lib/spinner'\nimport { ensureInstallReady } from '../lib/install-status'\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\nconst API_URL = process.env.DEEPSPACE_API_URL ?? ENVS.prod.api\n\nconst CLOUDFLARE_DEPLOY_ERROR_HINT =\n 'Deployment reached the DeepSpace deploy worker, but Cloudflare\\'s deployment ' +\n 'control-plane API failed. This is often caused by a Cloudflare Dashboard/API ' +\n 'incident or Workers for Platforms entitlement outage. Already deployed apps ' +\n 'should keep serving; wait for Cloudflare to recover and retry.'\n\n/**\n * SDK-reserved `run_worker_first` prefixes. Apps can't override or\n * shadow these; only declare additional patterns. The CLI strips the\n * reserved ones before forwarding so the platform never sees them\n * twice — keeps the deploy-side merge a clean set-union.\n */\nconst RESERVED_RUN_WORKER_FIRST = new Set([\n '/api/*',\n '/ws/*',\n '/internal/*',\n '/v1/*',\n '/_deepspace/*',\n])\n\nfunction extractRunWorkerFirst(cfg: { assets?: { run_worker_first?: unknown } }): string[] {\n const raw = cfg.assets?.run_worker_first\n if (!Array.isArray(raw)) return []\n const out: string[] = []\n const seen = new Set<string>()\n for (const entry of raw) {\n if (typeof entry !== 'string') continue\n const trimmed = entry.trim()\n if (!trimmed.startsWith('/')) continue\n if (RESERVED_RUN_WORKER_FIRST.has(trimmed)) continue\n if (seen.has(trimmed)) continue\n seen.add(trimmed)\n out.push(trimmed)\n }\n return out\n}\n\nfunction isLikelyCloudflareDeployFailure(status: number, error: string | undefined): boolean {\n if (status >= 500) return true\n if (!error) return false\n return [\n 'Upload session failed',\n 'Asset upload failed',\n 'Worker deploy failed',\n 'entitlements.not_available',\n 'Internal Server Error',\n ].some((needle) => error.includes(needle))\n}\n\nfunction formatDeployWorkerError(status: number, error: string | undefined): string {\n const detail = error ?? `Deployment error (${status})`\n if (!isLikelyCloudflareDeployFailure(status, error)) return detail\n return `${CLOUDFLARE_DEPLOY_ERROR_HINT}\\n\\nUnderlying error: ${detail}`\n}\n\n/**\n * Must stay <= the deploy worker's MAX_UPLOAD_GROUP_BYTES, otherwise the worker\n * rejects a group with a 413 that postWithRetry won't retry (it's a 4xx),\n * dead-ending the deploy. The DEEPSPACE_DEPLOY_GROUP_BYTES override is clamped\n * to this.\n */\nconst MAX_GROUP_BYTES = 40 * 1024 * 1024\n\n/**\n * Soft cap on the serialized size of one asset *group*. We pack whole asset\n * entries into groups under this size and POST each group on its own, so no\n * single request carries the entire payload (a ~40MB+ body stalls and gets\n * reset mid-upload on a marginal uplink: `write EPIPE`). A single asset larger\n * than this is sent alone in its own group — we never split an individual\n * asset. Overridable via DEEPSPACE_DEPLOY_GROUP_BYTES, clamped to MAX_GROUP_BYTES.\n */\nconst GROUP_BYTES = (() => {\n const raw = Number(process.env.DEEPSPACE_DEPLOY_GROUP_BYTES)\n const v = Number.isInteger(raw) && raw > 0 ? raw : 3 * 1024 * 1024\n return Math.min(v, MAX_GROUP_BYTES)\n})()\n\n/**\n * Pack whole asset entries into groups whose serialized JSON stays under\n * `maxBytes`. We never split an individual asset across groups, so a single\n * asset larger than `maxBytes` becomes its own (oversized) group.\n */\nexport function packAssetGroups<T>(assets: T[], maxBytes: number): T[][] {\n const groups: T[][] = []\n let current: T[] = []\n let currentBytes = 2 // \"[]\"\n for (const a of assets) {\n const entryBytes = Buffer.byteLength(JSON.stringify(a), 'utf-8') + 1 // +1 ≈ comma\n if (current.length > 0 && currentBytes + entryBytes > maxBytes) {\n groups.push(current)\n current = []\n currentBytes = 2\n }\n current.push(a)\n currentBytes += entryBytes\n }\n if (current.length > 0) groups.push(current)\n return groups\n}\n\n/**\n * POST with retry + backoff. Chunked upload exists to survive a flaky uplink,\n * so we always retry on network errors (fetch throws — e.g. `write EPIPE` when\n * the edge resets a stalled upload). Transient server statuses (408/429/5xx)\n * are only retried when `retryServerErrors` is set; client 4xx are always\n * returned as-is (caller surfaces the message). `makeInit` is called per\n * attempt so the request body is rebuilt fresh each time.\n *\n * The group-staging endpoint is an idempotent PUT, so retrying its 5xx is safe.\n * The commit endpoint runs a real (non-idempotent) deploy, so it passes\n * `retryServerErrors: false` — a 5xx means the server already received and\n * possibly acted on the request, and re-sending could double-deploy. Only a\n * thrown fetch (connection reset before/without a response) is retried there.\n */\nexport async function postWithRetry(\n url: string,\n makeInit: () => RequestInit,\n { attempts = 4, retryServerErrors = true }: { attempts?: number; retryServerErrors?: boolean } = {},\n): Promise<Response> {\n let lastRes: Response | undefined\n let lastErr: unknown\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n const res = await fetch(url, makeInit())\n const isTransient =\n retryServerErrors && (res.status >= 500 || res.status === 408 || res.status === 429)\n if (!isTransient) {\n return res\n }\n lastRes = res\n } catch (err) {\n lastErr = err\n }\n if (attempt < attempts) {\n await new Promise((r) => setTimeout(r, Math.min(8_000, 500 * 2 ** (attempt - 1))))\n }\n }\n if (lastRes) return lastRes\n throw lastErr instanceof Error ? lastErr : new Error(String(lastErr))\n}\n\n/**\n * Best-effort cleanup of an upload's staged groups after a deploy gives up.\n * Fire-and-forget: a failed deploy must surface its real error, not a cleanup\n * error, so this never throws. It's not the only safety net either — the\n * deploy worker's R2 staging prefix carries a lifecycle rule that reaps\n * anything this misses (e.g. the CLI process is killed before it can abort).\n */\nasync function abortStagedUpload(\n appName: string,\n uploadId: string,\n totalGroups: number,\n token: string,\n): Promise<void> {\n try {\n await fetch(\n `${DEPLOY_URL}/api/deploy/${appName}/assets` +\n `?uploadId=${uploadId}&totalGroups=${totalGroups}`,\n { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } },\n )\n } catch {\n // best-effort — orphaned groups are reaped by the staging lifecycle rule\n }\n}\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\n // ── Read app name from wrangler.toml ──────────────────────\n const wranglerPath = join(appDir, 'wrangler.toml')\n if (!existsSync(wranglerPath)) {\n console.error('No wrangler.toml found. Are you in a DeepSpace app directory?')\n process.exit(1)\n }\n\n ensureInstallReady(appDir)\n\n p.intro('Deploying DeepSpace app')\n\n const wranglerConfig = parseToml(readFileSync(wranglerPath, 'utf-8')) as {\n name?: string\n assets?: { run_worker_first?: unknown }\n }\n const nameRes = resolveAppName(wranglerConfig.name)\n if (!nameRes.ok) {\n p.cancel(`wrangler.toml: ${nameRes.reason}`)\n process.exit(1)\n }\n // Refuse noncanonical names the same way `deepspace dev` does. Without\n // this, deploy would canonicalize server bindings while client constants\n // (`SCOPE_ID = app:${APP_NAME}`) and `[vars].APP_NAME` continued to use\n // the raw name — splitting identity across surfaces. Fail-fast so the\n // dev fixes wrangler.toml once and every surface reads from the same\n // source of truth.\n if (wranglerConfig.name !== nameRes.name) {\n p.cancel(\n `wrangler.toml: name \"${wranglerConfig.name}\" is not in canonical form. ` +\n `Update \\`name\\` to \"${nameRes.name}\" and re-run.`,\n )\n process.exit(1)\n }\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 = createSpinner()\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 // Show both streams. Vite writes build errors to stderr, but the Rules of\n // Hooks checker (vite-plugin-checker) prints its diagnostics to stdout —\n // showing only stderr would collapse a hooks violation into a bare\n // \"Command failed\" and hide the exact fix the developer needs.\n const detail = [err.stdout?.toString(), err.stderr?.toString()]\n .filter(Boolean)\n .join('\\n')\n .trim()\n console.error(detail || 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 // ── Forward custom worker-first asset routes ───────────────\n // CF Workers `[assets]` config supports a `run_worker_first` array\n // that wins over the SPA 404 fallback for matching paths. We always\n // reserve the SDK baseline (/api/*, /ws/*, /internal/*, /v1/*,\n // /_deepspace/*) on the platform side, but apps can declare extra\n // dynamic routes (e.g. /preview/*, /oauth/*, /.well-known/*) in\n // their wrangler.toml under `[assets] run_worker_first`. Pass those\n // through so the platform merges them into the deployed metadata.\n const extraRoutes = extractRunWorkerFirst(wranglerConfig)\n if (extraRoutes.length) {\n p.log.info(`Custom worker-first routes: ${extraRoutes.join(', ')}`)\n }\n\n // ── Choose transport: inline vs grouped ────────────────────\n // The assets array (base64-inlined file bytes) is the bulk of the upload.\n // Sending it all in one request stalls and gets reset mid-body on a\n // marginal uplink (`write EPIPE`). When it doesn't fit in a single group we\n // pack whole asset entries into groups under GROUP_BYTES, POST each group\n // on its own (retry-able) into the deploy worker's R2 staging, and\n // reference them by `uploadId` in the small commit request below. Small\n // deploys keep the original single-request inline transport.\n const assetGroups = packAssetGroups(assets, GROUP_BYTES)\n let inlineAssets: string | null = null\n let uploadId: string | null = null\n let totalGroups = 0\n if (assetGroups.length <= 1) {\n inlineAssets = JSON.stringify(assets)\n } else {\n uploadId = randomUUID()\n totalGroups = assetGroups.length\n try {\n for (let i = 0; i < totalGroups; i++) {\n const groupJson = JSON.stringify(assetGroups[i])\n s.message(`Uploading assets — group ${i + 1}/${totalGroups}...`)\n const groupRes = await postWithRetry(\n `${DEPLOY_URL}/api/deploy/${appName}/assets` +\n `?uploadId=${uploadId}&groupIndex=${i}&totalGroups=${totalGroups}`,\n () => ({\n method: 'POST',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: groupJson,\n }),\n )\n if (!groupRes.ok) {\n const errBody = (await groupRes.json().catch(() => ({}))) as { error?: string }\n // Reap the groups already staged for this upload before bailing —\n // a fresh deploy mints a new uploadId, so these would otherwise\n // never be reused.\n await abortStagedUpload(appName, uploadId, totalGroups, token)\n s.stop('Deploy failed')\n p.cancel(\n `Asset upload failed on group ${i + 1}/${totalGroups}: ` +\n `${errBody.error ?? `HTTP ${groupRes.status}`}`,\n )\n process.exit(1)\n }\n }\n } catch (err: any) {\n // postWithRetry exhausted its network-error retries and threw.\n await abortStagedUpload(appName, uploadId, totalGroups, token)\n s.stop('Deploy failed')\n p.cancel(`Asset upload failed (network): ${err?.message ?? err}`)\n process.exit(1)\n }\n s.message(`Deploying to ${appName}.app.space...`)\n }\n\n // Rebuilt per attempt so retried requests get a fresh body.\n const makeForm = (): FormData => {\n const form = new FormData()\n form.append('worker', new Blob([workerJs], { type: 'application/javascript' }), 'worker.js')\n if (inlineAssets !== null) {\n form.append('assets', inlineAssets)\n } else {\n form.append('uploadId', uploadId as string)\n form.append('totalGroups', String(totalGroups))\n }\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 if (extraRoutes.length) {\n form.append('extraRunWorkerFirst', JSON.stringify(extraRoutes))\n }\n return form\n }\n\n let res: Response\n try {\n res = await postWithRetry(\n `${DEPLOY_URL}/api/deploy/${appName}`,\n () => ({\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n body: makeForm(),\n }),\n // Commit runs a real deploy — don't retry its 5xx (could double-deploy);\n // only a thrown fetch (dropped connection) is retried, and the staged\n // groups survive on the worker until this request succeeds.\n { retryServerErrors: false },\n )\n } catch (err: any) {\n // The commit never got a response after its retries (dropped connection).\n // Reap the staged groups — a fresh deploy mints a new uploadId.\n if (uploadId) await abortStagedUpload(appName, uploadId, totalGroups, token)\n s.stop('Deploy failed')\n p.cancel(`Deploy request failed: ${err?.message ?? err}`)\n process.exit(1)\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 // Definitive failure — the worker won't reuse these groups (a re-run mints\n // a new uploadId), so reap them now rather than leaving them for the\n // lifecycle rule.\n if (uploadId) await abortStagedUpload(appName, uploadId, totalGroups, token)\n s.stop('Deploy failed')\n p.cancel(formatDeployWorkerError(res.status, body.error))\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 await syncSubscriptionPlans(appDir, appName, token)\n await syncOneTimeProducts(appDir, appName, token)\n p.outro('Done')\n return\n }\n }\n\n s.stop('Deployed!')\n p.log.success(`Live at: ${body.url}`)\n\n // ── Reconcile subscription plans + one-time products (optional files) ──\n // Each surfaces its own result inline but never fails the deploy — a\n // developer who hasn't finished Stripe Connect onboarding still gets a\n // working deploy; they just see a warning telling them to connect first.\n await syncSubscriptionPlans(appDir, appName, token)\n await syncOneTimeProducts(appDir, appName, token)\n\n p.outro('Done')\n },\n})\n\n/**\n * Bundle the app's `src/subscriptions.ts` with esbuild, dynamic-import the\n * resulting ESM, and POST the declarations to /api/subscriptions/sync.\n * No-op when the file is absent.\n */\nasync function syncSubscriptionPlans(appDir: string, appName: string, token: string): Promise<void> {\n const subsPath = join(appDir, 'src', 'subscriptions.ts')\n if (!existsSync(subsPath)) return\n\n const s = createSpinner()\n s.start('Syncing subscription plans...')\n\n let plans: unknown\n try {\n const esbuild = await import('esbuild')\n const outDir = join(appDir, '.wrangler', 'deploy')\n const outFile = join(outDir, 'subscriptions.bundle.mjs')\n await esbuild.build({\n entryPoints: [subsPath],\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'node18',\n outfile: outFile,\n logLevel: 'silent',\n write: true,\n })\n // Cache-bust the import — repeat deploys in the same Node process would\n // otherwise reuse a stale module from the loader cache.\n const mod = (await import(`${pathToFileURL(outFile).href}?t=${Date.now()}`)) as {\n subscriptionPlans?: unknown\n }\n plans = mod.subscriptionPlans\n } catch (err: any) {\n s.stop('Plan sync skipped')\n p.log.warn(`Could not load src/subscriptions.ts: ${err.message}`)\n return\n }\n\n if (!Array.isArray(plans)) {\n s.stop('Plan sync skipped')\n p.log.warn(\n 'src/subscriptions.ts must `export const subscriptionPlans = [...] as const`',\n )\n return\n }\n\n // The deploy has already succeeded by the time we get here — a network blip\n // or malformed response on /sync must NOT throw, or the user sees a stack\n // trace after their app is live. Anything unexpected becomes a warning.\n let res: Response\n try {\n res = await fetch(`${API_URL}/api/subscriptions/sync`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ appName, plans }),\n })\n } catch (err: any) {\n s.stop('Plan sync skipped')\n p.log.warn(`Plan sync request failed (network): ${err.message ?? err}`)\n return\n }\n const body = (await res.json().catch(() => ({}))) as {\n ok?: boolean\n error?: string\n hint?: string\n onboardingUrl?: string\n planChanges?: PlanChange[]\n connectMissing?: boolean\n }\n\n if (res.ok && body.ok) {\n s.stop(`Synced ${plans.length} plan${plans.length === 1 ? '' : 's'} to Stripe`)\n // Connect-not-yet-set-up is no longer a sync-blocking error. Plans land\n // in Stripe normally; the warning tells the developer their earnings\n // will queue in the platform balance until they finish Stripe Connect\n // onboarding. Once they connect, the first payout sweeps everything.\n if (body.connectMissing) {\n p.log.warn(\n 'Stripe Connect not yet set up. Customers can subscribe and earnings ' +\n 'will queue in your platform balance until you finish onboarding at ' +\n '/earnings on the dashboard. The first payout after you connect ' +\n 'will sweep everything that accumulated in the meantime.',\n )\n }\n // Any plan change that stranded existing subscribers — whether the plan\n // was removed entirely or just had its price swapped — flows through one\n // prompt. The platform has no way to know whether the developer wants\n // those subscribers cancelled or grandfathered; this is the moment they\n // get to decide. Skipping is fine (silent grandfathering is the safe\n // default); they can always cancel later via the SDK helper.\n const changes = (body.planChanges ?? []).filter((c) => c.affectedSubscribers > 0)\n if (changes.length > 0) {\n await promptAndCancelChangedPlans(appName, token, changes)\n }\n return\n }\n\n s.stop('Plan sync skipped')\n p.log.warn(\n `Plan sync failed: ${body.error ?? `HTTP ${res.status}`}${\n body.hint ? ` — ${body.hint}` : ''\n }`,\n )\n}\n\n// Plan-change events the deploy CLI surfaces to the developer. Mirrors the\n// /sync response shape on the platform side; kept inline here so the helper\n// is self-contained.\ninterface PlanChange {\n slug: string\n reason: 'removed' | 'repriced'\n affectedSubscribers: number\n intervals?: Array<{ interval: 'month' | 'year'; oldCents: number; newCents: number }>\n}\n\nfunction formatCents(c: number): string {\n return c === 0 ? 'free' : `$${(c / 100).toFixed(2)}`\n}\n\nfunction summaryLine(c: PlanChange): string {\n const n = c.affectedSubscribers\n const suffix = `${n} subscriber${n === 1 ? '' : 's'}`\n if (c.reason === 'removed') {\n return ` • ${c.slug} — removed (${suffix} still on it)`\n }\n // repriced: include the interval diffs for context.\n const diffs = (c.intervals ?? [])\n .map((i) => `${i.interval}: ${formatCents(i.oldCents)} → ${formatCents(i.newCents)}`)\n .join('; ')\n return ` • ${c.slug} — repriced (${diffs}; ${suffix} grandfathered on old price)`\n}\n\n/**\n * After /sync reports plans that stranded existing subscribers (removed\n * outright OR repriced with grandfathered customers), ask the developer\n * whether to cancel those subscriptions at the end of their current billing\n * period. Skipping is fine — they can run their own cleanup later via the\n * SDK's `cancelSubscription` helper.\n *\n * One yes/no prompt covers every affected plan. Granular per-plan control\n * is intentionally not surfaced; if a developer wants to cancel for plan A\n * but keep plan B, they can re-declare A in their next deploy.\n *\n * Errors here are warnings, never deploy failures: the deploy itself\n * succeeded; cleanup is the polite-but-optional tail.\n */\nasync function promptAndCancelChangedPlans(\n appName: string,\n token: string,\n changes: PlanChange[],\n): Promise<void> {\n const summary = changes.map(summaryLine).join('\\n')\n p.log.warn(\n `Plan change${changes.length === 1 ? '' : 's'} from this deploy left subscribers stranded:\\n${summary}\\n\\n` +\n 'Stripe will keep charging them until you cancel. Cancel at the end of their\\n' +\n 'current billing period? (Skip to leave them grandfathered.)',\n )\n const choice = await p.confirm({\n message: `Cancel ${changes.length === 1 ? 'these subscribers' : 'all of them'} at period end?`,\n initialValue: false,\n })\n if (p.isCancel(choice) || !choice) {\n p.log.info('Skipped — existing subscribers stay on their current plan/price.')\n return\n }\n\n // The admin-cancel endpoint batches at 50 and returns `hasMore` when there\n // are more rows to process. Loop until done so a plan with hundreds of\n // stranded subscribers gets fully cleaned up — without this, the deploy\n // prompt's confirmation (\"cancel these subscribers\") would silently leave\n // the tail being charged. The cap on iterations is a safety net for the\n // unlikely \"nothing makes progress\" path; a fresh deploy can resume.\n const MAX_ITERATIONS = 100 // 50/batch × 100 = 5000 subs/plan max per deploy\n for (const c of changes) {\n const s = createSpinner()\n s.start(`Canceling ${c.affectedSubscribers} subscriber${c.affectedSubscribers === 1 ? '' : 's'} on ${c.slug}...`)\n let totalCanceled = 0\n let totalFailed = 0\n let iteration = 0\n let lastError: string | null = null\n let stopped = false\n try {\n while (iteration < MAX_ITERATIONS) {\n const res = await fetch(`${API_URL}/api/subscriptions/admin-cancel`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n appName,\n planSlug: c.slug,\n atPeriodEnd: true,\n reason: `plan ${c.reason} via deploy`,\n }),\n })\n const body = (await res.json().catch(() => ({}))) as {\n success?: boolean\n canceled?: number\n failures?: Array<{ stripeSubscriptionId: string; error: string }>\n hasMore?: boolean\n error?: string\n }\n if (!res.ok || !body.success) {\n // Genuine failure (auth, 5xx, etc.) — surface and stop. The empty-\n // match case returns 200 with hasMore=false, not an error, so this\n // branch only fires for real problems.\n lastError = body.error ?? `HTTP ${res.status}`\n s.stop(`Cancel failed for ${c.slug}: ${lastError}`)\n stopped = true\n break\n }\n const batchCanceled = body.canceled ?? 0\n totalCanceled += batchCanceled\n totalFailed += body.failures?.length ?? 0\n if (!body.hasMore) break\n // Progress guard: if a batch returned hasMore=true but canceled=0\n // (every row failed), we'd loop forever. Stop and report.\n if (batchCanceled === 0) {\n lastError = 'no progress (all rows failed this batch)'\n break\n }\n iteration++\n }\n if (!stopped) {\n const tail =\n totalFailed > 0\n ? `; ${totalFailed} failed (see Stripe)`\n : ''\n const cap =\n iteration >= MAX_ITERATIONS\n ? ` (batch cap reached — re-run deploy to finish remaining)`\n : ''\n const errSuffix = lastError ? ` — ${lastError}` : ''\n s.stop(`Canceled ${totalCanceled} on ${c.slug}${tail}${cap}${errSuffix}`)\n }\n } catch (err: any) {\n s.stop(`Cancel failed for ${c.slug}: ${err.message}`)\n }\n }\n}\n\n/**\n * Bundle the app's `src/products.ts` with esbuild, dynamic-import the\n * resulting ESM, and POST the declarations to /api/charges/products/sync.\n * No-op when the file is absent. Mirrors syncSubscriptionPlans — products are\n * the one-time-charge equivalent of subscription plans, and the platform\n * resolves amount/name from this catalog at checkout time so the browser\n * can't pick (productId, amount) together.\n */\nasync function syncOneTimeProducts(appDir: string, appName: string, token: string): Promise<void> {\n const productsPath = join(appDir, 'src', 'products.ts')\n if (!existsSync(productsPath)) return\n\n const s = createSpinner()\n s.start('Syncing one-time products...')\n\n let products: unknown\n try {\n const esbuild = await import('esbuild')\n const outDir = join(appDir, '.wrangler', 'deploy')\n const outFile = join(outDir, 'products.bundle.mjs')\n await esbuild.build({\n entryPoints: [productsPath],\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'node18',\n outfile: outFile,\n logLevel: 'silent',\n write: true,\n })\n const mod = (await import(`${pathToFileURL(outFile).href}?t=${Date.now()}`)) as {\n oneTimeProducts?: unknown\n }\n products = mod.oneTimeProducts\n } catch (err: any) {\n s.stop('Product sync skipped')\n p.log.warn(`Could not load src/products.ts: ${err.message}`)\n return\n }\n\n if (!Array.isArray(products)) {\n s.stop('Product sync skipped')\n p.log.warn(\n 'src/products.ts must `export const oneTimeProducts = [...] as const`',\n )\n return\n }\n\n // See syncSubscriptionPlans for rationale — the deploy is already live by\n // the time we get here, so network/parse failures degrade to warnings.\n let res: Response\n try {\n res = await fetch(`${API_URL}/api/charges/products/sync`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ appName, products }),\n })\n } catch (err: any) {\n s.stop('Product sync skipped')\n p.log.warn(`Product sync request failed (network): ${err.message ?? err}`)\n return\n }\n const body = (await res.json().catch(() => ({}))) as {\n ok?: boolean\n count?: number\n error?: string\n details?: unknown\n }\n\n if (res.ok && body.ok) {\n const n = body.count ?? products.length\n s.stop(`Synced ${n} one-time product${n === 1 ? '' : 's'}`)\n return\n }\n\n s.stop('Product sync skipped')\n p.log.warn(\n `Product sync failed: ${body.error ?? `HTTP ${res.status}`}${\n body.details ? ` — ${JSON.stringify(body.details)}` : ''\n }`,\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).\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 '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 * 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 { createSpinner } from '../lib/spinner'\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 = createSpinner()\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'\nimport { DASHBOARD_URL } from '../env'\nimport { decodeJwtPayload } from '../jwt'\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 = decodeJwtPayload<JwtPayload>(jwt)\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 console.log(`Dashboard: ${DASHBOARD_URL}`)\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'\nimport { ensureInstallReady } from '../lib/install-status'\n\nfunction findScript(from: string): string | null {\n // Preferred: ships inside the deepspace npm package at\n // node_modules/deepspace/scripts/add-feature.cjs, so the script and its\n // sibling features/ dir are delivered by `npm install`.\n const inNodeModules = join(from, 'node_modules', 'deepspace', 'scripts', 'add-feature.cjs')\n if (existsSync(inNodeModules)) return inNodeModules\n // Fallback for apps scaffolded before features moved into the SDK; their\n // .deepspace/ folder still works with newer deepspace versions.\n const inDotDeepspace = join(from, '.deepspace', 'scripts', 'add-feature.cjs')\n if (existsSync(inDotDeepspace)) return inDotDeepspace\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 ensureInstallReady(appDir)\n const script = findScript(appDir)\n\n if (!script) {\n console.error('Could not find the deepspace feature installer.')\n console.error('Looked in:')\n console.error(` ${join(appDir, 'node_modules', 'deepspace', 'scripts', 'add-feature.cjs')}`)\n console.error(` ${join(appDir, '.deepspace', 'scripts', 'add-feature.cjs')}`)\n console.error('Are you in a DeepSpace app directory? Try `npm install` first.')\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 skills <subcommand>\n *\n * Wraps `npx skills@latest add deepdotspace/deepspace-skill` so installation\n * lives under our verb (mirrors `npx remotion skills add`). The upstream\n * `skills` CLI owns repo fetch, idempotency, and agent layouts.\n *\n * deepspace skills add # multi-agent install\n * deepspace skills add -g # install globally\n * deepspace skills add --agent codex # single agent\n * deepspace skills add -y # non-interactive\n *\n * Pre-install fixup for vercel-labs/skills#1138: upstream's project-local\n * install silently skips the Claude Code symlink when `.claude/` doesn't\n * already exist. Pre-creating `.claude/` lets the upstream CLI do the right\n * thing itself, so we don't have to know its layout.\n */\n\nimport { defineCommand } from 'citty'\nimport spawn from 'cross-spawn'\nimport { mkdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\n\nconst SKILL_REPO = 'deepdotspace/deepspace-skill'\nconst SKILL_NAME = 'deepspace'\n\n/**\n * Run `npx -y skills@latest add <repo> [extraArgs]`. Inherits stdio so the\n * `skills` CLI's own prompts / progress bars show through.\n */\nfunction runSkillsAdd(extraArgs: string[]): Promise<number> {\n return new Promise((resolve) => {\n const child = spawn(\n 'npx',\n ['-y', 'skills@latest', 'add', SKILL_REPO, ...extraArgs],\n { stdio: 'inherit' },\n )\n child.on('close', (code) => resolve(code ?? 1))\n child.on('error', (err) => {\n console.error(`Failed to invoke npx: ${err.message}`)\n console.error('Is Node.js installed and on PATH?')\n resolve(1)\n })\n })\n}\n\n/**\n * Workaround for https://github.com/vercel-labs/skills/issues/1138 — the\n * upstream installer's project-local branch silently returns success without\n * creating the Claude Code symlink when `<baseDir>/.claude/` doesn't exist.\n * Pre-creating an empty `.claude/` flips that check and lets the upstream CLI\n * create the symlink itself. Idempotent.\n *\n * @param baseDir cwd for project-local install, $HOME for `-g` global.\n */\nfunction precreateClaudeDir(baseDir: string): void {\n mkdirSync(join(baseDir, '.claude'), { recursive: true })\n}\n\nconst add = defineCommand({\n meta: {\n name: 'add',\n description: 'Install the DeepSpace skill for your coding agent',\n },\n args: {\n global: {\n type: 'boolean',\n alias: 'g',\n description: 'Install globally (~/.agents/skills/) instead of into the current directory',\n default: false,\n },\n yes: {\n type: 'boolean',\n alias: 'y',\n description: 'Skip prompts (assume yes for any confirmation)',\n default: false,\n },\n agent: {\n type: 'string',\n description: 'Target a single agent (e.g. claude-code, codex, opencode). Default: install for all detected agents.',\n required: false,\n },\n },\n async run({ args }) {\n const extra: string[] = []\n if (args.global) extra.push('-g')\n if (args.yes) extra.push('-y')\n if (args.agent) extra.push('--agent', args.agent)\n\n // Pre-create .claude/ so upstream's install picks up Claude Code.\n // Skip when --agent targets a non-claude agent — no point creating\n // an empty .claude/ the user doesn't want.\n if (!args.agent || args.agent === 'claude-code') {\n const baseDir = args.global ? homedir() : process.cwd()\n try {\n precreateClaudeDir(baseDir)\n } catch (err: any) {\n // Non-fatal: upstream will still install for other agents.\n console.warn(`\\n Note: could not pre-create .claude/ for Claude Code: ${err?.message ?? err}`)\n }\n }\n\n const code = await runSkillsAdd(extra)\n if (code !== 0) process.exit(code)\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'skills',\n description: 'Manage the DeepSpace agent skill (Claude Code, Codex, OpenCode, Cursor, ...)',\n },\n subCommands: {\n add,\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\n/**\n * Strip internal-only pricing fields from any value before emitting it to\n * stdout. The api-worker exposes both the user-facing `chargedCents` and the\n * platform's at-cost `costCents`; only the former should reach the CLI user.\n */\nfunction scrubInternal<T>(value: T): T {\n if (Array.isArray(value)) return value.map(scrubInternal) as unknown as T\n if (value && typeof value === 'object') {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (k === 'costCents') continue\n out[k] = scrubInternal(v)\n }\n return out as T\n }\n return value\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(scrubInternal(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 open: { type: 'boolean', description: 'Open browser at Stripe URL (use --no-open to print URL only)', default: true },\n wait: { type: 'boolean', description: 'Poll until provisioning completes (use --no-wait to exit after session creation)', default: true },\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(scrubInternal({ ...checkout, expectedTime, registrar: result.registrar }), null, 2) + '\\n')\n } else {\n console.log(`Stripe Checkout: ${checkout.url}`)\n }\n\n if (args.open && process.stdin.isTTY) {\n openBrowser(checkout.url)\n }\n\n if (!args.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(scrubInternal({ ...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(scrubInternal(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(scrubInternal(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","/**\n * deepspace managed-repos\n *\n * Manage DeepSpace-owned GitHub repos. These are private repositories in the\n * DeepSpace-managed GitHub org, intended for users who do not have or do not\n * want to connect their own GitHub account.\n */\n\nimport { defineCommand } from 'citty'\nimport { ensureToken } from '../auth'\nimport { ENVS } from '../env'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? ENVS.prod.api\nconst SIMPLE_APP_ID = /^[a-z0-9][a-z0-9_.:-]{0,119}$/i\nconst SIMPLE_APP_NAME = /^[a-z0-9][a-z0-9_-]{0,119}$/i\n\ntype ManagedRepo = {\n id: string\n appId: string\n appName: string\n fullName: string\n owner: string\n name: string\n htmlUrl: string\n cloneUrl: string\n}\n\ntype RepoQuota = {\n limit: number\n activeCount: number\n remaining: number\n}\n\ntype RepoToken = {\n token: string\n expiresAt: string\n permissions?: Record<string, string>\n repositorySelection?: string\n}\n\ntype DeletionQuota = {\n limit: number\n deletedCount: number\n remaining: number\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 defaultAppId(appName: string): string {\n return `cli-${slugId(appName)}`\n}\n\nfunction slugId(raw: string): string {\n return raw\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'app'\n}\n\nfunction assertSimple(value: string, pattern: RegExp, label: string): void {\n if (!pattern.test(value)) {\n throw new Error(`${label} must start with a letter or number and contain only simple identifier characters.`)\n }\n}\n\nfunction printQuota(quota: RepoQuota): void {\n console.log(`Repo quota: ${quota.activeCount} / ${quota.limit} active (${quota.remaining} remaining)`)\n}\n\nfunction printRepo(repo: ManagedRepo): void {\n console.log(`${repo.fullName}`)\n console.log(` ID: ${repo.id}`)\n console.log(` App: ${repo.appName}`)\n console.log(` App ID: ${repo.appId}`)\n console.log(` URL: ${repo.htmlUrl}`)\n console.log(` Clone: ${repo.cloneUrl}`)\n}\n\nasync function confirm(message: string): Promise<boolean> {\n if (!process.stdin.isTTY) {\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\nconst list = defineCommand({\n meta: {\n name: 'list',\n description: 'List your DeepSpace-managed repos and quota',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Emit JSON instead of human output',\n default: false,\n },\n },\n async run({ args }) {\n const token = await ensureToken()\n const result = await api<{ repos: ManagedRepo[]; quota: RepoQuota }>(token, '/api/github/repos')\n\n if (args.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n\n printQuota(result.quota)\n if (result.repos.length === 0) {\n console.log('No DeepSpace-managed repos. Create one with `deepspace managed-repos create <app-name>`.')\n return\n }\n\n console.log('')\n for (const repo of result.repos) {\n printRepo(repo)\n }\n },\n})\n\nconst create = defineCommand({\n meta: {\n name: 'create',\n description: 'Create a private DeepSpace-managed GitHub repo',\n },\n args: {\n appName: {\n type: 'positional',\n description: 'Working app name for this repo',\n required: true,\n },\n appId: {\n type: 'string',\n description: 'Stable DeepSpace repo app id (defaults to cli-<app-name>)',\n required: false,\n },\n nameHint: {\n type: 'string',\n description: 'Repo-name hint (defaults to app name)',\n required: false,\n },\n json: {\n type: 'boolean',\n description: 'Emit JSON instead of human output',\n default: false,\n },\n },\n async run({ args }) {\n const appName = String(args.appName)\n const appId = args.appId ? String(args.appId) : defaultAppId(appName)\n const nameHint = args.nameHint ? String(args.nameHint) : undefined\n\n try {\n assertSimple(appName, SIMPLE_APP_NAME, 'appName')\n assertSimple(appId, SIMPLE_APP_ID, 'appId')\n if (nameHint) assertSimple(nameHint, SIMPLE_APP_NAME, 'nameHint')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n\n const token = await ensureToken()\n const result = await api<{ repo: ManagedRepo; alreadyExists: boolean }>(token, '/api/github/repos', {\n method: 'POST',\n body: JSON.stringify({ appName, appId, ...(nameHint ? { nameHint } : {}) }),\n })\n\n if (args.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n\n console.log(result.alreadyExists ? 'Existing DeepSpace-managed repo:' : 'Created DeepSpace-managed repo:')\n printRepo(result.repo)\n },\n})\n\nconst token = defineCommand({\n meta: {\n name: 'token',\n description: 'Mint a short-lived GitHub token for a DeepSpace-managed repo',\n },\n args: {\n repoId: {\n type: 'positional',\n description: 'Repo id from `deepspace managed-repos list`',\n required: true,\n },\n json: {\n type: 'boolean',\n description: 'Emit JSON instead of human output',\n default: false,\n },\n },\n async run({ args }) {\n const jwt = await ensureToken()\n const result = await api<{ repo: ManagedRepo; token: RepoToken }>(\n jwt,\n `/api/github/repos/${encodeURIComponent(String(args.repoId))}/agent-token`,\n { method: 'POST' },\n )\n\n if (args.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n\n console.log(`Repo: ${result.repo.fullName}`)\n console.log(`Expires: ${result.token.expiresAt}`)\n console.log(`Token: ${result.token.token}`)\n console.log('')\n console.log(`Clone: git clone https://x-access-token:${encodeURIComponent(result.token.token)}@github.com/${result.repo.fullName}.git`)\n },\n})\n\nconst remove = defineCommand({\n meta: {\n name: 'delete',\n description: 'Delete a DeepSpace-managed GitHub repo',\n },\n args: {\n repoId: {\n type: 'positional',\n description: 'Repo id from `deepspace managed-repos list`',\n required: true,\n },\n yes: {\n type: 'boolean',\n description: 'Skip the confirmation prompt',\n default: false,\n },\n json: {\n type: 'boolean',\n description: 'Emit JSON instead of human output',\n default: false,\n },\n },\n async run({ args }) {\n if (!args.yes) {\n try {\n const ok = await confirm(\n 'Delete this DeepSpace-managed GitHub repo? This removes the GitHub repository and counts against your daily delete quota.',\n )\n if (!ok) {\n console.log('Cancelled.')\n return\n }\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n }\n\n const jwt = await ensureToken()\n const result = await api<{ repo: ManagedRepo; deletionQuota: DeletionQuota }>(\n jwt,\n `/api/github/repos/${encodeURIComponent(String(args.repoId))}`,\n { method: 'DELETE' },\n )\n\n if (args.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n\n console.log(`Deleted ${result.repo.fullName}`)\n console.log(\n `Delete quota: ${result.deletionQuota.deletedCount} / ${result.deletionQuota.limit} used today (${result.deletionQuota.remaining} remaining)`,\n )\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'managed-repos',\n description: 'Create and manage DeepSpace-owned GitHub repos',\n },\n subCommands: {\n list,\n create,\n token,\n delete: remove,\n },\n})\n","/**\n * deepspace library [publish|unpublish] [options]\n *\n * Manage entries in the DeepSpace community library (lives at\n * deepdotspace-site.app.space by default; override with --library-app\n * or DEEPSPACE_LIBRARY_HOST). Subcommands POST to that app's\n * `library.publish` / `library.unpublish` actions as the currently\n * logged-in user.\n *\n * The publish action verifies the caller owns the deployed app (by\n * checking the deploy worker's `/api/apps` registry) before writing\n * the row, so publishing another user's app is rejected server-side.\n *\n * Usage:\n * deepspace library publish (uses wrangler.toml)\n * deepspace library publish --app my-cool-app --name \"My Cool App\"\n * deepspace library publish --description \"...\" --category Productivity\n * deepspace library publish --tags utility,ai --visibility unlisted\n * deepspace library unpublish <handle>\n */\n\nimport { defineCommand } from 'citty'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport * as p from '@clack/prompts'\n\nimport { ensureToken } from '../auth'\nimport { resolveAppName } from '../../server/rooms/app-name'\n\nconst DEFAULT_LIBRARY_APP = 'deepdotspace-site'\n\nconst publish = defineCommand({\n meta: {\n name: 'publish',\n description: 'Publish the current app to the DeepSpace library',\n },\n args: {\n dir: {\n type: 'string',\n description: 'App directory (default: current directory)',\n required: false,\n },\n app: {\n type: 'string',\n description: 'App name (default: read from wrangler.toml)',\n required: false,\n },\n name: {\n type: 'string',\n description: 'Display name (default: app name)',\n required: false,\n },\n description: {\n type: 'string',\n description: 'Short description',\n required: false,\n },\n category: {\n type: 'string',\n description: 'Category (e.g. Productivity, Finance, AI). Default: General',\n required: false,\n },\n tags: {\n type: 'string',\n description: 'Comma-separated tags',\n required: false,\n },\n visibility: {\n type: 'string',\n description: \"'public' (default), 'unlisted', or 'private'\",\n required: false,\n },\n screenshot: {\n type: 'string',\n description: 'Override the auto-captured preview with a public PNG URL',\n required: false,\n },\n 'library-app': {\n type: 'string',\n description: `Target library app subdomain (default: ${DEFAULT_LIBRARY_APP})`,\n required: false,\n },\n json: {\n type: 'boolean',\n description: 'Print only the JSON response (machine-readable)',\n default: false,\n },\n },\n async run({ args }) {\n const json = !!args.json\n const intro = (s: string) => { if (!json) p.intro(s) }\n const info = (s: string) => { if (!json) p.log.info(s) }\n const die = (msg: string) => {\n if (json) console.error(JSON.stringify({ ok: false, error: msg }))\n else p.cancel(msg)\n process.exit(1)\n }\n\n intro('Publishing to the DeepSpace library')\n\n let appName = typeof args.app === 'string' && args.app.trim() ? args.app.trim() : undefined\n if (!appName) {\n const appDir = resolve(typeof args.dir === 'string' && args.dir ? args.dir : '.')\n const wranglerPath = join(appDir, 'wrangler.toml')\n if (!existsSync(wranglerPath)) {\n return die(\"No --app provided and no wrangler.toml found. Either pass --app <name> or run from your app's directory.\")\n }\n const cfg = parseToml(readFileSync(wranglerPath, 'utf-8')) as { name?: string }\n const nameRes = resolveAppName(cfg.name)\n if (!nameRes.ok) return die(`wrangler.toml: ${nameRes.reason}`)\n appName = nameRes.name\n }\n info(`App: ${appName}`)\n\n const visibility = (args.visibility ?? 'public') as string\n if (!['public', 'private', 'unlisted'].includes(visibility)) {\n return die(\"--visibility must be 'public', 'unlisted', or 'private'.\")\n }\n\n const tags = typeof args.tags === 'string' && args.tags\n ? args.tags.split(',').map((t) => t.trim()).filter(Boolean)\n : undefined\n\n const libraryApp = typeof args['library-app'] === 'string' && args['library-app']\n ? args['library-app']\n : DEFAULT_LIBRARY_APP\n const libraryHost = process.env.DEEPSPACE_LIBRARY_HOST ?? `https://${libraryApp}.app.space`\n\n let token: string\n try {\n token = await ensureToken()\n } catch (err) {\n return die(err instanceof Error ? err.message : String(err))\n }\n\n const payload: Record<string, unknown> = {\n appName,\n ...(args.name ? { name: args.name } : {}),\n ...(args.description ? { description: args.description } : {}),\n ...(args.category ? { category: args.category } : {}),\n ...(tags ? { tags } : {}),\n visibility,\n ...(args.screenshot ? { screenshotUrl: args.screenshot } : {}),\n }\n\n const url = `${libraryHost}/api/actions/library.publish`\n let res: Response\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(payload),\n })\n } catch (err) {\n return die(`Network error reaching ${url}: ${err instanceof Error ? err.message : String(err)}`)\n }\n\n const body = await res.text()\n let parsed: { success?: boolean; data?: { templateHandle?: string; url?: string; version?: number }; error?: string }\n try {\n parsed = JSON.parse(body)\n } catch {\n return die(`Server returned non-JSON (${res.status}): ${body.slice(0, 400)}`)\n }\n\n if (json) {\n console.log(JSON.stringify(parsed))\n process.exit(parsed.success ? 0 : 1)\n }\n\n if (!parsed.success) {\n return die(parsed.error ?? `Publish failed (HTTP ${res.status}).`)\n }\n\n p.log.success(`Published ${appName} as ${parsed.data?.templateHandle} (v${parsed.data?.version})`)\n if (parsed.data?.url) p.log.message(parsed.data.url)\n p.outro('Done')\n },\n})\n\nconst unpublish = defineCommand({\n meta: {\n name: 'unpublish',\n description: 'Remove a library entry (owner or admin only)',\n },\n args: {\n handle: {\n type: 'positional',\n description: 'templateHandle to remove (usually your app name)',\n required: true,\n },\n 'library-app': {\n type: 'string',\n description: `Target library app subdomain (default: ${DEFAULT_LIBRARY_APP})`,\n required: false,\n },\n json: {\n type: 'boolean',\n description: 'Print only the JSON response',\n default: false,\n },\n },\n async run({ args }) {\n const json = !!args.json\n const die = (msg: string) => {\n if (json) console.error(JSON.stringify({ ok: false, error: msg }))\n else p.cancel(msg)\n process.exit(1)\n }\n if (!json) p.intro('Unpublishing library entry')\n\n let token: string\n try { token = await ensureToken() } catch (err) {\n return die(err instanceof Error ? err.message : String(err))\n }\n\n const libraryApp = typeof args['library-app'] === 'string' && args['library-app']\n ? args['library-app']\n : DEFAULT_LIBRARY_APP\n const libraryHost = process.env.DEEPSPACE_LIBRARY_HOST ?? `https://${libraryApp}.app.space`\n\n const res = await fetch(`${libraryHost}/api/actions/library.unpublish`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },\n body: JSON.stringify({ templateHandle: String(args.handle) }),\n })\n const body = await res.text()\n let parsed: { success?: boolean; error?: string; data?: { templateHandle?: string } }\n try { parsed = JSON.parse(body) } catch {\n return die(`Server returned non-JSON (${res.status}): ${body.slice(0, 400)}`)\n }\n if (json) { console.log(JSON.stringify(parsed)); process.exit(parsed.success ? 0 : 1) }\n if (!parsed.success) return die(parsed.error ?? `HTTP ${res.status}`)\n p.log.success(`Unpublished ${parsed.data?.templateHandle}`)\n p.outro('Done')\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'library',\n description: 'Manage your DeepSpace library entries',\n },\n subCommands: {\n publish,\n unpublish,\n },\n})\n","/**\n * deepspace admin\n *\n * Maintainer-only operations gated by DEEPSPACE_ADMIN_SECRET.\n */\n\nimport { defineCommand } from 'citty'\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { ENVS } from '../env'\nimport { TOKEN_PATH } from '../auth'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? ENVS.prod.auth\n\nconst impersonate = defineCommand({\n meta: {\n name: 'impersonate',\n description: 'Store a short-lived CLI token for another user',\n },\n args: {\n email: {\n type: 'string',\n description: 'Target user email',\n required: false,\n },\n userId: {\n type: 'string',\n description: 'Target user id',\n required: false,\n },\n secret: {\n type: 'string',\n description: 'Admin secret; defaults to DEEPSPACE_ADMIN_SECRET',\n required: false,\n },\n },\n async run({ args }) {\n const secret = args.secret ?? process.env.DEEPSPACE_ADMIN_SECRET\n if (!secret) {\n console.error('Missing admin secret. Set DEEPSPACE_ADMIN_SECRET or pass --secret.')\n process.exit(1)\n }\n if (!args.email && !args.userId) {\n console.error('Pass --email or --userId.')\n process.exit(1)\n }\n\n const res = await fetch(`${AUTH_URL}/api/auth/admin/impersonate`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${secret}`,\n },\n body: JSON.stringify({\n email: args.email,\n userId: args.userId,\n }),\n })\n\n const data = (await res.json().catch(() => ({}))) as {\n token?: string\n user?: { id: string; name?: string | null; email?: string | null }\n error?: string\n }\n\n if (!res.ok || !data.token || !data.user) {\n console.error(`Failed: ${data.error ?? `HTTP ${res.status}`}`)\n process.exit(1)\n }\n\n const dir = join(homedir(), '.deepspace')\n mkdirSync(dir, { recursive: true })\n writeFileSync(TOKEN_PATH, data.token, { mode: 0o600 })\n\n console.log(`Impersonating ${data.user.name ?? data.user.email ?? data.user.id}`)\n console.log(`Email: ${data.user.email ?? '(none)'}`)\n console.log(`UserID: ${data.user.id}`)\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'admin',\n description: 'Maintainer-only admin commands',\n },\n subCommands: {\n impersonate,\n },\n})\n"],"mappings":";;;AAWA,SAAS,iBAAAA,iBAAe,eAAe;AACvC,SAAS,YAAAC,iBAAgB;AACzB,SAAS,gBAAAC,gBAAc,cAAAC,oBAAkB;AACzC,SAAS,WAAAC,UAAS,QAAAC,cAAY;AAC9B,SAAS,qBAAqB;;;ACL9B,SAAS,qBAAqB;AAC9B,SAAS,iBAAAC,gBAAe,iBAAiB;AACzC,SAAS,QAAAC,aAAY;AACrB,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,gBAAgB;AACzB,SAA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AA,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","p","join","writeFileSync","resolve","defineCommand","existsSync","readFileSync","join","homedir","AUTH_URL","join","homedir","defineCommand","existsSync","readFileSync","defineCommand","existsSync","join","resolve","readFileSync","writeFileSync","existsSync","mkdirSync","join","homedir","token","AUTH_URL","DIR","join","homedir","SESSION_PATH","TOKEN_PATH","existsSync","readFileSync","token","mkdirSync","writeFileSync","existsSync","readFileSync","join","existsSync","status","defineCommand","resolve","existsSync","join","token","defineCommand","DEFAULT_PORT","resolvePort","defineCommand","existsSync","join","resolve","spawnSync","spawnSync","DEFAULT_PORT","defineCommand","resolve","resolvePort","existsSync","join","token","spawnSync","defineCommand","spawnSync","resolve","defineCommand","resolve","spawnSync","defineCommand","p","readFileSync","writeFileSync","existsSync","mkdirSync","join","homedir","SESSION_COOKIE","AUTH_URL","DIR","join","homedir","existsSync","readFileSync","mkdirSync","writeFileSync","token","SESSION_PATH","defineCommand","defineCommand","execSync","readFileSync","existsSync","parseToml","join","resolve","p","status","token","defineCommand","resolve","join","existsSync","parseToml","readFileSync","execSync","wait","defineCommand","readFileSync","existsSync","join","parseToml","p","DEPLOY_URL","defineCommand","join","existsSync","parseToml","readFileSync","token","defineCommand","defineCommand","defineCommand","existsSync","resolve","join","execSync","join","existsSync","defineCommand","resolve","execSync","defineCommand","spawn","mkdirSync","join","homedir","resolve","spawn","mkdirSync","join","defineCommand","homedir","defineCommand","execSync","existsSync","readFileSync","join","resolve","parseToml","API_URL","token","confirm","resolve","defineCommand","openBrowser","list","execSync","defineCommand","list","defineCommand","readFileSync","API_URL","readFileSync","info","list","defineCommand","defineCommand","defineCommand","defineCommand","API_URL","api","token","confirm","resolve","list","defineCommand","create","defineCommand","existsSync","readFileSync","join","resolve","parseToml","p","defineCommand","intro","info","resolve","join","existsSync","parseToml","readFileSync","token","defineCommand","mkdirSync","writeFileSync","homedir","join","AUTH_URL","defineCommand","join","homedir","mkdirSync","writeFileSync","TOKEN_PATH","dirname","readFileSync","join","existsSync","create","defineCommand","execSync"]}