@rebasepro/cli 0.9.1-canary.e2fc7b6 → 0.9.1-canary.e3f810f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","names":[],"sources":["../src/utils/package-manager.ts","../src/utils/project.ts","../src/commands/cloud/context.ts","../src/commands/init.ts","../src/commands/generate_sdk.ts","../src/commands/schema.ts","../src/commands/db.ts","../src/commands/dev.ts","../src/commands/build.ts","../src/commands/start.ts","../src/commands/auth.ts","../src/commands/doctor.ts","../src/commands/skills.ts","../src/commands/api-keys.ts","../src/commands/cloud/auth.ts","../src/commands/cloud/link.ts","../src/commands/cloud/projects.ts","../src/commands/cloud/deploy.ts","../src/commands/cloud/orgs.ts","../src/commands/cloud/databases.ts","../src/commands/cloud/env.ts","../src/commands/cloud/domains.ts","../src/commands/cloud/extensions.ts","../src/commands/cloud/settings.ts","../src/commands/cloud/deployments.ts","../src/commands/cloud/power.ts","../src/commands/cloud/resources.ts","../src/commands/cloud/index.ts","../src/cli.ts"],"sourcesContent":["/**\n * Package manager detection and command abstraction.\n *\n * Detects whether the user is running pnpm or npm and provides\n * a unified interface for common package-manager operations so\n * the rest of the CLI never has to hardcode a specific PM.\n */\nimport fs from \"fs\";\nimport path from \"path\";\n\nexport type PackageManager = \"pnpm\" | \"npm\";\n\nexport interface PMCommands {\n /** The binary name (\"pnpm\" | \"npm\"). */\n name: PackageManager;\n /** Install all dependencies — e.g. `pnpm install` / `npm install`. */\n install: string[];\n /** Run a script — e.g. `pnpm run dev` / `npm run dev`. */\n run: (script: string) => string[];\n /** Execute a local bin — e.g. `pnpm exec rebase ...` / `npx rebase ...`. */\n exec: (bin: string, args: string[]) => string[];\n /** Query the registry — e.g. `pnpm view <pkg> version` / `npm view <pkg> version`. */\n view: (pkg: string, field: string) => string[];\n /** Run all workspace scripts — e.g. `pnpm -r run build` / `npm run build --workspaces`. */\n runAll: (script: string) => string[];\n /** Run a script in a specific workspace — e.g. `pnpm --filter \"*-backend\" start` / `npm run start -w backend`. */\n runWorkspace: (workspace: string, script: string) => string[];\n /** Execute a one-off package — e.g. `pnpm dlx skills ...` / `npx -y skills ...`. */\n dlx: (pkg: string, args: string[]) => string[];\n /** The workspace dependency protocol: `\"workspace:*\"` for pnpm, `\"*\"` for npm. */\n workspaceProtocol: string;\n}\n\n/**\n * Detect the package manager from the environment or the target directory.\n *\n * Detection order:\n * 1. Explicit override (if provided)\n * 2. `npm_config_user_agent` env var (set by npm/pnpm when running via `npx`/`pnpm dlx`)\n * 3. Lock-file presence in the target directory\n * 4. Default to pnpm (Rebase's recommended PM)\n */\nexport function detectPackageManager(targetDir?: string): PackageManager {\n // 1. Check user agent (set when invoked via npx / pnpm dlx)\n const userAgent = process.env.npm_config_user_agent ?? \"\";\n if (userAgent.startsWith(\"npm/\")) return \"npm\";\n if (userAgent.startsWith(\"pnpm/\")) return \"pnpm\";\n\n // 2. Check for lock files in the target directory\n if (targetDir) {\n if (fs.existsSync(path.join(targetDir, \"package-lock.json\"))) return \"npm\";\n if (fs.existsSync(path.join(targetDir, \"pnpm-lock.yaml\"))) return \"pnpm\";\n }\n\n // 3. Check for lock files in cwd\n const cwd = process.cwd();\n if (cwd !== targetDir) {\n if (fs.existsSync(path.join(cwd, \"package-lock.json\"))) return \"npm\";\n if (fs.existsSync(path.join(cwd, \"pnpm-lock.yaml\"))) return \"pnpm\";\n }\n\n // 4. Default to pnpm\n return \"pnpm\";\n}\n\n/** Build the command helpers for a given package manager. */\nexport function getPMCommands(pm: PackageManager): PMCommands {\n if (pm === \"npm\") {\n return {\n name: \"npm\",\n install: [\"npm\", \"install\"],\n run: (script) => [\"npm\", \"run\", script],\n exec: (bin, args) => [\"npx\", bin, ...args],\n view: (pkg, field) => [\"npm\", \"view\", pkg, field],\n runAll: (script) => [\"npm\", \"run\", script, \"--workspaces\", \"--if-present\"],\n runWorkspace: (workspace, script) => [\"npm\", \"run\", script, \"-w\", workspace],\n dlx: (pkg, args) => [\"npx\", \"-y\", pkg, ...args],\n workspaceProtocol: \"*\"\n };\n }\n\n return {\n name: \"pnpm\",\n install: [\"pnpm\", \"install\"],\n run: (script) => [\"pnpm\", \"run\", script],\n exec: (bin, args) => [\"pnpm\", \"exec\", bin, ...args],\n view: (pkg, field) => [\"pnpm\", \"view\", pkg, field],\n runAll: (script) => [\"pnpm\", \"-r\", \"run\", script],\n runWorkspace: (workspace, script) => [\"pnpm\", \"--filter\", workspace, script],\n dlx: (pkg, args) => [\"pnpm\", \"dlx\", pkg, ...args],\n workspaceProtocol: \"workspace:*\"\n };\n}\n","/**\n * Project discovery utilities for the Rebase CLI.\n *\n * These helpers locate the project root, backend directory, .env file,\n * and local binaries — used by all CLI command modules.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { execSync } from \"child_process\";\nimport chalk from \"chalk\";\n\n/**\n * Walk up from `startDir` to find the Rebase project root.\n *\n * The root is identified by a `package.json` that either:\n * - has `workspaces` containing \"backend\" or \"frontend\", OR\n * - has a sibling `backend/` directory\n */\nexport function findProjectRoot(startDir: string = process.cwd()): string | null {\n let dir = path.resolve(startDir);\n const root = path.parse(dir).root;\n\n while (dir !== root) {\n const pkgPath = path.join(dir, \"package.json\");\n\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n // Check for workspace-based project (monorepo root)\n if (pkg.workspaces && Array.isArray(pkg.workspaces)) {\n const hasBackend = pkg.workspaces.some((w: string) =>\n w === \"backend\"\n );\n if (hasBackend) return dir;\n }\n } catch {\n // ignore parse errors\n }\n\n // Check for sibling backend directory\n if (fs.existsSync(path.join(dir, \"backend\")) && fs.existsSync(path.join(dir, \"config\"))) {\n return dir;\n }\n }\n\n dir = path.dirname(dir);\n }\n\n return null;\n}\n\n/**\n * Locate the backend directory within the project root.\n */\nexport function findBackendDir(projectRoot: string): string | null {\n const backendDir = path.join(projectRoot, \"backend\");\n return fs.existsSync(backendDir) ? backendDir : null;\n}\n\n/**\n * Detect the active backend plugin (e.g. @rebasepro/server-postgres) from the backend's package.json.\n */\nexport function getActiveBackendPlugin(backendDir: string): string | null {\n const pkgPath = path.join(backendDir, \"package.json\");\n if (!fs.existsSync(pkgPath)) return null;\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n const deps = { ...pkg.dependencies,\n...pkg.devDependencies };\n\n // Collect all @rebasepro/server-* driver plugins (exclude server itself)\n const candidates = Object.keys(deps).filter(\n dep => dep.startsWith(\"@rebasepro/server-\") && dep !== \"@rebasepro/server\"\n );\n\n if (candidates.length === 0) return null;\n\n // Prefer server-postgres — it's the primary supported driver\n if (candidates.includes(\"@rebasepro/server-postgres\")) {\n return \"@rebasepro/server-postgres\";\n }\n\n // Fallback: return the first candidate that actually has a CLI entry point\n for (const candidate of candidates) {\n if (resolvePluginCliScript(backendDir, candidate)) {\n return candidate;\n }\n }\n\n // Last resort: return whatever we found\n return candidates[0];\n } catch {\n // Ignore parse errors\n }\n return null;\n}\n\n/**\n * Resolve the active plugin's CLI script.\n */\nexport function resolvePluginCliScript(backendDir: string, pluginName: string): string | null {\n const candidates: string[] = [];\n\n // Walk up from the backend dir: pnpm links the plugin into\n // backend/node_modules, while npm workspaces hoist it to the project (or an\n // enclosing monorepo) root.\n let dir = path.resolve(backendDir);\n const fsRoot = path.parse(dir).root;\n while (dir !== fsRoot) {\n candidates.push(\n path.join(dir, \"node_modules\", pluginName, \"src\", \"cli.ts\"),\n path.join(dir, \"node_modules\", pluginName, \"dist\", \"cli.js\")\n );\n dir = path.dirname(dir);\n }\n\n candidates.push(\n // For monorepo dev mode:\n path.resolve(backendDir, \"..\", \"..\", \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\"),\n path.resolve(backendDir, \"..\", \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\"),\n path.resolve(backendDir, \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\")\n );\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Locate the frontend directory within the project root.\n */\nexport function findFrontendDir(projectRoot: string): string | null {\n const frontendDir = path.join(projectRoot, \"frontend\");\n return fs.existsSync(frontendDir) ? frontendDir : null;\n}\n\n/**\n * Find the .env file. Checks the project root first, then backend.\n */\nexport function findEnvFile(projectRoot: string): string | null {\n const candidates = [\n path.join(projectRoot, \".env\"),\n path.join(projectRoot, \"backend\", \".env\")\n ];\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n\n return null;\n}\n\n/**\n * Resolve a binary from the project's node_modules/.bin.\n * Checks backend, root, parent monorepo root, then falls back to PATH.\n */\nexport function resolveLocalBin(projectRoot: string, binName: string): string | null {\n const candidates = [\n path.join(projectRoot, \"backend\", \"node_modules\", \".bin\", binName),\n path.join(projectRoot, \"node_modules\", \".bin\", binName)\n ];\n\n // Also check parent directories (for monorepo setups where app/ is nested)\n let parent = path.dirname(projectRoot);\n const rootDir = path.parse(parent).root;\n while (parent !== rootDir) {\n candidates.push(path.join(parent, \"node_modules\", \".bin\", binName));\n parent = path.dirname(parent);\n }\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n\n // Fall back to globally installed binary via which\n try {\n const globalPath = execSync(`which ${binName}`, { encoding: \"utf-8\" }).trim();\n if (globalPath && fs.existsSync(globalPath)) return globalPath;\n } catch {\n // not found globally\n }\n\n return null;\n}\n\n/**\n * Resolve the tsx binary. Checks backend node_modules first, then root.\n */\nexport function resolveTsx(projectRoot: string): string | null {\n return resolveLocalBin(projectRoot, \"tsx\");\n}\n\n/**\n * Validate that a resolved tsx binary actually has an intact installation.\n *\n * `resolveLocalBin` only checks whether `node_modules/.bin/tsx` (a symlink)\n * exists. If the pnpm content-addressable store was cleaned or a previous\n * install was interrupted, the symlink can exist while critical files inside\n * the tsx package (e.g. `dist/preflight.cjs`) are missing — causing a\n * confusing MODULE_NOT_FOUND error at runtime.\n *\n * This function follows the symlink, walks up to find the tsx package root\n * (`package.json` with `name: \"tsx\"`), and verifies that `dist/preflight.cjs`\n * is present. Returns `null` when the installation looks healthy, or an\n * error description string when it appears corrupted.\n */\nexport function validateTsxInstallation(tsxBinPath: string): string | null {\n try {\n // Follow the symlink chain to the real tsx entry script\n const realPath = fs.realpathSync(tsxBinPath);\n\n // Walk up from the real binary to locate the tsx package root\n let dir = path.dirname(realPath);\n const fsRoot = path.parse(dir).root;\n for (let depth = 0; depth < 10 && dir !== fsRoot; depth++) {\n const pkgPath = path.join(dir, \"package.json\");\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n if (pkg.name === \"tsx\") {\n // Found the tsx package root — verify critical preload file\n const preflightPath = path.join(dir, \"dist\", \"preflight.cjs\");\n if (!fs.existsSync(preflightPath)) {\n return `tsx package at ${dir} is missing dist/preflight.cjs`;\n }\n return null; // Installation looks healthy\n }\n } catch {\n // Malformed package.json — keep walking\n }\n }\n dir = path.dirname(dir);\n }\n\n // Could not determine tsx root — don't block, assume valid\n return null;\n } catch (err) {\n // realpathSync throws if the symlink target is completely gone\n return `tsx binary symlink is broken: ${err instanceof Error ? err.message : String(err)}`;\n }\n}\n\n/**\n * Require the project root or exit with a helpful error.\n */\nexport function requireProjectRoot(): string {\n const root = findProjectRoot();\n if (!root) {\n console.error(chalk.red(\"✗ Could not find a Rebase project root.\"));\n console.error(chalk.gray(\" Make sure you are inside a Rebase project directory\"));\n console.error(chalk.gray(\" (one with backend/, frontend/, and config/ directories).\"));\n process.exit(1);\n }\n return root;\n}\n\n/**\n * Require the backend directory or exit with a helpful error.\n */\nexport function requireBackendDir(projectRoot: string): string {\n const backendDir = findBackendDir(projectRoot);\n if (!backendDir) {\n console.error(chalk.red(\"✗ Could not find a backend/ directory.\"));\n console.error(chalk.gray(` Expected at: ${path.join(projectRoot, \"backend\")}`));\n process.exit(1);\n }\n return backendDir;\n}\n","/**\n * Shared foundation for the `rebase cloud` command family.\n *\n * Everything cloud subcommands need in common lives here:\n * - credential storage (~/.rebase/credentials.json, keyed per control-plane host)\n * - project link file (.rebase/cloud.json in the project dir)\n * - control-plane URL resolution\n * - an authenticated `@rebasepro/client` instance (createCloudClient / requireClient)\n * - small output helpers shared across subcommands\n *\n * The control plane is itself a Rebase app, so we reuse the same SDK the web\n * console uses (`@rebasepro/client`). Auth, token refresh, the data REST client\n * and function invocation all come from the SDK — the CLI only supplies a\n * file-backed AuthStorage so a login persists across invocations.\n */\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\nimport { spawn } from \"child_process\";\nimport chalk from \"chalk\";\nimport arg from \"arg\";\nimport inquirer from \"inquirer\";\nimport { createRebaseClient, type AuthStorage } from \"@rebasepro/client\";\nimport { findProjectRoot } from \"../../utils/project\";\n\n/* ═══════════════════════════════════════════════════════════════\n Constants & paths\n ═══════════════════════════════════════════════════════════════ */\n\n/** Default hosted control plane (the Rebase Cloud console origin). */\nexport const DEFAULT_CLOUD_URL = \"https://app.rebase.pro\";\n\n/** The storage key the SDK's auth module reads/writes the session under. */\nconst SDK_SESSION_KEY = \"rebase_auth\";\n\n/** ~/.rebase/credentials.json — one file, many hosts. */\nfunction credentialsPath(): string {\n return path.join(os.homedir(), \".rebase\", \"credentials.json\");\n}\n\n/** Project-local link file: <project>/.rebase/cloud.json */\nexport function projectLinkPath(cwd: string = process.cwd()): string {\n const root = findProjectRoot(cwd) || cwd;\n return path.join(root, \".rebase\", \"cloud.json\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Credentials file model\n ═══════════════════════════════════════════════════════════════\n\n {\n \"current\": \"https://app.rebase.pro\",\n \"contexts\": {\n \"https://app.rebase.pro\": { \"auth\": \"<sdk session json>\", \"org\": \"42\" }\n }\n }\n*/\n\ninterface CloudContextEntry {\n /** Raw JSON blob the SDK auth module persists (the RebaseSession). */\n auth?: string;\n /** Active organization id for this host, if the user selected one. */\n org?: string;\n}\n\ninterface CredentialsFile {\n current?: string;\n contexts: Record<string, CloudContextEntry>;\n}\n\nfunction readCredentials(): CredentialsFile {\n try {\n const raw = fs.readFileSync(credentialsPath(), \"utf-8\");\n const parsed = JSON.parse(raw) as CredentialsFile;\n if (!parsed.contexts) parsed.contexts = {};\n return parsed;\n } catch {\n return { contexts: {} };\n }\n}\n\nfunction writeCredentials(data: CredentialsFile): void {\n const file = credentialsPath();\n fs.mkdirSync(path.dirname(file), { recursive: true });\n // Written with private perms — this file holds refresh tokens.\n fs.writeFileSync(file, JSON.stringify(data, null, 2), { mode: 0o600 });\n try {\n fs.chmodSync(file, 0o600);\n } catch {\n // best effort on platforms without chmod semantics\n }\n}\n\n/** Host that a bare `rebase cloud` command should target, if any. */\nexport function currentContextUrl(): string | undefined {\n return readCredentials().current;\n}\n\n/** Persist the active organization id for a host. */\nexport function setContextOrg(url: string, org: string | undefined): void {\n const creds = readCredentials();\n const entry = creds.contexts[url] || {};\n if (org) entry.org = org;\n else delete entry.org;\n creds.contexts[url] = entry;\n writeCredentials(creds);\n}\n\nexport function getContextOrg(url: string): string | undefined {\n return readCredentials().contexts[url]?.org;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n File-backed AuthStorage (per host)\n ═══════════════════════════════════════════════════════════════ */\n\nfunction createFileAuthStorage(url: string): AuthStorage {\n return {\n getItem(key) {\n if (key !== SDK_SESSION_KEY) return null;\n return readCredentials().contexts[url]?.auth ?? null;\n },\n setItem(key, value) {\n if (key !== SDK_SESSION_KEY) return;\n const creds = readCredentials();\n const entry = creds.contexts[url] || {};\n entry.auth = value;\n creds.contexts[url] = entry;\n if (!creds.current) creds.current = url;\n writeCredentials(creds);\n },\n removeItem(key) {\n if (key !== SDK_SESSION_KEY) return;\n const creds = readCredentials();\n if (creds.contexts[url]) {\n delete creds.contexts[url].auth;\n delete creds.contexts[url].org;\n }\n writeCredentials(creds);\n }\n };\n}\n\n/** Mark a host as the active context (called on login). */\nexport function setCurrentContext(url: string): void {\n const creds = readCredentials();\n creds.current = url;\n if (!creds.contexts[url]) creds.contexts[url] = {};\n writeCredentials(creds);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n URL resolution\n ═══════════════════════════════════════════════════════════════\n\n Priority: --url flag > REBASE_CLOUD_URL env > linked project's url\n > stored current context > default hosted URL.\n*/\n\nexport function resolveCloudUrl(rawArgs: string[]): string {\n const parsed = arg({ \"--url\": String }, { argv: rawArgs.slice(2),\npermissive: true });\n const explicit = parsed[\"--url\"] || process.env.REBASE_CLOUD_URL;\n if (explicit) return normalizeUrl(explicit);\n\n const link = readLink();\n if (link?.url) return normalizeUrl(link.url);\n\n const current = currentContextUrl();\n if (current) return normalizeUrl(current);\n\n return DEFAULT_CLOUD_URL;\n}\n\nfunction normalizeUrl(url: string): string {\n let u = url.trim().replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//.test(u)) u = `https://${u}`;\n return u;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Rebase client factory + auth guard\n ═══════════════════════════════════════════════════════════════ */\n\nexport type CloudClient = ReturnType<typeof createRebaseClient>;\n\n/**\n * Build an SDK client bound to a control-plane host, backed by the on-disk\n * credential store. `autoRefresh` is disabled so we never leave a dangling\n * setTimeout that keeps the CLI process alive; token refresh is done on demand\n * by `requireClient`.\n */\nexport function createCloudClient(url: string): CloudClient {\n return createRebaseClient({\n baseUrl: url,\n // Empty string disables the realtime socket — a short-lived CLI has no\n // use for it, and leaving it on opens a connection (and noisy errors)\n // on every invocation.\n websocketUrl: \"\",\n auth: {\n storage: createFileAuthStorage(url),\n persistSession: true,\n autoRefresh: false\n }\n });\n}\n\n/** Two minutes of head-room before a token is treated as expired. */\nconst EXPIRY_BUFFER_MS = 120_000;\n\n/**\n * Return an authenticated client for the resolved host, refreshing the access\n * token if it is close to expiry. Exits with a helpful message when there is no\n * usable session (never logged in, or the refresh token was revoked).\n */\nexport async function requireClient(rawArgs: string[]): Promise<{ client: CloudClient; url: string }> {\n const url = resolveCloudUrl(rawArgs);\n const client = createCloudClient(url);\n const session = client.auth.getSession();\n\n if (!session || !session.accessToken) {\n fail(\n `Not logged in to ${chalk.cyan(url)}.`,\n `Run ${chalk.bold(\"rebase cloud login\")} first.`\n );\n }\n\n if (session.expiresAt <= Date.now() + EXPIRY_BUFFER_MS) {\n try {\n await client.auth.refreshSession();\n } catch {\n fail(\n `Your session for ${chalk.cyan(url)} has expired.`,\n `Run ${chalk.bold(\"rebase cloud login\")} to sign in again.`\n );\n }\n }\n\n return { client,\nurl };\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Tenant hostnames\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * The base domain tenant projects are served at, as reported by the control\n * plane (`platform-config`, which derives it from the same TENANT_BASE_DOMAIN\n * the ingress and the console read — see saas/backend/src/utils/tenant-domain.ts).\n *\n * The CLI cannot know this value: it is per-deployment configuration (production\n * serves tenants at `apps.rebase.pro`, a dev control plane at `localhost`). It\n * used to be hardcoded to `rebase.pro`, so `cloud projects create` congratulated\n * the user with a URL that resolves nowhere near their app.\n *\n * Cached per host for the process: it is fixed for a control plane's lifetime,\n * and `projects list` formats one host per row off a single fetch.\n *\n * @returns the base domain, or `undefined` if the control plane doesn't serve\n * `platform-config` (an older deployment) or the request failed. A failure is\n * cached too — the caller renders a subdomain either way, and a short-lived\n * CLI should not retry once per row.\n */\nconst tenantBaseDomainCache = new Map<string, Promise<string | undefined>>();\n\nexport function fetchTenantBaseDomain(client: CloudClient, url: string): Promise<string | undefined> {\n let pending = tenantBaseDomainCache.get(url);\n if (!pending) {\n pending = client.functions\n .invoke<{ tenantBaseDomain?: string }>(\"platform-config\", undefined, { method: \"GET\" })\n .then((cfg) => cfg?.tenantBaseDomain?.trim() || undefined)\n .catch(() => undefined);\n tenantBaseDomainCache.set(url, pending);\n }\n return pending;\n}\n\n/**\n * Public host for a project — `<subdomain>.<base>`, or the bare subdomain when\n * the base domain is unknown.\n *\n * It deliberately never falls back to a guessed domain. The user copies this\n * string into a browser, so a plausible-but-wrong hostname is worse than an\n * obviously incomplete one: `acme.rebase.pro` looks reachable and isn't, while\n * `acme` reads as \"the subdomain is acme\" and prompts no wasted debugging.\n */\nexport function formatTenantHost(\n subdomain: string | undefined,\n baseDomain: string | undefined\n): string | undefined {\n if (!subdomain) return undefined;\n return baseDomain ? `${subdomain}.${baseDomain}` : subdomain;\n}\n\n/** The fields of a project row this module needs to render a host. */\nexport interface HostableProject {\n subdomain?: string;\n /** Resolved server-side; absent on control planes older than the host hook. */\n host?: string;\n}\n\n/**\n * The host to display for a project.\n *\n * Prefers `host` off the record: the control plane resolves it through the same\n * `tenantHost()` the ingress uses, so it accounts for the project's *cluster*\n * base domain. The CLI cannot compute that itself — `clusters` is admin-only\n * under RLS, so a normal user's token cannot read `baseDomain`, and a project on\n * a second cluster is served somewhere the platform default does not name.\n *\n * `baseDomain` (from `platform-config`) remains the fallback for a control plane\n * that predates the hook — right for the single-cluster case, which is every\n * project today.\n */\nexport function projectHost(\n project: HostableProject,\n baseDomain: string | undefined\n): string | undefined {\n return project.host || formatTenantHost(project.subdomain, baseDomain);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Project link file (.rebase/cloud.json)\n ═══════════════════════════════════════════════════════════════ */\n\nexport interface ProjectLink {\n url: string;\n projectId: string;\n /** The project's subdomain — the slug users see in console URLs and type into --project. */\n slug?: string;\n projectName?: string;\n orgId?: string;\n}\n\nexport function readLink(cwd: string = process.cwd()): ProjectLink | null {\n try {\n return JSON.parse(fs.readFileSync(projectLinkPath(cwd), \"utf-8\")) as ProjectLink;\n } catch {\n return null;\n }\n}\n\nexport function writeLink(link: ProjectLink, cwd: string = process.cwd()): void {\n const file = projectLinkPath(cwd);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(file, JSON.stringify(link, null, 2));\n}\n\nexport function removeLink(cwd: string = process.cwd()): boolean {\n const file = projectLinkPath(cwd);\n if (fs.existsSync(file)) {\n fs.rmSync(file);\n return true;\n }\n return false;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * The raw project reference to operate on: explicit `--project` flag wins,\n * otherwise the linked project. Exits with guidance when neither is present.\n * The value is a slug (the project's subdomain, as shown in console URLs) or,\n * for old scripts and link files, a raw project UUID.\n */\nexport function requireProjectRef(rawArgs: string[]): string {\n const parsed = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(2),\npermissive: true });\n if (parsed[\"--project\"]) return parsed[\"--project\"];\n const link = readLink();\n if (link?.projectId) return link.projectId;\n fail(\n \"No project specified and this directory is not linked.\",\n `Pass ${chalk.bold(\"--project <slug>\")} or run ${chalk.bold(\"rebase cloud link\")}.`\n );\n}\n\n/**\n * Resolve a project reference — slug or UUID — to the internal id the API\n * takes, or undefined when no such project is visible. Slugs cost one lookup;\n * UUIDs pass through untouched so linked directories and old scripts skip the\n * round-trip.\n */\nexport async function lookupProjectId(ref: string, client: CloudClient): Promise<string | undefined> {\n if (UUID_RE.test(ref)) return ref;\n const res = await client.data.collection(\"projects\").find({\n where: { subdomain: [\"==\", ref] },\n limit: 1\n });\n const row = res.data[0] as { id?: string | number } | undefined;\n return row?.id === undefined ? undefined : String(row.id);\n}\n\n/** Like `lookupProjectId`, but exits with guidance when the ref matches nothing. */\nexport async function resolveProjectRef(ref: string, client: CloudClient): Promise<string> {\n const id = await lookupProjectId(ref, client);\n if (id === undefined) {\n fail(\n `No project with slug ${chalk.bold(ref)}.`,\n `List yours with ${chalk.bold(\"rebase cloud projects\")}.`\n );\n }\n return id;\n}\n\n/** `requireProjectRef` + `resolveProjectRef` in one step. */\nexport async function requireProject(rawArgs: string[], client: CloudClient): Promise<string> {\n return resolveProjectRef(requireProjectRef(rawArgs), client);\n}\n\n/**\n * The project reference to SHOW: the slug the user typed or the linked slug.\n * Never resolves — for human output only. Old link files predate `slug` and\n * fall back to the stored id.\n */\nexport function displayProjectRef(rawArgs: string[]): string {\n const parsed = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(2),\npermissive: true });\n if (parsed[\"--project\"]) return parsed[\"--project\"];\n const link = readLink();\n return link?.slug || link?.projectId || \"\";\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Machine-readable output mode\n ═══════════════════════════════════════════════════════════════\n\n Rebase is built for agents, and the CLI is their primary interface. An agent\n must never scrape a colorized table, so every cloud command can emit a single\n JSON value instead of human output.\n\n JSON mode is on when ANY of these hold:\n • `--json` was passed,\n • `REBASE_JSON=1` is set, or\n • stdout is not a TTY (piped/redirected — i.e. a program is reading it).\n\n In JSON mode a command prints exactly one JSON value to stdout and nothing\n else; errors print `{\"error\":{...}}` and exit non-zero. The mode is a\n process-global set once, at dispatch, by `initOutputMode` — every helper here\n (fail, reportError, emit) reads it so the whole family is consistent.\n*/\n\nlet JSON_MODE = false;\n\n/**\n * Resolve and latch the output mode for this invocation. Call once at the top of\n * `cloudCommand`, before anything can print or `fail`. Returns the resolved mode\n * (handy for tests, which otherwise leave it at its `false` default).\n */\nexport function initOutputMode(rawArgs: string[]): boolean {\n const parsed = arg({ \"--json\": Boolean }, { argv: rawArgs.slice(2), permissive: true });\n JSON_MODE =\n Boolean(parsed[\"--json\"]) ||\n process.env.REBASE_JSON === \"1\" ||\n process.stdout.isTTY !== true;\n return JSON_MODE;\n}\n\n/** Whether the current invocation is emitting machine-readable JSON. */\nexport function isJsonMode(): boolean {\n return JSON_MODE;\n}\n\n/** Force the mode (tests only — production latches it via `initOutputMode`). */\nexport function setJsonModeForTest(value: boolean): void {\n JSON_MODE = value;\n}\n\n/** Strip ANSI colour codes — JSON output must never carry terminal escapes. */\n// eslint-disable-next-line no-control-regex\nconst ANSI_RE = /\u001b\\[[0-9;]*m/g;\nfunction stripAnsi(s: string): string {\n return s.replace(ANSI_RE, \"\");\n}\n\n/** Write one JSON value to stdout, followed by a newline. */\nexport function printJson(value: unknown): void {\n process.stdout.write(JSON.stringify(value) + \"\\n\");\n}\n\n/**\n * The one output primitive every new command uses: in JSON mode emit `json`\n * (and nothing else); otherwise run `human`. Keeping the two behind a single\n * call is what guarantees a command can never print a table AND a JSON blob.\n */\nexport function emit(human: () => void, json: unknown): void {\n if (JSON_MODE) printJson(json);\n else human();\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Output helpers\n ═══════════════════════════════════════════════════════════════ */\n\n/** Print an error (+ optional hint) and exit non-zero. Never returns. */\nexport function fail(message: string, hint?: string, code?: string): never {\n if (JSON_MODE) {\n printJson({ error: { message: stripAnsi(message), code: code ?? null, hint: hint ? stripAnsi(hint) : undefined } });\n process.exit(1);\n }\n console.error(\"\");\n console.error(chalk.red(` ✗ ${message}`));\n if (hint) console.error(chalk.gray(` ${hint}`));\n console.error(\"\");\n process.exit(1);\n}\n\n/**\n * Confirm a destructive/irreversible action, respecting non-interactive use.\n *\n * With `--yes`/`-y` it proceeds silently. In JSON mode or a non-TTY it REFUSES\n * to prompt — a prompt that can hang is a known repo landmine — and fails,\n * telling the caller to pass `--yes`. Only an interactive terminal gets a real\n * confirm prompt; declining there aborts cleanly (exit 0).\n */\nexport async function confirmDestructive(opts: { yes: boolean; prompt: string }): Promise<void> {\n if (opts.yes) return;\n if (JSON_MODE || process.stdin.isTTY !== true) {\n fail(\n \"This action is destructive and needs confirmation.\",\n `Re-run with ${chalk.bold(\"--yes\")} to proceed.`,\n \"confirmation_required\"\n );\n }\n const { confirmed } = (await inquirer.prompt([\n { type: \"confirm\", name: \"confirmed\", default: false, message: opts.prompt }\n ] as unknown as Parameters<typeof inquirer.prompt>[0])) as { confirmed: boolean };\n if (!confirmed) {\n console.log(chalk.gray(\" Aborted.\"));\n process.exit(0);\n }\n}\n\n/**\n * Positional tokens after `rebase cloud` — `[group, action, arg1, …]`.\n *\n * Deliberately NOT `arg({}, { permissive: true })._`: in permissive mode `arg`\n * pushes UNKNOWN FLAGS onto `_` too, so `rollback --yes --json` would report\n * `--yes` as the deployment id. Operand extraction must see operands only, so\n * anything starting with `-` is dropped — the same filter the db backup handler\n * has always used.\n */\nexport function cloudPositionals(rawArgs: string[]): string[] {\n return rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"));\n}\n\nexport function success(message: string): void {\n console.log(\"\");\n console.log(chalk.bold.green(` ✓ ${message}`));\n console.log(\"\");\n}\n\n/** Colorize a deployment / resource status token. */\nexport function colorStatus(status: string | undefined): string {\n switch (status) {\n case \"active\":\n case \"success\":\n case \"connected\":\n return chalk.green(status);\n case \"deploying\":\n case \"provisioning\":\n case \"pending_billing\":\n case \"untested\":\n return chalk.yellow(status ?? \"\");\n case \"failed\":\n return chalk.red(status);\n case \"stopped\":\n return chalk.gray(status);\n default:\n return chalk.gray(status ?? \"unknown\");\n }\n}\n\n/**\n * Render a two-column key/value block with aligned keys. Empty rows are skipped\n * — including `null`, which the API sends for an unset column and which used to\n * print the literal string \"null\" (e.g. `Custom domain: null`).\n */\nexport function keyValues(rows: Array<[string, string | null | undefined]>): void {\n const width = Math.max(...rows.map(([k]) => k.length));\n for (const [k, v] of rows) {\n if (v === undefined || v === null || v === \"\") continue;\n console.log(` ${chalk.gray(`${k}:`.padEnd(width + 1))} ${v}`);\n }\n}\n\n/**\n * Surface an SDK/HTTP error consistently. The SDK throws RebaseApiError with\n * a `.status` and `.message`; anything else falls back to its string form.\n */\nexport function reportError(e: unknown, context: string): never {\n const err = e as { status?: number; message?: string; code?: string };\n if (JSON_MODE) {\n printJson({\n error: {\n message: err?.message ? stripAnsi(err.message) : String(e),\n code: err?.code ?? null,\n status: err?.status ?? null,\n context\n }\n });\n process.exit(1);\n }\n const status = err?.status ? ` (${err.status})` : \"\";\n fail(`${context}${status}: ${err?.message ?? String(e)}`);\n}\n\n/**\n * Open a URL in the user's default browser (best effort). Always prints the URL\n * first so it stays usable over SSH or when no browser is available.\n */\nexport function openUrl(target: string, label = \"Opening\"): void {\n console.log(\"\");\n console.log(` ${label} ${chalk.cyan(target)}`);\n console.log(\"\");\n const opener =\n process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"start\" : \"xdg-open\";\n try {\n const child = spawn(opener, [target], {\n stdio: \"ignore\",\n detached: true,\n shell: process.platform === \"win32\"\n });\n child.on(\"error\", () => {\n /* URL already printed for manual copy */\n });\n child.unref();\n } catch {\n /* URL already printed */\n }\n}\n","import arg from \"arg\";\nimport inquirer from \"inquirer\";\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport net from \"net\";\nimport { promisify } from \"util\";\nimport { execa } from \"execa\";\nimport { cp } from \"fs/promises\";\nimport { fileURLToPath } from \"url\";\nimport crypto from \"crypto\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\nimport { resolveCloudUrl, writeLink } from \"./cloud/context\";\nimport type { PackageManager, PMCommands } from \"../utils/package-manager\";\n\nconst access = promisify(fs.access);\n\n\n// Resolve template path relative to this file\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nfunction findParentDir(currentDir: string, targetName: string): string | null {\n const root = path.parse(currentDir).root;\n while (currentDir && currentDir !== root) {\n if (path.basename(currentDir) === targetName) {\n return currentDir;\n }\n currentDir = path.dirname(currentDir);\n }\n return null;\n}\n\nconst cliRoot = findParentDir(__dirname, \"cli\");\n\nconst PROJECT_NAME_RE = /^[a-z0-9][a-z0-9._-]*$/;\n\n/** Returns an error message, or null when the name is a valid package name. */\nexport function validateProjectName(name: string): string | null {\n if (!name.trim()) return \"Project name is required\";\n if (!PROJECT_NAME_RE.test(name)) {\n return \"Project name must start with a lowercase letter or number and contain only lowercase letters, numbers, hyphens, dots, or underscores\";\n }\n return null;\n}\n\nexport type TemplatePreset = \"blog\" | \"ecommerce\" | \"blank\";\n\n/**\n * How much of Rebase to scaffold.\n *\n * `cms` is the full triad (config + backend + frontend). `baas` is the backend\n * alone, serving the database over REST with no collection files and no UI.\n */\n/**\n * `cms` scaffolds BaaS + the admin UI; `baas` scaffolds the API alone. The\n * values match `RebaseBackendConfig.mode`, which is what the generated backend\n * sets — the labels below are what users actually read.\n */\nexport type TemplateFlavor = \"cms\" | \"baas\";\n\nconst FLAVOR_CHOICES: Array<{ name: string; value: TemplateFlavor; short: string }> = [\n { name: \"BaaS + admin — API plus an admin UI, driven by collections you define (like Payload/Directus)\",\nvalue: \"cms\",\nshort: \"BaaS + admin\" },\n { name: \"BaaS only — headless API over your database. No collections, no UI (like Supabase)\",\nvalue: \"baas\",\nshort: \"BaaS only\" }\n];\n\nconst PRESET_CHOICES: Array<{ name: string; value: TemplatePreset; short: string }> = [\n { name: \"Blog — Posts, Authors, Tags (with markdown editor)\",\nvalue: \"blog\",\nshort: \"Blog\" },\n { name: \"E-commerce — Products, Categories, Orders\",\nvalue: \"ecommerce\",\nshort: \"E-commerce\" },\n { name: \"Blank — Empty project, just authentication\",\nvalue: \"blank\",\nshort: \"Blank\" }\n];\n\nexport interface InitOptions {\n projectName: string;\n git: boolean;\n installDeps: boolean;\n targetDirectory: string;\n templateDirectory: string;\n databaseUrl?: string;\n introspect?: boolean;\n /** Starter template preset. */\n preset: TemplatePreset;\n /** Which parts of Rebase to scaffold. */\n flavor: TemplateFlavor;\n /** Detected package manager (pnpm or npm). */\n pm: PackageManager;\n /** Command helpers for the detected PM. */\n pmCommands: PMCommands;\n /** Cloud project slug (its subdomain) to link the scaffold to. */\n cloudProject?: string;\n /** One-time setup key that authenticates the cloud link. */\n setupKey?: string;\n /** Control-plane URL the setup key is redeemed against. */\n cloudUrl?: string;\n}\n\nexport interface BuildQuestionsParams {\n nameArg?: string;\n templateArg?: TemplatePreset;\n flavorArg?: TemplateFlavor;\n hasGitFlag: boolean;\n hasInstallFlag: boolean;\n pm: PackageManager;\n}\n\n/**\n * Builds the interactive prompt questions for `rebase init`.\n * Exported for testability — all prompt `type` values must match\n * types registered by the installed version of inquirer.\n */\nexport function buildInitQuestions(params: BuildQuestionsParams): Record<string, unknown>[] {\n const { nameArg, templateArg, flavorArg, hasGitFlag, hasInstallFlag, pm } = params;\n const questions: Record<string, unknown>[] = [];\n\n if (!nameArg) {\n questions.push({\n type: \"input\",\n name: \"projectName\",\n message: \"Project name:\",\n default: \"my-rebase-app\",\n validate: (input: string) => validateProjectName(input) ?? true\n });\n }\n\n if (!flavorArg) {\n questions.push({\n type: \"select\",\n name: \"flavor\",\n message: \"What do you want to build?\",\n choices: FLAVOR_CHOICES,\n default: \"cms\"\n });\n }\n\n if (!templateArg) {\n questions.push({\n type: \"select\",\n name: \"preset\",\n message: \"Choose a starter template:\",\n choices: PRESET_CHOICES,\n default: \"blog\",\n // BaaS has no collection files, so a collections preset is moot.\n when: (answers: Record<string, unknown>) => (flavorArg ?? answers.flavor) !== \"baas\"\n });\n }\n\n if (!hasGitFlag) {\n questions.push({\n type: \"confirm\",\n name: \"git\",\n message: \"Initialize a git repository?\",\n default: true\n });\n }\n\n if (!hasInstallFlag) {\n questions.push({\n type: \"confirm\",\n name: \"installDeps\",\n message: `Install dependencies with ${pm}?`,\n default: true\n });\n }\n\n questions.push({\n type: \"input\",\n name: \"databaseUrl\",\n message: \"Enter your PostgreSQL database connection string (leave blank to use a local default):\",\n default: \"\",\n validate: (input: string) => {\n if (input.trim() && /[\\r\\n]/.test(input)) {\n return \"Database URL cannot contain newline characters.\";\n }\n return true;\n }\n });\n\n questions.push({\n type: \"confirm\",\n name: \"introspect\",\n message: \"Would you like to introspect this database to automatically generate collections?\",\n default: true,\n when: (answers: Record<string, unknown>) => !!(answers.databaseUrl as string)?.trim()\n });\n\n return questions;\n}\n\nexport async function createRebaseApp(rawArgs: string[]) {\n console.log(`\n${chalk.bold(\"Rebase\")} — Create a new project 🚀\n`);\n\n const pm = detectPackageManager();\n const options = await promptForOptions(rawArgs, pm);\n await createProject(options);\n}\n\nasync function promptForOptions(rawArgs: string[], pm: PackageManager): Promise<InitOptions> {\n const args = arg(\n {\n \"--git\": Boolean,\n \"--install\": Boolean,\n \"--database-url\": String,\n \"--introspect\": Boolean,\n \"--template\": String,\n \"--flavor\": String,\n \"--project\": String,\n \"--setup-key\": String,\n \"--yes\": Boolean,\n \"-g\": \"--git\",\n \"-i\": \"--install\",\n \"-t\": \"--template\",\n \"-f\": \"--flavor\",\n \"-y\": \"--yes\"\n },\n {\n argv: rawArgs.slice(3), // skip \"node\", \"rebase\", \"init\"\n permissive: true\n }\n );\n\n // The first positional arg after \"init\" is the project name\n const nameArg = args._[0];\n const isNonInteractive = args[\"--yes\"] || false;\n\n // The interactive prompt validates typed names; a name passed as an\n // argument must pass the same check or it becomes an invalid package.json\n // \"name\" that only fails later, at install time. Validate the basename so\n // nested paths (\"apps/my-app\") and \".\" still work.\n if (nameArg) {\n const resolvedName = path.basename(path.resolve(process.cwd(), nameArg));\n const nameError = validateProjectName(resolvedName);\n if (nameError) {\n console.error(chalk.red(`Invalid project name \"${resolvedName}\": ${nameError}`));\n process.exit(1);\n }\n }\n\n const templateArg = args[\"--template\"] as TemplatePreset | undefined;\n if (templateArg && !PRESET_CHOICES.some(p => p.value === templateArg)) {\n console.error(chalk.red(`Unknown template \"${templateArg}\". Available: ${PRESET_CHOICES.map(p => p.value).join(\", \")}`));\n process.exit(1);\n }\n\n const flavorArg = args[\"--flavor\"] as TemplateFlavor | undefined;\n if (flavorArg && !FLAVOR_CHOICES.some(f => f.value === flavorArg)) {\n console.error(chalk.red(`Unknown flavor \"${flavorArg}\". Available: ${FLAVOR_CHOICES.map(f => f.value).join(\", \")}`));\n process.exit(1);\n }\n\n if (isNonInteractive) {\n const projectName = nameArg || \"my-rebase-app\";\n const targetDirectory = path.resolve(process.cwd(), projectName);\n const templateDirectory = path.resolve(cliRoot!, \"templates\", \"template\");\n const pmCommands = getPMCommands(pm);\n\n return {\n projectName: path.basename(targetDirectory),\n git: args[\"--git\"] ?? false,\n installDeps: args[\"--install\"] ?? false,\n targetDirectory,\n templateDirectory,\n databaseUrl: args[\"--database-url\"] || undefined,\n introspect: args[\"--introspect\"] || false,\n preset: templateArg || \"blog\",\n flavor: flavorArg || \"cms\",\n pm,\n pmCommands,\n cloudProject: args[\"--project\"] || undefined,\n setupKey: args[\"--setup-key\"] || undefined,\n cloudUrl: resolveCloudUrl(rawArgs)\n };\n }\n\n const questions = buildInitQuestions({\n nameArg,\n templateArg,\n flavorArg,\n hasGitFlag: !!args[\"--git\"],\n hasInstallFlag: !!args[\"--install\"],\n pm\n });\n\n\n const answers = await inquirer.prompt(questions as unknown as Parameters<typeof inquirer.prompt>[0]);\n\n const targetDirectory = path.resolve(process.cwd(), nameArg || answers.projectName);\n const projectName = path.basename(targetDirectory);\n const templateDirectory = path.resolve(cliRoot!, \"templates\", \"template\");\n const pmCommands = getPMCommands(pm);\n\n return {\n projectName,\n git: args[\"--git\"] || answers.git || false,\n installDeps: args[\"--install\"] || answers.installDeps || false,\n targetDirectory,\n templateDirectory,\n databaseUrl: (answers.databaseUrl as string)?.trim() || undefined,\n introspect: answers.introspect || false,\n preset: templateArg || (answers.preset as TemplatePreset) || \"blog\",\n flavor: flavorArg || (answers.flavor as TemplateFlavor) || \"cms\",\n pm,\n pmCommands,\n cloudProject: args[\"--project\"] || undefined,\n setupKey: args[\"--setup-key\"] || undefined,\n cloudUrl: resolveCloudUrl(rawArgs)\n };\n}\n\n/**\n * Redeem the one-time setup key from the console's setup page and write the\n * `.rebase/cloud.json` link into the scaffold, so `rebase cloud deploy` etc.\n * work in the new directory with no further flags. `--project` carries the\n * project's slug (its subdomain, as shown in console URLs); the control plane\n * also accepts a raw id for old copies of the command.\n *\n * Best-effort by design: a failed link must never fail the scaffold, so every\n * exit path other than success is a warning plus instructions to link later.\n */\nasync function linkScaffoldToCloud(options: InitOptions): Promise<void> {\n if (!options.cloudProject && !options.setupKey) return;\n\n const linkLater = `Link it later with ${chalk.bold(\"rebase cloud login\")} then ${chalk.bold(\"rebase cloud link\")}.`;\n if (!options.cloudProject || !options.setupKey) {\n console.warn(chalk.yellow(\" --project and --setup-key go together; skipping the cloud link.\"));\n console.warn(chalk.yellow(` ${linkLater}`));\n return;\n }\n\n try {\n const res = await fetch(`${options.cloudUrl}/api/functions/setup-key/validate`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ projectId: options.cloudProject,\nsetupKey: options.setupKey })\n });\n const body = (await res.json().catch(() => ({}))) as {\n error?: { message?: string };\n project?: { id?: string | number; subdomain?: string; name?: string };\n };\n if (!res.ok || body.project?.id === undefined) {\n console.warn(chalk.yellow(` Could not verify the setup key: ${body.error?.message || res.statusText}`));\n console.warn(chalk.yellow(` ${linkLater}`));\n return;\n }\n writeLink(\n {\n url: String(options.cloudUrl),\n projectId: String(body.project.id),\n slug: body.project.subdomain,\n projectName: body.project.name\n },\n options.targetDirectory\n );\n console.log(\"\");\n console.log(` ${chalk.green(\"✓\")} Linked to cloud project ${chalk.bold(body.project.subdomain ?? options.cloudProject)}`);\n } catch (e) {\n console.warn(chalk.yellow(` Could not reach the control plane: ${e instanceof Error ? e.message : String(e)}`));\n console.warn(chalk.yellow(` ${linkLater}`));\n }\n}\n\nasync function createProject(options: InitOptions) {\n // Check if directory already exists and is not empty\n if (fs.existsSync(options.targetDirectory)) {\n if (fs.readdirSync(options.targetDirectory).length !== 0) {\n console.error(`${chalk.red.bold(\"ERROR\")} Directory \"${options.projectName}\" already exists and is not empty`);\n process.exit(1);\n }\n } else {\n fs.mkdirSync(options.targetDirectory, { recursive: true });\n }\n\n // Verify template exists\n try {\n await access(options.templateDirectory, fs.constants.R_OK);\n } catch {\n console.error(`${chalk.red.bold(\"ERROR\")} Template not found at ${options.templateDirectory}`);\n process.exit(1);\n }\n\n // Copy template files\n console.log(chalk.gray(\" Copying project files...\"));\n try {\n await cp(options.templateDirectory, options.targetDirectory, {\n recursive: true,\n filter: (source: string) => {\n const basename = path.basename(source);\n // Skip node_modules and .DS_Store\n return basename !== \"node_modules\" && basename !== \".DS_Store\";\n }\n });\n } catch (err: unknown) {\n console.error(`${chalk.red.bold(\"ERROR\")} Failed to copy template files: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n\n // npm/pnpm always strip files named .gitignore and .npmrc from published\n // tarballs, so the template ships them un-dotted and we restore the real\n // names here.\n for (const [from, to] of [[\"gitignore\", \".gitignore\"], [\"npmrc\", \".npmrc\"]] as const) {\n const shipped = path.join(options.targetDirectory, from);\n if (fs.existsSync(shipped)) {\n fs.renameSync(shipped, path.join(options.targetDirectory, to));\n }\n }\n\n // Apply the selected template preset (swap collection files)\n if (options.flavor !== \"baas\") {\n // When introspecting, the database is the source of truth: start from\n // the blank preset so example collections never register on top of\n // tables the database doesn't have.\n if (options.introspect && options.preset !== \"blank\") {\n console.log(chalk.gray(\" Using the blank template: collections will come from your database.\"));\n }\n await applyPreset(options.targetDirectory, options.introspect ? \"blank\" : options.preset);\n }\n\n // Reduce the project to the selected flavor\n await applyFlavor(options.targetDirectory, options.flavor);\n\n // Replace placeholder project name in package.json files\n await replacePlaceholders(options);\n\n // Rename .env.example to .env if it exists and randomize secrets\n await configureEnvFile(options.targetDirectory, options.databaseUrl);\n\n // Initialize git\n if (options.git) {\n console.log(chalk.gray(\" Initializing git repository...\"));\n try {\n await execa(\"git\", [\"init\"], { cwd: options.targetDirectory });\n } catch {\n console.warn(chalk.yellow(\" Warning: Failed to initialize git repository\"));\n }\n }\n\n const { pm, pmCommands } = options;\n const installCmd = pmCommands.install;\n const execCmd = pmCommands.exec(\"rebase\", [\"schema\", \"introspect\", \"--force\"]);\n const generateCmd = pmCommands.exec(\"rebase\", [\"schema\", \"generate\", \"--collections\", \"../config/collections\"]);\n\n if (options.installDeps) {\n console.log(\"\");\n console.log(chalk.gray(` Installing dependencies with ${pm}...`));\n console.log(\"\");\n try {\n await execa(installCmd[0], installCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n } catch {\n console.warn(chalk.yellow(` Warning: Failed to install dependencies. You may need to run \\`${installCmd.join(\" \")}\\` manually.`));\n }\n }\n\n if (options.introspect) {\n console.log(\"\");\n if (options.installDeps) {\n console.log(chalk.gray(\" Introspecting database and generating collections...\"));\n console.log(\"\");\n try {\n // --force overwrites template example collections with real ones\n await execa(execCmd[0], execCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n // The template ships a schema.generated.ts for the example blog\n // collections; regenerate it from the introspected collections or\n // the backend serves a schema that doesn't match the database.\n await execa(generateCmd[0], generateCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n console.log(chalk.green(\" Database successfully introspected!\"));\n } catch {\n console.warn(chalk.yellow(\" Warning: Failed to introspect database automatically.\"));\n console.warn(chalk.yellow(` You can run \\`${execCmd.join(\" \")}\\` then \\`${generateCmd.join(\" \")}\\` manually after setup.`));\n }\n } else {\n console.warn(chalk.yellow(\" Skipping introspection because dependencies were not installed.\"));\n console.warn(chalk.yellow(` Run \\`${installCmd.join(\" \")}\\` then \\`${execCmd.join(\" \")}\\` manually.`));\n }\n }\n\n await linkScaffoldToCloud(options);\n\n // Success message\n console.log(\"\");\n console.log(`${chalk.green.bold(\"✓\")} Project ${chalk.bold(options.projectName)} created successfully!`);\n console.log(\"\");\n console.log(chalk.bold(\"Next steps:\"));\n console.log(\"\");\n const runDev = pmCommands.run(\"dev\");\n const runDbPush = pmCommands.run(\"db:push\");\n const isBaas = options.flavor === \"baas\";\n console.log(` ${chalk.cyan(\"cd\")} ${options.projectName}`);\n if (!options.installDeps) {\n console.log(` ${chalk.cyan(installCmd.join(\" \"))}`);\n }\n console.log(\"\");\n\n if (options.databaseUrl) {\n if (options.introspect) {\n console.log(chalk.gray(\" # Database has been introspected & collections generated!\"));\n console.log(chalk.gray(\" # Start the development server (frontend + backend):\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n } else {\n console.log(chalk.gray(\" # Your custom database is configured in .env.\"));\n console.log(chalk.gray(\" # If the database is empty, push the Rebase schema to initialize it:\"));\n console.log(` ${chalk.cyan(runDbPush.join(\" \"))}`);\n console.log(\"\");\n console.log(chalk.gray(\" # Then start the development server:\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n }\n } else if (isBaas) {\n console.log(chalk.gray(\" # A local database configuration has been generated in .env.\"));\n console.log(chalk.gray(\" # 1. Start the PostgreSQL database container:\"));\n console.log(` ${chalk.cyan(\"docker compose up -d db\")}`);\n console.log(\"\");\n console.log(chalk.gray(\" # 2. Create your tables (migrations, SQL, any tool you like).\"));\n console.log(chalk.gray(\" # A table is served once it has an authorization model, i.e.\"));\n console.log(chalk.gray(\" # row-level security enabled plus at least one policy:\"));\n console.log(` ${chalk.cyan(\"ALTER TABLE your_table ENABLE ROW LEVEL SECURITY;\")}`);\n console.log(chalk.gray(\" # The API logs any table it skips, and why.\"));\n console.log(\"\");\n console.log(chalk.gray(\" # 3. Start the API — every protected table is served automatically:\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n } else {\n console.log(chalk.gray(\" # A local database configuration has been generated in .env.\"));\n console.log(chalk.gray(\" # 1. Start the PostgreSQL database container:\"));\n console.log(` ${chalk.cyan(\"docker compose up -d db\")}`);\n console.log(\"\");\n console.log(chalk.gray(\" # 2. Push the Rebase schema to initialize database tables:\"));\n console.log(` ${chalk.cyan(runDbPush.join(\" \"))}`);\n console.log(\"\");\n console.log(chalk.gray(\" # 3. Start the development server (frontend + backend):\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n }\n\n console.log(\"\");\n console.log(isBaas\n ? chalk.gray(\"This starts a headless API (Hono + PostgreSQL). There are no collection files: \")\n + chalk.gray(\"the API is derived from your database schema. Once it serves a table, docs are at /api/swagger.\")\n : chalk.gray(\"This starts both the backend (Hono + PostgreSQL)\")\n + chalk.gray(\" and the frontend (Vite + React) concurrently.\"));\n console.log(\"\");\n console.log(chalk.gray(\"Docs: https://rebase.pro/docs\"));\n console.log(chalk.gray(\"GitHub: https://github.com/rebasepro/rebase\"));\n console.log(\"\");\n console.log(chalk.bold(\"🤖 AI Agent Skills\"));\n console.log(\"\");\n console.log(chalk.gray(\" Install Rebase agent skills for your AI coding assistant:\"));\n console.log(\"\");\n console.log(` ${chalk.cyan(\"rebase skills install\")} ${chalk.gray(\"or\")} ${chalk.cyan(pmCommands.run(\"skills:install\").join(\" \"))}`);\n console.log(\"\");\n}\n\n/**\n * Apply a template preset by replacing the default collection files.\n *\n * The template ships with blog collections at the top level and\n * preset alternatives under `config/collections/presets/<name>/`.\n * This function swaps the active collection files and removes the\n * presets directory so the final project is clean.\n */\n/**\n * Reduce the scaffolded project to the chosen flavor.\n *\n * The base template is the full CMS triad. `baas` drops the frontend and the\n * collections config entirely — there is nothing to define, since the server\n * derives its API from the database — and overlays the files that differ.\n */\nasync function applyFlavor(targetDirectory: string, flavor: TemplateFlavor): Promise<void> {\n if (flavor !== \"baas\") return;\n\n for (const dir of [\"frontend\", \"config\"]) {\n fs.rmSync(path.join(targetDirectory, dir), { recursive: true, force: true });\n }\n // Generated from collection files in cms mode; baas reads the live schema.\n fs.rmSync(path.join(targetDirectory, \"backend\", \"src\", \"schema.generated.ts\"), { force: true });\n\n const overlayDir = path.resolve(cliRoot!, \"templates\", \"overlays\", \"baas\");\n if (!fs.existsSync(overlayDir)) {\n console.error(`${chalk.red.bold(\"ERROR\")} BaaS template overlay not found at ${overlayDir}`);\n process.exit(1);\n }\n\n await cp(overlayDir, targetDirectory, {\n recursive: true,\n force: true,\n filter: (source: string) => {\n const basename = path.basename(source);\n return basename !== \"node_modules\" && basename !== \".DS_Store\";\n }\n });\n}\n\nasync function applyPreset(targetDirectory: string, preset: TemplatePreset): Promise<void> {\n const collectionsDir = path.join(targetDirectory, \"config\", \"collections\");\n const presetsDir = path.join(collectionsDir, \"presets\");\n\n if (preset !== \"blog\") {\n const presetDir = path.join(presetsDir, preset);\n if (!fs.existsSync(presetDir)) {\n console.warn(chalk.yellow(` Warning: Preset \"${preset}\" not found, falling back to blog template.`));\n cleanupPresets(presetsDir);\n return;\n }\n\n // Remove the default blog collection files (keep users.ts — it's shared)\n const blogFiles = [\"posts.ts\", \"authors.ts\", \"tags.ts\", \"index.ts\"];\n for (const file of blogFiles) {\n const filePath = path.join(collectionsDir, file);\n if (fs.existsSync(filePath)) {\n fs.unlinkSync(filePath);\n }\n }\n\n // Copy preset files into the collections directory\n const presetFiles = fs.readdirSync(presetDir).filter(f => f.endsWith(\".ts\"));\n for (const file of presetFiles) {\n fs.copyFileSync(\n path.join(presetDir, file),\n path.join(collectionsDir, file)\n );\n }\n }\n\n // Always clean up the presets directory — it shouldn't ship with the final project\n cleanupPresets(presetsDir);\n}\n\nfunction cleanupPresets(presetsDir: string): void {\n if (fs.existsSync(presetsDir)) {\n fs.rmSync(presetsDir, { recursive: true,\nforce: true });\n }\n}\n\nasync function replacePlaceholders(options: InitOptions) {\n const filesToProcess = [\n \"package.json\",\n \"frontend/package.json\",\n \"backend/package.json\",\n \"config/package.json\",\n \"frontend/index.html\",\n \"pnpm-workspace.yaml\",\n \"README.md\"\n ];\n\n const packageJsonPath = path.resolve(cliRoot!, \"package.json\");\n let cliVersion = \"latest\";\n if (fs.existsSync(packageJsonPath)) {\n const pkg = JSON.parse(fs.readFileSync(packageJsonPath, \"utf-8\"));\n cliVersion = pkg.version || \"latest\";\n }\n\n const versionCache = new Map<string, string>();\n /** Packages with no release matching the CLI's own version. */\n const unreleased = new Map<string, string>();\n\n // Use npm view for registry queries — it's universal and works regardless of PM\n const viewBin = \"npm\";\n\n const getPackageVersion = async (pkgName: string) => {\n if (versionCache.has(pkgName)) return versionCache.get(pkgName)!;\n if (process.env.REBASE_E2E === \"true\") {\n versionCache.set(pkgName, cliVersion);\n return cliVersion;\n }\n let versionToUse = cliVersion;\n try {\n // First try to check if the specific cliVersion exists for this package\n const { stdout } = await execa(viewBin, [\"view\", `${pkgName}@${cliVersion}`, \"version\"]);\n if (!stdout.trim()) throw new Error(\"Not found\");\n versionToUse = stdout.trim();\n } catch {\n try {\n // If specific version doesn't exist, try the matching tag (canary or latest)\n const tag = cliVersion.includes(\"canary\") ? \"canary\" : \"latest\";\n const { stdout } = await execa(viewBin, [\"view\", `${pkgName}@${tag}`, \"version\"]);\n if (!stdout.trim()) throw new Error(\"Not found\");\n versionToUse = stdout.trim();\n } catch {\n try {\n // Fallback to absolute latest\n const { stdout } = await execa(viewBin, [\"view\", pkgName, \"version\"]);\n versionToUse = stdout.trim() || \"latest\";\n } catch {\n versionToUse = \"latest\";\n }\n }\n\n // The fallbacks above answer \"what can I install?\", not \"what matches\n // this CLI?\". When a package has no release at the CLI's own version,\n // they quietly pin whatever the registry last tagged — which can be a\n // prerelease from an entirely different era of the framework. Record\n // it so we can refuse rather than scaffold a mixed-version app.\n if (versionToUse !== cliVersion) {\n unreleased.set(pkgName, versionToUse);\n }\n }\n versionCache.set(pkgName, versionToUse);\n return versionToUse;\n };\n\n // First, find all unique @rebasepro packages across all files to process in parallel\n const allPackages = new Set<string>();\n const fileContents = new Map<string, string>();\n\n for (const file of filesToProcess) {\n const fullPath = path.resolve(options.targetDirectory, file);\n if (!fs.existsSync(fullPath)) continue;\n const content = fs.readFileSync(fullPath, \"utf-8\");\n fileContents.set(fullPath, content);\n\n const matches = [...content.matchAll(/\"(@rebasepro\\/[^\"]+)\":\\s*\"workspace:\\*\"/g)];\n for (const match of matches) {\n allPackages.add(match[1]);\n }\n }\n\n console.log(chalk.gray(\" Resolving package versions...\"));\n\n // Resolve all versions in parallel\n await Promise.all(Array.from(allPackages).map(getPackageVersion));\n\n // A stable CLI whose packages resolve only to a prerelease means those\n // packages were never released at this version — the usual cause is a rename\n // that left the new name published on the canary tag alone. Scaffolding\n // anyway mixes eras (say @rebasepro/types@0.9.0 beside a 0.0.1 canary) and\n // hands the user an app that fails at install or, worse, at runtime. Neither\n // failure names this as the cause, so stop here and say it plainly.\n const cliIsStable = cliVersion !== \"latest\" && !cliVersion.includes(\"-\");\n const prereleasePins = [...unreleased].filter(([, version]) => version === \"latest\" || version.includes(\"-\"));\n\n if (cliIsStable && prereleasePins.length > 0) {\n const lines = prereleasePins.map(([name, version]) => ` ${name} → ${version}`).join(\"\\n\");\n throw new Error(\n `Rebase ${cliVersion} is not fully published to npm.\\n\\n` +\n `These packages have no ${cliVersion} release, so the newest thing on the\\n` +\n `registry is a prerelease:\\n\\n${lines}\\n\\n` +\n `Scaffolding would pin those alongside the ${cliVersion} packages and produce\\n` +\n `an app that cannot install or run. That is a release gap in Rebase itself —\\n` +\n `not a problem with your machine, your network, or your package manager.\\n\\n` +\n `Stopped before writing dependency versions or installing anything. The\\n` +\n `project directory ${path.basename(options.targetDirectory)}/ was created and is safe to delete.\\n` +\n `Please report this with the list above.`\n );\n }\n\n // Perform replacements\n for (const [fullPath, originalContent] of fileContents.entries()) {\n let content = originalContent.replace(/\\{\\{PROJECT_NAME\\}\\}/g, options.projectName);\n\n // Replace workspace:* with the dynamically resolved version\n const matches = [...content.matchAll(/\"(@rebasepro\\/[^\"]+)\":\\s*\"workspace:\\*\"/g)];\n for (const match of matches) {\n const pkgName = match[1];\n const resolvedVersion = versionCache.get(pkgName) || \"latest\";\n content = content.replace(new RegExp(`\"${pkgName}\":\\\\s*\"workspace:\\\\*\"`, \"g\"), `\"${pkgName}\": \"${resolvedVersion}\"`);\n }\n\n fs.writeFileSync(fullPath, content, \"utf-8\");\n }\n}\n\n\nasync function isPortAvailable(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer();\n server.once(\"error\", () => {\n resolve(false);\n });\n server.once(\"listening\", () => {\n server.close(() => resolve(true));\n });\n server.listen(port);\n });\n}\n\nasync function findAvailablePort(startPort: number): Promise<number> {\n let port = startPort;\n while (!(await isPortAvailable(port))) {\n port++;\n }\n return port;\n}\n\nexport async function configureEnvFile(targetDirectory: string, databaseUrl?: string) {\n const envExamplePath = path.join(targetDirectory, \".env.example\");\n const envPath = path.join(targetDirectory, \".env\");\n if (fs.existsSync(envExamplePath) && !fs.existsSync(envPath)) {\n // Copy .env.example → .env (keep .env.example as a reference in the repo)\n fs.copyFileSync(envExamplePath, envPath);\n\n // Generate secure random strings\n const jwtSecret = crypto.randomBytes(32).toString(\"hex\");\n const dbPassword = crypto.randomBytes(16).toString(\"hex\");\n const serviceKey = crypto.randomBytes(48).toString(\"base64\");\n\n let envContent = fs.readFileSync(envPath, \"utf-8\");\n\n envContent = envContent.replace(\n /^JWT_SECRET=.*$/m,\n `JWT_SECRET=${jwtSecret}`\n );\n\n // Ships commented out in .env.example. Left unset, the server generates\n // one on every boot and silently invalidates the previous run's tokens,\n // so write a stable one now rather than making each restart a logout.\n envContent = envContent.replace(\n /^#\\s*REBASE_SERVICE_KEY=.*$/m,\n `REBASE_SERVICE_KEY=${serviceKey}`\n );\n\n if (databaseUrl) {\n if (/[\\r\\n]/.test(databaseUrl)) {\n throw new Error(\"Invalid DATABASE_URL: multiline values are not allowed.\");\n }\n envContent = envContent.replace(\n /^DATABASE_URL=.*$/m,\n `DATABASE_URL=${databaseUrl}`\n );\n } else {\n const dbPort = await findAvailablePort(5432);\n envContent = envContent.replace(\n /^DATABASE_URL=.*$/m,\n // sslmode=disable: the paired docker-compose Postgres has no TLS,\n // and Go-based tooling (atlas, via `rebase db push`) defaults to\n // requiring SSL when the URL doesn't say otherwise.\n `DATABASE_URL=postgresql://rebase:${dbPassword}@localhost:${dbPort}/rebase?options=-c%20search_path=public&sslmode=disable\\nDATABASE_PASSWORD=${dbPassword}`\n );\n\n // Also update docker-compose.yml with the dynamic host port if it has the default 5432 port mapping\n const dockerComposePath = path.join(targetDirectory, \"docker-compose.yml\");\n if (fs.existsSync(dockerComposePath)) {\n let dockerComposeContent = fs.readFileSync(dockerComposePath, \"utf-8\");\n dockerComposeContent = dockerComposeContent.replace(\n /-\\s*\"5432:5432\"/g,\n `- \"${dbPort}:5432\"`\n );\n fs.writeFileSync(dockerComposePath, dockerComposeContent, \"utf-8\");\n }\n }\n\n fs.writeFileSync(envPath, envContent, \"utf-8\");\n }\n}\n","/**\n * CLI command: generate-sdk\n *\n * Reads collection definitions from a specified directory (default: ./config/collections),\n * generates a typed TypeScript SDK, and writes it to the output directory (default: ./generated/sdk).\n *\n * Uses jiti for dynamic TypeScript import of collection files.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { generateSDK, GeneratedFile } from \"@rebasepro/codegen\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\n\ninterface GenerateSDKArgs {\n collectionsDir: string;\n output: string;\n cwd: string;\n}\n\n/**\n * Dynamically load collection definitions from a directory.\n *\n * Expects the directory to have an index.ts/index.js that exports a default\n * array of CollectionConfig objects (matching the app/config/collections pattern).\n */\nasync function loadCollections(collectionsDir: string): Promise<CollectionConfig[]> {\n const absDir = path.resolve(collectionsDir);\n\n if (!fs.existsSync(absDir)) {\n throw new Error(`Collections directory not found: ${absDir}`);\n }\n\n // Try to import the index file using jiti (supports TypeScript natively)\n let jiti: (id: string, userOptions?: Record<string, unknown>) => (modulePath: string) => Record<string, unknown>;\n try {\n const jitiModule = await import(\"jiti\");\n jiti = (jitiModule.default || jitiModule) as typeof jiti;\n } catch {\n const installCmd = [...getPMCommands(detectPackageManager()).install, \"-D\", \"jiti\"].join(\" \");\n throw new Error(\n `Could not load 'jiti'. Install it with: ${installCmd}\\n` +\n \"jiti is required to dynamically import TypeScript collection definitions.\"\n );\n }\n\n const jitiInstance = jiti(absDir, {\n interopDefault: true,\n esmResolve: true\n });\n\n // Look for index file\n const indexCandidates = [\"index.ts\", \"index.js\", \"index.mjs\"];\n let indexPath: string | null = null;\n\n for (const candidate of indexCandidates) {\n const p = path.join(absDir, candidate);\n if (fs.existsSync(p)) {\n indexPath = p;\n break;\n }\n }\n\n if (!indexPath) {\n // Fallback: load each .ts/.js file individually\n console.log(chalk.yellow(\" No index file found, scanning individual collection files...\"));\n const collections: CollectionConfig[] = [];\n const files = fs.readdirSync(absDir).filter(f =>\n (f.endsWith(\".ts\") || f.endsWith(\".js\")) && !f.startsWith(\".\")\n );\n\n for (const file of files) {\n try {\n const mod = jitiInstance(path.join(absDir, file));\n const exported = mod.default || mod;\n if (exported && typeof exported === \"object\" && \"slug\" in exported) {\n collections.push(exported as CollectionConfig);\n } else if (Array.isArray(exported)) {\n collections.push(...exported);\n }\n } catch (err) {\n console.warn(chalk.yellow(` ⚠ Skipping ${file}: ${(err as Error).message}`));\n }\n }\n\n return collections;\n }\n\n // Import the index\n const mod = jitiInstance(indexPath);\n const exported = mod.default || mod;\n\n if (Array.isArray(exported)) {\n return exported as CollectionConfig[];\n } else if (typeof exported === \"object\" && exported !== null) {\n // Could be a named export like { collections: [...] }\n if (\"collections\" in exported && Array.isArray(exported.collections)) {\n return exported.collections;\n }\n // Or individual named exports\n const collections: CollectionConfig[] = [];\n for (const value of Object.values(exported)) {\n if (value && typeof value === \"object\" && \"slug\" in (value as CollectionConfig)) {\n collections.push(value as CollectionConfig);\n }\n }\n if (collections.length > 0) return collections;\n }\n\n throw new Error(\n `Could not extract collections from ${indexPath}.\\n` +\n \"Expected a default export of CollectionConfig[] or an object with named collection exports.\"\n );\n}\n\n/**\n * Write generated files to the output directory.\n */\nfunction writeFiles(outputDir: string, files: GeneratedFile[]): void {\n const absOutput = path.resolve(outputDir);\n\n // Create output directory\n fs.mkdirSync(absOutput, { recursive: true });\n\n for (const file of files) {\n const filePath = path.join(absOutput, file.path);\n const dir = path.dirname(filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n fs.writeFileSync(filePath, file.content, \"utf-8\");\n }\n}\n\n/**\n * Main entry point for the generate-sdk command.\n */\nexport async function generateSdkCommand(args: GenerateSDKArgs): Promise<void> {\n const { collectionsDir, output, cwd } = args;\n\n const resolvedCollectionsDir = path.isAbsolute(collectionsDir)\n ? collectionsDir\n : path.join(cwd, collectionsDir);\n\n const resolvedOutput = path.isAbsolute(output)\n ? output\n : path.join(cwd, output);\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔧 Rebase SDK Generator\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Collections:\")} ${resolvedCollectionsDir}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n\n // 1. Load collections\n console.log(chalk.cyan(\" → Loading collection definitions...\"));\n const collections = await loadCollections(resolvedCollectionsDir);\n\n // Sort collections alphabetically by slug to ensure deterministic SDK generation\n collections.sort((a, b) => a.slug.localeCompare(b.slug));\n\n if (collections.length === 0) {\n console.log(chalk.red(\" ✗ No collections found. Nothing to generate.\"));\n process.exit(1);\n }\n\n console.log(chalk.green(` ✓ Found ${collections.length} collection(s): ${collections.map(c => c.slug).join(\", \")}`));\n console.log(\"\");\n\n // 2. Generate SDK files\n console.log(chalk.cyan(\" → Generating SDK files...\"));\n const files = generateSDK(collections);\n console.log(chalk.green(` ✓ Generated ${files.length} file(s)`));\n\n // 3. Write to disk\n console.log(chalk.cyan(` → Writing to ${resolvedOutput}...`));\n writeFiles(resolvedOutput, files);\n\n console.log(\"\");\n console.log(chalk.green.bold(\" ✓ SDK generated successfully!\"));\n console.log(\"\");\n console.log(chalk.gray(\" Usage:\"));\n console.log(chalk.gray(\" import { createRebaseClient } from '@rebasepro/client';\"));\n console.log(chalk.gray(` import type { Database } from './${path.relative(cwd, path.join(resolvedOutput, \"database.types\"))}';`));\n console.log(\"\");\n console.log(chalk.gray(\" const rebase = createRebaseClient<Database>({\"));\n console.log(chalk.gray(\" baseUrl: 'http://localhost:3001',\"));\n console.log(chalk.gray(\" // token: 'your-jwt-token',\"));\n console.log(chalk.gray(\" });\"));\n console.log(\"\");\n console.log(chalk.gray(` const { data } = await rebase.collection('${collections[0]?.slug || \"my_collection\"}').find();`));\n console.log(\"\");\n}\n","/**\n * CLI command: rebase schema <action>\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile\n} from \"../utils/project\";\n\nexport async function schemaCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printSchemaHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));\n process.exit(1);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n try {\n const isTs = pluginCli.endsWith(\".ts\");\n if (isTs) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n } else {\n await execa(\"node\", [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n } catch {\n process.exit(1);\n }\n}\n\nfunction printSchemaHelp() {\n console.log(`\n${chalk.bold(\"rebase schema\")} — Schema management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase schema ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"generate\")} Generate Schema from collection definitions\n ${chalk.blue.bold(\"introspect\")} Introspect an existing database to generate collection definitions\n\n${chalk.green.bold(\"generate Options\")}\n ${chalk.blue(\"--collections, -c\")} Path to collections directory\n ${chalk.blue(\"--output, -o\")} Output path for generated schema\n ${chalk.blue(\"--watch, -w\")} Watch for changes and regenerate automatically\n\n${chalk.green.bold(\"introspect Options\")}\n ${chalk.blue(\"--output, -o\")} Output directory for generated collection files\n`);\n}\n","/**\n * CLI command: rebase db <action>\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile\n} from \"../utils/project\";\n\nexport async function dbCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printDbHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));\n process.exit(1);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n try {\n const isTs = pluginCli.endsWith(\".ts\");\n if (isTs) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n } else {\n await execa(\"node\", [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n } catch {\n // If the process exits with an error code, execa will throw,\n // but inherit stdio means the user already saw the output.\n process.exit(1);\n }\n}\n\nfunction printDbHelp() {\n console.log(`\n${chalk.bold(\"rebase db\")} — Database management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase db ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"push\")} Apply schema directly to database (development)\n ${chalk.blue.bold(\"generate\")} Generate migration files\n ${chalk.blue.bold(\"migrate\")} Run pending migrations\n ${chalk.blue.bold(\"branch\")} Database branching (create, list, delete, info)\n ${chalk.blue.bold(\"backup\")} Create a backup with pg_dump (--out <path|s3://…>)\n ${chalk.blue.bold(\"restore\")} Restore a backup with pg_restore (destructive; needs --yes)\n ${chalk.blue.bold(\"backups\")} List stored backups (backups list)\n\n${chalk.green.bold(\"Examples\")}\n ${chalk.gray(\"# Quick development workflow\")}\n rebase schema generate && rebase db push\n\n ${chalk.gray(\"# Production migration workflow\")}\n rebase db generate\n rebase db migrate\n\n ${chalk.gray(\"# Create a database branch\")}\n rebase db branch create feature_auth\n\n ${chalk.gray(\"# Back up to a local directory, then to object storage\")}\n rebase db backup --out ./backups\n rebase db backup --out s3://my-private-bucket/backups\n\n ${chalk.gray(\"# Restore into a fresh database (safe: does not touch the live one)\")}\n rebase db restore ./backups/rebase-app-20260714T030000Z.dump --create-db --target-db app_restored\n`);\n}\n","/**\n * CLI command: rebase dev\n *\n * Starts the full development environment:\n * - Backend: tsx watch with auto-reload\n * - Frontend: vite dev server\n *\n * Both processes stream output with color-coded prefixes.\n *\n * When the backend uses port-retry (i.e. the configured port is busy and it\n * binds to the next free one), the CLI detects the actual port from stdout\n * and injects VITE_API_URL into the frontend so it connects automatically.\n *\n * Each project gets a deterministic default port derived from the project\n * root path, so multiple Rebase instances never collide.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { execa, execaCommandSync, type ResultPromise } from \"execa\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport {\n requireProjectRoot,\n findBackendDir,\n findFrontendDir,\n findEnvFile,\n resolveTsx,\n validateTsxInstallation,\n getActiveBackendPlugin,\n resolvePluginCliScript\n} from \"../utils/project\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\n\n/** Well-known filename the backend writes its actual port to. */\nconst DEV_PORT_FILENAME = \".rebase-dev-port\";\n\n/**\n * Compute a deterministic port from the project root path.\n * Range: 3001–3999 (avoids privileged ports and common services).\n * Two different project directories will almost always get different ports.\n */\nfunction getProjectPort(projectRoot: string): number {\n let hash = 0;\n for (let i = 0; i < projectRoot.length; i++) {\n hash = ((hash << 5) - hash + projectRoot.charCodeAt(i)) | 0;\n }\n return 3001 + (Math.abs(hash) % 999);\n}\n\n/**\n * Resolve the best starting port for this project:\n * 1. Explicit --port flag (highest priority)\n * 2. PORT env var\n * 3. Previously used port from .rebase-dev-port (port affinity across restarts)\n * 4. Deterministic hash from project path (unique per project)\n */\nfunction resolveStartPort(projectRoot: string, explicitPort?: number): number {\n // 1. Explicit flag\n if (explicitPort) return explicitPort;\n\n // 2. PORT env var\n if (process.env.PORT) return parseInt(process.env.PORT, 10);\n\n // 3. Port affinity — check if we wrote a port file from a previous run\n try {\n const portFile = path.join(projectRoot, DEV_PORT_FILENAME);\n if (fs.existsSync(portFile)) {\n const saved = parseInt(fs.readFileSync(portFile, \"utf-8\").trim(), 10);\n if (saved > 0 && saved < 65536) return saved;\n }\n } catch { /* ignore */ }\n\n // 4. Deterministic hash\n return getProjectPort(projectRoot);\n}\n\nexport async function devCommand(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--backend-only\": Boolean,\n \"--frontend-only\": Boolean,\n \"--port\": Number,\n \"--generate\": Boolean,\n \"--help\": Boolean,\n \"-b\": \"--backend-only\",\n \"-f\": \"--frontend-only\",\n \"-p\": \"--port\",\n \"-g\": \"--generate\",\n \"-h\": \"--help\"\n },\n {\n argv: rawArgs.slice(3), // skip \"node rebase dev\"\n permissive: true\n }\n );\n\n if (args[\"--help\"]) {\n printDevHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n const backendDir = findBackendDir(projectRoot);\n const frontendDir = findFrontendDir(projectRoot);\n const backendOnly = args[\"--backend-only\"] || false;\n const frontendOnly = args[\"--frontend-only\"] || false;\n const shouldGenerate = args[\"--generate\"] || process.env.REBASE_AUTO_GENERATE === \"true\" || process.env.REBASE_GENERATE === \"true\";\n\n // Resolve the port ONCE, before starting anything\n const startPort = resolveStartPort(projectRoot, args[\"--port\"]);\n\n console.log(\"\");\n console.log(chalk.bold(\" 🚀 Rebase Dev Server\"));\n console.log(\"\");\n\n const children: ResultPromise[] = [];\n\n // --- State for printing the banner ---\n let frontendUrl = \"\";\n let backendUrl = \"\";\n let debounceSummary: NodeJS.Timeout | null = null;\n let bannerPrinted = false;\n\n /** Actual backend port, resolved once the server prints its URL. */\n let resolvedBackendPort: number | null = null;\n\n // Use regex to strip ANSI codes before matching\n // eslint-disable-next-line no-control-regex\n const stripAnsi = (str: string) => str.replace(/[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, \"\");\n\n function printSummary() {\n if (!frontendUrl || !backendUrl) return;\n if (debounceSummary) clearTimeout(debounceSummary);\n debounceSummary = setTimeout(() => {\n if (bannerPrinted) return;\n console.log(\"\");\n console.log(chalk.cyan(\"┌────────────────────────────────────────────────────────────┐\"));\n console.log(chalk.cyan(\"│ │\"));\n console.log(chalk.cyan(\"│ ✦ Rebase Admin App is ready! │\"));\n const cleanUrl = stripAnsi(frontendUrl);\n const paddedUrl = cleanUrl.padEnd(41);\n console.log(chalk.cyan(\"│ ➜ Frontend URL: \") + chalk.white(paddedUrl) + chalk.cyan(\"│\"));\n console.log(chalk.cyan(\"│ │\"));\n console.log(chalk.cyan(\"└────────────────────────────────────────────────────────────┘\"));\n console.log(\"\");\n bannerPrinted = true;\n }, 500);\n }\n\n // Handle graceful shutdown\n const cleanup = () => {\n // Clean up dev port file\n try {\n const portFile = path.join(projectRoot, DEV_PORT_FILENAME);\n if (fs.existsSync(portFile)) fs.unlinkSync(portFile);\n\n const urlFile = path.join(projectRoot, \".rebase-dev-url\");\n if (fs.existsSync(urlFile)) fs.unlinkSync(urlFile);\n } catch { /* ignore */ }\n\n children.forEach((child) => {\n if (child.pid && !child.killed) {\n try {\n if (process.platform === \"win32\") {\n execaCommandSync(`taskkill /pid ${child.pid} /T /F`);\n } else {\n process.kill(-child.pid, \"SIGKILL\");\n }\n } catch (e) {\n try {\n child.kill(\"SIGKILL\");\n } catch (err) {\n // ignore\n }\n }\n }\n });\n process.exit(0);\n };\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n /**\n * Start the Vite frontend, optionally injecting the backend port.\n */\n function startFrontend(backendPort: number | null) {\n if (!frontendDir) return;\n\n console.log(` ${chalk.magenta(\"▶\")} Frontend: ${chalk.gray(frontendDir)}`);\n\n const frontendEnv: Record<string, string> = { ...process.env as Record<string, string> };\n\n // Inject the resolved backend URL so Vite picks it up\n if (backendPort) {\n frontendEnv.VITE_API_URL = `http://localhost:${backendPort}`;\n console.log(` ${chalk.gray(\"↳ VITE_API_URL\")} = ${chalk.white(`http://localhost:${backendPort}`)}`);\n }\n\n const pm = detectPackageManager(projectRoot);\n const pmCmds = getPMCommands(pm);\n const runDevCmd = pmCmds.run(\"dev\");\n\n const frontendChild = execa(\n runDevCmd[0],\n runDevCmd.slice(1),\n {\n cwd: frontendDir,\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n env: frontendEnv,\n shell: true,\n detached: process.platform !== \"win32\"\n }\n );\n frontendChild.catch(() => {}); // prevent unhandled promise rejection on exit\n\n frontendChild.stdout?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.magenta.bold(\"[admin]\")} ${line}`);\n const cleanLine = stripAnsi(line);\n const urlMatch = cleanLine.match(/(http:\\/\\/(?:localhost|127\\.0\\.0\\.1):\\d+)/);\n if (cleanLine.includes(\"Local:\") && urlMatch) {\n frontendUrl = urlMatch[1];\n printSummary();\n }\n });\n });\n\n frontendChild.stderr?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.magenta.bold(\"[admin]\")} ${line}`);\n });\n });\n\n children.push(frontendChild);\n }\n\n // Start backend\n if (!frontendOnly && backendDir) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n const pmCmdsLocal = getPMCommands(detectPackageManager(projectRoot));\n const addCmd = [...pmCmdsLocal.install, \"-D\", \"tsx\"].join(\" \");\n console.error(chalk.red(\" ✗ Could not find tsx binary for backend.\"));\n console.error(chalk.gray(` Install it with: ${addCmd}`));\n process.exit(1);\n }\n\n // Verify the tsx installation is intact (not just the symlink)\n const tsxValidationError = validateTsxInstallation(tsxBin);\n if (tsxValidationError) {\n const pmCmdsLocal = getPMCommands(detectPackageManager(projectRoot));\n const installCmd = pmCmdsLocal.install.join(\" \");\n console.error(chalk.red(\" ✗ tsx installation appears corrupted.\"));\n console.error(chalk.gray(` ${tsxValidationError}`));\n console.error(\"\");\n console.error(chalk.gray(\" To fix, run:\"));\n console.error(chalk.cyan(` rm -rf node_modules && ${installCmd}`));\n process.exit(1);\n }\n\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n // Always inject PORT so the backend uses our resolved port instead of\n // its hardcoded default (3001). This prevents cross-project collisions\n // when multiple Rebase instances run simultaneously.\n env.PORT = String(startPort);\n\n console.log(` ${chalk.cyan(\"▶\")} Backend: ${chalk.gray(backendDir)}`);\n console.log(` ${chalk.gray(\"↳ PORT\")} = ${chalk.white(String(startPort))}`);\n\n // The .env's PORT / VITE_API_URL look authoritative but are overridden in\n // dev: we derive a per-project port to avoid cross-project collisions and\n // point the frontend at it. Surface that so a mismatched .env doesn't turn\n // into a silent \"connecting to the wrong port\" debugging loop.\n if (envFile) {\n try {\n const envText = fs.readFileSync(envFile, \"utf-8\");\n const readEnvKey = (key: string): string | undefined => {\n const m = envText.match(new RegExp(`^\\\\s*${key}\\\\s*=\\\\s*(.+?)\\\\s*$`, \"m\"));\n return m ? m[1].replace(/^[\"']|[\"']$/g, \"\") : undefined;\n };\n const envPort = readEnvKey(\"PORT\");\n const envApiUrl = readEnvKey(\"VITE_API_URL\");\n // Only name the keys — never echo a raw `http://localhost:<port>`\n // value, so log scrapers don't mistake it for the dev server URL.\n const overridden: string[] = [];\n if (envPort && envPort !== String(startPort)) overridden.push(\"PORT\");\n if (envApiUrl && envApiUrl !== `http://localhost:${startPort}`) overridden.push(\"VITE_API_URL\");\n if (overridden.length > 0) {\n console.log(chalk.yellow(\n ` ⚠ dev uses a derived per-project port (${startPort}); your .env ${overridden.join(\" / \")} ` +\n `${overridden.length > 1 ? \"are\" : \"is\"} ignored here (avoids cross-project collisions). ` +\n `Pass ${chalk.white(\"--port\")} to pin a port.`\n ));\n }\n } catch { /* ignore — best-effort notice */ }\n }\n\n /** Whether the frontend has been launched (we only launch it once). */\n let frontendLaunched = false;\n\n // Initial schema and SDK generation (disabled by default, enabled via --generate or env var)\n if (shouldGenerate) {\n console.log(chalk.gray(\" → Ensuring schema and SDK are generated on start...\"));\n try {\n const activePlugin = getActiveBackendPlugin(backendDir);\n const pluginCli = activePlugin ? resolvePluginCliScript(backendDir, activePlugin) : null;\n if (pluginCli) {\n await execa(tsxBin, [pluginCli, \"schema\", \"generate\"], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n const sdkCmd = getPMCommands(detectPackageManager(projectRoot)).exec(\"rebase\", [\"generate-sdk\"]);\n await execa(sdkCmd[0], sdkCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n console.log(chalk.green(\" ✓ Initial schema and SDK generated successfully.\\n\"));\n } catch (err: unknown) {\n console.error(chalk.red(` ✗ Initial schema/SDK generation failed: ${err instanceof Error ? err.message : err}\\n`));\n }\n\n // Watch collections folder for changes\n const collectionsDir = path.join(projectRoot, \"config\", \"collections\");\n if (fs.existsSync(collectionsDir)) {\n let watchDebounce: NodeJS.Timeout | null = null;\n fs.watch(collectionsDir, { recursive: true }, (eventType, filename) => {\n if (!filename || filename.startsWith(\".\") || filename.endsWith(\".tmp\")) return;\n\n if (watchDebounce) clearTimeout(watchDebounce);\n watchDebounce = setTimeout(async () => {\n console.log(chalk.yellow(`\\n 🔄 Collection change detected (${filename}). Regenerating schema & SDK...`));\n try {\n const activePlugin = getActiveBackendPlugin(backendDir);\n const pluginCli = activePlugin ? resolvePluginCliScript(backendDir, activePlugin) : null;\n if (pluginCli) {\n await execa(tsxBin, [pluginCli, \"schema\", \"generate\"], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n const sdkCmd = getPMCommands(detectPackageManager(projectRoot)).exec(\"rebase\", [\"generate-sdk\"]);\n await execa(sdkCmd[0], sdkCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n console.log(chalk.green(\" ✓ Schema & SDK regenerated successfully. Hono will reload.\"));\n } catch (err: unknown) {\n console.error(chalk.red(` ✗ Failed to regenerate schema/SDK: ${err instanceof Error ? err.message : err}`));\n }\n }, 300);\n });\n }\n }\n\n const watchArgs = [\"watch\", \"--conditions\", \"development\", \"src/index.ts\"];\n if (!shouldGenerate) {\n // When auto-generation is disabled, watch the config/collections dir directly so the dev server\n // still reloads automatically when files there are edited/updated manually.\n watchArgs.splice(1, 0, `--watch=\"${path.join(\"..\", \"config\", \"**\", \"*\")}\"`);\n\n // Watch collections folder and warn about potential schema drift\n const collectionsDir = path.join(projectRoot, \"config\", \"collections\");\n if (fs.existsSync(collectionsDir)) {\n let driftDebounce: NodeJS.Timeout | null = null;\n fs.watch(collectionsDir, { recursive: true }, (_eventType, filename) => {\n if (!filename || filename.startsWith(\".\") || filename.endsWith(\".tmp\")) return;\n if (driftDebounce) clearTimeout(driftDebounce);\n driftDebounce = setTimeout(() => {\n console.log([\n \"\",\n chalk.yellow(\" ┌──────────────────────────────────────────────────────────────┐\"),\n chalk.yellow(\" │ ⚠️ Collection file changed: \") + chalk.white(filename!.padEnd(31)) + chalk.yellow(\"│\"),\n chalk.yellow(\" │ │\"),\n chalk.yellow(\" │ Your schema may be out of sync. Run: │\"),\n chalk.yellow(\" │ \") + chalk.cyan(\"rebase schema generate\") + chalk.yellow(\" regenerate Drizzle schema │\"),\n chalk.yellow(\" │ \") + chalk.cyan(\"rebase db push \") + chalk.yellow(\" sync schema to database │\"),\n chalk.yellow(\" │ \") + chalk.cyan(\"rebase doctor \") + chalk.yellow(\" check for drift │\"),\n chalk.yellow(\" │ │\"),\n chalk.yellow(\" │ TIP: Use \") + chalk.bold(\"rebase dev --generate\") + chalk.yellow(\" for auto-regeneration │\"),\n chalk.yellow(\" └──────────────────────────────────────────────────────────────┘\"),\n \"\"\n ].join(\"\\n\"));\n }, 500);\n });\n }\n }\n\n const backendChild = execa(\n tsxBin,\n watchArgs,\n {\n cwd: backendDir,\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n env,\n shell: true,\n detached: process.platform !== \"win32\"\n }\n );\n backendChild.catch(() => {}); // prevent unhandled promise rejection on exit\n\n backendChild.stdout?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.cyan.bold(\"[backend]\")} ${line}`);\n const cleanLine = stripAnsi(line);\n const serverMatch = cleanLine.match(/Server running at http:\\/\\/(?:localhost|127\\.0\\.0\\.1):(\\d+)/);\n if (serverMatch) {\n resolvedBackendPort = parseInt(serverMatch[1], 10);\n backendUrl = \"started\";\n printSummary();\n\n // Save the url to a temp file for scripts to pick up\n const urlFile = path.join(projectRoot, \".rebase-dev-url\");\n fs.writeFileSync(urlFile, `http://localhost:${resolvedBackendPort}`, \"utf-8\");\n\n // Save the port to .rebase-dev-port for port affinity\n const portFile = path.join(projectRoot, DEV_PORT_FILENAME);\n fs.writeFileSync(portFile, String(resolvedBackendPort), \"utf-8\");\n\n // Start frontend now that we know the real port\n if (!backendOnly && frontendDir && !frontendLaunched) {\n frontendLaunched = true;\n startFrontend(resolvedBackendPort);\n }\n }\n });\n });\n\n /** Whether we've already shown a corrupted-modules recovery hint. */\n let corruptedModulesWarned = false;\n\n backendChild.stderr?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.cyan.bold(\"[backend]\")} ${line}`);\n\n // Detect corrupted node_modules at runtime\n // (covers tsx and any other dependency whose pnpm store entry is broken)\n if (!corruptedModulesWarned) {\n const cleanLine = stripAnsi(line);\n if (\n cleanLine.includes(\"Cannot find module\") &&\n cleanLine.includes(\"node_modules/.pnpm/\")\n ) {\n corruptedModulesWarned = true;\n // Delay slightly so the full Node.js error stack prints first\n setTimeout(() => {\n const pm = detectPackageManager(projectRoot);\n const installCmd = getPMCommands(pm).install.join(\" \");\n console.error(\"\");\n console.error(chalk.red(\" ✗ node_modules appears corrupted — a required file is missing.\"));\n console.error(chalk.gray(\" This usually happens when a previous install was interrupted\"));\n console.error(chalk.gray(\" or the package manager store was cleaned.\"));\n console.error(\"\");\n console.error(chalk.gray(\" To fix, stop the dev server and run:\"));\n console.error(chalk.cyan(` rm -rf node_modules && ${installCmd}`));\n console.error(\"\");\n }, 200);\n }\n }\n });\n });\n\n children.push(backendChild);\n } else if (!frontendOnly && !backendDir) {\n console.warn(chalk.yellow(\" ⚠ No backend/ directory found, skipping backend.\"));\n }\n\n // Start frontend immediately if backend-only mode or no backend\n if (!backendOnly && frontendDir && (frontendOnly || !backendDir)) {\n startFrontend(null);\n } else if (!backendOnly && !frontendDir) {\n console.warn(chalk.yellow(\" ⚠ No frontend/ directory found, skipping frontend.\"));\n }\n\n if (children.length === 0) {\n console.error(chalk.red(\" ✗ Nothing to start. Check your project structure.\"));\n process.exit(1);\n }\n\n console.log(\"\");\n console.log(chalk.gray(\" Press Ctrl+C to stop all servers.\"));\n console.log(\"\");\n\n // Wait for all children to exit\n await Promise.all(\n children.map(\n (child) =>\n new Promise<void>((resolve) => {\n child.finally(() => resolve());\n })\n )\n );\n}\n\nfunction printDevHelp() {\n console.log(`\n${chalk.bold(\"rebase dev\")} — Start the development server\n\n${chalk.green.bold(\"Usage\")}\n rebase dev [options]\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--backend-only, -b\")} Only start the backend server\n ${chalk.blue(\"--frontend-only, -f\")} Only start the frontend server\n ${chalk.blue(\"--port, -p\")} Backend port (default: auto-detected per project)\n ${chalk.blue(\"--generate, -g\")} Enable automatic schema and SDK generation on startup and file changes\n\n${chalk.green.bold(\"Description\")}\n Starts both the backend (tsx watch + Hono) and frontend (Vite)\n dev servers concurrently with color-coded output prefixes.\n\n Each project automatically receives a unique default port derived\n from its directory path, preventing collisions when running multiple\n Rebase instances simultaneously.\n\n If the assigned port is already in use, the server will automatically\n try the next available port. The frontend is started only after the\n backend is ready, and VITE_API_URL is injected automatically.\n\n By default, automatic schema and SDK generation is disabled on startup\n and file changes. Pass --generate (-g) or set REBASE_AUTO_GENERATE=true\n in your environment to enable it.\n`);\n}\n","/**\n * CLI command: rebase build\n *\n * Runs the build script in all workspace packages.\n * Automatically detects the package manager (pnpm or npm) and\n * uses the correct workspace-aware command.\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport { requireProjectRoot } from \"../utils/project\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\n\nexport async function buildCommand(): Promise<void> {\n const projectRoot = requireProjectRoot();\n const pm = detectPackageManager(projectRoot);\n const cmds = getPMCommands(pm);\n\n const buildCmd = cmds.runAll(\"build\");\n\n console.log(`${chalk.bold(\"Rebase\")} — Building all workspaces with ${chalk.cyan(pm)}...\\n`);\n\n try {\n await execa(buildCmd[0], buildCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\"\n });\n } catch {\n console.error(chalk.red(\"\\n✗ Build failed.\"));\n process.exit(1);\n }\n}\n","/**\n * CLI command: rebase start\n *\n * Starts the backend server in production mode.\n * Automatically detects the package manager (pnpm or npm) and\n * runs the start script in the backend workspace.\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport { requireProjectRoot, findEnvFile } from \"../utils/project\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\n\nexport async function startCommand(): Promise<void> {\n const projectRoot = requireProjectRoot();\n const pm = detectPackageManager(projectRoot);\n const cmds = getPMCommands(pm);\n\n const startCmd = cmds.runWorkspace(\"backend\", \"start\");\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n console.log(`${chalk.bold(\"Rebase\")} — Starting backend server...\\n`);\n\n try {\n await execa(startCmd[0], startCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n } catch {\n console.error(chalk.red(\"\\n✗ Failed to start server.\"));\n process.exit(1);\n }\n}\n","/**\n * CLI command: rebase auth <action>\n *\n * Subcommands:\n * reset-password — Reset a user's password\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { spawn } from \"child_process\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n findEnvFile,\n resolveTsx\n} from \"../utils/project\";\n\nexport async function authCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printAuthHelp();\n return;\n }\n\n switch (subcommand) {\n case \"reset-password\":\n await resetPassword(rawArgs);\n break;\n default:\n console.error(chalk.red(`Unknown auth command: ${subcommand}`));\n console.log(\"\");\n printAuthHelp();\n process.exit(1);\n }\n}\n\nasync function resetPassword(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--email\": String,\n \"--password\": String,\n \"-e\": \"--email\",\n \"-p\": \"--password\"\n },\n {\n argv: rawArgs.slice(4), // skip \"node rebase auth reset-password\"\n permissive: true\n }\n );\n\n // Support both --email flag and positional args\n const email = args[\"--email\"] || args._[0];\n const newPassword = args[\"--password\"] || args._[1];\n\n if (!email) {\n console.error(chalk.red(\"✗ Email is required.\"));\n console.log(\"\");\n console.log(chalk.gray(\" Usage: rebase auth reset-password <email> [new-password]\"));\n console.log(chalk.gray(\" rebase auth reset-password --email user@example.com --password NewPass123!\"));\n process.exit(1);\n }\n\n const projectRoot = requireProjectRoot();\n\n // 1. Try API-first reset\n let envServiceKey: string | undefined;\n const envFile = findEnvFile(projectRoot);\n if (envFile && fs.existsSync(envFile)) {\n try {\n const envContent = fs.readFileSync(envFile, \"utf8\");\n const match = envContent.match(/^\\s*REBASE_SERVICE_KEY\\s*=\\s*['\"]?(.*?)['\"]?\\s*$/m);\n if (match && match[1]) {\n envServiceKey = match[1];\n }\n } catch {\n // Ignore\n }\n }\n\n let baseUrl = process.env.REBASE_BASE_URL;\n let serviceKey = process.env.REBASE_SERVICE_KEY || envServiceKey;\n\n const statePath = path.join(projectRoot, \".rebase\", \"state.json\");\n if (fs.existsSync(statePath)) {\n try {\n const state = JSON.parse(fs.readFileSync(statePath, \"utf8\")) as Record<string, unknown>;\n if (state && typeof state === \"object\") {\n if (typeof state.baseUrl === \"string\" && !baseUrl) {\n baseUrl = state.baseUrl;\n }\n if (typeof state.serviceKey === \"string\" && !serviceKey) {\n serviceKey = state.serviceKey;\n }\n }\n } catch {\n // Ignore\n }\n }\n\n const devUrlPath = path.join(projectRoot, \".rebase-dev-url\");\n if (fs.existsSync(devUrlPath) && !baseUrl) {\n try {\n baseUrl = fs.readFileSync(devUrlPath, \"utf8\").trim();\n } catch {\n // Ignore\n }\n }\n\n if (baseUrl && serviceKey) {\n console.log(\"Trying API-first reset via running backend...\");\n try {\n const finalPass = newPassword || \"NewPassword123!\";\n const cleanBaseUrl = baseUrl.replace(/\\/+$/, \"\");\n const searchUrl = `${cleanBaseUrl}/api/admin/users?search=${encodeURIComponent(email)}&limit=1`;\n const searchRes = await fetch(searchUrl, {\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Accept\": \"application/json\"\n }\n });\n if (!searchRes.ok) {\n throw new Error(`Failed to list users: ${searchRes.statusText}`);\n }\n const searchData = await searchRes.json() as unknown;\n if (!searchData || typeof searchData !== \"object\") {\n throw new Error(\"Invalid response format from user search API.\");\n }\n \n let userId: string | undefined;\n if (Array.isArray(searchData)) {\n const firstUser = searchData[0] as unknown;\n if (firstUser && typeof firstUser === \"object\" && \"id\" in firstUser && typeof (firstUser as { id: unknown }).id === \"string\") {\n userId = (firstUser as { id: string }).id;\n } else if (firstUser && typeof firstUser === \"object\" && \"uid\" in firstUser && typeof (firstUser as { uid: unknown }).uid === \"string\") {\n userId = (firstUser as { uid: string }).uid;\n }\n } else if (\"users\" in searchData && Array.isArray((searchData as { users: unknown }).users)) {\n const users = (searchData as { users: unknown[] }).users;\n const firstUser = users[0];\n if (firstUser && typeof firstUser === \"object\" && \"id\" in firstUser && typeof (firstUser as { id: unknown }).id === \"string\") {\n userId = (firstUser as { id: string }).id;\n } else if (firstUser && typeof firstUser === \"object\" && \"uid\" in firstUser && typeof (firstUser as { uid: unknown }).uid === \"string\") {\n userId = (firstUser as { uid: string }).uid;\n }\n }\n\n if (!userId) {\n throw new Error(`User not found with email: ${email}`);\n }\n\n const resetUrl = `${cleanBaseUrl}/api/admin/users/${userId}/reset-password`;\n const resetRes = await fetch(resetUrl, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n },\n body: JSON.stringify({ password: finalPass })\n });\n\n if (!resetRes.ok) {\n const errText = await resetRes.text();\n throw new Error(`Password reset endpoint failed: ${errText || resetRes.statusText}`);\n }\n\n console.log(\"API reset successful.\");\n console.log(chalk.bold(\" 🔑 Rebase Auth — Reset Password (via API)\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Email:\")} ${email}`);\n console.log(` ${chalk.gray(\"Password:\")} ${finalPass}`);\n console.log(\"\");\n return;\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n console.warn(chalk.yellow(\"API reset failed, falling back to direct database update...\"));\n console.warn(chalk.gray(` Details: ${errMsg}`));\n }\n }\n\n // 2. Direct-DB Fallback\n const backendDir = requireBackendDir(projectRoot);\n const tsxBin = resolveTsx(projectRoot);\n\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n\n try {\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n env.REBASE_RESET_EMAIL = email;\n env.REBASE_RESET_PASSWORD = newPassword || \"NewPassword123!\";\n env.REBASE_ENV_FILE_PATH = envFile || path.join(projectRoot, \".env\");\n\n const scriptContent = `\nimport { createPostgresDatabaseConnection } from \"@rebasepro/server-postgres\";\nimport { hashPassword } from \"@rebasepro/server\";\nimport { eq } from \"drizzle-orm\";\nimport * as dotenv from \"dotenv\";\nimport path from \"path\";\nimport fs from \"fs\";\n\ndotenv.config({ path: process.env.REBASE_ENV_FILE_PATH });\n\nconst email = process.env.REBASE_RESET_EMAIL!;\nconst newPassword = process.env.REBASE_RESET_PASSWORD!;\n\nasync function resetPassword() {\n const { db } = createPostgresDatabaseConnection(process.env.DATABASE_URL!);\n const hash = await hashPassword(newPassword);\n\n let usersTable;\n try {\n const schemaPath = path.resolve(\"./src/schema.generated.ts\");\n if (fs.existsSync(schemaPath)) {\n const schema = await import(\"file://\" + schemaPath);\n usersTable = schema.users || schema.tables?.users;\n }\n } catch (e) {\n // ignore and fallback\n }\n\n if (!usersTable) {\n const pgServer = await import(\"@rebasepro/server-postgres\");\n usersTable = pgServer.users;\n }\n\n const passwordHashKey = (usersTable.passwordHash || \"passwordHash\" in usersTable) ? \"passwordHash\" : \"password_hash\";\n\n const result = await db.update(usersTable)\n .set({ [passwordHashKey]: hash })\n .where(eq(usersTable.email, email))\n .returning({\n id: usersTable.id,\n email: usersTable.email\n });\n\n if (result.length > 0) {\n console.log(\"✅ Password reset for: \" + result[0].email);\n ${!newPassword ? 'console.log(\" New password: \" + newPassword);' : \"\"}\n } else {\n console.log(\"✗ User not found: \" + email);\n }\n process.exit(0);\n}\n\nresetPassword().catch(console.error);\n`;\n\n const tmpScriptPath = path.join(backendDir, \".tmp-reset-password.ts\");\n fs.writeFileSync(tmpScriptPath, scriptContent, \"utf-8\");\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 Rebase Auth — Reset Password (Direct DB Fallback)\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Email:\")} ${email}`);\n if (newPassword) {\n console.log(` ${chalk.gray(\"Password:\")} ${\"*\".repeat(newPassword.length)}`);\n }\n console.log(\"\");\n\n const child = spawn(tsxBin, [tmpScriptPath], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n\n return new Promise((resolve) => {\n child.on(\"close\", (code) => {\n // Clean up temp script\n try { fs.unlinkSync(tmpScriptPath); } catch { /* ignore */ }\n if (code !== 0) {\n process.exit(code ?? 1);\n }\n resolve();\n });\n });\n } catch (err) {\n console.error(chalk.red(\"✗ Direct database update failed.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\nfunction printAuthHelp() {\n console.log(`\n${chalk.bold(\"rebase auth\")} — Authentication management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase auth ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"reset-password\")} Reset a user's password\n\n${chalk.green.bold(\"reset-password Options\")}\n ${chalk.blue(\"--email, -e\")} User's email address\n ${chalk.blue(\"--password, -p\")} New password (default: NewPassword123!)\n\n${chalk.green.bold(\"Examples\")}\n rebase auth reset-password user@example.com\n rebase auth reset-password --email user@example.com --password MyNewPass!\n`);\n}\n","/**\n * CLI command: rebase doctor\n *\n * Detects three-way schema drift between collection definitions,\n * the generated Drizzle schema, and the live PostgreSQL database.\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile\n} from \"../utils/project\";\n\nexport async function doctorCommand(rawArgs: string[]): Promise<void> {\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));\n process.exit(1);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n try {\n const isTs = pluginCli.endsWith(\".ts\");\n if (isTs) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n } else {\n await execa(\"node\", [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n } catch {\n // If the process exits with an error code, execa will throw,\n // but inherit stdio means the user already saw the output.\n process.exit(1);\n }\n}\n","import chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport inquirer from \"inquirer\";\nimport { createRequire } from \"module\";\n\nconst require = createRequire(import.meta.url);\n\n/** Supported agent environments and their target directories. */\nconst AGENTS = {\n cursor: {\n label: \"Cursor\",\n detectDir: \".cursor\",\n targetDir: \".cursor/rules\",\n /** Cursor uses .mdc files (Markdown with Context). */\n transformFile: (skillName: string, content: string) => ({\n fileName: `${skillName}.mdc`,\n content\n })\n },\n claude: {\n label: \"Claude Code\",\n detectDir: \".claude\",\n targetDir: \".claude/skills\",\n /** Claude Code uses the standard SKILL.md format in subdirectories. */\n transformFile: (skillName: string, content: string) => ({\n fileName: path.join(skillName, \"SKILL.md\"),\n content\n })\n },\n windsurf: {\n label: \"Windsurf\",\n detectDir: \".windsurf\",\n targetDir: \".windsurf/rules\",\n /** Windsurf uses plain .md files. */\n transformFile: (skillName: string, content: string) => ({\n fileName: `${skillName}.md`,\n content\n })\n },\n gemini: {\n label: \"Gemini CLI / Antigravity\",\n detectDir: \".agents\",\n targetDir: \".agents/skills\",\n /** Gemini uses the standard SKILL.md format in subdirectories. */\n transformFile: (skillName: string, content: string) => ({\n fileName: path.join(skillName, \"SKILL.md\"),\n content\n })\n }\n} as const;\n\ntype AgentKey = keyof typeof AGENTS;\n\n/**\n * Resolve the path to the skills directory from @rebasepro/agent-skills.\n * Works in both workspace (symlink) and published (real files) layouts.\n */\nfunction getSkillsSourceDir(): string {\n const pkgJsonPath = require.resolve(\"@rebasepro/agent-skills/package.json\");\n const pkgRoot = path.dirname(pkgJsonPath);\n const skillsDir = path.join(pkgRoot, \"skills\");\n\n if (!fs.existsSync(skillsDir)) {\n throw new Error(\n `Skills directory not found at ${skillsDir}. ` +\n `Make sure @rebasepro/agent-skills is installed.`\n );\n }\n\n return skillsDir;\n}\n\n/** Read all skill directories and return their names + content. */\nfunction loadSkills(skillsDir: string): Array<{ name: string; content: string }> {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n const skills: Array<{ name: string; content: string }> = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const skillMdPath = path.join(skillsDir, entry.name, \"SKILL.md\");\n if (!fs.existsSync(skillMdPath)) continue;\n skills.push({\n name: entry.name,\n content: fs.readFileSync(skillMdPath, \"utf-8\")\n });\n }\n\n return skills;\n}\n\n/** Detect which agent environments already exist in the project. */\nfunction detectAgents(projectDir: string): AgentKey[] {\n const detected: AgentKey[] = [];\n for (const [key, agent] of Object.entries(AGENTS)) {\n if (fs.existsSync(path.join(projectDir, agent.detectDir))) {\n detected.push(key as AgentKey);\n }\n }\n return detected;\n}\n\n/** Install skills for a specific agent into the project directory. */\nfunction installForAgent(\n agentKey: AgentKey,\n skills: Array<{ name: string; content: string }>,\n projectDir: string\n): number {\n const agent = AGENTS[agentKey];\n const targetBase = path.join(projectDir, agent.targetDir);\n\n // Ensure the target directory exists\n fs.mkdirSync(targetBase, { recursive: true });\n\n let count = 0;\n for (const skill of skills) {\n const { fileName, content } = agent.transformFile(skill.name, skill.content);\n const targetPath = path.join(targetBase, fileName);\n\n // Ensure parent directory exists (for subdirectory-based formats)\n fs.mkdirSync(path.dirname(targetPath), { recursive: true });\n fs.writeFileSync(targetPath, content, \"utf-8\");\n count++;\n }\n\n return count;\n}\n\nexport async function skillsCommand(subcommand: string | undefined, _args: string[]) {\n switch (subcommand) {\n case \"install\":\n await skillsInstall();\n break;\n case \"--help\":\n case undefined:\n printSkillsHelp();\n break;\n default:\n console.log(chalk.red(`Unknown skills subcommand: ${subcommand}`));\n console.log(\"\");\n printSkillsHelp();\n }\n}\n\nasync function skillsInstall() {\n const projectDir = process.cwd();\n\n // 1. Load skills from @rebasepro/agent-skills\n let skillsDir: string;\n try {\n skillsDir = getSkillsSourceDir();\n } catch (err) {\n console.error(`${chalk.red.bold(\"ERROR\")} ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n\n const skills = loadSkills(skillsDir);\n if (skills.length === 0) {\n console.error(`${chalk.red.bold(\"ERROR\")} No skills found in ${skillsDir}`);\n process.exit(1);\n }\n\n // 2. Detect existing agent environments\n let agents = detectAgents(projectDir);\n\n // 3. If none detected, ask the user\n if (agents.length === 0) {\n const choices = Object.entries(AGENTS).map(([key, agent]) => ({\n name: agent.label,\n value: key,\n checked: false\n }));\n\n const { selectedAgents } = await inquirer.prompt([{\n type: \"checkbox\",\n name: \"selectedAgents\",\n message: \"No AI agent configuration detected. Which agents do you use?\",\n choices,\n validate: (input: string[]) => {\n if (input.length === 0) return \"Please select at least one agent.\";\n return true;\n }\n }]);\n\n agents = selectedAgents as AgentKey[];\n }\n\n // 4. Install skills for each agent\n console.log(\"\");\n console.log(chalk.gray(` Found ${chalk.white(skills.length)} Rebase skills`));\n console.log(\"\");\n\n for (const agentKey of agents) {\n const agent = AGENTS[agentKey];\n const count = installForAgent(agentKey, skills, projectDir);\n console.log(` ${chalk.green(\"✓\")} ${chalk.bold(agent.label)} — ${count} skills installed to ${chalk.gray(agent.targetDir)}`);\n }\n\n console.log(\"\");\n console.log(chalk.gray(\" Skills are project-local. Commit them to share with your team.\"));\n console.log(chalk.gray(\" Re-run this command anytime to update to the latest skills.\"));\n console.log(\"\");\n}\n\nfunction printSkillsHelp() {\n console.log(`\n${chalk.bold(\"rebase skills\")} — Manage AI agent skills\n\n${chalk.green.bold(\"Usage\")}\n rebase skills ${chalk.blue(\"<subcommand>\")}\n\n${chalk.green.bold(\"Subcommands\")}\n ${chalk.blue.bold(\"install\")} Install Rebase agent skills for your AI coding assistant\n Supports: Cursor, Claude Code, Windsurf, Gemini CLI, Antigravity\n\n${chalk.green.bold(\"Examples\")}\n ${chalk.cyan(\"rebase skills install\")}\n`);\n}\n","/**\n * CLI command: rebase api-keys <action>\n *\n * Subcommands:\n * list — List all API keys (masked)\n * create — Create a new API key\n * revoke — Revoke an existing API key\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireProjectRoot,\n findEnvFile\n} from \"../utils/project\";\nimport fs from \"fs\";\nimport path from \"path\";\n\n/* ═══════════════════════════════════════════════════════════════\n Env helper — reads SERVICE_KEY and PORT from .env\n ═══════════════════════════════════════════════════════════════ */\n\nfunction loadEnv(projectRoot: string): Record<string, string> {\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = {};\n if (envFile && fs.existsSync(envFile)) {\n const content = fs.readFileSync(envFile, \"utf-8\");\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const idx = trimmed.indexOf(\"=\");\n if (idx > 0) {\n const key = trimmed.slice(0, idx).trim();\n let value = trimmed.slice(idx + 1).trim();\n // Strip surrounding quotes\n if ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.slice(1, -1);\n }\n env[key] = value;\n }\n }\n }\n return env;\n}\n\nfunction resolveBaseUrl(env: Record<string, string>): string {\n const port = env.PORT || env.REBASE_PORT || \"3001\";\n return env.REBASE_BASE_URL || `http://localhost:${port}`;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Entry\n ═══════════════════════════════════════════════════════════════ */\n\nexport async function apiKeysCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printApiKeysHelp();\n return;\n }\n\n switch (subcommand) {\n case \"list\":\n await listKeys(rawArgs);\n break;\n case \"create\":\n await createKey(rawArgs);\n break;\n case \"revoke\":\n await revokeKey(rawArgs);\n break;\n default:\n console.error(chalk.red(`Unknown api-keys command: ${subcommand}`));\n console.log(\"\");\n printApiKeysHelp();\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n list\n ═══════════════════════════════════════════════════════════════ */\n\nasync function listKeys(_rawArgs: string[]): Promise<void> {\n const projectRoot = requireProjectRoot();\n const env = loadEnv(projectRoot);\n const baseUrl = resolveBaseUrl(env);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n\n if (!serviceKey) {\n console.error(chalk.red(\"✗ SERVICE_KEY not found in .env — required for admin operations.\"));\n process.exit(1);\n }\n\n try {\n const res = await fetch(`${baseUrl}/api/admin/api-keys`, {\n headers: { Authorization: `Bearer ${serviceKey}` }\n });\n if (!res.ok) {\n const body = await res.text();\n console.error(chalk.red(`✗ Failed to list API keys: ${res.status} ${body}`));\n process.exit(1);\n }\n\n const { keys } = await res.json() as { keys: Array<{\n id: string; name: string; key_prefix: string;\n permissions: Array<{ collection: string; operations: string[] }>;\n rate_limit: number | null; revoked_at: string | null;\n expires_at: string | null; last_used_at: string | null;\n created_at: string;\n }>};\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 API Keys\"));\n console.log(\"\");\n\n if (keys.length === 0) {\n console.log(chalk.gray(\" No API keys found.\"));\n console.log(\"\");\n return;\n }\n\n for (const key of keys) {\n const status = key.revoked_at ? chalk.red(\"revoked\")\n : (key.expires_at && new Date(key.expires_at) < new Date()) ? chalk.yellow(\"expired\")\n : chalk.green(\"active\");\n\n const perms = key.permissions.map(p =>\n `${p.collection}(${p.operations.join(\",\")})`\n ).join(\", \");\n\n console.log(` ${chalk.bold(key.name)} ${chalk.gray(`[${key.key_prefix}•••]`)} ${status}`);\n console.log(` ${chalk.gray(\"ID:\")} ${key.id}`);\n console.log(` ${chalk.gray(\"Permissions:\")} ${perms || \"none\"}`);\n console.log(` ${chalk.gray(\"Created:\")} ${new Date(key.created_at).toLocaleDateString()}`);\n if (key.last_used_at) {\n console.log(` ${chalk.gray(\"Last used:\")} ${new Date(key.last_used_at).toLocaleDateString()}`);\n }\n console.log(\"\");\n }\n } catch (e: unknown) {\n console.error(chalk.red(`✗ ${e instanceof Error ? e.message : String(e)}`));\n console.error(chalk.gray(\" Is the Rebase server running?\"));\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n create\n ═══════════════════════════════════════════════════════════════ */\n\nasync function createKey(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--name\": String,\n \"--permissions\": String,\n \"--full-access\": Boolean,\n \"--admin\": Boolean,\n \"--rate-limit\": Number,\n \"--expires\": String,\n \"-n\": \"--name\"\n },\n {\n argv: rawArgs.slice(4), // skip \"node rebase api-keys create\"\n permissive: true\n }\n );\n\n const name = args[\"--name\"] || args._[0];\n const permissionsRaw = args[\"--permissions\"];\n\n if (!name) {\n console.error(chalk.red(\"✗ Name is required.\"));\n console.log(\"\");\n console.log(chalk.gray(' Usage: rebase api-keys create --name \"My Key\" --permissions \\'[{\"collection\":\"*\",\"operations\":[\"read\"]}]\\''));\n process.exit(1);\n }\n\n let permissions: Array<{ collection: string; operations: string[] }>;\n if (permissionsRaw) {\n try {\n permissions = JSON.parse(permissionsRaw);\n } catch {\n console.error(chalk.red(\"✗ Invalid --permissions JSON.\"));\n console.log(chalk.gray(' Example: \\'[{\"collection\":\"*\",\"operations\":[\"read\",\"write\"]}]\\''));\n process.exit(1);\n return; // unreachable but satisfies TS\n }\n } else if (args[\"--full-access\"]) {\n permissions = [{ collection: \"*\", operations: [\"read\", \"write\", \"delete\"] }];\n } else {\n // No silent full-access default: a \"scoped keys\" feature should not\n // hand out read/write/delete on every collection when the flag is\n // simply forgotten. Full access must be asked for by name.\n console.error(chalk.red(\"✗ Specify what the key may access: --permissions '<json>' or --full-access.\"));\n console.log(\"\");\n console.log(chalk.gray(' Scoped: rebase api-keys create -n \"Analytics\" --permissions \\'[{\"collection\":\"events\",\"operations\":[\"read\"]}]\\''));\n console.log(chalk.gray(' Functions: add {\"collection\":\"functions/<name>\",\"operations\":[\"write\"]} to invoke a custom function'));\n console.log(chalk.gray(' Storage: add {\"collection\":\"storage\",\"operations\":[\"read\",\"write\"]} for file storage'));\n console.log(chalk.gray(' Full access: rebase api-keys create -n \"CI\" --full-access'));\n process.exit(1);\n return; // unreachable but satisfies TS\n }\n\n let expires_at: string | null = null;\n const expiresFlag = args[\"--expires\"];\n if (expiresFlag) {\n const days: Record<string, number> = { \"7d\": 7, \"30d\": 30, \"90d\": 90, \"1y\": 365 };\n if (days[expiresFlag]) {\n expires_at = new Date(Date.now() + days[expiresFlag] * 86400000).toISOString();\n } else {\n const parsed = new Date(expiresFlag);\n if (isNaN(parsed.getTime())) {\n console.error(chalk.red(\"✗ Invalid --expires value. Use 7d, 30d, 90d, 1y, or an ISO date.\"));\n process.exit(1);\n }\n expires_at = parsed.toISOString();\n }\n }\n\n const projectRoot = requireProjectRoot();\n const env = loadEnv(projectRoot);\n const baseUrl = resolveBaseUrl(env);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n\n if (!serviceKey) {\n console.error(chalk.red(\"✗ SERVICE_KEY not found in .env — required for admin operations.\"));\n process.exit(1);\n }\n\n try {\n const body: Record<string, unknown> = {\n name,\n permissions,\n admin: args[\"--admin\"] ?? false,\n rate_limit: args[\"--rate-limit\"] ?? null,\n expires_at\n };\n\n const res = await fetch(`${baseUrl}/api/admin/api-keys`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${serviceKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(body)\n });\n\n if (!res.ok) {\n const errBody = await res.text();\n console.error(chalk.red(`✗ Failed to create API key: ${res.status} ${errBody}`));\n process.exit(1);\n }\n\n const { key } = await res.json() as { key: { name: string; key: string; key_prefix: string; id: string } };\n\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key created successfully\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Name:\")} ${key.name}`);\n console.log(` ${chalk.gray(\"ID:\")} ${key.id}`);\n console.log(` ${chalk.gray(\"Prefix:\")} ${key.key_prefix}`);\n console.log(\"\");\n console.log(chalk.bold.yellow(\" ⚠ Copy your key now — it won't be shown again:\"));\n console.log(\"\");\n console.log(` ${chalk.cyan(key.key)}`);\n console.log(\"\");\n } catch (e: unknown) {\n console.error(chalk.red(`✗ ${e instanceof Error ? e.message : String(e)}`));\n console.error(chalk.gray(\" Is the Rebase server running?\"));\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n revoke\n ═══════════════════════════════════════════════════════════════ */\n\nasync function revokeKey(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--id\": String\n },\n {\n argv: rawArgs.slice(4), // skip \"node rebase api-keys revoke\"\n permissive: true\n }\n );\n\n const id = args[\"--id\"] || args._[0];\n\n if (!id) {\n console.error(chalk.red(\"✗ Key ID is required.\"));\n console.log(\"\");\n console.log(chalk.gray(\" Usage: rebase api-keys revoke <key-id>\"));\n process.exit(1);\n }\n\n const projectRoot = requireProjectRoot();\n const env = loadEnv(projectRoot);\n const baseUrl = resolveBaseUrl(env);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n\n if (!serviceKey) {\n console.error(chalk.red(\"✗ SERVICE_KEY not found in .env — required for admin operations.\"));\n process.exit(1);\n }\n\n try {\n const res = await fetch(`${baseUrl}/api/admin/api-keys/${encodeURIComponent(id)}`, {\n method: \"DELETE\",\n headers: { Authorization: `Bearer ${serviceKey}` }\n });\n\n if (!res.ok) {\n const errBody = await res.text();\n console.error(chalk.red(`✗ Failed to revoke API key: ${res.status} ${errBody}`));\n process.exit(1);\n }\n\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key revoked successfully\"));\n console.log(` ${chalk.gray(\"ID:\")} ${id}`);\n console.log(\"\");\n } catch (e: unknown) {\n console.error(chalk.red(`✗ ${e instanceof Error ? e.message : String(e)}`));\n console.error(chalk.gray(\" Is the Rebase server running?\"));\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Help\n ═══════════════════════════════════════════════════════════════ */\n\nfunction printApiKeysHelp() {\n console.log(`\n${chalk.bold(\"rebase api-keys\")} — Manage Service API Keys\n\n${chalk.green.bold(\"Usage\")}\n rebase api-keys ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List all API keys\n ${chalk.blue.bold(\"create\")} Create a new API key\n ${chalk.blue.bold(\"revoke\")} Revoke an API key\n\n${chalk.green.bold(\"create Options\")}\n ${chalk.blue(\"--name, -n\")} Key name ${chalk.gray(\"(required)\")}\n ${chalk.blue(\"--permissions\")} JSON array of permissions ${chalk.gray(\"(required unless --full-access)\")}\n ${chalk.gray('Collections by slug; custom functions as \"functions\" or \"functions/<name>\"')}\n ${chalk.blue(\"--full-access\")} Grant read/write/delete on every collection and function\n ${chalk.blue(\"--admin\")} Grant admin role (admin routes + RLS admin policies)\n ${chalk.blue(\"--rate-limit\")} Requests per 15-min window ${chalk.gray(\"(default: 1000)\")}\n ${chalk.blue(\"--expires\")} Expiration: 7d, 30d, 90d, 1y, or ISO date\n\n${chalk.green.bold(\"revoke Options\")}\n ${chalk.blue(\"--id\")} API key ID to revoke ${chalk.gray(\"(or positional arg)\")}\n\n${chalk.green.bold(\"Examples\")}\n rebase api-keys list\n rebase api-keys create --name \"Analytics\" --permissions '[{\"collection\":\"events\",\"operations\":[\"read\"]}]'\n rebase api-keys create -n \"Full Access\" --full-access --expires 90d\n rebase api-keys revoke abc123-def456\n`);\n}\n","/**\n * `rebase cloud` auth subcommands: login, logout, whoami.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n resolveCloudUrl,\n createCloudClient,\n requireClient,\n setCurrentContext,\n setContextOrg,\n getContextOrg,\n readLink,\n success,\n fail,\n keyValues,\n reportError\n} from \"./context\";\n\nexport async function loginCommand(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--email\": String,\n\"--password\": String,\n\"-e\": \"--email\",\n\"-p\": \"--password\" },\n { argv: rawArgs.slice(3),\npermissive: true }\n );\n const url = resolveCloudUrl(rawArgs);\n\n console.log(\"\");\n console.log(` Signing in to ${chalk.cyan(url)}`);\n console.log(\"\");\n\n // Collect any missing credentials interactively.\n const prompts: Array<Record<string, unknown>> = [];\n if (!args[\"--email\"]) {\n prompts.push({ type: \"input\",\nname: \"email\",\nmessage: \"Email:\" });\n }\n if (!args[\"--password\"]) {\n prompts.push({ type: \"password\",\nname: \"password\",\nmessage: \"Password:\",\nmask: \"•\" });\n }\n const answers = prompts.length\n ? await inquirer.prompt(prompts as unknown as Parameters<typeof inquirer.prompt>[0])\n : {};\n\n const email = (args[\"--email\"] || (answers as { email?: string }).email || \"\").trim();\n const password = args[\"--password\"] || (answers as { password?: string }).password || \"\";\n\n if (!email || !password) {\n fail(\"Email and password are required.\");\n }\n\n const client = createCloudClient(url);\n try {\n const { user } = await client.auth.signInWithEmail(email, password);\n setCurrentContext(url);\n\n // Convenience: if the account belongs to exactly one org, make it active.\n try {\n const orgs = await client.data.collection(\"organizations\").find({ limit: 2 });\n if (orgs.data.length === 1 && !getContextOrg(url)) {\n setContextOrg(url, String(orgs.data[0].id));\n }\n } catch {\n // non-fatal — org selection is optional\n }\n\n success(`Logged in as ${chalk.bold(user.email ?? email)}`);\n keyValues([\n [\"Host\", url],\n [\"User\", user.email ?? undefined],\n [\"Active org\", getContextOrg(url)]\n ]);\n console.log(\"\");\n } catch (e) {\n // Auth failures are the common case — give a clean message, not a stack.\n const err = e as { status?: number; message?: string };\n if (err?.status === 401) {\n fail(\"Invalid email or password.\");\n }\n reportError(e, \"Login failed\");\n }\n}\n\nexport async function logoutCommand(rawArgs: string[]): Promise<void> {\n const url = resolveCloudUrl(rawArgs);\n const client = createCloudClient(url);\n if (!client.auth.getSession()) {\n console.log(\"\");\n console.log(chalk.gray(` Not logged in to ${url}.`));\n console.log(\"\");\n return;\n }\n try {\n await client.auth.signOut();\n } catch {\n // signOut clears local state even if the network call fails\n }\n success(`Logged out of ${url}`);\n}\n\nexport async function whoamiCommand(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n try {\n const user = await client.auth.getUser();\n if (!user) fail(\"Session is no longer valid.\", \"Run `rebase cloud login` again.\");\n const link = readLink();\n console.log(\"\");\n console.log(chalk.bold(\" 🔐 Rebase Cloud session\"));\n console.log(\"\");\n keyValues([\n [\"Host\", url],\n [\"User\", user.email ?? undefined],\n [\"User ID\", user.uid],\n [\"Roles\", user.roles?.length ? user.roles.join(\", \") : undefined],\n [\"Active org\", getContextOrg(url)],\n [\"Linked project\", link ? `${link.projectName ?? \"\"} (${link.projectId})`.trim() : undefined]\n ]);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to fetch session\");\n }\n}\n","/**\n * `rebase cloud` context subcommands: link, unlink, use, open.\n *\n * `link` associates the current directory with a cloud project by writing\n * `.rebase/cloud.json`; deploy/logs/status then operate on it with no flags.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n resolveProjectRef,\n resolveCloudUrl,\n writeLink,\n removeLink,\n readLink,\n projectLinkPath,\n setContextOrg,\n getContextOrg,\n openUrl,\n success,\n fail,\n reportError\n} from \"./context\";\n\ninterface ProjectRow {\n id: string | number;\n name?: string;\n subdomain?: string;\n organization?: string | number;\n status?: string;\n}\n\nexport async function linkCommand(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(3),\npermissive: true });\n const { client, url } = await requireClient(rawArgs);\n\n try {\n let project: ProjectRow | undefined;\n\n if (args[\"--project\"]) {\n const projectId = await resolveProjectRef(args[\"--project\"], client);\n project = (await client.data.collection(\"projects\").findById(projectId)) as unknown as ProjectRow | undefined;\n if (!project) fail(`Project ${args[\"--project\"]} not found.`);\n } else {\n const org = getContextOrg(url);\n const projects = (await client.data.collection(\"projects\").find({\n where: org ? { organization: [\"==\", org] } : undefined,\n limit: 100\n })).data as unknown as ProjectRow[];\n\n if (projects.length === 0) {\n fail(\n \"No projects found for your account.\",\n `Create one with ${chalk.bold(\"rebase cloud projects create\")}.`\n );\n }\n\n const { picked } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"picked\",\n message: \"Select a project to link:\",\n choices: projects.map((p) => ({\n name: `${p.name ?? \"(unnamed)\"} ${chalk.gray(String(p.subdomain ?? \"\"))}`,\n value: p\n }))\n }\n ] as unknown as Parameters<typeof inquirer.prompt>[0]);\n project = picked as ProjectRow;\n }\n\n if (!project) fail(\"No project selected.\");\n\n writeLink({\n url,\n projectId: String(project.id),\n slug: project.subdomain,\n projectName: project.name,\n orgId: project.organization !== undefined ? String(project.organization) : undefined\n });\n\n success(`Linked to ${chalk.bold(project.name ?? project.subdomain ?? \"\")}`);\n console.log(chalk.gray(` Wrote ${projectLinkPath()}`));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to link project\");\n }\n}\n\nexport function unlinkCommand(): void {\n const link = readLink();\n if (!link) {\n console.log(\"\");\n console.log(chalk.gray(\" This directory is not linked to a cloud project.\"));\n console.log(\"\");\n return;\n }\n removeLink();\n success(\"Unlinked from cloud project\");\n}\n\nexport async function selectOrgCommand(rawArgs: string[]): Promise<void> {\n // positionals after \"cloud\" are [use, <org>]; take the token after \"use\".\n const target = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[1];\n const { client, url } = await requireClient(rawArgs);\n\n try {\n const orgs = (await client.data.collection(\"organizations\").find({ limit: 100 })).data as unknown as Array<{\n id: string | number;\n name?: string;\n slug?: string;\n }>;\n\n if (orgs.length === 0) fail(\"You are not a member of any organization.\");\n\n let chosen = target\n ? orgs.find((o) => String(o.id) === target || o.slug === target)\n : undefined;\n\n if (!chosen && !target) {\n const { picked } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"picked\",\n message: \"Select the active organization:\",\n choices: orgs.map((o) => ({\n name: `${o.name ?? \"(unnamed)\"} ${chalk.gray(`${o.slug ?? \"\"} · ${o.id}`)}`,\n value: o\n }))\n }\n ] as unknown as Parameters<typeof inquirer.prompt>[0]);\n chosen = picked;\n }\n\n if (!chosen) fail(`Organization \"${target}\" not found.`);\n\n setContextOrg(url, String(chosen.id));\n success(`Active organization set to ${chalk.bold(chosen.name ?? chosen.id)}`);\n } catch (e) {\n reportError(e, \"Failed to set organization\");\n }\n}\n\n/** Open the Rebase Cloud dashboard (or the linked project) in a browser. */\nexport function openCommand(rawArgs: string[]): void {\n const url = resolveCloudUrl(rawArgs);\n const link = readLink();\n const target = link ? `${url}/projects/${link.projectId}` : url;\n openUrl(target);\n}\n","/**\n * `rebase cloud projects` — list / create / info / delete.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n resolveProjectRef,\n getContextOrg,\n readLink,\n writeLink,\n colorStatus,\n keyValues,\n fetchTenantBaseDomain,\n projectHost,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\ninterface ProjectRow {\n id: string | number;\n name?: string;\n subdomain?: string;\n /**\n * Where the project is actually served. Computed by the control plane from\n * the project's cluster, which the CLI cannot read itself (admin-only RLS).\n * Absent on control planes older than that hook — `projectHost` falls back.\n */\n host?: string;\n customDomain?: string;\n gitRepoUrl?: string;\n gitBranch?: string;\n provider?: string;\n region?: string;\n status?: string;\n organization?: string | number;\n createdById?: string;\n}\n\n/* ─── list ─────────────────────────────────────────────────────── */\n\nexport async function listProjects(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n const org = getContextOrg(url);\n try {\n const [projects, baseDomain] = await Promise.all([\n client.data.collection(\"projects\").find({\n where: org ? { organization: [\"==\", org] } : undefined,\n orderBy: [\"name\", \"asc\"],\n limit: 100\n }).then((res) => res.data as unknown as ProjectRow[]),\n fetchTenantBaseDomain(client, url)\n ]);\n\n console.log(\"\");\n console.log(chalk.bold(\" 📦 Projects\") + (org ? chalk.gray(` (org ${org})`) : \"\"));\n console.log(\"\");\n\n if (projects.length === 0) {\n console.log(chalk.gray(\" No projects yet. Create one with `rebase cloud projects create`.\"));\n console.log(\"\");\n return;\n }\n\n const linkedId = readLink()?.projectId;\n for (const p of projects) {\n const marker = String(p.id) === linkedId ? chalk.green(\" ●\") : \" \";\n console.log(`${marker}${chalk.bold(p.name ?? \"(unnamed)\")} ${chalk.gray(`[${p.subdomain ?? p.id}]`)} ${colorStatus(p.status)}`);\n console.log(` ${chalk.gray(projectHost(p, baseDomain) ?? \"—\")}${p.provider ? chalk.gray(` · ${p.provider}`) : \"\"}`);\n }\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list projects\");\n }\n}\n\n/* ─── create ───────────────────────────────────────────────────── */\n\n/** Default region + VM size per provider (both are required on create). */\nfunction providerDefaults(provider: string): { region: string; vmSize: string } {\n switch (provider) {\n case \"gcp\":\n return { region: \"europe-west1\",\nvmSize: \"e2-small\" };\n case \"aws\":\n return { region: \"us-east-1\",\nvmSize: \"t3.small\" };\n default:\n return { region: \"nbg1\",\nvmSize: \"cx21\" };\n }\n}\n\nexport async function createProject(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--name\": String,\n \"--subdomain\": String,\n \"--repo\": String,\n \"--branch\": String,\n \"--provider\": String,\n \"--region\": String,\n \"--vm-size\": String,\n \"--org\": String,\n \"--link\": Boolean,\n \"-n\": \"--name\"\n },\n { argv: rawArgs.slice(4),\npermissive: true }\n );\n\n const { client, url } = await requireClient(rawArgs);\n const org = args[\"--org\"] || getContextOrg(url);\n if (!org) {\n fail(\n \"No organization selected.\",\n `Pass ${chalk.bold(\"--org <id>\")} or run ${chalk.bold(\"rebase cloud use\")}.`\n );\n }\n\n // Prompt only for the essentials, and only when attached to a terminal —\n // a headless `projects create --name X --subdomain Y` must never block.\n // repo/branch/provider are optional and default sensibly.\n const prompts: Array<Record<string, unknown>> = [];\n if (!args[\"--name\"]) prompts.push({ type: \"input\",\nname: \"name\",\nmessage: \"Project name:\" });\n if (!args[\"--subdomain\"]) prompts.push({ type: \"input\",\nname: \"subdomain\",\nmessage: \"Subdomain:\" });\n const answers = prompts.length && process.stdin.isTTY\n ? await inquirer.prompt(prompts as unknown as Parameters<typeof inquirer.prompt>[0])\n : {};\n const a = answers as Record<string, string>;\n\n const name = (args[\"--name\"] || a.name || \"\").trim();\n const subdomain = (args[\"--subdomain\"] || a.subdomain || \"\").trim().toLowerCase();\n const gitRepoUrl = (args[\"--repo\"] || a.repo || \"\").trim();\n const gitBranch = (args[\"--branch\"] || a.branch || \"main\").trim();\n const provider = (args[\"--provider\"] || a.provider || \"hetzner\").trim();\n // region + vmSize are required by the control plane; default sensibly per\n // provider so a headless `projects create` needs only name + subdomain.\n const defaults = providerDefaults(provider);\n const region = (args[\"--region\"] || defaults.region).trim();\n const vmSize = (args[\"--vm-size\"] || defaults.vmSize).trim();\n\n if (!name || !subdomain) {\n fail(\"Name and subdomain are required.\");\n }\n\n // Validate subdomain availability up front for a clean error.\n try {\n const check = await client.functions.invoke<{ available: boolean; reason?: string }>(\n \"check-subdomain\",\n { subdomain }\n );\n if (!check.available) {\n fail(\n `Subdomain \"${subdomain}\" is not available${check.reason ? ` (${check.reason})` : \"\"}.`\n );\n }\n } catch {\n // If the control plane has no such function, skip the pre-check —\n // the collection hook still enforces uniqueness on create.\n }\n\n try {\n const user = await client.auth.getUser();\n if (!user) fail(\"Session is no longer valid.\", \"Run `rebase cloud login` again.\");\n const created = (await client.data.collection(\"projects\").create({\n name,\n subdomain,\n gitRepoUrl,\n gitBranch,\n provider,\n region,\n vmSize,\n organization: org,\n createdById: user.uid,\n status: \"provisioning\"\n })) as unknown as ProjectRow;\n\n success(`Created project ${chalk.bold(name)}`);\n keyValues([\n [\"Slug\", String(created.subdomain ?? \"\")],\n [\"URL\", projectHost(created, await fetchTenantBaseDomain(client, url))],\n [\"Provider\", provider],\n [\"Branch\", gitBranch]\n ]);\n\n if (args[\"--link\"]) {\n writeLink({ url,\nprojectId: String(created.id),\nslug: created.subdomain,\nprojectName: name,\norgId: String(org) });\n console.log(chalk.gray(\" Linked this directory to the new project.\"));\n }\n console.log(\"\");\n console.log(chalk.gray(` Deploy it with: ${chalk.bold(`rebase cloud deploy --project ${created.subdomain ?? created.id}`)}`));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to create project\");\n }\n}\n\n/* ─── info ─────────────────────────────────────────────────────── */\n\nexport async function projectInfo(rawArgs: string[], projectRef: string): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n try {\n const projectId = await resolveProjectRef(projectRef, client);\n const p = (await client.data.collection(\"projects\").findById(projectId)) as unknown as ProjectRow | undefined;\n if (!p) fail(`Project ${projectRef} not found.`);\n\n const [db, lastDeploy, baseDomain] = await Promise.all([\n firstRow(client, \"databases\", projectId),\n latestDeployment(client, projectId),\n fetchTenantBaseDomain(client, url)\n ]);\n\n console.log(\"\");\n console.log(` ${chalk.bold(p.name ?? \"(unnamed)\")} ${chalk.gray(`[${p.subdomain ?? p.id}]`)} ${colorStatus(p.status)}`);\n console.log(\"\");\n keyValues([\n [\"Subdomain\", projectHost(p, baseDomain)],\n [\"Custom domain\", p.customDomain],\n [\"Repository\", p.gitRepoUrl],\n [\"Branch\", p.gitBranch],\n [\"Provider\", p.provider],\n [\"Region\", p.region],\n [\"Organization\", p.organization !== undefined ? String(p.organization) : undefined],\n [\"Database\", db ? `${db.type} (${colorStatus(db.connectionStatus as string)})` : \"none\"],\n [\"Last deploy\", lastDeploy ? `${colorStatus(lastDeploy.status)} · ${fmtDate(lastDeploy.createdAt)}` : \"never\"]\n ]);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to load project\");\n }\n}\n\n/* ─── delete ───────────────────────────────────────────────────── */\n\nexport async function deleteProject(rawArgs: string[], projectRef: string): Promise<void> {\n const args = arg({ \"--yes\": Boolean,\n\"-y\": \"--yes\" }, { argv: rawArgs.slice(2),\npermissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await resolveProjectRef(projectRef, client);\n\n const p = (await client.data.collection(\"projects\").findById(projectId).catch(() => undefined)) as\n | ProjectRow\n | undefined;\n if (!p) fail(`Project ${projectRef} not found.`);\n\n if (!args[\"--yes\"]) {\n const { confirmed } = await inquirer.prompt([\n {\n type: \"confirm\",\n name: \"confirmed\",\n default: false,\n message: `Permanently delete project \"${p.name ?? projectRef}\" (${p.subdomain ?? projectRef})? This tears down its deployment.`\n }\n ] as unknown as Parameters<typeof inquirer.prompt>[0]);\n if (!confirmed) {\n console.log(chalk.gray(\" Aborted.\"));\n return;\n }\n }\n\n try {\n await client.data.collection(\"projects\").delete(projectId);\n success(`Deleted project ${chalk.bold(p.name ?? projectId)}`);\n } catch (e) {\n reportError(e, \"Failed to delete project\");\n }\n}\n\n/* ─── shared helpers (used by other subcommands too) ───────────── */\n\nexport async function firstRow(\n client: CloudClient,\n collection: string,\n projectId: string\n): Promise<Record<string, unknown> | undefined> {\n const res = await client.data.collection(collection).find({\n where: { project: [\"==\", projectId] },\n limit: 1\n });\n return res.data[0];\n}\n\nexport async function latestDeployment(\n client: CloudClient,\n projectId: string\n): Promise<{ id: string | number; status?: string; createdAt?: string; logs?: string } | undefined> {\n const res = await client.data.collection(\"deployments\").find({\n where: { project: [\"==\", projectId] },\n orderBy: [\"createdAt\", \"desc\"],\n limit: 1\n });\n return res.data[0] as { id: string | number; status?: string; createdAt?: string; logs?: string } | undefined;\n}\n\nexport function fmtDate(value: string | undefined): string {\n if (!value) return \"—\";\n const d = new Date(value);\n return isNaN(d.getTime()) ? value : d.toLocaleString();\n}\n","/**\n * `rebase cloud deploy` and `rebase cloud logs`.\n *\n * `deploy` triggers the control-plane `deploy` function, then tails the build\n * logs from the deployment record until it succeeds or fails. `logs` shows the\n * latest build log, or runtime logs with `--runtime`.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\nimport { spawn } from \"child_process\";\nimport { requireClient, resolveProjectRef, colorStatus, fail, reportError, type CloudClient } from \"./context\";\nimport { latestDeployment } from \"./projects\";\n\ninterface Deployment {\n id: string | number;\n status?: string;\n logs?: string;\n createdAt?: string;\n}\n\nconst POLL_INTERVAL_MS = 1500;\nconst POLL_TIMEOUT_MS = 15 * 60 * 1000; // 15 min hard stop\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nfunction run(cmd: string, cmdArgs: string[], cwd?: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(cmd, cmdArgs, { cwd,\nstdio: [\"ignore\", \"ignore\", \"pipe\"] });\n let stderr = \"\";\n child.stderr.on(\"data\", (d) => (stderr += d.toString()));\n child.on(\"error\", reject);\n child.on(\"close\", (code) => (code === 0 ? resolve() : reject(new Error(stderr || `${cmd} exited ${code}`))));\n });\n}\n\n/**\n * Package `sourceDir` into a gzipped tarball, honoring `.gitignore`/`.rebaseignore`\n * and always excluding `.git` and `node_modules`. Returns the temp archive path.\n */\nasync function createSourceTarball(sourceDir: string): Promise<string> {\n const dir = path.resolve(sourceDir);\n if (!fs.existsSync(dir)) fail(`Source directory not found: ${dir}`);\n\n const tarPath = path.join(os.tmpdir(), `rebase-src-${Date.now()}.tar.gz`);\n const tarArgs = [\"-czf\", tarPath, \"--exclude=.git\", \"--exclude=node_modules\"];\n for (const ignore of [\".gitignore\", \".rebaseignore\"]) {\n if (fs.existsSync(path.join(dir, ignore))) tarArgs.push(`--exclude-from=${ignore}`);\n }\n tarArgs.push(\".\");\n\n try {\n await run(\"tar\", tarArgs, dir);\n } catch (e) {\n fail(`Failed to package source: ${e instanceof Error ? e.message : String(e)}`);\n }\n return tarPath;\n}\n\n/** Upload a build-context tarball; returns the opaque `source` ref for deploy. */\nasync function uploadSource(url: string, token: string, projectId: string, tarPath: string): Promise<string> {\n const bytes = fs.readFileSync(tarPath);\n const sizeMb = (bytes.length / 1024 / 1024).toFixed(1);\n console.log(chalk.gray(` Uploading source (${sizeMb} MB)...`));\n const res = await fetch(`${url}/api/functions/deploy/upload?projectId=${encodeURIComponent(projectId)}`, {\n method: \"POST\",\n headers: { Authorization: `Bearer ${token}`,\n\"Content-Type\": \"application/gzip\" },\n body: bytes\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n fail(`Source upload failed (${res.status}): ${body || res.statusText}`);\n }\n const data = (await res.json()) as { source?: string };\n if (!data.source) fail(\"Upload endpoint did not return a source reference.\");\n return data.source;\n}\n\nexport async function deployCommand(rawArgs: string[], projectRef: string): Promise<void> {\n const args = arg(\n { \"--no-follow\": Boolean,\n\"--source\": String },\n { argv: rawArgs.slice(2),\npermissive: true }\n );\n const { client, url } = await requireClient(rawArgs);\n const projectId = await resolveProjectRef(projectRef, client);\n\n // Optional fly-style local source upload: `deploy --source .`\n let source: string | undefined;\n if (args[\"--source\"]) {\n const tarPath = await createSourceTarball(args[\"--source\"]);\n try {\n const token = client.auth.getSession()?.accessToken;\n if (!token) fail(\"Not authenticated.\", \"Run `rebase cloud login`.\");\n source = await uploadSource(url, token, projectId, tarPath);\n } finally {\n fs.rmSync(tarPath, { force: true });\n }\n }\n\n console.log(\"\");\n console.log(` 🚀 Triggering deployment for project ${chalk.bold(projectRef)}${source ? \" from uploaded source\" : \"\"}...`);\n\n let deploymentId: string;\n try {\n const res = await client.functions.invoke<{ success: boolean; deployment: { id: string | number } }>(\n \"deploy\",\n source ? { projectId,\nsource } : { projectId }\n );\n if (!res?.deployment?.id) fail(\"Control plane did not return a deployment id.\");\n deploymentId = String(res.deployment.id);\n } catch (e) {\n const err = e as { status?: number; message?: string; code?: string };\n if (err?.status === 409) {\n fail(\"A deployment is already in progress for this project.\");\n }\n if (err?.status === 402) {\n // Billing gate: no card on file, card declined, or needs auth.\n fail(\n err.message || \"Payment required before deploying.\",\n \"Attach a card once with `rebase cloud billing setup`, then deploy again.\"\n );\n }\n reportError(e, \"Failed to trigger deployment\");\n }\n\n console.log(chalk.gray(` Deployment ${deploymentId} created.`));\n if (args[\"--no-follow\"]) {\n console.log(chalk.gray(\" Not following logs (--no-follow). Check status with `rebase cloud logs`.\"));\n console.log(\"\");\n return;\n }\n console.log(chalk.gray(\" Streaming build logs (Ctrl-C to stop watching — the build keeps running):\"));\n console.log(\"\");\n\n await streamBuildLogs(client, deploymentId);\n}\n\n/** Poll a deployment record and print new log output as it arrives. */\nasync function streamBuildLogs(client: CloudClient, deploymentId: string): Promise<void> {\n let printed = 0;\n const started = Date.now();\n\n for (;;) {\n let dep: Deployment | undefined;\n try {\n dep = (await client.data.collection(\"deployments\").findById(deploymentId)) as unknown as Deployment | undefined;\n } catch (e) {\n reportError(e, \"Failed to read deployment status\");\n }\n if (!dep) fail(`Deployment ${deploymentId} disappeared.`);\n\n const logs = dep.logs ?? \"\";\n if (logs.length > printed) {\n process.stdout.write(logs.slice(printed));\n printed = logs.length;\n }\n\n if (dep.status && dep.status !== \"deploying\") {\n console.log(\"\");\n if (dep.status === \"success\") {\n console.log(chalk.bold.green(\" ✓ Deployment succeeded\"));\n } else {\n console.log(chalk.bold.red(` ✗ Deployment ${dep.status}`));\n console.log(\"\");\n process.exit(1);\n }\n console.log(\"\");\n return;\n }\n\n if (Date.now() - started > POLL_TIMEOUT_MS) {\n console.log(\"\");\n fail(\n \"Timed out waiting for the build to finish.\",\n \"The deployment may still be running — check `rebase cloud logs`.\"\n );\n }\n\n await sleep(POLL_INTERVAL_MS);\n }\n}\n\nexport async function logsCommand(rawArgs: string[], projectRef: string): Promise<void> {\n const args = arg(\n { \"--runtime\": Boolean,\n\"--follow\": Boolean,\n\"-f\": \"--follow\" },\n { argv: rawArgs.slice(2),\npermissive: true }\n );\n const { client } = await requireClient(rawArgs);\n const projectId = await resolveProjectRef(projectRef, client);\n\n if (args[\"--runtime\"]) {\n try {\n const res = await client.functions.invoke<{ logs?: string; error?: string }>(\n \"runtime-logs\",\n undefined,\n { method: \"GET\",\npath: projectId }\n );\n console.log(\"\");\n console.log(chalk.bold(` 📄 Runtime logs — project ${projectRef}`));\n console.log(\"\");\n console.log(res.logs ?? chalk.gray(\" (no logs)\"));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to fetch runtime logs\");\n }\n return;\n }\n\n // Build logs: latest deployment, optionally follow if still running.\n try {\n const dep = (await latestDeployment(client, projectId)) as unknown as Deployment | undefined;\n if (!dep) {\n console.log(\"\");\n console.log(chalk.gray(\" No deployments yet for this project.\"));\n console.log(\"\");\n return;\n }\n\n console.log(\"\");\n console.log(chalk.bold(` 📄 Build logs — deployment ${dep.id}`) + ` ${colorStatus(dep.status)}`);\n console.log(\"\");\n\n if (args[\"--follow\"] && dep.status === \"deploying\") {\n // Hand off to the streamer, which prints from the top and tails live.\n await streamBuildLogs(client, String(dep.id));\n } else {\n console.log(dep.logs ?? chalk.gray(\" (no logs)\"));\n console.log(\"\");\n }\n } catch (e) {\n reportError(e, \"Failed to fetch build logs\");\n }\n}\n","/**\n * `rebase cloud orgs` — list / create / members.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n getContextOrg,\n setContextOrg,\n colorStatus,\n success,\n fail,\n reportError\n} from \"./context\";\n\ninterface OrgRow {\n id: string | number;\n name?: string;\n slug?: string;\n description?: string;\n createdAt?: string;\n}\n\nexport async function orgsCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n switch (subcommand) {\n case \"list\":\n case undefined:\n await listOrgs(rawArgs);\n break;\n case \"create\":\n await createOrg(rawArgs);\n break;\n case \"members\":\n await listMembers(rawArgs);\n break;\n case \"--help\":\n printOrgsHelp();\n break;\n default:\n fail(`Unknown orgs command: ${subcommand}`);\n }\n}\n\nasync function listOrgs(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n try {\n const orgs = (await client.data.collection(\"organizations\").find({ limit: 100 })).data as unknown as OrgRow[];\n const active = getContextOrg(url);\n\n console.log(\"\");\n console.log(chalk.bold(\" 🏢 Organizations\"));\n console.log(\"\");\n if (orgs.length === 0) {\n console.log(chalk.gray(\" You are not a member of any organization.\"));\n console.log(\"\");\n return;\n }\n for (const o of orgs) {\n const marker = String(o.id) === active ? chalk.green(\" ●\") : \" \";\n console.log(`${marker}${chalk.bold(o.name ?? \"(unnamed)\")} ${chalk.gray(`[${o.id}]`)}${o.slug ? chalk.gray(` ${o.slug}`) : \"\"}`);\n }\n console.log(\"\");\n console.log(chalk.gray(\" ● = active organization. Switch with `rebase cloud use <id>`.\"));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list organizations\");\n }\n}\n\nasync function createOrg(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--name\": String,\n\"--slug\": String,\n\"-n\": \"--name\" },\n { argv: rawArgs.slice(4),\npermissive: true }\n );\n const { client, url } = await requireClient(rawArgs);\n\n const prompts: Array<Record<string, unknown>> = [];\n if (!args[\"--name\"]) prompts.push({ type: \"input\",\nname: \"name\",\nmessage: \"Organization name:\" });\n const answers = prompts.length\n ? await inquirer.prompt(prompts as unknown as Parameters<typeof inquirer.prompt>[0])\n : {};\n\n const name = (args[\"--name\"] || (answers as { name?: string }).name || \"\").trim();\n if (!name) fail(\"Organization name is required.\");\n const slug = (args[\"--slug\"] || slugify(name)).trim();\n\n try {\n const created = (await client.data.collection(\"organizations\").create({\n name,\n slug,\n createdAt: new Date().toISOString()\n })) as unknown as OrgRow;\n setContextOrg(url, String(created.id));\n success(`Created organization ${chalk.bold(name)} and set it active`);\n } catch (e) {\n reportError(e, \"Failed to create organization\");\n }\n}\n\nasync function listMembers(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n const org = getContextOrg(url);\n if (!org) fail(\"No active organization.\", \"Run `rebase cloud use` first.\");\n\n try {\n const members = (await client.data.collection(\"organization-members\").find({\n where: { organization: [\"==\", org] },\n limit: 200\n })).data as unknown as Array<{ id: string | number; userId?: string; role?: string }>;\n\n console.log(\"\");\n console.log(chalk.bold(` 👥 Members — org ${org}`));\n console.log(\"\");\n if (members.length === 0) {\n console.log(chalk.gray(\" No members found.\"));\n console.log(\"\");\n return;\n }\n for (const m of members) {\n console.log(` ${chalk.bold(m.userId ?? \"?\")} ${colorStatus(m.role)}`);\n }\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list members\");\n }\n}\n\nfunction slugify(s: string): string {\n return s\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\n\nfunction printOrgsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud orgs\")} — Manage organizations\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List organizations you belong to\n ${chalk.blue.bold(\"create\")} Create a new organization ${chalk.gray(\"(--name, --slug)\")}\n ${chalk.blue.bold(\"members\")} List members of the active organization\n`);\n}\n","/**\n * `rebase cloud db` — database + backup management for a project.\n *\n * db list List databases attached to the project\n * db create Attach a managed or bring-your-own database\n * db test Test connectivity to the project's database\n * db backup list|create|restore\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n confirmDestructive,\n colorStatus,\n keyValues,\n success,\n fail,\n reportError\n} from \"./context\";\n\ninterface DatabaseRow {\n id: string | number;\n type?: string;\n connectionStatus?: string;\n useSshTunnel?: boolean;\n pitrEnabled?: boolean;\n}\n\ninterface BackupRow {\n filename: string;\n size?: number;\n createdAt?: string;\n type?: string;\n}\n\nexport async function dbCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n switch (subcommand) {\n case \"list\":\n case undefined:\n await listDatabases(rawArgs);\n break;\n case \"create\":\n await createDatabase(rawArgs);\n break;\n case \"info\":\n await dbInfo(rawArgs);\n break;\n case \"test\":\n await testDatabase(rawArgs);\n break;\n case \"backup\":\n await backupCommand(rawArgs);\n break;\n case \"pitr\":\n await pitrCommand(rawArgs);\n break;\n case \"--help\":\n printDbHelp();\n break;\n default:\n fail(`Unknown db command: ${subcommand}`);\n }\n}\n\nasync function listDatabases(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const dbs = (await client.data.collection(\"databases\").find({\n where: { project: [\"==\", projectId] },\n limit: 50\n })).data as unknown as DatabaseRow[];\n\n console.log(\"\");\n console.log(chalk.bold(` 🗄 Databases — project ${projectRef}`));\n console.log(\"\");\n if (dbs.length === 0) {\n console.log(chalk.gray(\" No database attached. Add one with `rebase cloud db create`.\"));\n console.log(\"\");\n return;\n }\n for (const d of dbs) {\n console.log(` ${chalk.bold(d.type ?? \"unknown\")} ${chalk.gray(`[${d.id}]`)} ${colorStatus(d.connectionStatus)}`);\n keyValues([\n [\"SSH tunnel\", d.useSshTunnel ? \"yes\" : undefined],\n [\"PITR\", d.pitrEnabled ? \"enabled\" : undefined]\n ]);\n }\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list databases\");\n }\n}\n\nasync function createDatabase(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--type\": String,\n\"--connection-string\": String,\n\"--project\": String,\n\"-p\": \"--project\" },\n { argv: rawArgs.slice(4),\npermissive: true }\n );\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n let type = args[\"--type\"];\n if (!type) {\n const { picked } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"picked\",\n message: \"Database type:\",\n choices: [\n { name: \"SaaS Managed (provisioned for you)\",\nvalue: \"managed\" },\n { name: \"Bring Your Own DB (external PostgreSQL)\",\nvalue: \"byodb\" }\n ]\n }\n ] as unknown as Parameters<typeof inquirer.prompt>[0]);\n type = picked as string;\n }\n\n let connectionString = args[\"--connection-string\"];\n if (type === \"byodb\" && !connectionString) {\n const { cs } = await inquirer.prompt([\n { type: \"input\",\nname: \"cs\",\nmessage: \"PostgreSQL connection string:\" }\n ] as unknown as Parameters<typeof inquirer.prompt>[0]);\n connectionString = (cs as string)?.trim();\n if (!connectionString) fail(\"A connection string is required for bring-your-own databases.\");\n }\n\n try {\n const created = (await client.data.collection(\"databases\").create({\n project: projectId,\n type,\n connectionString: type === \"byodb\" ? connectionString : undefined,\n connectionStatus: \"untested\"\n })) as unknown as DatabaseRow;\n success(`Attached ${type} database to project ${projectRef}`);\n keyValues([[\"ID\", String(created.id)]]);\n if (type === \"byodb\") {\n console.log(chalk.gray(\" Verify it with `rebase cloud db test`.\"));\n console.log(\"\");\n }\n } catch (e) {\n reportError(e, \"Failed to attach database\");\n }\n}\n\nasync function testDatabase(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n console.log(\"\");\n console.log(` Testing database connectivity for project ${chalk.bold(projectId)}...`);\n try {\n const res = await client.functions.invoke<{ success: boolean; logs?: string }>(\"db-test\", { projectId });\n console.log(\"\");\n if (res.logs) console.log(res.logs);\n if (res.success) success(\"Database connection succeeded\");\n else fail(\"Database connection failed. See logs above.\");\n } catch (e) {\n reportError(e, \"Failed to test database\");\n }\n}\n\n/* ─── db info ──────────────────────────────────────────────────── */\n\ninterface DbInfoResponse {\n type: \"managed\" | \"byodb\";\n host: string | null;\n port: string | null;\n database: string | null;\n username: string | null;\n passwordAvailable: boolean;\n portForward: { namespace: string; service: string; localPort: number; remotePort: number } | null;\n unavailableReason: string | null;\n}\n\n/**\n * `rebase cloud db info [--reveal]` — where a project's database actually lives.\n *\n * The password is NEVER in the default output; `--reveal` fetches it through the\n * separate reveal call, and it appears in JSON only when `--reveal` is given.\n * Any field the server could not resolve comes back `null` and is rendered as\n * unavailable, never a placeholder.\n */\nasync function dbInfo(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--reveal\": Boolean, \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n try {\n const info = await client.functions.invoke<DbInfoResponse>(\"db-info\", undefined, { method: \"GET\", path: projectId });\n\n let password: string | undefined;\n let connectionString: string | undefined;\n if (args[\"--reveal\"]) {\n if (!info.passwordAvailable) {\n fail(\"No password is available to reveal for this database.\", info.unavailableReason ?? undefined, \"password_unavailable\");\n }\n const revealed = await client.functions.invoke<{ password: string; connectionString: string }>(\n \"db-info\",\n { projectId },\n { path: \"reveal\" }\n );\n password = revealed.password;\n connectionString = revealed.connectionString;\n }\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🗄 Database — project ${projectRef}`) + chalk.gray(` (${info.type})`));\n console.log(\"\");\n keyValues([\n [\"Host\", info.host],\n [\"Port\", info.port],\n [\"Database\", info.database],\n [\"Username\", info.username],\n [\"Password\", info.passwordAvailable ? (password ?? chalk.gray(\"hidden — pass --reveal\")) : chalk.gray(\"unavailable\")],\n [\"Connection\", connectionString]\n ]);\n if (info.unavailableReason) {\n console.log(chalk.gray(` ${info.unavailableReason}`));\n }\n if (info.portForward) {\n const pf = info.portForward;\n console.log(\"\");\n console.log(chalk.gray(` Port-forward: kubectl -n ${pf.namespace} port-forward svc/${pf.service} ${pf.localPort}:${pf.remotePort}`));\n }\n console.log(\"\");\n },\n {\n projectId,\n type: info.type,\n host: info.host,\n port: info.port,\n database: info.database,\n username: info.username,\n passwordAvailable: info.passwordAvailable,\n portForward: info.portForward,\n unavailableReason: info.unavailableReason,\n // Only present when explicitly revealed.\n ...(args[\"--reveal\"] ? { password, connectionString } : {})\n }\n );\n } catch (e) {\n reportError(e, \"Failed to load database info\");\n }\n}\n\n/* ─── backups ──────────────────────────────────────────────────── */\n\nasync function backupCommand(rawArgs: string[]): Promise<void> {\n // `rebase cloud db backup <action>` — action is the 4th positional token.\n const action = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[2] || \"list\";\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\" }, { argv: rawArgs.slice(2), permissive: true });\n\n try {\n if (action === \"create\") {\n const res = await client.functions.invoke<{ success: boolean; backup?: BackupRow; error?: string }>(\n \"backup\",\n { projectId,\ntype: \"manual\" },\n { path: \"create\" }\n );\n if (!res.success) fail(res.error || \"Backup failed.\");\n emit(\n () => success(`Backup created: ${res.backup?.filename ?? \"(unknown)\"}`),\n { success: true, backup: res.backup ?? null }\n );\n return;\n }\n\n if (action === \"restore\") {\n const filename = cloudPositionals(rawArgs).slice(3)[0];\n if (!filename) fail(\"Usage: rebase cloud db backup restore <filename>\", undefined, \"usage\");\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Restore \"${filename}\" over the current database for project ${projectRef}?`\n });\n const res = await client.functions.invoke<{ success: boolean; message?: string; error?: string }>(\n \"backup\",\n { projectId,\nfilename },\n { path: \"restore\" }\n );\n if (!res.success) fail(res.error || \"Restore failed.\");\n emit(() => success(res.message || \"Restore complete\"), { success: true, message: res.message ?? null });\n return;\n }\n\n if (action === \"status\") {\n const res = await client.functions.invoke<Record<string, unknown>>(\"backup\", undefined, {\n method: \"GET\",\n path: `backup-status/${projectId}`\n });\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 💾 Automated backups — project ${projectRef}`));\n console.log(\"\");\n keyValues([\n [\"Enabled\", res.enabled ? chalk.green(\"yes\") : chalk.yellow(\"no\")],\n [\"Reason\", String(res.reason ?? \"\")],\n [\"Database type\", String(res.databaseType ?? \"\")],\n [\"Last backup\", (res.lastSuccessfulBackup as string) ?? undefined],\n [\n \"Recovery window\",\n res.recoveryWindow\n ? `${(res.recoveryWindow as { from: string }).from} → ${(res.recoveryWindow as { to: string }).to}`\n : undefined\n ]\n ]);\n console.log(\"\");\n },\n res\n );\n return;\n }\n\n if (action === \"download\") {\n const filename = cloudPositionals(rawArgs).slice(3)[0];\n if (!filename) fail(\"Usage: rebase cloud db backup download <filename>\", undefined, \"usage\");\n const res = await client.functions.invoke<{ url: string; name: string; size: number }>(\"backup\", undefined, {\n method: \"GET\",\n path: `download/${projectId}/${encodeURIComponent(filename)}`\n });\n // Print the signed URL rather than downloading the file — downloading\n // is a user-consented action, and the URL is what the operator/agent\n // needs to fetch it themselves.\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ${res.name}`) + chalk.gray(` ${(res.size / 1024 / 1024).toFixed(1)} MB`));\n console.log(` ${chalk.cyan(res.url)}`);\n console.log(\"\");\n console.log(chalk.gray(\" Short-lived signed URL — fetch it with curl/wget.\"));\n console.log(\"\");\n },\n { name: res.name, size: res.size, url: res.url }\n );\n return;\n }\n\n // default: list\n const res = await client.functions.invoke<{ backups: BackupRow[] }>(\n \"backup\",\n undefined,\n { method: \"GET\",\npath: `list/${projectId}` }\n );\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 💾 Backups — project ${projectRef}`));\n console.log(\"\");\n if (!res.backups?.length) {\n console.log(chalk.gray(\" No backups yet. Create one with `rebase cloud db backup create`.\"));\n console.log(\"\");\n return;\n }\n for (const b of res.backups) {\n const size = b.size !== undefined ? `${(b.size / 1024 / 1024).toFixed(1)} MB` : \"\";\n console.log(` ${chalk.bold(b.filename)} ${chalk.gray(`${b.type ?? \"\"} ${size}`.trim())}`);\n }\n console.log(\"\");\n },\n { projectId, backups: res.backups ?? [] }\n );\n } catch (e) {\n reportError(e, \"Backup operation failed\");\n }\n}\n\n/* ─── PITR (point-in-time recovery) ────────────────────────────── */\n\n/**\n * `rebase cloud db pitr <status|restore|cutover|discard>`.\n *\n * A PITR restore is STAGED, not applied: `restore` creates a recovered copy of\n * the database beside the live one — the application is NOT repointed and the\n * original is left running and unchanged. `cutover` is the separate, explicit\n * step that repoints the app at the recovered copy (and restarts it). `discard`\n * removes a staged copy; the server refuses to discard a copy that has been cut\n * over to (it is now the live database). Every mutating step requires `--yes` in\n * non-interactive use, and the CLI surfaces these staged semantics honestly.\n */\nasync function pitrCommand(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--target\": String, \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" },\n { argv: rawArgs.slice(2), permissive: true }\n );\n const action = cloudPositionals(rawArgs).slice(2)[0] || \"status\";\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n try {\n if (action === \"status\") {\n const res = await client.functions.invoke<Record<string, unknown>>(\"backup\", undefined, {\n method: \"GET\",\n path: `pitr-status/${projectId}`\n });\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ⏱ Point-in-time recovery — project ${projectRef}`));\n console.log(\"\");\n keyValues([\n [\"Available\", res.available ? chalk.green(\"yes\") : chalk.yellow(\"no\")],\n [\"First recoverable\", (res.firstRecoverabilityPoint as string) ?? undefined],\n [\"Last backup\", (res.lastSuccessfulBackup as string) ?? undefined],\n [\"Message\", (res.message as string) ?? undefined]\n ]);\n console.log(\"\");\n },\n res\n );\n return;\n }\n\n if (action === \"restore\") {\n const target = args[\"--target\"];\n if (!target) fail(\"Usage: rebase cloud db pitr restore --target <ISO timestamp>\", undefined, \"usage\");\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Stage a point-in-time recovery of project ${projectRef} at ${target}? (stages a copy; does not repoint your app)`\n });\n const res = await client.functions.invoke<Record<string, unknown>>(\n \"backup\",\n // acknowledgeNoCutover is required by the server: the caller must\n // affirm this only STAGES a copy. The confirm prompt above says so.\n { projectId, targetTime: target, acknowledgeNoCutover: true },\n { path: \"pitr-restore\" }\n );\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.yellow(` ⏳ ${String(res.message ?? \"Recovery staged.\")}`));\n console.log(chalk.gray(\" Watch progress with `rebase cloud db pitr status`, then `rebase cloud db pitr cutover --yes`.\"));\n console.log(\"\");\n },\n res\n );\n return;\n }\n\n if (action === \"cutover\") {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Cut project ${projectRef} over to the staged recovery? This repoints and restarts your application.`\n });\n const res = await client.functions.invoke<Record<string, unknown>>(\"backup\", { projectId }, { path: \"pitr-restore-cutover\" });\n emit(\n () => {\n console.log(\"\");\n console.log(String(res.message ?? \"Cutover requested.\"));\n console.log(\"\");\n },\n res\n );\n return;\n }\n\n if (action === \"discard\") {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Discard the staged recovery for project ${projectRef}? This deletes the staged copy and its storage.`\n });\n const res = await client.functions.invoke<Record<string, unknown>>(\"backup\", { projectId }, { path: \"pitr-restore-discard\" });\n emit(\n () => success(String(res.message ?? \"Staged restore discarded.\")),\n res\n );\n return;\n }\n\n fail(`Unknown pitr command: ${action}`, \"Try status | restore | cutover | discard.\", \"usage\");\n } catch (e) {\n reportError(e, \"PITR operation failed\");\n }\n}\n\nfunction printDbHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud db\")} — Database & backups\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List databases attached to the project\n ${chalk.blue.bold(\"create\")} Attach a managed or bring-your-own database\n ${chalk.blue.bold(\"info\")} ${chalk.gray(\"[--reveal]\")} Connection details ${chalk.gray(\"(password only with --reveal)\")}\n ${chalk.blue.bold(\"test\")} Test database connectivity\n ${chalk.blue.bold(\"backup list\")} List backups\n ${chalk.blue.bold(\"backup create\")} Create a manual backup\n ${chalk.blue.bold(\"backup restore\")} ${chalk.gray(\"<file>\")} Restore a backup\n ${chalk.blue.bold(\"backup status\")} Automated-backup health\n ${chalk.blue.bold(\"backup download\")} ${chalk.gray(\"<file>\")} Signed URL for a backup\n ${chalk.blue.bold(\"pitr status\")} Point-in-time recovery window\n ${chalk.blue.bold(\"pitr restore\")} ${chalk.gray(\"--target <ISO>\")} Stage a recovery ${chalk.gray(\"(does not repoint)\")}\n ${chalk.blue.bold(\"pitr cutover\")} ${chalk.gray(\"-y\")} Repoint the app at the staged recovery\n ${chalk.blue.bold(\"pitr discard\")} ${chalk.gray(\"-y\")} Delete a staged recovery\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\n ${chalk.blue(\"--reveal\")} Include the DB password ${chalk.gray(\"(info)\")}\n ${chalk.blue(\"--type\")} managed | byodb ${chalk.gray(\"(create)\")}\n ${chalk.blue(\"--connection-string\")} External DB URL ${chalk.gray(\"(byodb)\")}\n ${chalk.blue(\"--json\")} Machine-readable output\n`);\n}\n","/**\n * `rebase cloud env` — a project's environment variables.\n *\n * env list Keys only — a value is NEVER printed here\n * env set KEY=VALUE Create/replace one variable (`--secret` ⇒ write-only)\n * env unset KEY Remove one variable\n * env reveal KEY Release one non-secret value (a secret var 403s)\n * env pull [--out .env] Write revealable values to a local dotenv file\n *\n * Values are the sharp edge here. The list endpoint returns keys and never\n * values by design (a page load is not consent to spray a customer's secrets\n * through caches and logs), and a `--secret` variable is write-only: it can be\n * replaced but never read back. This mirrors `env-vars` exactly and refuses to\n * offer reveal for a secret variable rather than letting the server 403.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n isJsonMode,\n confirmDestructive,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\ninterface EnvVarView {\n id: string;\n key: string;\n secret: boolean;\n valueSet: boolean;\n createdAt: string | null;\n updatedAt: string | null;\n}\n\ninterface EnvVarListResponse {\n vars: EnvVarView[];\n pendingRedeploy: boolean | null;\n pendingSince: string | null;\n limits: {\n maxVars: number;\n maxValueBytes: number;\n maxTotalBytes: number;\n keyPattern: string;\n reservedKeys: string[];\n };\n}\n\nasync function fetchEnvVars(client: CloudClient, projectId: string): Promise<EnvVarListResponse> {\n return client.functions.invoke<EnvVarListResponse>(\"env-vars\", undefined, {\n method: \"GET\",\n path: projectId\n });\n}\n\nexport async function envCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case undefined:\n await listEnv(rawArgs);\n break;\n case \"set\":\n await setEnv(rawArgs);\n break;\n case \"unset\":\n case \"delete\":\n case \"rm\":\n await unsetEnv(rawArgs);\n break;\n case \"reveal\":\n await revealEnv(rawArgs);\n break;\n case \"pull\":\n await pullEnv(rawArgs);\n break;\n case \"--help\":\n printEnvHelp();\n break;\n default:\n fail(`Unknown env command: ${action}`, \"Try `rebase cloud env --help`.\");\n }\n}\n\n/** A short human hint about redeploy state (the JSON carries `pendingRedeploy`). */\nfunction pendingHint(pending: boolean | null): string | undefined {\n if (pending === true) return chalk.yellow(\"A variable changed since the last deploy — run `rebase cloud deploy` to apply it.\");\n if (pending === null) return chalk.gray(\"Redeploy state is unknown (deployment history unavailable).\");\n return undefined;\n}\n\nasync function listEnv(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const res = await fetchEnvVars(client, projectId);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🔑 Environment — project ${projectRef}`));\n console.log(\"\");\n if (!res.vars.length) {\n console.log(chalk.gray(\" No variables. Add one with `rebase cloud env set KEY=VALUE`.\"));\n console.log(\"\");\n return;\n }\n for (const v of res.vars) {\n const badges = [\n v.secret ? chalk.magenta(\"secret\") : undefined,\n v.valueSet ? undefined : chalk.gray(\"empty\")\n ]\n .filter(Boolean)\n .join(\" \");\n // Deliberately no value — reveal is the only way to read one.\n console.log(` ${chalk.bold(v.key)}${badges ? ` ${badges}` : \"\"}`);\n }\n const hint = pendingHint(res.pendingRedeploy);\n if (hint) {\n console.log(\"\");\n console.log(` ${hint}`);\n }\n console.log(\"\");\n },\n {\n projectId,\n pendingRedeploy: res.pendingRedeploy,\n pendingSince: res.pendingSince,\n // Never a value: keys + shape only.\n vars: res.vars.map((v) => ({\n key: v.key,\n secret: v.secret,\n valueSet: v.valueSet,\n createdAt: v.createdAt,\n updatedAt: v.updatedAt\n })),\n limits: res.limits\n }\n );\n } catch (e) {\n reportError(e, \"Failed to list environment variables\");\n }\n}\n\n/** Parse `KEY=VALUE` or `KEY VALUE` from the positional operands. */\nexport function parseEnvAssignment(operands: string[]): { key: string; value: string } | null {\n const first = operands[0];\n if (!first) return null;\n const eq = first.indexOf(\"=\");\n if (eq > 0) {\n return { key: first.slice(0, eq).trim(), value: first.slice(eq + 1) };\n }\n // `set KEY VALUE` form — VALUE is the next operand (may be absent ⇒ empty).\n return { key: first.trim(), value: operands[1] ?? \"\" };\n}\n\nasync function setEnv(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--secret\": Boolean, \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const operands = cloudPositionals(rawArgs).slice(2); // after `env set`\n const parsed = parseEnvAssignment(operands);\n if (!parsed || !parsed.key) {\n fail(\"Usage: rebase cloud env set KEY=VALUE [--secret]\", undefined, \"usage\");\n }\n\n const body: { key: string; value: string; secret?: boolean } = { key: parsed!.key, value: parsed!.value };\n if (args[\"--secret\"]) body.secret = true;\n\n try {\n const res = await client.functions.invoke<{ success: boolean; var: EnvVarView; pendingRedeploy: true }>(\n \"env-vars\",\n body,\n { path: projectId }\n );\n emit(\n () => {\n success(`Set ${chalk.bold(res.var.key)}${res.var.secret ? chalk.magenta(\" (secret)\") : \"\"}`);\n console.log(` ${chalk.yellow(\"Pending redeploy\")} — run \\`rebase cloud deploy\\` to apply it.`);\n console.log(\"\");\n },\n {\n success: true,\n key: res.var.key,\n secret: res.var.secret,\n valueSet: res.var.valueSet,\n pendingRedeploy: res.pendingRedeploy\n }\n );\n } catch (e) {\n reportError(e, \"Failed to set environment variable\");\n }\n}\n\nasync function unsetEnv(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const key = cloudPositionals(rawArgs).slice(2)[0];\n if (!key) fail(\"Usage: rebase cloud env unset KEY\", undefined, \"usage\");\n\n try {\n const res = await client.functions.invoke<{ success: boolean; pendingRedeploy: true }>(\"env-vars\", undefined, {\n method: \"DELETE\",\n path: `${projectId}/${encodeURIComponent(key!)}`\n });\n emit(\n () => {\n success(`Removed ${chalk.bold(key!)}`);\n console.log(` ${chalk.yellow(\"Pending redeploy\")} — run \\`rebase cloud deploy\\` to apply it.`);\n console.log(\"\");\n },\n { success: true, key, pendingRedeploy: res.pendingRedeploy }\n );\n } catch (e) {\n reportError(e, \"Failed to remove environment variable\");\n }\n}\n\nasync function revealEnv(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const key = cloudPositionals(rawArgs).slice(2)[0];\n if (!key) fail(\"Usage: rebase cloud env reveal KEY\", undefined, \"usage\");\n\n // Pre-check: a secret variable is write-only. Don't even ask the server — it\n // would 403 — say so plainly and never offer reveal for it. Done OUTSIDE the\n // reveal try so a deliberate refusal is not re-wrapped as a server error.\n let list: EnvVarListResponse;\n try {\n list = await fetchEnvVars(client, projectId);\n } catch (e) {\n reportError(e, \"Failed to reveal environment variable\");\n }\n const found = list!.vars.find((v) => v.key === key);\n if (!found) fail(`No variable named ${key} in project ${projectRef}.`, undefined, \"not_found\");\n if (found!.secret) {\n fail(\n `${key} is a secret (write-only) variable; its value cannot be revealed.`,\n \"Replace it with `rebase cloud env set KEY=VALUE` if you need to change it.\",\n \"secret_write_only\"\n );\n }\n\n try {\n const res = await client.functions.invoke<{ key: string; value: string }>(\n \"env-vars\",\n { projectId, key },\n { path: \"reveal\" }\n );\n emit(\n () => {\n console.log(\"\");\n console.log(` ${chalk.bold(res.key)}=${res.value}`);\n console.log(\"\");\n },\n { key: res.key, value: res.value }\n );\n } catch (e) {\n reportError(e, \"Failed to reveal environment variable\");\n }\n}\n\nasync function pullEnv(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--out\": String, \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const outPath = path.resolve(args[\"--out\"] || \".env\");\n\n try {\n const list = await fetchEnvVars(client, projectId);\n\n if (fs.existsSync(outPath)) {\n await confirmDestructive({ yes: Boolean(args[\"--yes\"]), prompt: `Overwrite ${outPath}?` });\n }\n\n // Only non-secret, value-set variables can be written — a secret var is\n // write-only and reveal 403s, so it is honestly skipped, not faked.\n const written: string[] = [];\n const skipped: Array<{ key: string; reason: string }> = [];\n const lines: string[] = [];\n for (const v of list.vars) {\n if (v.secret) {\n skipped.push({ key: v.key, reason: \"secret (write-only)\" });\n continue;\n }\n if (!v.valueSet) {\n lines.push(`${v.key}=`);\n written.push(v.key);\n continue;\n }\n const revealed = await client.functions.invoke<{ key: string; value: string }>(\n \"env-vars\",\n { projectId, key: v.key },\n { path: \"reveal\" }\n );\n // Quote values that contain whitespace or a hash so a dotenv reader\n // keeps them intact.\n const needsQuote = /[\\s#'\"]/.test(revealed.value);\n lines.push(`${v.key}=${needsQuote ? JSON.stringify(revealed.value) : revealed.value}`);\n written.push(v.key);\n }\n\n fs.writeFileSync(outPath, lines.length ? lines.join(\"\\n\") + \"\\n\" : \"\", { mode: 0o600 });\n\n emit(\n () => {\n success(`Wrote ${written.length} variable${written.length === 1 ? \"\" : \"s\"} to ${outPath}`);\n if (skipped.length) {\n console.log(chalk.gray(` Skipped ${skipped.length} secret variable(s): ${skipped.map((s) => s.key).join(\", \")}`));\n console.log(\"\");\n }\n },\n { success: true, path: outPath, written, skipped }\n );\n } catch (e) {\n reportError(e, \"Failed to pull environment variables\");\n }\n}\n\nfunction printEnvHelp(): void {\n if (isJsonMode()) {\n printEnvHelpJson();\n return;\n }\n console.log(`\n${chalk.bold(\"rebase cloud env\")} — Environment variables\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List keys ${chalk.gray(\"(values are never printed)\")}\n ${chalk.blue.bold(\"set\")} ${chalk.gray(\"KEY=VALUE [--secret]\")} Create or replace a variable\n ${chalk.blue.bold(\"unset\")} ${chalk.gray(\"KEY\")} Remove a variable\n ${chalk.blue.bold(\"reveal\")} ${chalk.gray(\"KEY\")} Print one non-secret value\n ${chalk.blue.bold(\"pull\")} ${chalk.gray(\"[--out .env] [-y]\")} Write revealable values to a dotenv file\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--secret\")} Mark a variable write-only ${chalk.gray(\"(set)\")}\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\n`);\n}\n\nfunction printEnvHelpJson(): void {\n process.stdout.write(\n JSON.stringify({\n command: \"env\",\n actions: [\"list\", \"set\", \"unset\", \"reveal\", \"pull\"]\n }) + \"\\n\"\n );\n}\n","/**\n * `rebase cloud domains` — a project's custom domain.\n *\n * domains list Current domain + the DNS records it needs\n * domains add <domain> Register a domain (starts, does not finish, setup)\n * domains verify Check the published DNS now; live only if it passes\n * domains remove Detach the custom domain\n *\n * The DNS record set comes from the server (`verify-domain`), never composed\n * here: whether to publish an A or a CNAME depends on apex-vs-subdomain and on\n * the ingress address behind the tenant host, which the CLI cannot know. Adding\n * a domain only registers it — it is unverified until the records are published\n * and `verify` passes.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n confirmDestructive,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\ninterface DomainRecord {\n type: \"A\" | \"CNAME\" | \"TXT\";\n name: string;\n values: string[];\n}\n\ninterface DomainSetup {\n domain: string | null;\n status: \"none\" | \"pending\" | \"verified\";\n isApex?: boolean;\n tenantHost?: string;\n verifiedAt?: string | null;\n instructions?: {\n pointing?: DomainRecord;\n ownership: DomainRecord;\n };\n}\n\ninterface DomainCheck {\n ok: boolean;\n expected: string[];\n observed: string[];\n error?: string;\n}\n\ninterface VerifyResult extends DomainSetup {\n verified: boolean;\n checks: { ownership: DomainCheck; pointing: DomainCheck };\n}\n\nasync function fetchDomainSetup(client: CloudClient, projectId: string): Promise<DomainSetup> {\n return client.functions.invoke<DomainSetup>(\"verify-domain\", undefined, { method: \"GET\", path: projectId });\n}\n\nfunction printRecords(setup: DomainSetup): void {\n const recs = [setup.instructions?.pointing, setup.instructions?.ownership].filter(Boolean) as DomainRecord[];\n if (!recs.length) return;\n console.log(chalk.bold(\" DNS records to publish:\"));\n for (const r of recs) {\n console.log(` ${chalk.cyan(r.type)} ${r.name} → ${r.values.join(\", \")}`);\n }\n console.log(\"\");\n}\n\nexport async function domainsCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case \"status\":\n case undefined:\n await listDomains(rawArgs);\n break;\n case \"add\":\n case \"set\":\n await addDomain(rawArgs);\n break;\n case \"verify\":\n await verifyDomains(rawArgs);\n break;\n case \"remove\":\n case \"rm\":\n case \"delete\":\n await removeDomain(rawArgs);\n break;\n case \"--help\":\n printDomainsHelp();\n break;\n default:\n fail(`Unknown domains command: ${action}`, \"Try `rebase cloud domains --help`.\");\n }\n}\n\nasync function listDomains(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const setup = await fetchDomainSetup(client, projectId);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🌐 Custom domain — project ${projectRef}`));\n console.log(\"\");\n if (!setup.domain) {\n console.log(chalk.gray(\" No custom domain. Add one with `rebase cloud domains add <domain>`.\"));\n console.log(\"\");\n return;\n }\n keyValues([\n [\"Domain\", setup.domain],\n [\"Status\", setup.status === \"verified\" ? chalk.green(setup.status) : chalk.yellow(setup.status)],\n [\"Apex\", setup.isApex === undefined ? undefined : setup.isApex ? \"yes\" : \"no\"],\n [\"Tenant host\", setup.tenantHost],\n [\"Verified at\", setup.verifiedAt ?? undefined]\n ]);\n console.log(\"\");\n if (setup.status !== \"verified\") printRecords(setup);\n },\n { projectId, ...setup }\n );\n } catch (e) {\n reportError(e, \"Failed to load custom domain\");\n }\n}\n\nasync function addDomain(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const domain = cloudPositionals(rawArgs).slice(2)[0];\n if (!domain) fail(\"Usage: rebase cloud domains add <domain>\", undefined, \"usage\");\n\n try {\n // Registering the domain is a project update; the DNS records to publish\n // then come from the server's setup endpoint.\n await client.data.collection(\"projects\").update(projectId, { customDomain: domain });\n const setup = await fetchDomainSetup(client, projectId);\n emit(\n () => {\n success(`Registered ${chalk.bold(domain!)} — not yet verified`);\n printRecords(setup);\n console.log(chalk.gray(\" Publish the records above, then run `rebase cloud domains verify`.\"));\n console.log(\"\");\n },\n { success: true, projectId, ...setup }\n );\n } catch (e) {\n reportError(e, \"Failed to register domain\");\n }\n}\n\nasync function verifyDomains(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const res = await client.functions.invoke<VerifyResult>(\"verify-domain\", {}, { path: projectId });\n emit(\n () => {\n console.log(\"\");\n if (res.verified) success(`${res.domain} is verified and live`);\n else {\n console.log(chalk.yellow(` ⚠ ${res.domain ?? \"domain\"} is not verified yet`));\n console.log(\"\");\n const rows: Array<[string, DomainCheck]> = [\n [\"Ownership\", res.checks.ownership],\n [\"Pointing\", res.checks.pointing]\n ];\n for (const [label, check] of rows) {\n const mark = check.ok ? chalk.green(\"ok\") : chalk.red(\"missing\");\n console.log(` ${label}: ${mark}`);\n console.log(chalk.gray(` expected: ${check.expected.join(\", \") || \"—\"}`));\n console.log(chalk.gray(` observed: ${check.observed.join(\", \") || \"—\"}`));\n if (check.error) console.log(chalk.gray(` error: ${check.error}`));\n }\n console.log(\"\");\n printRecords(res);\n }\n },\n { projectId, verified: res.verified, status: res.status, domain: res.domain, checks: res.checks, instructions: res.instructions }\n );\n if (!res.verified) process.exit(1);\n } catch (e) {\n reportError(e, \"Failed to verify domain\");\n }\n}\n\nasync function removeDomain(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Remove the custom domain from project ${projectRef}?`\n });\n\n try {\n await client.data.collection(\"projects\").update(projectId, { customDomain: \"\" });\n emit(\n () => success(`Removed the custom domain from project ${projectRef}`),\n { success: true, projectId }\n );\n } catch (e) {\n reportError(e, \"Failed to remove domain\");\n }\n}\n\nfunction printDomainsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud domains\")} — Custom domain\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} Show the domain + DNS records\n ${chalk.blue.bold(\"add\")} ${chalk.gray(\"<domain>\")} Register a custom domain\n ${chalk.blue.bold(\"verify\")} Check DNS and go live\n ${chalk.blue.bold(\"remove\")} ${chalk.gray(\"[-y]\")} Detach the custom domain\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\n`);\n}\n","/**\n * `rebase cloud extensions` — allowlisted Postgres extensions.\n *\n * extensions list Every allowlisted extension + its real state\n * extensions enable <name> [-y] Install one (may restart the DB ⇒ needs -y)\n * extensions disable <name> Drop one (and remove any preload library)\n *\n * `manageable === false` is the anti-brick guard reaching the CLI: the server\n * has already said it will refuse, so enable/disable is never offered for such an\n * extension — its `manageableReason` is surfaced instead. Enabling one that\n * restarts the customer's database requires `--yes` in non-interactive use. The\n * `pgvector` alias resolves to `vector`, and a 202 (`pending`) means the database\n * is restarting and the extension is not installed yet — re-drive later.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n confirmDestructive,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\ninterface ExtensionStatus {\n name: string;\n displayName: string;\n description: string;\n requiresRestart: boolean;\n enabled: boolean;\n version: string | null;\n enabledAt: string | null;\n available: boolean;\n pendingRestart: boolean;\n manageable: boolean;\n manageableReason: string | null;\n}\n\ninterface ExtensionListResponse {\n databaseType: \"managed\" | \"byodb\" | \"none\";\n reason: string;\n source: \"database\" | \"record\";\n extensions: ExtensionStatus[];\n}\n\ninterface EnableResult {\n success: boolean;\n extension: string;\n pending?: boolean;\n restarted?: boolean;\n requiresRestart?: boolean;\n alreadyEnabled?: boolean;\n version?: string | null;\n recordWritten?: boolean;\n message: string;\n}\n\ninterface DisableResult {\n success: boolean;\n extension: string;\n dropped: boolean;\n preloadRemoved: boolean;\n restarted?: boolean;\n message: string;\n}\n\n/** The identifier CREATE EXTENSION takes. `pgvector` is a common alias. */\nexport function resolveExtensionAlias(name: string): string {\n return name.toLowerCase() === \"pgvector\" ? \"vector\" : name;\n}\n\nasync function fetchExtensions(client: CloudClient, projectId: string): Promise<ExtensionListResponse> {\n return client.functions.invoke<ExtensionListResponse>(\"extensions\", undefined, {\n method: \"GET\",\n path: `list/${projectId}`\n });\n}\n\nexport async function extensionsCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case undefined:\n await listExtensions(rawArgs);\n break;\n case \"enable\":\n await enableExtension(rawArgs);\n break;\n case \"disable\":\n await disableExtension(rawArgs);\n break;\n case \"--help\":\n printExtensionsHelp();\n break;\n default:\n fail(`Unknown extensions command: ${action}`, \"Try `rebase cloud extensions --help`.\");\n }\n}\n\nasync function listExtensions(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const res = await fetchExtensions(client, projectId);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🧩 Extensions — project ${projectRef}`) + chalk.gray(` (${res.databaseType}, source: ${res.source})`));\n console.log(\"\");\n if (res.source === \"record\") {\n console.log(chalk.yellow(\" ⚠ Database unreachable — showing cached state, not live catalog.\"));\n console.log(\"\");\n }\n for (const e of res.extensions) {\n const state = e.enabled ? chalk.green(\"enabled\") : chalk.gray(\"disabled\");\n const restart = e.requiresRestart ? chalk.yellow(\" ⟳ restarts DB\") : \"\";\n const locked = !e.manageable ? chalk.gray(\" [not manageable]\") : \"\";\n console.log(` ${chalk.bold(e.name)} ${state}${e.version ? chalk.gray(` v${e.version}`) : \"\"}${restart}${locked}`);\n if (!e.manageable && e.manageableReason) console.log(chalk.gray(` ${e.manageableReason}`));\n }\n console.log(\"\");\n },\n { projectId, databaseType: res.databaseType, reason: res.reason, source: res.source, extensions: res.extensions }\n );\n } catch (e) {\n reportError(e, \"Failed to list extensions\");\n }\n}\n\nasync function enableExtension(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const raw = cloudPositionals(rawArgs).slice(2)[0];\n if (!raw) fail(\"Usage: rebase cloud extensions enable <name>\", undefined, \"usage\");\n const name = resolveExtensionAlias(raw!);\n\n try {\n // Consult the catalog first: never offer enable where the server says it\n // is not manageable, and gate a DB-restarting enable behind --yes.\n const list = await fetchExtensions(client, projectId);\n const ext = list.extensions.find((e) => e.name === name);\n if (ext && !ext.manageable) {\n fail(\n `Extension ${name} cannot be managed on this project.`,\n ext.manageableReason ?? undefined,\n \"not_manageable\"\n );\n }\n if (ext?.requiresRestart && !ext.enabled) {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Enabling ${name} restarts the project's database. Continue?`\n });\n }\n\n const res = await client.functions.invoke<EnableResult>(\"extensions\", { projectId, extensionName: name }, { path: \"enable\" });\n emit(\n () => {\n if (res.pending) {\n console.log(\"\");\n console.log(chalk.yellow(` ⏳ ${res.message}`));\n console.log(chalk.gray(\" The database is restarting; re-run this once it is back to finish installing.\"));\n console.log(\"\");\n } else {\n success(res.message || `Enabled ${name}`);\n keyValues([[\"Version\", res.version ?? undefined]]);\n }\n },\n {\n success: res.success,\n extension: res.extension,\n pending: res.pending ?? false,\n restarted: res.restarted ?? false,\n alreadyEnabled: res.alreadyEnabled ?? false,\n version: res.version ?? null,\n message: res.message\n }\n );\n } catch (e) {\n reportError(e, \"Failed to enable extension\");\n }\n}\n\nasync function disableExtension(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const raw = cloudPositionals(rawArgs).slice(2)[0];\n if (!raw) fail(\"Usage: rebase cloud extensions disable <name>\", undefined, \"usage\");\n const name = resolveExtensionAlias(raw!);\n\n try {\n const list = await fetchExtensions(client, projectId);\n const ext = list.extensions.find((e) => e.name === name);\n if (ext && !ext.manageable) {\n fail(\n `Extension ${name} cannot be managed on this project.`,\n ext.manageableReason ?? undefined,\n \"not_manageable\"\n );\n }\n if (ext?.requiresRestart && ext.enabled) {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Disabling ${name} restarts the project's database. Continue?`\n });\n }\n\n const res = await client.functions.invoke<DisableResult>(\"extensions\", { projectId, extensionName: name }, { path: \"disable\" });\n emit(\n () => success(res.message || `Disabled ${name}`),\n {\n success: res.success,\n extension: res.extension,\n dropped: res.dropped,\n preloadRemoved: res.preloadRemoved,\n restarted: res.restarted ?? false,\n message: res.message\n }\n );\n } catch (e) {\n reportError(e, \"Failed to disable extension\");\n }\n}\n\nfunction printExtensionsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud extensions\")} — Postgres extensions\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List extensions and their state\n ${chalk.blue.bold(\"enable\")} ${chalk.gray(\"<name> [-y]\")} Enable one ${chalk.gray(\"(pgvector alias ⇒ vector)\")}\n ${chalk.blue.bold(\"disable\")} ${chalk.gray(\"<name>\")} Disable one\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--yes, -y\")} Confirm a DB-restarting change\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\n`);\n}\n","/**\n * `rebase cloud settings` — a project's editable configuration.\n *\n * settings Show the current settings\n * settings set [flags] Update name / branch / repo / subdomain\n *\n * These are plain `projects` updates. A subdomain change is validated against\n * `check-subdomain` up front so the CLI fails with the real reason rather than a\n * generic collection error.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { requireClient, requireProject, displayProjectRef, emit, keyValues, success, fail, reportError } from \"./context\";\n\ninterface ProjectSettings {\n id: string | number;\n name?: string;\n subdomain?: string;\n gitRepoUrl?: string;\n gitBranch?: string;\n customDomain?: string;\n provider?: string;\n region?: string;\n}\n\nexport async function settingsCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"set\":\n await setSettings(rawArgs);\n break;\n case undefined:\n case \"show\":\n case \"list\":\n await showSettings(rawArgs);\n break;\n case \"--help\":\n printSettingsHelp();\n break;\n default:\n fail(`Unknown settings command: ${action}`, \"Try `rebase cloud settings --help`.\");\n }\n}\n\nasync function showSettings(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const p = (await client.data.collection(\"projects\").findById(projectId)) as unknown as ProjectSettings | undefined;\n if (!p) fail(`Project ${projectRef} not found.`, undefined, \"not_found\");\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ⚙️ Settings — project ${projectRef}`));\n console.log(\"\");\n keyValues([\n [\"Name\", p!.name],\n [\"Subdomain\", p!.subdomain],\n [\"Repository\", p!.gitRepoUrl],\n [\"Branch\", p!.gitBranch],\n [\"Custom domain\", p!.customDomain],\n [\"Provider\", p!.provider],\n [\"Region\", p!.region]\n ]);\n console.log(\"\");\n },\n {\n projectId: String(p!.id),\n name: p!.name ?? null,\n subdomain: p!.subdomain ?? null,\n gitRepoUrl: p!.gitRepoUrl ?? null,\n gitBranch: p!.gitBranch ?? null,\n customDomain: p!.customDomain ?? null,\n provider: p!.provider ?? null,\n region: p!.region ?? null\n }\n );\n } catch (e) {\n reportError(e, \"Failed to load settings\");\n }\n}\n\n/** Build the update patch from the flags actually supplied (pure/testable). */\nexport function buildSettingsPatch(args: {\n name?: string;\n subdomain?: string;\n repo?: string;\n branch?: string;\n}): Record<string, string> {\n const patch: Record<string, string> = {};\n if (args.name !== undefined) patch.name = args.name;\n if (args.subdomain !== undefined) patch.subdomain = args.subdomain.toLowerCase();\n if (args.repo !== undefined) patch.gitRepoUrl = args.repo;\n if (args.branch !== undefined) patch.gitBranch = args.branch;\n return patch;\n}\n\nasync function setSettings(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--name\": String,\n \"--subdomain\": String,\n \"--repo\": String,\n \"--branch\": String,\n \"--project\": String,\n \"-p\": \"--project\"\n },\n { argv: rawArgs.slice(2), permissive: true }\n );\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const patch = buildSettingsPatch({\n name: args[\"--name\"],\n subdomain: args[\"--subdomain\"],\n repo: args[\"--repo\"],\n branch: args[\"--branch\"]\n });\n if (Object.keys(patch).length === 0) {\n fail(\"Nothing to update.\", \"Pass --name, --subdomain, --repo, or --branch.\", \"usage\");\n }\n\n try {\n if (patch.subdomain) {\n const check = await client.functions\n .invoke<{ available: boolean; reason?: string }>(\"check-subdomain\", { subdomain: patch.subdomain })\n .catch(() => undefined);\n if (check && !check.available) {\n fail(`Subdomain \"${patch.subdomain}\" is not available${check.reason ? ` (${check.reason})` : \"\"}.`, undefined, \"subdomain_taken\");\n }\n }\n\n await client.data.collection(\"projects\").update(projectId, patch);\n emit(\n () => success(`Updated ${Object.keys(patch).join(\", \")} for project ${projectRef}`),\n { success: true, projectId, updated: patch }\n );\n } catch (e) {\n reportError(e, \"Failed to update settings\");\n }\n}\n\nfunction printSettingsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud settings\")} — Project configuration\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"show\")} Show current settings\n ${chalk.blue.bold(\"set\")} ${chalk.gray(\"[flags]\")} Update settings\n\n${chalk.green.bold(\"Set flags\")}\n ${chalk.blue(\"--name\")} ${chalk.gray(\"<name>\")}\n ${chalk.blue(\"--subdomain\")} ${chalk.gray(\"<sub>\")}\n ${chalk.blue(\"--repo\")} ${chalk.gray(\"<git url>\")}\n ${chalk.blue(\"--branch\")} ${chalk.gray(\"<branch>\")}\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\n`);\n}\n","/**\n * Deployment lifecycle: `rebase cloud deployments list`, `rollback`, `cancel`.\n *\n * The rollback rule is the load-bearing part. A rollback is only honoured for a\n * SUCCESSFUL deploy that recorded an image (`status === \"success\" && imageUrl`);\n * anything else 409s `deploy_not_rollbackable` server-side. So this module never\n * offers — and refuses to invoke — a rollback the server would reject, exactly\n * mirroring the console's `isRollbackable`.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n confirmDestructive,\n colorStatus,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\n/** A deployment row, as the data API hands it back (camel or snake columns). */\nexport interface DeploymentRow {\n id: string | number;\n status?: string;\n createdAt?: string | Date;\n created_at?: string | Date;\n finishedAt?: string | Date;\n finished_at?: string | Date;\n imageUrl?: string;\n image_url?: string;\n rollbackOf?: string;\n rollback_of?: string;\n triggeredBy?: string;\n triggered_by?: string;\n triggerSource?: string;\n trigger_source?: string;\n triggeredByUserId?: string;\n triggered_by_user_id?: string;\n gitCommitHash?: string;\n gitCommitMessage?: string;\n}\n\nfunction str(dep: DeploymentRow, camel: keyof DeploymentRow, snake: keyof DeploymentRow): string | null {\n const raw = (dep[camel] ?? dep[snake]) as unknown;\n return typeof raw === \"string\" && raw.trim() !== \"\" ? raw.trim() : null;\n}\n\nfunction isoOf(dep: DeploymentRow, camel: keyof DeploymentRow, snake: keyof DeploymentRow): string | null {\n const raw = (dep[camel] ?? dep[snake]) as unknown;\n if (raw instanceof Date) return Number.isNaN(raw.getTime()) ? null : raw.toISOString();\n return typeof raw === \"string\" && raw.trim() !== \"\" ? raw.trim() : null;\n}\n\nexport function deploymentImage(dep: DeploymentRow): string | null {\n return str(dep, \"imageUrl\", \"image_url\");\n}\n\n/**\n * The backend's rule EXACTLY: a rollback is honoured only for a successful\n * deploy that recorded an image. Any other row 409s `deploy_not_rollbackable`.\n */\nexport function isRollbackable(dep: DeploymentRow): boolean {\n return dep.status === \"success\" && deploymentImage(dep) !== null;\n}\n\n/** finishedAt − createdAt in ms, or null (still running / missing / skewed). */\nexport function deploymentDurationMs(dep: DeploymentRow): number | null {\n const created = isoOf(dep, \"createdAt\", \"created_at\");\n const finished = isoOf(dep, \"finishedAt\", \"finished_at\");\n if (!created || !finished) return null;\n const a = new Date(created).getTime();\n const b = new Date(finished).getTime();\n if (Number.isNaN(a) || Number.isNaN(b)) return null;\n const ms = b - a;\n return ms >= 0 ? ms : null;\n}\n\nfunction formatDuration(ms: number): string {\n const totalSec = Math.max(0, Math.round(ms / 1000));\n if (totalSec < 60) return `${totalSec}s`;\n const m = Math.floor(totalSec / 60);\n const s = totalSec % 60;\n if (m < 60) return s ? `${m}m ${s}s` : `${m}m`;\n const h = Math.floor(m / 60);\n const mm = m % 60;\n return mm ? `${h}h ${mm}m` : `${h}h`;\n}\n\nconst TRIGGERED_BY = [\"user\", \"automation\", \"unknown\"] as const;\nconst TRIGGER_SOURCES = [\"console\", \"cli\", \"webhook\", \"unknown\"] as const;\n\nexport function triggerInfo(dep: DeploymentRow): { by: string; source: string; userId: string } {\n const byRaw = (dep.triggeredBy ?? dep.triggered_by) as unknown;\n const srcRaw = (dep.triggerSource ?? dep.trigger_source) as unknown;\n const by = typeof byRaw === \"string\" && (TRIGGERED_BY as readonly string[]).includes(byRaw) ? byRaw : \"unknown\";\n const source =\n typeof srcRaw === \"string\" && (TRIGGER_SOURCES as readonly string[]).includes(srcRaw) ? srcRaw : \"unknown\";\n return { by, source, userId: str(dep, \"triggeredByUserId\", \"triggered_by_user_id\") ?? \"\" };\n}\n\n/** Shape one deployment row into the stable JSON view the CLI publishes. */\nexport function deploymentView(dep: DeploymentRow): Record<string, unknown> {\n const durationMs = deploymentDurationMs(dep);\n return {\n id: String(dep.id),\n status: dep.status ?? null,\n createdAt: isoOf(dep, \"createdAt\", \"created_at\"),\n finishedAt: isoOf(dep, \"finishedAt\", \"finished_at\"),\n durationMs,\n image: deploymentImage(dep),\n rollbackOf: str(dep, \"rollbackOf\", \"rollback_of\"),\n isRollback: str(dep, \"rollbackOf\", \"rollback_of\") !== null,\n rollbackable: isRollbackable(dep),\n trigger: triggerInfo(dep),\n commit: {\n hash: str(dep, \"gitCommitHash\", \"gitCommitHash\"),\n message: str(dep, \"gitCommitMessage\", \"gitCommitMessage\")\n }\n };\n}\n\nasync function fetchDeployments(client: CloudClient, projectId: string, limit = 100): Promise<DeploymentRow[]> {\n const res = await client.data.collection(\"deployments\").find({\n where: { project: [\"==\", projectId] },\n orderBy: [\"createdAt\", \"desc\"],\n limit\n });\n return res.data as unknown as DeploymentRow[];\n}\n\nexport async function deploymentsListCommand(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const rows = await fetchDeployments(client, projectId);\n const views = rows.map(deploymentView);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🚀 Deployments — project ${projectRef}`));\n console.log(\"\");\n if (!views.length) {\n console.log(chalk.gray(\" No deployments yet. Deploy with `rebase cloud deploy`.\"));\n console.log(\"\");\n return;\n }\n for (const v of views) {\n const dur = v.durationMs !== null ? formatDuration(v.durationMs as number) : chalk.gray(\"running\");\n const trig = (v.trigger as { source: string }).source;\n const roll = v.rollbackable ? chalk.green(\" ↺ rollbackable\") : \"\";\n console.log(\n ` ${chalk.gray(`[${v.id}]`)} ${colorStatus(v.status as string)} ${chalk.gray(String(v.createdAt ?? \"—\"))} ${dur} ${chalk.gray(trig)}${roll}`\n );\n }\n console.log(\"\");\n },\n { projectId, deployments: views }\n );\n } catch (e) {\n reportError(e, \"Failed to list deployments\");\n }\n}\n\nexport async function rollbackCommand(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n // `rollback [deploymentId]` — the id, when given, is the first operand after\n // the `rollback` group token.\n const explicitId = cloudPositionals(rawArgs).slice(1)[0];\n\n // Fetch history — the only step here that can fail with a server error.\n let rows: DeploymentRow[];\n try {\n rows = await fetchDeployments(client, projectId);\n } catch (e) {\n reportError(e, \"Failed to read deployment history\");\n }\n if (!rows!.length) fail(\"No deployments to roll back to.\", undefined, \"no_deployments\");\n\n // Select + validate the target OUTSIDE any catch — a refusal here is a\n // deliberate exit, never a server error to re-wrap.\n let target: DeploymentRow | undefined;\n if (explicitId) {\n target = rows!.find((d) => String(d.id) === explicitId);\n if (!target) fail(`Deployment ${explicitId} not found for project ${projectRef}.`, undefined, \"not_found\");\n // Refuse locally rather than let the server 409 — this is the safety\n // contract, mirrored from the backend's rollback rule.\n if (!isRollbackable(target!)) {\n fail(\n `Deployment ${explicitId} is not rollbackable (needs a successful deploy that recorded an image).`,\n \"List candidates with `rebase cloud deployments list`.\",\n \"deploy_not_rollbackable\"\n );\n }\n } else {\n const rollbackable = rows!.filter(isRollbackable);\n if (!rollbackable.length) {\n fail(\n \"No rollbackable deployment found (needs a successful deploy that recorded an image).\",\n \"List history with `rebase cloud deployments list`.\",\n \"deploy_not_rollbackable\"\n );\n }\n // Prefer the previous good image when the newest deploy is itself good\n // (rolling back to the live image is a no-op); otherwise the most recent\n // good one.\n target = rollbackable.find((d) => String(d.id) !== String(rows![0].id)) ?? rollbackable[0];\n }\n\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Roll project ${projectRef} back to deployment ${target!.id}? This starts a new deployment.`\n });\n\n try {\n const res = await client.functions.invoke<{\n success: boolean;\n deployment: { id: string };\n rolledBackTo: string;\n imageUrl: string;\n }>(\"deploy\", { projectId, deploymentId: String(target!.id), client: \"cli\" }, { path: \"rollback\" });\n\n emit(\n () => {\n success(`Rolling back to deployment ${chalk.bold(String(target!.id))}`);\n keyValues([\n [\"New deployment\", res.deployment?.id ? String(res.deployment.id) : undefined],\n [\"Rolled back to\", res.rolledBackTo],\n [\"Image\", res.imageUrl]\n ]);\n console.log(chalk.gray(\" Follow it with `rebase cloud logs -f`.\"));\n console.log(\"\");\n },\n {\n success: true,\n deploymentId: res.deployment?.id ?? null,\n rolledBackTo: res.rolledBackTo,\n imageUrl: res.imageUrl\n }\n );\n } catch (e) {\n reportError(e, \"Failed to roll back\");\n }\n}\n\nexport async function cancelCommand(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const explicitId = cloudPositionals(rawArgs).slice(1)[0];\n\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Cancel the in-flight build for project ${projectRef}?`\n });\n\n try {\n const res = await client.functions.invoke<{ success: boolean; deploymentId: string; buildJobDeleted: boolean }>(\n \"deploy\",\n explicitId ? { projectId, deploymentId: explicitId } : { projectId },\n { path: \"cancel\" }\n );\n emit(\n () => {\n success(`Cancelled deployment ${chalk.bold(res.deploymentId)}`);\n if (res.buildJobDeleted) console.log(chalk.gray(\" The build job was deleted.\"));\n console.log(\"\");\n },\n { success: true, deploymentId: res.deploymentId, buildJobDeleted: res.buildJobDeleted }\n );\n } catch (e) {\n const err = e as { status?: number };\n if (err?.status === 404) {\n fail(\"No deployment in progress to cancel.\", undefined, \"not_found\");\n }\n reportError(e, \"Failed to cancel deployment\");\n }\n}\n","/**\n * `rebase cloud start | stop | restart` — power operations.\n *\n * These flip the project's `status`, exactly as the console's `handleServerAction`\n * does: stop → `stopped`, start → `active`, restart → stop then start with a\n * brief pause in between (a real stop→start with genuine downtime). Stop and\n * restart cause downtime, so they require `--yes` in non-interactive use.\n */\nimport arg from \"arg\";\nimport { requireClient, requireProject, displayProjectRef, emit, confirmDestructive, success, reportError, type CloudClient } from \"./context\";\n\ntype PowerAction = \"start\" | \"stop\" | \"restart\";\n\nasync function setStatus(client: CloudClient, projectId: string, status: \"active\" | \"stopped\"): Promise<void> {\n await client.data.collection(\"projects\").update(projectId, { status });\n}\n\nexport async function powerCommand(action: PowerAction, rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n // start is benign; stop and restart cause downtime and are gated.\n if (action !== \"start\") {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `${action === \"stop\" ? \"Stop\" : \"Restart\"} project ${projectRef}? This causes downtime.`\n });\n }\n\n try {\n if (action === \"stop\") {\n await setStatus(client, projectId, \"stopped\");\n emit(() => success(`Stopped project ${projectRef}`), { success: true, projectId, status: \"stopped\" });\n } else if (action === \"start\") {\n await setStatus(client, projectId, \"active\");\n emit(() => success(`Started project ${projectRef}`), { success: true, projectId, status: \"active\" });\n } else {\n await setStatus(client, projectId, \"stopped\");\n await new Promise((r) => setTimeout(r, 1500));\n await setStatus(client, projectId, \"active\");\n emit(() => success(`Restarted project ${projectRef}`), { success: true, projectId, status: \"active\" });\n }\n } catch (e) {\n reportError(e, `Failed to ${action} project`);\n }\n}\n\nexport function isPowerAction(v: string | undefined): v is PowerAction {\n return v === \"start\" || v === \"stop\" || v === \"restart\";\n}\n","/**\n * `rebase cloud` resource subcommands: status, metrics, webhooks, storage,\n * clusters, billing.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n lookupProjectId,\n displayProjectRef,\n getContextOrg,\n readLink,\n colorStatus,\n keyValues,\n fetchTenantBaseDomain,\n projectHost,\n openUrl,\n success,\n fail,\n reportError\n} from \"./context\";\nimport { firstRow, latestDeployment, fmtDate } from \"./projects\";\n\n/* ─── status: quick project dashboard ──────────────────────────── */\n\nexport async function statusCommand(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n try {\n const project = (await client.data.collection(\"projects\").findById(projectId)) as\n | { id: string | number; name?: string; subdomain?: string; host?: string; status?: string; gitBranch?: string }\n | undefined;\n if (!project) fail(`Project ${displayProjectRef(rawArgs)} not found.`);\n\n const [db, storage, deploy, baseDomain] = await Promise.all([\n firstRow(client, \"databases\", projectId),\n firstRow(client, \"storages\", projectId),\n latestDeployment(client, projectId),\n fetchTenantBaseDomain(client, url)\n ]);\n\n console.log(\"\");\n console.log(` ${chalk.bold(project.name ?? project.subdomain ?? \"\")} ${chalk.gray(`[${project.subdomain ?? displayProjectRef(rawArgs)}]`)} ${colorStatus(project.status)}`);\n console.log(\"\");\n keyValues([\n [\"URL\", projectHost(project, baseDomain)],\n [\"Branch\", project.gitBranch],\n [\"Last deploy\", deploy ? `${colorStatus(deploy.status)} · ${fmtDate(deploy.createdAt)}` : \"never\"],\n [\"Database\", db ? `${db.type} (${colorStatus(db.connectionStatus as string)})` : \"none\"],\n [\"Storage\", storage ? `${storage.type} (${colorStatus(storage.status as string)})` : \"none\"]\n ]);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to load status\");\n }\n}\n\n/* ─── metrics: live compute metrics ────────────────────────────── */\n\nexport async function metricsCommand(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n try {\n const m = await client.functions.invoke<{\n status?: string;\n cpu?: string;\n memory?: string;\n memoryPercent?: string;\n disk?: string;\n }>(\"metrics\", undefined, { method: \"GET\",\npath: projectId });\n\n console.log(\"\");\n console.log(chalk.bold(` 📊 Metrics — project ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n keyValues([\n [\"Status\", m.status ? colorStatus(m.status === \"running\" ? \"active\" : m.status) : undefined],\n [\"CPU\", m.cpu],\n [\"Memory\", m.memory ? `${m.memory}${m.memoryPercent ? ` (${m.memoryPercent})` : \"\"}` : undefined],\n [\"Disk\", m.disk]\n ]);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to fetch metrics\");\n }\n}\n\n/* ─── webhooks ─────────────────────────────────────────────────── */\n\nexport async function webhooksCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n try {\n if (subcommand === \"create\") {\n const args = arg(\n { \"--name\": String,\n\"--table\": String,\n\"--url\": String,\n\"--events\": String },\n { argv: rawArgs.slice(4),\npermissive: true }\n );\n const name = args[\"--name\"] || fail(\"--name is required.\");\n const table = args[\"--table\"] || fail(\"--table is required.\");\n const url = args[\"--url\"] || fail(\"--url (endpoint) is required.\");\n const events = (args[\"--events\"] || \"insert,update,delete\").split(\",\").map((s) => s.trim());\n\n const created = (await client.data.collection(\"webhooks\").create({\n project: projectId,\n name,\n table,\n url,\n events,\n enabled: true\n })) as unknown as { id: string | number };\n success(`Created webhook ${chalk.bold(name)} [${created.id}]`);\n return;\n }\n\n if (subcommand === \"delete\") {\n const id = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[2];\n if (!id) fail(\"Usage: rebase cloud webhooks delete <id>\");\n await client.data.collection(\"webhooks\").delete(id);\n success(`Deleted webhook ${id}`);\n return;\n }\n\n // list\n const hooks = (await client.data.collection(\"webhooks\").find({\n where: { project: [\"==\", projectId] },\n limit: 100\n })).data as unknown as Array<{ id: string | number; name?: string; table?: string; url?: string; enabled?: boolean; events?: string[] }>;\n\n console.log(\"\");\n console.log(chalk.bold(` 🔗 Webhooks — project ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n if (hooks.length === 0) {\n console.log(chalk.gray(\" No webhooks. Add one with `rebase cloud webhooks create`.\"));\n console.log(\"\");\n return;\n }\n for (const h of hooks) {\n const state = h.enabled ? chalk.green(\"enabled\") : chalk.gray(\"disabled\");\n console.log(` ${chalk.bold(h.name ?? \"(unnamed)\")} ${chalk.gray(`[${h.id}]`)} ${state}`);\n console.log(` ${chalk.gray(`${h.table ?? \"?\"} → ${h.url ?? \"?\"} (${(h.events ?? []).join(\", \")})`)}`);\n }\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Webhook operation failed\");\n }\n}\n\n/* ─── storage ──────────────────────────────────────────────────── */\n\nexport async function storageCommand(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n try {\n const stores = (await client.data.collection(\"storages\").find({\n where: { project: [\"==\", projectId] },\n limit: 50\n })).data as unknown as Array<{ id: string | number; type?: string; provider?: string; bucketName?: string; status?: string }>;\n\n console.log(\"\");\n console.log(chalk.bold(` 🪣 Storage — project ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n if (stores.length === 0) {\n console.log(chalk.gray(\" No storage buckets attached.\"));\n console.log(\"\");\n return;\n }\n for (const s of stores) {\n console.log(` ${chalk.bold(s.bucketName ?? s.type ?? \"bucket\")} ${chalk.gray(`[${s.id}]`)} ${colorStatus(s.status)}`);\n keyValues([[\"Provider\", s.provider], [\"Type\", s.type]]);\n }\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list storage\");\n }\n}\n\n/* ─── clusters ─────────────────────────────────────────────────── */\n\nexport async function clustersCommand(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n try {\n const clusters = (await client.data.collection(\"clusters\").find({ limit: 100 })).data as unknown as Array<{\n id: string | number;\n name?: string;\n provider?: string;\n region?: string;\n status?: string;\n }>;\n\n console.log(\"\");\n console.log(chalk.bold(\" ☸ Clusters\"));\n console.log(\"\");\n if (clusters.length === 0) {\n console.log(chalk.gray(\" No clusters registered.\"));\n console.log(\"\");\n return;\n }\n for (const c of clusters) {\n console.log(` ${chalk.bold(c.name ?? \"(unnamed)\")} ${chalk.gray(`[${c.id}]`)} ${colorStatus(c.status)}`);\n keyValues([[\"Provider\", c.provider], [\"Region\", c.region]]);\n }\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list clusters\");\n }\n}\n\n/* ─── billing ──────────────────────────────────────────────────── */\n\nexport async function billingCommand(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n const org = getContextOrg(url);\n\n const action = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[1];\n\n // `rebase cloud billing setup` — attach a card to the org (one-time, opens a\n // browser). Once done, project create/deploy work headlessly (off_session).\n if (action === \"setup\") {\n if (!org) fail(\"No active organization.\", \"Run `rebase cloud use` first.\");\n try {\n const res = await client.functions.invoke<{ url?: string; simulated?: boolean }>(\n \"stripe-billing\",\n { organizationId: org },\n { path: \"setup-session\" }\n );\n if (!res.url) fail(\"Could not start billing setup.\");\n openUrl(res.url, \"Add a payment method in your browser:\");\n if (res.simulated) {\n console.log(chalk.gray(\" (dev mode — Stripe not configured; complete setup from the console)\"));\n console.log(\"\");\n } else {\n console.log(chalk.gray(\" Once you've added a card, `rebase cloud deploy` runs without further prompts.\"));\n console.log(\"\");\n }\n } catch (e) {\n reportError(e, \"Failed to start billing setup\");\n }\n return;\n }\n\n // `rebase cloud billing checkout --project <slug>` opens a Stripe session.\n if (action === \"checkout\") {\n const projectId = await requireProject(rawArgs, client);\n try {\n const res = await client.functions.invoke<{ url?: string }>(\n \"stripe-billing\",\n { projectId },\n { path: \"session\" }\n );\n if (!res.url) fail(\"Billing session could not be created.\");\n console.log(\"\");\n console.log(\" Complete checkout in your browser:\");\n console.log(` ${chalk.cyan(res.url)}`);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to start checkout\");\n }\n return;\n }\n\n // default: show the active org's billing account.\n if (!org) fail(\"No active organization.\", \"Run `rebase cloud use` first.\");\n try {\n const orgRow = (await client.data.collection(\"organizations\").findById(org)) as\n | { billing_account_id?: string | number; billingAccount?: string | number }\n | undefined;\n const billingId = orgRow?.billing_account_id ?? orgRow?.billingAccount;\n if (!billingId) {\n console.log(\"\");\n console.log(chalk.gray(` Organization ${org} has no billing account yet.`));\n console.log(\"\");\n return;\n }\n const acct = (await client.data.collection(\"billing-accounts\").findById(billingId)) as\n | { id: string | number; billingEmail?: string; status?: string; stripeCustomerId?: string }\n | undefined;\n\n // Card-on-file lives in Stripe; the control plane reports it for us.\n let card: { hasPaymentMethod?: boolean; brand?: string; last4?: string; expMonth?: number; expYear?: number } = {};\n try {\n card = await client.functions.invoke<typeof card>(\n \"stripe-billing\",\n undefined,\n { method: \"GET\",\npath: `payment-method/${org}` }\n );\n } catch {\n // status endpoint optional — fall back to the local account record\n }\n\n // Best-effort: show which plan the linked/`--project` project is on.\n // BYO-cluster projects pay a flat platform fee; the rest pay managed compute.\n let plan: string | undefined;\n try {\n const parsed = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(2),\npermissive: true });\n const ref = parsed[\"--project\"] || readLink()?.projectId;\n const projectId = ref ? await lookupProjectId(ref, client) : undefined;\n if (projectId) {\n const proj = (await client.data.collection(\"projects\").findById(projectId)) as\n | { cluster_id?: string | number; cluster?: unknown; provider?: string; vmSize?: string }\n | undefined;\n const hasCluster = proj?.cluster_id != null || proj?.cluster != null;\n plan = hasCluster ? \"platform fee (own cluster)\" : \"managed compute\";\n\n // Best-effort: append the resolved monthly amount from Stripe (via\n // the control plane's /api/functions/pricing). Keep working if the\n // endpoint is unreachable — the label alone is still useful.\n try {\n const pricing = await client.functions.invoke<{\n items: Array<{ lookupKey: string; amountEur: number }>;\n }>(\"pricing\", undefined, { method: \"GET\" });\n const key = hasCluster\n ? \"platform_byo\"\n : `compute_${proj?.provider || \"hetzner\"}_${proj?.vmSize || \"cx21\"}`;\n const item = pricing.items?.find((i) => i.lookupKey === key);\n if (item) plan = `${plan} — €${item.amountEur.toFixed(2)}/mo`;\n } catch {\n // pricing endpoint unreachable — keep the plan label without an amount\n }\n }\n } catch {\n // no linked/resolvable project — skip the Plan line\n }\n\n console.log(\"\");\n console.log(chalk.bold(` 💳 Billing — org ${org}`));\n console.log(\"\");\n keyValues([\n [\"Account\", acct ? String(acct.id) : undefined],\n [\"Email\", acct?.billingEmail],\n [\"Status\", acct?.status ? colorStatus(acct.status) : undefined],\n [\"Plan\", plan],\n [\n \"Payment method\",\n card.hasPaymentMethod\n ? `${card.brand ?? \"card\"} •••• ${card.last4 ?? \"????\"}${card.expMonth ? ` (exp ${card.expMonth}/${card.expYear})` : \"\"}`\n : chalk.yellow(\"none — run `rebase cloud billing setup`\")\n ]\n ]);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to load billing\");\n }\n}\n","/**\n * CLI command: `rebase cloud <group> [action] [options]`\n *\n * A single entry point for everything you do against Rebase Cloud — the hosted\n * control plane. Auth, project link, deploys, databases, and the rest are all\n * dispatched from here. Individual groups live in sibling modules; this file\n * only routes and prints help.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { loginCommand, logoutCommand, whoamiCommand } from \"./auth\";\nimport { linkCommand, unlinkCommand, selectOrgCommand, openCommand } from \"./link\";\nimport { listProjects, createProject, projectInfo, deleteProject } from \"./projects\";\nimport { deployCommand, logsCommand } from \"./deploy\";\nimport { orgsCommand } from \"./orgs\";\nimport { dbCommand } from \"./databases\";\nimport { envCommand } from \"./env\";\nimport { domainsCommand } from \"./domains\";\nimport { extensionsCommand } from \"./extensions\";\nimport { settingsCommand } from \"./settings\";\nimport { deploymentsListCommand, rollbackCommand, cancelCommand } from \"./deployments\";\nimport { powerCommand } from \"./power\";\nimport {\n statusCommand,\n metricsCommand,\n webhooksCommand,\n storageCommand,\n clustersCommand,\n billingCommand\n} from \"./resources\";\nimport { requireProjectRef, initOutputMode } from \"./context\";\n\n/** Positional tokens after `rebase cloud` (group, action, …). */\nfunction positionals(rawArgs: string[]): string[] {\n return arg({}, { argv: rawArgs.slice(3),\npermissive: true })._;\n}\n\nexport async function cloudCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // Latch the output mode FIRST — before anything can print or `fail` — so the\n // whole command family agrees on human vs. machine-readable output.\n initOutputMode(rawArgs);\n\n const pos = positionals(rawArgs);\n const group = subcommand && subcommand !== \"--help\" ? subcommand : pos[0];\n const action = pos[1];\n\n if (!group || subcommand === \"--help\") {\n printCloudHelp();\n return;\n }\n\n switch (group) {\n /* auth */\n case \"login\":\n await loginCommand(rawArgs);\n break;\n case \"logout\":\n await logoutCommand(rawArgs);\n break;\n case \"whoami\":\n await whoamiCommand(rawArgs);\n break;\n\n /* context / link */\n case \"link\":\n await linkCommand(rawArgs);\n break;\n case \"unlink\":\n unlinkCommand();\n break;\n case \"use\":\n await selectOrgCommand(rawArgs);\n break;\n case \"open\":\n openCommand(rawArgs);\n break;\n\n /* projects */\n case \"projects\":\n case \"project\":\n await projectsGroup(action, rawArgs);\n break;\n\n /* deploy + logs (operate on linked/--project) */\n case \"deploy\":\n await deployCommand(rawArgs, requireProjectRef(rawArgs));\n break;\n case \"logs\":\n await logsCommand(rawArgs, requireProjectRef(rawArgs));\n break;\n case \"deployments\":\n case \"releases\":\n await deploymentsGroup(action, rawArgs);\n break;\n case \"rollback\":\n await rollbackCommand(rawArgs);\n break;\n case \"cancel\":\n await cancelCommand(rawArgs);\n break;\n case \"start\":\n case \"stop\":\n case \"restart\":\n await powerCommand(group, rawArgs);\n break;\n case \"status\":\n await statusCommand(rawArgs);\n break;\n case \"metrics\":\n await metricsCommand(rawArgs);\n break;\n\n /* env / domains / extensions / settings */\n case \"env\":\n await envCommand(action, rawArgs);\n break;\n case \"domains\":\n case \"domain\":\n await domainsCommand(action, rawArgs);\n break;\n case \"extensions\":\n case \"extension\":\n await extensionsCommand(action, rawArgs);\n break;\n case \"settings\":\n await settingsCommand(action, rawArgs);\n break;\n\n /* orgs */\n case \"orgs\":\n case \"org\":\n await orgsCommand(action, rawArgs);\n break;\n\n /* databases */\n case \"db\":\n case \"database\":\n await dbCommand(action, rawArgs);\n break;\n\n /* other resources */\n case \"webhooks\":\n await webhooksCommand(action, rawArgs);\n break;\n case \"storage\":\n await storageCommand(rawArgs);\n break;\n case \"clusters\":\n await clustersCommand(rawArgs);\n break;\n case \"billing\":\n await billingCommand(rawArgs);\n break;\n\n default:\n console.error(chalk.red(`Unknown cloud command: ${group}`));\n console.log(\"\");\n printCloudHelp();\n process.exit(1);\n }\n}\n\nasync function projectsGroup(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case undefined:\n await listProjects(rawArgs);\n break;\n case \"create\":\n await createProject(rawArgs);\n break;\n case \"info\": {\n const id = positionals(rawArgs)[2] || requireProjectRef(rawArgs);\n await projectInfo(rawArgs, id);\n break;\n }\n case \"delete\": {\n const id = positionals(rawArgs)[2] || requireProjectRef(rawArgs);\n await deleteProject(rawArgs, id);\n break;\n }\n case \"--help\":\n printCloudHelp();\n break;\n default:\n console.error(chalk.red(`Unknown projects command: ${action}`));\n process.exit(1);\n }\n}\n\nasync function deploymentsGroup(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case undefined:\n await deploymentsListCommand(rawArgs);\n break;\n case \"--help\":\n printCloudHelp();\n break;\n default:\n console.error(chalk.red(`Unknown deployments command: ${action}`));\n process.exit(1);\n }\n}\n\nfunction printCloudHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud\")} — Manage your apps on Rebase Cloud\n\n${chalk.green.bold(\"Usage\")}\n rebase cloud ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Auth\")}\n ${chalk.blue.bold(\"login\")} Sign in to the control plane\n ${chalk.blue.bold(\"logout\")} Sign out\n ${chalk.blue.bold(\"whoami\")} Show the current session\n\n${chalk.green.bold(\"Project link\")}\n ${chalk.blue.bold(\"link\")} Link this directory to a cloud project\n ${chalk.blue.bold(\"unlink\")} Remove the link\n ${chalk.blue.bold(\"use\")} ${chalk.gray(\"[org]\")} Select the active organization\n ${chalk.blue.bold(\"open\")} Open the dashboard in a browser\n\n${chalk.green.bold(\"Projects\")}\n ${chalk.blue.bold(\"projects list\")} List projects\n ${chalk.blue.bold(\"projects create\")} Create a project ${chalk.gray(\"(--link to link it)\")}\n ${chalk.blue.bold(\"projects info\")} ${chalk.gray(\"[id]\")} Show project details\n ${chalk.blue.bold(\"projects delete\")} ${chalk.gray(\"[id]\")} Delete a project\n\n${chalk.green.bold(\"Deploy & observe\")}\n ${chalk.blue.bold(\"deploy\")} ${chalk.gray(\"[--source .]\")} Deploy the linked project + stream build logs\n ${chalk.blue.bold(\"logs\")} ${chalk.gray(\"[--runtime] [-f]\")} Show build (or runtime) logs\n ${chalk.blue.bold(\"deployments list\")} Deployment history ${chalk.gray(\"(status, duration, trigger)\")}\n ${chalk.blue.bold(\"rollback\")} ${chalk.gray(\"[id] [-y]\")} Roll back to a successful deploy\n ${chalk.blue.bold(\"cancel\")} ${chalk.gray(\"[-y]\")} Cancel the in-flight build\n ${chalk.blue.bold(\"start|stop|restart\")} ${chalk.gray(\"[-y]\")} Power ops ${chalk.gray(\"(stop/restart need -y)\")}\n ${chalk.blue.bold(\"status\")} One-glance project status\n ${chalk.blue.bold(\"metrics\")} Live CPU / memory / disk\n\n${chalk.green.bold(\"Config\")}\n ${chalk.blue.bold(\"env list|set|unset|reveal|pull\")}\n ${chalk.blue.bold(\"domains list|add|verify|remove\")}\n ${chalk.blue.bold(\"extensions list|enable|disable\")}\n ${chalk.blue.bold(\"settings show|set\")} Name / branch / repo / subdomain\n\n${chalk.green.bold(\"Organizations\")}\n ${chalk.blue.bold(\"orgs list|create|members\")}\n\n${chalk.green.bold(\"Databases\")}\n ${chalk.blue.bold(\"db list|create|info|test\")}\n ${chalk.blue.bold(\"db backup list|create|restore|status|download\")}\n ${chalk.blue.bold(\"db pitr status|restore|cutover|discard\")}\n\n${chalk.green.bold(\"Other resources\")}\n ${chalk.blue.bold(\"webhooks list|create|delete\")}\n ${chalk.blue.bold(\"storage\")} List storage buckets\n ${chalk.blue.bold(\"clusters\")} List compute clusters\n ${chalk.blue.bold(\"billing setup\")} Attach a card to the org ${chalk.gray(\"(one-time, opens browser)\")}\n ${chalk.blue.bold(\"billing\")} Show billing account + card on file\n\n${chalk.green.bold(\"Global options\")}\n ${chalk.blue(\"--json\")} Machine-readable output ${chalk.gray(\"(also when piped, or REBASE_JSON=1)\")}\n ${chalk.blue(\"--url <origin>\")} Target a specific control plane ${chalk.gray(\"(or REBASE_CLOUD_URL)\")}\n ${chalk.blue(\"--project, -p <id>\")} Operate on a project without linking\n\n${chalk.gray(\"Most commands act on the linked project (.rebase/cloud.json) unless --project is given.\")}\n${chalk.gray(\"Docs: https://rebase.pro/docs\")}\n`);\n}\n","import chalk from \"chalk\";\nimport arg from \"arg\";\nimport { createRebaseApp } from \"./commands/init\";\nimport { generateSdkCommand } from \"./commands/generate_sdk\";\nimport { schemaCommand } from \"./commands/schema\";\nimport { dbCommand } from \"./commands/db\";\nimport { devCommand } from \"./commands/dev\";\nimport { buildCommand } from \"./commands/build\";\nimport { startCommand } from \"./commands/start\";\nimport { authCommand } from \"./commands/auth\";\nimport { doctorCommand } from \"./commands/doctor\";\nimport { skillsCommand } from \"./commands/skills\";\nimport { apiKeysCommand } from \"./commands/api-keys\";\nimport { cloudCommand } from \"./commands/cloud\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nfunction getVersion(): string {\n try {\n // Try to read version from package.json\n const pkgPath = path.resolve(__dirname, \"../package.json\");\n if (fs.existsSync(pkgPath)) {\n return JSON.parse(fs.readFileSync(pkgPath, \"utf-8\")).version;\n }\n } catch {\n // ignore\n }\n return \"unknown\";\n}\n\nexport async function entry(args: string[]) {\n const parsedArgs = arg(\n {\n \"--version\": Boolean,\n \"--help\": Boolean,\n \"-v\": \"--version\",\n \"-h\": \"--help\"\n },\n {\n argv: args.slice(2),\n permissive: true\n }\n );\n\n if (parsedArgs[\"--version\"]) {\n console.log(getVersion());\n return;\n }\n\n const command = parsedArgs._[0];\n const subcommand = parsedArgs._[1];\n\n // Show global help only when no command given, or --help with no recognized command\n const namespacedCommands = [\"schema\", \"db\", \"dev\", \"build\", \"start\", \"auth\", \"doctor\", \"skills\", \"api-keys\", \"cloud\"];\n if (!command || (parsedArgs[\"--help\"] && !namespacedCommands.includes(command))) {\n printHelp();\n return;\n }\n\n // For namespaced commands with --help, pass it through as subcommand\n const effectiveSubcommand = parsedArgs[\"--help\"] ? \"--help\" : subcommand;\n\n switch (command) {\n case \"init\":\n await createRebaseApp(args);\n break;\n\n case \"generate-sdk\": {\n const sdkArgs = arg(\n {\n \"--collections-dir\": String,\n \"--output\": String,\n \"-c\": \"--collections-dir\",\n \"-o\": \"--output\"\n },\n {\n argv: args.slice(3),\n permissive: true\n }\n );\n await generateSdkCommand({\n collectionsDir: sdkArgs[\"--collections-dir\"] || \"./config/collections\",\n output: sdkArgs[\"--output\"] || \"./generated/sdk\",\n cwd: process.cwd()\n });\n break;\n }\n\n case \"schema\":\n await schemaCommand(effectiveSubcommand, args);\n break;\n\n case \"db\":\n await dbCommand(effectiveSubcommand, args);\n break;\n\n case \"dev\":\n await devCommand(args);\n break;\n\n case \"build\":\n await buildCommand();\n break;\n\n case \"start\":\n await startCommand();\n break;\n\n case \"auth\":\n await authCommand(effectiveSubcommand, args);\n break;\n\n case \"doctor\":\n await doctorCommand(args);\n break;\n\n case \"skills\":\n await skillsCommand(effectiveSubcommand, args);\n break;\n\n case \"api-keys\":\n await apiKeysCommand(effectiveSubcommand, args);\n break;\n\n case \"cloud\":\n await cloudCommand(effectiveSubcommand, args);\n break;\n\n default:\n console.log(chalk.red(`Unknown command: ${command}`));\n console.log(\"\");\n printHelp();\n }\n}\n\nfunction printHelp() {\n console.log(`\n${chalk.bold(\"Rebase CLI\")} — Developer tools for Rebase projects\n\n${chalk.green.bold(\"Usage\")}\n rebase ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"init\")} Create a new Rebase project\n ${chalk.blue.bold(\"dev\")} Start the development server\n ${chalk.blue.bold(\"build\")} Build all workspace packages\n ${chalk.blue.bold(\"start\")} Start the backend server ${chalk.gray(\"(production)\")}\n\n${chalk.green.bold(\"Schema\")}\n ${chalk.blue.bold(\"schema generate\")} Generate Drizzle schema from collections\n ${chalk.blue.bold(\"schema introspect\")} Introspect database → Rebase collections\n ${chalk.blue.bold(\"schema\")} ${chalk.gray(\"--help\")} Show schema command help\n\n${chalk.green.bold(\"Database\")}\n ${chalk.blue.bold(\"db push\")} Apply schema directly to database ${chalk.gray(\"(dev)\")}\n ${chalk.blue.bold(\"db generate\")} Generate SQL migration files\n ${chalk.blue.bold(\"db migrate\")} Run pending migrations\n ${chalk.blue.bold(\"db\")} ${chalk.gray(\"--help\")} Show database command help\n\n${chalk.green.bold(\"SDK\")}\n ${chalk.blue.bold(\"generate-sdk\")} Generate a typed TypeScript SDK from collections\n\n${chalk.green.bold(\"Auth\")}\n ${chalk.blue.bold(\"auth reset-password\")} Reset a user's password\n ${chalk.blue.bold(\"auth\")} ${chalk.gray(\"--help\")} Show auth command help\n\n${chalk.green.bold(\"Diagnostics\")}\n ${chalk.blue.bold(\"doctor\")} Detect schema drift between collections, schema, and DB\n\n${chalk.green.bold(\"AI Agent Skills\")}\n ${chalk.blue.bold(\"skills install\")} Install Rebase agent skills for your AI coding assistant\n\n${chalk.green.bold(\"API Keys\")}\n ${chalk.blue.bold(\"api-keys list\")} List all service API keys\n ${chalk.blue.bold(\"api-keys create\")} Create a new scoped API key\n ${chalk.blue.bold(\"api-keys revoke\")} Revoke an existing API key\n ${chalk.blue.bold(\"api-keys\")} ${chalk.gray(\"--help\")} Show API key command help\n\n${chalk.green.bold(\"Rebase Cloud\")}\n ${chalk.blue.bold(\"cloud login\")} Sign in to the hosted control plane\n ${chalk.blue.bold(\"cloud link\")} Link this directory to a cloud project\n ${chalk.blue.bold(\"cloud deploy\")} Deploy the linked project + stream logs\n ${chalk.blue.bold(\"cloud\")} ${chalk.gray(\"--help\")} Show all cloud commands\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--version, -v\")} Show version number\n ${chalk.blue(\"--help, -h\")} Show this help message\n\n${chalk.gray(\"Documentation: https://rebase.pro/docs\")}\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,qBAAqB,WAAoC;CAErE,MAAM,YAAY,QAAQ,IAAI,yBAAyB;CACvD,IAAI,UAAU,WAAW,MAAM,GAAG,OAAO;CACzC,IAAI,UAAU,WAAW,OAAO,GAAG,OAAO;CAG1C,IAAI,WAAW;EACX,IAAI,GAAG,WAAW,KAAK,KAAK,WAAW,mBAAmB,CAAC,GAAG,OAAO;EACrE,IAAI,GAAG,WAAW,KAAK,KAAK,WAAW,gBAAgB,CAAC,GAAG,OAAO;CACtE;CAGA,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,QAAQ,WAAW;EACnB,IAAI,GAAG,WAAW,KAAK,KAAK,KAAK,mBAAmB,CAAC,GAAG,OAAO;EAC/D,IAAI,G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,EAAE;;EAE3B,MAAM,KAAK,wCAAwC,EAAE;CACtD;AACD"}
1
+ {"version":3,"file":"index.es.js","names":[],"sources":["../src/utils/package-manager.ts","../src/utils/project.ts","../src/commands/cloud/context.ts","../src/commands/init.ts","../src/commands/generate_sdk.ts","../src/commands/schema.ts","../src/commands/db.ts","../src/commands/dev.ts","../src/commands/build.ts","../src/commands/start.ts","../src/commands/auth.ts","../src/commands/doctor.ts","../src/commands/skills.ts","../src/commands/api-keys.ts","../src/commands/cloud/auth.ts","../src/commands/cloud/link.ts","../src/commands/cloud/projects.ts","../src/commands/cloud/deploy.ts","../src/commands/cloud/orgs.ts","../src/commands/cloud/databases.ts","../src/commands/cloud/env.ts","../src/commands/cloud/domains.ts","../src/commands/cloud/extensions.ts","../src/commands/cloud/settings.ts","../src/commands/cloud/deployments.ts","../src/commands/cloud/power.ts","../src/commands/cloud/resources.ts","../src/commands/cloud/index.ts","../src/cli.ts"],"sourcesContent":["/**\n * Package manager detection and command abstraction.\n *\n * Detects whether the user is running pnpm or npm and provides\n * a unified interface for common package-manager operations so\n * the rest of the CLI never has to hardcode a specific PM.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { spawnSync } from \"child_process\";\n\nexport type PackageManager = \"pnpm\" | \"npm\";\n\nexport interface PMCommands {\n /** The binary name (\"pnpm\" | \"npm\"). */\n name: PackageManager;\n /** Install all dependencies — e.g. `pnpm install` / `npm install`. */\n install: string[];\n /** Run a script — e.g. `pnpm run dev` / `npm run dev`. */\n run: (script: string) => string[];\n /** Execute a local bin — e.g. `pnpm exec rebase ...` / `npx rebase ...`. */\n exec: (bin: string, args: string[]) => string[];\n /** Query the registry — e.g. `pnpm view <pkg> version` / `npm view <pkg> version`. */\n view: (pkg: string, field: string) => string[];\n /** Run all workspace scripts — e.g. `pnpm -r run build` / `npm run build --workspaces`. */\n runAll: (script: string) => string[];\n /** Run a script in a specific workspace — e.g. `pnpm --filter \"*-backend\" start` / `npm run start -w backend`. */\n runWorkspace: (workspace: string, script: string) => string[];\n /** Execute a one-off package — e.g. `pnpm dlx skills ...` / `npx -y skills ...`. */\n dlx: (pkg: string, args: string[]) => string[];\n /** The workspace dependency protocol: `\"workspace:*\"` for pnpm, `\"*\"` for npm. */\n workspaceProtocol: string;\n}\n\n/**\n * Whether pnpm is runnable on this machine.\n *\n * Used to decide whether a fresh project can be scaffolded with pnpm. Kept\n * cheap and non-interactive (short timeout, output discarded) so it never\n * hangs detection if a corepack shim misbehaves.\n */\nexport function isPnpmAvailable(): boolean {\n try {\n const res = spawnSync(\"pnpm\", [\"--version\"], { stdio: \"ignore\", timeout: 3000 });\n return res.status === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Detect the package manager for a Rebase project.\n *\n * Rebase recommends pnpm, so detection prefers it. Crucially, *how the CLI was\n * invoked* (`npx` vs `pnpm dlx`, i.e. `npm_config_user_agent`) is deliberately\n * ignored: running `npx @rebasepro/cli init` says nothing about how the user\n * wants to manage the project they're creating, and letting it pin the scaffold\n * to npm is what made every `npx`-invoked project an npm project.\n *\n * Detection order:\n * 1. An existing lock file — an explicit choice we always respect\n * (`pnpm-lock.yaml` wins over `package-lock.json` when both are present).\n * 2. pnpm, whenever it is installed.\n * 3. npm, only as a fallback when pnpm is genuinely unavailable.\n */\nexport function detectPackageManager(targetDir?: string): PackageManager {\n // 1. Respect an existing project's lock file.\n const dirs = [targetDir, process.cwd()].filter((d): d is string => !!d);\n for (const dir of dirs) {\n if (fs.existsSync(path.join(dir, \"pnpm-lock.yaml\"))) return \"pnpm\";\n if (fs.existsSync(path.join(dir, \"package-lock.json\"))) return \"npm\";\n }\n\n // 2. Prefer pnpm whenever it's installed.\n if (isPnpmAvailable()) return \"pnpm\";\n\n // 3. Fall back to npm only when pnpm is genuinely unavailable.\n return \"npm\";\n}\n\n/** Build the command helpers for a given package manager. */\nexport function getPMCommands(pm: PackageManager): PMCommands {\n if (pm === \"npm\") {\n return {\n name: \"npm\",\n install: [\"npm\", \"install\"],\n run: (script) => [\"npm\", \"run\", script],\n exec: (bin, args) => [\"npx\", bin, ...args],\n view: (pkg, field) => [\"npm\", \"view\", pkg, field],\n runAll: (script) => [\"npm\", \"run\", script, \"--workspaces\", \"--if-present\"],\n runWorkspace: (workspace, script) => [\"npm\", \"run\", script, \"-w\", workspace],\n dlx: (pkg, args) => [\"npx\", \"-y\", pkg, ...args],\n workspaceProtocol: \"*\"\n };\n }\n\n return {\n name: \"pnpm\",\n install: [\"pnpm\", \"install\"],\n run: (script) => [\"pnpm\", \"run\", script],\n exec: (bin, args) => [\"pnpm\", \"exec\", bin, ...args],\n view: (pkg, field) => [\"pnpm\", \"view\", pkg, field],\n runAll: (script) => [\"pnpm\", \"-r\", \"run\", script],\n // Filter by directory (`./backend`), not name: pnpm's `--filter` matches\n // the package *name* (e.g. `my-app-backend`), so a bare `backend` matches\n // nothing. npm's `-w` is path-based, which is why this only bites pnpm.\n runWorkspace: (workspace, script) => [\"pnpm\", \"--filter\", `./${workspace}`, \"run\", script],\n dlx: (pkg, args) => [\"pnpm\", \"dlx\", pkg, ...args],\n workspaceProtocol: \"workspace:*\"\n };\n}\n","/**\n * Project discovery utilities for the Rebase CLI.\n *\n * These helpers locate the project root, backend directory, .env file,\n * and local binaries — used by all CLI command modules.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { execSync } from \"child_process\";\nimport chalk from \"chalk\";\n\n/**\n * Walk up from `startDir` to find the Rebase project root.\n *\n * The root is identified by a `package.json` that either:\n * - has `workspaces` containing \"backend\" or \"frontend\", OR\n * - has a sibling `backend/` directory\n */\nexport function findProjectRoot(startDir: string = process.cwd()): string | null {\n let dir = path.resolve(startDir);\n const root = path.parse(dir).root;\n\n while (dir !== root) {\n const pkgPath = path.join(dir, \"package.json\");\n\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n // Check for workspace-based project (monorepo root)\n if (pkg.workspaces && Array.isArray(pkg.workspaces)) {\n const hasBackend = pkg.workspaces.some((w: string) =>\n w === \"backend\"\n );\n if (hasBackend) return dir;\n }\n } catch {\n // ignore parse errors\n }\n\n // Check for sibling backend directory\n if (fs.existsSync(path.join(dir, \"backend\")) && fs.existsSync(path.join(dir, \"config\"))) {\n return dir;\n }\n }\n\n dir = path.dirname(dir);\n }\n\n return null;\n}\n\n/**\n * Locate the backend directory within the project root.\n */\nexport function findBackendDir(projectRoot: string): string | null {\n const backendDir = path.join(projectRoot, \"backend\");\n return fs.existsSync(backendDir) ? backendDir : null;\n}\n\n/**\n * Detect the active backend plugin (e.g. @rebasepro/server-postgres) from the backend's package.json.\n */\nexport function getActiveBackendPlugin(backendDir: string): string | null {\n const pkgPath = path.join(backendDir, \"package.json\");\n if (!fs.existsSync(pkgPath)) return null;\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n const deps = { ...pkg.dependencies,\n...pkg.devDependencies };\n\n // Collect all @rebasepro/server-* driver plugins (exclude server itself)\n const candidates = Object.keys(deps).filter(\n dep => dep.startsWith(\"@rebasepro/server-\") && dep !== \"@rebasepro/server\"\n );\n\n if (candidates.length === 0) return null;\n\n // Prefer server-postgres — it's the primary supported driver\n if (candidates.includes(\"@rebasepro/server-postgres\")) {\n return \"@rebasepro/server-postgres\";\n }\n\n // Fallback: return the first candidate that actually has a CLI entry point\n for (const candidate of candidates) {\n if (resolvePluginCliScript(backendDir, candidate)) {\n return candidate;\n }\n }\n\n // Last resort: return whatever we found\n return candidates[0];\n } catch {\n // Ignore parse errors\n }\n return null;\n}\n\n/**\n * Resolve the active plugin's CLI script.\n */\nexport function resolvePluginCliScript(backendDir: string, pluginName: string): string | null {\n const candidates: string[] = [];\n\n // Walk up from the backend dir: pnpm links the plugin into\n // backend/node_modules, while npm workspaces hoist it to the project (or an\n // enclosing monorepo) root.\n let dir = path.resolve(backendDir);\n const fsRoot = path.parse(dir).root;\n while (dir !== fsRoot) {\n candidates.push(\n path.join(dir, \"node_modules\", pluginName, \"src\", \"cli.ts\"),\n path.join(dir, \"node_modules\", pluginName, \"dist\", \"cli.js\")\n );\n dir = path.dirname(dir);\n }\n\n candidates.push(\n // For monorepo dev mode:\n path.resolve(backendDir, \"..\", \"..\", \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\"),\n path.resolve(backendDir, \"..\", \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\"),\n path.resolve(backendDir, \"..\", \"packages\", pluginName.replace(\"@rebasepro/\", \"\"), \"src\", \"cli.ts\")\n );\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Locate the frontend directory within the project root.\n */\nexport function findFrontendDir(projectRoot: string): string | null {\n const frontendDir = path.join(projectRoot, \"frontend\");\n return fs.existsSync(frontendDir) ? frontendDir : null;\n}\n\n/**\n * Find the .env file. Checks the project root first, then backend.\n */\nexport function findEnvFile(projectRoot: string): string | null {\n const candidates = [\n path.join(projectRoot, \".env\"),\n path.join(projectRoot, \"backend\", \".env\")\n ];\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n\n return null;\n}\n\n/**\n * Resolve a binary from the project's node_modules/.bin.\n * Checks backend, root, parent monorepo root, then falls back to PATH.\n */\nexport function resolveLocalBin(projectRoot: string, binName: string): string | null {\n const candidates = [\n path.join(projectRoot, \"backend\", \"node_modules\", \".bin\", binName),\n path.join(projectRoot, \"node_modules\", \".bin\", binName)\n ];\n\n // Also check parent directories (for monorepo setups where app/ is nested)\n let parent = path.dirname(projectRoot);\n const rootDir = path.parse(parent).root;\n while (parent !== rootDir) {\n candidates.push(path.join(parent, \"node_modules\", \".bin\", binName));\n parent = path.dirname(parent);\n }\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate;\n }\n\n // Fall back to globally installed binary via which\n try {\n const globalPath = execSync(`which ${binName}`, { encoding: \"utf-8\" }).trim();\n if (globalPath && fs.existsSync(globalPath)) return globalPath;\n } catch {\n // not found globally\n }\n\n return null;\n}\n\n/**\n * Resolve the tsx binary. Checks backend node_modules first, then root.\n */\nexport function resolveTsx(projectRoot: string): string | null {\n return resolveLocalBin(projectRoot, \"tsx\");\n}\n\n/**\n * Validate that a resolved tsx binary actually has an intact installation.\n *\n * `resolveLocalBin` only checks whether `node_modules/.bin/tsx` (a symlink)\n * exists. If the pnpm content-addressable store was cleaned or a previous\n * install was interrupted, the symlink can exist while critical files inside\n * the tsx package (e.g. `dist/preflight.cjs`) are missing — causing a\n * confusing MODULE_NOT_FOUND error at runtime.\n *\n * This function follows the symlink, walks up to find the tsx package root\n * (`package.json` with `name: \"tsx\"`), and verifies that `dist/preflight.cjs`\n * is present. Returns `null` when the installation looks healthy, or an\n * error description string when it appears corrupted.\n */\nexport function validateTsxInstallation(tsxBinPath: string): string | null {\n try {\n // Follow the symlink chain to the real tsx entry script\n const realPath = fs.realpathSync(tsxBinPath);\n\n // Walk up from the real binary to locate the tsx package root\n let dir = path.dirname(realPath);\n const fsRoot = path.parse(dir).root;\n for (let depth = 0; depth < 10 && dir !== fsRoot; depth++) {\n const pkgPath = path.join(dir, \"package.json\");\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n if (pkg.name === \"tsx\") {\n // Found the tsx package root — verify critical preload file\n const preflightPath = path.join(dir, \"dist\", \"preflight.cjs\");\n if (!fs.existsSync(preflightPath)) {\n return `tsx package at ${dir} is missing dist/preflight.cjs`;\n }\n return null; // Installation looks healthy\n }\n } catch {\n // Malformed package.json — keep walking\n }\n }\n dir = path.dirname(dir);\n }\n\n // Could not determine tsx root — don't block, assume valid\n return null;\n } catch (err) {\n // realpathSync throws if the symlink target is completely gone\n return `tsx binary symlink is broken: ${err instanceof Error ? err.message : String(err)}`;\n }\n}\n\n/**\n * Require the project root or exit with a helpful error.\n */\nexport function requireProjectRoot(): string {\n const root = findProjectRoot();\n if (!root) {\n console.error(chalk.red(\"✗ Could not find a Rebase project root.\"));\n console.error(chalk.gray(\" Make sure you are inside a Rebase project directory\"));\n console.error(chalk.gray(\" (one with backend/, frontend/, and config/ directories).\"));\n process.exit(1);\n }\n return root;\n}\n\n/**\n * Require the backend directory or exit with a helpful error.\n */\nexport function requireBackendDir(projectRoot: string): string {\n const backendDir = findBackendDir(projectRoot);\n if (!backendDir) {\n console.error(chalk.red(\"✗ Could not find a backend/ directory.\"));\n console.error(chalk.gray(` Expected at: ${path.join(projectRoot, \"backend\")}`));\n process.exit(1);\n }\n return backendDir;\n}\n","/**\n * Shared foundation for the `rebase cloud` command family.\n *\n * Everything cloud subcommands need in common lives here:\n * - credential storage (~/.rebase/credentials.json, keyed per control-plane host)\n * - project link file (.rebase/cloud.json in the project dir)\n * - control-plane URL resolution\n * - an authenticated `@rebasepro/client` instance (createCloudClient / requireClient)\n * - small output helpers shared across subcommands\n *\n * The control plane is itself a Rebase app, so we reuse the same SDK the web\n * console uses (`@rebasepro/client`). Auth, token refresh, the data REST client\n * and function invocation all come from the SDK — the CLI only supplies a\n * file-backed AuthStorage so a login persists across invocations.\n */\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\nimport { spawn } from \"child_process\";\nimport chalk from \"chalk\";\nimport arg from \"arg\";\nimport inquirer from \"inquirer\";\nimport { createRebaseClient, type AuthStorage } from \"@rebasepro/client\";\nimport { findProjectRoot } from \"../../utils/project\";\n\n/* ═══════════════════════════════════════════════════════════════\n Constants & paths\n ═══════════════════════════════════════════════════════════════ */\n\n/** Default hosted control plane (the Rebase Cloud console origin). */\nexport const DEFAULT_CLOUD_URL = \"https://app.rebase.pro\";\n\n/** The storage key the SDK's auth module reads/writes the session under. */\nconst SDK_SESSION_KEY = \"rebase_auth\";\n\n/** ~/.rebase/credentials.json — one file, many hosts. */\nfunction credentialsPath(): string {\n return path.join(os.homedir(), \".rebase\", \"credentials.json\");\n}\n\n/** Project-local link file: <project>/.rebase/cloud.json */\nexport function projectLinkPath(cwd: string = process.cwd()): string {\n const root = findProjectRoot(cwd) || cwd;\n return path.join(root, \".rebase\", \"cloud.json\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Credentials file model\n ═══════════════════════════════════════════════════════════════\n\n {\n \"current\": \"https://app.rebase.pro\",\n \"contexts\": {\n \"https://app.rebase.pro\": { \"auth\": \"<sdk session json>\", \"org\": \"42\" }\n }\n }\n*/\n\ninterface CloudContextEntry {\n /** Raw JSON blob the SDK auth module persists (the RebaseSession). */\n auth?: string;\n /** Active organization id for this host, if the user selected one. */\n org?: string;\n}\n\ninterface CredentialsFile {\n current?: string;\n contexts: Record<string, CloudContextEntry>;\n}\n\nfunction readCredentials(): CredentialsFile {\n try {\n const raw = fs.readFileSync(credentialsPath(), \"utf-8\");\n const parsed = JSON.parse(raw) as CredentialsFile;\n if (!parsed.contexts) parsed.contexts = {};\n return parsed;\n } catch {\n return { contexts: {} };\n }\n}\n\nfunction writeCredentials(data: CredentialsFile): void {\n const file = credentialsPath();\n fs.mkdirSync(path.dirname(file), { recursive: true });\n // Written with private perms — this file holds refresh tokens.\n fs.writeFileSync(file, JSON.stringify(data, null, 2), { mode: 0o600 });\n try {\n fs.chmodSync(file, 0o600);\n } catch {\n // best effort on platforms without chmod semantics\n }\n}\n\n/** Host that a bare `rebase cloud` command should target, if any. */\nexport function currentContextUrl(): string | undefined {\n return readCredentials().current;\n}\n\n/** Persist the active organization id for a host. */\nexport function setContextOrg(url: string, org: string | undefined): void {\n const creds = readCredentials();\n const entry = creds.contexts[url] || {};\n if (org) entry.org = org;\n else delete entry.org;\n creds.contexts[url] = entry;\n writeCredentials(creds);\n}\n\nexport function getContextOrg(url: string): string | undefined {\n return readCredentials().contexts[url]?.org;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n File-backed AuthStorage (per host)\n ═══════════════════════════════════════════════════════════════ */\n\nfunction createFileAuthStorage(url: string): AuthStorage {\n return {\n getItem(key) {\n if (key !== SDK_SESSION_KEY) return null;\n return readCredentials().contexts[url]?.auth ?? null;\n },\n setItem(key, value) {\n if (key !== SDK_SESSION_KEY) return;\n const creds = readCredentials();\n const entry = creds.contexts[url] || {};\n entry.auth = value;\n creds.contexts[url] = entry;\n if (!creds.current) creds.current = url;\n writeCredentials(creds);\n },\n removeItem(key) {\n if (key !== SDK_SESSION_KEY) return;\n const creds = readCredentials();\n if (creds.contexts[url]) {\n delete creds.contexts[url].auth;\n delete creds.contexts[url].org;\n }\n writeCredentials(creds);\n }\n };\n}\n\n/** Mark a host as the active context (called on login). */\nexport function setCurrentContext(url: string): void {\n const creds = readCredentials();\n creds.current = url;\n if (!creds.contexts[url]) creds.contexts[url] = {};\n writeCredentials(creds);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n URL resolution\n ═══════════════════════════════════════════════════════════════\n\n Priority: --url flag > REBASE_CLOUD_URL env > linked project's url\n > stored current context > default hosted URL.\n*/\n\nexport function resolveCloudUrl(rawArgs: string[]): string {\n const parsed = arg({ \"--url\": String }, { argv: rawArgs.slice(2),\npermissive: true });\n const explicit = parsed[\"--url\"] || process.env.REBASE_CLOUD_URL;\n if (explicit) return normalizeUrl(explicit);\n\n const link = readLink();\n if (link?.url) return normalizeUrl(link.url);\n\n const current = currentContextUrl();\n if (current) return normalizeUrl(current);\n\n return DEFAULT_CLOUD_URL;\n}\n\nfunction normalizeUrl(url: string): string {\n let u = url.trim().replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//.test(u)) u = `https://${u}`;\n return u;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Rebase client factory + auth guard\n ═══════════════════════════════════════════════════════════════ */\n\nexport type CloudClient = ReturnType<typeof createRebaseClient>;\n\n/**\n * Build an SDK client bound to a control-plane host, backed by the on-disk\n * credential store. `autoRefresh` is disabled so we never leave a dangling\n * setTimeout that keeps the CLI process alive; token refresh is done on demand\n * by `requireClient`.\n */\nexport function createCloudClient(url: string): CloudClient {\n return createRebaseClient({\n baseUrl: url,\n // Empty string disables the realtime socket — a short-lived CLI has no\n // use for it, and leaving it on opens a connection (and noisy errors)\n // on every invocation.\n websocketUrl: \"\",\n auth: {\n storage: createFileAuthStorage(url),\n persistSession: true,\n autoRefresh: false\n }\n });\n}\n\n/** Two minutes of head-room before a token is treated as expired. */\nconst EXPIRY_BUFFER_MS = 120_000;\n\n/**\n * Return an authenticated client for the resolved host, refreshing the access\n * token if it is close to expiry. Exits with a helpful message when there is no\n * usable session (never logged in, or the refresh token was revoked).\n */\nexport async function requireClient(rawArgs: string[]): Promise<{ client: CloudClient; url: string }> {\n const url = resolveCloudUrl(rawArgs);\n const client = createCloudClient(url);\n const session = client.auth.getSession();\n\n if (!session || !session.accessToken) {\n fail(\n `Not logged in to ${chalk.cyan(url)}.`,\n `Run ${chalk.bold(\"rebase cloud login\")} first.`\n );\n }\n\n if (session.expiresAt <= Date.now() + EXPIRY_BUFFER_MS) {\n try {\n await client.auth.refreshSession();\n } catch {\n fail(\n `Your session for ${chalk.cyan(url)} has expired.`,\n `Run ${chalk.bold(\"rebase cloud login\")} to sign in again.`\n );\n }\n }\n\n return { client,\nurl };\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Tenant hostnames\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * The base domain tenant projects are served at, as reported by the control\n * plane (`platform-config`, which derives it from the same TENANT_BASE_DOMAIN\n * the ingress and the console read — see saas/backend/src/utils/tenant-domain.ts).\n *\n * The CLI cannot know this value: it is per-deployment configuration (production\n * serves tenants at `apps.rebase.pro`, a dev control plane at `localhost`). It\n * used to be hardcoded to `rebase.pro`, so `cloud projects create` congratulated\n * the user with a URL that resolves nowhere near their app.\n *\n * Cached per host for the process: it is fixed for a control plane's lifetime,\n * and `projects list` formats one host per row off a single fetch.\n *\n * @returns the base domain, or `undefined` if the control plane doesn't serve\n * `platform-config` (an older deployment) or the request failed. A failure is\n * cached too — the caller renders a subdomain either way, and a short-lived\n * CLI should not retry once per row.\n */\nconst tenantBaseDomainCache = new Map<string, Promise<string | undefined>>();\n\nexport function fetchTenantBaseDomain(client: CloudClient, url: string): Promise<string | undefined> {\n let pending = tenantBaseDomainCache.get(url);\n if (!pending) {\n pending = client.functions\n .invoke<{ tenantBaseDomain?: string }>(\"platform-config\", undefined, { method: \"GET\" })\n .then((cfg) => cfg?.tenantBaseDomain?.trim() || undefined)\n .catch(() => undefined);\n tenantBaseDomainCache.set(url, pending);\n }\n return pending;\n}\n\n/**\n * Public host for a project — `<subdomain>.<base>`, or the bare subdomain when\n * the base domain is unknown.\n *\n * It deliberately never falls back to a guessed domain. The user copies this\n * string into a browser, so a plausible-but-wrong hostname is worse than an\n * obviously incomplete one: `acme.rebase.pro` looks reachable and isn't, while\n * `acme` reads as \"the subdomain is acme\" and prompts no wasted debugging.\n */\nexport function formatTenantHost(\n subdomain: string | undefined,\n baseDomain: string | undefined\n): string | undefined {\n if (!subdomain) return undefined;\n return baseDomain ? `${subdomain}.${baseDomain}` : subdomain;\n}\n\n/** The fields of a project row this module needs to render a host. */\nexport interface HostableProject {\n subdomain?: string;\n /** Resolved server-side; absent on control planes older than the host hook. */\n host?: string;\n}\n\n/**\n * The host to display for a project.\n *\n * Prefers `host` off the record: the control plane resolves it through the same\n * `tenantHost()` the ingress uses, so it accounts for the project's *cluster*\n * base domain. The CLI cannot compute that itself — `clusters` is admin-only\n * under RLS, so a normal user's token cannot read `baseDomain`, and a project on\n * a second cluster is served somewhere the platform default does not name.\n *\n * `baseDomain` (from `platform-config`) remains the fallback for a control plane\n * that predates the hook — right for the single-cluster case, which is every\n * project today.\n */\nexport function projectHost(\n project: HostableProject,\n baseDomain: string | undefined\n): string | undefined {\n return project.host || formatTenantHost(project.subdomain, baseDomain);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Project link file (.rebase/cloud.json)\n ═══════════════════════════════════════════════════════════════ */\n\nexport interface ProjectLink {\n url: string;\n projectId: string;\n /** The project's subdomain — the slug users see in console URLs and type into --project. */\n slug?: string;\n projectName?: string;\n orgId?: string;\n}\n\nexport function readLink(cwd: string = process.cwd()): ProjectLink | null {\n try {\n return JSON.parse(fs.readFileSync(projectLinkPath(cwd), \"utf-8\")) as ProjectLink;\n } catch {\n return null;\n }\n}\n\nexport function writeLink(link: ProjectLink, cwd: string = process.cwd()): void {\n const file = projectLinkPath(cwd);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(file, JSON.stringify(link, null, 2));\n}\n\nexport function removeLink(cwd: string = process.cwd()): boolean {\n const file = projectLinkPath(cwd);\n if (fs.existsSync(file)) {\n fs.rmSync(file);\n return true;\n }\n return false;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * The raw project reference to operate on: explicit `--project` flag wins,\n * otherwise the linked project. Exits with guidance when neither is present.\n * The value is a slug (the project's subdomain, as shown in console URLs) or,\n * for old scripts and link files, a raw project UUID.\n */\nexport function requireProjectRef(rawArgs: string[]): string {\n const parsed = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(2),\npermissive: true });\n if (parsed[\"--project\"]) return parsed[\"--project\"];\n const link = readLink();\n if (link?.projectId) return link.projectId;\n fail(\n \"No project specified and this directory is not linked.\",\n `Pass ${chalk.bold(\"--project <slug>\")} or run ${chalk.bold(\"rebase cloud link\")}.`\n );\n}\n\n/**\n * Resolve a project reference — slug or UUID — to the internal id the API\n * takes, or undefined when no such project is visible. Slugs cost one lookup;\n * UUIDs pass through untouched so linked directories and old scripts skip the\n * round-trip.\n */\nexport async function lookupProjectId(ref: string, client: CloudClient): Promise<string | undefined> {\n if (UUID_RE.test(ref)) return ref;\n const res = await client.data.collection(\"projects\").find({\n where: { subdomain: [\"==\", ref] },\n limit: 1\n });\n const row = res.data[0] as { id?: string | number } | undefined;\n return row?.id === undefined ? undefined : String(row.id);\n}\n\n/** Like `lookupProjectId`, but exits with guidance when the ref matches nothing. */\nexport async function resolveProjectRef(ref: string, client: CloudClient): Promise<string> {\n const id = await lookupProjectId(ref, client);\n if (id === undefined) {\n fail(\n `No project with slug ${chalk.bold(ref)}.`,\n `List yours with ${chalk.bold(\"rebase cloud projects\")}.`\n );\n }\n return id;\n}\n\n/** `requireProjectRef` + `resolveProjectRef` in one step. */\nexport async function requireProject(rawArgs: string[], client: CloudClient): Promise<string> {\n return resolveProjectRef(requireProjectRef(rawArgs), client);\n}\n\n/**\n * The project reference to SHOW: the slug the user typed or the linked slug.\n * Never resolves — for human output only. Old link files predate `slug` and\n * fall back to the stored id.\n */\nexport function displayProjectRef(rawArgs: string[]): string {\n const parsed = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(2),\npermissive: true });\n if (parsed[\"--project\"]) return parsed[\"--project\"];\n const link = readLink();\n return link?.slug || link?.projectId || \"\";\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Machine-readable output mode\n ═══════════════════════════════════════════════════════════════\n\n Rebase is built for agents, and the CLI is their primary interface. An agent\n must never scrape a colorized table, so every cloud command can emit a single\n JSON value instead of human output.\n\n JSON mode is on when ANY of these hold:\n • `--json` was passed,\n • `REBASE_JSON=1` is set, or\n • stdout is not a TTY (piped/redirected — i.e. a program is reading it).\n\n In JSON mode a command prints exactly one JSON value to stdout and nothing\n else; errors print `{\"error\":{...}}` and exit non-zero. The mode is a\n process-global set once, at dispatch, by `initOutputMode` — every helper here\n (fail, reportError, emit) reads it so the whole family is consistent.\n*/\n\nlet JSON_MODE = false;\n\n/**\n * Resolve and latch the output mode for this invocation. Call once at the top of\n * `cloudCommand`, before anything can print or `fail`. Returns the resolved mode\n * (handy for tests, which otherwise leave it at its `false` default).\n */\nexport function initOutputMode(rawArgs: string[]): boolean {\n const parsed = arg({ \"--json\": Boolean }, { argv: rawArgs.slice(2), permissive: true });\n JSON_MODE =\n Boolean(parsed[\"--json\"]) ||\n process.env.REBASE_JSON === \"1\" ||\n process.stdout.isTTY !== true;\n return JSON_MODE;\n}\n\n/** Whether the current invocation is emitting machine-readable JSON. */\nexport function isJsonMode(): boolean {\n return JSON_MODE;\n}\n\n/** Force the mode (tests only — production latches it via `initOutputMode`). */\nexport function setJsonModeForTest(value: boolean): void {\n JSON_MODE = value;\n}\n\n/** Strip ANSI colour codes — JSON output must never carry terminal escapes. */\n// eslint-disable-next-line no-control-regex\nconst ANSI_RE = /\u001b\\[[0-9;]*m/g;\nfunction stripAnsi(s: string): string {\n return s.replace(ANSI_RE, \"\");\n}\n\n/** Write one JSON value to stdout, followed by a newline. */\nexport function printJson(value: unknown): void {\n process.stdout.write(JSON.stringify(value) + \"\\n\");\n}\n\n/**\n * The one output primitive every new command uses: in JSON mode emit `json`\n * (and nothing else); otherwise run `human`. Keeping the two behind a single\n * call is what guarantees a command can never print a table AND a JSON blob.\n */\nexport function emit(human: () => void, json: unknown): void {\n if (JSON_MODE) printJson(json);\n else human();\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Output helpers\n ═══════════════════════════════════════════════════════════════ */\n\n/** Print an error (+ optional hint) and exit non-zero. Never returns. */\nexport function fail(message: string, hint?: string, code?: string): never {\n if (JSON_MODE) {\n printJson({ error: { message: stripAnsi(message), code: code ?? null, hint: hint ? stripAnsi(hint) : undefined } });\n process.exit(1);\n }\n console.error(\"\");\n console.error(chalk.red(` ✗ ${message}`));\n if (hint) console.error(chalk.gray(` ${hint}`));\n console.error(\"\");\n process.exit(1);\n}\n\n/**\n * Confirm a destructive/irreversible action, respecting non-interactive use.\n *\n * With `--yes`/`-y` it proceeds silently. In JSON mode or a non-TTY it REFUSES\n * to prompt — a prompt that can hang is a known repo landmine — and fails,\n * telling the caller to pass `--yes`. Only an interactive terminal gets a real\n * confirm prompt; declining there aborts cleanly (exit 0).\n */\nexport async function confirmDestructive(opts: { yes: boolean; prompt: string }): Promise<void> {\n if (opts.yes) return;\n if (JSON_MODE || process.stdin.isTTY !== true) {\n fail(\n \"This action is destructive and needs confirmation.\",\n `Re-run with ${chalk.bold(\"--yes\")} to proceed.`,\n \"confirmation_required\"\n );\n }\n const { confirmed } = (await inquirer.prompt([\n { type: \"confirm\", name: \"confirmed\", default: false, message: opts.prompt }\n ] as unknown as Parameters<typeof inquirer.prompt>[0])) as { confirmed: boolean };\n if (!confirmed) {\n console.log(chalk.gray(\" Aborted.\"));\n process.exit(0);\n }\n}\n\n/**\n * Positional tokens after `rebase cloud` — `[group, action, arg1, …]`.\n *\n * Deliberately NOT `arg({}, { permissive: true })._`: in permissive mode `arg`\n * pushes UNKNOWN FLAGS onto `_` too, so `rollback --yes --json` would report\n * `--yes` as the deployment id. Operand extraction must see operands only, so\n * anything starting with `-` is dropped — the same filter the db backup handler\n * has always used.\n */\nexport function cloudPositionals(rawArgs: string[]): string[] {\n return rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"));\n}\n\nexport function success(message: string): void {\n console.log(\"\");\n console.log(chalk.bold.green(` ✓ ${message}`));\n console.log(\"\");\n}\n\n/** Colorize a deployment / resource status token. */\nexport function colorStatus(status: string | undefined): string {\n switch (status) {\n case \"active\":\n case \"success\":\n case \"connected\":\n return chalk.green(status);\n case \"deploying\":\n case \"provisioning\":\n case \"pending_billing\":\n case \"untested\":\n return chalk.yellow(status ?? \"\");\n case \"failed\":\n return chalk.red(status);\n case \"stopped\":\n return chalk.gray(status);\n default:\n return chalk.gray(status ?? \"unknown\");\n }\n}\n\n/**\n * Render a two-column key/value block with aligned keys. Empty rows are skipped\n * — including `null`, which the API sends for an unset column and which used to\n * print the literal string \"null\" (e.g. `Custom domain: null`).\n */\nexport function keyValues(rows: Array<[string, string | null | undefined]>): void {\n const width = Math.max(...rows.map(([k]) => k.length));\n for (const [k, v] of rows) {\n if (v === undefined || v === null || v === \"\") continue;\n console.log(` ${chalk.gray(`${k}:`.padEnd(width + 1))} ${v}`);\n }\n}\n\n/**\n * Surface an SDK/HTTP error consistently. The SDK throws RebaseApiError with\n * a `.status` and `.message`; anything else falls back to its string form.\n */\nexport function reportError(e: unknown, context: string): never {\n const err = e as { status?: number; message?: string; code?: string };\n if (JSON_MODE) {\n printJson({\n error: {\n message: err?.message ? stripAnsi(err.message) : String(e),\n code: err?.code ?? null,\n status: err?.status ?? null,\n context\n }\n });\n process.exit(1);\n }\n const status = err?.status ? ` (${err.status})` : \"\";\n fail(`${context}${status}: ${err?.message ?? String(e)}`);\n}\n\n/**\n * Open a URL in the user's default browser (best effort). Always prints the URL\n * first so it stays usable over SSH or when no browser is available.\n */\nexport function openUrl(target: string, label = \"Opening\"): void {\n console.log(\"\");\n console.log(` ${label} ${chalk.cyan(target)}`);\n console.log(\"\");\n const opener =\n process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"start\" : \"xdg-open\";\n try {\n const child = spawn(opener, [target], {\n stdio: \"ignore\",\n detached: true,\n shell: process.platform === \"win32\"\n });\n child.on(\"error\", () => {\n /* URL already printed for manual copy */\n });\n child.unref();\n } catch {\n /* URL already printed */\n }\n}\n","import arg from \"arg\";\nimport inquirer from \"inquirer\";\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport net from \"net\";\nimport { promisify } from \"util\";\nimport { execa } from \"execa\";\nimport { cp } from \"fs/promises\";\nimport { fileURLToPath } from \"url\";\nimport crypto from \"crypto\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\nimport { resolveCloudUrl, writeLink } from \"./cloud/context\";\nimport type { PackageManager, PMCommands } from \"../utils/package-manager\";\n\nconst access = promisify(fs.access);\n\n\n// Resolve template path relative to this file\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nfunction findParentDir(currentDir: string, targetName: string): string | null {\n const root = path.parse(currentDir).root;\n while (currentDir && currentDir !== root) {\n if (path.basename(currentDir) === targetName) {\n return currentDir;\n }\n currentDir = path.dirname(currentDir);\n }\n return null;\n}\n\nconst cliRoot = findParentDir(__dirname, \"cli\");\n\nconst PROJECT_NAME_RE = /^[a-z0-9][a-z0-9._-]*$/;\n\n/** Returns an error message, or null when the name is a valid package name. */\nexport function validateProjectName(name: string): string | null {\n if (!name.trim()) return \"Project name is required\";\n if (!PROJECT_NAME_RE.test(name)) {\n return \"Project name must start with a lowercase letter or number and contain only lowercase letters, numbers, hyphens, dots, or underscores\";\n }\n return null;\n}\n\nexport type TemplatePreset = \"blog\" | \"ecommerce\" | \"blank\";\n\n/**\n * How much of Rebase to scaffold.\n *\n * `cms` is the full triad (config + backend + frontend). `baas` is the backend\n * alone, serving the database over REST with no collection files and no UI.\n */\n/**\n * `cms` scaffolds BaaS + the admin UI; `baas` scaffolds the API alone. The\n * values match `RebaseBackendConfig.mode`, which is what the generated backend\n * sets — the labels below are what users actually read.\n */\nexport type TemplateFlavor = \"cms\" | \"baas\";\n\nconst FLAVOR_CHOICES: Array<{ name: string; value: TemplateFlavor; short: string }> = [\n { name: \"BaaS + admin — API plus an admin UI, driven by collections you define (like Payload/Directus)\",\nvalue: \"cms\",\nshort: \"BaaS + admin\" },\n { name: \"BaaS only — headless API over your database. No collections, no UI (like Supabase)\",\nvalue: \"baas\",\nshort: \"BaaS only\" }\n];\n\nconst PRESET_CHOICES: Array<{ name: string; value: TemplatePreset; short: string }> = [\n { name: \"Blog — Posts, Authors, Tags (with markdown editor)\",\nvalue: \"blog\",\nshort: \"Blog\" },\n { name: \"E-commerce — Products, Categories, Orders\",\nvalue: \"ecommerce\",\nshort: \"E-commerce\" },\n { name: \"Blank — Empty project, just authentication\",\nvalue: \"blank\",\nshort: \"Blank\" }\n];\n\nexport interface InitOptions {\n projectName: string;\n git: boolean;\n installDeps: boolean;\n targetDirectory: string;\n templateDirectory: string;\n databaseUrl?: string;\n introspect?: boolean;\n /** Starter template preset. */\n preset: TemplatePreset;\n /** Which parts of Rebase to scaffold. */\n flavor: TemplateFlavor;\n /** Detected package manager (pnpm or npm). */\n pm: PackageManager;\n /** Command helpers for the detected PM. */\n pmCommands: PMCommands;\n /** Cloud project slug (its subdomain) to link the scaffold to. */\n cloudProject?: string;\n /** One-time setup key that authenticates the cloud link. */\n setupKey?: string;\n /** Control-plane URL the setup key is redeemed against. */\n cloudUrl?: string;\n}\n\nexport interface BuildQuestionsParams {\n nameArg?: string;\n templateArg?: TemplatePreset;\n flavorArg?: TemplateFlavor;\n hasGitFlag: boolean;\n hasInstallFlag: boolean;\n pm: PackageManager;\n}\n\n/**\n * Builds the interactive prompt questions for `rebase init`.\n * Exported for testability — all prompt `type` values must match\n * types registered by the installed version of inquirer.\n */\nexport function buildInitQuestions(params: BuildQuestionsParams): Record<string, unknown>[] {\n const { nameArg, templateArg, flavorArg, hasGitFlag, hasInstallFlag, pm } = params;\n const questions: Record<string, unknown>[] = [];\n\n if (!nameArg) {\n questions.push({\n type: \"input\",\n name: \"projectName\",\n message: \"Project name:\",\n default: \"my-rebase-app\",\n validate: (input: string) => validateProjectName(input) ?? true\n });\n }\n\n if (!flavorArg) {\n questions.push({\n type: \"select\",\n name: \"flavor\",\n message: \"What do you want to build?\",\n choices: FLAVOR_CHOICES,\n default: \"cms\"\n });\n }\n\n if (!templateArg) {\n questions.push({\n type: \"select\",\n name: \"preset\",\n message: \"Choose a starter template:\",\n choices: PRESET_CHOICES,\n default: \"blog\",\n // BaaS has no collection files, so a collections preset is moot.\n when: (answers: Record<string, unknown>) => (flavorArg ?? answers.flavor) !== \"baas\"\n });\n }\n\n if (!hasGitFlag) {\n questions.push({\n type: \"confirm\",\n name: \"git\",\n message: \"Initialize a git repository?\",\n default: true\n });\n }\n\n if (!hasInstallFlag) {\n questions.push({\n type: \"confirm\",\n name: \"installDeps\",\n message: `Install dependencies with ${pm}?`,\n default: true\n });\n }\n\n questions.push({\n type: \"input\",\n name: \"databaseUrl\",\n message: \"Enter your PostgreSQL database connection string (leave blank to use a local default):\",\n default: \"\",\n validate: (input: string) => {\n if (input.trim() && /[\\r\\n]/.test(input)) {\n return \"Database URL cannot contain newline characters.\";\n }\n return true;\n }\n });\n\n questions.push({\n type: \"confirm\",\n name: \"introspect\",\n message: \"Would you like to introspect this database to automatically generate collections?\",\n default: true,\n when: (answers: Record<string, unknown>) => !!(answers.databaseUrl as string)?.trim()\n });\n\n return questions;\n}\n\nexport async function createRebaseApp(rawArgs: string[]) {\n console.log(`\n${chalk.bold(\"Rebase\")} — Create a new project 🚀\n`);\n\n const pm = detectPackageManager();\n const options = await promptForOptions(rawArgs, pm);\n await createProject(options);\n}\n\nasync function promptForOptions(rawArgs: string[], pm: PackageManager): Promise<InitOptions> {\n const args = arg(\n {\n \"--git\": Boolean,\n \"--install\": Boolean,\n \"--database-url\": String,\n \"--introspect\": Boolean,\n \"--template\": String,\n \"--flavor\": String,\n \"--project\": String,\n \"--setup-key\": String,\n \"--yes\": Boolean,\n \"-g\": \"--git\",\n \"-i\": \"--install\",\n \"-t\": \"--template\",\n \"-f\": \"--flavor\",\n \"-y\": \"--yes\"\n },\n {\n argv: rawArgs.slice(3), // skip \"node\", \"rebase\", \"init\"\n permissive: true\n }\n );\n\n // The first positional arg after \"init\" is the project name\n const nameArg = args._[0];\n const isNonInteractive = args[\"--yes\"] || false;\n\n // The interactive prompt validates typed names; a name passed as an\n // argument must pass the same check or it becomes an invalid package.json\n // \"name\" that only fails later, at install time. Validate the basename so\n // nested paths (\"apps/my-app\") and \".\" still work.\n if (nameArg) {\n const resolvedName = path.basename(path.resolve(process.cwd(), nameArg));\n const nameError = validateProjectName(resolvedName);\n if (nameError) {\n console.error(chalk.red(`Invalid project name \"${resolvedName}\": ${nameError}`));\n process.exit(1);\n }\n }\n\n const templateArg = args[\"--template\"] as TemplatePreset | undefined;\n if (templateArg && !PRESET_CHOICES.some(p => p.value === templateArg)) {\n console.error(chalk.red(`Unknown template \"${templateArg}\". Available: ${PRESET_CHOICES.map(p => p.value).join(\", \")}`));\n process.exit(1);\n }\n\n const flavorArg = args[\"--flavor\"] as TemplateFlavor | undefined;\n if (flavorArg && !FLAVOR_CHOICES.some(f => f.value === flavorArg)) {\n console.error(chalk.red(`Unknown flavor \"${flavorArg}\". Available: ${FLAVOR_CHOICES.map(f => f.value).join(\", \")}`));\n process.exit(1);\n }\n\n if (isNonInteractive) {\n const projectName = nameArg || \"my-rebase-app\";\n const targetDirectory = path.resolve(process.cwd(), projectName);\n const templateDirectory = path.resolve(cliRoot!, \"templates\", \"template\");\n const pmCommands = getPMCommands(pm);\n\n return {\n projectName: path.basename(targetDirectory),\n git: args[\"--git\"] ?? false,\n installDeps: args[\"--install\"] ?? false,\n targetDirectory,\n templateDirectory,\n databaseUrl: args[\"--database-url\"] || undefined,\n introspect: args[\"--introspect\"] || false,\n preset: templateArg || \"blog\",\n flavor: flavorArg || \"cms\",\n pm,\n pmCommands,\n cloudProject: args[\"--project\"] || undefined,\n setupKey: args[\"--setup-key\"] || undefined,\n cloudUrl: resolveCloudUrl(rawArgs)\n };\n }\n\n // A non-interactive stdin (CI, a pipe, no TTY) can't answer prompts:\n // inquirer either blocks forever waiting for input or aborts with a raw\n // ExitPromptError stack trace. Fail fast with actionable guidance instead.\n if (!process.stdin.isTTY) {\n console.error(chalk.red(\"Cannot prompt: this is a non-interactive terminal (no TTY).\"));\n console.error(chalk.yellow(\" Re-run with --yes to accept defaults, passing any choices as flags, e.g.:\"));\n console.error(chalk.yellow(` rebase init ${nameArg || \"my-app\"} --yes --template blog --flavor cms`));\n console.error(chalk.gray(\" Options: --template <blog|ecommerce|blank> --flavor <cms|baas> --database-url <url> --install --git\"));\n process.exit(1);\n }\n\n const questions = buildInitQuestions({\n nameArg,\n templateArg,\n flavorArg,\n hasGitFlag: !!args[\"--git\"],\n hasInstallFlag: !!args[\"--install\"],\n pm\n });\n\n\n const answers = await inquirer.prompt(questions as unknown as Parameters<typeof inquirer.prompt>[0]);\n\n const targetDirectory = path.resolve(process.cwd(), nameArg || answers.projectName);\n const projectName = path.basename(targetDirectory);\n const templateDirectory = path.resolve(cliRoot!, \"templates\", \"template\");\n const pmCommands = getPMCommands(pm);\n\n return {\n projectName,\n git: args[\"--git\"] || answers.git || false,\n installDeps: args[\"--install\"] || answers.installDeps || false,\n targetDirectory,\n templateDirectory,\n databaseUrl: (answers.databaseUrl as string)?.trim() || undefined,\n introspect: answers.introspect || false,\n preset: templateArg || (answers.preset as TemplatePreset) || \"blog\",\n flavor: flavorArg || (answers.flavor as TemplateFlavor) || \"cms\",\n pm,\n pmCommands,\n cloudProject: args[\"--project\"] || undefined,\n setupKey: args[\"--setup-key\"] || undefined,\n cloudUrl: resolveCloudUrl(rawArgs)\n };\n}\n\n/**\n * Redeem the one-time setup key from the console's setup page and write the\n * `.rebase/cloud.json` link into the scaffold, so `rebase cloud deploy` etc.\n * work in the new directory with no further flags. `--project` carries the\n * project's slug (its subdomain, as shown in console URLs); the control plane\n * also accepts a raw id for old copies of the command.\n *\n * Best-effort by design: a failed link must never fail the scaffold, so every\n * exit path other than success is a warning plus instructions to link later.\n */\nasync function linkScaffoldToCloud(options: InitOptions): Promise<void> {\n if (!options.cloudProject && !options.setupKey) return;\n\n const linkLater = `Link it later with ${chalk.bold(\"rebase cloud login\")} then ${chalk.bold(\"rebase cloud link\")}.`;\n if (!options.cloudProject || !options.setupKey) {\n console.warn(chalk.yellow(\" --project and --setup-key go together; skipping the cloud link.\"));\n console.warn(chalk.yellow(` ${linkLater}`));\n return;\n }\n\n try {\n const res = await fetch(`${options.cloudUrl}/api/functions/setup-key/validate`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ projectId: options.cloudProject,\nsetupKey: options.setupKey })\n });\n const body = (await res.json().catch(() => ({}))) as {\n error?: { message?: string };\n project?: { id?: string | number; subdomain?: string; name?: string };\n };\n if (!res.ok || body.project?.id === undefined) {\n console.warn(chalk.yellow(` Could not verify the setup key: ${body.error?.message || res.statusText}`));\n console.warn(chalk.yellow(` ${linkLater}`));\n return;\n }\n writeLink(\n {\n url: String(options.cloudUrl),\n projectId: String(body.project.id),\n slug: body.project.subdomain,\n projectName: body.project.name\n },\n options.targetDirectory\n );\n console.log(\"\");\n console.log(` ${chalk.green(\"✓\")} Linked to cloud project ${chalk.bold(body.project.subdomain ?? options.cloudProject)}`);\n } catch (e) {\n console.warn(chalk.yellow(` Could not reach the control plane: ${e instanceof Error ? e.message : String(e)}`));\n console.warn(chalk.yellow(` ${linkLater}`));\n }\n}\n\nasync function createProject(options: InitOptions) {\n // Check if directory already exists and is not empty\n if (fs.existsSync(options.targetDirectory)) {\n if (fs.readdirSync(options.targetDirectory).length !== 0) {\n console.error(`${chalk.red.bold(\"ERROR\")} Directory \"${options.projectName}\" already exists and is not empty`);\n process.exit(1);\n }\n } else {\n fs.mkdirSync(options.targetDirectory, { recursive: true });\n }\n\n // Verify template exists\n try {\n await access(options.templateDirectory, fs.constants.R_OK);\n } catch {\n console.error(`${chalk.red.bold(\"ERROR\")} Template not found at ${options.templateDirectory}`);\n process.exit(1);\n }\n\n // Copy template files\n console.log(chalk.gray(\" Copying project files...\"));\n try {\n await cp(options.templateDirectory, options.targetDirectory, {\n recursive: true,\n filter: (source: string) => {\n const basename = path.basename(source);\n // Skip node_modules and .DS_Store\n return basename !== \"node_modules\" && basename !== \".DS_Store\";\n }\n });\n } catch (err: unknown) {\n console.error(`${chalk.red.bold(\"ERROR\")} Failed to copy template files: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n\n // npm/pnpm always strip files named .gitignore and .npmrc from published\n // tarballs, so the template ships them un-dotted and we restore the real\n // names here.\n for (const [from, to] of [[\"gitignore\", \".gitignore\"], [\"npmrc\", \".npmrc\"]] as const) {\n const shipped = path.join(options.targetDirectory, from);\n if (fs.existsSync(shipped)) {\n fs.renameSync(shipped, path.join(options.targetDirectory, to));\n }\n }\n\n // Apply the selected template preset (swap collection files)\n if (options.flavor !== \"baas\") {\n // When introspecting, the database is the source of truth: start from\n // the blank preset so example collections never register on top of\n // tables the database doesn't have.\n if (options.introspect && options.preset !== \"blank\") {\n console.log(chalk.gray(\" Using the blank template: collections will come from your database.\"));\n }\n await applyPreset(options.targetDirectory, options.introspect ? \"blank\" : options.preset);\n }\n\n // Reduce the project to the selected flavor\n await applyFlavor(options.targetDirectory, options.flavor);\n\n // Replace placeholder project name in package.json files\n await replacePlaceholders(options);\n\n // Rename .env.example to .env if it exists and randomize secrets\n await configureEnvFile(options.targetDirectory, options.databaseUrl);\n\n // Initialize git\n if (options.git) {\n console.log(chalk.gray(\" Initializing git repository...\"));\n try {\n await execa(\"git\", [\"init\"], { cwd: options.targetDirectory });\n } catch {\n console.warn(chalk.yellow(\" Warning: Failed to initialize git repository\"));\n }\n }\n\n const { pm, pmCommands } = options;\n const installCmd = pmCommands.install;\n const execCmd = pmCommands.exec(\"rebase\", [\"schema\", \"introspect\", \"--force\"]);\n const generateCmd = pmCommands.exec(\"rebase\", [\"schema\", \"generate\", \"--collections\", \"../config/collections\"]);\n\n if (options.installDeps) {\n console.log(\"\");\n console.log(chalk.gray(` Installing dependencies with ${pm}...`));\n console.log(\"\");\n try {\n await execa(installCmd[0], installCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n } catch {\n console.warn(chalk.yellow(` Warning: Failed to install dependencies. You may need to run \\`${installCmd.join(\" \")}\\` manually.`));\n }\n }\n\n if (options.introspect) {\n console.log(\"\");\n if (options.installDeps) {\n console.log(chalk.gray(\" Introspecting database and generating collections...\"));\n console.log(\"\");\n try {\n // --force overwrites template example collections with real ones\n await execa(execCmd[0], execCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n // The template ships a schema.generated.ts for the example blog\n // collections; regenerate it from the introspected collections or\n // the backend serves a schema that doesn't match the database.\n await execa(generateCmd[0], generateCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n console.log(chalk.green(\" Database successfully introspected!\"));\n } catch {\n console.warn(chalk.yellow(\" Warning: Failed to introspect database automatically.\"));\n console.warn(chalk.yellow(` You can run \\`${execCmd.join(\" \")}\\` then \\`${generateCmd.join(\" \")}\\` manually after setup.`));\n }\n } else {\n console.warn(chalk.yellow(\" Skipping introspection because dependencies were not installed.\"));\n console.warn(chalk.yellow(` Run \\`${installCmd.join(\" \")}\\` then \\`${execCmd.join(\" \")}\\` manually.`));\n }\n }\n\n await linkScaffoldToCloud(options);\n\n // Success message\n console.log(\"\");\n console.log(`${chalk.green.bold(\"✓\")} Project ${chalk.bold(options.projectName)} created successfully!`);\n console.log(\"\");\n console.log(chalk.bold(\"Next steps:\"));\n console.log(\"\");\n const runDev = pmCommands.run(\"dev\");\n const runDbPush = pmCommands.run(\"db:push\");\n const isBaas = options.flavor === \"baas\";\n console.log(` ${chalk.cyan(\"cd\")} ${options.projectName}`);\n if (!options.installDeps) {\n console.log(` ${chalk.cyan(installCmd.join(\" \"))}`);\n }\n console.log(\"\");\n\n if (options.databaseUrl) {\n if (options.introspect) {\n console.log(chalk.gray(\" # Database has been introspected & collections generated!\"));\n console.log(chalk.gray(\" # Start the development server (frontend + backend):\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n } else {\n console.log(chalk.gray(\" # Your custom database is configured in .env.\"));\n console.log(chalk.gray(\" # If the database is empty, push the Rebase schema to initialize it:\"));\n console.log(` ${chalk.cyan(runDbPush.join(\" \"))}`);\n console.log(\"\");\n console.log(chalk.gray(\" # Then start the development server:\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n }\n } else if (isBaas) {\n console.log(chalk.gray(\" # A local database configuration has been generated in .env.\"));\n console.log(chalk.gray(\" # 1. Start the PostgreSQL database container:\"));\n console.log(` ${chalk.cyan(\"docker compose up -d db\")}`);\n console.log(\"\");\n console.log(chalk.gray(\" # 2. Create your tables (migrations, SQL, any tool you like).\"));\n console.log(chalk.gray(\" # A table is served once it has an authorization model, i.e.\"));\n console.log(chalk.gray(\" # row-level security enabled plus at least one policy:\"));\n console.log(` ${chalk.cyan(\"ALTER TABLE your_table ENABLE ROW LEVEL SECURITY;\")}`);\n console.log(chalk.gray(\" # The API logs any table it skips, and why.\"));\n console.log(\"\");\n console.log(chalk.gray(\" # 3. Start the API — every protected table is served automatically:\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n } else {\n console.log(chalk.gray(\" # A local database configuration has been generated in .env.\"));\n console.log(chalk.gray(\" # 1. Start the PostgreSQL database container:\"));\n console.log(` ${chalk.cyan(\"docker compose up -d db\")}`);\n console.log(\"\");\n console.log(chalk.gray(\" # 2. Push the Rebase schema to initialize database tables:\"));\n console.log(` ${chalk.cyan(runDbPush.join(\" \"))}`);\n console.log(\"\");\n console.log(chalk.gray(\" # 3. Start the development server (frontend + backend):\"));\n console.log(` ${chalk.cyan(runDev.join(\" \"))}`);\n }\n\n console.log(\"\");\n console.log(isBaas\n ? chalk.gray(\"This starts a headless API (Hono + PostgreSQL). There are no collection files: \")\n + chalk.gray(\"the API is derived from your database schema. Once it serves a table, docs are at /api/swagger.\")\n : chalk.gray(\"This starts both the backend (Hono + PostgreSQL)\")\n + chalk.gray(\" and the frontend (Vite + React) concurrently.\"));\n console.log(\"\");\n console.log(chalk.gray(\"Docs: https://rebase.pro/docs\"));\n console.log(chalk.gray(\"GitHub: https://github.com/rebasepro/rebase\"));\n console.log(\"\");\n console.log(chalk.bold(\"🤖 AI Agent Skills\"));\n console.log(\"\");\n console.log(chalk.gray(\" Install Rebase agent skills for your AI coding assistant:\"));\n console.log(\"\");\n console.log(` ${chalk.cyan(\"rebase skills install\")} ${chalk.gray(\"or\")} ${chalk.cyan(pmCommands.run(\"skills:install\").join(\" \"))}`);\n console.log(\"\");\n}\n\n/**\n * Apply a template preset by replacing the default collection files.\n *\n * The template ships with blog collections at the top level and\n * preset alternatives under `config/collections/presets/<name>/`.\n * This function swaps the active collection files and removes the\n * presets directory so the final project is clean.\n */\n/**\n * Reduce the scaffolded project to the chosen flavor.\n *\n * The base template is the full CMS triad. `baas` drops the frontend and the\n * collections config entirely — there is nothing to define, since the server\n * derives its API from the database — and overlays the files that differ.\n */\nasync function applyFlavor(targetDirectory: string, flavor: TemplateFlavor): Promise<void> {\n if (flavor !== \"baas\") return;\n\n for (const dir of [\"frontend\", \"config\"]) {\n fs.rmSync(path.join(targetDirectory, dir), { recursive: true, force: true });\n }\n // Generated from collection files in cms mode; baas reads the live schema.\n fs.rmSync(path.join(targetDirectory, \"backend\", \"src\", \"schema.generated.ts\"), { force: true });\n\n const overlayDir = path.resolve(cliRoot!, \"templates\", \"overlays\", \"baas\");\n if (!fs.existsSync(overlayDir)) {\n console.error(`${chalk.red.bold(\"ERROR\")} BaaS template overlay not found at ${overlayDir}`);\n process.exit(1);\n }\n\n await cp(overlayDir, targetDirectory, {\n recursive: true,\n force: true,\n filter: (source: string) => {\n const basename = path.basename(source);\n return basename !== \"node_modules\" && basename !== \".DS_Store\";\n }\n });\n}\n\nasync function applyPreset(targetDirectory: string, preset: TemplatePreset): Promise<void> {\n const collectionsDir = path.join(targetDirectory, \"config\", \"collections\");\n const presetsDir = path.join(collectionsDir, \"presets\");\n\n if (preset !== \"blog\") {\n const presetDir = path.join(presetsDir, preset);\n if (!fs.existsSync(presetDir)) {\n console.warn(chalk.yellow(` Warning: Preset \"${preset}\" not found, falling back to blog template.`));\n cleanupPresets(presetsDir);\n return;\n }\n\n // Remove the default blog collection files (keep users.ts — it's shared)\n const blogFiles = [\"posts.ts\", \"authors.ts\", \"tags.ts\", \"index.ts\"];\n for (const file of blogFiles) {\n const filePath = path.join(collectionsDir, file);\n if (fs.existsSync(filePath)) {\n fs.unlinkSync(filePath);\n }\n }\n\n // Copy preset files into the collections directory\n const presetFiles = fs.readdirSync(presetDir).filter(f => f.endsWith(\".ts\"));\n for (const file of presetFiles) {\n fs.copyFileSync(\n path.join(presetDir, file),\n path.join(collectionsDir, file)\n );\n }\n }\n\n // Always clean up the presets directory — it shouldn't ship with the final project\n cleanupPresets(presetsDir);\n}\n\nfunction cleanupPresets(presetsDir: string): void {\n if (fs.existsSync(presetsDir)) {\n fs.rmSync(presetsDir, { recursive: true,\nforce: true });\n }\n}\n\nasync function replacePlaceholders(options: InitOptions) {\n const filesToProcess = [\n \"package.json\",\n \"frontend/package.json\",\n \"backend/package.json\",\n \"config/package.json\",\n \"frontend/index.html\",\n \"pnpm-workspace.yaml\",\n \"README.md\"\n ];\n\n const packageJsonPath = path.resolve(cliRoot!, \"package.json\");\n let cliVersion = \"latest\";\n if (fs.existsSync(packageJsonPath)) {\n const pkg = JSON.parse(fs.readFileSync(packageJsonPath, \"utf-8\"));\n cliVersion = pkg.version || \"latest\";\n }\n\n const versionCache = new Map<string, string>();\n /** Packages with no release matching the CLI's own version. */\n const unreleased = new Map<string, string>();\n\n // Use npm view for registry queries — it's universal and works regardless of PM\n const viewBin = \"npm\";\n\n const getPackageVersion = async (pkgName: string) => {\n if (versionCache.has(pkgName)) return versionCache.get(pkgName)!;\n if (process.env.REBASE_E2E === \"true\") {\n versionCache.set(pkgName, cliVersion);\n return cliVersion;\n }\n let versionToUse = cliVersion;\n try {\n // First try to check if the specific cliVersion exists for this package\n const { stdout } = await execa(viewBin, [\"view\", `${pkgName}@${cliVersion}`, \"version\"]);\n if (!stdout.trim()) throw new Error(\"Not found\");\n versionToUse = stdout.trim();\n } catch {\n try {\n // If specific version doesn't exist, try the matching tag (canary or latest)\n const tag = cliVersion.includes(\"canary\") ? \"canary\" : \"latest\";\n const { stdout } = await execa(viewBin, [\"view\", `${pkgName}@${tag}`, \"version\"]);\n if (!stdout.trim()) throw new Error(\"Not found\");\n versionToUse = stdout.trim();\n } catch {\n try {\n // Fallback to absolute latest\n const { stdout } = await execa(viewBin, [\"view\", pkgName, \"version\"]);\n versionToUse = stdout.trim() || \"latest\";\n } catch {\n versionToUse = \"latest\";\n }\n }\n\n // The fallbacks above answer \"what can I install?\", not \"what matches\n // this CLI?\". When a package has no release at the CLI's own version,\n // they quietly pin whatever the registry last tagged — which can be a\n // prerelease from an entirely different era of the framework. Record\n // it so we can refuse rather than scaffold a mixed-version app.\n if (versionToUse !== cliVersion) {\n unreleased.set(pkgName, versionToUse);\n }\n }\n versionCache.set(pkgName, versionToUse);\n return versionToUse;\n };\n\n // First, find all unique @rebasepro packages across all files to process in parallel\n const allPackages = new Set<string>();\n const fileContents = new Map<string, string>();\n\n for (const file of filesToProcess) {\n const fullPath = path.resolve(options.targetDirectory, file);\n if (!fs.existsSync(fullPath)) continue;\n const content = fs.readFileSync(fullPath, \"utf-8\");\n fileContents.set(fullPath, content);\n\n const matches = [...content.matchAll(/\"(@rebasepro\\/[^\"]+)\":\\s*\"workspace:\\*\"/g)];\n for (const match of matches) {\n allPackages.add(match[1]);\n }\n }\n\n console.log(chalk.gray(\" Resolving package versions...\"));\n\n // Resolve all versions in parallel\n await Promise.all(Array.from(allPackages).map(getPackageVersion));\n\n // A stable CLI whose packages resolve only to a prerelease means those\n // packages were never released at this version — the usual cause is a rename\n // that left the new name published on the canary tag alone. Scaffolding\n // anyway mixes eras (say @rebasepro/types@0.9.0 beside a 0.0.1 canary) and\n // hands the user an app that fails at install or, worse, at runtime. Neither\n // failure names this as the cause, so stop here and say it plainly.\n const cliIsStable = cliVersion !== \"latest\" && !cliVersion.includes(\"-\");\n const prereleasePins = [...unreleased].filter(([, version]) => version === \"latest\" || version.includes(\"-\"));\n\n if (cliIsStable && prereleasePins.length > 0) {\n const lines = prereleasePins.map(([name, version]) => ` ${name} → ${version}`).join(\"\\n\");\n throw new Error(\n `Rebase ${cliVersion} is not fully published to npm.\\n\\n` +\n `These packages have no ${cliVersion} release, so the newest thing on the\\n` +\n `registry is a prerelease:\\n\\n${lines}\\n\\n` +\n `Scaffolding would pin those alongside the ${cliVersion} packages and produce\\n` +\n `an app that cannot install or run. That is a release gap in Rebase itself —\\n` +\n `not a problem with your machine, your network, or your package manager.\\n\\n` +\n `Stopped before writing dependency versions or installing anything. The\\n` +\n `project directory ${path.basename(options.targetDirectory)}/ was created and is safe to delete.\\n` +\n `Please report this with the list above.`\n );\n }\n\n // Perform replacements\n for (const [fullPath, originalContent] of fileContents.entries()) {\n let content = originalContent.replace(/\\{\\{PROJECT_NAME\\}\\}/g, options.projectName);\n\n // Replace workspace:* with the dynamically resolved version\n const matches = [...content.matchAll(/\"(@rebasepro\\/[^\"]+)\":\\s*\"workspace:\\*\"/g)];\n for (const match of matches) {\n const pkgName = match[1];\n const resolvedVersion = versionCache.get(pkgName) || \"latest\";\n content = content.replace(new RegExp(`\"${pkgName}\":\\\\s*\"workspace:\\\\*\"`, \"g\"), `\"${pkgName}\": \"${resolvedVersion}\"`);\n }\n\n fs.writeFileSync(fullPath, content, \"utf-8\");\n }\n}\n\n\nasync function isPortAvailable(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer();\n server.once(\"error\", () => {\n resolve(false);\n });\n server.once(\"listening\", () => {\n server.close(() => resolve(true));\n });\n server.listen(port);\n });\n}\n\nasync function findAvailablePort(startPort: number): Promise<number> {\n let port = startPort;\n while (!(await isPortAvailable(port))) {\n port++;\n }\n return port;\n}\n\nexport async function configureEnvFile(targetDirectory: string, databaseUrl?: string) {\n const envExamplePath = path.join(targetDirectory, \".env.example\");\n const envPath = path.join(targetDirectory, \".env\");\n if (fs.existsSync(envExamplePath) && !fs.existsSync(envPath)) {\n // Copy .env.example → .env (keep .env.example as a reference in the repo)\n fs.copyFileSync(envExamplePath, envPath);\n\n // Generate secure random strings\n const jwtSecret = crypto.randomBytes(32).toString(\"hex\");\n const dbPassword = crypto.randomBytes(16).toString(\"hex\");\n const serviceKey = crypto.randomBytes(48).toString(\"base64\");\n\n let envContent = fs.readFileSync(envPath, \"utf-8\");\n\n envContent = envContent.replace(\n /^JWT_SECRET=.*$/m,\n `JWT_SECRET=${jwtSecret}`\n );\n\n // Ships commented out in .env.example. Left unset, the server generates\n // one on every boot and silently invalidates the previous run's tokens,\n // so write a stable one now rather than making each restart a logout.\n envContent = envContent.replace(\n /^#\\s*REBASE_SERVICE_KEY=.*$/m,\n `REBASE_SERVICE_KEY=${serviceKey}`\n );\n\n if (databaseUrl) {\n if (/[\\r\\n]/.test(databaseUrl)) {\n throw new Error(\"Invalid DATABASE_URL: multiline values are not allowed.\");\n }\n envContent = envContent.replace(\n /^DATABASE_URL=.*$/m,\n `DATABASE_URL=${databaseUrl}`\n );\n } else {\n const dbPort = await findAvailablePort(5432);\n envContent = envContent.replace(\n /^DATABASE_URL=.*$/m,\n // sslmode=disable: the paired docker-compose Postgres has no TLS,\n // and Go-based tooling (atlas, via `rebase db push`) defaults to\n // requiring SSL when the URL doesn't say otherwise.\n `DATABASE_URL=postgresql://rebase:${dbPassword}@localhost:${dbPort}/rebase?options=-c%20search_path=public&sslmode=disable\\nDATABASE_PASSWORD=${dbPassword}`\n );\n\n // Also update docker-compose.yml with the dynamic host port if it has the default 5432 port mapping\n const dockerComposePath = path.join(targetDirectory, \"docker-compose.yml\");\n if (fs.existsSync(dockerComposePath)) {\n let dockerComposeContent = fs.readFileSync(dockerComposePath, \"utf-8\");\n dockerComposeContent = dockerComposeContent.replace(\n /-\\s*\"5432:5432\"/g,\n `- \"${dbPort}:5432\"`\n );\n fs.writeFileSync(dockerComposePath, dockerComposeContent, \"utf-8\");\n }\n }\n\n fs.writeFileSync(envPath, envContent, \"utf-8\");\n }\n}\n","/**\n * CLI command: generate-sdk\n *\n * Reads collection definitions from a specified directory (default: ./config/collections),\n * generates a typed TypeScript SDK, and writes it to the output directory (default: ./generated/sdk).\n *\n * Uses jiti for dynamic TypeScript import of collection files.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { generateSDK, GeneratedFile } from \"@rebasepro/codegen\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\n\ninterface GenerateSDKArgs {\n collectionsDir: string;\n output: string;\n cwd: string;\n}\n\n/**\n * Dynamically load collection definitions from a directory.\n *\n * Expects the directory to have an index.ts/index.js that exports a default\n * array of CollectionConfig objects (matching the app/config/collections pattern).\n */\nasync function loadCollections(collectionsDir: string): Promise<CollectionConfig[]> {\n const absDir = path.resolve(collectionsDir);\n\n if (!fs.existsSync(absDir)) {\n throw new Error(`Collections directory not found: ${absDir}`);\n }\n\n // Try to import the index file using jiti (supports TypeScript natively)\n let jiti: (id: string, userOptions?: Record<string, unknown>) => (modulePath: string) => Record<string, unknown>;\n try {\n const jitiModule = await import(\"jiti\");\n jiti = (jitiModule.default || jitiModule) as typeof jiti;\n } catch {\n const installCmd = [...getPMCommands(detectPackageManager()).install, \"-D\", \"jiti\"].join(\" \");\n throw new Error(\n `Could not load 'jiti'. Install it with: ${installCmd}\\n` +\n \"jiti is required to dynamically import TypeScript collection definitions.\"\n );\n }\n\n const jitiInstance = jiti(absDir, {\n interopDefault: true,\n esmResolve: true\n });\n\n // Look for index file\n const indexCandidates = [\"index.ts\", \"index.js\", \"index.mjs\"];\n let indexPath: string | null = null;\n\n for (const candidate of indexCandidates) {\n const p = path.join(absDir, candidate);\n if (fs.existsSync(p)) {\n indexPath = p;\n break;\n }\n }\n\n if (!indexPath) {\n // Fallback: load each .ts/.js file individually\n console.log(chalk.yellow(\" No index file found, scanning individual collection files...\"));\n const collections: CollectionConfig[] = [];\n const files = fs.readdirSync(absDir).filter(f =>\n (f.endsWith(\".ts\") || f.endsWith(\".js\")) && !f.startsWith(\".\")\n );\n\n for (const file of files) {\n try {\n const mod = jitiInstance(path.join(absDir, file));\n const exported = mod.default || mod;\n if (exported && typeof exported === \"object\" && \"slug\" in exported) {\n collections.push(exported as CollectionConfig);\n } else if (Array.isArray(exported)) {\n collections.push(...exported);\n }\n } catch (err) {\n console.warn(chalk.yellow(` ⚠ Skipping ${file}: ${(err as Error).message}`));\n }\n }\n\n return collections;\n }\n\n // Import the index\n const mod = jitiInstance(indexPath);\n const exported = mod.default || mod;\n\n if (Array.isArray(exported)) {\n return exported as CollectionConfig[];\n } else if (typeof exported === \"object\" && exported !== null) {\n // Could be a named export like { collections: [...] }\n if (\"collections\" in exported && Array.isArray(exported.collections)) {\n return exported.collections;\n }\n // Or individual named exports\n const collections: CollectionConfig[] = [];\n for (const value of Object.values(exported)) {\n if (value && typeof value === \"object\" && \"slug\" in (value as CollectionConfig)) {\n collections.push(value as CollectionConfig);\n }\n }\n if (collections.length > 0) return collections;\n }\n\n throw new Error(\n `Could not extract collections from ${indexPath}.\\n` +\n \"Expected a default export of CollectionConfig[] or an object with named collection exports.\"\n );\n}\n\n/**\n * Write generated files to the output directory.\n */\nfunction writeFiles(outputDir: string, files: GeneratedFile[]): void {\n const absOutput = path.resolve(outputDir);\n\n // Create output directory\n fs.mkdirSync(absOutput, { recursive: true });\n\n for (const file of files) {\n const filePath = path.join(absOutput, file.path);\n const dir = path.dirname(filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n fs.writeFileSync(filePath, file.content, \"utf-8\");\n }\n}\n\n/**\n * Main entry point for the generate-sdk command.\n */\nexport async function generateSdkCommand(args: GenerateSDKArgs): Promise<void> {\n const { collectionsDir, output, cwd } = args;\n\n const resolvedCollectionsDir = path.isAbsolute(collectionsDir)\n ? collectionsDir\n : path.join(cwd, collectionsDir);\n\n const resolvedOutput = path.isAbsolute(output)\n ? output\n : path.join(cwd, output);\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔧 Rebase SDK Generator\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Collections:\")} ${resolvedCollectionsDir}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n\n // 1. Load collections\n console.log(chalk.cyan(\" → Loading collection definitions...\"));\n const collections = await loadCollections(resolvedCollectionsDir);\n\n // Sort collections alphabetically by slug to ensure deterministic SDK generation\n collections.sort((a, b) => a.slug.localeCompare(b.slug));\n\n if (collections.length === 0) {\n console.log(chalk.red(\" ✗ No collections found. Nothing to generate.\"));\n process.exit(1);\n }\n\n console.log(chalk.green(` ✓ Found ${collections.length} collection(s): ${collections.map(c => c.slug).join(\", \")}`));\n console.log(\"\");\n\n // 2. Generate SDK files\n console.log(chalk.cyan(\" → Generating SDK files...\"));\n const files = generateSDK(collections);\n console.log(chalk.green(` ✓ Generated ${files.length} file(s)`));\n\n // 3. Write to disk\n console.log(chalk.cyan(` → Writing to ${resolvedOutput}...`));\n writeFiles(resolvedOutput, files);\n\n console.log(\"\");\n console.log(chalk.green.bold(\" ✓ SDK generated successfully!\"));\n console.log(\"\");\n console.log(chalk.gray(\" Usage:\"));\n console.log(chalk.gray(\" import { createRebaseClient } from '@rebasepro/client';\"));\n console.log(chalk.gray(` import type { Database } from './${path.relative(cwd, path.join(resolvedOutput, \"database.types\"))}';`));\n console.log(\"\");\n console.log(chalk.gray(\" const rebase = createRebaseClient<Database>({\"));\n console.log(chalk.gray(\" baseUrl: 'http://localhost:3001',\"));\n console.log(chalk.gray(\" // token: 'your-jwt-token',\"));\n console.log(chalk.gray(\" });\"));\n console.log(\"\");\n console.log(chalk.gray(` const { data } = await rebase.collection('${collections[0]?.slug || \"my_collection\"}').find();`));\n console.log(\"\");\n}\n","/**\n * CLI command: rebase schema <action>\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile\n} from \"../utils/project\";\n\nexport async function schemaCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printSchemaHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));\n process.exit(1);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n try {\n const isTs = pluginCli.endsWith(\".ts\");\n if (isTs) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n } else {\n await execa(\"node\", [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n } catch {\n process.exit(1);\n }\n}\n\nfunction printSchemaHelp() {\n console.log(`\n${chalk.bold(\"rebase schema\")} — Schema management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase schema ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"generate\")} Generate Schema from collection definitions\n ${chalk.blue.bold(\"introspect\")} Introspect an existing database to generate collection definitions\n\n${chalk.green.bold(\"generate Options\")}\n ${chalk.blue(\"--collections, -c\")} Path to collections directory\n ${chalk.blue(\"--output, -o\")} Output path for generated schema\n ${chalk.blue(\"--watch, -w\")} Watch for changes and regenerate automatically\n\n${chalk.green.bold(\"introspect Options\")}\n ${chalk.blue(\"--output, -o\")} Output directory for generated collection files\n`);\n}\n","/**\n * CLI command: rebase db <action>\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile\n} from \"../utils/project\";\n\nexport async function dbCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printDbHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));\n process.exit(1);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n try {\n const isTs = pluginCli.endsWith(\".ts\");\n if (isTs) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n } else {\n await execa(\"node\", [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n } catch {\n // If the process exits with an error code, execa will throw,\n // but inherit stdio means the user already saw the output.\n process.exit(1);\n }\n}\n\nfunction printDbHelp() {\n console.log(`\n${chalk.bold(\"rebase db\")} — Database management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase db ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"push\")} Apply schema directly to database (development)\n ${chalk.blue.bold(\"generate\")} Generate migration files\n ${chalk.blue.bold(\"migrate\")} Run pending migrations\n ${chalk.blue.bold(\"branch\")} Database branching (create, list, delete, info)\n ${chalk.blue.bold(\"backup\")} Create a backup with pg_dump (--out <path|s3://…>)\n ${chalk.blue.bold(\"restore\")} Restore a backup with pg_restore (destructive; needs --yes)\n ${chalk.blue.bold(\"backups\")} List stored backups (backups list)\n\n${chalk.green.bold(\"Examples\")}\n ${chalk.gray(\"# Quick development workflow\")}\n rebase schema generate && rebase db push\n\n ${chalk.gray(\"# Production migration workflow\")}\n rebase db generate\n rebase db migrate\n\n ${chalk.gray(\"# Create a database branch\")}\n rebase db branch create feature_auth\n\n ${chalk.gray(\"# Back up to a local directory, then to object storage\")}\n rebase db backup --out ./backups\n rebase db backup --out s3://my-private-bucket/backups\n\n ${chalk.gray(\"# Restore into a fresh database (safe: does not touch the live one)\")}\n rebase db restore ./backups/rebase-app-20260714T030000Z.dump --create-db --target-db app_restored\n`);\n}\n","/**\n * CLI command: rebase dev\n *\n * Starts the full development environment:\n * - Backend: tsx watch with auto-reload\n * - Frontend: vite dev server\n *\n * Both processes stream output with color-coded prefixes.\n *\n * When the backend uses port-retry (i.e. the configured port is busy and it\n * binds to the next free one), the CLI detects the actual port from stdout\n * and injects VITE_API_URL into the frontend so it connects automatically.\n *\n * Each project gets a deterministic default port derived from the project\n * root path, so multiple Rebase instances never collide.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { execa, execaCommandSync, type ResultPromise } from \"execa\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport {\n requireProjectRoot,\n findBackendDir,\n findFrontendDir,\n findEnvFile,\n resolveTsx,\n validateTsxInstallation,\n getActiveBackendPlugin,\n resolvePluginCliScript\n} from \"../utils/project\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\n\n/** Well-known filename the backend writes its actual port to. */\nconst DEV_PORT_FILENAME = \".rebase-dev-port\";\n\n/**\n * Compute a deterministic port from the project root path.\n * Range: 3001–3999 (avoids privileged ports and common services).\n * Two different project directories will almost always get different ports.\n */\nfunction getProjectPort(projectRoot: string): number {\n let hash = 0;\n for (let i = 0; i < projectRoot.length; i++) {\n hash = ((hash << 5) - hash + projectRoot.charCodeAt(i)) | 0;\n }\n return 3001 + (Math.abs(hash) % 999);\n}\n\n/**\n * Resolve the best starting port for this project:\n * 1. Explicit --port flag (highest priority)\n * 2. PORT env var\n * 3. Previously used port from .rebase-dev-port (port affinity across restarts)\n * 4. Deterministic hash from project path (unique per project)\n */\nfunction resolveStartPort(projectRoot: string, explicitPort?: number): number {\n // 1. Explicit flag\n if (explicitPort) return explicitPort;\n\n // 2. PORT env var\n if (process.env.PORT) return parseInt(process.env.PORT, 10);\n\n // 3. Port affinity — check if we wrote a port file from a previous run\n try {\n const portFile = path.join(projectRoot, DEV_PORT_FILENAME);\n if (fs.existsSync(portFile)) {\n const saved = parseInt(fs.readFileSync(portFile, \"utf-8\").trim(), 10);\n if (saved > 0 && saved < 65536) return saved;\n }\n } catch { /* ignore */ }\n\n // 4. Deterministic hash\n return getProjectPort(projectRoot);\n}\n\nexport async function devCommand(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--backend-only\": Boolean,\n \"--frontend-only\": Boolean,\n \"--port\": Number,\n \"--generate\": Boolean,\n \"--help\": Boolean,\n \"-b\": \"--backend-only\",\n \"-f\": \"--frontend-only\",\n \"-p\": \"--port\",\n \"-g\": \"--generate\",\n \"-h\": \"--help\"\n },\n {\n argv: rawArgs.slice(3), // skip \"node rebase dev\"\n permissive: true\n }\n );\n\n if (args[\"--help\"]) {\n printDevHelp();\n return;\n }\n\n const projectRoot = requireProjectRoot();\n const backendDir = findBackendDir(projectRoot);\n const frontendDir = findFrontendDir(projectRoot);\n const backendOnly = args[\"--backend-only\"] || false;\n const frontendOnly = args[\"--frontend-only\"] || false;\n const shouldGenerate = args[\"--generate\"] || process.env.REBASE_AUTO_GENERATE === \"true\" || process.env.REBASE_GENERATE === \"true\";\n\n // Resolve the port ONCE, before starting anything\n const startPort = resolveStartPort(projectRoot, args[\"--port\"]);\n\n console.log(\"\");\n console.log(chalk.bold(\" 🚀 Rebase Dev Server\"));\n console.log(\"\");\n\n const children: ResultPromise[] = [];\n\n // --- State for printing the banner ---\n let frontendUrl = \"\";\n let backendUrl = \"\";\n let debounceSummary: NodeJS.Timeout | null = null;\n let bannerPrinted = false;\n\n /** Actual backend port, resolved once the server prints its URL. */\n let resolvedBackendPort: number | null = null;\n\n // Use regex to strip ANSI codes before matching\n // eslint-disable-next-line no-control-regex\n const stripAnsi = (str: string) => str.replace(/[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, \"\");\n\n function printSummary() {\n if (!frontendUrl || !backendUrl) return;\n if (debounceSummary) clearTimeout(debounceSummary);\n debounceSummary = setTimeout(() => {\n if (bannerPrinted) return;\n console.log(\"\");\n console.log(chalk.cyan(\"┌────────────────────────────────────────────────────────────┐\"));\n console.log(chalk.cyan(\"│ │\"));\n console.log(chalk.cyan(\"│ ✦ Rebase Admin App is ready! │\"));\n const cleanUrl = stripAnsi(frontendUrl);\n const paddedUrl = cleanUrl.padEnd(41);\n console.log(chalk.cyan(\"│ ➜ Frontend URL: \") + chalk.white(paddedUrl) + chalk.cyan(\"│\"));\n console.log(chalk.cyan(\"│ │\"));\n console.log(chalk.cyan(\"└────────────────────────────────────────────────────────────┘\"));\n console.log(\"\");\n bannerPrinted = true;\n }, 500);\n }\n\n // Handle graceful shutdown\n const cleanup = () => {\n // Clean up dev port file\n try {\n const portFile = path.join(projectRoot, DEV_PORT_FILENAME);\n if (fs.existsSync(portFile)) fs.unlinkSync(portFile);\n\n const urlFile = path.join(projectRoot, \".rebase-dev-url\");\n if (fs.existsSync(urlFile)) fs.unlinkSync(urlFile);\n } catch { /* ignore */ }\n\n children.forEach((child) => {\n if (child.pid && !child.killed) {\n try {\n if (process.platform === \"win32\") {\n execaCommandSync(`taskkill /pid ${child.pid} /T /F`);\n } else {\n process.kill(-child.pid, \"SIGKILL\");\n }\n } catch (e) {\n try {\n child.kill(\"SIGKILL\");\n } catch (err) {\n // ignore\n }\n }\n }\n });\n process.exit(0);\n };\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n /**\n * Start the Vite frontend, optionally injecting the backend port.\n */\n function startFrontend(backendPort: number | null) {\n if (!frontendDir) return;\n\n console.log(` ${chalk.magenta(\"▶\")} Frontend: ${chalk.gray(frontendDir)}`);\n\n const frontendEnv: Record<string, string> = { ...process.env as Record<string, string> };\n\n // Inject the resolved backend URL so Vite picks it up\n if (backendPort) {\n frontendEnv.VITE_API_URL = `http://localhost:${backendPort}`;\n console.log(` ${chalk.gray(\"↳ VITE_API_URL\")} = ${chalk.white(`http://localhost:${backendPort}`)}`);\n }\n\n const pm = detectPackageManager(projectRoot);\n const pmCmds = getPMCommands(pm);\n const runDevCmd = pmCmds.run(\"dev\");\n\n const frontendChild = execa(\n runDevCmd[0],\n runDevCmd.slice(1),\n {\n cwd: frontendDir,\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n env: frontendEnv,\n shell: true,\n detached: process.platform !== \"win32\"\n }\n );\n frontendChild.catch(() => {}); // prevent unhandled promise rejection on exit\n\n frontendChild.stdout?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.magenta.bold(\"[admin]\")} ${line}`);\n const cleanLine = stripAnsi(line);\n const urlMatch = cleanLine.match(/(http:\\/\\/(?:localhost|127\\.0\\.0\\.1):\\d+)/);\n if (cleanLine.includes(\"Local:\") && urlMatch) {\n frontendUrl = urlMatch[1];\n printSummary();\n }\n });\n });\n\n frontendChild.stderr?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.magenta.bold(\"[admin]\")} ${line}`);\n });\n });\n\n children.push(frontendChild);\n }\n\n // Start backend\n if (!frontendOnly && backendDir) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n const pmCmdsLocal = getPMCommands(detectPackageManager(projectRoot));\n const addCmd = [...pmCmdsLocal.install, \"-D\", \"tsx\"].join(\" \");\n console.error(chalk.red(\" ✗ Could not find tsx binary for backend.\"));\n console.error(chalk.gray(` Install it with: ${addCmd}`));\n process.exit(1);\n }\n\n // Verify the tsx installation is intact (not just the symlink)\n const tsxValidationError = validateTsxInstallation(tsxBin);\n if (tsxValidationError) {\n const pmCmdsLocal = getPMCommands(detectPackageManager(projectRoot));\n const installCmd = pmCmdsLocal.install.join(\" \");\n console.error(chalk.red(\" ✗ tsx installation appears corrupted.\"));\n console.error(chalk.gray(` ${tsxValidationError}`));\n console.error(\"\");\n console.error(chalk.gray(\" To fix, run:\"));\n console.error(chalk.cyan(` rm -rf node_modules && ${installCmd}`));\n process.exit(1);\n }\n\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n // Always inject PORT so the backend uses our resolved port instead of\n // its hardcoded default (3001). This prevents cross-project collisions\n // when multiple Rebase instances run simultaneously.\n env.PORT = String(startPort);\n\n console.log(` ${chalk.cyan(\"▶\")} Backend: ${chalk.gray(backendDir)}`);\n console.log(` ${chalk.gray(\"↳ PORT\")} = ${chalk.white(String(startPort))}`);\n\n // The .env's PORT / VITE_API_URL look authoritative but are overridden in\n // dev: we derive a per-project port to avoid cross-project collisions and\n // point the frontend at it. Surface that so a mismatched .env doesn't turn\n // into a silent \"connecting to the wrong port\" debugging loop.\n if (envFile) {\n try {\n const envText = fs.readFileSync(envFile, \"utf-8\");\n const readEnvKey = (key: string): string | undefined => {\n const m = envText.match(new RegExp(`^\\\\s*${key}\\\\s*=\\\\s*(.+?)\\\\s*$`, \"m\"));\n return m ? m[1].replace(/^[\"']|[\"']$/g, \"\") : undefined;\n };\n const envPort = readEnvKey(\"PORT\");\n const envApiUrl = readEnvKey(\"VITE_API_URL\");\n // Only name the keys — never echo a raw `http://localhost:<port>`\n // value, so log scrapers don't mistake it for the dev server URL.\n const overridden: string[] = [];\n if (envPort && envPort !== String(startPort)) overridden.push(\"PORT\");\n if (envApiUrl && envApiUrl !== `http://localhost:${startPort}`) overridden.push(\"VITE_API_URL\");\n if (overridden.length > 0) {\n console.log(chalk.yellow(\n ` ⚠ dev uses a derived per-project port (${startPort}); your .env ${overridden.join(\" / \")} ` +\n `${overridden.length > 1 ? \"are\" : \"is\"} ignored here (avoids cross-project collisions). ` +\n `Pass ${chalk.white(\"--port\")} to pin a port.`\n ));\n }\n } catch { /* ignore — best-effort notice */ }\n }\n\n /** Whether the frontend has been launched (we only launch it once). */\n let frontendLaunched = false;\n\n // Initial schema and SDK generation (disabled by default, enabled via --generate or env var)\n if (shouldGenerate) {\n console.log(chalk.gray(\" → Ensuring schema and SDK are generated on start...\"));\n try {\n const activePlugin = getActiveBackendPlugin(backendDir);\n const pluginCli = activePlugin ? resolvePluginCliScript(backendDir, activePlugin) : null;\n if (pluginCli) {\n await execa(tsxBin, [pluginCli, \"schema\", \"generate\"], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n const sdkCmd = getPMCommands(detectPackageManager(projectRoot)).exec(\"rebase\", [\"generate-sdk\"]);\n await execa(sdkCmd[0], sdkCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n console.log(chalk.green(\" ✓ Initial schema and SDK generated successfully.\\n\"));\n } catch (err: unknown) {\n console.error(chalk.red(` ✗ Initial schema/SDK generation failed: ${err instanceof Error ? err.message : err}\\n`));\n }\n\n // Watch collections folder for changes\n const collectionsDir = path.join(projectRoot, \"config\", \"collections\");\n if (fs.existsSync(collectionsDir)) {\n let watchDebounce: NodeJS.Timeout | null = null;\n fs.watch(collectionsDir, { recursive: true }, (eventType, filename) => {\n if (!filename || filename.startsWith(\".\") || filename.endsWith(\".tmp\")) return;\n\n if (watchDebounce) clearTimeout(watchDebounce);\n watchDebounce = setTimeout(async () => {\n console.log(chalk.yellow(`\\n 🔄 Collection change detected (${filename}). Regenerating schema & SDK...`));\n try {\n const activePlugin = getActiveBackendPlugin(backendDir);\n const pluginCli = activePlugin ? resolvePluginCliScript(backendDir, activePlugin) : null;\n if (pluginCli) {\n await execa(tsxBin, [pluginCli, \"schema\", \"generate\"], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n const sdkCmd = getPMCommands(detectPackageManager(projectRoot)).exec(\"rebase\", [\"generate-sdk\"]);\n await execa(sdkCmd[0], sdkCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n console.log(chalk.green(\" ✓ Schema & SDK regenerated successfully. Hono will reload.\"));\n } catch (err: unknown) {\n console.error(chalk.red(` ✗ Failed to regenerate schema/SDK: ${err instanceof Error ? err.message : err}`));\n }\n }, 300);\n });\n }\n }\n\n const watchArgs = [\"watch\", \"--conditions\", \"development\", \"src/index.ts\"];\n if (!shouldGenerate) {\n // When auto-generation is disabled, watch the config/collections dir directly so the dev server\n // still reloads automatically when files there are edited/updated manually.\n watchArgs.splice(1, 0, `--watch=\"${path.join(\"..\", \"config\", \"**\", \"*\")}\"`);\n\n // Watch collections folder and warn about potential schema drift\n const collectionsDir = path.join(projectRoot, \"config\", \"collections\");\n if (fs.existsSync(collectionsDir)) {\n let driftDebounce: NodeJS.Timeout | null = null;\n fs.watch(collectionsDir, { recursive: true }, (_eventType, filename) => {\n if (!filename || filename.startsWith(\".\") || filename.endsWith(\".tmp\")) return;\n if (driftDebounce) clearTimeout(driftDebounce);\n driftDebounce = setTimeout(() => {\n console.log([\n \"\",\n chalk.yellow(\" ┌──────────────────────────────────────────────────────────────┐\"),\n chalk.yellow(\" │ ⚠️ Collection file changed: \") + chalk.white(filename!.padEnd(31)) + chalk.yellow(\"│\"),\n chalk.yellow(\" │ │\"),\n chalk.yellow(\" │ Your schema may be out of sync. Run: │\"),\n chalk.yellow(\" │ \") + chalk.cyan(\"rebase schema generate\") + chalk.yellow(\" regenerate Drizzle schema │\"),\n chalk.yellow(\" │ \") + chalk.cyan(\"rebase db push \") + chalk.yellow(\" sync schema to database │\"),\n chalk.yellow(\" │ \") + chalk.cyan(\"rebase doctor \") + chalk.yellow(\" check for drift │\"),\n chalk.yellow(\" │ │\"),\n chalk.yellow(\" │ TIP: Use \") + chalk.bold(\"rebase dev --generate\") + chalk.yellow(\" for auto-regeneration │\"),\n chalk.yellow(\" └──────────────────────────────────────────────────────────────┘\"),\n \"\"\n ].join(\"\\n\"));\n }, 500);\n });\n }\n }\n\n const backendChild = execa(\n tsxBin,\n watchArgs,\n {\n cwd: backendDir,\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n env,\n shell: true,\n detached: process.platform !== \"win32\"\n }\n );\n backendChild.catch(() => {}); // prevent unhandled promise rejection on exit\n\n backendChild.stdout?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.cyan.bold(\"[backend]\")} ${line}`);\n const cleanLine = stripAnsi(line);\n const serverMatch = cleanLine.match(/Server running at http:\\/\\/(?:localhost|127\\.0\\.0\\.1):(\\d+)/);\n if (serverMatch) {\n resolvedBackendPort = parseInt(serverMatch[1], 10);\n backendUrl = \"started\";\n printSummary();\n\n // Save the url to a temp file for scripts to pick up\n const urlFile = path.join(projectRoot, \".rebase-dev-url\");\n fs.writeFileSync(urlFile, `http://localhost:${resolvedBackendPort}`, \"utf-8\");\n\n // Save the port to .rebase-dev-port for port affinity\n const portFile = path.join(projectRoot, DEV_PORT_FILENAME);\n fs.writeFileSync(portFile, String(resolvedBackendPort), \"utf-8\");\n\n // Start frontend now that we know the real port\n if (!backendOnly && frontendDir && !frontendLaunched) {\n frontendLaunched = true;\n startFrontend(resolvedBackendPort);\n }\n }\n });\n });\n\n /** Whether we've already shown a corrupted-modules recovery hint. */\n let corruptedModulesWarned = false;\n\n backendChild.stderr?.on(\"data\", (data: Buffer) => {\n const lines = data.toString().split(\"\\n\").filter(Boolean);\n lines.forEach((line: string) => {\n console.log(`${chalk.cyan.bold(\"[backend]\")} ${line}`);\n\n // Detect corrupted node_modules at runtime\n // (covers tsx and any other dependency whose pnpm store entry is broken)\n if (!corruptedModulesWarned) {\n const cleanLine = stripAnsi(line);\n if (\n cleanLine.includes(\"Cannot find module\") &&\n cleanLine.includes(\"node_modules/.pnpm/\")\n ) {\n corruptedModulesWarned = true;\n // Delay slightly so the full Node.js error stack prints first\n setTimeout(() => {\n const pm = detectPackageManager(projectRoot);\n const installCmd = getPMCommands(pm).install.join(\" \");\n console.error(\"\");\n console.error(chalk.red(\" ✗ node_modules appears corrupted — a required file is missing.\"));\n console.error(chalk.gray(\" This usually happens when a previous install was interrupted\"));\n console.error(chalk.gray(\" or the package manager store was cleaned.\"));\n console.error(\"\");\n console.error(chalk.gray(\" To fix, stop the dev server and run:\"));\n console.error(chalk.cyan(` rm -rf node_modules && ${installCmd}`));\n console.error(\"\");\n }, 200);\n }\n }\n });\n });\n\n children.push(backendChild);\n } else if (!frontendOnly && !backendDir) {\n console.warn(chalk.yellow(\" ⚠ No backend/ directory found, skipping backend.\"));\n }\n\n // Start frontend immediately if backend-only mode or no backend\n if (!backendOnly && frontendDir && (frontendOnly || !backendDir)) {\n startFrontend(null);\n } else if (!backendOnly && !frontendDir) {\n console.warn(chalk.yellow(\" ⚠ No frontend/ directory found, skipping frontend.\"));\n }\n\n if (children.length === 0) {\n console.error(chalk.red(\" ✗ Nothing to start. Check your project structure.\"));\n process.exit(1);\n }\n\n console.log(\"\");\n console.log(chalk.gray(\" Press Ctrl+C to stop all servers.\"));\n console.log(\"\");\n\n // Wait for all children to exit\n await Promise.all(\n children.map(\n (child) =>\n new Promise<void>((resolve) => {\n child.finally(() => resolve());\n })\n )\n );\n}\n\nfunction printDevHelp() {\n console.log(`\n${chalk.bold(\"rebase dev\")} — Start the development server\n\n${chalk.green.bold(\"Usage\")}\n rebase dev [options]\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--backend-only, -b\")} Only start the backend server\n ${chalk.blue(\"--frontend-only, -f\")} Only start the frontend server\n ${chalk.blue(\"--port, -p\")} Backend port (default: auto-detected per project)\n ${chalk.blue(\"--generate, -g\")} Enable automatic schema and SDK generation on startup and file changes\n\n${chalk.green.bold(\"Description\")}\n Starts both the backend (tsx watch + Hono) and frontend (Vite)\n dev servers concurrently with color-coded output prefixes.\n\n Each project automatically receives a unique default port derived\n from its directory path, preventing collisions when running multiple\n Rebase instances simultaneously.\n\n If the assigned port is already in use, the server will automatically\n try the next available port. The frontend is started only after the\n backend is ready, and VITE_API_URL is injected automatically.\n\n By default, automatic schema and SDK generation is disabled on startup\n and file changes. Pass --generate (-g) or set REBASE_AUTO_GENERATE=true\n in your environment to enable it.\n`);\n}\n","/**\n * CLI command: rebase build\n *\n * Runs the build script in all workspace packages.\n * Automatically detects the package manager (pnpm or npm) and\n * uses the correct workspace-aware command.\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport { requireProjectRoot } from \"../utils/project\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\n\nexport async function buildCommand(): Promise<void> {\n const projectRoot = requireProjectRoot();\n const pm = detectPackageManager(projectRoot);\n const cmds = getPMCommands(pm);\n\n const buildCmd = cmds.runAll(\"build\");\n\n console.log(`${chalk.bold(\"Rebase\")} — Building all workspaces with ${chalk.cyan(pm)}...\\n`);\n\n try {\n await execa(buildCmd[0], buildCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\"\n });\n } catch {\n console.error(chalk.red(\"\\n✗ Build failed.\"));\n process.exit(1);\n }\n}\n","/**\n * CLI command: rebase start\n *\n * Starts the backend server in production mode.\n * Automatically detects the package manager (pnpm or npm) and\n * runs the start script in the backend workspace.\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport { requireProjectRoot, findEnvFile } from \"../utils/project\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\n\nexport async function startCommand(): Promise<void> {\n const projectRoot = requireProjectRoot();\n const pm = detectPackageManager(projectRoot);\n const cmds = getPMCommands(pm);\n\n const startCmd = cmds.runWorkspace(\"backend\", \"start\");\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n console.log(`${chalk.bold(\"Rebase\")} — Starting backend server...\\n`);\n\n try {\n await execa(startCmd[0], startCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n } catch {\n console.error(chalk.red(\"\\n✗ Failed to start server.\"));\n process.exit(1);\n }\n}\n","/**\n * CLI command: rebase auth <action>\n *\n * Subcommands:\n * reset-password — Reset a user's password\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { spawn } from \"child_process\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n findEnvFile,\n resolveTsx\n} from \"../utils/project\";\n\nexport async function authCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printAuthHelp();\n return;\n }\n\n switch (subcommand) {\n case \"reset-password\":\n await resetPassword(rawArgs);\n break;\n default:\n console.error(chalk.red(`Unknown auth command: ${subcommand}`));\n console.log(\"\");\n printAuthHelp();\n process.exit(1);\n }\n}\n\nasync function resetPassword(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--email\": String,\n \"--password\": String,\n \"-e\": \"--email\",\n \"-p\": \"--password\"\n },\n {\n argv: rawArgs.slice(4), // skip \"node rebase auth reset-password\"\n permissive: true\n }\n );\n\n // Support both --email flag and positional args\n const email = args[\"--email\"] || args._[0];\n const newPassword = args[\"--password\"] || args._[1];\n\n if (!email) {\n console.error(chalk.red(\"✗ Email is required.\"));\n console.log(\"\");\n console.log(chalk.gray(\" Usage: rebase auth reset-password <email> [new-password]\"));\n console.log(chalk.gray(\" rebase auth reset-password --email user@example.com --password NewPass123!\"));\n process.exit(1);\n }\n\n const projectRoot = requireProjectRoot();\n\n // 1. Try API-first reset\n let envServiceKey: string | undefined;\n const envFile = findEnvFile(projectRoot);\n if (envFile && fs.existsSync(envFile)) {\n try {\n const envContent = fs.readFileSync(envFile, \"utf8\");\n const match = envContent.match(/^\\s*REBASE_SERVICE_KEY\\s*=\\s*['\"]?(.*?)['\"]?\\s*$/m);\n if (match && match[1]) {\n envServiceKey = match[1];\n }\n } catch {\n // Ignore\n }\n }\n\n let baseUrl = process.env.REBASE_BASE_URL;\n let serviceKey = process.env.REBASE_SERVICE_KEY || envServiceKey;\n\n const statePath = path.join(projectRoot, \".rebase\", \"state.json\");\n if (fs.existsSync(statePath)) {\n try {\n const state = JSON.parse(fs.readFileSync(statePath, \"utf8\")) as Record<string, unknown>;\n if (state && typeof state === \"object\") {\n if (typeof state.baseUrl === \"string\" && !baseUrl) {\n baseUrl = state.baseUrl;\n }\n if (typeof state.serviceKey === \"string\" && !serviceKey) {\n serviceKey = state.serviceKey;\n }\n }\n } catch {\n // Ignore\n }\n }\n\n const devUrlPath = path.join(projectRoot, \".rebase-dev-url\");\n if (fs.existsSync(devUrlPath) && !baseUrl) {\n try {\n baseUrl = fs.readFileSync(devUrlPath, \"utf8\").trim();\n } catch {\n // Ignore\n }\n }\n\n if (baseUrl && serviceKey) {\n console.log(\"Trying API-first reset via running backend...\");\n try {\n const finalPass = newPassword || \"NewPassword123!\";\n const cleanBaseUrl = baseUrl.replace(/\\/+$/, \"\");\n const searchUrl = `${cleanBaseUrl}/api/admin/users?search=${encodeURIComponent(email)}&limit=1`;\n const searchRes = await fetch(searchUrl, {\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Accept\": \"application/json\"\n }\n });\n if (!searchRes.ok) {\n throw new Error(`Failed to list users: ${searchRes.statusText}`);\n }\n const searchData = await searchRes.json() as unknown;\n if (!searchData || typeof searchData !== \"object\") {\n throw new Error(\"Invalid response format from user search API.\");\n }\n \n let userId: string | undefined;\n if (Array.isArray(searchData)) {\n const firstUser = searchData[0] as unknown;\n if (firstUser && typeof firstUser === \"object\" && \"id\" in firstUser && typeof (firstUser as { id: unknown }).id === \"string\") {\n userId = (firstUser as { id: string }).id;\n } else if (firstUser && typeof firstUser === \"object\" && \"uid\" in firstUser && typeof (firstUser as { uid: unknown }).uid === \"string\") {\n userId = (firstUser as { uid: string }).uid;\n }\n } else if (\"users\" in searchData && Array.isArray((searchData as { users: unknown }).users)) {\n const users = (searchData as { users: unknown[] }).users;\n const firstUser = users[0];\n if (firstUser && typeof firstUser === \"object\" && \"id\" in firstUser && typeof (firstUser as { id: unknown }).id === \"string\") {\n userId = (firstUser as { id: string }).id;\n } else if (firstUser && typeof firstUser === \"object\" && \"uid\" in firstUser && typeof (firstUser as { uid: unknown }).uid === \"string\") {\n userId = (firstUser as { uid: string }).uid;\n }\n }\n\n if (!userId) {\n throw new Error(`User not found with email: ${email}`);\n }\n\n const resetUrl = `${cleanBaseUrl}/api/admin/users/${userId}/reset-password`;\n const resetRes = await fetch(resetUrl, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n },\n body: JSON.stringify({ password: finalPass })\n });\n\n if (!resetRes.ok) {\n const errText = await resetRes.text();\n throw new Error(`Password reset endpoint failed: ${errText || resetRes.statusText}`);\n }\n\n console.log(\"API reset successful.\");\n console.log(chalk.bold(\" 🔑 Rebase Auth — Reset Password (via API)\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Email:\")} ${email}`);\n console.log(` ${chalk.gray(\"Password:\")} ${finalPass}`);\n console.log(\"\");\n return;\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n console.warn(chalk.yellow(\"API reset failed, falling back to direct database update...\"));\n console.warn(chalk.gray(` Details: ${errMsg}`));\n }\n }\n\n // 2. Direct-DB Fallback\n const backendDir = requireBackendDir(projectRoot);\n const tsxBin = resolveTsx(projectRoot);\n\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n\n try {\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n env.REBASE_RESET_EMAIL = email;\n env.REBASE_RESET_PASSWORD = newPassword || \"NewPassword123!\";\n env.REBASE_ENV_FILE_PATH = envFile || path.join(projectRoot, \".env\");\n\n const scriptContent = `\nimport { createPostgresDatabaseConnection } from \"@rebasepro/server-postgres\";\nimport { hashPassword } from \"@rebasepro/server\";\nimport { eq } from \"drizzle-orm\";\nimport * as dotenv from \"dotenv\";\nimport path from \"path\";\nimport fs from \"fs\";\n\ndotenv.config({ path: process.env.REBASE_ENV_FILE_PATH });\n\nconst email = process.env.REBASE_RESET_EMAIL!;\nconst newPassword = process.env.REBASE_RESET_PASSWORD!;\n\nasync function resetPassword() {\n const { db } = createPostgresDatabaseConnection(process.env.DATABASE_URL!);\n const hash = await hashPassword(newPassword);\n\n let usersTable;\n try {\n const schemaPath = path.resolve(\"./src/schema.generated.ts\");\n if (fs.existsSync(schemaPath)) {\n const schema = await import(\"file://\" + schemaPath);\n usersTable = schema.users || schema.tables?.users;\n }\n } catch (e) {\n // ignore and fallback\n }\n\n if (!usersTable) {\n const pgServer = await import(\"@rebasepro/server-postgres\");\n usersTable = pgServer.users;\n }\n\n const passwordHashKey = (usersTable.passwordHash || \"passwordHash\" in usersTable) ? \"passwordHash\" : \"password_hash\";\n\n const result = await db.update(usersTable)\n .set({ [passwordHashKey]: hash })\n .where(eq(usersTable.email, email))\n .returning({\n id: usersTable.id,\n email: usersTable.email\n });\n\n if (result.length > 0) {\n console.log(\"✅ Password reset for: \" + result[0].email);\n ${!newPassword ? 'console.log(\" New password: \" + newPassword);' : \"\"}\n } else {\n console.log(\"✗ User not found: \" + email);\n }\n process.exit(0);\n}\n\nresetPassword().catch(console.error);\n`;\n\n const tmpScriptPath = path.join(backendDir, \".tmp-reset-password.ts\");\n fs.writeFileSync(tmpScriptPath, scriptContent, \"utf-8\");\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 Rebase Auth — Reset Password (Direct DB Fallback)\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Email:\")} ${email}`);\n if (newPassword) {\n console.log(` ${chalk.gray(\"Password:\")} ${\"*\".repeat(newPassword.length)}`);\n }\n console.log(\"\");\n\n const child = spawn(tsxBin, [tmpScriptPath], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n\n return new Promise((resolve) => {\n child.on(\"close\", (code) => {\n // Clean up temp script\n try { fs.unlinkSync(tmpScriptPath); } catch { /* ignore */ }\n if (code !== 0) {\n process.exit(code ?? 1);\n }\n resolve();\n });\n });\n } catch (err) {\n console.error(chalk.red(\"✗ Direct database update failed.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\nfunction printAuthHelp() {\n console.log(`\n${chalk.bold(\"rebase auth\")} — Authentication management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase auth ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"reset-password\")} Reset a user's password\n\n${chalk.green.bold(\"reset-password Options\")}\n ${chalk.blue(\"--email, -e\")} User's email address\n ${chalk.blue(\"--password, -p\")} New password (default: NewPassword123!)\n\n${chalk.green.bold(\"Examples\")}\n rebase auth reset-password user@example.com\n rebase auth reset-password --email user@example.com --password MyNewPass!\n`);\n}\n","/**\n * CLI command: rebase doctor\n *\n * Detects three-way schema drift between collection definitions,\n * the generated Drizzle schema, and the live PostgreSQL database.\n */\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile\n} from \"../utils/project\";\n\nexport async function doctorCommand(rawArgs: string[]): Promise<void> {\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));\n process.exit(1);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n try {\n const isTs = pluginCli.endsWith(\".ts\");\n if (isTs) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n console.error(chalk.red(\"✗ Could not find tsx binary.\"));\n process.exit(1);\n }\n await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n } else {\n await execa(\"node\", [pluginCli, ...rawArgs.slice(2)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n } catch {\n // If the process exits with an error code, execa will throw,\n // but inherit stdio means the user already saw the output.\n process.exit(1);\n }\n}\n","import chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport inquirer from \"inquirer\";\nimport { createRequire } from \"module\";\n\nconst require = createRequire(import.meta.url);\n\n/** Supported agent environments and their target directories. */\nconst AGENTS = {\n cursor: {\n label: \"Cursor\",\n detectDir: \".cursor\",\n targetDir: \".cursor/rules\",\n /** Cursor uses .mdc files (Markdown with Context). */\n transformFile: (skillName: string, content: string) => ({\n fileName: `${skillName}.mdc`,\n content\n })\n },\n claude: {\n label: \"Claude Code\",\n detectDir: \".claude\",\n targetDir: \".claude/skills\",\n /** Claude Code uses the standard SKILL.md format in subdirectories. */\n transformFile: (skillName: string, content: string) => ({\n fileName: path.join(skillName, \"SKILL.md\"),\n content\n })\n },\n windsurf: {\n label: \"Windsurf\",\n detectDir: \".windsurf\",\n targetDir: \".windsurf/rules\",\n /** Windsurf uses plain .md files. */\n transformFile: (skillName: string, content: string) => ({\n fileName: `${skillName}.md`,\n content\n })\n },\n gemini: {\n label: \"Gemini CLI / Antigravity\",\n detectDir: \".agents\",\n targetDir: \".agents/skills\",\n /** Gemini uses the standard SKILL.md format in subdirectories. */\n transformFile: (skillName: string, content: string) => ({\n fileName: path.join(skillName, \"SKILL.md\"),\n content\n })\n }\n} as const;\n\ntype AgentKey = keyof typeof AGENTS;\n\n/**\n * Resolve the path to the skills directory from @rebasepro/agent-skills.\n * Works in both workspace (symlink) and published (real files) layouts.\n */\nfunction getSkillsSourceDir(): string {\n const pkgJsonPath = require.resolve(\"@rebasepro/agent-skills/package.json\");\n const pkgRoot = path.dirname(pkgJsonPath);\n const skillsDir = path.join(pkgRoot, \"skills\");\n\n if (!fs.existsSync(skillsDir)) {\n throw new Error(\n `Skills directory not found at ${skillsDir}. ` +\n `Make sure @rebasepro/agent-skills is installed.`\n );\n }\n\n return skillsDir;\n}\n\n/** Read all skill directories and return their names + content. */\nfunction loadSkills(skillsDir: string): Array<{ name: string; content: string }> {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n const skills: Array<{ name: string; content: string }> = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const skillMdPath = path.join(skillsDir, entry.name, \"SKILL.md\");\n if (!fs.existsSync(skillMdPath)) continue;\n skills.push({\n name: entry.name,\n content: fs.readFileSync(skillMdPath, \"utf-8\")\n });\n }\n\n return skills;\n}\n\n/** Detect which agent environments already exist in the project. */\nfunction detectAgents(projectDir: string): AgentKey[] {\n const detected: AgentKey[] = [];\n for (const [key, agent] of Object.entries(AGENTS)) {\n if (fs.existsSync(path.join(projectDir, agent.detectDir))) {\n detected.push(key as AgentKey);\n }\n }\n return detected;\n}\n\n/** Install skills for a specific agent into the project directory. */\nfunction installForAgent(\n agentKey: AgentKey,\n skills: Array<{ name: string; content: string }>,\n projectDir: string\n): number {\n const agent = AGENTS[agentKey];\n const targetBase = path.join(projectDir, agent.targetDir);\n\n // Ensure the target directory exists\n fs.mkdirSync(targetBase, { recursive: true });\n\n let count = 0;\n for (const skill of skills) {\n const { fileName, content } = agent.transformFile(skill.name, skill.content);\n const targetPath = path.join(targetBase, fileName);\n\n // Ensure parent directory exists (for subdirectory-based formats)\n fs.mkdirSync(path.dirname(targetPath), { recursive: true });\n fs.writeFileSync(targetPath, content, \"utf-8\");\n count++;\n }\n\n return count;\n}\n\nexport async function skillsCommand(subcommand: string | undefined, rawArgs: string[]) {\n switch (subcommand) {\n case \"install\":\n await skillsInstall(rawArgs);\n break;\n case \"--help\":\n case undefined:\n printSkillsHelp();\n break;\n default:\n console.error(chalk.red(`Unknown skills subcommand: ${subcommand}`));\n console.log(\"\");\n printSkillsHelp();\n process.exit(1);\n }\n}\n\n/**\n * Agents named explicitly on the command line, e.g. `--agent claude --agent cursor`\n * (also accepts a comma-separated list). Returns null when none were given.\n */\nfunction parseAgentFlags(rawArgs: string[]): AgentKey[] | null {\n const requested: string[] = [];\n for (let i = 0; i < rawArgs.length; i++) {\n if (rawArgs[i] !== \"--agent\" && rawArgs[i] !== \"-a\") continue;\n const value = rawArgs[i + 1];\n if (value && !value.startsWith(\"-\")) {\n requested.push(...value.split(\",\").map(v => v.trim()).filter(Boolean));\n }\n }\n if (requested.length === 0) return null;\n\n const valid = Object.keys(AGENTS);\n const unknown = requested.filter(a => !valid.includes(a));\n if (unknown.length > 0) {\n console.error(chalk.red(`Unknown agent(s): ${unknown.join(\", \")}. Available: ${valid.join(\", \")}`));\n process.exit(1);\n }\n return requested as AgentKey[];\n}\n\nasync function skillsInstall(rawArgs: string[] = []) {\n const projectDir = process.cwd();\n\n // 1. Load skills from @rebasepro/agent-skills\n let skillsDir: string;\n try {\n skillsDir = getSkillsSourceDir();\n } catch (err) {\n console.error(`${chalk.red.bold(\"ERROR\")} ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n\n const skills = loadSkills(skillsDir);\n if (skills.length === 0) {\n console.error(`${chalk.red.bold(\"ERROR\")} No skills found in ${skillsDir}`);\n process.exit(1);\n }\n\n // 2. Explicit --agent wins; otherwise detect existing agent environments\n let agents = parseAgentFlags(rawArgs) ?? detectAgents(projectDir);\n\n // 3. If none detected, ask the user\n if (agents.length === 0) {\n // A scaffolded project ships `.cursorrules` / `CLAUDE.md` files but none\n // of the *directories* detectAgents looks for, so a fresh project always\n // lands here. On a non-TTY that used to abort with a raw ExitPromptError.\n if (!process.stdin.isTTY) {\n console.error(chalk.red(\"Cannot prompt: this is a non-interactive terminal (no TTY).\"));\n console.error(chalk.yellow(` Name the agents explicitly, e.g. rebase skills install --agent ${Object.keys(AGENTS)[0]}`));\n console.error(chalk.gray(` Available: ${Object.keys(AGENTS).join(\", \")}`));\n process.exit(1);\n }\n\n const choices = Object.entries(AGENTS).map(([key, agent]) => ({\n name: agent.label,\n value: key,\n checked: false\n }));\n\n const { selectedAgents } = await inquirer.prompt([{\n type: \"checkbox\",\n name: \"selectedAgents\",\n message: \"No AI agent configuration detected. Which agents do you use?\",\n choices,\n validate: (input: string[]) => {\n if (input.length === 0) return \"Please select at least one agent.\";\n return true;\n }\n }]);\n\n agents = selectedAgents as AgentKey[];\n }\n\n // 4. Install skills for each agent\n console.log(\"\");\n console.log(chalk.gray(` Found ${chalk.white(skills.length)} Rebase skills`));\n console.log(\"\");\n\n for (const agentKey of agents) {\n const agent = AGENTS[agentKey];\n const count = installForAgent(agentKey, skills, projectDir);\n console.log(` ${chalk.green(\"✓\")} ${chalk.bold(agent.label)} — ${count} skills installed to ${chalk.gray(agent.targetDir)}`);\n }\n\n console.log(\"\");\n console.log(chalk.gray(\" Skills are project-local. Commit them to share with your team.\"));\n console.log(chalk.gray(\" Re-run this command anytime to update to the latest skills.\"));\n console.log(\"\");\n}\n\nfunction printSkillsHelp() {\n console.log(`\n${chalk.bold(\"rebase skills\")} — Manage AI agent skills\n\n${chalk.green.bold(\"Usage\")}\n rebase skills ${chalk.blue(\"<subcommand>\")}\n\n${chalk.green.bold(\"Subcommands\")}\n ${chalk.blue.bold(\"install\")} Install Rebase agent skills for your AI coding assistant\n Supports: Cursor, Claude Code, Windsurf, Gemini CLI, Antigravity\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--agent, -a\")} Agent(s) to install for, skipping detection and the prompt.\n Repeat the flag or pass a comma-separated list.\n Available: ${Object.keys(AGENTS).join(\", \")}\n\n${chalk.green.bold(\"Examples\")}\n ${chalk.cyan(\"rebase skills install\")}\n ${chalk.cyan(\"rebase skills install --agent claude\")}\n ${chalk.cyan(\"rebase skills install --agent claude,cursor\")}\n`);\n}\n","/**\n * CLI command: rebase api-keys <action>\n *\n * Subcommands:\n * list — List all API keys (masked)\n * create — Create a new API key\n * revoke — Revoke an existing API key\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireProjectRoot,\n findEnvFile\n} from \"../utils/project\";\nimport fs from \"fs\";\nimport path from \"path\";\n\n/* ═══════════════════════════════════════════════════════════════\n Env helper — reads SERVICE_KEY and PORT from .env\n ═══════════════════════════════════════════════════════════════ */\n\nfunction loadEnv(projectRoot: string): Record<string, string> {\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = {};\n if (envFile && fs.existsSync(envFile)) {\n const content = fs.readFileSync(envFile, \"utf-8\");\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const idx = trimmed.indexOf(\"=\");\n if (idx > 0) {\n const key = trimmed.slice(0, idx).trim();\n let value = trimmed.slice(idx + 1).trim();\n // Strip surrounding quotes\n if ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.slice(1, -1);\n }\n env[key] = value;\n }\n }\n }\n return env;\n}\n\nfunction resolveBaseUrl(env: Record<string, string>, projectRoot?: string): string {\n // An explicit override always wins.\n if (env.REBASE_BASE_URL) return env.REBASE_BASE_URL;\n\n // `rebase dev` runs on a derived per-project port, not the .env PORT, and\n // records the URL it actually bound. Without this, these commands default to\n // :3001 and report \"Is the Rebase server running?\" while it is running.\n if (projectRoot) {\n try {\n const urlFile = path.join(projectRoot, \".rebase-dev-url\");\n if (fs.existsSync(urlFile)) {\n const devUrl = fs.readFileSync(urlFile, \"utf-8\").trim();\n if (devUrl) return devUrl;\n }\n } catch { /* fall through to the configured port */ }\n }\n\n const port = env.PORT || env.REBASE_PORT || \"3001\";\n return `http://localhost:${port}`;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Entry\n ═══════════════════════════════════════════════════════════════ */\n\nexport async function apiKeysCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\") {\n printApiKeysHelp();\n return;\n }\n\n switch (subcommand) {\n case \"list\":\n await listKeys(rawArgs);\n break;\n case \"create\":\n await createKey(rawArgs);\n break;\n case \"revoke\":\n await revokeKey(rawArgs);\n break;\n default:\n console.error(chalk.red(`Unknown api-keys command: ${subcommand}`));\n console.log(\"\");\n printApiKeysHelp();\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n list\n ═══════════════════════════════════════════════════════════════ */\n\nasync function listKeys(_rawArgs: string[]): Promise<void> {\n const projectRoot = requireProjectRoot();\n const env = loadEnv(projectRoot);\n const baseUrl = resolveBaseUrl(env, projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n\n if (!serviceKey) {\n console.error(chalk.red(\"✗ SERVICE_KEY not found in .env — required for admin operations.\"));\n process.exit(1);\n }\n\n try {\n const res = await fetch(`${baseUrl}/api/admin/api-keys`, {\n headers: { Authorization: `Bearer ${serviceKey}` }\n });\n if (!res.ok) {\n const body = await res.text();\n console.error(chalk.red(`✗ Failed to list API keys: ${res.status} ${body}`));\n process.exit(1);\n }\n\n const { keys } = await res.json() as { keys: Array<{\n id: string; name: string; key_prefix: string;\n permissions: Array<{ collection: string; operations: string[] }>;\n rate_limit: number | null; revoked_at: string | null;\n expires_at: string | null; last_used_at: string | null;\n created_at: string;\n }>};\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 API Keys\"));\n console.log(\"\");\n\n if (keys.length === 0) {\n console.log(chalk.gray(\" No API keys found.\"));\n console.log(\"\");\n return;\n }\n\n for (const key of keys) {\n const status = key.revoked_at ? chalk.red(\"revoked\")\n : (key.expires_at && new Date(key.expires_at) < new Date()) ? chalk.yellow(\"expired\")\n : chalk.green(\"active\");\n\n const perms = key.permissions.map(p =>\n `${p.collection}(${p.operations.join(\",\")})`\n ).join(\", \");\n\n console.log(` ${chalk.bold(key.name)} ${chalk.gray(`[${key.key_prefix}•••]`)} ${status}`);\n console.log(` ${chalk.gray(\"ID:\")} ${key.id}`);\n console.log(` ${chalk.gray(\"Permissions:\")} ${perms || \"none\"}`);\n console.log(` ${chalk.gray(\"Created:\")} ${new Date(key.created_at).toLocaleDateString()}`);\n if (key.last_used_at) {\n console.log(` ${chalk.gray(\"Last used:\")} ${new Date(key.last_used_at).toLocaleDateString()}`);\n }\n console.log(\"\");\n }\n } catch (e: unknown) {\n console.error(chalk.red(`✗ ${e instanceof Error ? e.message : String(e)}`));\n console.error(chalk.gray(\" Is the Rebase server running?\"));\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n create\n ═══════════════════════════════════════════════════════════════ */\n\nasync function createKey(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--name\": String,\n \"--permissions\": String,\n \"--full-access\": Boolean,\n \"--admin\": Boolean,\n \"--rate-limit\": Number,\n \"--expires\": String,\n \"-n\": \"--name\"\n },\n {\n argv: rawArgs.slice(4), // skip \"node rebase api-keys create\"\n permissive: true\n }\n );\n\n const name = args[\"--name\"] || args._[0];\n const permissionsRaw = args[\"--permissions\"];\n\n if (!name) {\n console.error(chalk.red(\"✗ Name is required.\"));\n console.log(\"\");\n console.log(chalk.gray(' Usage: rebase api-keys create --name \"My Key\" --permissions \\'[{\"collection\":\"*\",\"operations\":[\"read\"]}]\\''));\n process.exit(1);\n }\n\n let permissions: Array<{ collection: string; operations: string[] }>;\n if (permissionsRaw) {\n try {\n permissions = JSON.parse(permissionsRaw);\n } catch {\n console.error(chalk.red(\"✗ Invalid --permissions JSON.\"));\n console.log(chalk.gray(' Example: \\'[{\"collection\":\"*\",\"operations\":[\"read\",\"write\"]}]\\''));\n process.exit(1);\n return; // unreachable but satisfies TS\n }\n } else if (args[\"--full-access\"]) {\n permissions = [{ collection: \"*\", operations: [\"read\", \"write\", \"delete\"] }];\n } else {\n // No silent full-access default: a \"scoped keys\" feature should not\n // hand out read/write/delete on every collection when the flag is\n // simply forgotten. Full access must be asked for by name.\n console.error(chalk.red(\"✗ Specify what the key may access: --permissions '<json>' or --full-access.\"));\n console.log(\"\");\n console.log(chalk.gray(' Scoped: rebase api-keys create -n \"Analytics\" --permissions \\'[{\"collection\":\"events\",\"operations\":[\"read\"]}]\\''));\n console.log(chalk.gray(' Functions: add {\"collection\":\"functions/<name>\",\"operations\":[\"write\"]} to invoke a custom function'));\n console.log(chalk.gray(' Storage: add {\"collection\":\"storage\",\"operations\":[\"read\",\"write\"]} for file storage'));\n console.log(chalk.gray(' Full access: rebase api-keys create -n \"CI\" --full-access'));\n process.exit(1);\n return; // unreachable but satisfies TS\n }\n\n let expires_at: string | null = null;\n const expiresFlag = args[\"--expires\"];\n if (expiresFlag) {\n const days: Record<string, number> = { \"7d\": 7, \"30d\": 30, \"90d\": 90, \"1y\": 365 };\n if (days[expiresFlag]) {\n expires_at = new Date(Date.now() + days[expiresFlag] * 86400000).toISOString();\n } else {\n const parsed = new Date(expiresFlag);\n if (isNaN(parsed.getTime())) {\n console.error(chalk.red(\"✗ Invalid --expires value. Use 7d, 30d, 90d, 1y, or an ISO date.\"));\n process.exit(1);\n }\n expires_at = parsed.toISOString();\n }\n }\n\n const projectRoot = requireProjectRoot();\n const env = loadEnv(projectRoot);\n const baseUrl = resolveBaseUrl(env, projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n\n if (!serviceKey) {\n console.error(chalk.red(\"✗ SERVICE_KEY not found in .env — required for admin operations.\"));\n process.exit(1);\n }\n\n try {\n const body: Record<string, unknown> = {\n name,\n permissions,\n admin: args[\"--admin\"] ?? false,\n rate_limit: args[\"--rate-limit\"] ?? null,\n expires_at\n };\n\n const res = await fetch(`${baseUrl}/api/admin/api-keys`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${serviceKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(body)\n });\n\n if (!res.ok) {\n const errBody = await res.text();\n console.error(chalk.red(`✗ Failed to create API key: ${res.status} ${errBody}`));\n process.exit(1);\n }\n\n const { key } = await res.json() as { key: { name: string; key: string; key_prefix: string; id: string } };\n\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key created successfully\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Name:\")} ${key.name}`);\n console.log(` ${chalk.gray(\"ID:\")} ${key.id}`);\n console.log(` ${chalk.gray(\"Prefix:\")} ${key.key_prefix}`);\n console.log(\"\");\n console.log(chalk.bold.yellow(\" ⚠ Copy your key now — it won't be shown again:\"));\n console.log(\"\");\n console.log(` ${chalk.cyan(key.key)}`);\n console.log(\"\");\n } catch (e: unknown) {\n console.error(chalk.red(`✗ ${e instanceof Error ? e.message : String(e)}`));\n console.error(chalk.gray(\" Is the Rebase server running?\"));\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n revoke\n ═══════════════════════════════════════════════════════════════ */\n\nasync function revokeKey(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--id\": String\n },\n {\n argv: rawArgs.slice(4), // skip \"node rebase api-keys revoke\"\n permissive: true\n }\n );\n\n const id = args[\"--id\"] || args._[0];\n\n if (!id) {\n console.error(chalk.red(\"✗ Key ID is required.\"));\n console.log(\"\");\n console.log(chalk.gray(\" Usage: rebase api-keys revoke <key-id>\"));\n process.exit(1);\n }\n\n const projectRoot = requireProjectRoot();\n const env = loadEnv(projectRoot);\n const baseUrl = resolveBaseUrl(env, projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n\n if (!serviceKey) {\n console.error(chalk.red(\"✗ SERVICE_KEY not found in .env — required for admin operations.\"));\n process.exit(1);\n }\n\n try {\n const res = await fetch(`${baseUrl}/api/admin/api-keys/${encodeURIComponent(id)}`, {\n method: \"DELETE\",\n headers: { Authorization: `Bearer ${serviceKey}` }\n });\n\n if (!res.ok) {\n const errBody = await res.text();\n console.error(chalk.red(`✗ Failed to revoke API key: ${res.status} ${errBody}`));\n process.exit(1);\n }\n\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key revoked successfully\"));\n console.log(` ${chalk.gray(\"ID:\")} ${id}`);\n console.log(\"\");\n } catch (e: unknown) {\n console.error(chalk.red(`✗ ${e instanceof Error ? e.message : String(e)}`));\n console.error(chalk.gray(\" Is the Rebase server running?\"));\n process.exit(1);\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Help\n ═══════════════════════════════════════════════════════════════ */\n\nfunction printApiKeysHelp() {\n console.log(`\n${chalk.bold(\"rebase api-keys\")} — Manage Service API Keys\n\n${chalk.green.bold(\"Usage\")}\n rebase api-keys ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List all API keys\n ${chalk.blue.bold(\"create\")} Create a new API key\n ${chalk.blue.bold(\"revoke\")} Revoke an API key\n\n${chalk.green.bold(\"create Options\")}\n ${chalk.blue(\"--name, -n\")} Key name ${chalk.gray(\"(required)\")}\n ${chalk.blue(\"--permissions\")} JSON array of permissions ${chalk.gray(\"(required unless --full-access)\")}\n ${chalk.gray('Collections by slug; custom functions as \"functions\" or \"functions/<name>\"')}\n ${chalk.blue(\"--full-access\")} Grant read/write/delete on every collection and function\n ${chalk.blue(\"--admin\")} Grant admin role (admin routes + RLS admin policies)\n ${chalk.blue(\"--rate-limit\")} Requests per 15-min window ${chalk.gray(\"(default: 1000)\")}\n ${chalk.blue(\"--expires\")} Expiration: 7d, 30d, 90d, 1y, or ISO date\n\n${chalk.green.bold(\"revoke Options\")}\n ${chalk.blue(\"--id\")} API key ID to revoke ${chalk.gray(\"(or positional arg)\")}\n\n${chalk.green.bold(\"Examples\")}\n rebase api-keys list\n rebase api-keys create --name \"Analytics\" --permissions '[{\"collection\":\"events\",\"operations\":[\"read\"]}]'\n rebase api-keys create -n \"Full Access\" --full-access --expires 90d\n rebase api-keys revoke abc123-def456\n`);\n}\n","/**\n * `rebase cloud` auth subcommands: login, logout, whoami.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n resolveCloudUrl,\n createCloudClient,\n requireClient,\n setCurrentContext,\n setContextOrg,\n getContextOrg,\n readLink,\n success,\n fail,\n keyValues,\n reportError\n} from \"./context\";\n\nexport async function loginCommand(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--email\": String,\n\"--password\": String,\n\"-e\": \"--email\",\n\"-p\": \"--password\" },\n { argv: rawArgs.slice(3),\npermissive: true }\n );\n const url = resolveCloudUrl(rawArgs);\n\n console.log(\"\");\n console.log(` Signing in to ${chalk.cyan(url)}`);\n console.log(\"\");\n\n // Collect any missing credentials interactively.\n const prompts: Array<Record<string, unknown>> = [];\n if (!args[\"--email\"]) {\n prompts.push({ type: \"input\",\nname: \"email\",\nmessage: \"Email:\" });\n }\n if (!args[\"--password\"]) {\n prompts.push({ type: \"password\",\nname: \"password\",\nmessage: \"Password:\",\nmask: \"•\" });\n }\n const answers = prompts.length\n ? await inquirer.prompt(prompts as unknown as Parameters<typeof inquirer.prompt>[0])\n : {};\n\n const email = (args[\"--email\"] || (answers as { email?: string }).email || \"\").trim();\n const password = args[\"--password\"] || (answers as { password?: string }).password || \"\";\n\n if (!email || !password) {\n fail(\"Email and password are required.\");\n }\n\n const client = createCloudClient(url);\n try {\n const { user } = await client.auth.signInWithEmail(email, password);\n setCurrentContext(url);\n\n // Convenience: if the account belongs to exactly one org, make it active.\n try {\n const orgs = await client.data.collection(\"organizations\").find({ limit: 2 });\n if (orgs.data.length === 1 && !getContextOrg(url)) {\n setContextOrg(url, String(orgs.data[0].id));\n }\n } catch {\n // non-fatal — org selection is optional\n }\n\n success(`Logged in as ${chalk.bold(user.email ?? email)}`);\n keyValues([\n [\"Host\", url],\n [\"User\", user.email ?? undefined],\n [\"Active org\", getContextOrg(url)]\n ]);\n console.log(\"\");\n } catch (e) {\n // Auth failures are the common case — give a clean message, not a stack.\n const err = e as { status?: number; message?: string };\n if (err?.status === 401) {\n fail(\"Invalid email or password.\");\n }\n reportError(e, \"Login failed\");\n }\n}\n\nexport async function logoutCommand(rawArgs: string[]): Promise<void> {\n const url = resolveCloudUrl(rawArgs);\n const client = createCloudClient(url);\n if (!client.auth.getSession()) {\n console.log(\"\");\n console.log(chalk.gray(` Not logged in to ${url}.`));\n console.log(\"\");\n return;\n }\n try {\n await client.auth.signOut();\n } catch {\n // signOut clears local state even if the network call fails\n }\n success(`Logged out of ${url}`);\n}\n\nexport async function whoamiCommand(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n try {\n const user = await client.auth.getUser();\n if (!user) fail(\"Session is no longer valid.\", \"Run `rebase cloud login` again.\");\n const link = readLink();\n console.log(\"\");\n console.log(chalk.bold(\" 🔐 Rebase Cloud session\"));\n console.log(\"\");\n keyValues([\n [\"Host\", url],\n [\"User\", user.email ?? undefined],\n [\"User ID\", user.uid],\n [\"Roles\", user.roles?.length ? user.roles.join(\", \") : undefined],\n [\"Active org\", getContextOrg(url)],\n [\"Linked project\", link ? `${link.projectName ?? \"\"} (${link.projectId})`.trim() : undefined]\n ]);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to fetch session\");\n }\n}\n","/**\n * `rebase cloud` context subcommands: link, unlink, use, open.\n *\n * `link` associates the current directory with a cloud project by writing\n * `.rebase/cloud.json`; deploy/logs/status then operate on it with no flags.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n resolveProjectRef,\n resolveCloudUrl,\n writeLink,\n removeLink,\n readLink,\n projectLinkPath,\n setContextOrg,\n getContextOrg,\n openUrl,\n success,\n fail,\n reportError\n} from \"./context\";\n\ninterface ProjectRow {\n id: string | number;\n name?: string;\n subdomain?: string;\n organization?: string | number;\n status?: string;\n}\n\nexport async function linkCommand(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(3),\npermissive: true });\n const { client, url } = await requireClient(rawArgs);\n\n try {\n let project: ProjectRow | undefined;\n\n if (args[\"--project\"]) {\n const projectId = await resolveProjectRef(args[\"--project\"], client);\n project = (await client.data.collection(\"projects\").findById(projectId)) as unknown as ProjectRow | undefined;\n if (!project) fail(`Project ${args[\"--project\"]} not found.`);\n } else {\n const org = getContextOrg(url);\n const projects = (await client.data.collection(\"projects\").find({\n where: org ? { organization: [\"==\", org] } : undefined,\n limit: 100\n })).data as unknown as ProjectRow[];\n\n if (projects.length === 0) {\n fail(\n \"No projects found for your account.\",\n `Create one with ${chalk.bold(\"rebase cloud projects create\")}.`\n );\n }\n\n const { picked } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"picked\",\n message: \"Select a project to link:\",\n choices: projects.map((p) => ({\n name: `${p.name ?? \"(unnamed)\"} ${chalk.gray(String(p.subdomain ?? \"\"))}`,\n value: p\n }))\n }\n ] as unknown as Parameters<typeof inquirer.prompt>[0]);\n project = picked as ProjectRow;\n }\n\n if (!project) fail(\"No project selected.\");\n\n writeLink({\n url,\n projectId: String(project.id),\n slug: project.subdomain,\n projectName: project.name,\n orgId: project.organization !== undefined ? String(project.organization) : undefined\n });\n\n success(`Linked to ${chalk.bold(project.name ?? project.subdomain ?? \"\")}`);\n console.log(chalk.gray(` Wrote ${projectLinkPath()}`));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to link project\");\n }\n}\n\nexport function unlinkCommand(): void {\n const link = readLink();\n if (!link) {\n console.log(\"\");\n console.log(chalk.gray(\" This directory is not linked to a cloud project.\"));\n console.log(\"\");\n return;\n }\n removeLink();\n success(\"Unlinked from cloud project\");\n}\n\nexport async function selectOrgCommand(rawArgs: string[]): Promise<void> {\n // positionals after \"cloud\" are [use, <org>]; take the token after \"use\".\n const target = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[1];\n const { client, url } = await requireClient(rawArgs);\n\n try {\n const orgs = (await client.data.collection(\"organizations\").find({ limit: 100 })).data as unknown as Array<{\n id: string | number;\n name?: string;\n slug?: string;\n }>;\n\n if (orgs.length === 0) fail(\"You are not a member of any organization.\");\n\n let chosen = target\n ? orgs.find((o) => String(o.id) === target || o.slug === target)\n : undefined;\n\n if (!chosen && !target) {\n const { picked } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"picked\",\n message: \"Select the active organization:\",\n choices: orgs.map((o) => ({\n name: `${o.name ?? \"(unnamed)\"} ${chalk.gray(`${o.slug ?? \"\"} · ${o.id}`)}`,\n value: o\n }))\n }\n ] as unknown as Parameters<typeof inquirer.prompt>[0]);\n chosen = picked;\n }\n\n if (!chosen) fail(`Organization \"${target}\" not found.`);\n\n setContextOrg(url, String(chosen.id));\n success(`Active organization set to ${chalk.bold(chosen.name ?? chosen.id)}`);\n } catch (e) {\n reportError(e, \"Failed to set organization\");\n }\n}\n\n/** Open the Rebase Cloud dashboard (or the linked project) in a browser. */\nexport function openCommand(rawArgs: string[]): void {\n const url = resolveCloudUrl(rawArgs);\n const link = readLink();\n const target = link ? `${url}/projects/${link.projectId}` : url;\n openUrl(target);\n}\n","/**\n * `rebase cloud projects` — list / create / info / delete.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n resolveProjectRef,\n getContextOrg,\n readLink,\n writeLink,\n colorStatus,\n keyValues,\n fetchTenantBaseDomain,\n projectHost,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\ninterface ProjectRow {\n id: string | number;\n name?: string;\n subdomain?: string;\n /**\n * Where the project is actually served. Computed by the control plane from\n * the project's cluster, which the CLI cannot read itself (admin-only RLS).\n * Absent on control planes older than that hook — `projectHost` falls back.\n */\n host?: string;\n customDomain?: string;\n gitRepoUrl?: string;\n gitBranch?: string;\n provider?: string;\n region?: string;\n status?: string;\n organization?: string | number;\n createdById?: string;\n}\n\n/* ─── list ─────────────────────────────────────────────────────── */\n\nexport async function listProjects(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n const org = getContextOrg(url);\n try {\n const [projects, baseDomain] = await Promise.all([\n client.data.collection(\"projects\").find({\n where: org ? { organization: [\"==\", org] } : undefined,\n orderBy: [\"name\", \"asc\"],\n limit: 100\n }).then((res) => res.data as unknown as ProjectRow[]),\n fetchTenantBaseDomain(client, url)\n ]);\n\n console.log(\"\");\n console.log(chalk.bold(\" 📦 Projects\") + (org ? chalk.gray(` (org ${org})`) : \"\"));\n console.log(\"\");\n\n if (projects.length === 0) {\n console.log(chalk.gray(\" No projects yet. Create one with `rebase cloud projects create`.\"));\n console.log(\"\");\n return;\n }\n\n const linkedId = readLink()?.projectId;\n for (const p of projects) {\n const marker = String(p.id) === linkedId ? chalk.green(\" ●\") : \" \";\n console.log(`${marker}${chalk.bold(p.name ?? \"(unnamed)\")} ${chalk.gray(`[${p.subdomain ?? p.id}]`)} ${colorStatus(p.status)}`);\n console.log(` ${chalk.gray(projectHost(p, baseDomain) ?? \"—\")}${p.provider ? chalk.gray(` · ${p.provider}`) : \"\"}`);\n }\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list projects\");\n }\n}\n\n/* ─── create ───────────────────────────────────────────────────── */\n\n/** Default region + VM size per provider (both are required on create). */\nfunction providerDefaults(provider: string): { region: string; vmSize: string } {\n switch (provider) {\n case \"gcp\":\n return { region: \"europe-west1\",\nvmSize: \"e2-small\" };\n case \"aws\":\n return { region: \"us-east-1\",\nvmSize: \"t3.small\" };\n default:\n return { region: \"nbg1\",\nvmSize: \"cx21\" };\n }\n}\n\nexport async function createProject(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--name\": String,\n \"--subdomain\": String,\n \"--repo\": String,\n \"--branch\": String,\n \"--provider\": String,\n \"--region\": String,\n \"--vm-size\": String,\n \"--org\": String,\n \"--link\": Boolean,\n \"-n\": \"--name\"\n },\n { argv: rawArgs.slice(4),\npermissive: true }\n );\n\n const { client, url } = await requireClient(rawArgs);\n const org = args[\"--org\"] || getContextOrg(url);\n if (!org) {\n fail(\n \"No organization selected.\",\n `Pass ${chalk.bold(\"--org <id>\")} or run ${chalk.bold(\"rebase cloud use\")}.`\n );\n }\n\n // Prompt only for the essentials, and only when attached to a terminal —\n // a headless `projects create --name X --subdomain Y` must never block.\n // repo/branch/provider are optional and default sensibly.\n const prompts: Array<Record<string, unknown>> = [];\n if (!args[\"--name\"]) prompts.push({ type: \"input\",\nname: \"name\",\nmessage: \"Project name:\" });\n if (!args[\"--subdomain\"]) prompts.push({ type: \"input\",\nname: \"subdomain\",\nmessage: \"Subdomain:\" });\n const answers = prompts.length && process.stdin.isTTY\n ? await inquirer.prompt(prompts as unknown as Parameters<typeof inquirer.prompt>[0])\n : {};\n const a = answers as Record<string, string>;\n\n const name = (args[\"--name\"] || a.name || \"\").trim();\n const subdomain = (args[\"--subdomain\"] || a.subdomain || \"\").trim().toLowerCase();\n const gitRepoUrl = (args[\"--repo\"] || a.repo || \"\").trim();\n const gitBranch = (args[\"--branch\"] || a.branch || \"main\").trim();\n const provider = (args[\"--provider\"] || a.provider || \"hetzner\").trim();\n // region + vmSize are required by the control plane; default sensibly per\n // provider so a headless `projects create` needs only name + subdomain.\n const defaults = providerDefaults(provider);\n const region = (args[\"--region\"] || defaults.region).trim();\n const vmSize = (args[\"--vm-size\"] || defaults.vmSize).trim();\n\n if (!name || !subdomain) {\n fail(\"Name and subdomain are required.\");\n }\n\n // Validate subdomain availability up front for a clean error.\n try {\n const check = await client.functions.invoke<{ available: boolean; reason?: string }>(\n \"check-subdomain\",\n { subdomain }\n );\n if (!check.available) {\n fail(\n `Subdomain \"${subdomain}\" is not available${check.reason ? ` (${check.reason})` : \"\"}.`\n );\n }\n } catch {\n // If the control plane has no such function, skip the pre-check —\n // the collection hook still enforces uniqueness on create.\n }\n\n try {\n const user = await client.auth.getUser();\n if (!user) fail(\"Session is no longer valid.\", \"Run `rebase cloud login` again.\");\n const created = (await client.data.collection(\"projects\").create({\n name,\n subdomain,\n gitRepoUrl,\n gitBranch,\n provider,\n region,\n vmSize,\n organization: org,\n createdById: user.uid,\n status: \"provisioning\"\n })) as unknown as ProjectRow;\n\n success(`Created project ${chalk.bold(name)}`);\n keyValues([\n [\"Slug\", String(created.subdomain ?? \"\")],\n [\"URL\", projectHost(created, await fetchTenantBaseDomain(client, url))],\n [\"Provider\", provider],\n [\"Branch\", gitBranch]\n ]);\n\n if (args[\"--link\"]) {\n writeLink({ url,\nprojectId: String(created.id),\nslug: created.subdomain,\nprojectName: name,\norgId: String(org) });\n console.log(chalk.gray(\" Linked this directory to the new project.\"));\n }\n console.log(\"\");\n console.log(chalk.gray(` Deploy it with: ${chalk.bold(`rebase cloud deploy --project ${created.subdomain ?? created.id}`)}`));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to create project\");\n }\n}\n\n/* ─── info ─────────────────────────────────────────────────────── */\n\nexport async function projectInfo(rawArgs: string[], projectRef: string): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n try {\n const projectId = await resolveProjectRef(projectRef, client);\n const p = (await client.data.collection(\"projects\").findById(projectId)) as unknown as ProjectRow | undefined;\n if (!p) fail(`Project ${projectRef} not found.`);\n\n const [db, lastDeploy, baseDomain] = await Promise.all([\n firstRow(client, \"databases\", projectId),\n latestDeployment(client, projectId),\n fetchTenantBaseDomain(client, url)\n ]);\n\n console.log(\"\");\n console.log(` ${chalk.bold(p.name ?? \"(unnamed)\")} ${chalk.gray(`[${p.subdomain ?? p.id}]`)} ${colorStatus(p.status)}`);\n console.log(\"\");\n keyValues([\n [\"Subdomain\", projectHost(p, baseDomain)],\n [\"Custom domain\", p.customDomain],\n [\"Repository\", p.gitRepoUrl],\n [\"Branch\", p.gitBranch],\n [\"Provider\", p.provider],\n [\"Region\", p.region],\n [\"Organization\", p.organization !== undefined ? String(p.organization) : undefined],\n [\"Database\", db ? `${db.type} (${colorStatus(db.connectionStatus as string)})` : \"none\"],\n [\"Last deploy\", lastDeploy ? `${colorStatus(lastDeploy.status)} · ${fmtDate(lastDeploy.createdAt)}` : \"never\"]\n ]);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to load project\");\n }\n}\n\n/* ─── delete ───────────────────────────────────────────────────── */\n\nexport async function deleteProject(rawArgs: string[], projectRef: string): Promise<void> {\n const args = arg({ \"--yes\": Boolean,\n\"-y\": \"--yes\" }, { argv: rawArgs.slice(2),\npermissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await resolveProjectRef(projectRef, client);\n\n const p = (await client.data.collection(\"projects\").findById(projectId).catch(() => undefined)) as\n | ProjectRow\n | undefined;\n if (!p) fail(`Project ${projectRef} not found.`);\n\n if (!args[\"--yes\"]) {\n const { confirmed } = await inquirer.prompt([\n {\n type: \"confirm\",\n name: \"confirmed\",\n default: false,\n message: `Permanently delete project \"${p.name ?? projectRef}\" (${p.subdomain ?? projectRef})? This tears down its deployment.`\n }\n ] as unknown as Parameters<typeof inquirer.prompt>[0]);\n if (!confirmed) {\n console.log(chalk.gray(\" Aborted.\"));\n return;\n }\n }\n\n try {\n await client.data.collection(\"projects\").delete(projectId);\n success(`Deleted project ${chalk.bold(p.name ?? projectId)}`);\n } catch (e) {\n reportError(e, \"Failed to delete project\");\n }\n}\n\n/* ─── shared helpers (used by other subcommands too) ───────────── */\n\nexport async function firstRow(\n client: CloudClient,\n collection: string,\n projectId: string\n): Promise<Record<string, unknown> | undefined> {\n const res = await client.data.collection(collection).find({\n where: { project: [\"==\", projectId] },\n limit: 1\n });\n return res.data[0];\n}\n\nexport async function latestDeployment(\n client: CloudClient,\n projectId: string\n): Promise<{ id: string | number; status?: string; createdAt?: string; logs?: string } | undefined> {\n const res = await client.data.collection(\"deployments\").find({\n where: { project: [\"==\", projectId] },\n orderBy: [\"createdAt\", \"desc\"],\n limit: 1\n });\n return res.data[0] as { id: string | number; status?: string; createdAt?: string; logs?: string } | undefined;\n}\n\nexport function fmtDate(value: string | undefined): string {\n if (!value) return \"—\";\n const d = new Date(value);\n return isNaN(d.getTime()) ? value : d.toLocaleString();\n}\n","/**\n * `rebase cloud deploy` and `rebase cloud logs`.\n *\n * `deploy` triggers the control-plane `deploy` function, then tails the build\n * logs from the deployment record until it succeeds or fails. `logs` shows the\n * latest build log, or runtime logs with `--runtime`.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\nimport { spawn } from \"child_process\";\nimport { requireClient, resolveProjectRef, colorStatus, fail, reportError, type CloudClient } from \"./context\";\nimport { latestDeployment } from \"./projects\";\n\ninterface Deployment {\n id: string | number;\n status?: string;\n logs?: string;\n createdAt?: string;\n}\n\nconst POLL_INTERVAL_MS = 1500;\nconst POLL_TIMEOUT_MS = 15 * 60 * 1000; // 15 min hard stop\n\n// Keep in sync with the control plane's build-context cap (deploy/upload\n// MAX_BYTES and the backend's maxBodySize). Checked before uploading so an\n// oversized context fails in milliseconds with a hint, not after the upload\n// with a bare 413.\nconst MAX_SOURCE_UPLOAD_BYTES = 100 * 1024 * 1024;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nfunction run(cmd: string, cmdArgs: string[], cwd?: string, env?: NodeJS.ProcessEnv): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(cmd, cmdArgs, { cwd,\nenv: env ? { ...process.env, ...env } : undefined,\nstdio: [\"ignore\", \"ignore\", \"pipe\"] });\n let stderr = \"\";\n child.stderr.on(\"data\", (d) => (stderr += d.toString()));\n child.on(\"error\", reject);\n child.on(\"close\", (code) => (code === 0 ? resolve() : reject(new Error(stderr || `${cmd} exited ${code}`))));\n });\n}\n\n/**\n * Package `sourceDir` into a gzipped tarball, honoring `.gitignore`/`.rebaseignore`\n * and always excluding `.git` and `node_modules`. Returns the temp archive path.\n */\nasync function createSourceTarball(sourceDir: string): Promise<string> {\n const dir = path.resolve(sourceDir);\n if (!fs.existsSync(dir)) fail(`Source directory not found: ${dir}`);\n\n const tarPath = path.join(os.tmpdir(), `rebase-src-${Date.now()}.tar.gz`);\n const tarArgs = [\"-czf\", tarPath, \"--exclude=.git\", \"--exclude=node_modules\"];\n for (const ignore of [\".gitignore\", \".rebaseignore\"]) {\n if (fs.existsSync(path.join(dir, ignore))) tarArgs.push(`--exclude-from=${ignore}`);\n }\n tarArgs.push(\".\");\n\n try {\n // COPYFILE_DISABLE: macOS bsdtar otherwise emits an AppleDouble sidecar\n // (`._foo.ts`) for every file carrying an xattr — and macOS stamps the\n // SIP-protected `com.apple.provenance` xattr routinely, so a stock\n // checkout ships `._*` binary junk that crashes schema generation in\n // the builder. GNU tar ignores the variable, so this is safe everywhere.\n await run(\"tar\", tarArgs, dir, { COPYFILE_DISABLE: \"1\" });\n } catch (e) {\n fail(`Failed to package source: ${e instanceof Error ? e.message : String(e)}`);\n }\n return tarPath;\n}\n\n/** Upload a build-context tarball; returns the opaque `source` ref for deploy. */\nasync function uploadSource(url: string, token: string, projectId: string, tarPath: string): Promise<string> {\n const bytes = fs.readFileSync(tarPath);\n const sizeMb = (bytes.length / 1024 / 1024).toFixed(1);\n if (bytes.length > MAX_SOURCE_UPLOAD_BYTES) {\n fail(\n `Source context is ${sizeMb} MB — the upload cap is ${Math.round(MAX_SOURCE_UPLOAD_BYTES / 1024 / 1024)} MB.`,\n \"Trim the build context: exclude sourcemaps (*.map), build output and large assets via .rebaseignore or .gitignore.\"\n );\n }\n console.log(chalk.gray(` Uploading source (${sizeMb} MB)...`));\n const res = await fetch(`${url}/api/functions/deploy/upload?projectId=${encodeURIComponent(projectId)}`, {\n method: \"POST\",\n headers: { Authorization: `Bearer ${token}`,\n\"Content-Type\": \"application/gzip\" },\n body: bytes\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n fail(`Source upload failed (${res.status}): ${body || res.statusText}`);\n }\n const data = (await res.json()) as { source?: string };\n if (!data.source) fail(\"Upload endpoint did not return a source reference.\");\n return data.source;\n}\n\nexport async function deployCommand(rawArgs: string[], projectRef: string): Promise<void> {\n const args = arg(\n { \"--no-follow\": Boolean,\n\"--source\": String },\n { argv: rawArgs.slice(2),\npermissive: true }\n );\n const { client, url } = await requireClient(rawArgs);\n const projectId = await resolveProjectRef(projectRef, client);\n\n // Optional fly-style local source upload: `deploy --source .`\n let source: string | undefined;\n if (args[\"--source\"]) {\n const tarPath = await createSourceTarball(args[\"--source\"]);\n try {\n const token = client.auth.getSession()?.accessToken;\n if (!token) fail(\"Not authenticated.\", \"Run `rebase cloud login`.\");\n source = await uploadSource(url, token, projectId, tarPath);\n } finally {\n fs.rmSync(tarPath, { force: true });\n }\n }\n\n console.log(\"\");\n console.log(` 🚀 Triggering deployment for project ${chalk.bold(projectRef)}${source ? \" from uploaded source\" : \"\"}...`);\n\n let deploymentId: string;\n try {\n const res = await client.functions.invoke<{ success: boolean; deployment: { id: string | number } }>(\n \"deploy\",\n source ? { projectId,\nsource } : { projectId }\n );\n if (!res?.deployment?.id) fail(\"Control plane did not return a deployment id.\");\n deploymentId = String(res.deployment.id);\n } catch (e) {\n const err = e as { status?: number; message?: string; code?: string };\n if (err?.status === 409) {\n fail(\"A deployment is already in progress for this project.\");\n }\n if (err?.status === 402) {\n // Billing gate: no card on file, card declined, or needs auth.\n fail(\n err.message || \"Payment required before deploying.\",\n \"Attach a card once with `rebase cloud billing setup`, then deploy again.\"\n );\n }\n reportError(e, \"Failed to trigger deployment\");\n }\n\n console.log(chalk.gray(` Deployment ${deploymentId} created.`));\n if (args[\"--no-follow\"]) {\n console.log(chalk.gray(\" Not following logs (--no-follow). Check status with `rebase cloud logs`.\"));\n console.log(\"\");\n return;\n }\n console.log(chalk.gray(\" Streaming build logs (Ctrl-C to stop watching — the build keeps running):\"));\n console.log(\"\");\n\n await streamBuildLogs(client, deploymentId);\n}\n\n/** Poll a deployment record and print new log output as it arrives. */\nasync function streamBuildLogs(client: CloudClient, deploymentId: string): Promise<void> {\n let printed = 0;\n const started = Date.now();\n\n for (;;) {\n let dep: Deployment | undefined;\n try {\n dep = (await client.data.collection(\"deployments\").findById(deploymentId)) as unknown as Deployment | undefined;\n } catch (e) {\n reportError(e, \"Failed to read deployment status\");\n }\n if (!dep) fail(`Deployment ${deploymentId} disappeared.`);\n\n const logs = dep.logs ?? \"\";\n if (logs.length > printed) {\n process.stdout.write(logs.slice(printed));\n printed = logs.length;\n }\n\n if (dep.status && dep.status !== \"deploying\") {\n console.log(\"\");\n if (dep.status === \"success\") {\n console.log(chalk.bold.green(\" ✓ Deployment succeeded\"));\n } else {\n console.log(chalk.bold.red(` ✗ Deployment ${dep.status}`));\n console.log(\"\");\n process.exit(1);\n }\n console.log(\"\");\n return;\n }\n\n if (Date.now() - started > POLL_TIMEOUT_MS) {\n console.log(\"\");\n fail(\n \"Timed out waiting for the build to finish.\",\n \"The deployment may still be running — check `rebase cloud logs`.\"\n );\n }\n\n await sleep(POLL_INTERVAL_MS);\n }\n}\n\nexport async function logsCommand(rawArgs: string[], projectRef: string): Promise<void> {\n const args = arg(\n { \"--runtime\": Boolean,\n\"--follow\": Boolean,\n\"-f\": \"--follow\" },\n { argv: rawArgs.slice(2),\npermissive: true }\n );\n const { client } = await requireClient(rawArgs);\n const projectId = await resolveProjectRef(projectRef, client);\n\n if (args[\"--runtime\"]) {\n try {\n const res = await client.functions.invoke<{ logs?: string; error?: string }>(\n \"runtime-logs\",\n undefined,\n { method: \"GET\",\npath: projectId }\n );\n console.log(\"\");\n console.log(chalk.bold(` 📄 Runtime logs — project ${projectRef}`));\n console.log(\"\");\n console.log(res.logs ?? chalk.gray(\" (no logs)\"));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to fetch runtime logs\");\n }\n return;\n }\n\n // Build logs: latest deployment, optionally follow if still running.\n try {\n const dep = (await latestDeployment(client, projectId)) as unknown as Deployment | undefined;\n if (!dep) {\n console.log(\"\");\n console.log(chalk.gray(\" No deployments yet for this project.\"));\n console.log(\"\");\n return;\n }\n\n console.log(\"\");\n console.log(chalk.bold(` 📄 Build logs — deployment ${dep.id}`) + ` ${colorStatus(dep.status)}`);\n console.log(\"\");\n\n if (args[\"--follow\"] && dep.status === \"deploying\") {\n // Hand off to the streamer, which prints from the top and tails live.\n await streamBuildLogs(client, String(dep.id));\n } else {\n console.log(dep.logs ?? chalk.gray(\" (no logs)\"));\n console.log(\"\");\n }\n } catch (e) {\n reportError(e, \"Failed to fetch build logs\");\n }\n}\n","/**\n * `rebase cloud orgs` — list / create / members.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n getContextOrg,\n setContextOrg,\n colorStatus,\n success,\n fail,\n reportError\n} from \"./context\";\n\ninterface OrgRow {\n id: string | number;\n name?: string;\n slug?: string;\n description?: string;\n createdAt?: string;\n}\n\nexport async function orgsCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n switch (subcommand) {\n case \"list\":\n case undefined:\n await listOrgs(rawArgs);\n break;\n case \"create\":\n await createOrg(rawArgs);\n break;\n case \"members\":\n await listMembers(rawArgs);\n break;\n case \"--help\":\n printOrgsHelp();\n break;\n default:\n fail(`Unknown orgs command: ${subcommand}`);\n }\n}\n\nasync function listOrgs(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n try {\n const orgs = (await client.data.collection(\"organizations\").find({ limit: 100 })).data as unknown as OrgRow[];\n const active = getContextOrg(url);\n\n console.log(\"\");\n console.log(chalk.bold(\" 🏢 Organizations\"));\n console.log(\"\");\n if (orgs.length === 0) {\n console.log(chalk.gray(\" You are not a member of any organization.\"));\n console.log(\"\");\n return;\n }\n for (const o of orgs) {\n const marker = String(o.id) === active ? chalk.green(\" ●\") : \" \";\n console.log(`${marker}${chalk.bold(o.name ?? \"(unnamed)\")} ${chalk.gray(`[${o.id}]`)}${o.slug ? chalk.gray(` ${o.slug}`) : \"\"}`);\n }\n console.log(\"\");\n console.log(chalk.gray(\" ● = active organization. Switch with `rebase cloud use <id>`.\"));\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list organizations\");\n }\n}\n\nasync function createOrg(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--name\": String,\n\"--slug\": String,\n\"-n\": \"--name\" },\n { argv: rawArgs.slice(4),\npermissive: true }\n );\n const { client, url } = await requireClient(rawArgs);\n\n const prompts: Array<Record<string, unknown>> = [];\n if (!args[\"--name\"]) prompts.push({ type: \"input\",\nname: \"name\",\nmessage: \"Organization name:\" });\n const answers = prompts.length\n ? await inquirer.prompt(prompts as unknown as Parameters<typeof inquirer.prompt>[0])\n : {};\n\n const name = (args[\"--name\"] || (answers as { name?: string }).name || \"\").trim();\n if (!name) fail(\"Organization name is required.\");\n const slug = (args[\"--slug\"] || slugify(name)).trim();\n\n try {\n const created = (await client.data.collection(\"organizations\").create({\n name,\n slug,\n createdAt: new Date().toISOString()\n })) as unknown as OrgRow;\n setContextOrg(url, String(created.id));\n success(`Created organization ${chalk.bold(name)} and set it active`);\n } catch (e) {\n reportError(e, \"Failed to create organization\");\n }\n}\n\nasync function listMembers(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n const org = getContextOrg(url);\n if (!org) fail(\"No active organization.\", \"Run `rebase cloud use` first.\");\n\n try {\n const members = (await client.data.collection(\"organization-members\").find({\n where: { organization: [\"==\", org] },\n limit: 200\n })).data as unknown as Array<{ id: string | number; userId?: string; role?: string }>;\n\n console.log(\"\");\n console.log(chalk.bold(` 👥 Members — org ${org}`));\n console.log(\"\");\n if (members.length === 0) {\n console.log(chalk.gray(\" No members found.\"));\n console.log(\"\");\n return;\n }\n for (const m of members) {\n console.log(` ${chalk.bold(m.userId ?? \"?\")} ${colorStatus(m.role)}`);\n }\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list members\");\n }\n}\n\nfunction slugify(s: string): string {\n return s\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\n\nfunction printOrgsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud orgs\")} — Manage organizations\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List organizations you belong to\n ${chalk.blue.bold(\"create\")} Create a new organization ${chalk.gray(\"(--name, --slug)\")}\n ${chalk.blue.bold(\"members\")} List members of the active organization\n`);\n}\n","/**\n * `rebase cloud db` — database + backup management for a project.\n *\n * db list List databases attached to the project\n * db create Attach a managed or bring-your-own database\n * db test Test connectivity to the project's database\n * db backup list|create|restore\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n confirmDestructive,\n colorStatus,\n keyValues,\n success,\n fail,\n reportError\n} from \"./context\";\n\ninterface DatabaseRow {\n id: string | number;\n type?: string;\n connectionStatus?: string;\n useSshTunnel?: boolean;\n pitrEnabled?: boolean;\n}\n\ninterface BackupRow {\n filename: string;\n size?: number;\n createdAt?: string;\n type?: string;\n}\n\nexport async function dbCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n switch (subcommand) {\n case \"list\":\n case undefined:\n await listDatabases(rawArgs);\n break;\n case \"create\":\n await createDatabase(rawArgs);\n break;\n case \"info\":\n await dbInfo(rawArgs);\n break;\n case \"test\":\n await testDatabase(rawArgs);\n break;\n case \"backup\":\n await backupCommand(rawArgs);\n break;\n case \"pitr\":\n await pitrCommand(rawArgs);\n break;\n case \"--help\":\n printDbHelp();\n break;\n default:\n fail(`Unknown db command: ${subcommand}`);\n }\n}\n\nasync function listDatabases(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const dbs = (await client.data.collection(\"databases\").find({\n where: { project: [\"==\", projectId] },\n limit: 50\n })).data as unknown as DatabaseRow[];\n\n console.log(\"\");\n console.log(chalk.bold(` 🗄 Databases — project ${projectRef}`));\n console.log(\"\");\n if (dbs.length === 0) {\n console.log(chalk.gray(\" No database attached. Add one with `rebase cloud db create`.\"));\n console.log(\"\");\n return;\n }\n for (const d of dbs) {\n console.log(` ${chalk.bold(d.type ?? \"unknown\")} ${chalk.gray(`[${d.id}]`)} ${colorStatus(d.connectionStatus)}`);\n keyValues([\n [\"SSH tunnel\", d.useSshTunnel ? \"yes\" : undefined],\n [\"PITR\", d.pitrEnabled ? \"enabled\" : undefined]\n ]);\n }\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list databases\");\n }\n}\n\nasync function createDatabase(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--type\": String,\n\"--connection-string\": String,\n\"--project\": String,\n\"-p\": \"--project\" },\n { argv: rawArgs.slice(4),\npermissive: true }\n );\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n let type = args[\"--type\"];\n if (!type) {\n const { picked } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"picked\",\n message: \"Database type:\",\n choices: [\n { name: \"SaaS Managed (provisioned for you)\",\nvalue: \"managed\" },\n { name: \"Bring Your Own DB (external PostgreSQL)\",\nvalue: \"byodb\" }\n ]\n }\n ] as unknown as Parameters<typeof inquirer.prompt>[0]);\n type = picked as string;\n }\n\n let connectionString = args[\"--connection-string\"];\n if (type === \"byodb\" && !connectionString) {\n const { cs } = await inquirer.prompt([\n { type: \"input\",\nname: \"cs\",\nmessage: \"PostgreSQL connection string:\" }\n ] as unknown as Parameters<typeof inquirer.prompt>[0]);\n connectionString = (cs as string)?.trim();\n if (!connectionString) fail(\"A connection string is required for bring-your-own databases.\");\n }\n\n try {\n const created = (await client.data.collection(\"databases\").create({\n project: projectId,\n type,\n connectionString: type === \"byodb\" ? connectionString : undefined,\n connectionStatus: \"untested\"\n })) as unknown as DatabaseRow;\n success(`Attached ${type} database to project ${projectRef}`);\n keyValues([[\"ID\", String(created.id)]]);\n if (type === \"byodb\") {\n console.log(chalk.gray(\" Verify it with `rebase cloud db test`.\"));\n console.log(\"\");\n }\n } catch (e) {\n reportError(e, \"Failed to attach database\");\n }\n}\n\nasync function testDatabase(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n console.log(\"\");\n console.log(` Testing database connectivity for project ${chalk.bold(projectId)}...`);\n try {\n const res = await client.functions.invoke<{ success: boolean; logs?: string }>(\"db-test\", { projectId });\n console.log(\"\");\n if (res.logs) console.log(res.logs);\n if (res.success) success(\"Database connection succeeded\");\n else fail(\"Database connection failed. See logs above.\");\n } catch (e) {\n reportError(e, \"Failed to test database\");\n }\n}\n\n/* ─── db info ──────────────────────────────────────────────────── */\n\ninterface DbInfoResponse {\n type: \"managed\" | \"byodb\";\n host: string | null;\n port: string | null;\n database: string | null;\n username: string | null;\n passwordAvailable: boolean;\n portForward: { namespace: string; service: string; localPort: number; remotePort: number } | null;\n unavailableReason: string | null;\n}\n\n/**\n * `rebase cloud db info [--reveal]` — where a project's database actually lives.\n *\n * The password is NEVER in the default output; `--reveal` fetches it through the\n * separate reveal call, and it appears in JSON only when `--reveal` is given.\n * Any field the server could not resolve comes back `null` and is rendered as\n * unavailable, never a placeholder.\n */\nasync function dbInfo(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--reveal\": Boolean, \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n try {\n const info = await client.functions.invoke<DbInfoResponse>(\"db-info\", undefined, { method: \"GET\", path: projectId });\n\n let password: string | undefined;\n let connectionString: string | undefined;\n if (args[\"--reveal\"]) {\n if (!info.passwordAvailable) {\n fail(\"No password is available to reveal for this database.\", info.unavailableReason ?? undefined, \"password_unavailable\");\n }\n const revealed = await client.functions.invoke<{ password: string; connectionString: string }>(\n \"db-info\",\n { projectId },\n { path: \"reveal\" }\n );\n password = revealed.password;\n connectionString = revealed.connectionString;\n }\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🗄 Database — project ${projectRef}`) + chalk.gray(` (${info.type})`));\n console.log(\"\");\n keyValues([\n [\"Host\", info.host],\n [\"Port\", info.port],\n [\"Database\", info.database],\n [\"Username\", info.username],\n [\"Password\", info.passwordAvailable ? (password ?? chalk.gray(\"hidden — pass --reveal\")) : chalk.gray(\"unavailable\")],\n [\"Connection\", connectionString]\n ]);\n if (info.unavailableReason) {\n console.log(chalk.gray(` ${info.unavailableReason}`));\n }\n if (info.portForward) {\n const pf = info.portForward;\n console.log(\"\");\n console.log(chalk.gray(` Port-forward: kubectl -n ${pf.namespace} port-forward svc/${pf.service} ${pf.localPort}:${pf.remotePort}`));\n }\n console.log(\"\");\n },\n {\n projectId,\n type: info.type,\n host: info.host,\n port: info.port,\n database: info.database,\n username: info.username,\n passwordAvailable: info.passwordAvailable,\n portForward: info.portForward,\n unavailableReason: info.unavailableReason,\n // Only present when explicitly revealed.\n ...(args[\"--reveal\"] ? { password, connectionString } : {})\n }\n );\n } catch (e) {\n reportError(e, \"Failed to load database info\");\n }\n}\n\n/* ─── backups ──────────────────────────────────────────────────── */\n\nasync function backupCommand(rawArgs: string[]): Promise<void> {\n // `rebase cloud db backup <action>` — action is the 4th positional token.\n const action = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[2] || \"list\";\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\" }, { argv: rawArgs.slice(2), permissive: true });\n\n try {\n if (action === \"create\") {\n const res = await client.functions.invoke<{ success: boolean; backup?: BackupRow; error?: string }>(\n \"backup\",\n { projectId,\ntype: \"manual\" },\n { path: \"create\" }\n );\n if (!res.success) fail(res.error || \"Backup failed.\");\n emit(\n () => success(`Backup created: ${res.backup?.filename ?? \"(unknown)\"}`),\n { success: true, backup: res.backup ?? null }\n );\n return;\n }\n\n if (action === \"restore\") {\n const filename = cloudPositionals(rawArgs).slice(3)[0];\n if (!filename) fail(\"Usage: rebase cloud db backup restore <filename>\", undefined, \"usage\");\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Restore \"${filename}\" over the current database for project ${projectRef}?`\n });\n const res = await client.functions.invoke<{ success: boolean; message?: string; error?: string }>(\n \"backup\",\n { projectId,\nfilename },\n { path: \"restore\" }\n );\n if (!res.success) fail(res.error || \"Restore failed.\");\n emit(() => success(res.message || \"Restore complete\"), { success: true, message: res.message ?? null });\n return;\n }\n\n if (action === \"status\") {\n const res = await client.functions.invoke<Record<string, unknown>>(\"backup\", undefined, {\n method: \"GET\",\n path: `backup-status/${projectId}`\n });\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 💾 Automated backups — project ${projectRef}`));\n console.log(\"\");\n keyValues([\n [\"Enabled\", res.enabled ? chalk.green(\"yes\") : chalk.yellow(\"no\")],\n [\"Reason\", String(res.reason ?? \"\")],\n [\"Database type\", String(res.databaseType ?? \"\")],\n [\"Last backup\", (res.lastSuccessfulBackup as string) ?? undefined],\n [\n \"Recovery window\",\n res.recoveryWindow\n ? `${(res.recoveryWindow as { from: string }).from} → ${(res.recoveryWindow as { to: string }).to}`\n : undefined\n ]\n ]);\n console.log(\"\");\n },\n res\n );\n return;\n }\n\n if (action === \"download\") {\n const filename = cloudPositionals(rawArgs).slice(3)[0];\n if (!filename) fail(\"Usage: rebase cloud db backup download <filename>\", undefined, \"usage\");\n const res = await client.functions.invoke<{ url: string; name: string; size: number }>(\"backup\", undefined, {\n method: \"GET\",\n path: `download/${projectId}/${encodeURIComponent(filename)}`\n });\n // Print the signed URL rather than downloading the file — downloading\n // is a user-consented action, and the URL is what the operator/agent\n // needs to fetch it themselves.\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ${res.name}`) + chalk.gray(` ${(res.size / 1024 / 1024).toFixed(1)} MB`));\n console.log(` ${chalk.cyan(res.url)}`);\n console.log(\"\");\n console.log(chalk.gray(\" Short-lived signed URL — fetch it with curl/wget.\"));\n console.log(\"\");\n },\n { name: res.name, size: res.size, url: res.url }\n );\n return;\n }\n\n // default: list\n const res = await client.functions.invoke<{ backups: BackupRow[] }>(\n \"backup\",\n undefined,\n { method: \"GET\",\npath: `list/${projectId}` }\n );\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 💾 Backups — project ${projectRef}`));\n console.log(\"\");\n if (!res.backups?.length) {\n console.log(chalk.gray(\" No backups yet. Create one with `rebase cloud db backup create`.\"));\n console.log(\"\");\n return;\n }\n for (const b of res.backups) {\n const size = b.size !== undefined ? `${(b.size / 1024 / 1024).toFixed(1)} MB` : \"\";\n console.log(` ${chalk.bold(b.filename)} ${chalk.gray(`${b.type ?? \"\"} ${size}`.trim())}`);\n }\n console.log(\"\");\n },\n { projectId, backups: res.backups ?? [] }\n );\n } catch (e) {\n reportError(e, \"Backup operation failed\");\n }\n}\n\n/* ─── PITR (point-in-time recovery) ────────────────────────────── */\n\n/**\n * `rebase cloud db pitr <status|restore|cutover|discard>`.\n *\n * A PITR restore is STAGED, not applied: `restore` creates a recovered copy of\n * the database beside the live one — the application is NOT repointed and the\n * original is left running and unchanged. `cutover` is the separate, explicit\n * step that repoints the app at the recovered copy (and restarts it). `discard`\n * removes a staged copy; the server refuses to discard a copy that has been cut\n * over to (it is now the live database). Every mutating step requires `--yes` in\n * non-interactive use, and the CLI surfaces these staged semantics honestly.\n */\nasync function pitrCommand(rawArgs: string[]): Promise<void> {\n const args = arg(\n { \"--target\": String, \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" },\n { argv: rawArgs.slice(2), permissive: true }\n );\n const action = cloudPositionals(rawArgs).slice(2)[0] || \"status\";\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n try {\n if (action === \"status\") {\n const res = await client.functions.invoke<Record<string, unknown>>(\"backup\", undefined, {\n method: \"GET\",\n path: `pitr-status/${projectId}`\n });\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ⏱ Point-in-time recovery — project ${projectRef}`));\n console.log(\"\");\n keyValues([\n [\"Available\", res.available ? chalk.green(\"yes\") : chalk.yellow(\"no\")],\n [\"First recoverable\", (res.firstRecoverabilityPoint as string) ?? undefined],\n [\"Last backup\", (res.lastSuccessfulBackup as string) ?? undefined],\n [\"Message\", (res.message as string) ?? undefined]\n ]);\n console.log(\"\");\n },\n res\n );\n return;\n }\n\n if (action === \"restore\") {\n const target = args[\"--target\"];\n if (!target) fail(\"Usage: rebase cloud db pitr restore --target <ISO timestamp>\", undefined, \"usage\");\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Stage a point-in-time recovery of project ${projectRef} at ${target}? (stages a copy; does not repoint your app)`\n });\n const res = await client.functions.invoke<Record<string, unknown>>(\n \"backup\",\n // acknowledgeNoCutover is required by the server: the caller must\n // affirm this only STAGES a copy. The confirm prompt above says so.\n { projectId, targetTime: target, acknowledgeNoCutover: true },\n { path: \"pitr-restore\" }\n );\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.yellow(` ⏳ ${String(res.message ?? \"Recovery staged.\")}`));\n console.log(chalk.gray(\" Watch progress with `rebase cloud db pitr status`, then `rebase cloud db pitr cutover --yes`.\"));\n console.log(\"\");\n },\n res\n );\n return;\n }\n\n if (action === \"cutover\") {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Cut project ${projectRef} over to the staged recovery? This repoints and restarts your application.`\n });\n const res = await client.functions.invoke<Record<string, unknown>>(\"backup\", { projectId }, { path: \"pitr-restore-cutover\" });\n emit(\n () => {\n console.log(\"\");\n console.log(String(res.message ?? \"Cutover requested.\"));\n console.log(\"\");\n },\n res\n );\n return;\n }\n\n if (action === \"discard\") {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Discard the staged recovery for project ${projectRef}? This deletes the staged copy and its storage.`\n });\n const res = await client.functions.invoke<Record<string, unknown>>(\"backup\", { projectId }, { path: \"pitr-restore-discard\" });\n emit(\n () => success(String(res.message ?? \"Staged restore discarded.\")),\n res\n );\n return;\n }\n\n fail(`Unknown pitr command: ${action}`, \"Try status | restore | cutover | discard.\", \"usage\");\n } catch (e) {\n reportError(e, \"PITR operation failed\");\n }\n}\n\nfunction printDbHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud db\")} — Database & backups\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List databases attached to the project\n ${chalk.blue.bold(\"create\")} Attach a managed or bring-your-own database\n ${chalk.blue.bold(\"info\")} ${chalk.gray(\"[--reveal]\")} Connection details ${chalk.gray(\"(password only with --reveal)\")}\n ${chalk.blue.bold(\"test\")} Test database connectivity\n ${chalk.blue.bold(\"backup list\")} List backups\n ${chalk.blue.bold(\"backup create\")} Create a manual backup\n ${chalk.blue.bold(\"backup restore\")} ${chalk.gray(\"<file>\")} Restore a backup\n ${chalk.blue.bold(\"backup status\")} Automated-backup health\n ${chalk.blue.bold(\"backup download\")} ${chalk.gray(\"<file>\")} Signed URL for a backup\n ${chalk.blue.bold(\"pitr status\")} Point-in-time recovery window\n ${chalk.blue.bold(\"pitr restore\")} ${chalk.gray(\"--target <ISO>\")} Stage a recovery ${chalk.gray(\"(does not repoint)\")}\n ${chalk.blue.bold(\"pitr cutover\")} ${chalk.gray(\"-y\")} Repoint the app at the staged recovery\n ${chalk.blue.bold(\"pitr discard\")} ${chalk.gray(\"-y\")} Delete a staged recovery\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\n ${chalk.blue(\"--reveal\")} Include the DB password ${chalk.gray(\"(info)\")}\n ${chalk.blue(\"--type\")} managed | byodb ${chalk.gray(\"(create)\")}\n ${chalk.blue(\"--connection-string\")} External DB URL ${chalk.gray(\"(byodb)\")}\n ${chalk.blue(\"--json\")} Machine-readable output\n`);\n}\n","/**\n * `rebase cloud env` — a project's environment variables.\n *\n * env list Keys only — a value is NEVER printed here\n * env set KEY=VALUE Create/replace one variable (`--secret` ⇒ write-only)\n * env unset KEY Remove one variable\n * env reveal KEY Release one non-secret value (a secret var 403s)\n * env pull [--out .env] Write revealable values to a local dotenv file\n *\n * Values are the sharp edge here. The list endpoint returns keys and never\n * values by design (a page load is not consent to spray a customer's secrets\n * through caches and logs), and a `--secret` variable is write-only: it can be\n * replaced but never read back. This mirrors `env-vars` exactly and refuses to\n * offer reveal for a secret variable rather than letting the server 403.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n isJsonMode,\n confirmDestructive,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\ninterface EnvVarView {\n id: string;\n key: string;\n secret: boolean;\n valueSet: boolean;\n createdAt: string | null;\n updatedAt: string | null;\n}\n\ninterface EnvVarListResponse {\n vars: EnvVarView[];\n pendingRedeploy: boolean | null;\n pendingSince: string | null;\n limits: {\n maxVars: number;\n maxValueBytes: number;\n maxTotalBytes: number;\n keyPattern: string;\n reservedKeys: string[];\n };\n}\n\nasync function fetchEnvVars(client: CloudClient, projectId: string): Promise<EnvVarListResponse> {\n return client.functions.invoke<EnvVarListResponse>(\"env-vars\", undefined, {\n method: \"GET\",\n path: projectId\n });\n}\n\nexport async function envCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case undefined:\n await listEnv(rawArgs);\n break;\n case \"set\":\n await setEnv(rawArgs);\n break;\n case \"unset\":\n case \"delete\":\n case \"rm\":\n await unsetEnv(rawArgs);\n break;\n case \"reveal\":\n await revealEnv(rawArgs);\n break;\n case \"pull\":\n await pullEnv(rawArgs);\n break;\n case \"--help\":\n printEnvHelp();\n break;\n default:\n fail(`Unknown env command: ${action}`, \"Try `rebase cloud env --help`.\");\n }\n}\n\n/** A short human hint about redeploy state (the JSON carries `pendingRedeploy`). */\nfunction pendingHint(pending: boolean | null): string | undefined {\n if (pending === true) return chalk.yellow(\"A variable changed since the last deploy — run `rebase cloud deploy` to apply it.\");\n if (pending === null) return chalk.gray(\"Redeploy state is unknown (deployment history unavailable).\");\n return undefined;\n}\n\nasync function listEnv(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const res = await fetchEnvVars(client, projectId);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🔑 Environment — project ${projectRef}`));\n console.log(\"\");\n if (!res.vars.length) {\n console.log(chalk.gray(\" No variables. Add one with `rebase cloud env set KEY=VALUE`.\"));\n console.log(\"\");\n return;\n }\n for (const v of res.vars) {\n const badges = [\n v.secret ? chalk.magenta(\"secret\") : undefined,\n v.valueSet ? undefined : chalk.gray(\"empty\")\n ]\n .filter(Boolean)\n .join(\" \");\n // Deliberately no value — reveal is the only way to read one.\n console.log(` ${chalk.bold(v.key)}${badges ? ` ${badges}` : \"\"}`);\n }\n const hint = pendingHint(res.pendingRedeploy);\n if (hint) {\n console.log(\"\");\n console.log(` ${hint}`);\n }\n console.log(\"\");\n },\n {\n projectId,\n pendingRedeploy: res.pendingRedeploy,\n pendingSince: res.pendingSince,\n // Never a value: keys + shape only.\n vars: res.vars.map((v) => ({\n key: v.key,\n secret: v.secret,\n valueSet: v.valueSet,\n createdAt: v.createdAt,\n updatedAt: v.updatedAt\n })),\n limits: res.limits\n }\n );\n } catch (e) {\n reportError(e, \"Failed to list environment variables\");\n }\n}\n\n/** Parse `KEY=VALUE` or `KEY VALUE` from the positional operands. */\nexport function parseEnvAssignment(operands: string[]): { key: string; value: string } | null {\n const first = operands[0];\n if (!first) return null;\n const eq = first.indexOf(\"=\");\n if (eq > 0) {\n return { key: first.slice(0, eq).trim(), value: first.slice(eq + 1) };\n }\n // `set KEY VALUE` form — VALUE is the next operand (may be absent ⇒ empty).\n return { key: first.trim(), value: operands[1] ?? \"\" };\n}\n\nasync function setEnv(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--secret\": Boolean, \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const operands = cloudPositionals(rawArgs).slice(2); // after `env set`\n const parsed = parseEnvAssignment(operands);\n if (!parsed || !parsed.key) {\n fail(\"Usage: rebase cloud env set KEY=VALUE [--secret]\", undefined, \"usage\");\n }\n\n const body: { key: string; value: string; secret?: boolean } = { key: parsed!.key, value: parsed!.value };\n if (args[\"--secret\"]) body.secret = true;\n\n try {\n const res = await client.functions.invoke<{ success: boolean; var: EnvVarView; pendingRedeploy: true }>(\n \"env-vars\",\n body,\n { path: projectId }\n );\n emit(\n () => {\n success(`Set ${chalk.bold(res.var.key)}${res.var.secret ? chalk.magenta(\" (secret)\") : \"\"}`);\n console.log(` ${chalk.yellow(\"Pending redeploy\")} — run \\`rebase cloud deploy\\` to apply it.`);\n console.log(\"\");\n },\n {\n success: true,\n key: res.var.key,\n secret: res.var.secret,\n valueSet: res.var.valueSet,\n pendingRedeploy: res.pendingRedeploy\n }\n );\n } catch (e) {\n reportError(e, \"Failed to set environment variable\");\n }\n}\n\nasync function unsetEnv(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const key = cloudPositionals(rawArgs).slice(2)[0];\n if (!key) fail(\"Usage: rebase cloud env unset KEY\", undefined, \"usage\");\n\n try {\n const res = await client.functions.invoke<{ success: boolean; pendingRedeploy: true }>(\"env-vars\", undefined, {\n method: \"DELETE\",\n path: `${projectId}/${encodeURIComponent(key!)}`\n });\n emit(\n () => {\n success(`Removed ${chalk.bold(key!)}`);\n console.log(` ${chalk.yellow(\"Pending redeploy\")} — run \\`rebase cloud deploy\\` to apply it.`);\n console.log(\"\");\n },\n { success: true, key, pendingRedeploy: res.pendingRedeploy }\n );\n } catch (e) {\n reportError(e, \"Failed to remove environment variable\");\n }\n}\n\nasync function revealEnv(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const key = cloudPositionals(rawArgs).slice(2)[0];\n if (!key) fail(\"Usage: rebase cloud env reveal KEY\", undefined, \"usage\");\n\n // Pre-check: a secret variable is write-only. Don't even ask the server — it\n // would 403 — say so plainly and never offer reveal for it. Done OUTSIDE the\n // reveal try so a deliberate refusal is not re-wrapped as a server error.\n let list: EnvVarListResponse;\n try {\n list = await fetchEnvVars(client, projectId);\n } catch (e) {\n reportError(e, \"Failed to reveal environment variable\");\n }\n const found = list!.vars.find((v) => v.key === key);\n if (!found) fail(`No variable named ${key} in project ${projectRef}.`, undefined, \"not_found\");\n if (found!.secret) {\n fail(\n `${key} is a secret (write-only) variable; its value cannot be revealed.`,\n \"Replace it with `rebase cloud env set KEY=VALUE` if you need to change it.\",\n \"secret_write_only\"\n );\n }\n\n try {\n const res = await client.functions.invoke<{ key: string; value: string }>(\n \"env-vars\",\n { projectId, key },\n { path: \"reveal\" }\n );\n emit(\n () => {\n console.log(\"\");\n console.log(` ${chalk.bold(res.key)}=${res.value}`);\n console.log(\"\");\n },\n { key: res.key, value: res.value }\n );\n } catch (e) {\n reportError(e, \"Failed to reveal environment variable\");\n }\n}\n\nasync function pullEnv(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--out\": String, \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const outPath = path.resolve(args[\"--out\"] || \".env\");\n\n try {\n const list = await fetchEnvVars(client, projectId);\n\n if (fs.existsSync(outPath)) {\n await confirmDestructive({ yes: Boolean(args[\"--yes\"]), prompt: `Overwrite ${outPath}?` });\n }\n\n // Only non-secret, value-set variables can be written — a secret var is\n // write-only and reveal 403s, so it is honestly skipped, not faked.\n const written: string[] = [];\n const skipped: Array<{ key: string; reason: string }> = [];\n const lines: string[] = [];\n for (const v of list.vars) {\n if (v.secret) {\n skipped.push({ key: v.key, reason: \"secret (write-only)\" });\n continue;\n }\n if (!v.valueSet) {\n lines.push(`${v.key}=`);\n written.push(v.key);\n continue;\n }\n const revealed = await client.functions.invoke<{ key: string; value: string }>(\n \"env-vars\",\n { projectId, key: v.key },\n { path: \"reveal\" }\n );\n // Quote values that contain whitespace or a hash so a dotenv reader\n // keeps them intact.\n const needsQuote = /[\\s#'\"]/.test(revealed.value);\n lines.push(`${v.key}=${needsQuote ? JSON.stringify(revealed.value) : revealed.value}`);\n written.push(v.key);\n }\n\n fs.writeFileSync(outPath, lines.length ? lines.join(\"\\n\") + \"\\n\" : \"\", { mode: 0o600 });\n\n emit(\n () => {\n success(`Wrote ${written.length} variable${written.length === 1 ? \"\" : \"s\"} to ${outPath}`);\n if (skipped.length) {\n console.log(chalk.gray(` Skipped ${skipped.length} secret variable(s): ${skipped.map((s) => s.key).join(\", \")}`));\n console.log(\"\");\n }\n },\n { success: true, path: outPath, written, skipped }\n );\n } catch (e) {\n reportError(e, \"Failed to pull environment variables\");\n }\n}\n\nfunction printEnvHelp(): void {\n if (isJsonMode()) {\n printEnvHelpJson();\n return;\n }\n console.log(`\n${chalk.bold(\"rebase cloud env\")} — Environment variables\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List keys ${chalk.gray(\"(values are never printed)\")}\n ${chalk.blue.bold(\"set\")} ${chalk.gray(\"KEY=VALUE [--secret]\")} Create or replace a variable\n ${chalk.blue.bold(\"unset\")} ${chalk.gray(\"KEY\")} Remove a variable\n ${chalk.blue.bold(\"reveal\")} ${chalk.gray(\"KEY\")} Print one non-secret value\n ${chalk.blue.bold(\"pull\")} ${chalk.gray(\"[--out .env] [-y]\")} Write revealable values to a dotenv file\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--secret\")} Mark a variable write-only ${chalk.gray(\"(set)\")}\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\n\n${chalk.gray(\"Values are encrypted at rest (AES-256-GCM) and only decrypted at deploy time.\")}\n`);\n}\n\nfunction printEnvHelpJson(): void {\n process.stdout.write(\n JSON.stringify({\n command: \"env\",\n actions: [\"list\", \"set\", \"unset\", \"reveal\", \"pull\"]\n }) + \"\\n\"\n );\n}\n","/**\n * `rebase cloud domains` — a project's custom domain.\n *\n * domains list Current domain + the DNS records it needs\n * domains add <domain> Register a domain (starts, does not finish, setup)\n * domains verify Check the published DNS now; live only if it passes\n * domains remove Detach the custom domain\n *\n * The DNS record set comes from the server (`verify-domain`), never composed\n * here: whether to publish an A or a CNAME depends on apex-vs-subdomain and on\n * the ingress address behind the tenant host, which the CLI cannot know. Adding\n * a domain only registers it — it is unverified until the records are published\n * and `verify` passes.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n confirmDestructive,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\ninterface DomainRecord {\n type: \"A\" | \"CNAME\" | \"TXT\";\n name: string;\n values: string[];\n}\n\ninterface DomainSetup {\n domain: string | null;\n status: \"none\" | \"pending\" | \"verified\";\n isApex?: boolean;\n tenantHost?: string;\n verifiedAt?: string | null;\n instructions?: {\n pointing?: DomainRecord;\n ownership: DomainRecord;\n };\n}\n\ninterface DomainCheck {\n ok: boolean;\n expected: string[];\n observed: string[];\n error?: string;\n}\n\ninterface VerifyResult extends DomainSetup {\n verified: boolean;\n checks: { ownership: DomainCheck; pointing: DomainCheck };\n}\n\nasync function fetchDomainSetup(client: CloudClient, projectId: string): Promise<DomainSetup> {\n return client.functions.invoke<DomainSetup>(\"verify-domain\", undefined, { method: \"GET\", path: projectId });\n}\n\nfunction printRecords(setup: DomainSetup): void {\n const recs = [setup.instructions?.pointing, setup.instructions?.ownership].filter(Boolean) as DomainRecord[];\n if (!recs.length) return;\n console.log(chalk.bold(\" DNS records to publish:\"));\n for (const r of recs) {\n console.log(` ${chalk.cyan(r.type)} ${r.name} → ${r.values.join(\", \")}`);\n }\n console.log(\"\");\n}\n\nexport async function domainsCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case \"status\":\n case undefined:\n await listDomains(rawArgs);\n break;\n case \"add\":\n case \"set\":\n await addDomain(rawArgs);\n break;\n case \"verify\":\n await verifyDomains(rawArgs);\n break;\n case \"remove\":\n case \"rm\":\n case \"delete\":\n await removeDomain(rawArgs);\n break;\n case \"--help\":\n printDomainsHelp();\n break;\n default:\n fail(`Unknown domains command: ${action}`, \"Try `rebase cloud domains --help`.\");\n }\n}\n\nasync function listDomains(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const setup = await fetchDomainSetup(client, projectId);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🌐 Custom domain — project ${projectRef}`));\n console.log(\"\");\n if (!setup.domain) {\n console.log(chalk.gray(\" No custom domain. Add one with `rebase cloud domains add <domain>`.\"));\n console.log(\"\");\n return;\n }\n keyValues([\n [\"Domain\", setup.domain],\n [\"Status\", setup.status === \"verified\" ? chalk.green(setup.status) : chalk.yellow(setup.status)],\n [\"Apex\", setup.isApex === undefined ? undefined : setup.isApex ? \"yes\" : \"no\"],\n [\"Tenant host\", setup.tenantHost],\n [\"Verified at\", setup.verifiedAt ?? undefined]\n ]);\n console.log(\"\");\n if (setup.status !== \"verified\") printRecords(setup);\n },\n { projectId, ...setup }\n );\n } catch (e) {\n reportError(e, \"Failed to load custom domain\");\n }\n}\n\nasync function addDomain(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const domain = cloudPositionals(rawArgs).slice(2)[0];\n if (!domain) fail(\"Usage: rebase cloud domains add <domain>\", undefined, \"usage\");\n\n try {\n // Registering the domain is a project update; the DNS records to publish\n // then come from the server's setup endpoint.\n await client.data.collection(\"projects\").update(projectId, { customDomain: domain });\n const setup = await fetchDomainSetup(client, projectId);\n emit(\n () => {\n success(`Registered ${chalk.bold(domain!)} — not yet verified`);\n printRecords(setup);\n console.log(chalk.gray(\" Publish the records above, then run `rebase cloud domains verify`.\"));\n console.log(\"\");\n },\n { success: true, projectId, ...setup }\n );\n } catch (e) {\n reportError(e, \"Failed to register domain\");\n }\n}\n\nasync function verifyDomains(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const res = await client.functions.invoke<VerifyResult>(\"verify-domain\", {}, { path: projectId });\n emit(\n () => {\n console.log(\"\");\n if (res.verified) success(`${res.domain} is verified and live`);\n else {\n console.log(chalk.yellow(` ⚠ ${res.domain ?? \"domain\"} is not verified yet`));\n console.log(\"\");\n const rows: Array<[string, DomainCheck]> = [\n [\"Ownership\", res.checks.ownership],\n [\"Pointing\", res.checks.pointing]\n ];\n for (const [label, check] of rows) {\n const mark = check.ok ? chalk.green(\"ok\") : chalk.red(\"missing\");\n console.log(` ${label}: ${mark}`);\n console.log(chalk.gray(` expected: ${check.expected.join(\", \") || \"—\"}`));\n console.log(chalk.gray(` observed: ${check.observed.join(\", \") || \"—\"}`));\n if (check.error) console.log(chalk.gray(` error: ${check.error}`));\n }\n console.log(\"\");\n printRecords(res);\n }\n },\n { projectId, verified: res.verified, status: res.status, domain: res.domain, checks: res.checks, instructions: res.instructions }\n );\n if (!res.verified) process.exit(1);\n } catch (e) {\n reportError(e, \"Failed to verify domain\");\n }\n}\n\nasync function removeDomain(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Remove the custom domain from project ${projectRef}?`\n });\n\n try {\n await client.data.collection(\"projects\").update(projectId, { customDomain: \"\" });\n emit(\n () => success(`Removed the custom domain from project ${projectRef}`),\n { success: true, projectId }\n );\n } catch (e) {\n reportError(e, \"Failed to remove domain\");\n }\n}\n\nfunction printDomainsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud domains\")} — Custom domain\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} Show the domain + DNS records\n ${chalk.blue.bold(\"add\")} ${chalk.gray(\"<domain>\")} Register a custom domain\n ${chalk.blue.bold(\"verify\")} Check DNS and go live\n ${chalk.blue.bold(\"remove\")} ${chalk.gray(\"[-y]\")} Detach the custom domain\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\n`);\n}\n","/**\n * `rebase cloud extensions` — allowlisted Postgres extensions.\n *\n * extensions list Every allowlisted extension + its real state\n * extensions enable <name> [-y] Install one (may restart the DB ⇒ needs -y)\n * extensions disable <name> Drop one (and remove any preload library)\n *\n * `manageable === false` is the anti-brick guard reaching the CLI: the server\n * has already said it will refuse, so enable/disable is never offered for such an\n * extension — its `manageableReason` is surfaced instead. Enabling one that\n * restarts the customer's database requires `--yes` in non-interactive use. The\n * `pgvector` alias resolves to `vector`, and a 202 (`pending`) means the database\n * is restarting and the extension is not installed yet — re-drive later.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n confirmDestructive,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\ninterface ExtensionStatus {\n name: string;\n displayName: string;\n description: string;\n requiresRestart: boolean;\n enabled: boolean;\n version: string | null;\n enabledAt: string | null;\n available: boolean;\n pendingRestart: boolean;\n manageable: boolean;\n manageableReason: string | null;\n}\n\ninterface ExtensionListResponse {\n databaseType: \"managed\" | \"byodb\" | \"none\";\n reason: string;\n source: \"database\" | \"record\";\n extensions: ExtensionStatus[];\n}\n\ninterface EnableResult {\n success: boolean;\n extension: string;\n pending?: boolean;\n restarted?: boolean;\n requiresRestart?: boolean;\n alreadyEnabled?: boolean;\n version?: string | null;\n recordWritten?: boolean;\n message: string;\n}\n\ninterface DisableResult {\n success: boolean;\n extension: string;\n dropped: boolean;\n preloadRemoved: boolean;\n restarted?: boolean;\n message: string;\n}\n\n/** The identifier CREATE EXTENSION takes. `pgvector` is a common alias. */\nexport function resolveExtensionAlias(name: string): string {\n return name.toLowerCase() === \"pgvector\" ? \"vector\" : name;\n}\n\nasync function fetchExtensions(client: CloudClient, projectId: string): Promise<ExtensionListResponse> {\n return client.functions.invoke<ExtensionListResponse>(\"extensions\", undefined, {\n method: \"GET\",\n path: `list/${projectId}`\n });\n}\n\nexport async function extensionsCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case undefined:\n await listExtensions(rawArgs);\n break;\n case \"enable\":\n await enableExtension(rawArgs);\n break;\n case \"disable\":\n await disableExtension(rawArgs);\n break;\n case \"--help\":\n printExtensionsHelp();\n break;\n default:\n fail(`Unknown extensions command: ${action}`, \"Try `rebase cloud extensions --help`.\");\n }\n}\n\nasync function listExtensions(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const res = await fetchExtensions(client, projectId);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🧩 Extensions — project ${projectRef}`) + chalk.gray(` (${res.databaseType}, source: ${res.source})`));\n console.log(\"\");\n if (res.source === \"record\") {\n console.log(chalk.yellow(\" ⚠ Database unreachable — showing cached state, not live catalog.\"));\n console.log(\"\");\n }\n for (const e of res.extensions) {\n const state = e.enabled ? chalk.green(\"enabled\") : chalk.gray(\"disabled\");\n const restart = e.requiresRestart ? chalk.yellow(\" ⟳ restarts DB\") : \"\";\n const locked = !e.manageable ? chalk.gray(\" [not manageable]\") : \"\";\n console.log(` ${chalk.bold(e.name)} ${state}${e.version ? chalk.gray(` v${e.version}`) : \"\"}${restart}${locked}`);\n if (!e.manageable && e.manageableReason) console.log(chalk.gray(` ${e.manageableReason}`));\n }\n console.log(\"\");\n },\n { projectId, databaseType: res.databaseType, reason: res.reason, source: res.source, extensions: res.extensions }\n );\n } catch (e) {\n reportError(e, \"Failed to list extensions\");\n }\n}\n\nasync function enableExtension(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const raw = cloudPositionals(rawArgs).slice(2)[0];\n if (!raw) fail(\"Usage: rebase cloud extensions enable <name>\", undefined, \"usage\");\n const name = resolveExtensionAlias(raw!);\n\n try {\n // Consult the catalog first: never offer enable where the server says it\n // is not manageable, and gate a DB-restarting enable behind --yes.\n const list = await fetchExtensions(client, projectId);\n const ext = list.extensions.find((e) => e.name === name);\n if (ext && !ext.manageable) {\n fail(\n `Extension ${name} cannot be managed on this project.`,\n ext.manageableReason ?? undefined,\n \"not_manageable\"\n );\n }\n if (ext?.requiresRestart && !ext.enabled) {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Enabling ${name} restarts the project's database. Continue?`\n });\n }\n\n const res = await client.functions.invoke<EnableResult>(\"extensions\", { projectId, extensionName: name }, { path: \"enable\" });\n emit(\n () => {\n if (res.pending) {\n console.log(\"\");\n console.log(chalk.yellow(` ⏳ ${res.message}`));\n console.log(chalk.gray(\" The database is restarting; re-run this once it is back to finish installing.\"));\n console.log(\"\");\n } else {\n success(res.message || `Enabled ${name}`);\n keyValues([[\"Version\", res.version ?? undefined]]);\n }\n },\n {\n success: res.success,\n extension: res.extension,\n pending: res.pending ?? false,\n restarted: res.restarted ?? false,\n alreadyEnabled: res.alreadyEnabled ?? false,\n version: res.version ?? null,\n message: res.message\n }\n );\n } catch (e) {\n reportError(e, \"Failed to enable extension\");\n }\n}\n\nasync function disableExtension(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n const raw = cloudPositionals(rawArgs).slice(2)[0];\n if (!raw) fail(\"Usage: rebase cloud extensions disable <name>\", undefined, \"usage\");\n const name = resolveExtensionAlias(raw!);\n\n try {\n const list = await fetchExtensions(client, projectId);\n const ext = list.extensions.find((e) => e.name === name);\n if (ext && !ext.manageable) {\n fail(\n `Extension ${name} cannot be managed on this project.`,\n ext.manageableReason ?? undefined,\n \"not_manageable\"\n );\n }\n if (ext?.requiresRestart && ext.enabled) {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Disabling ${name} restarts the project's database. Continue?`\n });\n }\n\n const res = await client.functions.invoke<DisableResult>(\"extensions\", { projectId, extensionName: name }, { path: \"disable\" });\n emit(\n () => success(res.message || `Disabled ${name}`),\n {\n success: res.success,\n extension: res.extension,\n dropped: res.dropped,\n preloadRemoved: res.preloadRemoved,\n restarted: res.restarted ?? false,\n message: res.message\n }\n );\n } catch (e) {\n reportError(e, \"Failed to disable extension\");\n }\n}\n\nfunction printExtensionsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud extensions\")} — Postgres extensions\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List extensions and their state\n ${chalk.blue.bold(\"enable\")} ${chalk.gray(\"<name> [-y]\")} Enable one ${chalk.gray(\"(pgvector alias ⇒ vector)\")}\n ${chalk.blue.bold(\"disable\")} ${chalk.gray(\"<name>\")} Disable one\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--yes, -y\")} Confirm a DB-restarting change\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\n`);\n}\n","/**\n * `rebase cloud settings` — a project's editable configuration.\n *\n * settings Show the current settings\n * settings set [flags] Update name / branch / repo / subdomain\n *\n * These are plain `projects` updates. A subdomain change is validated against\n * `check-subdomain` up front so the CLI fails with the real reason rather than a\n * generic collection error.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { requireClient, requireProject, displayProjectRef, emit, keyValues, success, fail, reportError } from \"./context\";\n\ninterface ProjectSettings {\n id: string | number;\n name?: string;\n subdomain?: string;\n gitRepoUrl?: string;\n gitBranch?: string;\n customDomain?: string;\n provider?: string;\n region?: string;\n}\n\nexport async function settingsCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"set\":\n await setSettings(rawArgs);\n break;\n case undefined:\n case \"show\":\n case \"list\":\n await showSettings(rawArgs);\n break;\n case \"--help\":\n printSettingsHelp();\n break;\n default:\n fail(`Unknown settings command: ${action}`, \"Try `rebase cloud settings --help`.\");\n }\n}\n\nasync function showSettings(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const p = (await client.data.collection(\"projects\").findById(projectId)) as unknown as ProjectSettings | undefined;\n if (!p) fail(`Project ${projectRef} not found.`, undefined, \"not_found\");\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ⚙️ Settings — project ${projectRef}`));\n console.log(\"\");\n keyValues([\n [\"Name\", p!.name],\n [\"Subdomain\", p!.subdomain],\n [\"Repository\", p!.gitRepoUrl],\n [\"Branch\", p!.gitBranch],\n [\"Custom domain\", p!.customDomain],\n [\"Provider\", p!.provider],\n [\"Region\", p!.region]\n ]);\n console.log(\"\");\n },\n {\n projectId: String(p!.id),\n name: p!.name ?? null,\n subdomain: p!.subdomain ?? null,\n gitRepoUrl: p!.gitRepoUrl ?? null,\n gitBranch: p!.gitBranch ?? null,\n customDomain: p!.customDomain ?? null,\n provider: p!.provider ?? null,\n region: p!.region ?? null\n }\n );\n } catch (e) {\n reportError(e, \"Failed to load settings\");\n }\n}\n\n/** Build the update patch from the flags actually supplied (pure/testable). */\nexport function buildSettingsPatch(args: {\n name?: string;\n subdomain?: string;\n repo?: string;\n branch?: string;\n}): Record<string, string> {\n const patch: Record<string, string> = {};\n if (args.name !== undefined) patch.name = args.name;\n if (args.subdomain !== undefined) patch.subdomain = args.subdomain.toLowerCase();\n if (args.repo !== undefined) patch.gitRepoUrl = args.repo;\n if (args.branch !== undefined) patch.gitBranch = args.branch;\n return patch;\n}\n\nasync function setSettings(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--name\": String,\n \"--subdomain\": String,\n \"--repo\": String,\n \"--branch\": String,\n \"--project\": String,\n \"-p\": \"--project\"\n },\n { argv: rawArgs.slice(2), permissive: true }\n );\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const patch = buildSettingsPatch({\n name: args[\"--name\"],\n subdomain: args[\"--subdomain\"],\n repo: args[\"--repo\"],\n branch: args[\"--branch\"]\n });\n if (Object.keys(patch).length === 0) {\n fail(\"Nothing to update.\", \"Pass --name, --subdomain, --repo, or --branch.\", \"usage\");\n }\n\n try {\n if (patch.subdomain) {\n const check = await client.functions\n .invoke<{ available: boolean; reason?: string }>(\"check-subdomain\", { subdomain: patch.subdomain })\n .catch(() => undefined);\n if (check && !check.available) {\n fail(`Subdomain \"${patch.subdomain}\" is not available${check.reason ? ` (${check.reason})` : \"\"}.`, undefined, \"subdomain_taken\");\n }\n }\n\n await client.data.collection(\"projects\").update(projectId, patch);\n emit(\n () => success(`Updated ${Object.keys(patch).join(\", \")} for project ${projectRef}`),\n { success: true, projectId, updated: patch }\n );\n } catch (e) {\n reportError(e, \"Failed to update settings\");\n }\n}\n\nfunction printSettingsHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud settings\")} — Project configuration\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"show\")} Show current settings\n ${chalk.blue.bold(\"set\")} ${chalk.gray(\"[flags]\")} Update settings\n\n${chalk.green.bold(\"Set flags\")}\n ${chalk.blue(\"--name\")} ${chalk.gray(\"<name>\")}\n ${chalk.blue(\"--subdomain\")} ${chalk.gray(\"<sub>\")}\n ${chalk.blue(\"--repo\")} ${chalk.gray(\"<git url>\")}\n ${chalk.blue(\"--branch\")} ${chalk.gray(\"<branch>\")}\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--json\")} Machine-readable output\n ${chalk.blue(\"--project, -p\")} Project slug ${chalk.gray(\"(defaults to the linked project)\")}\n`);\n}\n","/**\n * Deployment lifecycle: `rebase cloud deployments list`, `rollback`, `cancel`.\n *\n * The rollback rule is the load-bearing part. A rollback is only honoured for a\n * SUCCESSFUL deploy that recorded an image (`status === \"success\" && imageUrl`);\n * anything else 409s `deploy_not_rollbackable` server-side. So this module never\n * offers — and refuses to invoke — a rollback the server would reject, exactly\n * mirroring the console's `isRollbackable`.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n displayProjectRef,\n cloudPositionals,\n emit,\n confirmDestructive,\n colorStatus,\n keyValues,\n success,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\n/** A deployment row, as the data API hands it back (camel or snake columns). */\nexport interface DeploymentRow {\n id: string | number;\n status?: string;\n createdAt?: string | Date;\n created_at?: string | Date;\n finishedAt?: string | Date;\n finished_at?: string | Date;\n imageUrl?: string;\n image_url?: string;\n rollbackOf?: string;\n rollback_of?: string;\n triggeredBy?: string;\n triggered_by?: string;\n triggerSource?: string;\n trigger_source?: string;\n triggeredByUserId?: string;\n triggered_by_user_id?: string;\n gitCommitHash?: string;\n gitCommitMessage?: string;\n}\n\nfunction str(dep: DeploymentRow, camel: keyof DeploymentRow, snake: keyof DeploymentRow): string | null {\n const raw = (dep[camel] ?? dep[snake]) as unknown;\n return typeof raw === \"string\" && raw.trim() !== \"\" ? raw.trim() : null;\n}\n\nfunction isoOf(dep: DeploymentRow, camel: keyof DeploymentRow, snake: keyof DeploymentRow): string | null {\n const raw = (dep[camel] ?? dep[snake]) as unknown;\n if (raw instanceof Date) return Number.isNaN(raw.getTime()) ? null : raw.toISOString();\n return typeof raw === \"string\" && raw.trim() !== \"\" ? raw.trim() : null;\n}\n\nexport function deploymentImage(dep: DeploymentRow): string | null {\n return str(dep, \"imageUrl\", \"image_url\");\n}\n\n/**\n * The backend's rule EXACTLY: a rollback is honoured only for a successful\n * deploy that recorded an image. Any other row 409s `deploy_not_rollbackable`.\n */\nexport function isRollbackable(dep: DeploymentRow): boolean {\n return dep.status === \"success\" && deploymentImage(dep) !== null;\n}\n\n/** finishedAt − createdAt in ms, or null (still running / missing / skewed). */\nexport function deploymentDurationMs(dep: DeploymentRow): number | null {\n const created = isoOf(dep, \"createdAt\", \"created_at\");\n const finished = isoOf(dep, \"finishedAt\", \"finished_at\");\n if (!created || !finished) return null;\n const a = new Date(created).getTime();\n const b = new Date(finished).getTime();\n if (Number.isNaN(a) || Number.isNaN(b)) return null;\n const ms = b - a;\n return ms >= 0 ? ms : null;\n}\n\nfunction formatDuration(ms: number): string {\n const totalSec = Math.max(0, Math.round(ms / 1000));\n if (totalSec < 60) return `${totalSec}s`;\n const m = Math.floor(totalSec / 60);\n const s = totalSec % 60;\n if (m < 60) return s ? `${m}m ${s}s` : `${m}m`;\n const h = Math.floor(m / 60);\n const mm = m % 60;\n return mm ? `${h}h ${mm}m` : `${h}h`;\n}\n\nconst TRIGGERED_BY = [\"user\", \"automation\", \"unknown\"] as const;\nconst TRIGGER_SOURCES = [\"console\", \"cli\", \"webhook\", \"unknown\"] as const;\n\nexport function triggerInfo(dep: DeploymentRow): { by: string; source: string; userId: string } {\n const byRaw = (dep.triggeredBy ?? dep.triggered_by) as unknown;\n const srcRaw = (dep.triggerSource ?? dep.trigger_source) as unknown;\n const by = typeof byRaw === \"string\" && (TRIGGERED_BY as readonly string[]).includes(byRaw) ? byRaw : \"unknown\";\n const source =\n typeof srcRaw === \"string\" && (TRIGGER_SOURCES as readonly string[]).includes(srcRaw) ? srcRaw : \"unknown\";\n return { by, source, userId: str(dep, \"triggeredByUserId\", \"triggered_by_user_id\") ?? \"\" };\n}\n\n/** Shape one deployment row into the stable JSON view the CLI publishes. */\nexport function deploymentView(dep: DeploymentRow): Record<string, unknown> {\n const durationMs = deploymentDurationMs(dep);\n return {\n id: String(dep.id),\n status: dep.status ?? null,\n createdAt: isoOf(dep, \"createdAt\", \"created_at\"),\n finishedAt: isoOf(dep, \"finishedAt\", \"finished_at\"),\n durationMs,\n image: deploymentImage(dep),\n rollbackOf: str(dep, \"rollbackOf\", \"rollback_of\"),\n isRollback: str(dep, \"rollbackOf\", \"rollback_of\") !== null,\n rollbackable: isRollbackable(dep),\n trigger: triggerInfo(dep),\n commit: {\n hash: str(dep, \"gitCommitHash\", \"gitCommitHash\"),\n message: str(dep, \"gitCommitMessage\", \"gitCommitMessage\")\n }\n };\n}\n\nasync function fetchDeployments(client: CloudClient, projectId: string, limit = 100): Promise<DeploymentRow[]> {\n const res = await client.data.collection(\"deployments\").find({\n where: { project: [\"==\", projectId] },\n orderBy: [\"createdAt\", \"desc\"],\n limit\n });\n return res.data as unknown as DeploymentRow[];\n}\n\nexport async function deploymentsListCommand(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n try {\n const rows = await fetchDeployments(client, projectId);\n const views = rows.map(deploymentView);\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🚀 Deployments — project ${projectRef}`));\n console.log(\"\");\n if (!views.length) {\n console.log(chalk.gray(\" No deployments yet. Deploy with `rebase cloud deploy`.\"));\n console.log(\"\");\n return;\n }\n for (const v of views) {\n const dur = v.durationMs !== null ? formatDuration(v.durationMs as number) : chalk.gray(\"running\");\n const trig = (v.trigger as { source: string }).source;\n const roll = v.rollbackable ? chalk.green(\" ↺ rollbackable\") : \"\";\n console.log(\n ` ${chalk.gray(`[${v.id}]`)} ${colorStatus(v.status as string)} ${chalk.gray(String(v.createdAt ?? \"—\"))} ${dur} ${chalk.gray(trig)}${roll}`\n );\n }\n console.log(\"\");\n },\n { projectId, deployments: views }\n );\n } catch (e) {\n reportError(e, \"Failed to list deployments\");\n }\n}\n\nexport async function rollbackCommand(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n // `rollback [deploymentId]` — the id, when given, is the first operand after\n // the `rollback` group token.\n const explicitId = cloudPositionals(rawArgs).slice(1)[0];\n\n // Fetch history — the only step here that can fail with a server error.\n let rows: DeploymentRow[];\n try {\n rows = await fetchDeployments(client, projectId);\n } catch (e) {\n reportError(e, \"Failed to read deployment history\");\n }\n if (!rows!.length) fail(\"No deployments to roll back to.\", undefined, \"no_deployments\");\n\n // Select + validate the target OUTSIDE any catch — a refusal here is a\n // deliberate exit, never a server error to re-wrap.\n let target: DeploymentRow | undefined;\n if (explicitId) {\n target = rows!.find((d) => String(d.id) === explicitId);\n if (!target) fail(`Deployment ${explicitId} not found for project ${projectRef}.`, undefined, \"not_found\");\n // Refuse locally rather than let the server 409 — this is the safety\n // contract, mirrored from the backend's rollback rule.\n if (!isRollbackable(target!)) {\n fail(\n `Deployment ${explicitId} is not rollbackable (needs a successful deploy that recorded an image).`,\n \"List candidates with `rebase cloud deployments list`.\",\n \"deploy_not_rollbackable\"\n );\n }\n } else {\n const rollbackable = rows!.filter(isRollbackable);\n if (!rollbackable.length) {\n fail(\n \"No rollbackable deployment found (needs a successful deploy that recorded an image).\",\n \"List history with `rebase cloud deployments list`.\",\n \"deploy_not_rollbackable\"\n );\n }\n // Prefer the previous good image when the newest deploy is itself good\n // (rolling back to the live image is a no-op); otherwise the most recent\n // good one.\n target = rollbackable.find((d) => String(d.id) !== String(rows![0].id)) ?? rollbackable[0];\n }\n\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Roll project ${projectRef} back to deployment ${target!.id}? This starts a new deployment.`\n });\n\n try {\n const res = await client.functions.invoke<{\n success: boolean;\n deployment: { id: string };\n rolledBackTo: string;\n imageUrl: string;\n }>(\"deploy\", { projectId, deploymentId: String(target!.id), client: \"cli\" }, { path: \"rollback\" });\n\n emit(\n () => {\n success(`Rolling back to deployment ${chalk.bold(String(target!.id))}`);\n keyValues([\n [\"New deployment\", res.deployment?.id ? String(res.deployment.id) : undefined],\n [\"Rolled back to\", res.rolledBackTo],\n [\"Image\", res.imageUrl]\n ]);\n console.log(chalk.gray(\" Follow it with `rebase cloud logs -f`.\"));\n console.log(\"\");\n },\n {\n success: true,\n deploymentId: res.deployment?.id ?? null,\n rolledBackTo: res.rolledBackTo,\n imageUrl: res.imageUrl\n }\n );\n } catch (e) {\n reportError(e, \"Failed to roll back\");\n }\n}\n\nexport async function cancelCommand(rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n const explicitId = cloudPositionals(rawArgs).slice(1)[0];\n\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `Cancel the in-flight build for project ${projectRef}?`\n });\n\n try {\n const res = await client.functions.invoke<{ success: boolean; deploymentId: string; buildJobDeleted: boolean }>(\n \"deploy\",\n explicitId ? { projectId, deploymentId: explicitId } : { projectId },\n { path: \"cancel\" }\n );\n emit(\n () => {\n success(`Cancelled deployment ${chalk.bold(res.deploymentId)}`);\n if (res.buildJobDeleted) console.log(chalk.gray(\" The build job was deleted.\"));\n console.log(\"\");\n },\n { success: true, deploymentId: res.deploymentId, buildJobDeleted: res.buildJobDeleted }\n );\n } catch (e) {\n const err = e as { status?: number };\n if (err?.status === 404) {\n fail(\"No deployment in progress to cancel.\", undefined, \"not_found\");\n }\n reportError(e, \"Failed to cancel deployment\");\n }\n}\n","/**\n * `rebase cloud start | stop | restart` — power operations.\n *\n * These flip the project's `status`, exactly as the console's `handleServerAction`\n * does: stop → `stopped`, start → `active`, restart → stop then start with a\n * brief pause in between (a real stop→start with genuine downtime). Stop and\n * restart cause downtime, so they require `--yes` in non-interactive use.\n */\nimport arg from \"arg\";\nimport { requireClient, requireProject, displayProjectRef, emit, confirmDestructive, success, reportError, type CloudClient } from \"./context\";\n\ntype PowerAction = \"start\" | \"stop\" | \"restart\";\n\nasync function setStatus(client: CloudClient, projectId: string, status: \"active\" | \"stopped\"): Promise<void> {\n await client.data.collection(\"projects\").update(projectId, { status });\n}\n\nexport async function powerCommand(action: PowerAction, rawArgs: string[]): Promise<void> {\n const args = arg({ \"--yes\": Boolean, \"-y\": \"--yes\", \"--project\": String, \"-p\": \"--project\" }, { argv: rawArgs.slice(2), permissive: true });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const projectRef = displayProjectRef(rawArgs);\n\n // start is benign; stop and restart cause downtime and are gated.\n if (action !== \"start\") {\n await confirmDestructive({\n yes: Boolean(args[\"--yes\"]),\n prompt: `${action === \"stop\" ? \"Stop\" : \"Restart\"} project ${projectRef}? This causes downtime.`\n });\n }\n\n try {\n if (action === \"stop\") {\n await setStatus(client, projectId, \"stopped\");\n emit(() => success(`Stopped project ${projectRef}`), { success: true, projectId, status: \"stopped\" });\n } else if (action === \"start\") {\n await setStatus(client, projectId, \"active\");\n emit(() => success(`Started project ${projectRef}`), { success: true, projectId, status: \"active\" });\n } else {\n await setStatus(client, projectId, \"stopped\");\n await new Promise((r) => setTimeout(r, 1500));\n await setStatus(client, projectId, \"active\");\n emit(() => success(`Restarted project ${projectRef}`), { success: true, projectId, status: \"active\" });\n }\n } catch (e) {\n reportError(e, `Failed to ${action} project`);\n }\n}\n\nexport function isPowerAction(v: string | undefined): v is PowerAction {\n return v === \"start\" || v === \"stop\" || v === \"restart\";\n}\n","/**\n * `rebase cloud` resource subcommands: status, metrics, webhooks, storage,\n * clusters, billing.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport {\n requireClient,\n requireProject,\n lookupProjectId,\n displayProjectRef,\n getContextOrg,\n readLink,\n colorStatus,\n keyValues,\n fetchTenantBaseDomain,\n projectHost,\n openUrl,\n success,\n fail,\n reportError\n} from \"./context\";\nimport { firstRow, latestDeployment, fmtDate } from \"./projects\";\n\n/* ─── status: quick project dashboard ──────────────────────────── */\n\nexport async function statusCommand(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n try {\n const project = (await client.data.collection(\"projects\").findById(projectId)) as\n | { id: string | number; name?: string; subdomain?: string; host?: string; status?: string; gitBranch?: string }\n | undefined;\n if (!project) fail(`Project ${displayProjectRef(rawArgs)} not found.`);\n\n const [db, storage, deploy, baseDomain] = await Promise.all([\n firstRow(client, \"databases\", projectId),\n firstRow(client, \"storages\", projectId),\n latestDeployment(client, projectId),\n fetchTenantBaseDomain(client, url)\n ]);\n\n console.log(\"\");\n console.log(` ${chalk.bold(project.name ?? project.subdomain ?? \"\")} ${chalk.gray(`[${project.subdomain ?? displayProjectRef(rawArgs)}]`)} ${colorStatus(project.status)}`);\n console.log(\"\");\n keyValues([\n [\"URL\", projectHost(project, baseDomain)],\n [\"Branch\", project.gitBranch],\n [\"Last deploy\", deploy ? `${colorStatus(deploy.status)} · ${fmtDate(deploy.createdAt)}` : \"never\"],\n [\"Database\", db ? `${db.type} (${colorStatus(db.connectionStatus as string)})` : \"none\"],\n [\"Storage\", storage ? `${storage.type} (${colorStatus(storage.status as string)})` : \"none\"]\n ]);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to load status\");\n }\n}\n\n/* ─── metrics: live compute metrics ────────────────────────────── */\n\nexport async function metricsCommand(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n try {\n const m = await client.functions.invoke<{\n status?: string;\n cpu?: string;\n memory?: string;\n memoryPercent?: string;\n disk?: string;\n }>(\"metrics\", undefined, { method: \"GET\",\npath: projectId });\n\n console.log(\"\");\n console.log(chalk.bold(` 📊 Metrics — project ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n keyValues([\n [\"Status\", m.status ? colorStatus(m.status === \"running\" ? \"active\" : m.status) : undefined],\n [\"CPU\", m.cpu],\n [\"Memory\", m.memory ? `${m.memory}${m.memoryPercent ? ` (${m.memoryPercent})` : \"\"}` : undefined],\n [\"Disk\", m.disk]\n ]);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to fetch metrics\");\n }\n}\n\n/* ─── webhooks ─────────────────────────────────────────────────── */\n\nexport async function webhooksCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n try {\n if (subcommand === \"create\") {\n const args = arg(\n { \"--name\": String,\n\"--table\": String,\n\"--url\": String,\n\"--events\": String },\n { argv: rawArgs.slice(4),\npermissive: true }\n );\n const name = args[\"--name\"] || fail(\"--name is required.\");\n const table = args[\"--table\"] || fail(\"--table is required.\");\n const url = args[\"--url\"] || fail(\"--url (endpoint) is required.\");\n const events = (args[\"--events\"] || \"insert,update,delete\").split(\",\").map((s) => s.trim());\n\n const created = (await client.data.collection(\"webhooks\").create({\n project: projectId,\n name,\n table,\n url,\n events,\n enabled: true\n })) as unknown as { id: string | number };\n success(`Created webhook ${chalk.bold(name)} [${created.id}]`);\n return;\n }\n\n if (subcommand === \"delete\") {\n const id = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[2];\n if (!id) fail(\"Usage: rebase cloud webhooks delete <id>\");\n await client.data.collection(\"webhooks\").delete(id);\n success(`Deleted webhook ${id}`);\n return;\n }\n\n // list\n const hooks = (await client.data.collection(\"webhooks\").find({\n where: { project: [\"==\", projectId] },\n limit: 100\n })).data as unknown as Array<{ id: string | number; name?: string; table?: string; url?: string; enabled?: boolean; events?: string[] }>;\n\n console.log(\"\");\n console.log(chalk.bold(` 🔗 Webhooks — project ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n if (hooks.length === 0) {\n console.log(chalk.gray(\" No webhooks. Add one with `rebase cloud webhooks create`.\"));\n console.log(\"\");\n return;\n }\n for (const h of hooks) {\n const state = h.enabled ? chalk.green(\"enabled\") : chalk.gray(\"disabled\");\n console.log(` ${chalk.bold(h.name ?? \"(unnamed)\")} ${chalk.gray(`[${h.id}]`)} ${state}`);\n console.log(` ${chalk.gray(`${h.table ?? \"?\"} → ${h.url ?? \"?\"} (${(h.events ?? []).join(\", \")})`)}`);\n }\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Webhook operation failed\");\n }\n}\n\n/* ─── storage ──────────────────────────────────────────────────── */\n\nexport async function storageCommand(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n try {\n const stores = (await client.data.collection(\"storages\").find({\n where: { project: [\"==\", projectId] },\n limit: 50\n })).data as unknown as Array<{ id: string | number; type?: string; provider?: string; bucketName?: string; status?: string }>;\n\n console.log(\"\");\n console.log(chalk.bold(` 🪣 Storage — project ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n if (stores.length === 0) {\n console.log(chalk.gray(\" No storage buckets attached.\"));\n console.log(\"\");\n return;\n }\n for (const s of stores) {\n console.log(` ${chalk.bold(s.bucketName ?? s.type ?? \"bucket\")} ${chalk.gray(`[${s.id}]`)} ${colorStatus(s.status)}`);\n keyValues([[\"Provider\", s.provider], [\"Type\", s.type]]);\n }\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list storage\");\n }\n}\n\n/* ─── clusters ─────────────────────────────────────────────────── */\n\nexport async function clustersCommand(rawArgs: string[]): Promise<void> {\n const { client } = await requireClient(rawArgs);\n try {\n const clusters = (await client.data.collection(\"clusters\").find({ limit: 100 })).data as unknown as Array<{\n id: string | number;\n name?: string;\n provider?: string;\n region?: string;\n status?: string;\n }>;\n\n console.log(\"\");\n console.log(chalk.bold(\" ☸ Clusters\"));\n console.log(\"\");\n if (clusters.length === 0) {\n console.log(chalk.gray(\" No clusters registered.\"));\n console.log(\"\");\n return;\n }\n for (const c of clusters) {\n console.log(` ${chalk.bold(c.name ?? \"(unnamed)\")} ${chalk.gray(`[${c.id}]`)} ${colorStatus(c.status)}`);\n keyValues([[\"Provider\", c.provider], [\"Region\", c.region]]);\n }\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to list clusters\");\n }\n}\n\n/* ─── billing ──────────────────────────────────────────────────── */\n\nexport async function billingCommand(rawArgs: string[]): Promise<void> {\n const { client, url } = await requireClient(rawArgs);\n const org = getContextOrg(url);\n\n const action = rawArgs.slice(3).filter((a) => !a.startsWith(\"-\"))[1];\n\n // `rebase cloud billing setup` — attach a card to the org (one-time, opens a\n // browser). Once done, project create/deploy work headlessly (off_session).\n if (action === \"setup\") {\n if (!org) fail(\"No active organization.\", \"Run `rebase cloud use` first.\");\n try {\n const res = await client.functions.invoke<{ url?: string; simulated?: boolean }>(\n \"stripe-billing\",\n { organizationId: org },\n { path: \"setup-session\" }\n );\n if (!res.url) fail(\"Could not start billing setup.\");\n openUrl(res.url, \"Add a payment method in your browser:\");\n if (res.simulated) {\n console.log(chalk.gray(\" (dev mode — Stripe not configured; complete setup from the console)\"));\n console.log(\"\");\n } else {\n console.log(chalk.gray(\" Once you've added a card, `rebase cloud deploy` runs without further prompts.\"));\n console.log(\"\");\n }\n } catch (e) {\n reportError(e, \"Failed to start billing setup\");\n }\n return;\n }\n\n // `rebase cloud billing checkout --project <slug>` opens a Stripe session.\n if (action === \"checkout\") {\n const projectId = await requireProject(rawArgs, client);\n try {\n const res = await client.functions.invoke<{ url?: string }>(\n \"stripe-billing\",\n { projectId },\n { path: \"session\" }\n );\n if (!res.url) fail(\"Billing session could not be created.\");\n console.log(\"\");\n console.log(\" Complete checkout in your browser:\");\n console.log(` ${chalk.cyan(res.url)}`);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to start checkout\");\n }\n return;\n }\n\n // default: show the active org's billing account.\n if (!org) fail(\"No active organization.\", \"Run `rebase cloud use` first.\");\n try {\n const orgRow = (await client.data.collection(\"organizations\").findById(org)) as\n | { billing_account_id?: string | number; billingAccount?: string | number }\n | undefined;\n const billingId = orgRow?.billing_account_id ?? orgRow?.billingAccount;\n if (!billingId) {\n console.log(\"\");\n console.log(chalk.gray(` Organization ${org} has no billing account yet.`));\n console.log(\"\");\n return;\n }\n const acct = (await client.data.collection(\"billing-accounts\").findById(billingId)) as\n | { id: string | number; billingEmail?: string; status?: string; stripeCustomerId?: string }\n | undefined;\n\n // Card-on-file lives in Stripe; the control plane reports it for us.\n let card: { hasPaymentMethod?: boolean; brand?: string; last4?: string; expMonth?: number; expYear?: number } = {};\n try {\n card = await client.functions.invoke<typeof card>(\n \"stripe-billing\",\n undefined,\n { method: \"GET\",\npath: `payment-method/${org}` }\n );\n } catch {\n // status endpoint optional — fall back to the local account record\n }\n\n // Best-effort: show which plan the linked/`--project` project is on.\n // BYO-cluster projects pay a flat platform fee; the rest pay managed compute.\n let plan: string | undefined;\n try {\n const parsed = arg({ \"--project\": String,\n\"-p\": \"--project\" }, { argv: rawArgs.slice(2),\npermissive: true });\n const ref = parsed[\"--project\"] || readLink()?.projectId;\n const projectId = ref ? await lookupProjectId(ref, client) : undefined;\n if (projectId) {\n const proj = (await client.data.collection(\"projects\").findById(projectId)) as\n | { cluster_id?: string | number; cluster?: unknown; provider?: string; vmSize?: string }\n | undefined;\n const hasCluster = proj?.cluster_id != null || proj?.cluster != null;\n plan = hasCluster ? \"platform fee (own cluster)\" : \"managed compute\";\n\n // Best-effort: append the resolved monthly amount from Stripe (via\n // the control plane's /api/functions/pricing). Keep working if the\n // endpoint is unreachable — the label alone is still useful.\n try {\n const pricing = await client.functions.invoke<{\n items: Array<{ lookupKey: string; amountEur: number }>;\n }>(\"pricing\", undefined, { method: \"GET\" });\n const key = hasCluster\n ? \"platform_byo\"\n : `compute_${proj?.provider || \"hetzner\"}_${proj?.vmSize || \"cx21\"}`;\n const item = pricing.items?.find((i) => i.lookupKey === key);\n if (item) plan = `${plan} — €${item.amountEur.toFixed(2)}/mo`;\n } catch {\n // pricing endpoint unreachable — keep the plan label without an amount\n }\n }\n } catch {\n // no linked/resolvable project — skip the Plan line\n }\n\n console.log(\"\");\n console.log(chalk.bold(` 💳 Billing — org ${org}`));\n console.log(\"\");\n keyValues([\n [\"Account\", acct ? String(acct.id) : undefined],\n [\"Email\", acct?.billingEmail],\n [\"Status\", acct?.status ? colorStatus(acct.status) : undefined],\n [\"Plan\", plan],\n [\n \"Payment method\",\n card.hasPaymentMethod\n ? `${card.brand ?? \"card\"} •••• ${card.last4 ?? \"????\"}${card.expMonth ? ` (exp ${card.expMonth}/${card.expYear})` : \"\"}`\n : chalk.yellow(\"none — run `rebase cloud billing setup`\")\n ]\n ]);\n console.log(\"\");\n } catch (e) {\n reportError(e, \"Failed to load billing\");\n }\n}\n","/**\n * CLI command: `rebase cloud <group> [action] [options]`\n *\n * A single entry point for everything you do against Rebase Cloud — the hosted\n * control plane. Auth, project link, deploys, databases, and the rest are all\n * dispatched from here. Individual groups live in sibling modules; this file\n * only routes and prints help.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { loginCommand, logoutCommand, whoamiCommand } from \"./auth\";\nimport { linkCommand, unlinkCommand, selectOrgCommand, openCommand } from \"./link\";\nimport { listProjects, createProject, projectInfo, deleteProject } from \"./projects\";\nimport { deployCommand, logsCommand } from \"./deploy\";\nimport { orgsCommand } from \"./orgs\";\nimport { dbCommand } from \"./databases\";\nimport { envCommand } from \"./env\";\nimport { domainsCommand } from \"./domains\";\nimport { extensionsCommand } from \"./extensions\";\nimport { settingsCommand } from \"./settings\";\nimport { deploymentsListCommand, rollbackCommand, cancelCommand } from \"./deployments\";\nimport { powerCommand } from \"./power\";\nimport {\n statusCommand,\n metricsCommand,\n webhooksCommand,\n storageCommand,\n clustersCommand,\n billingCommand\n} from \"./resources\";\nimport { requireProjectRef, initOutputMode } from \"./context\";\n\n/** Positional tokens after `rebase cloud` (group, action, …). */\nfunction positionals(rawArgs: string[]): string[] {\n return arg({}, { argv: rawArgs.slice(3),\npermissive: true })._;\n}\n\nexport async function cloudCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // Latch the output mode FIRST — before anything can print or `fail` — so the\n // whole command family agrees on human vs. machine-readable output.\n initOutputMode(rawArgs);\n\n const pos = positionals(rawArgs);\n const group = subcommand && subcommand !== \"--help\" ? subcommand : pos[0];\n const action = pos[1];\n\n if (!group || subcommand === \"--help\") {\n printCloudHelp();\n return;\n }\n\n switch (group) {\n /* auth */\n case \"login\":\n await loginCommand(rawArgs);\n break;\n case \"logout\":\n await logoutCommand(rawArgs);\n break;\n case \"whoami\":\n await whoamiCommand(rawArgs);\n break;\n\n /* context / link */\n case \"link\":\n await linkCommand(rawArgs);\n break;\n case \"unlink\":\n unlinkCommand();\n break;\n case \"use\":\n await selectOrgCommand(rawArgs);\n break;\n case \"open\":\n openCommand(rawArgs);\n break;\n\n /* projects */\n case \"projects\":\n case \"project\":\n await projectsGroup(action, rawArgs);\n break;\n\n /* deploy + logs (operate on linked/--project) */\n case \"deploy\":\n await deployCommand(rawArgs, requireProjectRef(rawArgs));\n break;\n case \"logs\":\n await logsCommand(rawArgs, requireProjectRef(rawArgs));\n break;\n case \"deployments\":\n case \"releases\":\n await deploymentsGroup(action, rawArgs);\n break;\n case \"rollback\":\n await rollbackCommand(rawArgs);\n break;\n case \"cancel\":\n await cancelCommand(rawArgs);\n break;\n case \"start\":\n case \"stop\":\n case \"restart\":\n await powerCommand(group, rawArgs);\n break;\n case \"status\":\n await statusCommand(rawArgs);\n break;\n case \"metrics\":\n await metricsCommand(rawArgs);\n break;\n\n /* env / domains / extensions / settings */\n case \"env\":\n await envCommand(action, rawArgs);\n break;\n case \"domains\":\n case \"domain\":\n await domainsCommand(action, rawArgs);\n break;\n case \"extensions\":\n case \"extension\":\n await extensionsCommand(action, rawArgs);\n break;\n case \"settings\":\n await settingsCommand(action, rawArgs);\n break;\n\n /* orgs */\n case \"orgs\":\n case \"org\":\n await orgsCommand(action, rawArgs);\n break;\n\n /* databases */\n case \"db\":\n case \"database\":\n await dbCommand(action, rawArgs);\n break;\n\n /* other resources */\n case \"webhooks\":\n await webhooksCommand(action, rawArgs);\n break;\n case \"storage\":\n await storageCommand(rawArgs);\n break;\n case \"clusters\":\n await clustersCommand(rawArgs);\n break;\n case \"billing\":\n await billingCommand(rawArgs);\n break;\n\n default:\n console.error(chalk.red(`Unknown cloud command: ${group}`));\n console.log(\"\");\n printCloudHelp();\n process.exit(1);\n }\n}\n\nasync function projectsGroup(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case undefined:\n await listProjects(rawArgs);\n break;\n case \"create\":\n await createProject(rawArgs);\n break;\n case \"info\": {\n const id = positionals(rawArgs)[2] || requireProjectRef(rawArgs);\n await projectInfo(rawArgs, id);\n break;\n }\n case \"delete\": {\n const id = positionals(rawArgs)[2] || requireProjectRef(rawArgs);\n await deleteProject(rawArgs, id);\n break;\n }\n case \"--help\":\n printCloudHelp();\n break;\n default:\n console.error(chalk.red(`Unknown projects command: ${action}`));\n process.exit(1);\n }\n}\n\nasync function deploymentsGroup(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case \"list\":\n case undefined:\n await deploymentsListCommand(rawArgs);\n break;\n case \"--help\":\n printCloudHelp();\n break;\n default:\n console.error(chalk.red(`Unknown deployments command: ${action}`));\n process.exit(1);\n }\n}\n\nfunction printCloudHelp(): void {\n console.log(`\n${chalk.bold(\"rebase cloud\")} — Manage your apps on Rebase Cloud\n\n${chalk.green.bold(\"Usage\")}\n rebase cloud ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Auth\")}\n ${chalk.blue.bold(\"login\")} Sign in to the control plane\n ${chalk.blue.bold(\"logout\")} Sign out\n ${chalk.blue.bold(\"whoami\")} Show the current session\n\n${chalk.green.bold(\"Project link\")}\n ${chalk.blue.bold(\"link\")} Link this directory to a cloud project\n ${chalk.blue.bold(\"unlink\")} Remove the link\n ${chalk.blue.bold(\"use\")} ${chalk.gray(\"[org]\")} Select the active organization\n ${chalk.blue.bold(\"open\")} Open the dashboard in a browser\n\n${chalk.green.bold(\"Projects\")}\n ${chalk.blue.bold(\"projects list\")} List projects\n ${chalk.blue.bold(\"projects create\")} Create a project ${chalk.gray(\"(--link to link it)\")}\n ${chalk.blue.bold(\"projects info\")} ${chalk.gray(\"[id]\")} Show project details\n ${chalk.blue.bold(\"projects delete\")} ${chalk.gray(\"[id]\")} Delete a project\n\n${chalk.green.bold(\"Deploy & observe\")}\n ${chalk.blue.bold(\"deploy\")} ${chalk.gray(\"[--source .]\")} Deploy the linked project + stream build logs\n ${chalk.blue.bold(\"logs\")} ${chalk.gray(\"[--runtime] [-f]\")} Show build (or runtime) logs\n ${chalk.blue.bold(\"deployments list\")} Deployment history ${chalk.gray(\"(status, duration, trigger)\")}\n ${chalk.blue.bold(\"rollback\")} ${chalk.gray(\"[id] [-y]\")} Roll back to a successful deploy\n ${chalk.blue.bold(\"cancel\")} ${chalk.gray(\"[-y]\")} Cancel the in-flight build\n ${chalk.blue.bold(\"start|stop|restart\")} ${chalk.gray(\"[-y]\")} Power ops ${chalk.gray(\"(stop/restart need -y)\")}\n ${chalk.blue.bold(\"status\")} One-glance project status\n ${chalk.blue.bold(\"metrics\")} Live CPU / memory / disk\n\n${chalk.green.bold(\"Config\")}\n ${chalk.blue.bold(\"env list|set|unset|reveal|pull\")}\n ${chalk.blue.bold(\"domains list|add|verify|remove\")}\n ${chalk.blue.bold(\"extensions list|enable|disable\")}\n ${chalk.blue.bold(\"settings show|set\")} Name / branch / repo / subdomain\n\n${chalk.green.bold(\"Organizations\")}\n ${chalk.blue.bold(\"orgs list|create|members\")}\n\n${chalk.green.bold(\"Databases\")}\n ${chalk.blue.bold(\"db list|create|info|test\")}\n ${chalk.blue.bold(\"db backup list|create|restore|status|download\")}\n ${chalk.blue.bold(\"db pitr status|restore|cutover|discard\")}\n\n${chalk.green.bold(\"Other resources\")}\n ${chalk.blue.bold(\"webhooks list|create|delete\")}\n ${chalk.blue.bold(\"storage\")} List storage buckets\n ${chalk.blue.bold(\"clusters\")} List compute clusters\n ${chalk.blue.bold(\"billing setup\")} Attach a card to the org ${chalk.gray(\"(one-time, opens browser)\")}\n ${chalk.blue.bold(\"billing\")} Show billing account + card on file\n\n${chalk.green.bold(\"Global options\")}\n ${chalk.blue(\"--json\")} Machine-readable output ${chalk.gray(\"(also when piped, or REBASE_JSON=1)\")}\n ${chalk.blue(\"--url <origin>\")} Target a specific control plane ${chalk.gray(\"(or REBASE_CLOUD_URL)\")}\n ${chalk.blue(\"--project, -p <id>\")} Operate on a project without linking\n\n${chalk.gray(\"Most commands act on the linked project (.rebase/cloud.json) unless --project is given.\")}\n${chalk.gray(\"Docs: https://rebase.pro/docs\")}\n`);\n}\n","import chalk from \"chalk\";\nimport arg from \"arg\";\nimport { createRebaseApp } from \"./commands/init\";\nimport { generateSdkCommand } from \"./commands/generate_sdk\";\nimport { schemaCommand } from \"./commands/schema\";\nimport { dbCommand } from \"./commands/db\";\nimport { devCommand } from \"./commands/dev\";\nimport { buildCommand } from \"./commands/build\";\nimport { startCommand } from \"./commands/start\";\nimport { authCommand } from \"./commands/auth\";\nimport { doctorCommand } from \"./commands/doctor\";\nimport { skillsCommand } from \"./commands/skills\";\nimport { apiKeysCommand } from \"./commands/api-keys\";\nimport { cloudCommand } from \"./commands/cloud\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nfunction getVersion(): string {\n try {\n // Try to read version from package.json\n const pkgPath = path.resolve(__dirname, \"../package.json\");\n if (fs.existsSync(pkgPath)) {\n return JSON.parse(fs.readFileSync(pkgPath, \"utf-8\")).version;\n }\n } catch {\n // ignore\n }\n return \"unknown\";\n}\n\nexport async function entry(args: string[]) {\n const parsedArgs = arg(\n {\n \"--version\": Boolean,\n \"--help\": Boolean,\n \"-v\": \"--version\",\n \"-h\": \"--help\"\n },\n {\n argv: args.slice(2),\n permissive: true\n }\n );\n\n if (parsedArgs[\"--version\"]) {\n console.log(getVersion());\n return;\n }\n\n const command = parsedArgs._[0];\n const subcommand = parsedArgs._[1];\n\n // Show global help only when no command given, or --help with no recognized command\n const namespacedCommands = [\"schema\", \"db\", \"dev\", \"build\", \"start\", \"auth\", \"doctor\", \"skills\", \"api-keys\", \"cloud\"];\n if (!command || (parsedArgs[\"--help\"] && !namespacedCommands.includes(command))) {\n printHelp();\n return;\n }\n\n // For namespaced commands with --help, pass it through as subcommand\n const effectiveSubcommand = parsedArgs[\"--help\"] ? \"--help\" : subcommand;\n\n switch (command) {\n case \"init\":\n await createRebaseApp(args);\n break;\n\n case \"generate-sdk\": {\n const sdkArgs = arg(\n {\n \"--collections-dir\": String,\n \"--output\": String,\n \"-c\": \"--collections-dir\",\n \"-o\": \"--output\"\n },\n {\n argv: args.slice(3),\n permissive: true\n }\n );\n await generateSdkCommand({\n collectionsDir: sdkArgs[\"--collections-dir\"] || \"./config/collections\",\n output: sdkArgs[\"--output\"] || \"./generated/sdk\",\n cwd: process.cwd()\n });\n break;\n }\n\n case \"schema\":\n await schemaCommand(effectiveSubcommand, args);\n break;\n\n case \"db\":\n await dbCommand(effectiveSubcommand, args);\n break;\n\n case \"dev\":\n await devCommand(args);\n break;\n\n case \"build\":\n await buildCommand();\n break;\n\n case \"start\":\n await startCommand();\n break;\n\n case \"auth\":\n await authCommand(effectiveSubcommand, args);\n break;\n\n case \"doctor\":\n await doctorCommand(args);\n break;\n\n case \"skills\":\n await skillsCommand(effectiveSubcommand, args);\n break;\n\n case \"api-keys\":\n await apiKeysCommand(effectiveSubcommand, args);\n break;\n\n case \"cloud\":\n await cloudCommand(effectiveSubcommand, args);\n break;\n\n default:\n console.error(chalk.red(`Unknown command: ${command}`));\n console.log(\"\");\n printHelp();\n // A mistyped command must not look like success to a shell or CI.\n process.exit(1);\n }\n}\n\nfunction printHelp() {\n console.log(`\n${chalk.bold(\"Rebase CLI\")} — Developer tools for Rebase projects\n\n${chalk.green.bold(\"Usage\")}\n rebase ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"init\")} Create a new Rebase project\n ${chalk.blue.bold(\"dev\")} Start the development server\n ${chalk.blue.bold(\"build\")} Build all workspace packages\n ${chalk.blue.bold(\"start\")} Start the backend server ${chalk.gray(\"(production)\")}\n\n${chalk.green.bold(\"Schema\")}\n ${chalk.blue.bold(\"schema generate\")} Generate Drizzle schema from collections\n ${chalk.blue.bold(\"schema introspect\")} Introspect database → Rebase collections\n ${chalk.blue.bold(\"schema\")} ${chalk.gray(\"--help\")} Show schema command help\n\n${chalk.green.bold(\"Database\")}\n ${chalk.blue.bold(\"db push\")} Apply schema directly to database ${chalk.gray(\"(dev)\")}\n ${chalk.blue.bold(\"db generate\")} Generate SQL migration files\n ${chalk.blue.bold(\"db migrate\")} Run pending migrations\n ${chalk.blue.bold(\"db\")} ${chalk.gray(\"--help\")} Show database command help\n\n${chalk.green.bold(\"SDK\")}\n ${chalk.blue.bold(\"generate-sdk\")} Generate a typed TypeScript SDK from collections\n\n${chalk.green.bold(\"Auth\")}\n ${chalk.blue.bold(\"auth reset-password\")} Reset a user's password\n ${chalk.blue.bold(\"auth\")} ${chalk.gray(\"--help\")} Show auth command help\n\n${chalk.green.bold(\"Diagnostics\")}\n ${chalk.blue.bold(\"doctor\")} Detect schema drift between collections, schema, and DB\n\n${chalk.green.bold(\"AI Agent Skills\")}\n ${chalk.blue.bold(\"skills install\")} Install Rebase agent skills for your AI coding assistant\n\n${chalk.green.bold(\"API Keys\")}\n ${chalk.blue.bold(\"api-keys list\")} List all service API keys\n ${chalk.blue.bold(\"api-keys create\")} Create a new scoped API key\n ${chalk.blue.bold(\"api-keys revoke\")} Revoke an existing API key\n ${chalk.blue.bold(\"api-keys\")} ${chalk.gray(\"--help\")} Show API key command help\n\n${chalk.green.bold(\"Rebase Cloud\")}\n ${chalk.blue.bold(\"cloud login\")} Sign in to the hosted control plane\n ${chalk.blue.bold(\"cloud link\")} Link this directory to a cloud project\n ${chalk.blue.bold(\"cloud deploy\")} Deploy the linked project + stream logs\n ${chalk.blue.bold(\"cloud\")} ${chalk.gray(\"--help\")} Show all cloud commands\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--version, -v\")} Show version number\n ${chalk.blue(\"--help, -h\")} Show this help message\n\n${chalk.gray(\"Documentation: https://rebase.pro/docs\")}\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,kBAA2B;CACvC,IAAI;EAEA,OADY,UAAU,QAAQ,CAAC,WAAW,GAAG;GAAE,OAAO;GAAU,SAAS;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