@rebasepro/cli 0.27.0 → 0.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-setup-D9mHRZ5R.js → agent-setup-0uyfC7VX.js} +3 -3
- package/dist/{agent-setup-D9mHRZ5R.js.map → agent-setup-0uyfC7VX.js.map} +1 -1
- package/dist/{api-keys-CyJ26KEJ.js → api-keys-Dfw5-9s1.js} +23 -2
- package/dist/{api-keys-CyJ26KEJ.js.map → api-keys-Dfw5-9s1.js.map} +1 -1
- package/dist/{apps-CdrFm7Y3.js → apps-BpYRGOaM.js} +3 -3
- package/dist/{apps-CdrFm7Y3.js.map → apps-BpYRGOaM.js.map} +1 -1
- package/dist/{auth-dII2jCO1.js → auth-DifFaOyq.js} +2 -2
- package/dist/{auth-dII2jCO1.js.map → auth-DifFaOyq.js.map} +1 -1
- package/dist/{build-D-t5FSg0.js → build-CS-Z75eK.js} +3 -3
- package/dist/{build-D-t5FSg0.js.map → build-CS-Z75eK.js.map} +1 -1
- package/dist/{bundle-CrAWbpbG.js → bundle-C0IBCVpV.js} +5 -4
- package/dist/bundle-C0IBCVpV.js.map +1 -0
- package/dist/{cloud-B2_oJmK7.js → cloud-nwWkzAHu.js} +16 -10
- package/dist/cloud-nwWkzAHu.js.map +1 -0
- package/dist/commands/agent-setup.d.ts +2 -0
- package/dist/commands/cloud/context.d.ts +18 -0
- package/dist/commands/dev.d.ts +12 -0
- package/dist/commands/doctor.d.ts +10 -0
- package/dist/commands/schema-reconcile.d.ts +9 -0
- package/dist/commands/skills.d.ts +3 -0
- package/dist/{context-GUxkZm-S.js → context-DvIUbE-b.js} +39 -5
- package/dist/context-DvIUbE-b.js.map +1 -0
- package/dist/{dev-DTqVMgB3.js → dev-CzOazEHW.js} +17 -3
- package/dist/dev-CzOazEHW.js.map +1 -0
- package/dist/{doctor-BRWOlqeG.js → doctor-BuqSHNrd.js} +45 -26
- package/dist/doctor-BuqSHNrd.js.map +1 -0
- package/dist/doctor-environment.d.ts +7 -19
- package/dist/{fold-static-BGlpi22F.js → fold-static-BMO8LC01.js} +3 -3
- package/dist/fold-static-BMO8LC01.js.map +1 -0
- package/dist/{generate_sdk-BvcWvoUh.js → generate_sdk-_SQuSbJW.js} +2 -2
- package/dist/{generate_sdk-BvcWvoUh.js.map → generate_sdk-_SQuSbJW.js.map} +1 -1
- package/dist/index.es.js +23 -23
- package/dist/index.es.js.map +1 -1
- package/dist/{init-CaU6GhwI.js → init-CHtpYLlh.js} +5 -4
- package/dist/init-CHtpYLlh.js.map +1 -0
- package/dist/{normalize-imports-CK_Mpcej.js → normalize-imports-BN0fzZS8.js} +2 -2
- package/dist/{normalize-imports-CK_Mpcej.js.map → normalize-imports-BN0fzZS8.js.map} +1 -1
- package/dist/schema-2A0dd-Bv.js +321 -0
- package/dist/schema-2A0dd-Bv.js.map +1 -0
- package/dist/schema-reconcile-C3ToVnHr.js +2 -0
- package/dist/{skills-BU2flMOy.js → skills-CbwV6vw_.js} +170 -5
- package/dist/skills-CbwV6vw_.js.map +1 -0
- package/dist/{start-CflvYL60.js → start-21GRsZKc.js} +2 -2
- package/dist/{start-CflvYL60.js.map → start-21GRsZKc.js.map} +1 -1
- package/dist/{storage-DtOXGflp.js → storage-CO9ouK76.js} +2 -2
- package/dist/{storage-DtOXGflp.js.map → storage-CO9ouK76.js.map} +1 -1
- package/dist/utils/libpq-url.d.ts +8 -0
- package/dist/utils/root-pointer.d.ts +43 -0
- package/package.json +8 -8
- package/templates/template/.cursorrules +10 -0
- package/templates/template/.github/copilot-instructions.md +10 -0
- package/templates/template/.windsurfrules +10 -0
- package/templates/template/AGENTS.md +10 -0
- package/templates/template/CLAUDE.md +10 -0
- package/templates/template/ai-instructions.md +1 -1
- package/dist/bundle-CrAWbpbG.js.map +0 -1
- package/dist/cloud-B2_oJmK7.js.map +0 -1
- package/dist/context-GUxkZm-S.js.map +0 -1
- package/dist/dev-DTqVMgB3.js.map +0 -1
- package/dist/doctor-BRWOlqeG.js.map +0 -1
- package/dist/fold-static-BGlpi22F.js.map +0 -1
- package/dist/init-CaU6GhwI.js.map +0 -1
- package/dist/schema-BSXwZSiI.js +0 -152
- package/dist/schema-BSXwZSiI.js.map +0 -1
- package/dist/skills-BU2flMOy.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"doctor-BuqSHNrd.js","names":[],"sources":["../src/utils/libpq-url.ts","../src/doctor-environment.ts","../src/commands/doctor.ts"],"sourcesContent":["/**\n * Detect Postgres connection strings that libpq refuses to parse.\n *\n * libpq splits a URI query parameter on the FIRST `=` and rejects any further\n * one in the same parameter:\n *\n * extra key/value separator \"=\" in URI query parameter: \"options\"\n *\n * That makes a URL like\n *\n * postgresql://u:p@h:5432/db?options=-c%20search_path=public&sslmode=disable\n *\n * unusable by every libpq caller — `pg_dump`/`pg_restore` behind\n * `rebase db backup|restore`, and a plain `psql \"$DATABASE_URL\"`. It is not a\n * version quirk: Postgres 15 through 18 all refuse it.\n *\n * `rebase init` generated exactly that string until 2026-08-18, and the failure\n * is invisible day to day because node-postgres parses URLs itself and accepts\n * it — so `rebase dev` and `rebase db push` work while backups do not. Fixing\n * the generator does nothing for projects that already exist, which is what\n * these functions are for: `rebase doctor` reads them off disk and reports.\n */\n\n/** A query parameter whose value carries a literal `=`. */\nexport interface UnparseableParam {\n /** The parameter name, e.g. \"options\". */\n name: string;\n /** The raw `name=value` text as it appears in the URL. */\n raw: string;\n}\n\n/** Postgres URI schemes. A key/value DSN (\"host=… dbname=…\") is not one. */\nconst POSTGRES_URI_RE = /^postgres(ql)?:\\/\\//i;\n\n/**\n * Return the query parameters libpq would reject, or an empty array.\n *\n * Deliberately not built on `new URL()`: that parser is happy to accept the\n * broken form (it splits on the first `=` and keeps the rest as the value),\n * so it cannot see the defect at all. The rule being checked is libpq's, and\n * it is about the raw text.\n */\nexport function findUnparseableParams(connectionString: string): UnparseableParam[] {\n if (!POSTGRES_URI_RE.test(connectionString)) return [];\n\n const q = connectionString.indexOf(\"?\");\n if (q === -1) return [];\n\n // A fragment is not part of the query.\n const query = connectionString.slice(q + 1).split(\"#\")[0];\n if (!query) return [];\n\n const found: UnparseableParam[] = [];\n for (const part of query.split(\"&\")) {\n if (!part) continue;\n // One separator is the parameter's own; any further one is the defect.\n if (part.split(\"=\").length > 2) {\n found.push({ name: part.slice(0, part.indexOf(\"=\")), raw: part });\n }\n }\n return found;\n}\n\n/**\n * Percent-encode the offending `=` characters, leaving everything else byte for\n * byte as it was.\n *\n * Only the second and later `=` in a parameter are rewritten — the first is the\n * real separator. Nothing else is touched: re-serialising through `URL` would\n * also reorder parameters and turn spaces into `+`, which libpq does not decode,\n * so a \"tidy up\" would trade one unparseable string for another.\n */\nexport function encodeExtraEquals(connectionString: string): string {\n if (findUnparseableParams(connectionString).length === 0) return connectionString;\n\n const q = connectionString.indexOf(\"?\");\n const head = connectionString.slice(0, q + 1);\n const rest = connectionString.slice(q + 1);\n const hash = rest.indexOf(\"#\");\n const query = hash === -1 ? rest : rest.slice(0, hash);\n const fragment = hash === -1 ? \"\" : rest.slice(hash);\n\n const fixed = query.split(\"&\").map(encodeParamExtraEquals).join(\"&\");\n\n return `${head}${fixed}${fragment}`;\n}\n\n/** One `name=value` query parameter with every `=` after its separator encoded. */\nfunction encodeParamExtraEquals(part: string): string {\n const first = part.indexOf(\"=\");\n if (first === -1) return part;\n return `${part.slice(0, first)}=${part.slice(first + 1).replace(/=/g, \"%3D\")}`;\n}\n\n/** One connection string, found somewhere on disk, that libpq cannot parse. */\nexport interface LibpqUrlFinding {\n /** File it came from, relative to the project root. */\n file: string;\n /** The variable holding it, e.g. \"DATABASE_URL\". */\n variable: string;\n /** Parameter names libpq objects to. */\n params: string[];\n /** The same string with the offending `=` encoded. */\n suggested: string;\n /**\n * Each offending parameter as it is, and as it should be. What a report\n * prints: the whole string carries the database password.\n */\n fixes: Array<{ from: string; to: string }>;\n}\n\n/** Variables whose value is a Postgres connection string. */\nconst CONNECTION_VARIABLES = [\"DATABASE_URL\", \"ADMIN_CONNECTION_STRING\"];\n\n/**\n * Scan one file's text for connection strings libpq would reject.\n *\n * Handles both shapes a scaffolded project uses, because both shipped with the\n * defect and a deployed stack is broken by the compose one alone:\n *\n * .env DATABASE_URL=postgresql://…\n * docker-compose.yml DATABASE_URL: postgresql://…\n */\nexport function scanTextForLibpqUrls(file: string, text: string): LibpqUrlFinding[] {\n const findings: LibpqUrlFinding[] = [];\n\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim();\n // Commented-out examples are not what the project runs on.\n if (trimmed.startsWith(\"#\")) continue;\n\n for (const variable of CONNECTION_VARIABLES) {\n // `NAME=value` or `NAME: value`, optionally exported/indented.\n const match = trimmed.match(\n new RegExp(`^(?:export\\\\s+)?${variable}\\\\s*[:=]\\\\s*(.+)$`)\n );\n if (!match) continue;\n\n // Strip surrounding quotes and any trailing comment-free whitespace.\n let value = match[1].trim();\n const quoted = value.match(/^(['\"])(.*)\\1$/);\n if (quoted) value = quoted[2];\n if (!value) continue;\n\n const params = findUnparseableParams(value);\n if (params.length === 0) continue;\n\n findings.push({\n file,\n variable,\n params: params.map((p) => p.name),\n suggested: encodeExtraEquals(value),\n fixes: params.map((p) => ({ from: p.raw, to: encodeParamExtraEquals(p.raw) }))\n });\n }\n }\n\n return findings;\n}\n","/**\n * The checks that need no database, and that catch what breaks a first run.\n *\n * `rebase doctor` compared three descriptions of a schema, which is the right\n * check for a project that is working and the wrong one for a project that has\n * never worked. Everything that stops a first run — the wrong Node, two\n * lockfiles disagreeing, two collections claiming one slug, a `JWT_SECRET`\n * short enough to be guessed, a half-installed workspace with three versions of\n * `@rebasepro/server` in it — happens before a single table is compared, and\n * doctor said nothing about any of it.\n *\n * Every function here is pure: it takes what it read and returns findings. The\n * reading and the printing are at the edges, in `commands/doctor.ts`, so each\n * check has a fixture that fails it without a filesystem, a project or a\n * database.\n */\nimport dotenv from \"dotenv\";\n\n/** One thing that is wrong, and what to do about it. */\nexport interface EnvironmentFinding {\n /** Which check produced it, for grouping in the report. */\n check: \"node\" | \"package-manager\" | \"collections\" | \"env\" | \"versions\" | \"atlas\";\n severity: \"error\" | \"warning\";\n message: string;\n fix: string;\n}\n\n// ── Atlas ────────────────────────────────────────────────────────────────\n\n/** What is on disk for `@ariga/atlas`, read by `commands/doctor.ts`. */\nexport interface AtlasBinaryState {\n /** A `node_modules/.bin/atlas` the project's commands would find. */\n onPath: boolean;\n /** `@ariga/atlas/package.json` resolves from the project. */\n packageInstalled: boolean;\n /** The binary the package's `bin` names exists as a file. */\n binaryOnDisk: boolean;\n /** For the remedy: the reader's own package manager. */\n manager: string;\n /**\n * The workspace member the install goes into (`backend` in a scaffold),\n * or absent at a project that is no workspace. A scaffold's root refuses\n * `pnpm add` without `-w`, and atlas belongs to the backend anyway.\n */\n workspaceDir?: string | null;\n}\n\n/** `@ariga/atlas` added as a dev dependency where the project keeps it. */\nfunction atlasAddCommand(manager: string, workspaceDir: string | null | undefined): string {\n const pkg = \"@ariga/atlas\";\n if (!workspaceDir) return `${manager} add -D ${pkg}`;\n switch (manager) {\n case \"npm\": return `npm install -D ${pkg} -w ${workspaceDir}`;\n case \"yarn\": return `yarn --cwd ${workspaceDir} add -D ${pkg}`;\n case \"bun\": return `bun add -d ${pkg} --cwd ${workspaceDir}`;\n default: return `${manager} --dir ${workspaceDir} add -D ${pkg}`;\n }\n}\n\n/**\n * Whether `db push`, `db generate` and `db migrate` can run at all.\n *\n * They shell out to `atlas`, and its absence is invisible until one of them is\n * run: `@ariga/atlas` downloads its platform binary in `preinstall`, pnpm 10+\n * and npm 12+ refuse a dependency's lifecycle scripts unless allowlisted, and\n * the install exits 0 either way. The scaffold allowlists it, so this is a\n * problem for the person who added `@rebasepro/server-postgres` to a project\n * they already had — five lines of `ERR_PNPM_IGNORED_BUILDS` and\n * `Failed to create bin … ENOENT`, several screens up, with nothing saying that\n * a schema push will fail later.\n *\n * Three states, because two of them need opposite advice. The package absent is\n * an install; the package present with no binary is an allowlist; the binary\n * present with no `.bin` shim is a re-install, and telling that reader their\n * build scripts are blocked sends them to a command that does nothing.\n */\nexport function checkAtlasBinary(state: AtlasBinaryState | null): EnvironmentFinding[] {\n if (!state || state.onPath) return [];\n\n if (!state.packageInstalled) {\n return [{\n check: \"atlas\",\n severity: \"warning\",\n message: \"The atlas binary is not on PATH and @ariga/atlas is not installed — \"\n + \"`db push`, `db generate` and `db migrate` will fail.\",\n fix: `Install it: ${atlasAddCommand(state.manager, state.workspaceDir)}, and allow its install script.`\n }];\n }\n\n if (!state.binaryOnDisk) {\n return [{\n check: \"atlas\",\n severity: \"warning\",\n message: \"@ariga/atlas is installed and its binary is missing — its `preinstall` \"\n + \"script was blocked, so `db push` and `db migrate` will fail.\",\n fix: \"Allow the build script (pnpm: `allowBuilds` in pnpm-workspace.yaml or \"\n + \"`pnpm approve-builds`; npm: `allowScripts` in package.json), then re-install.\"\n }];\n }\n\n return [{\n check: \"atlas\",\n severity: \"warning\",\n message: \"The atlas binary is on disk but node_modules/.bin/atlas is missing, \"\n + \"so nothing can invoke it.\",\n fix: \"Re-resolve the tree so the link is recreated: `pnpm install --force`, or delete \"\n + \"node_modules and install again.\"\n }];\n}\n\n// ── Node ─────────────────────────────────────────────────────────────────\n\n/**\n * `20.11.0` → `[20, 11, 0]`, ignoring anything after the patch.\n *\n * A bare major is a version: `>=20` is how every `engines.node` in this repo is\n * written, and requiring a minor here made the whole check return nothing —\n * silently, which is the only way a check like this ever fails.\n */\nfunction parseVersion(raw: string): [number, number, number] | null {\n const match = raw.trim().replace(/^v/, \"\").match(/^(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?/);\n if (!match) return null;\n return [Number(match[1]), Number(match[2] ?? 0), Number(match[3] ?? 0)];\n}\n\n/** The lowest version a `>=x.y.z` range admits, or null for anything else. */\nexport function minimumFromRange(range: string): [number, number, number] | null {\n const match = range.match(/>=\\s*v?(\\d+(?:\\.\\d+)?(?:\\.\\d+)?)/);\n return match ? parseVersion(match[1]) : null;\n}\n\nfunction isBelow(actual: [number, number, number], minimum: [number, number, number]): boolean {\n for (let i = 0; i < 3; i++) {\n if (actual[i] < minimum[i]) return true;\n if (actual[i] > minimum[i]) return false;\n }\n return false;\n}\n\n/**\n * Is the running Node old enough to break things that will not say so?\n *\n * The symptoms are not \"unsupported Node\". They are a syntax error inside a\n * dependency, a missing global, or — the one that costs the most time — a\n * `node:` builtin that resolves and then behaves differently. Naming the\n * version is the whole check.\n */\nexport function checkNodeVersion(running: string, required: string | undefined): EnvironmentFinding[] {\n if (!required) return [];\n const minimum = minimumFromRange(required);\n const actual = parseVersion(running);\n if (!minimum || !actual) return [];\n if (!isBelow(actual, minimum)) return [];\n\n return [{\n check: \"node\",\n severity: \"error\",\n message: `Node ${running} is running, and Rebase needs ${required}.`,\n fix: `Install Node ${minimum[0]} or newer (nvm install ${minimum[0]}), then reinstall dependencies.`\n }];\n}\n\n// ── Package manager ──────────────────────────────────────────────────────\n\n/** The lockfiles a project may have, and the manager each one belongs to. */\nexport const LOCKFILES: Record<string, string> = {\n \"pnpm-lock.yaml\": \"pnpm\",\n \"package-lock.json\": \"npm\",\n \"yarn.lock\": \"yarn\",\n \"bun.lockb\": \"bun\"\n};\n\n/**\n * Two package managers in one project.\n *\n * A Rebase project is a pnpm workspace, and running `npm install` inside one\n * rewrites `node_modules` into a hoisted layout that pnpm then disagrees with.\n * The result is not an install error: it is `Cannot find module` from inside a\n * dependency, hours later, on a machine where it worked yesterday. The\n * leftover `package-lock.json` is the only durable evidence, and nothing looked\n * at it.\n */\nexport function checkPackageManager(\n lockfilesPresent: string[],\n declared: string | undefined\n): EnvironmentFinding[] {\n const known = lockfilesPresent.filter(file => file in LOCKFILES);\n if (known.length < 2) {\n // One lockfile, or none. A single one that disagrees with\n // `packageManager` is worth saying too.\n const declaredName = declared?.split(\"@\")[0];\n if (known.length === 1 && declaredName && LOCKFILES[known[0]] !== declaredName) {\n return [{\n check: \"package-manager\",\n severity: \"warning\",\n message: `This project declares packageManager \"${declared}\" and has a ${LOCKFILES[known[0]]} lockfile (${known[0]}).`,\n fix: `Delete ${known[0]} and node_modules, then install with ${declaredName}.`\n }];\n }\n return [];\n }\n\n const managers = known.map(file => LOCKFILES[file]);\n return [{\n check: \"package-manager\",\n severity: \"error\",\n message: `Two package managers have installed here: ${known.join(\" and \")}.`,\n fix: `Keep one. Delete the others and node_modules, then reinstall with ${declared?.split(\"@\")[0] ?? managers[0]}.`\n }];\n}\n\n// ── Collections ──────────────────────────────────────────────────────────\n\n/**\n * Two collections claiming one slug.\n *\n * The slug is the route, the table lookup and the registry key, and the\n * registry keeps the last one registered. So the loser is not reported missing:\n * it is served as the winner, with the winner's properties, under its own name.\n * Every symptom of this points somewhere else.\n */\nexport function checkDuplicateSlugs(\n collections: Array<{ slug?: string; name?: string }>\n): EnvironmentFinding[] {\n const byslug = new Map<string, number>();\n for (const collection of collections) {\n if (!collection.slug) continue;\n byslug.set(collection.slug, (byslug.get(collection.slug) ?? 0) + 1);\n }\n\n return [...byslug]\n .filter(([, count]) => count > 1)\n .map(([slug, count]) => ({\n check: \"collections\" as const,\n severity: \"error\" as const,\n message: `${count} collections declare the slug \"${slug}\". Only the last one registered is served.`,\n fix: `Give each collection its own slug. The one that loses is not reported missing — it answers as the winner.`\n }));\n}\n\n// ── .env ─────────────────────────────────────────────────────────────────\n\n/** What `loadEnv` requires of a JWT secret. Mirrors `rebaseEnvSchema`. */\nexport const MIN_JWT_SECRET_LENGTH = 32;\n\n/**\n * The two `.env` facts that fail late and confusingly.\n *\n * A short `JWT_SECRET` boots fine and is refused by `loadEnv` only in\n * production, which is the worst place to find out. Missing CORS in production\n * is the opposite shape — it does not fail at all; the API simply accepts\n * requests from anywhere.\n *\n * Values are never echoed. This reads a file that holds every credential the\n * project has, and doctor's output goes wherever a terminal goes.\n */\nexport function checkEnvSanity(values: Record<string, string>): EnvironmentFinding[] {\n const findings: EnvironmentFinding[] = [];\n const production = values.NODE_ENV === \"production\";\n\n const secret = values.JWT_SECRET;\n if (secret !== undefined && secret.length > 0 && secret.length < MIN_JWT_SECRET_LENGTH) {\n findings.push({\n check: \"env\",\n severity: production ? \"error\" : \"warning\",\n message: `JWT_SECRET is ${secret.length} characters. The runtime requires at least ${MIN_JWT_SECRET_LENGTH}, and refuses to boot below it in production.`,\n fix: \"Generate one: openssl rand -hex 32\"\n });\n }\n\n if (production && !values.CORS_ORIGINS && !values.FRONTEND_URL) {\n findings.push({\n check: \"env\",\n severity: \"error\",\n message: \"NODE_ENV=production with neither CORS_ORIGINS nor FRONTEND_URL set — the API will accept requests from any origin.\",\n fix: \"Set CORS_ORIGINS to the origins that may call this API.\"\n });\n }\n\n return findings;\n}\n\n/**\n * Parse a `.env` into a plain object, the way the runtime reads it.\n *\n * `dotenv.parse`, not `dotenv.config`: this must not touch `process.env`, and\n * doctor may be reading a file for a different environment than the one it is\n * running in. And dotenv's grammar, not a line splitter: the server loads this\n * file with dotenv, so `NODE_ENV=production # deploy` is production to it, and\n * a reading that kept the comment in the value judged the file as development\n * and skipped every production check.\n */\nexport function parseEnvFile(text: string): Record<string, string> {\n return dotenv.parse(text);\n}\n\n// ── Version skew ─────────────────────────────────────────────────────────\n\n/** One `@rebasepro/*` dependency, and where it was declared. */\nexport interface DeclaredDependency {\n /** Where it was declared, relative to the project root. */\n file: string;\n name: string;\n /** The range exactly as written. */\n range: string;\n}\n\n/**\n * The same `@rebasepro/*` package pinned to different versions in one project.\n *\n * A Rebase project declares them in several package.json files — the root, the\n * backend, the frontend, the config workspace — and nothing has ever compared\n * them. The failure that produces is not an install error: pnpm installs both,\n * `instanceof` stops working across the two copies, and the symptom is a\n * `CollectionConfig` that fails a type guard written against an identical type.\n *\n * `workspace:` ranges are excluded: inside this repo's own workspaces they all\n * resolve to the same build by construction.\n */\nexport function checkVersionSkew(declared: DeclaredDependency[]): EnvironmentFinding[] {\n const byPackage = new Map<string, Map<string, string[]>>();\n\n for (const dependency of declared) {\n if (!dependency.name.startsWith(\"@rebasepro/\")) continue;\n if (dependency.range.startsWith(\"workspace:\") || dependency.range.startsWith(\"link:\")) continue;\n if (dependency.range === \"*\" || dependency.range === \"latest\") continue;\n\n const ranges = byPackage.get(dependency.name) ?? new Map<string, string[]>();\n ranges.set(dependency.range, [...(ranges.get(dependency.range) ?? []), dependency.file]);\n byPackage.set(dependency.name, ranges);\n }\n\n const findings: EnvironmentFinding[] = [];\n for (const [name, ranges] of byPackage) {\n if (ranges.size < 2) continue;\n const described = [...ranges]\n .map(([range, files]) => `${range} (${files.join(\", \")})`)\n .join(\", \");\n findings.push({\n check: \"versions\",\n severity: \"error\",\n message: `${name} is pinned to different versions in this project: ${described}.`,\n fix: \"Run `rebase upgrade` to pin every @rebasepro package to one release and reinstall. Two copies of a Rebase package break `instanceof` between them, which fails as a type guard rejecting its own type.\"\n });\n }\n return findings;\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 fs from \"fs\";\nimport path from \"path\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile,\n exitDependenciesNotInstalled\n} from \"../utils/project\";\nimport { fileURLToPath, pathToFileURL } from \"url\";\nimport { createRequire } from \"module\";\nimport { scanTextForLibpqUrls, type LibpqUrlFinding } from \"../utils/libpq-url\";\nimport { redactConnectionPasswords } from \"../utils/redact\";\nimport { analyseFunctionsDirectory, summarisePortability } from \"../function-portability\";\nimport { reportSpawnFailure } from \"../utils/spawn-error\";\nimport { argsFromCommand } from \"../utils/command-words\";\nimport { COLLECTIONS_FLAG_HELP, refuseMissingCollectionsPath } from \"../utils/path-flags\";\nimport { collectionsDirArgs, resolveCollectionsDir } from \"../utils/collections-dir\";\nimport { absolutizeLocalPathArgs, DATABASE_SOURCE_ENV } from \"./db\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { loadManifest, findBackendApp, resolveBackendPaths } from \"../manifest\";\nimport { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from \"../dev-db/prepare\";\nimport {\n checkDuplicateSlugs,\n checkEnvSanity,\n checkAtlasBinary,\n checkNodeVersion,\n checkPackageManager,\n checkVersionSkew,\n LOCKFILES,\n parseEnvFile,\n type AtlasBinaryState,\n type DeclaredDependency,\n type EnvironmentFinding\n} from \"../doctor-environment\";\n\n/**\n * Files that can hold a connection string the project actually runs on.\n *\n * `.env` is what local commands read; the compose files are what a self-hosted\n * stack and its scheduled backup cron read. Both shipped with the defect, and a\n * deployed stack is broken by the compose one even when `.env` has been fixed.\n * `.env.example` is deliberately absent: nothing runs on it.\n */\nconst CONNECTION_FILES = [\n \".env\",\n \".env.local\",\n \"docker-compose.yml\",\n \"docker-compose.yaml\",\n \"docker-compose.custom.yml\"\n];\n\n/**\n * Find connection strings libpq cannot parse, anywhere in the project.\n *\n * Exported for the tests; `envFile` is passed separately because a project may\n * keep its `.env` outside the root (see `findEnvFile`).\n */\nexport function findLibpqUrlProblems(projectRoot: string, envFile?: string | null): LibpqUrlFinding[] {\n const candidates = CONNECTION_FILES.map((f) => path.join(projectRoot, f));\n if (envFile) candidates.push(envFile);\n\n const findings: LibpqUrlFinding[] = [];\n const seen = new Set<string>();\n\n for (const file of candidates) {\n if (seen.has(file)) continue;\n seen.add(file);\n let text: string;\n try {\n if (!fs.existsSync(file)) continue;\n text = fs.readFileSync(file, \"utf-8\");\n } catch {\n // Unreadable is not a finding — doctor reports what it can see.\n continue;\n }\n findings.push(...scanTextForLibpqUrls(path.relative(projectRoot, file) || path.basename(file), text));\n }\n\n return findings;\n}\n\n/**\n * Report unparseable connection strings, if any. Returns true when there were,\n * so the finding reaches the exit code like the environment errors do.\n *\n * Runs before the plugin's drift check and never blocks it. The plugin connects\n * through node-postgres, which parses these URLs happily — so it cannot see this\n * defect, and a project with it will otherwise get a clean bill of health while\n * `rebase db backup` fails.\n */\nexport function reportLibpqUrlProblems(findings: LibpqUrlFinding[]): boolean {\n if (findings.length === 0) return false;\n\n console.log(\"\");\n console.log(chalk.red.bold(\" ✗ Connection string that PostgreSQL's own tools cannot parse\"));\n console.log(\"\");\n for (const f of findings) {\n console.log(` ${chalk.bold(f.file)} → ${chalk.bold(f.variable)}`);\n console.log(chalk.gray(` the \"${f.params.join('\", \"')}\" parameter contains an unencoded \"=\". In the value, replace:`));\n // The parameter, not the whole string: the string carries the\n // database password, and this report lands in terminals, CI logs and\n // an assistant's context. A `password=` parameter is masked too.\n for (const fix of f.fixes) {\n console.log(` ${chalk.cyan(redactConnectionPasswords(fix.from))}`);\n console.log(chalk.gray(\" with:\"));\n console.log(` ${chalk.cyan(redactConnectionPasswords(fix.to))}`);\n }\n console.log(\"\");\n }\n console.log(chalk.gray(\" libpq splits a query parameter on the first \\\"=\\\" and rejects any further\"));\n console.log(chalk.gray(\" one, so this fails:\"));\n console.log(chalk.gray(\" extra key/value separator \\\"=\\\" in URI query parameter\"));\n console.log(\"\");\n console.log(chalk.gray(\" Affects rebase db backup / restore, scheduled backups, and psql.\"));\n console.log(chalk.gray(\" NOT rebase dev or db push — those use a driver that accepts it, which\"));\n console.log(chalk.gray(\" is why a project can look healthy and still have no working backups.\"));\n console.log(chalk.gray(\" Projects scaffolded before 2026-08-18 all carry it.\"));\n console.log(\"\");\n return true;\n}\n\n/**\n * `--help` is answered before the project guard, not after.\n *\n * `doctor` declared no `--help` at all, so the flag fell through to the command\n * body and hit `requireProjectRoot()` — and `rebase doctor --help` outside a\n * project answered \"✗ Could not find a Rebase project root.\" Asking a command\n * what it does is the one question that cannot require being somewhere\n * particular to ask.\n */\n/**\n * What each custom function needs from its host.\n *\n * Prints nothing when there is nothing to say — which is the common case, and\n * the reason it can afford to run every time. When it does print, the ordering\n * is deliberate: the one finding that is a bug *today* comes first, and the\n * rest is a single descriptive line about where these functions could run.\n */\nfunction reportFunctionPortability(projectRoot: string): void {\n let results: ReturnType<typeof analyseFunctionsDirectory>;\n try {\n const backend = findBackendApp(loadManifest(projectRoot).manifest);\n if (!backend) return;\n const paths = resolveBackendPaths(backend.app, projectRoot);\n results = analyseFunctionsDirectory(path.join(projectRoot, paths.functions), projectRoot);\n } catch {\n // A project with no manifest, or one shaped differently — doctor has\n // plenty else to report, and this section is advisory.\n return;\n }\n\n const lines = summarisePortability(results);\n if (lines.length === 0) return;\n\n console.log(chalk.bold(\"\\nCustom functions\"));\n for (const line of lines) {\n console.log(line.trimStart().startsWith(\"⚠\") ? chalk.yellow(line) : chalk.gray(line));\n }\n console.log(chalk.gray(\" See https://rebase.pro/docs/backend/custom-functions#runtime-portability\"));\n}\n\n/**\n * Read everything the environment checks need, then run them.\n *\n * The reading is here and the deciding is in `doctor-environment.ts`, so every\n * check has a fixture that fails it without a project on disk.\n */\nexport function collectEnvironmentFindings(\n projectRoot: string,\n envFile: string | null | undefined\n): EnvironmentFinding[] {\n const findings: EnvironmentFinding[] = [];\n\n // Node, against the engines range the installed CLI declares.\n findings.push(...checkNodeVersion(process.versions.node, readCliEngines()));\n\n // Two package managers in one project.\n const rootPackage = readJson(path.join(projectRoot, \"package.json\"));\n findings.push(...checkPackageManager(\n Object.keys(LOCKFILES).filter(file => fs.existsSync(path.join(projectRoot, file))),\n typeof rootPackage?.packageManager === \"string\" ? rootPackage.packageManager : undefined\n ));\n\n // Two collections claiming one slug. Read as text rather than imported: a\n // collection file can import anything, and doctor must not execute a\n // project's code to tell it two slugs collide.\n findings.push(...checkDuplicateSlugs(readDeclaredSlugs(projectRoot)));\n\n // `.env`, values never echoed.\n if (envFile && fs.existsSync(envFile)) {\n try {\n findings.push(...checkEnvSanity(parseEnvFile(fs.readFileSync(envFile, \"utf-8\"))));\n } catch { /* unreadable is not a finding */ }\n }\n\n // One `@rebasepro/*` package, two versions.\n findings.push(...checkVersionSkew(readDeclaredRebaseDeps(projectRoot)));\n\n // The atlas binary, which every schema command shells out to and whose\n // absence is invisible until one of them is run.\n findings.push(...checkAtlasBinary(readAtlasBinaryState(projectRoot)));\n\n return findings;\n}\n\n/**\n * What is actually on disk for `@ariga/atlas`, from the project's point of view.\n *\n * Three separate questions, because the three states they distinguish need\n * three different remedies — see `checkAtlasBinary`. Directories are searched\n * from the project root upwards and through the workspaces a scaffold has,\n * because `db push` runs from `backend/` and the install may be hoisted to the\n * root.\n */\nexport function readAtlasBinaryState(projectRoot: string): AtlasBinaryState | null {\n const roots = [projectRoot, path.join(projectRoot, \"backend\"), path.join(projectRoot, \"config\")];\n\n const findUpwards = (starts: string[], relative: string): string | null => {\n for (const start of starts) {\n let dir = start;\n for (let i = 0; i < 8; i++) {\n const candidate = path.join(dir, \"node_modules\", relative);\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n }\n return null;\n };\n\n // `@ariga/atlas` is a dependency of `@rebasepro/server-postgres`, not of the\n // project, so under pnpm's isolated layout — the scaffold default — it lives\n // in `.pnpm/` and a directory walk over `node_modules/` never sees it.\n // Resolve through the module graph the way the driver itself does.\n const resolveFrom = (from: string, request: string): string | null => {\n try {\n return createRequire(pathToFileURL(from)).resolve(request);\n } catch {\n return null;\n }\n };\n const bases = roots.map(dir => path.join(dir, \"package.json\")).filter(file => fs.existsSync(file));\n const driverManifests = bases\n .map(base => resolveFrom(base, \"@rebasepro/server-postgres/package.json\"))\n .filter((file): file is string => file !== null);\n\n let manifest: string | null = findUpwards(roots, path.join(\"@ariga\", \"atlas\", \"package.json\"));\n if (!manifest) {\n for (const base of [...bases, ...driverManifests]) {\n manifest = resolveFrom(base, \"@ariga/atlas/package.json\");\n if (manifest) break;\n }\n }\n\n // The `.bin` shim is written beside whichever package declared the\n // dependency, so the driver's own directory is a search root too.\n const onPath = findUpwards(\n [...roots, ...driverManifests.map(file => path.dirname(file))],\n path.join(\".bin\", \"atlas\")\n ) !== null;\n\n let binaryOnDisk = false;\n if (manifest) {\n try {\n const pkg = JSON.parse(fs.readFileSync(manifest, \"utf-8\")) as {\n bin?: string | Record<string, string>;\n };\n const dir = path.dirname(manifest);\n const targets = typeof pkg.bin === \"string\"\n ? [pkg.bin]\n : Object.values(pkg.bin ?? {}).filter((t): t is string => typeof t === \"string\");\n binaryOnDisk = targets.some(target => fs.existsSync(path.resolve(dir, target)));\n } catch { /* unreadable manifest: treat the binary as absent */ }\n }\n\n return {\n onPath,\n packageInstalled: manifest !== null,\n binaryOnDisk,\n manager: readPackageManagerName(projectRoot),\n workspaceDir: fs.existsSync(path.join(projectRoot, \"backend\", \"package.json\")) && isWorkspaceRoot(projectRoot)\n ? \"backend\"\n : null\n };\n}\n\n/** Whether `dir` is a workspace root, where `pnpm add` refuses without `-w`. */\nfunction isWorkspaceRoot(dir: string): boolean {\n if (fs.existsSync(path.join(dir, \"pnpm-workspace.yaml\"))) return true;\n try {\n const manifest: unknown = JSON.parse(fs.readFileSync(path.join(dir, \"package.json\"), \"utf8\"));\n return typeof manifest === \"object\" && manifest !== null && \"workspaces\" in manifest;\n } catch {\n return false;\n }\n}\n\n/** The reader's own package manager, from the lockfile beside their project. */\nfunction readPackageManagerName(projectRoot: string): string {\n for (const [file, manager] of Object.entries(LOCKFILES)) {\n if (fs.existsSync(path.join(projectRoot, file))) return manager;\n }\n return \"pnpm\";\n}\n\n/** The `engines.node` range of the CLI actually running. */\nfunction readCliEngines(): string | undefined {\n try {\n const here = path.dirname(fileURLToPath(import.meta.url));\n for (let dir = here, i = 0; i < 5; i++) {\n const candidate = path.join(dir, \"package.json\");\n if (fs.existsSync(candidate)) {\n const parsed = readJson(candidate);\n if (parsed?.name === \"@rebasepro/cli\") {\n const engines = parsed.engines as { node?: string } | undefined;\n return engines?.node;\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n } catch { /* the check is advisory */ }\n return undefined;\n}\n\nfunction readJson(file: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf-8\")) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\n/** Where a project's package.json files live, relative to its root. */\nconst PACKAGE_JSON_LOCATIONS = [\"package.json\", \"backend/package.json\", \"frontend/package.json\", \"config/package.json\"];\n\nfunction readDeclaredRebaseDeps(projectRoot: string): DeclaredDependency[] {\n const declared: DeclaredDependency[] = [];\n for (const relative of PACKAGE_JSON_LOCATIONS) {\n const parsed = readJson(path.join(projectRoot, relative));\n if (!parsed) continue;\n for (const field of [\"dependencies\", \"devDependencies\", \"peerDependencies\"] as const) {\n const block = parsed[field] as Record<string, string> | undefined;\n if (!block) continue;\n for (const [name, range] of Object.entries(block)) {\n if (typeof range === \"string\") declared.push({ file: relative, name, range });\n }\n }\n }\n return declared;\n}\n\n/**\n * Does this project declare its collections in code?\n *\n * `resolveBackendPaths` answers it against the manifest's own `config` path\n * rather than the convention, because a project may move the directory. A\n * project with no manifest, or one shaped differently, is treated as declaring\n * them: the wrong answer there would silently skip the drift report, which is\n * the reason the command exists.\n */\nexport function hasDeclaredCollections(projectRoot: string): boolean {\n try {\n const backend = findBackendApp(loadManifest(projectRoot).manifest);\n if (!backend) return true;\n return resolveBackendPaths(backend.app, projectRoot).hasCollections;\n } catch {\n return true;\n }\n}\n\n/**\n * Every `slug:` a collection file declares, read as text.\n *\n * Deliberately not by importing them: a collection file may import anything the\n * project depends on, and doctor must not run a project's code to tell it two\n * slugs collide. A regex over `slug: \"...\"` finds the literal in every shape\n * the scaffold and the docs use; a computed slug is simply not seen, which is\n * the right failure for a check that only ever reports.\n */\nfunction readDeclaredSlugs(projectRoot: string): Array<{ slug: string }> {\n const dir = resolveCollectionsDir(projectRoot);\n if (!fs.existsSync(dir)) return [];\n const slugs: Array<{ slug: string }> = [];\n let entries: string[];\n try {\n entries = fs.readdirSync(dir);\n } catch {\n return [];\n }\n for (const entry of entries) {\n if (!/\\.(ts|js|mts|mjs)$/.test(entry) || entry.startsWith(\"index.\")) continue;\n try {\n const text = fs.readFileSync(path.join(dir, entry), \"utf-8\");\n for (const match of text.matchAll(/\\bslug:\\s*[\"'`]([^\"'`]+)[\"'`]/g)) {\n slugs.push({ slug: match[1] });\n }\n } catch { /* unreadable is not a finding */ }\n }\n return slugs;\n}\n\n/** Print what the environment checks found, grouped, or nothing at all. */\nfunction reportEnvironmentFindings(findings: EnvironmentFinding[]): boolean {\n if (findings.length === 0) return false;\n\n console.log(\"\");\n console.log(chalk.bold(\" Environment\"));\n for (const finding of findings) {\n const mark = finding.severity === \"error\" ? chalk.red(\" ✗\") : chalk.yellow(\" ⚠\");\n console.log(`${mark} ${finding.message}`);\n console.log(chalk.gray(` ${finding.fix}`));\n }\n console.log(\"\");\n return findings.some(finding => finding.severity === \"error\");\n}\n\n/**\n * The flags `rebase doctor` takes, and what each is for.\n *\n * One table, read by both the parser and the help page, because they were two\n * things that had to agree and did not: the page listed no flags at all, so\n * `--policies` — the form `cli/index.md` calls \"the form to use as a CI gate\" —\n * was invisible to anyone who ran `rebase doctor --help` to find it. And with\n * nothing parsing the line here, a typo travelled to the driver's permissive\n * parser and was silently dropped, so `rebase doctor --polices` ran the ordinary\n * doctor and reported success on a gate that never ran.\n *\n * The spec mirrors the driver's own (`doctorPluginCommand` in\n * `server-postgres/src/cli.ts`), because the line is relayed to it verbatim.\n */\nexport const DOCTOR_FLAGS = {\n \"--policies\": Boolean,\n \"--collections\": String,\n \"-c\": \"--collections\",\n \"--schema\": String,\n \"-s\": \"--schema\",\n \"--sdk\": String,\n \"-k\": \"--sdk\"\n} as const;\n\n/** What each long flag above does, for the Options block. */\nconst DOCTOR_FLAG_HELP: Record<string, string> = {\n \"--policies\": \"Also audit the row-level security policies. The form to use as a CI gate.\",\n \"--collections\": COLLECTIONS_FLAG_HELP,\n \"--schema\": \"Path to the generated Drizzle schema (default: backend/src/schema.generated.ts)\",\n \"--sdk\": \"Path to the generated SDK types (default: generated/sdk/database.types.ts)\"\n};\n\n/**\n * The line handed to the driver, every path on it resolved from where the\n * command was run — the driver runs in `backend/`. See `utils/path-flags.ts`.\n */\nexport function doctorDriverArgs(rawArgs: string[], cwd: string, projectRoot?: string): string[] {\n const args = absolutizeLocalPathArgs(argsFromCommand(rawArgs, \"doctor\"), cwd, [\"--collections\", \"-c\", \"--schema\", \"-s\", \"--sdk\", \"-k\"]);\n return projectRoot ? [...args, ...collectionsDirArgs(projectRoot, args)] : args;\n}\n\n/** `--collections, -c` — the aliases, resolved from the spec rather than retyped. */\nfunction doctorFlagLabel(flag: string): string {\n const aliases = Object.entries(DOCTOR_FLAGS)\n .filter(([, target]) => target === flag)\n .map(([alias]) => alias);\n return [flag, ...aliases].join(\", \");\n}\n\nfunction printDoctorHelp(): void {\n console.log(`\n${chalk.bold(\"rebase doctor\")} — Check a project for drift and misconfiguration\n\n${chalk.green.bold(\"Usage\")}\n rebase doctor [options]\n\n${chalk.green.bold(\"Options\")}\n${Object.keys(DOCTOR_FLAG_HELP)\n .map(flag => ` ${chalk.blue(doctorFlagLabel(flag).padEnd(22))} ${DOCTOR_FLAG_HELP[flag]}`)\n .join(\"\\n\")}\n\nCompares the collections you declare, the generated Drizzle schema, and the\ntables that actually exist, then reports what disagrees and how to reconcile it.\n\nAlso checks the connection strings in .env and the compose files for the\nunencoded \"=\" that makes PostgreSQL's own tools refuse to parse them — which\nbreaks backups and psql while leaving the app itself working.\n\nRun from inside a Rebase project — it reads the project's collections and\nconnects to its database.\n`);\n}\n\nexport async function doctorCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) {\n printDoctorHelp();\n return;\n }\n\n // Strictly, before the line is relayed. The driver's own parser is\n // `permissive`, which turns an undeclared flag into a positional rather\n // than an error, so `rebase doctor --polices` ran the ordinary doctor and\n // exited 0 — a CI gate that reported success because the flag asking for it\n // was dropped on the way.\n parseCommandArgs({\n spec: DOCTOR_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"doctor\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n refuseMissingCollectionsPath(rawArgs, process.cwd(), backendDir, \"doctor\");\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 exitDependenciesNotInstalled(projectRoot);\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 env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? \"\";\n\n // Reported before the plugin runs: this one needs no database, and if the\n // URL is the problem then anything that tries to connect with it first will\n // fail with a worse message.\n const connectionFailed = reportLibpqUrlProblems(findLibpqUrlProblems(projectRoot, envFile));\n\n // Same reasoning: no database needed, and one of these findings — a\n // `process.env` read at module scope — is a live failure whose only symptom\n // today is a function quietly missing from `GET /api/functions`.\n reportFunctionPortability(projectRoot);\n\n // Everything that breaks a first run happens before a table is compared:\n // the wrong Node, two lockfiles disagreeing, two collections claiming one\n // slug, a JWT_SECRET short enough to be refused in production, three\n // versions of @rebasepro/server in one workspace. Doctor said nothing about\n // any of it. Reported before the plugin runs, and non-blocking — a project\n // with one of these still deserves its drift report.\n const environmentFailed = reportEnvironmentFindings(collectEnvironmentFindings(projectRoot, envFile));\n // Either is an error a CI gate must see: a connection string libpq cannot\n // parse is a project whose backups have never run.\n const failed = connectionFailed || environmentFailed;\n\n // Which database, resolved the way every other command resolves it.\n //\n // Two of doctor's three phases need one, and both used to key on\n // `DATABASE_URL` alone. On the documented first-run path that variable does\n // not exist — `rebase init` leaves it commented out and the managed\n // database fills the vacuum — so a stock scaffold always ended with\n // `⏭ Collections → Database: skipped (DATABASE_URL not set)` and\n // `⚠ No DATABASE_URL — RLS policies were NOT checked`, then told the reader\n // to set the one variable the quickstart tells them to leave alone. For the\n // command `ai-instructions.md` names as the thing to run before guessing.\n //\n // The managed daemon is started here, exactly as `rebase db url` starts it:\n // a doctor that will not start the database it is asked about can only ever\n // answer \"I did not look\".\n //\n // Last, and never fatal. Everything above needs no database, and a doctor\n // that cannot report what it *can* see because a database would not start\n // is the opposite of the job. A failure here is said out loud and the run\n // continues; the driver then reports its two database phases as skipped,\n // which is the truth.\n try {\n const prepared = await prepareDatabaseEnv(projectRoot, {\n onProgress: (message) => console.log(chalk.gray(` ${message}`))\n });\n Object.assign(env, prepared.env);\n // What named the database, as the `db` commands pass it: the driver's\n // \"Cannot connect\" banner picks its fixes by it. Without it, the\n // remembered Docker database, stopped, got \"Verify DATABASE_URL in\n // your .env file\" — a file that had named nothing.\n env[DATABASE_SOURCE_ENV] = prepared.database.source;\n for (const line of managedNotices(prepared)) console.log(chalk.gray(` ${line}`));\n } catch (error) {\n console.log(\"\");\n console.error(chalk.yellow(` ⚠ Could not resolve this project's database: ${\n error instanceof Error ? error.message : String(error)}`));\n console.error(chalk.gray(\" The checks that need one are reported below as not run.\"));\n }\n\n // A headless project has no `config/collections` by design — its API is\n // introspected from the live database at boot — and the driver's doctor\n // opens by loading them, finds none, and exits 1. So `rebase doctor` failed\n // on the documented headless path, in 0.17.3 and on main, while every check\n // above it had just passed. Its three phases all compare *against* declared\n // collections, so there is nothing for them to do here; the environment\n // findings are the whole report.\n if (!hasDeclaredCollections(projectRoot)) {\n console.log(\"\");\n console.log(chalk.gray(\n \" ○ Schema drift not checked: this project derives its API from the database — \"\n + \"run `rebase schema introspect` first.\"\n ));\n if (failed) process.exit(1);\n return;\n }\n\n try {\n const isTs = pluginCli.endsWith(\".ts\");\n if (isTs) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n exitDependenciesNotInstalled(projectRoot);\n }\n await execa(tsxBin, [pluginCli, ...doctorDriverArgs(rawArgs, process.cwd(), projectRoot)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n } else {\n await execa(\"node\", [pluginCli, ...doctorDriverArgs(rawArgs, process.cwd(), projectRoot)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n } catch (error) {\n // A child that ran and exited non-zero already printed its diagnostics\n // through inherited stdio. A child that never started did not — and\n // \"the tsx symlink is broken\" is exactly the state `doctor` exists to\n // report, so exiting 1 in silence was the worst possible answer.\n reportSpawnFailure(error);\n process.exit(1);\n }\n\n // The plugin exited clean, so the schema agrees with itself. That is not\n // the same as the project being able to run: an environment error is still\n // an error, and a doctor that exits 0 over one is a doctor nobody can gate\n // on.\n if (failed) process.exit(1);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,IAAM,kBAAkB;;;;;;;;;AAUxB,SAAgB,sBAAsB,kBAA8C;CAChF,IAAI,CAAC,gBAAgB,KAAK,gBAAgB,GAAG,OAAO,CAAC;CAErD,MAAM,IAAI,iBAAiB,QAAQ,GAAG;CACtC,IAAI,MAAM,IAAI,OAAO,CAAC;CAGtB,MAAM,QAAQ,iBAAiB,MAAM,IAAI,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;CACvD,IAAI,CAAC,OAAO,OAAO,CAAC;CAEpB,MAAM,QAA4B,CAAC;CACnC,KAAK,MAAM,QAAQ,MAAM,MAAM,GAAG,GAAG;EACjC,IAAI,CAAC,MAAM;EAEX,IAAI,KAAK,MAAM,GAAG,CAAC,CAAC,SAAS,GACzB,MAAM,KAAK;GAAE,MAAM,KAAK,MAAM,GAAG,KAAK,QAAQ,GAAG,CAAC;GAAG,KAAK;EAAK,CAAC;CAExE;CACA,OAAO;AACX;;;;;;;;;;AAWA,SAAgB,kBAAkB,kBAAkC;CAChE,IAAI,sBAAsB,gBAAgB,CAAC,CAAC,WAAW,GAAG,OAAO;CAEjE,MAAM,IAAI,iBAAiB,QAAQ,GAAG;CACtC,MAAM,OAAO,iBAAiB,MAAM,GAAG,IAAI,CAAC;CAC5C,MAAM,OAAO,iBAAiB,MAAM,IAAI,CAAC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,YAAY,QAAQ,IAAI,MAAM,KAAK,KAAK,SAAS,CAAC,EACnE,CAAC;EACD,OAAO,OAAO,KAAK,SAAS,GAAG;EAK/B,IAAI,uBAAuB,SAAS,SAAS;EAC7C,KAAK,MAAM,QAAQ,eAAe,QAAQ,GAAG,QAAQ,IAAI,MAAM,KAAK,KAAK,MAAM,CAAC;CACpF,SAAS,OAAO;EACZ,QAAQ,IAAI,EAAE;EACd,QAAQ,MAAM,MAAM,OAAO,kDACvB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,CAAC;EAC7D,QAAQ,MAAM,MAAM,KAAK,6DAA6D,CAAC;CAC3F;CASA,IAAI,CAAC,uBAAuB,WAAW,GAAG;EACtC,QAAQ,IAAI,EAAE;EACd,QAAQ,IAAI,MAAM,KACd,sHAEJ,CAAC;EACD,IAAI,QAAQ,QAAQ,KAAK,CAAC;EAC1B;CACJ;CAEA,IAAI;EAEA,IADa,UAAU,SAAS,KAC5B,GAAM;GACN,MAAM,SAAS,WAAW,WAAW;GACrC,IAAI,CAAC,QACD,6BAA6B,WAAW;GAE5C,MAAM,MAAM,QAAQ,CAAC,WAAW,GAAG,iBAAiB,SAAS,QAAQ,IAAI,GAAG,WAAW,CAAC,GAAG;IACvF,KAAK;IACL,OAAO;IACP;GACJ,CAAC;EACL,OACI,MAAM,MAAM,QAAQ,CAAC,WAAW,GAAG,iBAAiB,SAAS,QAAQ,IAAI,GAAG,WAAW,CAAC,GAAG;GACvF,KAAK;GACL,OAAO;GACP;EACJ,CAAC;CAET,SAAS,OAAO;EAKZ,mBAAmB,KAAK;EACxB,QAAQ,KAAK,CAAC;CAClB;CAMA,IAAI,QAAQ,QAAQ,KAAK,CAAC;AAC9B"}
|
|
@@ -1,19 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The checks that need no database, and that catch what breaks a first run.
|
|
3
|
-
*
|
|
4
|
-
* `rebase doctor` compared three descriptions of a schema, which is the right
|
|
5
|
-
* check for a project that is working and the wrong one for a project that has
|
|
6
|
-
* never worked. Everything that stops a first run — the wrong Node, two
|
|
7
|
-
* lockfiles disagreeing, two collections claiming one slug, a `JWT_SECRET`
|
|
8
|
-
* short enough to be guessed, a half-installed workspace with three versions of
|
|
9
|
-
* `@rebasepro/server` in it — happens before a single table is compared, and
|
|
10
|
-
* doctor said nothing about any of it.
|
|
11
|
-
*
|
|
12
|
-
* Every function here is pure: it takes what it read and returns findings. The
|
|
13
|
-
* reading and the printing are at the edges, in `commands/doctor.ts`, so each
|
|
14
|
-
* check has a fixture that fails it without a filesystem, a project or a
|
|
15
|
-
* database.
|
|
16
|
-
*/
|
|
17
1
|
/** One thing that is wrong, and what to do about it. */
|
|
18
2
|
export interface EnvironmentFinding {
|
|
19
3
|
/** Which check produced it, for grouping in the report. */
|
|
@@ -108,10 +92,14 @@ export declare const MIN_JWT_SECRET_LENGTH = 32;
|
|
|
108
92
|
*/
|
|
109
93
|
export declare function checkEnvSanity(values: Record<string, string>): EnvironmentFinding[];
|
|
110
94
|
/**
|
|
111
|
-
* Parse a `.env` into a plain object.
|
|
95
|
+
* Parse a `.env` into a plain object, the way the runtime reads it.
|
|
112
96
|
*
|
|
113
|
-
*
|
|
114
|
-
* be reading a file for a different environment than the one it is
|
|
97
|
+
* `dotenv.parse`, not `dotenv.config`: this must not touch `process.env`, and
|
|
98
|
+
* doctor may be reading a file for a different environment than the one it is
|
|
99
|
+
* running in. And dotenv's grammar, not a line splitter: the server loads this
|
|
100
|
+
* file with dotenv, so `NODE_ENV=production # deploy` is production to it, and
|
|
101
|
+
* a reading that kept the comment in the value judged the file as development
|
|
102
|
+
* and skipped every production check.
|
|
115
103
|
*/
|
|
116
104
|
export declare function parseEnvFile(text: string): Record<string, string>;
|
|
117
105
|
/** One `@rebasepro/*` dependency, and where it was declared. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { u as compareMountOrder, v as staticAppAddress } from "./manifest-BtzDy7KQ.js";
|
|
2
|
-
import { C as toolStdio, y as foldStaticIntoBundle } from "./bundle-
|
|
2
|
+
import { C as toolStdio, y as foldStaticIntoBundle } from "./bundle-C0IBCVpV.js";
|
|
3
3
|
import chalk from "chalk";
|
|
4
4
|
import fs from "fs";
|
|
5
5
|
import path from "path";
|
|
@@ -80,7 +80,7 @@ function assertBuiltForPath(indexHtml, basePath, appName) {
|
|
|
80
80
|
const offenders = [];
|
|
81
81
|
for (const match of indexHtml.matchAll(/<(?:script|link)\b[^>]*?\b(?:src|href)\s*=\s*["']([^"']+)["']/gi)) {
|
|
82
82
|
const ref = match[1];
|
|
83
|
-
if (!ref.startsWith("/")) continue;
|
|
83
|
+
if (!ref.startsWith("/") || ref.startsWith("//")) continue;
|
|
84
84
|
if (ref === `${basePath}` || ref.startsWith(`${basePath}/`)) continue;
|
|
85
85
|
offenders.push(ref);
|
|
86
86
|
}
|
|
@@ -198,4 +198,4 @@ async function foldFrontendIntoBundle(options) {
|
|
|
198
198
|
//#endregion
|
|
199
199
|
export { staticBuildEnv as i, foldFrontendIntoBundle as n, foldableApps as r, assertBuiltForPath as t };
|
|
200
200
|
|
|
201
|
-
//# sourceMappingURL=fold-static-
|
|
201
|
+
//# sourceMappingURL=fold-static-BMO8LC01.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fold-static-BMO8LC01.js","names":[],"sources":["../src/fold-static.ts"],"sourcesContent":["/**\n * Folding a project's static apps into its backend bundle.\n *\n * Shared by `rebase build` and `rebase cloud deploy` deliberately. It lived in\n * the build *command* first, and `deploy` rebuilds the bundle itself — so a\n * deploy silently produced a bundle without the frontend, packed 164 KB where\n * 39 MB was expected, and the site 404'd on the managed runtime exactly as if\n * folding had never been written. Two callers building the same artefact must\n * share the step that completes it.\n *\n * Why fold at all: `bootFromBundle` serves static apps from `entry.static`\n * behind `REBASE_SERVE_STATIC` (default on). A managed tenant runs one pod, so\n * putting the built assets in the bundle gives it the shape a custom container\n * already had — site at `/`, admin at `/admin`, API at `/api` — which is the\n * only honest baseline for calling the managed runtime a drop-in replacement.\n *\n * **Every** static app is folded, each at its declared path. Folding used to\n * pick exactly one and refuse when it found two, which meant a project with a\n * site and an admin panel deployed with neither.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { execa } from \"execa\";\nimport chalk from \"chalk\";\nimport { foldStaticIntoBundle } from \"./bundle\";\nimport { compareMountOrder, staticAppAddress } from \"./manifest\";\nimport { toolStdio } from \"./utils/tool-stdio\";\n\n/** The apps section of a project manifest, as much of it as folding needs. */\nexport interface FoldableManifest {\n apps?: Record<string, {\n type?: string;\n build?: string;\n output?: string;\n path?: string;\n spa?: boolean;\n cms?: string;\n }>;\n}\n\nexport interface FoldOptions {\n projectRoot: string;\n manifest: FoldableManifest;\n /** The backend bundle directory, already written. */\n bundleDir: string;\n /** Skip running each app's own build command; fold what is already built. */\n skipBuild?: boolean;\n /**\n * The static apps already built in this run, shared with `buildAssetApp`.\n * An app named here is not built again; an app built here is added. One\n * `rebase build` used to run the admin's `vite build && tsc` twice — once\n * to fold it, once for its own static bundle — with the same command, the\n * same environment and the same output directory.\n */\n builtApps?: Set<string>;\n log?: (message: string) => void;\n /** Send each app's build output to stderr: the caller's stdout carries a result. See `toolStdio`. */\n quietStdout?: boolean;\n}\n\nexport interface FoldOutcome {\n appName: string;\n fileCount: number;\n /** Public base path this app was folded in at. */\n path: string;\n /** The one hostname it answers on, when its `path` names one. */\n host?: string;\n}\n\n/** A static app as folding sees it, with the manifest's defaults applied. */\nexport interface FoldableApp {\n name: string;\n build?: string;\n output?: string;\n /**\n * Public base path, defaulted to `/`. Always a path: when the manifest's\n * `path` is a URL, this is the part after the hostname, which is what the\n * app is built for and mounted at.\n */\n path: string;\n /** The one hostname this app answers on, when its `path` is a URL. */\n host?: string;\n /** SPA fallback, defaulted to `true`. */\n spa: boolean;\n /** Where this app mounts the Rebase CMS, if it does. */\n cms?: string;\n}\n\n/**\n * Every static app in the manifest, in mount order.\n *\n * Longest path first, so the `/`-rooted app is registered last — its catch-all\n * would otherwise claim its siblings' URLs — and, at an equal path, the app with\n * a hostname before the one without (see `compareMountOrder`). Pure, so the\n * ordering is testable without a filesystem.\n */\nexport function foldableApps(manifest: FoldableManifest): {\n apps: FoldableApp[];\n /** Apps that cannot be folded, and why. */\n skipped: { name: string; reason: string }[];\n} {\n const apps: FoldableApp[] = [];\n const skipped: { name: string; reason: string }[] = [];\n\n for (const [name, app] of Object.entries(manifest.apps ?? {})) {\n if (app?.type !== \"static\") continue;\n if (!app.output) {\n skipped.push({ name,\nreason: `\"${name}\" declares no output directory — not folded in.` });\n continue;\n }\n const { host, path: appPath } = staticAppAddress(name, app);\n apps.push({\n name,\n build: app.build,\n output: app.output,\n path: appPath,\n ...(host ? { host } : {}),\n spa: app.spa ?? true,\n cms: app.cms\n });\n }\n\n apps.sort(compareMountOrder);\n return { apps,\nskipped };\n}\n\n/**\n * Assert a built app's assets are actually rooted at the path it is served from.\n *\n * An app mounted at `/admin` but built with Vite's default `base: \"/\"` emits\n * `<script src=\"/assets/index-a1b2.js\">`. The server serves `index.html` fine\n * and 404s every asset: a blank page, no server error, nothing in the logs. It\n * is the single most expensive silent failure in this design, so it is a build\n * error rather than a runtime surprise.\n *\n * Only `<script src>` and `<link href>` are inspected — those are what a bundler\n * rewrites through `base`. Author-written anchors and canonical URLs are not\n * evidence of a misbuild.\n */\nexport function assertBuiltForPath(\n indexHtml: string,\n basePath: string,\n appName: string\n): void {\n if (basePath === \"/\") return;\n\n const offenders: string[] = [];\n const pattern = /<(?:script|link)\\b[^>]*?\\b(?:src|href)\\s*=\\s*[\"']([^\"']+)[\"']/gi;\n for (const match of indexHtml.matchAll(pattern)) {\n const ref = match[1];\n // Relative, or on another host: `//cdn.example.com/x.js` starts with a\n // slash and is no more rooted at this app's path than `https://` is.\n if (!ref.startsWith(\"/\") || ref.startsWith(\"//\")) continue;\n if (ref === `${basePath}` || ref.startsWith(`${basePath}/`)) continue;\n offenders.push(ref);\n }\n\n if (offenders.length === 0) return;\n\n throw new Error(\n `\"${appName}\" is declared at ${basePath} but its build emitted assets rooted at /.\\n` +\n ` index.html references: ${offenders.slice(0, 3).join(\", \")}\\n` +\n \" The app would load a blank page. Set `base` from REBASE_APP_BASE in its\\n\" +\n \" build config — see docs/apps-and-runtimes.md §4.2.\"\n );\n}\n\n/**\n * The environment every static app is built with, wherever that build is driven from.\n *\n * Shared because there are two drivers — `foldFrontendIntoBundle` here, and\n * `buildAssetApp` in `build.ts` for a standalone `type: \"static\"` app — and they\n * had already drifted: the path variables were duplicated into both, so a fix\n * applied to one shipped a bundle built the old way from the other. One function\n * makes that impossible rather than merely unlikely.\n *\n * ## REBASE_APP_*\n *\n * The declared path is a build-time input, not only a serving concern: Vite\n * reads `base` from REBASE_APP_BASE, and the trailing slash is that field's\n * convention. See `assertBuiltForPath`.\n *\n * For an app declared at a URL these carry the path part only — `/` for\n * `https://admin.example.com`. The hostname is where the platform routes the\n * app, not something its assets should name: an absolute `base` would pin\n * every script to production, so `vite preview` and any other hostname the app\n * is opened on would load it from somewhere else.\n *\n * ## NODE_ENV\n *\n * A built app is a production artifact by construction, so build it as one. Not\n * a formality: the scaffold's `.env` carries `NODE_ENV=development` for the dev\n * backend, and Vite's `loadEnv` promotes a `NODE_ENV` found in an env file into\n * the build unless the environment already sets one. So `rebase build` and\n * `rebase cloud deploy` shipped a *development* bundle — `import.meta.env.DEV\n * === true`, development React, dev-only branches live — from commands whose\n * whole purpose is to produce something deployable. Setting it here is what\n * closes it: Vite consults the env file's NODE_ENV only when `process.env`\n * has none.\n *\n * ## VITE_API_URL\n *\n * An app served by the backend it talks to has its API on its own origin by\n * construction, so a baked-in absolute URL can only be wrong. It was: that same\n * `.env` carries `VITE_API_URL=http://localhost:3001` and\n * `frontend/vite.config.ts` reads the project root via `envDir: \"..\"`, so a\n * stock deploy shipped a site whose every request went to whoever ran the build\n * — passing every server-side health check on the way out. Blanking it here\n * fixes the bundle even for a project whose `.env` predates the `init` fix, or\n * was written by hand. Empty is the right value rather than a missing one: the\n * client falls back to `window.location.origin`, which keeps working when a\n * custom domain is added.\n *\n * Vite prioritises `process.env.VITE_*` over `.env` files, so an explicit\n * `VITE_API_URL=https://api.example.com rebase cloud deploy` still wins — the\n * cross-origin escape hatch stays open, it just has to be deliberate. Nothing on\n * this path loads the project `.env` into `process.env`, so a value inherited\n * here really was set by the caller.\n */\nexport function staticBuildEnv(appPath: string, appName: string): Record<string, string> {\n return {\n REBASE_APP_PATH: appPath,\n REBASE_APP_BASE: appPath === \"/\" ? \"/\" : `${appPath}/`,\n REBASE_APP_NAME: appName,\n NODE_ENV: \"production\",\n VITE_API_URL: process.env.VITE_API_URL ?? \"\"\n };\n}\n\n/**\n * Build the project's static apps and fold them into the backend bundle.\n *\n * Throws rather than exiting, so the caller decides whether a missing frontend\n * should fail its command — a `build` may reasonably want to stop, and so should\n * a deploy, but that is not this function's call to make.\n */\nexport async function foldFrontendIntoBundle(options: FoldOptions): Promise<FoldOutcome[]> {\n const { projectRoot, manifest, bundleDir, skipBuild } = options;\n const log = options.log ?? ((m: string) => console.log(m));\n\n const { apps, skipped } = foldableApps(manifest);\n for (const { reason } of skipped) log(chalk.yellow(` ⚠ ${reason}`));\n if (apps.length === 0) return [];\n\n const outcomes: FoldOutcome[] = [];\n\n for (const app of apps) {\n if (app.build && !skipBuild && !options.builtApps?.has(app.name)) {\n await execa(app.build, {\n cwd: projectRoot,\n stdio: toolStdio(options.quietStdout),\n shell: true,\n env: staticBuildEnv(app.path, app.name)\n });\n options.builtApps?.add(app.name);\n }\n\n const assetsDir = path.join(projectRoot, app.output as string);\n if (!fs.existsSync(assetsDir)) {\n // Exited 0 and produced nothing where the manifest says it should.\n // Folding that ships an empty site, which from the outside is\n // indistinguishable from a broken deploy.\n throw new Error(\n `\"${app.name}\" declared output \"${app.output}\" does not exist after building — ` +\n \"the bundle would ship without a frontend.\"\n );\n }\n\n const indexHtml = path.join(assetsDir, \"index.html\");\n if (fs.existsSync(indexHtml)) {\n assertBuiltForPath(fs.readFileSync(indexHtml, \"utf8\"), app.path, app.name);\n }\n\n const { fileCount } = foldStaticIntoBundle({\n bundleDir,\n assetsDir,\n appName: app.name,\n path: app.path,\n host: app.host,\n spa: app.spa,\n cms: app.cms\n });\n outcomes.push({ appName: app.name,\nfileCount,\npath: app.path,\n...(app.host ? { host: app.host } : {}) });\n }\n\n return outcomes;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,SAAgB,aAAa,UAI3B;CACE,MAAM,OAAsB,CAAC;CAC7B,MAAM,UAA8C,CAAC;CAErD,KAAK,MAAM,CAAC,MAAM,QAAQ,OAAO,QAAQ,SAAS,QAAQ,CAAC,CAAC,GAAG;EAC3D,IAAI,KAAK,SAAS,UAAU;EAC5B,IAAI,CAAC,IAAI,QAAQ;GACb,QAAQ,KAAK;IAAE;IAC3B,QAAQ,IAAI,KAAK;GAAiD,CAAC;GACvD;EACJ;EACA,MAAM,EAAE,MAAM,MAAM,YAAY,iBAAiB,MAAM,GAAG;EAC1D,KAAK,KAAK;GACN;GACA,OAAO,IAAI;GACX,QAAQ,IAAI;GACZ,MAAM;GACN,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;GACvB,KAAK,IAAI,OAAO;GAChB,KAAK,IAAI;EACb,CAAC;CACL;CAEA,KAAK,KAAK,iBAAiB;CAC3B,OAAO;EAAE;EACb;CAAQ;AACR;;;;;;;;;;;;;;AAeA,SAAgB,mBACZ,WACA,UACA,SACI;CACJ,IAAI,aAAa,KAAK;CAEtB,MAAM,YAAsB,CAAC;CAE7B,KAAK,MAAM,SAAS,UAAU,SAAS,iEAAO,GAAG;EAC7C,MAAM,MAAM,MAAM;EAGlB,IAAI,CAAC,IAAI,WAAW,GAAG,KAAK,IAAI,WAAW,IAAI,GAAG;EAClD,IAAI,QAAQ,GAAG,cAAc,IAAI,WAAW,GAAG,SAAS,EAAE,GAAG;EAC7D,UAAU,KAAK,GAAG;CACtB;CAEA,IAAI,UAAU,WAAW,GAAG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,aAAa,WAAW,MAAM,GAAG,IAAI,MAAM,IAAI,IAAI;EAG7E,MAAM,EAAE,cAAc,qBAAqB;GACvC;GACA;GACA,SAAS,IAAI;GACb,MAAM,IAAI;GACV,MAAM,IAAI;GACV,KAAK,IAAI;GACT,KAAK,IAAI;EACb,CAAC;EACD,SAAS,KAAK;GAAE,SAAS,IAAI;GACrC;GACA,MAAM,IAAI;GACV,GAAI,IAAI,OAAO,EAAE,MAAM,IAAI,KAAK,IAAI,CAAC;EAAG,CAAC;CACrC;CAEA,OAAO;AACX"}
|
|
@@ -2,7 +2,7 @@ import { n as getPMCommands, t as detectPackageManager } from "./package-manager
|
|
|
2
2
|
import { c as findProjectRoot, d as readEnvFile } from "./project-CasK56vN.js";
|
|
3
3
|
import { d as findBackendApp, m as manifestExists, p as loadManifest, x as writeManifest } from "./manifest-BtzDy7KQ.js";
|
|
4
4
|
import { t as DEV_BACKEND_URL_ENV } from "./dev-server-OJsUGZEB.js";
|
|
5
|
-
import { V as readLink } from "./context-
|
|
5
|
+
import { V as readLink } from "./context-DvIUbE-b.js";
|
|
6
6
|
import { n as COLLECTIONS_PATH_RULE, t as COLLECTIONS_FLAG_HELP } from "./path-flags-DNvtEi2-.js";
|
|
7
7
|
import { t as Refusal } from "./refusal-ReeeGP8a.js";
|
|
8
8
|
import { n as isLoadedCollectionFile } from "./collection-drift-BKj_BoMq.js";
|
|
@@ -522,4 +522,4 @@ export const SCHEMA_VERSION = ${JSON.stringify(schemaVersion)};
|
|
|
522
522
|
//#endregion
|
|
523
523
|
export { generateSdkCommand, writeRegistrationForBuild };
|
|
524
524
|
|
|
525
|
-
//# sourceMappingURL=generate_sdk-
|
|
525
|
+
//# sourceMappingURL=generate_sdk-_SQuSbJW.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate_sdk-BvcWvoUh.js","names":[],"sources":["../src/commands/generate_sdk.ts"],"sourcesContent":["/**\n * CLI command: generate-sdk\n *\n * Reads every collection file in a directory (default: ./config/collections) —\n * the files the backend serves, not the barrel's list — generates a typed\n * 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, computeSchemaVersion, deserializeCollections } from \"@rebasepro/types\";\nimport { CodegenError, generateSDK, GeneratedFile, toCollectionAccessor } from \"@rebasepro/codegen\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\nimport { findProjectRoot, readEnvFile } from \"../utils/project\";\nimport { DEV_BACKEND_URL_ENV } from \"../utils/dev-server\";\nimport { Refusal } from \"../utils/refusal\";\nimport { findBackendApp, loadManifest, manifestExists, writeManifest } from \"../manifest\";\nimport { readLink } from \"./cloud/context\";\nimport { COLLECTIONS_FLAG_HELP, COLLECTIONS_PATH_RULE } from \"../utils/path-flags\";\nimport { isLoadedCollectionFile } from \"../utils/collection-drift\";\n\ninterface GenerateSDKArgs {\n collectionsDir: string;\n output: string;\n cwd: string;\n /**\n * Where to read the schema from instead of local source.\n *\n * `link` uses this checkout's linked project; anything else is treated as\n * the base URL of a Rebase backend. This is what lets a repository that\n * contains no collections — a separate frontend, a second web app — generate\n * a typed client from the project it talks to.\n */\n from?: string;\n /** Bearer token for the contract endpoint. Falls back to REBASE_SERVICE_KEY. */\n token?: string;\n /**\n * Also register the generated `Database` for server-side code: write the\n * types and the `Register` augmentation into `config/generated/`. See\n * {@link writeRegistration}.\n */\n register?: boolean;\n /**\n * The directory holding `rebase.json`, where `--register` is remembered.\n * Found from `cwd` when not given.\n */\n projectRoot?: string;\n help?: boolean;\n}\n\n/** What `--register` writes, and what marks a project as having opted in. */\nexport const REGISTER_FILE = \"register.ts\";\n\n/** The first line of {@link REGISTER_FILE}: a file without it is the developer's own. */\nconst REGISTER_MARKER = \"// Auto-generated by `rebase generate-sdk --register`. Do not edit.\";\n\nconst REGISTER_SOURCE = `${REGISTER_MARKER}\n//\n// Registers this project's generated \\`Database\\` on \\`@rebasepro/types\\`, so\n// \\`context.data\\` in collection callbacks, \\`rebase.dataAsAdmin\\`, and the\n// \\`rebase\\` a function or a cron receives are typed from it. Every later\n// \\`rebase generate-sdk\\` (and \\`rebase dev\\`) refreshes this directory; delete\n// it to go back to untyped server-side data.\nimport type { Database } from \"./database.types\";\n\ndeclare module \"@rebasepro/types\" {\n interface Register {\n database: Database;\n }\n}\n`;\n\n/**\n * Where `--register` writes: `generated/` beside the collections directory,\n * which is `config/generated/` in a scaffolded project.\n *\n * Inside `config/` because that is the one directory both compiles of a\n * collection file include: the backend's program (it includes\n * `../config/**`) and the `config` package's own `tsc`. A registration\n * there that imported `../generated/sdk/database.types` pulled a file from\n * outside `config/` into that package's program, which TypeScript refuses\n * (the file is not under its `rootDir`) — so the types are copied in beside\n * the registration rather than imported from the SDK.\n */\nexport function registrationDir(collectionsDir: string): string {\n return path.join(path.dirname(path.resolve(collectionsDir)), \"generated\");\n}\n\n/** Whether this project opted in: the registration is there, and it is ours. */\nfunction hasRegistration(dir: string): boolean {\n try {\n return fs.readFileSync(path.join(dir, REGISTER_FILE), \"utf-8\").startsWith(REGISTER_MARKER);\n } catch {\n return false;\n }\n}\n\n/** Write a file only when its content changed, so a watcher on the directory does not restart for nothing. */\nfunction writeIfChanged(filePath: string, content: string): void {\n try {\n if (fs.readFileSync(filePath, \"utf-8\") === content) return;\n } catch {\n // Not there yet.\n }\n fs.writeFileSync(filePath, content, \"utf-8\");\n}\n\n/**\n * Write the generated `Database` and its `Register` augmentation into\n * {@link registrationDir}. Refuses to overwrite a `register.ts` it did not\n * write.\n */\nfunction writeRegistration(dir: string, databaseTypes: string): void {\n const registerPath = path.join(dir, REGISTER_FILE);\n if (fs.existsSync(registerPath) && !hasRegistration(dir)) {\n throw new Error(\n `${registerPath} exists and was not written by \"rebase generate-sdk --register\". ` +\n \"Move it, or register the Database there yourself.\"\n );\n }\n fs.mkdirSync(dir, { recursive: true });\n writeIfChanged(path.join(dir, \"database.types.ts\"), databaseTypes);\n writeIfChanged(registerPath, REGISTER_SOURCE);\n}\n\n/**\n * Write the server-side registration from the collection files in\n * `collectionsDir`, exactly as `rebase generate-sdk` writes it, for a build.\n *\n * Only for a project that asked for it: `registerDatabase` in `rebase.json`,\n * or a registration an earlier `--register` left, which is kept current. The\n * registration lives in gitignored `config/generated/`, so a fresh clone (a CI\n * job) has none until something writes it, and a bundle compiled without it\n * types `context.data` as untyped rows: callbacks that read a typed column\n * fail to compile there while they compile locally.\n *\n * Returns the directory written, or null when there was nothing to do.\n * Throws when a `register.ts` there is not ours, as `generate-sdk` refuses.\n */\nexport async function writeRegistrationForBuild(collectionsDir: string, registerDatabase: boolean): Promise<string | null> {\n const dir = registrationDir(collectionsDir);\n if (!registerDatabase && !hasRegistration(dir)) return null;\n if (!fs.existsSync(collectionsDir)) return null;\n const collections = await loadCollections(collectionsDir);\n if (collections.length === 0) return null;\n collections.sort((a, b) => a.slug.localeCompare(b.slug));\n const databaseTypes = generateSDK(collections, { includeReadme: false })\n .find((file) => file.path === \"database.types.ts\")?.content;\n if (databaseTypes === undefined) return null;\n writeRegistration(dir, databaseTypes);\n return dir;\n}\n\n/**\n * Whether `rebase.json` asks for the registration (`registerDatabase: true` on\n * the backend app). That is what survives a clone: `generated/` is gitignored,\n * so a `register.ts` from an earlier run is not there to say it.\n *\n * An unreadable manifest answers no; `rebase build` is where it is reported.\n */\nfunction manifestRegisters(projectRoot: string | undefined): boolean {\n if (!projectRoot || !manifestExists(projectRoot)) return false;\n try {\n return findBackendApp(loadManifest(projectRoot).manifest)?.app.registerDatabase === true;\n } catch {\n return false;\n }\n}\n\n/**\n * Remember `--register` in `rebase.json`, so later runs, `rebase dev` and a\n * fresh clone keep registering. Returns where it was written, or why not.\n *\n * Never creates the file: a project without one is synthesized from its\n * layout, and writing one is `rebase apps init`'s decision, not this flag's.\n */\nfunction rememberRegistration(projectRoot: string | undefined): { written: string } | { skipped: string } {\n if (!projectRoot || !manifestExists(projectRoot)) {\n return { skipped: \"No rebase.json here, so the choice lasts as long as the generated files.\" };\n }\n let loaded: ReturnType<typeof loadManifest>;\n try {\n loaded = loadManifest(projectRoot);\n } catch (error) {\n return { skipped: `rebase.json could not be read (${error instanceof Error ? error.message : String(error)}).` };\n }\n const backend = findBackendApp(loaded.manifest);\n if (!backend) return { skipped: \"rebase.json declares no backend app to remember it on.\" };\n if (backend.app.registerDatabase === true) return { written: loaded.filePath ?? projectRoot };\n const manifest = {\n ...loaded.manifest,\n apps: { ...loaded.manifest.apps, [backend.name]: { ...backend.app, registerDatabase: true } }\n };\n return { written: writeManifest(projectRoot, manifest) };\n}\n\n/**\n * Load the collections the backend serves, the way it finds them.\n *\n * A directory is read as `loadCollectionsFromDirectory` in @rebasepro/server\n * reads it: every top-level collection file, each default-exporting one\n * collection. The barrel (`index.ts`) is not a registry. The runtime, the admin\n * panel, `rebase build` and `rebase schema generate` all scan the directory, and\n * the barrel only orders the panel's navigation and declares\n * `defaultSecurityRules`. This command used to read the barrel instead, so a\n * collection file left out of it was created, served at `/api/data/<slug>` and\n * listed in the panel, and missing from the typed SDK alone.\n *\n * A file that does not load is fatal, as it is at boot: `rebase dev` runs this\n * on every save, and skipping the file would overwrite good types with a\n * `Database` that is silently short a collection.\n *\n * A path to a single module is read as the runtime reads one: its\n * `backendCollections`, or its `collections`.\n *\n * A missing directory, a missing jiti and a module that exports no collections\n * are `Refusal`s: the message says all there is. A collection file that throws\n * on import is not: that is the project's own code failing, and the stack\n * `--debug` prints points at the line, so `bin/rebase.js` keeps its hint.\n */\nasync function loadCollections(collectionsDir: string): Promise<CollectionConfig[]> {\n const absDir = path.resolve(collectionsDir);\n\n if (!fs.existsSync(absDir)) {\n throw new Refusal(`Collections directory not found: ${absDir} (${COLLECTIONS_PATH_RULE})`);\n }\n\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 Refusal(\n `Could not load 'jiti'. Install it with: ${installCmd}\\n` +\n \"jiti is required to dynamically import TypeScript collection definitions.\"\n );\n }\n\n if (!fs.statSync(absDir).isDirectory()) {\n const mod = jiti(path.dirname(absDir), { interopDefault: true, esmResolve: true })(absDir);\n const listed = mod.backendCollections ?? mod.collections ?? mod.default;\n if (Array.isArray(listed)) return listed as CollectionConfig[];\n throw new Refusal(\n `Could not extract collections from ${absDir}.\\n` +\n \"A single collections module exports `backendCollections` or `collections`: an array of collections.\"\n );\n }\n\n const jitiInstance = jiti(absDir, {\n interopDefault: true,\n esmResolve: true\n });\n\n const collections: CollectionConfig[] = [];\n const failures: string[] = [];\n const files = fs.readdirSync(absDir).filter(isLoadedCollectionFile).sort();\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 {\n failures.push(`${file}: no default export of a collection`);\n }\n } catch (err) {\n failures.push(`${file}: ${(err as Error).message}`);\n }\n }\n\n if (failures.length > 0) {\n throw new Error(\n `Could not load ${failures.length} collection file(s) from ${absDir}:\\n` +\n failures.map(failure => ` • ${failure}`).join(\"\\n\") +\n \"\\n\\nEvery collection file must import cleanly and default-export a collection — \" +\n \"the backend refuses to boot on the same file.\"\n );\n }\n\n return collections;\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\nfunction printSdkHelp(): void {\n console.log(`\n${chalk.bold(\"rebase generate-sdk\")} — generate a typed client from a project's schema\n\n${chalk.bold(\"Usage\")}\n rebase generate-sdk [options]\n\n${chalk.bold(\"Options\")}\n -c, --collections <dir> ${COLLECTIONS_FLAG_HELP}\n (--collections-dir is accepted too)\n -o, --output <dir> Where to write the SDK (default: ./generated/sdk)\n (--out is accepted too, as on 'rebase build')\n --from <link|url> Fetch the schema from a running project instead of\n local source. \"link\" uses this checkout's linked project.\n --token <token> Bearer token for the contract endpoint\n (default: $REBASE_SERVICE_KEY)\n --register Also type server-side data: write the types and the\n Register declaration to config/generated/, and\n remember it in rebase.json so later runs keep it.\n -h, --help Show this help\n\n${chalk.bold(\"Examples\")}\n rebase generate-sdk From local collections\n rebase generate-sdk --from link From the linked project\n rebase generate-sdk --from https://api.acme.com From any Rebase backend\n rebase generate-sdk --register Type context.data and rebase.dataAsAdmin too\n`.trim());\n}\n\n/**\n * Fetch collections from a running project's contract endpoint.\n *\n * The payload replaces relation `target` functions with slug references, so it\n * has to be rehydrated before the generator sees it — the generator *calls*\n * `target()` to decide whether a foreign key is a string or a number, and a\n * missing target silently degrades that to a union rather than failing.\n */\n/** What `--from` sent to the contract endpoint, and which keys it left behind. */\ninterface ContractCredential {\n /** The bearer token sent: `--token`, the shell's key, or none. */\n sent: \"token\" | \"ambient\" | null;\n /** `REBASE_SERVICE_KEY` is in the shell environment. */\n shellKey: boolean;\n /** `REBASE_SERVICE_KEY` is in the project's `.env`. */\n envFileKey: boolean;\n}\n\n/**\n * What to say when the contract endpoint refuses, by what was and was not sent.\n *\n * \"Set REBASE_SERVICE_KEY\" is only right when no key exists. The shell's key is\n * withheld from every host but the linked project, and `.env`'s is never read\n * here — it is the local backend's key, and the linked project is usually a\n * deployed one — so telling a reader whose key is in `.env` to set it sends them\n * to fix something that is not broken.\n */\nfunction contractRefusalHint(credential: ContractCredential): string[] {\n if (credential.sent === \"token\") {\n return [\"The token passed with --token was refused: pass a service key, or an admin's token.\"];\n }\n if (credential.sent === \"ambient\") {\n return [\"REBASE_SERVICE_KEY was sent and refused: it is not this project's service key. Pass the right one with --token.\"];\n }\n if (credential.shellKey) {\n return [\n \"REBASE_SERVICE_KEY is set, but it is only sent to this checkout's linked project, and this host is not it.\",\n \"Pass the key with --token to send it here.\"\n ];\n }\n if (credential.envFileKey) {\n return [\n \"REBASE_SERVICE_KEY in .env is not sent: --from sends the shell's REBASE_SERVICE_KEY, and only to this checkout's linked project.\",\n \"Pass the key with --token.\"\n ];\n }\n return [\"Pass --token <key>, a service key or an admin's token. The shell's REBASE_SERVICE_KEY is sent only to this checkout's linked project.\"];\n}\n\nasync function fetchRemoteCollections(\n baseUrl: string,\n token: string | undefined,\n credential: ContractCredential\n): Promise<{ collections: CollectionConfig[]; schemaVersion: string }> {\n const url = `${baseUrl.replace(/\\/+$/, \"\")}/api/meta/contract`;\n\n const headers: Record<string, string> = { accept: \"application/json\" };\n if (token) headers.authorization = `Bearer ${token}`;\n\n let response: Response;\n try {\n response = await fetch(url, { headers });\n } catch (err) {\n console.log(chalk.red(` ✗ Could not reach ${url}`));\n console.log(chalk.gray(` ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n }\n\n if (response.status === 401 || response.status === 403) {\n console.log(chalk.red(` ✗ Not authorized to read the project contract (${response.status}).`));\n console.log(chalk.gray(\" The contract describes every table and relation, so it is admin-only.\"));\n for (const line of contractRefusalHint(credential)) console.log(chalk.gray(` ${line}`));\n process.exit(1);\n }\n\n if (response.status === 404) {\n console.log(chalk.red(\" ✗ This server has no contract endpoint.\"));\n console.log(chalk.gray(\" It needs to be running Rebase 0.11 or newer.\"));\n process.exit(1);\n }\n\n if (!response.ok) {\n console.log(chalk.red(` ✗ Contract request failed with ${response.status}.`));\n process.exit(1);\n }\n\n const contract = await response.json() as {\n collections?: unknown[];\n schemaVersion?: string;\n };\n\n if (!Array.isArray(contract.collections)) {\n console.log(chalk.red(\" ✗ The contract response did not contain collections.\"));\n process.exit(1);\n }\n\n return {\n collections: deserializeCollections(contract.collections),\n schemaVersion: contract.schemaVersion ?? \"unknown\"\n };\n}\n\n/**\n * Decide whether the ambient service key may be sent to this host.\n *\n * `REBASE_SERVICE_KEY` grants full admin bypass. Attaching it to whatever URL\n * happened to be passed — or, worse, to whatever a committed `.rebase/cloud.json`\n * points at — would hand the project's most powerful credential to a host nobody\n * vetted. An explicit `--token` is a decision the caller made; the ambient\n * variable is not, so it only travels to the project this checkout is linked to.\n */\nfunction mayUseAmbientKey(target: string, cwd: string): boolean {\n const link = readLink(findProjectRoot(cwd) ?? cwd);\n if (!link?.apiUrl) return false;\n try {\n // Origin, not host: with a link recorded as https, an `http://` target\n // for the same host would otherwise pass and send the key in cleartext.\n return new URL(link.apiUrl).origin === new URL(target).origin;\n } catch {\n return false;\n }\n}\n\n/**\n * The base URL to show in the printed usage example.\n *\n * `rebase dev` binds a port derived from the project path, not 3001, and writes\n * the one it actually got to `.rebase/state.json`. Printing a hardcoded\n * `localhost:3001` sent people to a port nothing was listening on — or, with\n * several projects on one machine, to a different project's backend. Prefer the\n * port `rebase dev` says it is starting the backend on (`DEV_BACKEND_URL_ENV`:\n * it regenerates the SDK before the backend binds), then the port this project\n * last ran on; fall back to the literal only when the project has never been\n * started.\n */\nexport function resolveExampleBaseUrl(cwd: string): string {\n const fromDev = process.env[DEV_BACKEND_URL_ENV]?.trim();\n if (fromDev) return fromDev;\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n try {\n const state = JSON.parse(fs.readFileSync(path.join(projectRoot, \".rebase\", \"state.json\"), \"utf-8\"));\n if (typeof state.baseUrl === \"string\" && state.baseUrl) return state.baseUrl;\n if (typeof state.port === \"number\") return `http://localhost:${state.port}`;\n } catch {\n // Never started, or the file is unreadable — fall through.\n }\n return \"http://localhost:3001\";\n}\n\n/** Whether a slug can be written as `rebase.data.<slug>` rather than a lookup. */\nexport function isIdentifierLike(slug: string): boolean {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(slug);\n}\n\n/** Resolve `--from` into a base URL, following the link file when asked. */\nfunction resolveSchemaSource(from: string, cwd: string): string {\n if (from !== \"link\") {\n // A bare hostname or a typo would otherwise be handed to `fetch` and fail\n // with something unhelpful; a non-http scheme has no business here at all.\n let parsed: URL;\n try {\n parsed = new URL(from);\n } catch {\n console.log(chalk.red(` ✗ \"${from}\" is not a valid URL.`));\n console.log(chalk.gray(\" Pass a full URL, e.g. https://api.example.com, or \\\"link\\\".\"));\n process.exit(1);\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n console.log(chalk.red(\" ✗ The project URL must be http or https.\"));\n process.exit(1);\n }\n return from;\n }\n\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n const link = readLink(projectRoot);\n\n if (!link) {\n console.log(chalk.red(\" ✗ This checkout is not linked to a project.\"));\n console.log(chalk.gray(\" Run `rebase cloud link <url>`, or pass --from <url>.\"));\n process.exit(1);\n }\n\n const apiUrl = link.apiUrl;\n if (!apiUrl) {\n console.log(chalk.red(\" ✗ The project link has no API URL.\"));\n console.log(chalk.gray(\" Re-link with `rebase cloud link <url>` to record one.\"));\n process.exit(1);\n }\n\n return apiUrl;\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 if (args.help) {\n printSdkHelp();\n return;\n }\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\n let collections: CollectionConfig[];\n let remoteSchemaVersion: string | undefined;\n\n if (args.from) {\n const baseUrl = resolveSchemaSource(args.from, cwd);\n console.log(` ${chalk.gray(\"Project:\")} ${baseUrl}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Fetching the project contract...\"));\n\n const ambient = mayUseAmbientKey(baseUrl, cwd)\n ? process.env.REBASE_SERVICE_KEY\n : undefined;\n\n if (!args.token && !ambient && process.env.REBASE_SERVICE_KEY) {\n console.log(chalk.dim(\n \" (not sending REBASE_SERVICE_KEY — this host is not the linked project; pass --token to override)\"\n ));\n }\n\n const remote = await fetchRemoteCollections(baseUrl, args.token || ambient, {\n sent: args.token ? \"token\" : ambient ? \"ambient\" : null,\n shellKey: Boolean(process.env.REBASE_SERVICE_KEY),\n envFileKey: Boolean(readEnvFile(findProjectRoot(cwd) ?? cwd).REBASE_SERVICE_KEY)\n });\n collections = remote.collections;\n remoteSchemaVersion = remote.schemaVersion;\n } else {\n // A headless project has no collections directory by design: its API is\n // introspected from the live database at boot, and there is nothing here\n // to generate a client from. The scaffold ships `pnpm generate:sdk`\n // anyway, so the documented headless path had a script that could only\n // ever fail — and it failed with a path, which reads as a broken install\n // rather than a question with an answer.\n if (!fs.existsSync(resolvedCollectionsDir)) {\n console.log(chalk.gray(\n \" ○ This project derives its API from the database — \"\n + \"run `rebase schema introspect` first.\"\n ));\n console.log(chalk.gray(\n ` Nothing to generate from: ${resolvedCollectionsDir} does not exist.`\n ));\n console.log(\"\");\n return;\n }\n console.log(` ${chalk.gray(\"Collections:\")} ${resolvedCollectionsDir}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Loading collection definitions...\"));\n collections = await loadCollections(resolvedCollectionsDir);\n }\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 let files: GeneratedFile[];\n try {\n files = generateSDK(collections, { baseUrl: resolveExampleBaseUrl(cwd) });\n } catch (err) {\n // A schema that cannot be expressed as valid TypeScript — two slugs\n // that collide on one accessor, a slug with no usable name. The\n // generator refuses rather than emitting a file that does not compile,\n // or one that silently routes a collection's reads to another's table.\n if (err instanceof CodegenError) {\n console.log(\"\");\n console.log(chalk.red(` ✗ ${err.message}`));\n process.exit(1);\n }\n throw err;\n }\n\n // Stamp the schema this SDK was built from.\n //\n // Without it, an app in a separate repository has no way to know its client\n // is stale: the backend moves on, the frontend keeps compiling against types\n // captured weeks ago, and the mismatch only surfaces as a runtime error. With\n // it, CI can compare against `/api/meta/schema-version` and say so.\n //\n // No generation timestamp. Collections are sorted above precisely so that\n // the same schema produces the same bytes; a timestamp put that back,\n // turning every regeneration into a diff and making the obvious staleness\n // gate — `rebase generate-sdk && git diff --exit-code` — impossible to pass.\n // `SCHEMA_VERSION` already identifies what this was built from, and does it\n // in a way that can be compared against a running project.\n const schemaVersion = remoteSchemaVersion ?? computeSchemaVersion(collections);\n files.push({\n path: \"schema.meta.ts\",\n content: `// Auto-generated by \\`rebase generate-sdk\\`. Do not edit.\n//\n// The schema version this SDK was generated from. Compare it against the\n// project's current version to detect drift:\n//\n// curl -s <api-url>/api/meta/schema-version\n//\n// Pass it to the client as \\`schemaVersion\\` and every request carries it in\n// the \\`x-rebase-schema\\` header, so the server can name the drift instead of\n// answering a renamed field with a bare 400.\nexport const SCHEMA_VERSION = ${JSON.stringify(schemaVersion)};\n`\n });\n\n console.log(chalk.green(` ✓ Generated ${files.length} file(s)`));\n console.log(chalk.gray(` schema ${schemaVersion}`));\n\n // 3. Write to disk\n console.log(chalk.cyan(` → Writing to ${resolvedOutput}...`));\n writeFiles(resolvedOutput, files);\n\n // 4. The server-side registration: on request, and kept current once a\n // project has it, so `rebase dev` regenerating the SDK never leaves the\n // server typed against an older schema than the client.\n const registerDir = registrationDir(resolvedCollectionsDir);\n const projectRoot = args.projectRoot ?? findProjectRoot(cwd) ?? undefined;\n if (args.register || hasRegistration(registerDir) || manifestRegisters(projectRoot)) {\n if (!fs.existsSync(path.dirname(registerDir))) {\n console.log(chalk.red(` ✗ No ${path.dirname(registerDir)} to register the Database in.`));\n console.log(chalk.gray(\" --register writes beside the collections directory; pass --collections.\"));\n process.exit(1);\n return;\n }\n const databaseTypes = files.find((file) => file.path === \"database.types.ts\")?.content;\n if (databaseTypes !== undefined) {\n try {\n writeRegistration(registerDir, databaseTypes);\n } catch (error) {\n console.log(chalk.red(` ✗ ${error instanceof Error ? error.message : String(error)}`));\n process.exit(1);\n return;\n }\n console.log(chalk.green(` ✓ Registered the Database for server-side code in ${registerDir}`));\n if (args.register) {\n const remembered = rememberRegistration(projectRoot);\n if (\"written\" in remembered) {\n console.log(chalk.gray(` Remembered in ${path.relative(cwd, remembered.written) || \"rebase.json\"} (registerDatabase).`));\n } else {\n console.log(chalk.yellow(` ${remembered.skipped}`));\n }\n }\n }\n }\n\n console.log(\"\");\n console.log(chalk.green.bold(\" ✓ SDK generated successfully!\"));\n console.log(\"\");\n const typesImport = `./${path.relative(cwd, path.join(resolvedOutput, \"database.types\"))}`;\n const metaImport = `./${path.relative(cwd, path.join(resolvedOutput, \"schema.meta\"))}`;\n const exampleSlug = collections[0]?.slug || \"my_collection\";\n\n console.log(chalk.gray(\" Usage:\"));\n console.log(chalk.gray(\" import { createRebaseClient } from '@rebasepro/client';\"));\n console.log(chalk.gray(` import { collectionsDictionary, type Database } from '${typesImport}';`));\n console.log(chalk.gray(` import { SCHEMA_VERSION } from '${metaImport}';`));\n console.log(\"\");\n console.log(chalk.gray(\" const rebase = createRebaseClient<Database>({\"));\n console.log(chalk.gray(` baseUrl: '${resolveExampleBaseUrl(cwd)}',`));\n // Sent as `x-rebase-schema` on every request. Costs one line here and is\n // the difference between a server that can say \"this client is three\n // deploys behind\" and one that can only reject a field it does not know.\n console.log(chalk.gray(\" schemaVersion: SCHEMA_VERSION,\"));\n // Without the dictionary a hyphenated slug is not resolvable from the\n // property name alone, and the request 404s at runtime.\n console.log(chalk.gray(\" collections: collectionsDictionary,\"));\n console.log(chalk.gray(\" // token: 'your-jwt-token',\"));\n console.log(chalk.gray(\" });\"));\n console.log(\"\");\n // `rebase.data.<accessor>` is the typed surface, so it is what gets printed.\n // `rebase.data.collection(slug)` exists too, but it is generic over\n // `Record<string, unknown>` and has no link to `Database` — it was the\n // headline example here for a while, which advertised the one call shape\n // that throws away the types this command just generated.\n const exampleAccessor = toCollectionAccessor(exampleSlug);\n const exampleAccess = isIdentifierLike(exampleAccessor)\n ? `rebase.data.${exampleAccessor}`\n : `rebase.data[${JSON.stringify(exampleAccessor)}]`;\n console.log(chalk.gray(` const { data } = await ${exampleAccess}.find();`));\n console.log(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAa,gBAAgB;;AAG7B,IAAM,kBAAkB;AAExB,IAAM,kBAAkB,GAAG,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4B3C,SAAgB,gBAAgB,gBAAgC;CAC5D,OAAO,KAAK,KAAK,KAAK,QAAQ,KAAK,QAAQ,cAAc,CAAC,GAAG,WAAW;AAC5E;;AAGA,SAAS,gBAAgB,KAAsB;CAC3C,IAAI;EACA,OAAO,GAAG,aAAa,KAAK,KAAK,KAAK,aAAa,GAAG,OAAO,CAAC,CAAC,WAAW,eAAe;CAC7F,QAAQ;EACJ,OAAO;CACX;AACJ;;AAGA,SAAS,eAAe,UAAkB,SAAuB;CAC7D,IAAI;EACA,IAAI,GAAG,aAAa,UAAU,OAAO,MAAM,SAAS;CACxD,QAAQ,CAER;CACA,GAAG,cAAc,UAAU,SAAS,OAAO;AAC/C;;;;;;AAOA,SAAS,kBAAkB,KAAa,eAA6B;CACjE,MAAM,eAAe,KAAK,KAAK,KAAK,aAAa;CACjD,IAAI,GAAG,WAAW,YAAY,KAAK,CAAC,gBAAgB,GAAG,GACnD,MAAM,IAAI,MACN,GAAG,aAAa,mHAEpB;CAEJ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|
1
|
+
{"version":3,"file":"generate_sdk-_SQuSbJW.js","names":[],"sources":["../src/commands/generate_sdk.ts"],"sourcesContent":["/**\n * CLI command: generate-sdk\n *\n * Reads every collection file in a directory (default: ./config/collections) —\n * the files the backend serves, not the barrel's list — generates a typed\n * 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, computeSchemaVersion, deserializeCollections } from \"@rebasepro/types\";\nimport { CodegenError, generateSDK, GeneratedFile, toCollectionAccessor } from \"@rebasepro/codegen\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\nimport { findProjectRoot, readEnvFile } from \"../utils/project\";\nimport { DEV_BACKEND_URL_ENV } from \"../utils/dev-server\";\nimport { Refusal } from \"../utils/refusal\";\nimport { findBackendApp, loadManifest, manifestExists, writeManifest } from \"../manifest\";\nimport { readLink } from \"./cloud/context\";\nimport { COLLECTIONS_FLAG_HELP, COLLECTIONS_PATH_RULE } from \"../utils/path-flags\";\nimport { isLoadedCollectionFile } from \"../utils/collection-drift\";\n\ninterface GenerateSDKArgs {\n collectionsDir: string;\n output: string;\n cwd: string;\n /**\n * Where to read the schema from instead of local source.\n *\n * `link` uses this checkout's linked project; anything else is treated as\n * the base URL of a Rebase backend. This is what lets a repository that\n * contains no collections — a separate frontend, a second web app — generate\n * a typed client from the project it talks to.\n */\n from?: string;\n /** Bearer token for the contract endpoint. Falls back to REBASE_SERVICE_KEY. */\n token?: string;\n /**\n * Also register the generated `Database` for server-side code: write the\n * types and the `Register` augmentation into `config/generated/`. See\n * {@link writeRegistration}.\n */\n register?: boolean;\n /**\n * The directory holding `rebase.json`, where `--register` is remembered.\n * Found from `cwd` when not given.\n */\n projectRoot?: string;\n help?: boolean;\n}\n\n/** What `--register` writes, and what marks a project as having opted in. */\nexport const REGISTER_FILE = \"register.ts\";\n\n/** The first line of {@link REGISTER_FILE}: a file without it is the developer's own. */\nconst REGISTER_MARKER = \"// Auto-generated by `rebase generate-sdk --register`. Do not edit.\";\n\nconst REGISTER_SOURCE = `${REGISTER_MARKER}\n//\n// Registers this project's generated \\`Database\\` on \\`@rebasepro/types\\`, so\n// \\`context.data\\` in collection callbacks, \\`rebase.dataAsAdmin\\`, and the\n// \\`rebase\\` a function or a cron receives are typed from it. Every later\n// \\`rebase generate-sdk\\` (and \\`rebase dev\\`) refreshes this directory; delete\n// it to go back to untyped server-side data.\nimport type { Database } from \"./database.types\";\n\ndeclare module \"@rebasepro/types\" {\n interface Register {\n database: Database;\n }\n}\n`;\n\n/**\n * Where `--register` writes: `generated/` beside the collections directory,\n * which is `config/generated/` in a scaffolded project.\n *\n * Inside `config/` because that is the one directory both compiles of a\n * collection file include: the backend's program (it includes\n * `../config/**`) and the `config` package's own `tsc`. A registration\n * there that imported `../generated/sdk/database.types` pulled a file from\n * outside `config/` into that package's program, which TypeScript refuses\n * (the file is not under its `rootDir`) — so the types are copied in beside\n * the registration rather than imported from the SDK.\n */\nexport function registrationDir(collectionsDir: string): string {\n return path.join(path.dirname(path.resolve(collectionsDir)), \"generated\");\n}\n\n/** Whether this project opted in: the registration is there, and it is ours. */\nfunction hasRegistration(dir: string): boolean {\n try {\n return fs.readFileSync(path.join(dir, REGISTER_FILE), \"utf-8\").startsWith(REGISTER_MARKER);\n } catch {\n return false;\n }\n}\n\n/** Write a file only when its content changed, so a watcher on the directory does not restart for nothing. */\nfunction writeIfChanged(filePath: string, content: string): void {\n try {\n if (fs.readFileSync(filePath, \"utf-8\") === content) return;\n } catch {\n // Not there yet.\n }\n fs.writeFileSync(filePath, content, \"utf-8\");\n}\n\n/**\n * Write the generated `Database` and its `Register` augmentation into\n * {@link registrationDir}. Refuses to overwrite a `register.ts` it did not\n * write.\n */\nfunction writeRegistration(dir: string, databaseTypes: string): void {\n const registerPath = path.join(dir, REGISTER_FILE);\n if (fs.existsSync(registerPath) && !hasRegistration(dir)) {\n throw new Error(\n `${registerPath} exists and was not written by \"rebase generate-sdk --register\". ` +\n \"Move it, or register the Database there yourself.\"\n );\n }\n fs.mkdirSync(dir, { recursive: true });\n writeIfChanged(path.join(dir, \"database.types.ts\"), databaseTypes);\n writeIfChanged(registerPath, REGISTER_SOURCE);\n}\n\n/**\n * Write the server-side registration from the collection files in\n * `collectionsDir`, exactly as `rebase generate-sdk` writes it, for a build.\n *\n * Only for a project that asked for it: `registerDatabase` in `rebase.json`,\n * or a registration an earlier `--register` left, which is kept current. The\n * registration lives in gitignored `config/generated/`, so a fresh clone (a CI\n * job) has none until something writes it, and a bundle compiled without it\n * types `context.data` as untyped rows: callbacks that read a typed column\n * fail to compile there while they compile locally.\n *\n * Returns the directory written, or null when there was nothing to do.\n * Throws when a `register.ts` there is not ours, as `generate-sdk` refuses.\n */\nexport async function writeRegistrationForBuild(collectionsDir: string, registerDatabase: boolean): Promise<string | null> {\n const dir = registrationDir(collectionsDir);\n if (!registerDatabase && !hasRegistration(dir)) return null;\n if (!fs.existsSync(collectionsDir)) return null;\n const collections = await loadCollections(collectionsDir);\n if (collections.length === 0) return null;\n collections.sort((a, b) => a.slug.localeCompare(b.slug));\n const databaseTypes = generateSDK(collections, { includeReadme: false })\n .find((file) => file.path === \"database.types.ts\")?.content;\n if (databaseTypes === undefined) return null;\n writeRegistration(dir, databaseTypes);\n return dir;\n}\n\n/**\n * Whether `rebase.json` asks for the registration (`registerDatabase: true` on\n * the backend app). That is what survives a clone: `generated/` is gitignored,\n * so a `register.ts` from an earlier run is not there to say it.\n *\n * An unreadable manifest answers no; `rebase build` is where it is reported.\n */\nfunction manifestRegisters(projectRoot: string | undefined): boolean {\n if (!projectRoot || !manifestExists(projectRoot)) return false;\n try {\n return findBackendApp(loadManifest(projectRoot).manifest)?.app.registerDatabase === true;\n } catch {\n return false;\n }\n}\n\n/**\n * Remember `--register` in `rebase.json`, so later runs, `rebase dev` and a\n * fresh clone keep registering. Returns where it was written, or why not.\n *\n * Never creates the file: a project without one is synthesized from its\n * layout, and writing one is `rebase apps init`'s decision, not this flag's.\n */\nfunction rememberRegistration(projectRoot: string | undefined): { written: string } | { skipped: string } {\n if (!projectRoot || !manifestExists(projectRoot)) {\n return { skipped: \"No rebase.json here, so the choice lasts as long as the generated files.\" };\n }\n let loaded: ReturnType<typeof loadManifest>;\n try {\n loaded = loadManifest(projectRoot);\n } catch (error) {\n return { skipped: `rebase.json could not be read (${error instanceof Error ? error.message : String(error)}).` };\n }\n const backend = findBackendApp(loaded.manifest);\n if (!backend) return { skipped: \"rebase.json declares no backend app to remember it on.\" };\n if (backend.app.registerDatabase === true) return { written: loaded.filePath ?? projectRoot };\n const manifest = {\n ...loaded.manifest,\n apps: { ...loaded.manifest.apps, [backend.name]: { ...backend.app, registerDatabase: true } }\n };\n return { written: writeManifest(projectRoot, manifest) };\n}\n\n/**\n * Load the collections the backend serves, the way it finds them.\n *\n * A directory is read as `loadCollectionsFromDirectory` in @rebasepro/server\n * reads it: every top-level collection file, each default-exporting one\n * collection. The barrel (`index.ts`) is not a registry. The runtime, the admin\n * panel, `rebase build` and `rebase schema generate` all scan the directory, and\n * the barrel only orders the panel's navigation and declares\n * `defaultSecurityRules`. This command used to read the barrel instead, so a\n * collection file left out of it was created, served at `/api/data/<slug>` and\n * listed in the panel, and missing from the typed SDK alone.\n *\n * A file that does not load is fatal, as it is at boot: `rebase dev` runs this\n * on every save, and skipping the file would overwrite good types with a\n * `Database` that is silently short a collection.\n *\n * A path to a single module is read as the runtime reads one: its\n * `backendCollections`, or its `collections`.\n *\n * A missing directory, a missing jiti and a module that exports no collections\n * are `Refusal`s: the message says all there is. A collection file that throws\n * on import is not: that is the project's own code failing, and the stack\n * `--debug` prints points at the line, so `bin/rebase.js` keeps its hint.\n */\nasync function loadCollections(collectionsDir: string): Promise<CollectionConfig[]> {\n const absDir = path.resolve(collectionsDir);\n\n if (!fs.existsSync(absDir)) {\n throw new Refusal(`Collections directory not found: ${absDir} (${COLLECTIONS_PATH_RULE})`);\n }\n\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 Refusal(\n `Could not load 'jiti'. Install it with: ${installCmd}\\n` +\n \"jiti is required to dynamically import TypeScript collection definitions.\"\n );\n }\n\n if (!fs.statSync(absDir).isDirectory()) {\n const mod = jiti(path.dirname(absDir), { interopDefault: true, esmResolve: true })(absDir);\n const listed = mod.backendCollections ?? mod.collections ?? mod.default;\n if (Array.isArray(listed)) return listed as CollectionConfig[];\n throw new Refusal(\n `Could not extract collections from ${absDir}.\\n` +\n \"A single collections module exports `backendCollections` or `collections`: an array of collections.\"\n );\n }\n\n const jitiInstance = jiti(absDir, {\n interopDefault: true,\n esmResolve: true\n });\n\n const collections: CollectionConfig[] = [];\n const failures: string[] = [];\n const files = fs.readdirSync(absDir).filter(isLoadedCollectionFile).sort();\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 {\n failures.push(`${file}: no default export of a collection`);\n }\n } catch (err) {\n failures.push(`${file}: ${(err as Error).message}`);\n }\n }\n\n if (failures.length > 0) {\n throw new Error(\n `Could not load ${failures.length} collection file(s) from ${absDir}:\\n` +\n failures.map(failure => ` • ${failure}`).join(\"\\n\") +\n \"\\n\\nEvery collection file must import cleanly and default-export a collection — \" +\n \"the backend refuses to boot on the same file.\"\n );\n }\n\n return collections;\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\nfunction printSdkHelp(): void {\n console.log(`\n${chalk.bold(\"rebase generate-sdk\")} — generate a typed client from a project's schema\n\n${chalk.bold(\"Usage\")}\n rebase generate-sdk [options]\n\n${chalk.bold(\"Options\")}\n -c, --collections <dir> ${COLLECTIONS_FLAG_HELP}\n (--collections-dir is accepted too)\n -o, --output <dir> Where to write the SDK (default: ./generated/sdk)\n (--out is accepted too, as on 'rebase build')\n --from <link|url> Fetch the schema from a running project instead of\n local source. \"link\" uses this checkout's linked project.\n --token <token> Bearer token for the contract endpoint\n (default: $REBASE_SERVICE_KEY)\n --register Also type server-side data: write the types and the\n Register declaration to config/generated/, and\n remember it in rebase.json so later runs keep it.\n -h, --help Show this help\n\n${chalk.bold(\"Examples\")}\n rebase generate-sdk From local collections\n rebase generate-sdk --from link From the linked project\n rebase generate-sdk --from https://api.acme.com From any Rebase backend\n rebase generate-sdk --register Type context.data and rebase.dataAsAdmin too\n`.trim());\n}\n\n/**\n * Fetch collections from a running project's contract endpoint.\n *\n * The payload replaces relation `target` functions with slug references, so it\n * has to be rehydrated before the generator sees it — the generator *calls*\n * `target()` to decide whether a foreign key is a string or a number, and a\n * missing target silently degrades that to a union rather than failing.\n */\n/** What `--from` sent to the contract endpoint, and which keys it left behind. */\ninterface ContractCredential {\n /** The bearer token sent: `--token`, the shell's key, or none. */\n sent: \"token\" | \"ambient\" | null;\n /** `REBASE_SERVICE_KEY` is in the shell environment. */\n shellKey: boolean;\n /** `REBASE_SERVICE_KEY` is in the project's `.env`. */\n envFileKey: boolean;\n}\n\n/**\n * What to say when the contract endpoint refuses, by what was and was not sent.\n *\n * \"Set REBASE_SERVICE_KEY\" is only right when no key exists. The shell's key is\n * withheld from every host but the linked project, and `.env`'s is never read\n * here — it is the local backend's key, and the linked project is usually a\n * deployed one — so telling a reader whose key is in `.env` to set it sends them\n * to fix something that is not broken.\n */\nfunction contractRefusalHint(credential: ContractCredential): string[] {\n if (credential.sent === \"token\") {\n return [\"The token passed with --token was refused: pass a service key, or an admin's token.\"];\n }\n if (credential.sent === \"ambient\") {\n return [\"REBASE_SERVICE_KEY was sent and refused: it is not this project's service key. Pass the right one with --token.\"];\n }\n if (credential.shellKey) {\n return [\n \"REBASE_SERVICE_KEY is set, but it is only sent to this checkout's linked project, and this host is not it.\",\n \"Pass the key with --token to send it here.\"\n ];\n }\n if (credential.envFileKey) {\n return [\n \"REBASE_SERVICE_KEY in .env is not sent: --from sends the shell's REBASE_SERVICE_KEY, and only to this checkout's linked project.\",\n \"Pass the key with --token.\"\n ];\n }\n return [\"Pass --token <key>, a service key or an admin's token. The shell's REBASE_SERVICE_KEY is sent only to this checkout's linked project.\"];\n}\n\nasync function fetchRemoteCollections(\n baseUrl: string,\n token: string | undefined,\n credential: ContractCredential\n): Promise<{ collections: CollectionConfig[]; schemaVersion: string }> {\n const url = `${baseUrl.replace(/\\/+$/, \"\")}/api/meta/contract`;\n\n const headers: Record<string, string> = { accept: \"application/json\" };\n if (token) headers.authorization = `Bearer ${token}`;\n\n let response: Response;\n try {\n response = await fetch(url, { headers });\n } catch (err) {\n console.log(chalk.red(` ✗ Could not reach ${url}`));\n console.log(chalk.gray(` ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n }\n\n if (response.status === 401 || response.status === 403) {\n console.log(chalk.red(` ✗ Not authorized to read the project contract (${response.status}).`));\n console.log(chalk.gray(\" The contract describes every table and relation, so it is admin-only.\"));\n for (const line of contractRefusalHint(credential)) console.log(chalk.gray(` ${line}`));\n process.exit(1);\n }\n\n if (response.status === 404) {\n console.log(chalk.red(\" ✗ This server has no contract endpoint.\"));\n console.log(chalk.gray(\" It needs to be running Rebase 0.11 or newer.\"));\n process.exit(1);\n }\n\n if (!response.ok) {\n console.log(chalk.red(` ✗ Contract request failed with ${response.status}.`));\n process.exit(1);\n }\n\n const contract = await response.json() as {\n collections?: unknown[];\n schemaVersion?: string;\n };\n\n if (!Array.isArray(contract.collections)) {\n console.log(chalk.red(\" ✗ The contract response did not contain collections.\"));\n process.exit(1);\n }\n\n return {\n collections: deserializeCollections(contract.collections),\n schemaVersion: contract.schemaVersion ?? \"unknown\"\n };\n}\n\n/**\n * Decide whether the ambient service key may be sent to this host.\n *\n * `REBASE_SERVICE_KEY` grants full admin bypass. Attaching it to whatever URL\n * happened to be passed — or, worse, to whatever a committed `.rebase/cloud.json`\n * points at — would hand the project's most powerful credential to a host nobody\n * vetted. An explicit `--token` is a decision the caller made; the ambient\n * variable is not, so it only travels to the project this checkout is linked to.\n */\nfunction mayUseAmbientKey(target: string, cwd: string): boolean {\n const link = readLink(findProjectRoot(cwd) ?? cwd);\n if (!link?.apiUrl) return false;\n try {\n // Origin, not host: with a link recorded as https, an `http://` target\n // for the same host would otherwise pass and send the key in cleartext.\n return new URL(link.apiUrl).origin === new URL(target).origin;\n } catch {\n return false;\n }\n}\n\n/**\n * The base URL to show in the printed usage example.\n *\n * `rebase dev` binds a port derived from the project path, not 3001, and writes\n * the one it actually got to `.rebase/state.json`. Printing a hardcoded\n * `localhost:3001` sent people to a port nothing was listening on — or, with\n * several projects on one machine, to a different project's backend. Prefer the\n * port `rebase dev` says it is starting the backend on (`DEV_BACKEND_URL_ENV`:\n * it regenerates the SDK before the backend binds), then the port this project\n * last ran on; fall back to the literal only when the project has never been\n * started.\n */\nexport function resolveExampleBaseUrl(cwd: string): string {\n const fromDev = process.env[DEV_BACKEND_URL_ENV]?.trim();\n if (fromDev) return fromDev;\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n try {\n const state = JSON.parse(fs.readFileSync(path.join(projectRoot, \".rebase\", \"state.json\"), \"utf-8\"));\n if (typeof state.baseUrl === \"string\" && state.baseUrl) return state.baseUrl;\n if (typeof state.port === \"number\") return `http://localhost:${state.port}`;\n } catch {\n // Never started, or the file is unreadable — fall through.\n }\n return \"http://localhost:3001\";\n}\n\n/** Whether a slug can be written as `rebase.data.<slug>` rather than a lookup. */\nexport function isIdentifierLike(slug: string): boolean {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(slug);\n}\n\n/** Resolve `--from` into a base URL, following the link file when asked. */\nfunction resolveSchemaSource(from: string, cwd: string): string {\n if (from !== \"link\") {\n // A bare hostname or a typo would otherwise be handed to `fetch` and fail\n // with something unhelpful; a non-http scheme has no business here at all.\n let parsed: URL;\n try {\n parsed = new URL(from);\n } catch {\n console.log(chalk.red(` ✗ \"${from}\" is not a valid URL.`));\n console.log(chalk.gray(\" Pass a full URL, e.g. https://api.example.com, or \\\"link\\\".\"));\n process.exit(1);\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n console.log(chalk.red(\" ✗ The project URL must be http or https.\"));\n process.exit(1);\n }\n return from;\n }\n\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n const link = readLink(projectRoot);\n\n if (!link) {\n console.log(chalk.red(\" ✗ This checkout is not linked to a project.\"));\n console.log(chalk.gray(\" Run `rebase cloud link <url>`, or pass --from <url>.\"));\n process.exit(1);\n }\n\n const apiUrl = link.apiUrl;\n if (!apiUrl) {\n console.log(chalk.red(\" ✗ The project link has no API URL.\"));\n console.log(chalk.gray(\" Re-link with `rebase cloud link <url>` to record one.\"));\n process.exit(1);\n }\n\n return apiUrl;\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 if (args.help) {\n printSdkHelp();\n return;\n }\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\n let collections: CollectionConfig[];\n let remoteSchemaVersion: string | undefined;\n\n if (args.from) {\n const baseUrl = resolveSchemaSource(args.from, cwd);\n console.log(` ${chalk.gray(\"Project:\")} ${baseUrl}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Fetching the project contract...\"));\n\n const ambient = mayUseAmbientKey(baseUrl, cwd)\n ? process.env.REBASE_SERVICE_KEY\n : undefined;\n\n if (!args.token && !ambient && process.env.REBASE_SERVICE_KEY) {\n console.log(chalk.dim(\n \" (not sending REBASE_SERVICE_KEY — this host is not the linked project; pass --token to override)\"\n ));\n }\n\n const remote = await fetchRemoteCollections(baseUrl, args.token || ambient, {\n sent: args.token ? \"token\" : ambient ? \"ambient\" : null,\n shellKey: Boolean(process.env.REBASE_SERVICE_KEY),\n envFileKey: Boolean(readEnvFile(findProjectRoot(cwd) ?? cwd).REBASE_SERVICE_KEY)\n });\n collections = remote.collections;\n remoteSchemaVersion = remote.schemaVersion;\n } else {\n // A headless project has no collections directory by design: its API is\n // introspected from the live database at boot, and there is nothing here\n // to generate a client from. The scaffold ships `pnpm generate:sdk`\n // anyway, so the documented headless path had a script that could only\n // ever fail — and it failed with a path, which reads as a broken install\n // rather than a question with an answer.\n if (!fs.existsSync(resolvedCollectionsDir)) {\n console.log(chalk.gray(\n \" ○ This project derives its API from the database — \"\n + \"run `rebase schema introspect` first.\"\n ));\n console.log(chalk.gray(\n ` Nothing to generate from: ${resolvedCollectionsDir} does not exist.`\n ));\n console.log(\"\");\n return;\n }\n console.log(` ${chalk.gray(\"Collections:\")} ${resolvedCollectionsDir}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Loading collection definitions...\"));\n collections = await loadCollections(resolvedCollectionsDir);\n }\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 let files: GeneratedFile[];\n try {\n files = generateSDK(collections, { baseUrl: resolveExampleBaseUrl(cwd) });\n } catch (err) {\n // A schema that cannot be expressed as valid TypeScript — two slugs\n // that collide on one accessor, a slug with no usable name. The\n // generator refuses rather than emitting a file that does not compile,\n // or one that silently routes a collection's reads to another's table.\n if (err instanceof CodegenError) {\n console.log(\"\");\n console.log(chalk.red(` ✗ ${err.message}`));\n process.exit(1);\n }\n throw err;\n }\n\n // Stamp the schema this SDK was built from.\n //\n // Without it, an app in a separate repository has no way to know its client\n // is stale: the backend moves on, the frontend keeps compiling against types\n // captured weeks ago, and the mismatch only surfaces as a runtime error. With\n // it, CI can compare against `/api/meta/schema-version` and say so.\n //\n // No generation timestamp. Collections are sorted above precisely so that\n // the same schema produces the same bytes; a timestamp put that back,\n // turning every regeneration into a diff and making the obvious staleness\n // gate — `rebase generate-sdk && git diff --exit-code` — impossible to pass.\n // `SCHEMA_VERSION` already identifies what this was built from, and does it\n // in a way that can be compared against a running project.\n const schemaVersion = remoteSchemaVersion ?? computeSchemaVersion(collections);\n files.push({\n path: \"schema.meta.ts\",\n content: `// Auto-generated by \\`rebase generate-sdk\\`. Do not edit.\n//\n// The schema version this SDK was generated from. Compare it against the\n// project's current version to detect drift:\n//\n// curl -s <api-url>/api/meta/schema-version\n//\n// Pass it to the client as \\`schemaVersion\\` and every request carries it in\n// the \\`x-rebase-schema\\` header, so the server can name the drift instead of\n// answering a renamed field with a bare 400.\nexport const SCHEMA_VERSION = ${JSON.stringify(schemaVersion)};\n`\n });\n\n console.log(chalk.green(` ✓ Generated ${files.length} file(s)`));\n console.log(chalk.gray(` schema ${schemaVersion}`));\n\n // 3. Write to disk\n console.log(chalk.cyan(` → Writing to ${resolvedOutput}...`));\n writeFiles(resolvedOutput, files);\n\n // 4. The server-side registration: on request, and kept current once a\n // project has it, so `rebase dev` regenerating the SDK never leaves the\n // server typed against an older schema than the client.\n const registerDir = registrationDir(resolvedCollectionsDir);\n const projectRoot = args.projectRoot ?? findProjectRoot(cwd) ?? undefined;\n if (args.register || hasRegistration(registerDir) || manifestRegisters(projectRoot)) {\n if (!fs.existsSync(path.dirname(registerDir))) {\n console.log(chalk.red(` ✗ No ${path.dirname(registerDir)} to register the Database in.`));\n console.log(chalk.gray(\" --register writes beside the collections directory; pass --collections.\"));\n process.exit(1);\n return;\n }\n const databaseTypes = files.find((file) => file.path === \"database.types.ts\")?.content;\n if (databaseTypes !== undefined) {\n try {\n writeRegistration(registerDir, databaseTypes);\n } catch (error) {\n console.log(chalk.red(` ✗ ${error instanceof Error ? error.message : String(error)}`));\n process.exit(1);\n return;\n }\n console.log(chalk.green(` ✓ Registered the Database for server-side code in ${registerDir}`));\n if (args.register) {\n const remembered = rememberRegistration(projectRoot);\n if (\"written\" in remembered) {\n console.log(chalk.gray(` Remembered in ${path.relative(cwd, remembered.written) || \"rebase.json\"} (registerDatabase).`));\n } else {\n console.log(chalk.yellow(` ${remembered.skipped}`));\n }\n }\n }\n }\n\n console.log(\"\");\n console.log(chalk.green.bold(\" ✓ SDK generated successfully!\"));\n console.log(\"\");\n const typesImport = `./${path.relative(cwd, path.join(resolvedOutput, \"database.types\"))}`;\n const metaImport = `./${path.relative(cwd, path.join(resolvedOutput, \"schema.meta\"))}`;\n const exampleSlug = collections[0]?.slug || \"my_collection\";\n\n console.log(chalk.gray(\" Usage:\"));\n console.log(chalk.gray(\" import { createRebaseClient } from '@rebasepro/client';\"));\n console.log(chalk.gray(` import { collectionsDictionary, type Database } from '${typesImport}';`));\n console.log(chalk.gray(` import { SCHEMA_VERSION } from '${metaImport}';`));\n console.log(\"\");\n console.log(chalk.gray(\" const rebase = createRebaseClient<Database>({\"));\n console.log(chalk.gray(` baseUrl: '${resolveExampleBaseUrl(cwd)}',`));\n // Sent as `x-rebase-schema` on every request. Costs one line here and is\n // the difference between a server that can say \"this client is three\n // deploys behind\" and one that can only reject a field it does not know.\n console.log(chalk.gray(\" schemaVersion: SCHEMA_VERSION,\"));\n // Without the dictionary a hyphenated slug is not resolvable from the\n // property name alone, and the request 404s at runtime.\n console.log(chalk.gray(\" collections: collectionsDictionary,\"));\n console.log(chalk.gray(\" // token: 'your-jwt-token',\"));\n console.log(chalk.gray(\" });\"));\n console.log(\"\");\n // `rebase.data.<accessor>` is the typed surface, so it is what gets printed.\n // `rebase.data.collection(slug)` exists too, but it is generic over\n // `Record<string, unknown>` and has no link to `Database` — it was the\n // headline example here for a while, which advertised the one call shape\n // that throws away the types this command just generated.\n const exampleAccessor = toCollectionAccessor(exampleSlug);\n const exampleAccess = isIdentifierLike(exampleAccessor)\n ? `rebase.data.${exampleAccessor}`\n : `rebase.data[${JSON.stringify(exampleAccessor)}]`;\n console.log(chalk.gray(` const { data } = await ${exampleAccess}.find();`));\n console.log(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAa,gBAAgB;;AAG7B,IAAM,kBAAkB;AAExB,IAAM,kBAAkB,GAAG,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4B3C,SAAgB,gBAAgB,gBAAgC;CAC5D,OAAO,KAAK,KAAK,KAAK,QAAQ,KAAK,QAAQ,cAAc,CAAC,GAAG,WAAW;AAC5E;;AAGA,SAAS,gBAAgB,KAAsB;CAC3C,IAAI;EACA,OAAO,GAAG,aAAa,KAAK,KAAK,KAAK,aAAa,GAAG,OAAO,CAAC,CAAC,WAAW,eAAe;CAC7F,QAAQ;EACJ,OAAO;CACX;AACJ;;AAGA,SAAS,eAAe,UAAkB,SAAuB;CAC7D,IAAI;EACA,IAAI,GAAG,aAAa,UAAU,OAAO,MAAM,SAAS;CACxD,QAAQ,CAER;CACA,GAAG,cAAc,UAAU,SAAS,OAAO;AAC/C;;;;;;AAOA,SAAS,kBAAkB,KAAa,eAA6B;CACjE,MAAM,eAAe,K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