@rebasepro/cli 0.25.0-canary.ge06257e → 0.25.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.
Files changed (142) hide show
  1. package/bin/rebase.js +9 -5
  2. package/dist/{agent-setup-C83DXnlx.js → agent-setup-BYb2Tbdz.js} +2 -2
  3. package/dist/{agent-setup-C83DXnlx.js.map → agent-setup-BYb2Tbdz.js.map} +1 -1
  4. package/dist/{api-keys-Bc4FJKYp.js → api-keys-CSMbsmAn.js} +28 -22
  5. package/dist/api-keys-CSMbsmAn.js.map +1 -0
  6. package/dist/{apps-wG-ZTryA.js → apps-iBXNZhVN.js} +6 -7
  7. package/dist/{apps-wG-ZTryA.js.map → apps-iBXNZhVN.js.map} +1 -1
  8. package/dist/{atlas-dev-database-DeK3Sa4h.js → atlas-dev-database-BusbHP6n.js} +4 -4
  9. package/dist/{atlas-dev-database-DeK3Sa4h.js.map → atlas-dev-database-BusbHP6n.js.map} +1 -1
  10. package/dist/{auth-BL7bNQVu.js → auth-DRsTWPky.js} +77 -11
  11. package/dist/auth-DRsTWPky.js.map +1 -0
  12. package/dist/{branch-pointer-DTQNLFtb.js → branch-pointer-Bn_FjNld.js} +1 -1
  13. package/dist/{build-h_7Re-67.js → build-et7Rccxi.js} +6 -7
  14. package/dist/{build-h_7Re-67.js.map → build-et7Rccxi.js.map} +1 -1
  15. package/dist/{bundle-CqURVN-K.js → bundle-DlqkDYSe.js} +6 -21
  16. package/dist/bundle-DlqkDYSe.js.map +1 -0
  17. package/dist/{cloud-DVV_5GPG.js → cloud-B-ZIjHrA.js} +10 -11
  18. package/dist/{cloud-DVV_5GPG.js.map → cloud-B-ZIjHrA.js.map} +1 -1
  19. package/dist/commands/api-keys.d.ts +4 -1
  20. package/dist/commands/auth.d.ts +3 -2
  21. package/dist/commands/dev.d.ts +12 -0
  22. package/dist/commands/generate_sdk.d.ts +4 -2
  23. package/dist/commands/init.d.ts +20 -0
  24. package/dist/commands/start.d.ts +10 -0
  25. package/dist/commands/upgrade.d.ts +12 -0
  26. package/dist/connection-banner-DbLJzWf4.js +128 -0
  27. package/dist/connection-banner-DbLJzWf4.js.map +1 -0
  28. package/dist/{consent-ClRHmcxf.js → consent-BaB-eQKG.js} +2 -2
  29. package/dist/{consent-ClRHmcxf.js.map → consent-BaB-eQKG.js.map} +1 -1
  30. package/dist/{console-Dw3HLdUs.js → console-BlD9kjFW.js} +4 -4
  31. package/dist/{console-Dw3HLdUs.js.map → console-BlD9kjFW.js.map} +1 -1
  32. package/dist/{context-BM-oOMNX.js → context-DHiiiJ5C.js} +3 -4
  33. package/dist/context-DHiiiJ5C.js.map +1 -0
  34. package/dist/{daemon-CknkDjd6.js → daemon-DDMRbz4T.js} +160 -5
  35. package/dist/daemon-DDMRbz4T.js.map +1 -0
  36. package/dist/{daemon-entry-C6pxdily.js → daemon-entry-zOC1revO.js} +204 -5
  37. package/dist/daemon-entry-zOC1revO.js.map +1 -0
  38. package/dist/{db-Dkn9XhT-.js → db-9P6MnmdC.js} +237 -86
  39. package/dist/db-9P6MnmdC.js.map +1 -0
  40. package/dist/{derive-Dl0z2OWi.js → derive-MTdClnkc.js} +29 -14
  41. package/dist/{derive-Dl0z2OWi.js.map → derive-MTdClnkc.js.map} +1 -1
  42. package/dist/{dev-DAcZR4Pp.js → dev-BDN_OKXA.js} +183 -23
  43. package/dist/dev-BDN_OKXA.js.map +1 -0
  44. package/dist/dev-db/connection-banner.d.ts +47 -0
  45. package/dist/dev-db/daemon.d.ts +41 -0
  46. package/dist/dev-db/notification-proxy.d.ts +82 -1
  47. package/dist/dev-db/pull.d.ts +33 -5
  48. package/dist/dev-db/state.d.ts +9 -0
  49. package/dist/{dev-preflight-CorMg7Ub.js → dev-preflight-FT9GbJVj.js} +73 -4
  50. package/dist/dev-preflight-FT9GbJVj.js.map +1 -0
  51. package/dist/{dev-server-B1UYifZJ.js → dev-server-CIZwAfZa.js} +14 -3
  52. package/dist/dev-server-CIZwAfZa.js.map +1 -0
  53. package/dist/{doctor-Ds_lzc9p.js → doctor-D8YXz7df.js} +6 -6
  54. package/dist/doctor-D8YXz7df.js.map +1 -0
  55. package/dist/{eject-CJHkfnat.js → eject-izG2KjMo.js} +3 -4
  56. package/dist/{eject-CJHkfnat.js.map → eject-izG2KjMo.js.map} +1 -1
  57. package/dist/{fold-static-BC9CYicw.js → fold-static-CybSay_W.js} +3 -3
  58. package/dist/{fold-static-BC9CYicw.js.map → fold-static-CybSay_W.js.map} +1 -1
  59. package/dist/{generate_sdk-kfkZmG-d.js → generate_sdk-B4R65oUV.js} +22 -12
  60. package/dist/generate_sdk-B4R65oUV.js.map +1 -0
  61. package/dist/index.es.js +36 -37
  62. package/dist/index.es.js.map +1 -1
  63. package/dist/{init-CjoJoThg.js → init-DYaeppEN.js} +52 -63
  64. package/dist/init-DYaeppEN.js.map +1 -0
  65. package/dist/invoked-command-CG_rIa_o.js +55 -0
  66. package/dist/invoked-command-CG_rIa_o.js.map +1 -0
  67. package/dist/last-dev-database-B_75fxZC.js +2 -0
  68. package/dist/{manifest-DRp0UVTj.js → manifest-nvPdLlJY.js} +2 -2
  69. package/dist/{manifest-DRp0UVTj.js.map → manifest-nvPdLlJY.js.map} +1 -1
  70. package/dist/{normalize-imports-BHxL2d05.js → normalize-imports-BYw8ad87.js} +3 -3
  71. package/dist/{normalize-imports-BHxL2d05.js.map → normalize-imports-BYw8ad87.js.map} +1 -1
  72. package/dist/precompress.d.ts +0 -7
  73. package/dist/{prepare-C1iaiTC4.js → prepare-1rVNd2PF.js} +7 -6
  74. package/dist/prepare-1rVNd2PF.js.map +1 -0
  75. package/dist/project-g4K6kV1t.js +701 -0
  76. package/dist/project-g4K6kV1t.js.map +1 -0
  77. package/dist/{pull-COpNJFzY.js → pull-DDMpsZ5r.js} +143 -63
  78. package/dist/pull-DDMpsZ5r.js.map +1 -0
  79. package/dist/refusal-ReeeGP8a.js +26 -0
  80. package/dist/refusal-ReeeGP8a.js.map +1 -0
  81. package/dist/resolve-BQUAC3Wi.js +2 -0
  82. package/dist/resources/derive.d.ts +9 -0
  83. package/dist/{resources-CLm6g0br.js → resources-CovP8AZ-.js} +4 -5
  84. package/dist/{resources-CLm6g0br.js.map → resources-CovP8AZ-.js.map} +1 -1
  85. package/dist/{schema-BKdh6UoE.js → schema-nuxvvc50.js} +5 -6
  86. package/dist/{schema-BKdh6UoE.js.map → schema-nuxvvc50.js.map} +1 -1
  87. package/dist/{skills-DEhYiPeO.js → skills-DeUIsZcT.js} +3 -4
  88. package/dist/{skills-DEhYiPeO.js.map → skills-DeUIsZcT.js.map} +1 -1
  89. package/dist/{start-BsPJedPQ.js → start-RzZqDroW.js} +20 -7
  90. package/dist/start-RzZqDroW.js.map +1 -0
  91. package/dist/{state-CCB-FAQ9.js → state-CYdBvnwA.js} +3 -2
  92. package/dist/state-CYdBvnwA.js.map +1 -0
  93. package/dist/{status-D_B3tlDy.js → status-D9Zm88NZ.js} +11 -12
  94. package/dist/{status-D_B3tlDy.js.map → status-D9Zm88NZ.js.map} +1 -1
  95. package/dist/{storage-CtB8polS.js → storage-BB3umRfw.js} +3 -4
  96. package/dist/{storage-CtB8polS.js.map → storage-BB3umRfw.js.map} +1 -1
  97. package/dist/{telemetry-EMFRVRQi.js → telemetry-HfU5uAh1.js} +2 -2
  98. package/dist/{telemetry-EMFRVRQi.js.map → telemetry-HfU5uAh1.js.map} +1 -1
  99. package/dist/{telemetry-BYmPU-Ji.js → telemetry-TseNLk6X.js} +4 -4
  100. package/dist/{telemetry-BYmPU-Ji.js.map → telemetry-TseNLk6X.js.map} +1 -1
  101. package/dist/{upgrade-DbuKX9lv.js → upgrade-apiPKKE_.js} +29 -6
  102. package/dist/{upgrade-DbuKX9lv.js.map → upgrade-apiPKKE_.js.map} +1 -1
  103. package/dist/utils/args.d.ts +45 -3
  104. package/dist/utils/boot-retry.d.ts +41 -0
  105. package/dist/utils/dev-preflight.d.ts +34 -1
  106. package/dist/utils/dev-server.d.ts +11 -0
  107. package/dist/utils/project.d.ts +5 -1
  108. package/dist/utils/redact.d.ts +10 -0
  109. package/dist/utils/refusal.d.ts +18 -0
  110. package/dist/utils/unknown-command.d.ts +4 -0
  111. package/package.json +7 -7
  112. package/templates/overlays/baas/README.md +2 -1
  113. package/templates/resource-graphs/blank.json +25 -0
  114. package/templates/resource-graphs/blog.json +28 -0
  115. package/templates/resource-graphs/ecommerce.json +28 -0
  116. package/templates/resource-graphs/headless.json +22 -0
  117. package/templates/template/.env.example +11 -4
  118. package/templates/template/frontend/src/App.tsx +10 -9
  119. package/templates/template/frontend/vite.config.ts +7 -73
  120. package/dist/api-keys-Bc4FJKYp.js.map +0 -1
  121. package/dist/args-CcBphFdj.js +0 -237
  122. package/dist/args-CcBphFdj.js.map +0 -1
  123. package/dist/auth-BL7bNQVu.js.map +0 -1
  124. package/dist/bundle-CqURVN-K.js.map +0 -1
  125. package/dist/context-BM-oOMNX.js.map +0 -1
  126. package/dist/daemon-CknkDjd6.js.map +0 -1
  127. package/dist/daemon-entry-C6pxdily.js.map +0 -1
  128. package/dist/db-Dkn9XhT-.js.map +0 -1
  129. package/dist/dev-DAcZR4Pp.js.map +0 -1
  130. package/dist/dev-preflight-CorMg7Ub.js.map +0 -1
  131. package/dist/dev-server-B1UYifZJ.js.map +0 -1
  132. package/dist/doctor-Ds_lzc9p.js.map +0 -1
  133. package/dist/generate_sdk-kfkZmG-d.js.map +0 -1
  134. package/dist/init-CjoJoThg.js.map +0 -1
  135. package/dist/last-dev-database-BEBPfAMY.js +0 -2
  136. package/dist/prepare-C1iaiTC4.js.map +0 -1
  137. package/dist/project-Wp2zoyeN.js +0 -349
  138. package/dist/project-Wp2zoyeN.js.map +0 -1
  139. package/dist/pull-COpNJFzY.js.map +0 -1
  140. package/dist/resolve-b_p9bmdH.js +0 -2
  141. package/dist/start-BsPJedPQ.js.map +0 -1
  142. package/dist/state-CCB-FAQ9.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"daemon-CknkDjd6.js","names":[],"sources":["../src/dev-db/daemon.ts"],"sourcesContent":["/**\n * Starting, finding and stopping the managed database, from the caller's side.\n *\n * Every command that needs Postgres calls {@link ensureManagedDatabase} and\n * gets a connection string back. Whether that started a process or found one\n * already running is not the caller's business, which is the point: `rebase\n * db push`, `rebase dev` and `rebase studio` in three terminals must all reach\n * the same database without coordinating, because two processes opening one\n * PGlite data directory would corrupt it.\n *\n * The hard part is not starting the daemon; it is deciding whether the one the\n * state file describes is still there. A pid can be recycled after a reboot and\n * a port can be taken by a stranger, so believing either on its own would let\n * Rebase send a migration somewhere unintended. {@link isDaemonAlive} asks the\n * daemon to identify itself instead.\n */\n\nimport { randomBytes } from \"crypto\";\nimport { type ChildProcess, spawn } from \"child_process\";\nimport fs from \"fs\";\nimport net from \"net\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nimport { runningBackendUrl } from \"../utils/dev-server\";\nimport {\n acquireStartLock,\n chooseManagedPort,\n clearState,\n type DaemonState,\n dataDir,\n devDbDir,\n pidRunning,\n readState,\n releaseStartLock,\n stateFile\n} from \"./state\";\n\n/** How long to wait for a first boot. PGlite runs initdb on an empty data dir. */\nconst START_TIMEOUT_MS = 60_000;\n/** Poll interval while waiting for the daemon to publish its state file. */\nconst POLL_INTERVAL_MS = 150;\n/** How long the identity handshake may take before we call it dead. */\nconst IDENTITY_TIMEOUT_MS = 1_500;\n\nexport interface ManagedDatabase {\n /** Connection string for this project's managed database. */\n url: string;\n /** Where the data lives, for diagnostics and `--reset`. */\n dataDir: string;\n port: number;\n pid: number;\n /** True when this call started the daemon rather than finding it. */\n started: boolean;\n /**\n * Connection strings for the additional databases the caller asked for,\n * by declared key — `database(\"analytics\")` → `analytics`. Each is its\n * own PGlite instance behind the same daemon.\n */\n additional: Record<string, string>;\n}\n\n/**\n * PGlite's built-in superuser and database.\n *\n * Fixed by PGlite rather than chosen here, and asserted by the socket spike:\n * `session_user` comes back as `postgres`.\n */\nconst MANAGED_USER = \"postgres\";\nconst MANAGED_DATABASE = \"postgres\";\n\n/**\n * The DSN for the managed development database.\n *\n * **`sslmode=disable` is not decoration.** PGlite's socket server speaks no TLS,\n * and libpq-family clients try SSL first — so Atlas, which `rebase db push`\n * shells out to, failed the whole push with\n * `pq: SSL is not enabled on the server`. Its remedy box then told the reader to\n * append `sslmode=disable` to `DATABASE_URL`, which on this path is not set at\n * all: `rebase init` leaves it commented out precisely so the managed database\n * is used. The advice was correct and unfollowable.\n *\n * Putting it in the URL fixes every consumer at once — Atlas, `pg`, and anything\n * a driver shells out to later — rather than teaching each one about PGlite.\n */\n\n/**\n * The end of `pglite.log`, for an error message that has to carry its own reason.\n *\n * The daemon writes its output to a file because it is detached — it has to\n * outlive the command that started it. That is right, and it means every\n * startup failure used to be reported as a path: \"see pglite.log for the\n * reason\". On a laptop that is a fair trade. In CI it is not a trade at all,\n * because the runner discards the workspace: the log named in the message no\n * longer exists by the time anybody reads the message, so a failed run says\n * only that something failed.\n *\n * So the tail comes with the error. Bounded, because a log that has been\n * appended to across many runs is not something to paste in full.\n */\nexport function pgliteLogTail(projectRoot: string, lines = 12): string {\n try {\n const contents = fs.readFileSync(path.join(devDbDir(projectRoot), \"pglite.log\"), \"utf8\").trimEnd();\n if (!contents) return \" (pglite.log is empty — the daemon wrote nothing before exiting)\";\n return contents.split(\"\\n\").slice(-lines).map(line => ` ${line}`).join(\"\\n\");\n } catch {\n return \" (pglite.log could not be read)\";\n }\n}\n\nexport function managedUrl(port: number): string {\n return `postgresql://${MANAGED_USER}@127.0.0.1:${port}/${MANAGED_DATABASE}?sslmode=disable`;\n}\n\n/**\n * Ask the process behind a state record to prove it is the one we wrote down.\n *\n * A pid check alone answers \"is *a* process running\", and a port check alone\n * answers \"is *something* listening\" — after a reboot both say yes about\n * strangers. The daemon answers with the token from its own state file, so a\n * match is the only evidence accepted.\n */\nexport function isDaemonAlive(state: DaemonState): Promise<boolean> {\n if (!pidRunning(state.pid)) return Promise.resolve(false);\n\n return new Promise((resolve) => {\n const socket = new net.Socket();\n let answer = \"\";\n const settle = (alive: boolean) => {\n socket.removeAllListeners();\n socket.destroy();\n resolve(alive);\n };\n socket.setTimeout(IDENTITY_TIMEOUT_MS);\n socket.once(\"timeout\", () => settle(false));\n socket.once(\"error\", () => settle(false));\n socket.on(\"data\", (chunk) => {\n answer += chunk.toString(\"utf8\");\n if (answer.includes(\"\\n\")) settle(answer.trim() === `rebase-dev-db ${state.token}`);\n });\n socket.once(\"close\", () => settle(answer.trim() === `rebase-dev-db ${state.token}`));\n socket.connect(state.identityPort, \"127.0.0.1\");\n });\n}\n\n/** The running daemon for this project, or `null`. Never starts anything. */\nexport async function findRunningDaemon(projectRoot: string): Promise<DaemonState | null> {\n const state = readState(projectRoot);\n if (!state) return null;\n if (await isDaemonAlive(state)) return state;\n\n // The record describes something that is not there. Clearing it is the\n // whole recovery: the next ensure call starts a fresh daemon, and leaving\n // it would make every subsequent check pay the identity timeout.\n clearState(projectRoot);\n\n return null;\n}\n\n/**\n * Resolve the CLI entry point, so the daemon can be spawned as ourselves.\n *\n * A hidden subcommand rather than a second build entry: under `tsx` this file\n * is `src/dev-db/daemon.ts` and in a published CLI it is bundled into\n * `dist/index.js`, and in both cases the executable to re-invoke is the one\n * already running. `rebase dev` re-runs itself the same way to regenerate the\n * SDK types.\n */\nexport function resolveCliEntry(): string {\n // `process.argv[1]` is `bin/rebase.js` for a real invocation, which is\n // exactly what should be re-run. Under a test runner it is the runner, so\n // fall back to this module's own directory.\n const argvEntry = process.argv[1];\n if (argvEntry && fs.existsSync(argvEntry)) return argvEntry;\n\n return fileURLToPath(new URL(\"../index.js\", import.meta.url));\n}\n\n/**\n * How to re-invoke ourselves, which differs between a published CLI and this\n * repository.\n *\n * A published `rebase` is `node bin/rebase.js`, and re-running that is trivial.\n * Inside the monorepo the entry is TypeScript, which plain `node` cannot load —\n * so the daemon has to be started through the same loader that is running now.\n * Getting this wrong fails as a spawn that exits instantly with a syntax error,\n * which is why the caller reads `pglite.log` on failure.\n */\nexport function resolveSpawn(entry: string): { execPath: string; prefixArgs: string[] } {\n if (!/\\.[cm]?ts$/.test(entry)) return { execPath: process.execPath, prefixArgs: [] };\n\n // Node can load TypeScript when tsx is registered as an import hook. tsx is\n // already a dependency of this package, because `rebase dev` runs the\n // backend through it.\n return { execPath: process.execPath, prefixArgs: [\"--import\", \"tsx\"] };\n}\n\nexport interface EnsureOptions {\n /** Silence the \"starting…\" progress line. */\n quiet?: boolean;\n /** Milliseconds of inactivity before the daemon exits. 0 disables. */\n idleTimeoutMs?: number;\n /** Where progress goes. Injected for tests. */\n onProgress?: (message: string) => void;\n /** Override how the daemon process is launched. For tests. */\n spawn?: { execPath: string; prefixArgs: string[] };\n /**\n * Override the CLI entry to re-invoke. For tests.\n *\n * Necessary because under a test runner `process.argv[1]` is the runner\n * itself, which exists and is therefore accepted by {@link resolveCliEntry}\n * — spawning vitest with `__dev-db-daemon` rather than the CLI.\n */\n entry?: string;\n /**\n * Keys of the additional databases the project declares, beyond the\n * default. Each is served by the daemon on request, so a project that\n * adds `database(\"analytics\")` while the daemon is running gets it\n * without a restart.\n */\n additionalKeys?: readonly string[];\n}\n\n/**\n * Ask the running daemon for one additional database, and get its port.\n *\n * The identity socket doubles as the command channel: the daemon answers\n * with its token first, which is how the caller knows it is talking to the\n * daemon the state file describes and not to a stranger on a recycled port.\n */\nfunction ensureAdditionalDatabase(state: DaemonState, key: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const socket = new net.Socket();\n let answer = \"\";\n let identified = false;\n const fail = (message: string) => {\n socket.removeAllListeners();\n socket.destroy();\n reject(new Error(message));\n };\n socket.setTimeout(START_TIMEOUT_MS);\n socket.once(\"timeout\", () => fail(`The development database did not answer for \"${key}\" within ${Math.round(START_TIMEOUT_MS / 1000)}s.`));\n socket.once(\"error\", (err) => fail(`Could not reach the development database for \"${key}\": ${err.message}`));\n socket.on(\"data\", (chunk) => {\n answer += chunk.toString(\"utf8\");\n let newline = answer.indexOf(\"\\n\");\n while (newline !== -1) {\n const line = answer.slice(0, newline).trim();\n answer = answer.slice(newline + 1);\n if (!identified) {\n if (line !== `rebase-dev-db ${state.token}`) return fail(\"The process on the development database's port is not the daemon.\");\n identified = true;\n socket.write(`ensure ${key}\\n`);\n } else if (line.startsWith(\"ok \")) {\n const port = Number(line.slice(3));\n socket.removeAllListeners();\n socket.destroy();\n if (!Number.isInteger(port) || port <= 0) return reject(new Error(`The development database answered with an invalid port for \"${key}\": ${line}`));\n return resolve(port);\n } else {\n return fail(`The development database could not serve \"${key}\": ${line.replace(/^error\\s*/, \"\")}`);\n }\n newline = answer.indexOf(\"\\n\");\n }\n });\n socket.connect(state.identityPort, \"127.0.0.1\");\n });\n}\n\n/** Every additional database the caller asked for, as connection strings. */\nasync function adoptWithAdditional(state: DaemonState, started: boolean, keys: readonly string[]): Promise<ManagedDatabase> {\n const additional: Record<string, string> = {};\n for (const key of keys) {\n const known = state.databases?.[key];\n const port = known ? known.port : await ensureAdditionalDatabase(state, key);\n additional[key] = managedUrl(port);\n }\n return { ...adopt(state, started), additional };\n}\n\n/**\n * The project's managed database, started if it is not already running.\n *\n * Safe to call concurrently from several commands: the loser of the race finds\n * the winner's state file during its poll and adopts it rather than starting a\n * second daemon.\n */\nexport async function ensureManagedDatabase(\n projectRoot: string,\n options: EnsureOptions = {}\n): Promise<ManagedDatabase> {\n const keys = options.additionalKeys ?? [];\n const existing = await findRunningDaemon(projectRoot);\n if (existing) return adoptWithAdditional(existing, false, keys);\n\n fs.mkdirSync(devDbDir(projectRoot), { recursive: true });\n ensureGitignore(projectRoot);\n\n // Exactly one process may spawn a daemon. Without this, `rebase dev` and\n // `rebase db push` started in the same second both see no state file, both\n // spawn, and two processes open one PGlite data directory — the corruption\n // the single-daemon design exists to prevent.\n if (!acquireStartLock(projectRoot, START_TIMEOUT_MS)) {\n const adopted = await waitForDaemon(projectRoot, START_TIMEOUT_MS);\n if (adopted) return adoptWithAdditional(adopted, false, keys);\n\n // The holder gave up or died without publishing. Falling through to\n // start one ourselves is better than failing: the lock is stale by now,\n // so the next acquire will break it.\n if (!acquireStartLock(projectRoot, 0)) {\n throw new Error(\n \"Another process is starting the development database and did not finish.\\n\" +\n ` Remove ${path.join(devDbDir(projectRoot), \"starting.lock\")} if nothing is running.`\n );\n }\n }\n\n // Where the last daemon listened, so a backend still holding that URL\n // reconnects to this one. See `chooseManagedPort`.\n const port = await chooseManagedPort(projectRoot);\n const token = randomBytes(16).toString(\"hex\");\n const entry = options.entry ?? resolveCliEntry();\n\n const spawnPlan = options.spawn ?? resolveSpawn(entry);\n const args = [\n ...spawnPlan.prefixArgs,\n entry,\n \"__dev-db-daemon\",\n \"--project\", projectRoot,\n \"--port\", String(port),\n \"--token\", token\n ];\n if (options.idleTimeoutMs !== undefined) {\n args.push(\"--idle-timeout\", String(options.idleTimeoutMs));\n }\n\n const log = fs.openSync(path.join(devDbDir(projectRoot), \"pglite.log\"), \"a\");\n const child: ChildProcess = spawn(spawnPlan.execPath, args, {\n // Detached with no stdin and its output on a file: the daemon must\n // survive the command that started it, and must not hold the terminal\n // open when that command exits.\n detached: true,\n stdio: [\"ignore\", log, log]\n });\n child.unref();\n\n try {\n const deadline = Date.now() + START_TIMEOUT_MS;\n let announced = false;\n while (Date.now() < deadline) {\n const state = readState(projectRoot);\n if (state && (await isDaemonAlive(state))) return adoptWithAdditional(state, true, keys);\n\n if (!announced && !options.quiet) {\n announced = true;\n options.onProgress?.(\"Starting the development database…\");\n }\n\n // A daemon that died on startup will never publish a state file, and\n // waiting the full minute for that is a bad way to learn it. The log\n // is the only place the reason exists.\n if (child.exitCode !== null && child.exitCode !== 0) {\n throw new Error(\n `The development database failed to start (exit ${child.exitCode}).\\n` +\n ` ${path.join(devDbDir(projectRoot), \"pglite.log\")} ends:\\n` +\n pgliteLogTail(projectRoot)\n );\n }\n\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n\n throw new Error(\n `The development database did not start within ${Math.round(START_TIMEOUT_MS / 1000)}s.\\n` +\n ` ${path.join(devDbDir(projectRoot), \"pglite.log\")} ends:\\n` +\n pgliteLogTail(projectRoot) + \"\\n\" +\n \" To use your own Postgres instead, set DATABASE_URL or pass --database-url.\"\n );\n } finally {\n // Released whether we succeeded, timed out or threw. A lock left behind\n // by a crash is broken by age, but only after a full timeout — which a\n // developer should never have to wait out.\n releaseStartLock(projectRoot);\n }\n}\n\n/** Shape a live state record as the caller's result. */\nfunction adopt(state: DaemonState, started: boolean): ManagedDatabase {\n return {\n url: managedUrl(state.port),\n dataDir: state.dataDir,\n port: state.port,\n pid: state.pid,\n started,\n additional: {}\n };\n}\n\n/** Poll until another process publishes a live daemon, or give up. */\nasync function waitForDaemon(projectRoot: string, timeoutMs: number): Promise<DaemonState | null> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const state = readState(projectRoot);\n if (state && (await isDaemonAlive(state))) return state;\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n\n return null;\n}\n\n/** Stop the daemon. Returns false when there was nothing running. */\nexport async function stopManagedDatabase(projectRoot: string): Promise<boolean> {\n const state = await findRunningDaemon(projectRoot);\n if (!state) return false;\n\n try {\n process.kill(state.pid, \"SIGTERM\");\n } catch {\n clearState(projectRoot);\n\n return false;\n }\n\n // Wait for it to clear its own state file, which is how it says it closed\n // the data directory cleanly. A hard kill here would risk the WAL.\n const deadline = Date.now() + 10_000;\n while (Date.now() < deadline) {\n if (!fs.existsSync(stateFile(projectRoot))) return true;\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n clearState(projectRoot);\n\n return true;\n}\n\n/**\n * What `rebase db stop` says once the daemon is down: the headline, then any\n * detail.\n *\n * \"`rebase dev` will start it again\" was not true of a `rebase dev` that is\n * running: nothing in it watches the database, so its backend answered 503\n * until something else started one. The next command that needs it does, on\n * the port it had (`chooseManagedPort`), and the backend's pool reconnects to\n * that address by itself — so while a backend runs, that is what this says.\n */\nexport function stoppedManagedDatabaseLines(projectRoot: string): string[] {\n const backend = runningBackendUrl(projectRoot);\n if (!backend) {\n return [\"✓ Development database stopped. Data is kept — the next `rebase dev`, or any command that needs it, starts it again.\"];\n }\n return [\n \"✓ Development database stopped. Data is kept.\",\n ` The backend at ${backend} cannot reach it until it is back. The next command that needs it — \\`rebase db url\\`, for one — ` +\n \"starts it on the same port, and the backend reconnects.\"\n ];\n}\n\n/**\n * Stop the daemon and delete the data directory.\n *\n * Destructive and deliberately not clever: it removes the whole directory\n * rather than dropping schemas, because \"give me an empty database\" is the only\n * thing anyone means by it.\n */\nexport async function resetManagedDatabase(projectRoot: string): Promise<void> {\n await stopManagedDatabase(projectRoot);\n fs.rmSync(dataDir(projectRoot), { recursive: true, force: true });\n // Every additional database too: `pgdata__<key>` beside `pgdata`. \"Give\n // me an empty database\" means all of them — a reset that emptied the\n // default and kept the analytics rows would be a surprise on first read.\n const dir = devDbDir(projectRoot);\n if (fs.existsSync(dir)) {\n for (const entry of fs.readdirSync(dir)) {\n if (entry.startsWith(\"pgdata__\")) fs.rmSync(path.join(dir, entry), { recursive: true, force: true });\n }\n }\n clearState(projectRoot);\n}\n\n/**\n * Keep the generated directory out of git.\n *\n * `.rebase/` holds a Postgres data directory and a log. A project that commits\n * it will push hundreds of megabytes and a database that only makes sense on\n * one machine, so the ignore file is written next to the data rather than\n * relying on the project's root `.gitignore` having been updated.\n */\nfunction ensureGitignore(projectRoot: string): void {\n const target = path.join(devDbDir(projectRoot), \".gitignore\");\n if (fs.existsSync(target)) return;\n fs.writeFileSync(\n target,\n \"# Generated by `rebase dev` — a local Postgres data directory and its log.\\n\" +\n \"# Machine-specific and large; never commit it.\\n*\\n\",\n \"utf8\"\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAM,mBAAmB;;AAEzB,IAAM,mBAAmB;;AAEzB,IAAM,sBAAsB;;;;;;;AAyB5B,IAAM,eAAe;AACrB,IAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;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AAM,OAAO;CAAK,CAAC;CAIhE,MAAM,MAAM,SAAS,WAAW;CAChC,IAAI,GAAG,WAAW,GAAG;OACZ,MAAM,SAAS,GAAG,YAAY,GAAG,GAClC,IAAI,MAAM,WAAW,UAAU,GAAG,GAAG,OAAO,KAAK,KAAK,KAAK,KAAK,GAAG;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CAAA;CAG3G,WAAW,WAAW;AAC1B;;;;;;;;;AAUA,SAAS,gBAAgB,aAA2B;CAChD,MAAM,SAAS,KAAK,KAAK,SAAS,WAAW,GAAG,YAAY;CAC5D,IAAI,GAAG,WAAW,MAAM,GAAG;CAC3B,GAAG,cACC,QACA,mIAEA,MACJ;AACJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"daemon-entry-C6pxdily.js","names":[],"sources":["../src/dev-db/notification-proxy.ts","../src/dev-db/daemon-entry.ts"],"sourcesContent":["/**\n * A transparent Postgres proxy that puts LISTEN/NOTIFY back.\n *\n * Without this, realtime does not work against the managed database — and it\n * fails silently, which is worse than failing. The reason is specific and\n * measurable:\n *\n * PGlite is a *single* backend session, and `PGLiteSocketServer` multiplexes\n * every client connection onto it. `LISTEN` is therefore session-wide: whichever\n * client issues it arms the whole database. But a `NotificationResponse` is an\n * asynchronous message with no request to answer, so the multiplexer hands it to\n * whichever socket happens to be reading the protocol stream at that moment —\n * which is the client that *caused* the notification, not the one that asked for\n * it.\n *\n * Measured against pglite-socket 0.2.9:\n *\n * LISTEN and NOTIFY on one connection → delivered\n * trigger-fired pg_notify, same connection → delivered\n * another connection causes the notify → NOT delivered to the listener\n * …and the same notification IS delivered to the notifier, which never asked\n *\n * The realtime engine listens on a dedicated connection and the writes come\n * from request connections, so it is exactly the broken case, every time.\n *\n * The fix is to stop treating a notification as belonging to one connection,\n * which for a single-session database is the truth anyway: this proxy watches\n * the server→client direction, and every `NotificationResponse` frame it sees is\n * copied to every other connected client. A client that never issued `LISTEN`\n * may receive one it did not ask for; `pg` raises a `notification` event nobody\n * has subscribed to, which costs nothing. A client that *did* ask now always\n * gets it, which is the whole point.\n *\n * Two properties make this safe rather than clever:\n *\n * - **It never parses SQL and never rewrites a byte.** Frames are forwarded\n * verbatim; the only edit is delivering a copy of one to more sockets.\n * - **Injection only happens on a message boundary.** The server→client stream\n * is reassembled into whole protocol messages before anything is written on,\n * so an injected frame can never land inside another message.\n *\n * This exists only for the managed development database. Against a real Postgres\n * there is no proxy, because there is no defect to correct.\n */\n\nimport net from \"net\";\n\n/** `NotificationResponse`. The one message type this proxy treats specially. */\nconst NOTIFICATION_RESPONSE = 0x41; // 'A'\n\n/**\n * The SSL negotiation request, which is the one thing on the wire that is not\n * a typed message.\n *\n * A client may open with an 8-byte `SSLRequest` (length 8, code 80877103), and\n * the server answers with a *single untyped byte* — `N` or `S`. Feeding that\n * byte to a parser expecting `type + Int32 length` would desynchronise the\n * stream for the rest of the connection, so it is recognised and passed through.\n */\nconst SSL_REQUEST_LENGTH = 8;\nconst SSL_REQUEST_CODE = 80877103;\n\nfunction isSslRequest(chunk: Buffer): boolean {\n return (\n chunk.length >= SSL_REQUEST_LENGTH &&\n chunk.readInt32BE(0) === SSL_REQUEST_LENGTH &&\n chunk.readInt32BE(4) === SSL_REQUEST_CODE\n );\n}\n\n/**\n * Reassembles a server→client byte stream into whole protocol messages.\n *\n * Every backend message is `Int8 type` + `Int32 length` + payload, where the\n * length counts itself but not the type byte. Anything shorter than a full\n * message is held until the rest arrives — TCP offers no guarantee that a\n * message arrives in one chunk, and a proxy that assumed otherwise would inject\n * into the middle of a row description under load.\n */\nexport class BackendMessageParser {\n private buffered: Buffer = Buffer.alloc(0);\n /** Set once the untyped SSL negotiation byte has been dealt with. */\n private awaitingSslReply = false;\n\n expectSslReply(): void {\n this.awaitingSslReply = true;\n }\n\n /** Feed bytes in; get whole messages out, in order. */\n push(chunk: Buffer): Buffer[] {\n const messages: Buffer[] = [];\n this.buffered = this.buffered.length === 0 ? chunk : Buffer.concat([this.buffered, chunk]);\n\n if (this.awaitingSslReply && this.buffered.length >= 1) {\n // Single untyped byte: 'N' (no SSL) or 'S' (proceed).\n messages.push(this.buffered.subarray(0, 1));\n this.buffered = this.buffered.subarray(1);\n this.awaitingSslReply = false;\n }\n\n while (this.buffered.length >= 5) {\n const length = this.buffered.readInt32BE(1);\n // A length below 4 cannot describe itself; the stream is not one we\n // understand, so stop parsing and let the rest through untouched\n // rather than guessing.\n if (length < 4) break;\n const total = length + 1;\n if (this.buffered.length < total) break;\n messages.push(this.buffered.subarray(0, total));\n this.buffered = this.buffered.subarray(total);\n }\n\n return messages;\n }\n\n /** Bytes held back because they are not yet a whole message. */\n get pending(): number {\n return this.buffered.length;\n }\n}\n\nexport function isNotificationFrame(message: Buffer): boolean {\n return message.length > 0 && message[0] === NOTIFICATION_RESPONSE;\n}\n\n/** Channel and payload of a NotificationResponse, for logging and tests. */\nexport function decodeNotification(message: Buffer): { channel: string; payload: string } | null {\n if (!isNotificationFrame(message) || message.length < 10) return null;\n // 1 type byte + 4 length + 4 process id, then two null-terminated strings.\n const body = message.subarray(9);\n const split = body.indexOf(0);\n if (split === -1) return null;\n const channel = body.subarray(0, split).toString(\"utf8\");\n const rest = body.subarray(split + 1);\n const end = rest.indexOf(0);\n\n return { channel, payload: (end === -1 ? rest : rest.subarray(0, end)).toString(\"utf8\") };\n}\n\nexport interface NotificationProxyOptions {\n /** Port clients connect to. */\n listenPort: number;\n /** Port the real PGlite socket server is on. */\n upstreamPort: number;\n host?: string;\n /** Called for every notification broadcast. For diagnostics and tests. */\n onNotification?: (channel: string, payload: string, copies: number) => void;\n}\n\ninterface Connection {\n client: net.Socket;\n upstream: net.Socket;\n parser: BackendMessageParser;\n}\n\n/**\n * The proxy itself.\n *\n * One upstream connection per client connection, so the multiplexer downstream\n * sees exactly what it would have seen without the proxy.\n */\nexport class NotificationProxy {\n private server: net.Server | null = null;\n private readonly connections = new Set<Connection>();\n\n constructor(private readonly options: NotificationProxyOptions) {}\n\n get connectionCount(): number {\n return this.connections.size;\n }\n\n start(): Promise<void> {\n const host = this.options.host ?? \"127.0.0.1\";\n\n return new Promise((resolve, reject) => {\n const server = net.createServer((client) => this.accept(client, host));\n server.once(\"error\", reject);\n server.listen(this.options.listenPort, host, () => {\n this.server = server;\n resolve();\n });\n });\n }\n\n private accept(client: net.Socket, host: string): void {\n const upstream = net.connect(this.options.upstreamPort, host);\n const connection: Connection = { client, upstream, parser: new BackendMessageParser() };\n this.connections.add(connection);\n\n // Nagle would batch a notification behind nothing at all, adding latency\n // to the one message whose entire value is arriving promptly.\n client.setNoDelay(true);\n upstream.setNoDelay(true);\n\n client.on(\"data\", (chunk: Buffer) => {\n if (isSslRequest(chunk)) connection.parser.expectSslReply();\n upstream.write(chunk);\n });\n\n upstream.on(\"data\", (chunk: Buffer) => {\n for (const message of connection.parser.push(chunk)) {\n // The rest of a response to a client that has gone is read\n // and dropped — see `close`.\n if (!client.destroyed) client.write(message);\n if (isNotificationFrame(message)) this.broadcast(message, connection);\n }\n });\n\n // The upstream socket is ended, never destroyed. A client that goes\n // away mid-response (Atlas exiting on a failed migration) leaves the\n // rest of that response in flight, and closing a socket with data\n // unread makes the kernel answer with a reset. `PGLiteSocketServer`\n // (0.2.9) handles a reset by detaching the connection's listeners\n // before its `close`, the one event it stops counting a connection\n // on, so every such exit cost one of the few connections it accepts\n // until the daemon restarted, and the next `rebase db migrate` beside\n // a running `rebase dev` got `Error: EOF`. Ended, the server reads an\n // ordinary close, and the proxy's upstream closes once it has.\n const close = () => {\n this.connections.delete(connection);\n client.destroy();\n upstream.end();\n };\n client.on(\"close\", close);\n client.on(\"error\", close);\n upstream.on(\"close\", close);\n upstream.on(\"error\", close);\n }\n\n /**\n * Copy a notification to every other client.\n *\n * Written directly rather than through a parser: it is already a whole\n * message, and every other socket is only ever written whole messages, so\n * there is no boundary to land inside.\n */\n private broadcast(message: Buffer, origin: Connection): void {\n let copies = 0;\n for (const connection of this.connections) {\n if (connection === origin) continue;\n if (connection.client.destroyed || !connection.client.writable) continue;\n connection.client.write(message);\n copies += 1;\n }\n\n const decoded = decodeNotification(message);\n if (decoded) this.options.onNotification?.(decoded.channel, decoded.payload, copies);\n }\n\n async stop(): Promise<void> {\n for (const connection of [...this.connections]) {\n connection.client.destroy();\n connection.upstream.destroy();\n }\n this.connections.clear();\n\n const server = this.server;\n this.server = null;\n if (!server) return;\n\n await new Promise<void>((resolve) => server.close(() => resolve()));\n }\n}\n","/**\n * The managed database process: one PGlite instance behind a Postgres socket.\n *\n * Runs as `rebase __dev-db-daemon`, a hidden subcommand rather than a separate\n * build entry point, so the same resolution works from `src` under tsx and from\n * the bundled `dist` a published CLI ships — there is no second file for a\n * build config to forget.\n *\n * It is deliberately detached from whoever started it. `rebase db push` in one\n * terminal and `rebase dev` in another must reach the same database, because\n * two processes opening one PGlite data directory would corrupt it, so the\n * daemon belongs to the *project* rather than to a command. What starts it is\n * incidental; what stops it is an explicit `rebase db stop`, an idle timeout,\n * or the machine going away.\n *\n * PGlite is imported dynamically. It is an optional dependency carrying a 25MB\n * WASM build, and the cost of that must fall only on someone who actually uses\n * the managed database — never on `rebase init`, and never on a CLI startup\n * that is about to print help.\n */\n\nimport fs from \"fs\";\nimport net from \"net\";\nimport { DEFAULT_RESOURCE_KEY } from \"@rebasepro/types\";\n\nimport {\n MANAGED_IDLE_TIMEOUT_MS,\n MANAGED_SERVER_MAX_CONNECTIONS,\n PGLITE_EXTENSIONS\n} from \"./constraints\";\nimport { NotificationProxy } from \"./notification-proxy\";\nimport { additionalDataDir, chooseManagedPort, clearState, dataDir, findFreePort, recordManagedPorts, writeState } from \"./state\";\n\n\n/** How often to check for idleness. */\nconst IDLE_CHECK_INTERVAL_MS = 60_000;\n\nexport interface DaemonArgs {\n projectRoot: string;\n port: number;\n token: string;\n idleTimeoutMs: number;\n}\n\n/**\n * `--project <dir> --port <n> --token <t> [--idle-timeout <ms>]`.\n *\n * Every field is required and unvalidated input is fatal: this process is\n * spawned by the CLI, never typed by a person, so a malformed argument is a bug\n * in the caller and guessing would hide it.\n */\nexport function parseDaemonArgs(argv: readonly string[]): DaemonArgs {\n const take = (flag: string): string | null => {\n const index = argv.indexOf(flag);\n\n return index >= 0 && index + 1 < argv.length ? argv[index + 1] : null;\n };\n\n const projectRoot = take(\"--project\");\n const port = Number(take(\"--port\"));\n const token = take(\"--token\");\n const idleRaw = take(\"--idle-timeout\");\n\n if (!projectRoot) throw new Error(\"__dev-db-daemon: --project is required\");\n if (!Number.isInteger(port) || port <= 0 || port > 65535) {\n throw new Error(\"__dev-db-daemon: --port must be a valid port\");\n }\n if (!token) throw new Error(\"__dev-db-daemon: --token is required\");\n\n const idleTimeoutMs = idleRaw === null ? MANAGED_IDLE_TIMEOUT_MS : Number(idleRaw);\n if (!Number.isFinite(idleTimeoutMs) || idleTimeoutMs < 0) {\n throw new Error(\"__dev-db-daemon: --idle-timeout must be a non-negative number of milliseconds\");\n }\n\n return { projectRoot, port, token, idleTimeoutMs };\n}\n\n/**\n * Load the extension bundles PGlite needs.\n *\n * `CREATE EXTENSION pg_trgm` cannot install anything on its own here — PGlite\n * resolves extensions from bundles handed to the constructor, and a missing one\n * fails at migration time with `extension \"pg_trgm\" is not available`, which\n * reads like a broken database rather than a missing import.\n *\n * Every failure here is loud for that reason, including the one that is new:\n * pgvector arrives from a package of its own, so unlike the contrib bundles it\n * can be absent while PGlite itself is fine.\n */\nexport async function loadExtensions(): Promise<Record<string, unknown>> {\n const extensions: Record<string, unknown> = {};\n for (const extension of PGLITE_EXTENSIONS) {\n let module: Record<string, unknown>;\n try {\n module = (await import(extension.module)) as Record<string, unknown>;\n } catch (err) {\n throw new Error(\n `Could not load \"${extension.module}\", which supplies the ${extension.name} extension: ` +\n `${err instanceof Error ? err.message : String(err)}\\n` +\n \"It is an optional dependency of @rebasepro/cli — reinstall the project, \" +\n \"or run `rebase dev --docker` to use a real Postgres instead.\"\n );\n }\n const bundle = module[extension.export];\n if (!bundle) {\n throw new Error(\n `${extension.module} did not export \"${extension.export}\". ` +\n \"The installed PGlite version may not ship this extension.\"\n );\n }\n extensions[extension.name] = bundle;\n }\n\n return extensions;\n}\n\n/**\n * A tiny sidecar listener that answers one question: \"are you the daemon this\n * state file describes?\"\n *\n * Liveness cannot be answered by the pid — after a reboot the number belongs to\n * something else — nor by the port alone, for the same reason. Both would let\n * Rebase send a migration to a stranger. So the daemon publishes a token on a\n * second loopback port and the answer is only yes when the token matches.\n */\n/**\n * How long a client has to send a command after the identity line, before\n * the daemon closes the socket. The liveness check never sends one and\n * closes on its own; this is for a client that connected and hung.\n */\nconst COMMAND_TIMEOUT_MS = 2_000;\n\n/**\n * One command a client may send after reading the identity line.\n *\n * `ensure <key>` answers `ok <port>` once a PGlite instance for that declared\n * database is serving, starting it if it is not. A daemon started before a\n * second database was declared serves it without a restart, which matters\n * because `rebase studio` in another terminal is connected to the first.\n */\ntype CommandHandler = (command: string) => Promise<string>;\n\nfunction startIdentityServer(token: string, onConnection: () => void, onCommand: CommandHandler): Promise<net.Server> {\n return new Promise((resolve, reject) => {\n const server = net.createServer((socket) => {\n onConnection();\n socket.write(`rebase-dev-db ${token}\\n`);\n let buffered = \"\";\n const timer = setTimeout(() => socket.end(), COMMAND_TIMEOUT_MS);\n socket.on(\"data\", (chunk) => {\n buffered += chunk.toString(\"utf8\");\n const newline = buffered.indexOf(\"\\n\");\n if (newline === -1) return;\n clearTimeout(timer);\n const command = buffered.slice(0, newline).trim();\n buffered = \"\";\n onCommand(command)\n .then((reply) => socket.end(`${reply}\\n`))\n .catch((err) => socket.end(`error ${err instanceof Error ? err.message : String(err)}\\n`));\n });\n socket.on(\"error\", () => clearTimeout(timer));\n socket.on(\"close\", () => clearTimeout(timer));\n });\n server.once(\"error\", reject);\n server.listen(0, \"127.0.0.1\", () => resolve(server));\n });\n}\n\nexport async function runDaemon(args: DaemonArgs): Promise<void> {\n const directory = dataDir(args.projectRoot);\n fs.mkdirSync(directory, { recursive: true });\n\n const { PGlite } = (await import(\"@electric-sql/pglite\")) as {\n PGlite: { create(options: unknown): Promise<unknown> };\n };\n const { PGLiteSocketServer } = (await import(\"@electric-sql/pglite-socket\")) as {\n PGLiteSocketServer: new (options: unknown) => {\n start(): Promise<void>;\n stop(): Promise<void>;\n getStats(): { activeConnections: number; queuedQueries: number };\n };\n };\n\n const extensions = await loadExtensions();\n\n /** One PGlite instance, its socket server and the proxy clients reach it through. */\n interface Instance {\n db: { close(): Promise<void> };\n server: { stop(): Promise<void>; getStats(): { activeConnections: number; queuedQueries: number } };\n proxy: NotificationProxy;\n port: number;\n dataDir: string;\n }\n\n // The socket server listens privately; clients reach it through the\n // notification proxy on the public port. Realtime does not work\n // otherwise — PGlite is one session, so a NotificationResponse is handed\n // to whichever socket is reading rather than to the one that issued\n // LISTEN. See `notification-proxy.ts` for the measurements.\n const startInstance = async (instanceDir: string, listenPort: number, label: string): Promise<Instance> => {\n fs.mkdirSync(instanceDir, { recursive: true });\n const db = (await PGlite.create({ dataDir: instanceDir, extensions })) as { close(): Promise<void> };\n const upstreamPort = await findFreePort();\n const server = new PGLiteSocketServer({\n db,\n port: upstreamPort,\n host: \"127.0.0.1\",\n // Above the client pool limit so a second *non-transactional* client is\n // refused with a connection error rather than deadlocking the\n // multiplexer. See `constraints.ts` — the pool limit is what actually\n // prevents overlapping transactions.\n maxConnections: MANAGED_SERVER_MAX_CONNECTIONS\n });\n await server.start();\n const proxy = new NotificationProxy({\n listenPort,\n upstreamPort,\n onNotification: (channel, _payload, copies) => {\n if (copies > 0) process.stdout.write(`dev-db${label}: relayed notification on ${channel} to ${copies} client(s)\\n`);\n }\n });\n await proxy.start();\n return { db, server, proxy, port: listenPort, dataDir: instanceDir };\n };\n\n const primary = await startInstance(directory, args.port, \"\");\n /** Additional declared databases, by key. Started on demand. */\n const additional = new Map<string, Instance>();\n /** In-flight starts, so two commands asking for one key start one instance. */\n const starting = new Map<string, Promise<Instance>>();\n\n // \"Idle\" means nothing is connected to the *database*. An earlier version\n // tracked identity pings instead, which meant a daemon serving queries\n // steadily for an hour would decide it was idle and shut down under a\n // running dev server.\n let idleSince: number | null = Date.now();\n\n const publishState = (identityPort: number) => {\n const databases: Record<string, { port: number; dataDir: string }> = {};\n for (const [key, instance] of additional) databases[key] = { port: instance.port, dataDir: instance.dataDir };\n // Kept after this daemon is gone, so the next one listens where this\n // one did (`chooseManagedPort`).\n const ports: Record<string, number> = { [DEFAULT_RESOURCE_KEY]: args.port };\n for (const [key, entry] of Object.entries(databases)) ports[key] = entry.port;\n recordManagedPorts(args.projectRoot, ports);\n writeState(args.projectRoot, {\n port: args.port,\n pid: process.pid,\n dataDir: directory,\n startedAt: new Date().toISOString(),\n token: args.token,\n identityPort,\n ...(additional.size > 0 ? { databases } : {})\n });\n };\n\n let identityPort = 0;\n const ensureAdditional = async (key: string): Promise<Instance> => {\n const existing = additional.get(key);\n if (existing) return existing;\n const inFlight = starting.get(key);\n if (inFlight) return inFlight;\n const promise = (async () => {\n // Its own stable port, for the same reason the default has one.\n const instance = await startInstance(additionalDataDir(args.projectRoot, key), await chooseManagedPort(args.projectRoot, key), ` [${key}]`);\n additional.set(key, instance);\n publishState(identityPort);\n process.stdout.write(`dev-db [${key}]: ready on 127.0.0.1:${instance.port}\\n`);\n return instance;\n })();\n starting.set(key, promise);\n try {\n return await promise;\n } finally {\n starting.delete(key);\n }\n };\n\n const identity = await startIdentityServer(args.token, () => {\n idleSince = null;\n }, async (command) => {\n const match = /^ensure\\s+(\\S+)$/.exec(command);\n if (!match) return `error unknown command \"${command}\"`;\n const key = match[1];\n // The key becomes a directory name and a variable suffix; the same\n // rule the declaration passed applies here, so nothing a declaration\n // could not say reaches the filesystem.\n if (!/[a-z0-9]/i.test(key) || key.includes(\"/\") || key.includes(\"..\")) return `error invalid key \"${key}\"`;\n const instance = await ensureAdditional(key);\n return `ok ${instance.port}`;\n });\n const identityAddress = identity.address();\n identityPort = identityAddress !== null && typeof identityAddress !== \"string\" ? identityAddress.port : 0;\n\n publishState(identityPort);\n\n let shuttingDown = false;\n const shutdown = async (reason: string) => {\n if (shuttingDown) return;\n shuttingDown = true;\n process.stdout.write(`dev-db: stopping (${reason})\\n`);\n // The state file goes first: a command that reads it during shutdown\n // should conclude \"not running\" and start a fresh daemon, rather than\n // connect to a socket that is closing under it.\n clearState(args.projectRoot);\n identity.close();\n for (const instance of [primary, ...additional.values()]) {\n try {\n await instance.proxy.stop();\n } catch { /* already down */ }\n try {\n await instance.server.stop();\n } catch { /* already down */ }\n try {\n await instance.db.close();\n } catch { /* already closed */ }\n }\n process.exit(0);\n };\n\n process.on(\"SIGINT\", () => void shutdown(\"SIGINT\"));\n process.on(\"SIGTERM\", () => void shutdown(\"SIGTERM\"));\n // The parent going away must not take the database with it — the daemon\n // belongs to the project. But an orphan with nobody left to serve should\n // not outlive the session either, which is what the idle timer is for.\n process.on(\"disconnect\", () => { /* detached on purpose */ });\n\n if (args.idleTimeoutMs > 0) {\n const timer = setInterval(() => {\n const busy = [primary, ...additional.values()].some((instance) => {\n const stats = instance.server.getStats();\n return stats.activeConnections > 0 || stats.queuedQueries > 0;\n });\n if (busy) {\n idleSince = null;\n\n return;\n }\n if (idleSince === null) {\n idleSince = Date.now();\n\n return;\n }\n if (Date.now() - idleSince >= args.idleTimeoutMs) {\n void shutdown(`idle for ${Math.round(args.idleTimeoutMs / 60_000)} minutes`);\n }\n }, IDLE_CHECK_INTERVAL_MS);\n timer.unref();\n }\n\n process.stdout.write(`dev-db: ready on 127.0.0.1:${args.port}\\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAM,wBAAwB;;;;;;;;;;AAW9B,IAAM,qBAAqB;AAC3B,IAAM,mBAAmB;AAEzB,SAAS,aAAa,OAAwB;CAC1C,OACI,MAAM,UAAU,sBAChB,MAAM,YAAY,CAAC,MAAM,sBACzB,MAAM,YAAY,CAAC,MAAM;AAEjC;;;;;;;;;;AAWA,IAAa,uBAAb,MAAkC;CAC9B,WAA2B,OAAO,MAAM,CAAC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AAY,KAAK,IAAI;GAErB;EACJ;EACA,IAAI,KAAK,IAAI,IAAI,aAAa,KAAK,eAC/B,SAAc,YAAY,KAAK,MAAM,KAAK,gBAAgB,GAAM,EAAE,SAAS;CAEnF,GAAG,sBACH,CAAA,CAAM,MAAM;CAGhB,QAAQ,OAAO,MAAM,8BAA8B,KAAK,KAAK,GAAG;AACpE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"db-Dkn9XhT-.js","names":[],"sources":["../src/utils/command-words.ts","../src/utils/spawn-error.ts","../src/commands/db.ts"],"sourcesContent":["/**\n * The words that name a command, with the flags taken back out.\n *\n * `rawArgs` is the whole of `process.argv`, and reading the command's words at\n * fixed indices off it assumes nothing precedes them. Something routinely does:\n * `--debug` is what `bin/rebase.js` prints after every failure as the thing to\n * re-run with, so it is the single most likely token to appear before a command\n * word, and it shifted every index by one.\n *\n * What that cost is not a bad error message. `rebase db branch switch feature`\n * writes a per-checkout pointer that the CLI owns; the driver, running as a\n * child process, cannot persist it and does not try. The dispatch found\n * `switch` by position, so `rebase --debug db branch switch feature` missed the\n * CLI's branch and handed the line to the driver — which reported success and\n * left the checkout on the main database. Every subsequent `dev`, `push` and\n * `backup` then ran against the wrong database, believing it was the branch,\n * which is the exact failure branching exists to prevent.\n *\n * The words are anchored on the command name rather than taken from position\n * zero, because a flag written in the space form (`--database-url <url>`) leaves\n * its value behind as a bare token and no parser at this level knows which\n * flags take values. Anchoring survives that: the value would have to be the\n * literal command name to fool it.\n *\n * Returns `[]` when the command name is not on the line at all.\n */\nexport function commandWords(rawArgs: readonly string[], command: string): string[] {\n const words = rawArgs.slice(2).filter(token => !token.startsWith(\"-\"));\n const start = words.indexOf(command);\n return start === -1 ? [] : words.slice(start);\n}\n\n/**\n * The line to hand a spawned driver, starting at the command word.\n *\n * The same defect one layer down, and it does not degrade gracefully: the\n * driver reads its domain from `args[0]`, so `rebase --debug db push` spawned\n * it with `[\"--debug\", \"db\", \"push\"]` and it answered \"Unknown domain command:\n * --debug\" — for a flag the CLI itself tells you to add after any failure.\n *\n * Tokens written *before* the command word are moved after it rather than\n * dropped. Dropping them would be the same class of bug in the other direction:\n * `rebase --database-url postgres://… db push` would silently lose the flag that\n * says which database to touch. Appending keeps each flag next to its value, and\n * `arg` reads flags wherever they appear.\n *\n * Falls back to `rawArgs.slice(2)` when the command word is not on the line,\n * which is what an internally synthesised argv looks like.\n */\nexport function argsFromCommand(rawArgs: readonly string[], command: string): string[] {\n const tail = rawArgs.slice(2);\n const start = tail.findIndex(token => token === command);\n if (start <= 0) return [...tail];\n return [...tail.slice(start), ...tail.slice(0, start)];\n}\n","/**\n * What to say when a spawned child process fails.\n *\n * Two failures arrive through the same `catch` and need opposite treatment:\n *\n * - **The child ran and exited non-zero.** It had inherited stdio, so it has\n * already printed its own diagnostics. execa's \"Command failed with exit\n * code 1: …\" is a second, worse copy of the same news with the whole argv\n * appended.\n * - **The child never started.** ENOENT on the tsx binary, EACCES on a script\n * that lost its permissions, ENOMEM on a full machine. Nobody printed\n * anything, because nothing ran. `schema.ts` and `doctor.ts` both swallowed\n * these — `catch { process.exit(1); }`, the error not even bound — so\n * `rebase schema generate` against a broken tsx exited 1 in silence, and so\n * did `rebase doctor`, the command whose entire job is to say what is wrong.\n *\n * The tsx symlink surviving a cleaned pnpm store is the ordinary way to get\n * here: `resolveLocalBin` finds the symlink, so \"dependencies are not\n * installed\" never fires, and the spawn is where it breaks.\n *\n * ## Why the message is not what decides it\n *\n * `db.ts` did make this distinction, by testing the message against\n * `/Command failed|exited with code/i` — and that test is wrong for every case\n * it was written to catch. execa prefixes **all** of them the same way:\n *\n * Command failed with exit code 3: /bin/sh -c 'exit 3'\n * Command failed with ENOENT: /…/tsx x⏎spawn /…/tsx ENOENT\n * Command failed with EACCES: /…/tsx x⏎spawn /…/tsx EACCES\n *\n * So the filter matched the spawn failures too and `db push` was as silent as\n * the other two. The structured fields do distinguish them: a child that ran\n * has a numeric `exitCode` (or a `signal`, if something killed it), and a child\n * that never started has neither — only an errno in `code`.\n */\nimport chalk from \"chalk\";\n\ninterface ChildProcessFailure {\n exitCode?: unknown;\n signal?: unknown;\n /** execa's message without the \"Command failed with …: <argv>\" preamble. */\n originalMessage?: unknown;\n}\n\n/** Did the process start? Only then has anything else already been printed. */\nfunction childRan(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const failure = error as Error & ChildProcessFailure;\n return typeof failure.exitCode === \"number\" || typeof failure.signal === \"string\";\n}\n\nexport function reportSpawnFailure(error: unknown): void {\n if (childRan(error) || !(error instanceof Error)) return;\n\n // `originalMessage` is \"spawn /…/tsx ENOENT\" — the same fact as `message`\n // without a second copy of the argv the user just typed. Absent on the\n // errors these commands raise themselves, which are already one sentence.\n const failure = error as Error & ChildProcessFailure;\n const message = typeof failure.originalMessage === \"string\"\n ? failure.originalMessage\n : error.message;\n if (message) console.error(chalk.red(`✗ ${message}`));\n}\n","/**\n * CLI command: rebase db <action>\n */\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport inquirer from \"inquirer\";\nimport os from \"os\";\nimport path from \"path\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n resolveTsxLoader,\n findEnvFile,\n dependenciesNotInstalled\n} from \"../utils/project\";\nimport { reportSpawnFailure } from \"../utils/spawn-error\";\nimport { parseCommandArgs, UsageError } from \"../utils/args\";\nimport { suggestCommand, unknownCommand } from \"../utils/unknown-command\";\nimport { argsFromCommand, commandWords } from \"../utils/command-words\";\nimport { COLLECTIONS_FLAG_HELP, refuseMissingCollectionsPath } from \"../utils/path-flags\";\nimport { recordEvent } from \"../telemetry\";\nimport { DEV_DATABASE_KIND_ENV, devDatabaseKind, type PreparedDatabase } from \"../dev-db/prepare\";\nimport { type DevDatabase } from \"../dev-db/resolve\";\nimport type { AtlasDevDatabase } from \"../dev-db/atlas-dev-database\";\n\n/**\n * The connection string a prepared database actually answers on.\n *\n * One function, because `db url` and `db pull` disagreed about it and the\n * disagreement was a dead command: `prepareDatabaseEnv` returns `env: {}` for a\n * plain external database — the connection string is already somewhere the\n * child looks — so `db pull`'s `prepared.env.DATABASE_URL ?? process.env\n * .DATABASE_URL` was empty for the standard `.env` configuration and answered\n * `✗ No local database to pull into.` on a project whose `rebase db url` had\n * just printed one. Exporting the same URL in the shell made it work, which is\n * the shape of a bug nobody reports as one.\n *\n * `readEnvFile` is passed in rather than imported: this module loads\n * `../utils/project` dynamically everywhere else, and the callers already have\n * it open.\n */\nexport function databaseUrlOf(\n prepared: Pick<PreparedDatabase, \"env\" | \"database\">,\n envFile: Record<string, string>\n): string | undefined {\n // An empty string is \"nothing named a database\", not \"the database is the\n // empty string\" — `docker` resolves to `url: null` when the compose file\n // declares no usable db service.\n const named = (value: string | null | undefined) => (value && value.trim() ? value : undefined);\n\n return named(prepared.env.DATABASE_URL)\n ?? named(prepared.database.kind === \"managed\" ? undefined : prepared.database.url)\n ?? named(envFile.DATABASE_URL)\n ?? named(process.env.DATABASE_URL);\n}\n\n/**\n * A destination that names a remote store rather than a local path.\n *\n * Matched as \"scheme://\" generally, not as a list of the schemes we support:\n * an unknown scheme is still not something to join onto a filesystem path, and\n * a Windows drive letter (\"C:\\backups\") has no \"//\" so it stays a path.\n */\nconst REMOTE_DESTINATION_RE = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n\n/**\n * The flags whose value is a local path, on every line the CLI relays.\n *\n * All three spellings of the destination, because the driver accepts all\n * three: `backup-cli.ts` maps `--output` and `-o` onto `--out`, and `rebase db\n * backup --help` advertises `--output` as an alias. Only `--out` and `-o` were\n * absolutised once, so the one spelling the help page names was the one that\n * landed in `backend/` — and the success line still echoed the path as typed.\n *\n * And `--collections`, which was not absolutised at all: from the project root,\n * `rebase schema generate --collections ./config/collections` was \"not found\",\n * while the same spelling worked for `generate-sdk`. See `utils/path-flags.ts`.\n */\nexport const LOCAL_PATH_FLAGS: readonly string[] = [\"--out\", \"--output\", \"-o\", \"--collections\", \"-c\"];\n\n/**\n * Rewrite local path arguments so they mean what the user typed.\n *\n * The plugin CLI is spawned with `cwd: backendDir` — it has to be, because that\n * is where the plugin and its dependencies resolve from. But the developer runs\n * `rebase db` from the project root, so a relative `--out ./backups` was being\n * resolved against `backend/` and landed in `backend/backups`, while the\n * success line echoed the path as typed. The file was real and the reported\n * location was wrong, which is the worst way for a backup command to behave.\n * `rebase db --help` documents exactly this invocation.\n *\n * Absolutising here rather than inside the plugin keeps the fix where the cwd\n * is actually changed, and leaves the plugin usable on its own terms.\n */\nexport function absolutizeLocalPathArgs(\n args: string[],\n cwd: string,\n pathFlags: readonly string[] = LOCAL_PATH_FLAGS\n): string[] {\n const takesPath = (flag: string) => pathFlags.includes(flag);\n /**\n * Flags whose next token is a value, not a positional.\n *\n * Mirrors the `arg` specs in `@rebasepro/server-postgres`'s backup CLI.\n * Needed only to find the `db restore` dump argument: without it,\n * `restore --target-db app_restored ./x.dump` treats `app_restored` as the\n * positional — it is the first token not starting with `-` — and turns a\n * database name into a path while leaving the real dump path unresolved.\n */\n const VALUE_FLAGS = new Set([\n \"--out\", \"--output\", \"-o\", \"--target-db\", \"--exclude-schema\", \"--row-security-role\"\n ]);\n const out = [...args];\n\n for (let i = 0; i < out.length; i++) {\n const arg = out[i];\n\n // `--out=<value>`\n const eq = arg.indexOf(\"=\");\n if (eq > 0 && takesPath(arg.slice(0, eq))) {\n const value = arg.slice(eq + 1);\n if (value && !REMOTE_DESTINATION_RE.test(value)) {\n out[i] = `${arg.slice(0, eq)}=${path.resolve(cwd, value)}`;\n }\n continue;\n }\n\n // `--out <value>`\n if (takesPath(arg)) {\n const value = out[i + 1];\n if (value && !value.startsWith(\"-\") && !REMOTE_DESTINATION_RE.test(value)) {\n out[i + 1] = path.resolve(cwd, value);\n i++;\n }\n }\n }\n\n // `db restore <file>` — the dump to read is a positional, and a relative one\n // was resolved against `backend/` too, so the path printed by a preceding\n // `db backup` could not be pasted into `db restore`.\n const restoreAt = out.indexOf(\"restore\");\n if (restoreAt !== -1) {\n for (let i = restoreAt + 1; i < out.length; i++) {\n const arg = out[i];\n if (arg.startsWith(\"-\")) {\n // `--flag=value` carries its value inline; `--flag value` eats\n // the next token only when the flag actually takes one.\n if (!arg.includes(\"=\") && VALUE_FLAGS.has(arg)) i++;\n continue;\n }\n // First true positional: the dump to restore.\n if (!REMOTE_DESTINATION_RE.test(arg)) out[i] = path.resolve(cwd, arg);\n break;\n }\n }\n\n return out;\n}\n\n/**\n/**\n * Read `--flag value` or `--flag=value` out of the raw argv.\n *\n * This command forwards its arguments to the driver plugin rather than parsing\n * them, so the two flags the CLI itself acts on are picked out by hand instead\n * of adding a spec that would then have to strip them back out again.\n */\nfunction readFlagValue(rawArgs: readonly string[], flag: string): string | null {\n for (let index = 0; index < rawArgs.length; index += 1) {\n const arg = rawArgs[index];\n if (arg === flag) return rawArgs[index + 1] ?? null;\n if (arg.startsWith(`${flag}=`)) return arg.slice(flag.length + 1);\n }\n\n return null;\n}\n\n/**\n * Run a database subcommand through the active driver's CLI, throwing on\n * failure instead of exiting.\n *\n * `dbCommand` below turns every failure into `process.exit(1)`, which is right\n * for a command the user invoked directly and wrong for a caller that has more\n * to do afterwards — `rebase dev` runs a schema push during start-up and must\n * survive it failing. Exiting is therefore the wrapper's job, not this\n * function's.\n *\n * The database is resolved *here* rather than in the wrapper, so the schema\n * push `rebase dev` performs during start-up reaches the managed database too.\n */\n/**\n * The `db` subcommands that plan their work with Atlas.\n *\n * Atlas computes a diff by replaying the desired schema into a **second, empty\n * database** and comparing. That is why these three are listed and `backup` and\n * `restore` are not — those shell out to `pg_dump`, which fails loudly on its\n * own. `branch` is refused too, but for its own reason and with its own\n * message: see {@link refuseBranchOnManagedDatabase}.\n */\nconst ATLAS_BACKED_SUBCOMMANDS = new Set([\"push\", \"generate\", \"migrate\"]);\n\n/**\n * A managed-database refusal, raised so the caller decides what it costs.\n *\n * These two guards used to `process.exit(1)` where they stood. That is right\n * for `rebase db push`, typed by a person, and catastrophic for the same code\n * reached from inside `rebase dev`: the dev server's first-boot schema push\n * runs in-process, so an exit there took the whole dev server down — with a\n * `try/catch` around it written expressly to prevent that, which could never\n * run. The first `rebase dev --docker` of every scaffold died this way.\n *\n * So the refusal is a value now. It carries the block it wants printed rather\n * than printing it, because who prints (and whether printing is even right) is\n * the caller's question: `dbCommand` prints it and exits 1, and `rebase dev`\n * keeps serving.\n */\nexport class ManagedDatabaseRefusal extends Error {\n /** The lines to print, in order, already coloured. */\n readonly lines: readonly string[];\n\n constructor(summary: string, lines: readonly string[]) {\n super(summary);\n this.name = \"ManagedDatabaseRefusal\";\n this.lines = lines;\n }\n}\n\n/** Print a refusal exactly as the guards used to print it themselves. */\nexport function printManagedDatabaseRefusal(refusal: ManagedDatabaseRefusal): void {\n for (const line of refusal.lines) console.error(line);\n}\n\n/**\n * The variable the driver reads for Atlas's dev database\n * (`ATLAS_DEV_URL_ENV` in `@rebasepro/server-postgres`, which this CLI does not\n * depend on).\n */\nexport const ATLAS_DEV_URL_ENV = \"REBASE_ATLAS_DEV_URL\";\n\n/**\n * The variable that tells the driver where `rebase` was run\n * (`INVOCATION_CWD_ENV` in `@rebasepro/server-postgres`). The driver runs in\n * `backend/`, so a path it resolves itself, such as `db backup`'s default\n * `./backups`, needs to know the directory the developer meant.\n */\nconst INVOCATION_CWD_ENV = \"REBASE_INVOCATION_CWD\";\n\n/** Loaded only when a command needs one: PGlite is 25 MB of WASM. */\nconst startAtlasDevDatabase = async (): Promise<AtlasDevDatabase> =>\n (await import(\"../dev-db/atlas-dev-database\")).startAtlasDevDatabase();\n\n/**\n * The empty database an Atlas-backed subcommand plans against, on the managed\n * development database.\n *\n * **PGlite serves exactly one database.** Atlas computes a change by replaying\n * the desired schema into a second, empty one; on a real server the driver\n * makes it as `<db>_dev_diff`, but `CREATE DATABASE` against PGlite reports\n * success and creates nothing, so Atlas connected straight back to the\n * database it was comparing and stopped with `connected database is not\n * clean`. These commands were refused outright on the managed database — and\n * with them every way to drop, rename or narrow a column there, since boot\n * only adds.\n *\n * So a throwaway second PGlite is started for the command instead — in\n * memory, in this process, gone when the command ends — and handed to the\n * driver as `REBASE_ATLAS_DEV_URL`. Nothing else about the push changes: the\n * destructive gate is the driver's, and holds as it does everywhere.\n *\n * `undefined` when none is needed: another database kind (the driver makes its\n * own), a subcommand that is not Atlas's, or a `REBASE_ATLAS_DEV_URL` the\n * developer set. When one cannot be started — PGlite is an optional\n * dependency — the old refusal stands, with the reason.\n */\nexport async function atlasDevDatabaseFor(\n rawArgs: string[],\n kind: string,\n env: Readonly<Record<string, string | undefined>>,\n start: () => Promise<AtlasDevDatabase> = startAtlasDevDatabase\n): Promise<AtlasDevDatabase | undefined> {\n if (kind !== \"managed\") return undefined;\n const [domain, subcommand] = commandWords(rawArgs, \"db\");\n if (domain !== \"db\" || !ATLAS_BACKED_SUBCOMMANDS.has(subcommand ?? \"\")) return undefined;\n if (env[ATLAS_DEV_URL_ENV]?.trim()) return undefined;\n\n try {\n return await start();\n } catch (err) {\n const summary = `rebase db ${subcommand} could not start the database Atlas plans against.`;\n throw new ManagedDatabaseRefusal(summary, [\n \"\",\n chalk.red(` ✗ ${summary}`),\n chalk.gray(` ${err instanceof Error ? err.message : String(err)}`),\n \"\",\n chalk.gray(\" Atlas plans every change against a second, empty database. On the managed\"),\n chalk.gray(\" database that is a throwaway PGlite, started for the command.\"),\n \"\",\n chalk.gray(` ${chalk.cyan(\"rebase dev\")} still applies your collections at boot, additively. Otherwise,`),\n chalk.gray(` set ${ATLAS_DEV_URL_ENV} to an empty Postgres database Atlas may fill and clear,`),\n chalk.gray(\" or point the project at a real Postgres (uncomment DATABASE_URL in .env).\"),\n \"\"\n ]);\n }\n}\n\n/**\n * Stop `rebase db branch` before it reports a branch that is not one.\n *\n * **PGlite serves exactly one database**, and this is the second thing that\n * follows from it. `CREATE DATABASE \"rb_feature_x\" TEMPLATE \"postgres\"` there\n * writes a `pg_database` catalog row and nothing else. Nothing errors, so the\n * whole feature reports success end to end:\n *\n * $ rebase db branch create feature_x\n * ✓ Branch \"feature_x\" created successfully.\n * $ rebase db branch list\n * ● feature_x (7.1 MB) — created just now\n *\n * `listBranches` joins `pg_database`, the catalog row is there, and\n * `pg_database_size` answers with the one database's size — so the listing\n * corroborates the lie. Then connecting to `rb_feature_x` reports\n * `current_database()` = `postgres`, and a table created \"in the branch\" is\n * visible in the parent immediately. Measured on a fresh `rebase init` scaffold.\n *\n * **The branch is the parent.** Every write made in the belief that it is\n * sandboxed lands in the developer's real development database — which is the\n * exact failure branching exists to prevent, announced as a success.\n *\n * So this refuses the whole `branch` domain rather than `create` alone: `list`\n * on the managed database ends with \"Create one with: rebase db branch create\",\n * an invitation to do the broken thing, and `info` would confirm a size for a\n * database that was never made.\n *\n * Push, generate and migrate had the same problem — Atlas's scratch database\n * is a second database too — and get a throwaway PGlite of their own instead\n * (`atlasDevDatabaseFor` above). A branch cannot: it is meant to keep the\n * project's data, and a throwaway instance has none.\n */\nexport function refuseBranchOnManagedDatabase(rawArgs: string[], kind: string): void {\n if (kind !== \"managed\") return;\n const [domain, subcommand] = commandWords(rawArgs, \"db\");\n if (domain !== \"db\" || subcommand !== \"branch\") return;\n\n const summary = \"rebase db branch does not work on the managed development database.\";\n\n throw new ManagedDatabaseRefusal(summary, [\n \"\",\n chalk.red(` ✗ ${summary}`),\n \"\",\n chalk.gray(\" Branching copies a database with CREATE DATABASE ... TEMPLATE. The managed\"),\n chalk.gray(\" database is PGlite, which serves exactly one — the copy would be the\"),\n chalk.gray(\" original, and every write you meant to sandbox would land in it.\"),\n \"\",\n chalk.gray(\" Branching needs a real Postgres. Either:\"),\n chalk.gray(` ${chalk.cyan(\"rebase dev --docker\")} starts one, and branches work against it`),\n chalk.gray(\" or uncomment DATABASE_URL in .env to point at your own.\"),\n \"\"\n ]);\n}\n\n/**\n * The variable a driver child reads what named its database from: the\n * resolution's `source` (`flag`, `environment`, `env-file`, `branch`,\n * `docker`, `last-dev` or `managed`). Read as a literal by\n * `@rebasepro/server-postgres`'s `cli-errors.ts`.\n */\nexport const DATABASE_SOURCE_ENV = \"REBASE_DATABASE_SOURCE\";\n\n/**\n * Refuse `rebase db restore` into the managed development database.\n *\n * A backup carries its rows as COPY data, and the managed database's socket\n * server cannot take `COPY … FROM stdin`: `rebase db restore --clean` into it\n * hung the daemon, and every command after it, until the daemon was killed.\n * `pg_restore` has no way to write the rows as INSERTs. `rebase db pull`\n * dumps them that way itself (see `dev-db/pull.ts`), so the route is to\n * restore into a real Postgres and pull the copy across.\n */\nexport function refuseRestoreOnManagedDatabase(rawArgs: string[], kind: string): void {\n if (kind !== \"managed\") return;\n const words = argsFromCommand(rawArgs, \"db\");\n if (words[0] !== \"db\" || words[1] !== \"restore\") return;\n\n let dump = \"<dump>\";\n for (let i = 2; i < words.length; i++) {\n if (words[i] === \"--target-db\") i++;\n else if (!words[i].startsWith(\"-\")) {\n dump = words[i];\n break;\n }\n }\n const summary = \"rebase db restore does not work on the managed development database.\";\n\n throw new ManagedDatabaseRefusal(summary, [\n \"\",\n chalk.red(` ✗ ${summary} Nothing was restored.`),\n \"\",\n chalk.gray(\" A backup carries its rows as COPY data, which the managed database (PGlite)\"),\n chalk.gray(\" cannot receive: the restore would leave it hung until it is stopped.\"),\n \"\",\n chalk.gray(\" Restore into Postgres in Docker instead:\"),\n chalk.gray(` ${chalk.cyan(`rebase db restore ${dump} --docker --clean --yes`)}`),\n chalk.gray(\" and, to have the copy in the managed database too, pull it across:\"),\n chalk.gray(` ${chalk.cyan(\"rebase db pull --from \\\"$(rebase db url --docker)\\\" --yes\")}`),\n \"\"\n ]);\n}\n\n/**\n * Resolve the active driver's CLI and the environment it should run in.\n *\n * Shared by the two runners below. Deliberately does NOT resolve a database:\n * `schema generate` reads collection files and writes one file, and starting a\n * database to run it would be a side effect nobody asked for.\n */\nexport async function resolveDriverCli(): Promise<{\n projectRoot: string;\n backendDir: string;\n pluginCli: string;\n env: Record<string, string>;\n}> {\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n throw new Error(\n \"Could not detect an active database plugin. Make sure a package like \"\n + \"@rebasepro/server-postgres is installed in backend/package.json.\"\n );\n }\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n throw new Error(dependenciesNotInstalled(projectRoot));\n }\n\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? \"\";\n\n return { projectRoot, backendDir, pluginCli, env };\n}\n\n/**\n * The one place this CLI spawns the driver's own CLI.\n *\n * There were three, each with its own copy of \"tsx for a `.ts` entry, `node`\n * otherwise\". That rule was right only while the driver shipped `src/`; once it\n * shipped `dist/cli.js` all three quietly switched to plain `node`, and the\n * driver loads the PROJECT's TypeScript in process:\n *\n * - `schema stale` reads the collections, could not resolve `./authors` onto\n * `authors.ts`, and answered \"⏭ Not checked\" while exiting 0;\n * - `db push` does the same in `ensureAuthTables`, so `rebase.users` was never\n * created and the push died at \"Applying RLS policies\" with\n * `relation \"rebase.users\" does not exist` — on a virgin database, which is\n * the documented bring-your-own-Postgres first run.\n *\n * Two were fixed and the third was missed, because three copies of a decision\n * are three chances to miss one. There is one now, and a gate holds it at one.\n *\n * tsx whenever it is installed — a devDependency of every scaffold, for exactly\n * this reason. Without it a `.ts` entry cannot run at all; a built entry still\n * runs, and the subcommands that never touch the project's TypeScript still work.\n *\n * tsx's loader in one Node (`node --import`) rather than the `tsx` binary,\n * which is a shell shim and a relay Node in front of the same loader: one Node\n * start instead of two, ~50–100 ms on each of the driver runs every `rebase\n * dev` start and every collection save makes. The binary stays the fallback for\n * a tsx whose loader does not resolve as a package — a global install.\n */\nexport async function spawnDriverCli(\n resolved: { projectRoot: string; backendDir: string; pluginCli: string; env: Record<string, string> },\n childArgs: string[],\n options: { quiet?: boolean } = {}\n): Promise<void> {\n const { projectRoot, backendDir, pluginCli, env } = resolved;\n const stdio = options.quiet ? \"pipe\" : \"inherit\";\n\n const tsxBin = resolveTsx(projectRoot);\n const tsxLoader = resolveTsxLoader(projectRoot);\n if (!tsxBin && !tsxLoader && pluginCli.endsWith(\".ts\")) {\n throw new Error(dependenciesNotInstalled(projectRoot));\n }\n\n const [command, ...prefix] = tsxLoader ? [process.execPath, \"--import\", tsxLoader] : [tsxBin ?? \"node\"];\n await execa(command, [...prefix, pluginCli, ...childArgs], { cwd: backendDir, stdio, env });\n}\n\n/** @deprecated Use {@link spawnDriverCli}. Kept as the internal name callers use. */\nconst execDriverCli = spawnDriverCli;\n\n/**\n * Run a `schema` subcommand through the active driver's CLI.\n *\n * Separate from {@link runDriverDbCommand} because it must NOT resolve a\n * database. `rebase dev` calls this before the database exists, which is the\n * whole point: the generated schema has to be right before anything reads it.\n * Throws rather than exiting — the caller has more to do.\n */\nexport async function runDriverSchemaCommand(\n rawArgs: string[],\n options: { quiet?: boolean } = {}\n): Promise<void> {\n const resolved = await resolveDriverCli();\n await execDriverCli(resolved, rawArgs.slice(2), options);\n}\n\nexport async function runDriverDbCommand(\n rawArgs: string[],\n options: { quiet?: boolean } = {}\n): Promise<void> {\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n throw new Error(\n \"Could not detect an active database plugin. Make sure a package like \"\n + \"@rebasepro/server-postgres is installed in backend/package.json.\"\n );\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n throw new Error(dependenciesNotInstalled(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 // Every `db` subcommand reaches Postgres through the driver plugin, which\n // reads DATABASE_URL from this environment — so resolving the database once\n // here covers push, generate, migrate, backup and restore alike, and any\n // subcommand a driver adds later. When the developer has named their own\n // database this adds nothing at all.\n // Refused before anything is started. `prepareDatabaseEnv` below *boots*\n // the managed database, and booting PGlite in order to say that PGlite\n // cannot branch is latency spent on an answer already known — the resolver\n // is a pure function and settles it. It also keeps the refusal working when\n // the managed database would have failed to start, where the developer\n // would otherwise be told about a daemon rather than about branching.\n const { resolveProjectDatabase } = await import(\"../dev-db/prepare\");\n const resolvedKind = resolveProjectDatabase(projectRoot, {\n flagUrl: readFlagValue(rawArgs, \"--database-url\"),\n flagDocker: rawArgs.includes(\"--docker\")\n }).kind;\n refuseBranchOnManagedDatabase(rawArgs, resolvedKind);\n refuseRestoreOnManagedDatabase(rawArgs, resolvedKind);\n\n const { prepareDatabaseEnv, managedNotices } = await import(\"../dev-db/prepare\");\n const prepared = await prepareDatabaseEnv(projectRoot, {\n flagUrl: readFlagValue(rawArgs, \"--database-url\"),\n flagDocker: rawArgs.includes(\"--docker\"),\n onProgress: (message) => { if (!options.quiet) console.log(chalk.gray(` ${message}`)); }\n });\n Object.assign(env, prepared.env);\n // What named the database, for the driver's \"Cannot connect\" banner to\n // send the reader to it rather than to a `.env` that played no part.\n env[DATABASE_SOURCE_ENV] = prepared.database.source;\n // And which kind it is, for the managed database's Atlas handling\n // (`--skip-lock`, the revisions table made first): the project default set\n // above is wrong for a command whose --database-url or --docker named\n // another database.\n env[DEV_DATABASE_KIND_ENV] = prepared.database.kind;\n // Suppressed for an internal caller. `rebase dev` runs a schema push during\n // start-up and has already said all of this in its own banner; repeating it\n // mid-boot reads as something having gone wrong.\n if (!options.quiet) {\n for (const line of managedNotices(prepared)) console.log(chalk.gray(` ${line}`));\n }\n\n // Started after the managed database, stopped when the driver exits —\n // whatever it exits with.\n const atlasDev = await atlasDevDatabaseFor(rawArgs, prepared.database.kind, env);\n if (atlasDev) env[ATLAS_DEV_URL_ENV] = atlasDev.url;\n env[INVOCATION_CWD_ENV] = process.cwd();\n\n // Resolved against the directory the developer is standing in, before the\n // child is handed a different one. See absolutizeLocalPathArgs.\n //\n // From the command word, not from index 2: the driver reads its domain out\n // of `args[0]`, so `rebase --debug db push` spawned it with [\"--debug\",\n // \"db\", \"push\"] and it answered \"Unknown domain command: --debug\" — for a\n // flag this CLI prints after every failure as the thing to re-run with.\n const childArgs = absolutizeLocalPathArgs(argsFromCommand(rawArgs, \"db\"), process.cwd());\n\n try {\n await spawnDriverCli({ projectRoot, backendDir, pluginCli, env }, childArgs, options);\n } finally {\n await atlasDev?.stop();\n }\n}\n\nexport async function dbCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // `--help` is answered here, before anything else, and never by a\n // subcommand.\n //\n // `cli.ts` rewrites the subcommand to `\"--help\"` only when the user named\n // none, so `rebase db --help` was covered and `rebase db push --help` was\n // not: the flag went through to `runDriverDbCommand`, which resolves (and\n // will START) the development database and then hands the whole line to the\n // driver, whose own dispatch has no `--help` case for `push`. **It ran the\n // push.** A flag whose entire job is to print text applied a schema to a\n // database — the single most dangerous shape a help flag can have, and the\n // same class as `skills install --help` writing files and `auth\n // reset-password --help` running an UPDATE.\n //\n // Answering before `requireProjectRoot` and before the driver spawn makes\n // it structurally impossible rather than conditionally safe: no subcommand\n // can act on `--help`, because no subcommand is reached.\n if (!subcommand || subcommand === \"--help\" || rawArgs.includes(\"--help\") || rawArgs.includes(\"-h\")) {\n printDbHelp(subcommand === \"--help\" ? undefined : subcommand);\n return;\n }\n\n // A typo is answered here, not by the driver, and not after a database has\n // been started for it.\n //\n // `rebase db psh` used to reach `runDriverDbCommand`, which resolves the\n // database first — so it **booted the managed PGlite**, a 180 MB daemon,\n // in order to hand the driver an argv it then rejected with `Unknown db\n // command. Valid: push, generate, migrate, branch, backup, restore,\n // backups`: a list missing `url`, `pull`, `stop` and `reset`, all four of\n // which `rebase db --help` lists and this CLI implements itself. The driver\n // cannot know about them, which is exactly why the answer does not belong\n // to the driver.\n //\n // The set comes from the help table, so the list a typo is measured against\n // and the list `--help` prints cannot drift apart.\n if (!DB_ACTION_HELP[subcommand]) unknownCommand(subcommand, Object.keys(DB_ACTION_HELP), \"db\");\n // `db backups` has one action, and its typo is answered here for the same reason.\n if (subcommand === \"backups\") {\n const action = argsFromCommand(rawArgs, \"backups\")[1];\n if (action !== undefined && action !== \"list\") unknownCommand(action, [\"list\"], \"db backups\");\n }\n\n const projectRoot = requireProjectRoot();\n\n // Fire-and-forget, and a no-op unless the developer opted in. Never awaited:\n // the command is what the user is waiting for, and a slow collector must not\n // sit in front of it.\n void recordEvent(\"cli.db\", { subcommand: subcommand ?? \"none\" }, { projectRoot });\n\n // Handled here rather than by the driver plugin: these are about the\n // *managed* database's process and data directory, which is a CLI concern.\n // A project pointed at its own Postgres has nothing here to stop or reset,\n // and is told so rather than silently doing nothing.\n if (subcommand === \"stop\" || subcommand === \"reset\") {\n await manageLocalDatabase(subcommand, projectRoot, rawArgs);\n\n return;\n }\n\n // `--docker` on a `db` subcommand meant \"resolve the compose URL\", and\n // nothing started it: `rebase db branch list --docker` on a stock scaffold\n // answered `✗ Failed query: CREATE SCHEMA IF NOT EXISTS rebase` and\n // `connect ECONNREFUSED 127.0.0.1:5436` — two lines, no diagnosis — while\n // the managed-database refusal that sends the reader here says \"`rebase dev\n // --docker` starts one, and branches work against it\".\n //\n // The same ensure step `rebase dev --docker` runs, not a second one.\n await ensureDockerDatabase(projectRoot, rawArgs);\n\n if (subcommand === \"pull\") {\n await pullIntoLocal(projectRoot, rawArgs);\n\n return;\n }\n\n if (subcommand === \"url\") {\n await printDatabaseUrl(projectRoot, rawArgs);\n\n return;\n }\n\n // Handled here rather than by the driver, for the same reason `stop` and\n // `reset` are: it writes per-checkout CLI state. The driver creates and\n // drops the databases; which one this checkout talks to is not its\n // business, and it runs as a child process that could not persist the\n // answer anyway.\n if (subcommand === \"branch\" && commandWords(rawArgs, \"db\")[2] === \"switch\") {\n await switchBranch(projectRoot, rawArgs);\n\n return;\n }\n\n // The other two branch actions that need to know where this checkout is\n // standing, for reasons the driver — a child process with no idea a pointer\n // exists — cannot answer.\n let driverArgs = rawArgs;\n if (subcommand === \"branch\") {\n const action = commandWords(rawArgs, \"db\")[2];\n if (action === \"delete\") await refuseDeletingActiveBranch(projectRoot, rawArgs);\n if (action && REGISTRY_ACTIONS.has(action)) driverArgs = await onParentDatabase(projectRoot, rawArgs, action);\n }\n\n // Before the database is resolved — and, for the managed one, started —\n // and in the reader's terms. See utils/path-flags.ts.\n refuseMissingCollectionsPath(driverArgs, process.cwd(), requireBackendDir(projectRoot));\n\n try {\n await runDriverDbCommand(driverArgs);\n } catch (error) {\n // The CLI entry point is where a managed-database refusal becomes an\n // exit code. The guards raise it instead of exiting so that `rebase dev`,\n // which runs `db push` in-process, survives one; here, where a person\n // typed the command, it is exactly as fatal as it always was.\n if (error instanceof ManagedDatabaseRefusal) {\n printManagedDatabaseRefusal(error);\n process.exit(1);\n }\n // A child that exited non-zero already printed its diagnostics through\n // inherited stdio; only the errors raised above have a message worth\n // adding here.\n reportSpawnFailure(error);\n process.exit(1);\n }\n}\n\n/**\n * `rebase db url` — the connection string this project is using, on stdout.\n *\n * The managed database is the one case where nothing on disk names it: `.env`\n * ships `DATABASE_URL` commented out on purpose, the port is derived from the\n * project path, and the data lives under `.rebase/`. A headless project has no\n * admin panel to open either, so before this there was no way to point `psql`,\n * a GUI client or a seeding script at the database `rebase dev` had just\n * created — short of reading the CLI's source.\n *\n * Resolution is the same ordered rule every other command uses, so this prints\n * your own `DATABASE_URL` when you have set one rather than inventing a second\n * answer. Nothing but the URL goes to stdout, so it pipes:\n *\n * psql \"$(rebase db url)\"\n *\n * It starts the managed database if it is not running, because a connection\n * string for a database nobody is serving is not an answer.\n */\nasync function printDatabaseUrl(projectRoot: string, rawArgs: readonly string[]): Promise<void> {\n // Strict about its flags, like every other command.\n //\n // The `db` family's strictness lives in the driver, and `url` is answered\n // here, before the driver is ever spawned — so it accepted anything.\n // `rebase db url --bogus` printed the URL and exited 0, and so did\n // `rebase db url --json`, which is worse: a flag that looks like it asks\n // for a different output format, silently ignored, hands a script a bare\n // string it will try to parse as JSON.\n parseCommandArgs({\n spec: { \"--database-url\": String, \"--docker\": Boolean },\n rawArgs: [...rawArgs],\n commandWords: 2,\n command: \"db url\",\n maxPositionals: 0\n });\n\n const { prepareDatabaseEnv } = await import(\"../dev-db/prepare\");\n const { readEnvFile } = await import(\"../utils/project\");\n\n const prepared = await prepareDatabaseEnv(projectRoot, {\n flagUrl: readFlagValue(rawArgs, \"--database-url\"),\n flagDocker: rawArgs.includes(\"--docker\"),\n quiet: true,\n // Progress goes to stderr: stdout is the URL and nothing else.\n onProgress: message => console.error(chalk.gray(` ${message}`))\n });\n\n const url = databaseUrlOf(prepared, readEnvFile(projectRoot));\n if (!url) {\n console.error(chalk.red(\" ✗ This project has no database URL to print.\"));\n console.error(chalk.gray(\" Set DATABASE_URL in .env, or run `rebase dev` to start the managed one.\"));\n process.exit(1);\n }\n\n console.log(url);\n}\n\n/**\n * `rebase db stop` and `rebase db reset`, for the managed database only.\n *\n * `reset` deletes the data directory rather than dropping schemas: \"give me an\n * empty database\" is the only thing anyone means by it, and doing it by\n * removing the directory cannot leave a half-dropped schema behind.\n */\nasync function manageLocalDatabase(\n subcommand: \"stop\" | \"reset\",\n projectRoot: string,\n rawArgs: readonly string[]\n): Promise<void> {\n const { resetManagedDatabase, stopManagedDatabase, stoppedManagedDatabaseLines, findRunningDaemon } = await import(\"../dev-db/daemon\");\n const { dataDir } = await import(\"../dev-db/state\");\n\n // What \"nothing here\" means, in the words of the project it is said to.\n //\n // \"No development database was running\" / \"No development database to\n // reset\" is true of the managed one and reads as being about the reader's\n // own Postgres — which these commands do not touch and could not stop.\n // On a project that named its own database, the sentence they need is that\n // it was not what this command was about.\n const nothingHere = (): string => {\n const kind = devDatabaseKind(projectRoot);\n const verb = subcommand === \"stop\" ? \"was not running\" : \"does not exist\";\n if (kind === \"docker\") {\n // The compose `db` service: the project names no DATABASE_URL for it.\n return ` The managed development database (PGlite) ${verb}; `\n + \"this project is on Postgres in Docker, which is untouched.\"\n + (subcommand === \"stop\" ? \" `docker compose stop db` stops it.\" : \"\");\n }\n if (kind === \"external\") {\n return ` The managed development database (PGlite) ${verb}; `\n + \"this project uses its own DATABASE_URL, which is untouched.\";\n }\n\n return subcommand === \"stop\"\n ? \" The managed development database (PGlite) was not running.\"\n : \" There is no managed development database (PGlite) to reset.\";\n };\n\n if (subcommand === \"stop\") {\n if (!(await stopManagedDatabase(projectRoot))) {\n console.log(chalk.gray(nothingHere()));\n\n return;\n }\n // \"`rebase dev` will start it again\" was not true of a dev that is\n // running: see `stoppedManagedDatabaseLines`.\n const [headline, ...detail] = stoppedManagedDatabaseLines(projectRoot);\n console.log(chalk.green(headline));\n for (const line of detail) console.log(chalk.gray(line));\n\n return;\n }\n\n const running = await findRunningDaemon(projectRoot);\n const hasData = fs.existsSync(dataDir(projectRoot));\n if (!running && !hasData) {\n console.log(chalk.gray(nothingHere()));\n\n return;\n }\n\n // Destructive, and the data is not backed up anywhere: it only ever existed\n // on this machine. So it asks, unless the caller has said not to — and\n // without a TTY there is nobody to ask, which is a refusal rather than an\n // assumption.\n if (!rawArgs.includes(\"--yes\") && !rawArgs.includes(\"-y\")) {\n if (!process.stdin.isTTY) {\n console.error(chalk.red(\"✗ `rebase db reset` deletes the local database and cannot prompt here.\"));\n console.error(chalk.yellow(\" Re-run with --yes if that is what you intend.\"));\n process.exit(1);\n }\n\n const { confirmed } = await inquirer.prompt([{\n type: \"confirm\",\n name: \"confirmed\",\n message: `Delete the development database at ${dataDir(projectRoot)}? This cannot be undone.`,\n default: false\n }]);\n if (!confirmed) {\n console.log(chalk.gray(\" Left alone.\"));\n\n return;\n }\n }\n\n await resetManagedDatabase(projectRoot);\n console.log(chalk.green(\"✓ Development database deleted. `rebase dev` will create a fresh one.\"));\n}\n\n/**\n * `rebase db pull --from <url>` — copy another database's contents into local\n * development.\n *\n * Deliberately one-directional. There is no flag that makes this push, because\n * a tool that can copy in both directions eventually copies in the wrong one,\n * and the wrong one here means overwriting production with a laptop.\n */\nasync function pullIntoLocal(projectRoot: string, rawArgs: readonly string[]): Promise<void> {\n const { describeRestoreFailure, describeTarget, dumpSource, findPgTool, restoreCopy } =\n await import(\"../dev-db/pull\");\n const { prepareDatabaseEnv } = await import(\"../dev-db/prepare\");\n const { readEnvFile } = await import(\"../utils/project\");\n\n const source = readFlagValue(rawArgs, \"--from\");\n if (!source) {\n console.error(chalk.red(\"✗ `rebase db pull` needs a source: --from <connection-string>\"));\n console.error(chalk.gray(\" Example: rebase db pull --from \\\"$PRODUCTION_DATABASE_URL\\\"\"));\n process.exit(1);\n }\n\n const schemas = rawArgs.flatMap((arg, index) =>\n arg === \"--schema\" && rawArgs[index + 1] ? [rawArgs[index + 1]] : []);\n const anonymize = rawArgs.includes(\"--anonymize\");\n\n // Both checked before anything destructive: discovering either is missing\n // after dropping the local database would be the worst possible ordering.\n for (const tool of [\"pg_dump\", \"pg_restore\"] as const) {\n if (!await findPgTool(tool)) {\n console.error(chalk.red(`✗ \\`${tool}\\` is not on PATH, and this command cannot run without it.`));\n console.error(chalk.gray(\" Install the PostgreSQL client tools, e.g. `brew install libpq`.\"));\n process.exit(1);\n }\n }\n\n // `--database-url` is refused rather than honoured, and refused rather than\n // ignored — which is what it was.\n //\n // Ignored is the dangerous one. The flag was accepted, dropped on the floor,\n // and the pull went ahead against the `.env` database: someone writing\n // `rebase db pull --from prod --database-url scratch --yes` destroyed their\n // working database while naming a different one. A flag that changes nothing\n // is a bug; a destructive flag that changes nothing is a data-loss bug.\n //\n // Honoured is the other tempting answer, and it breaks the one guarantee\n // this command makes. The target is always the local development database\n // *by construction* — there is no `--to`, and no flag that reverses the\n // direction — because a tool that can copy both ways eventually copies the\n // wrong way, and the wrong way here is a laptop over production.\n // `--database-url prod` is exactly that instruction written as a target.\n //\n // `--docker` is a different question and is passed through: it says how to\n // get a local database, not which database to overwrite.\n const targetFlag = readFlagValue(rawArgs, \"--database-url\");\n if (targetFlag !== null) {\n console.error(chalk.red(\"✗ `rebase db pull` does not take --database-url.\"));\n console.error(\"\");\n console.error(chalk.gray(\" The target is always this project's local development database. There is\"));\n console.error(chalk.gray(\" no flag that makes this write somewhere else, deliberately: a command that\"));\n console.error(chalk.gray(\" can copy in both directions eventually copies in the wrong one.\"));\n console.error(\"\");\n console.error(chalk.gray(` To read from another database, that is ${chalk.cyan(\"--from\")}:`));\n console.error(chalk.gray(` rebase db pull --from ${targetFlag}`));\n process.exit(1);\n }\n\n const prepared = await prepareDatabaseEnv(projectRoot, {\n flagDocker: rawArgs.includes(\"--docker\"),\n onProgress: (message) => console.log(chalk.gray(` ${message}`))\n });\n // The database `rebase db url` prints, resolved the one way — see\n // `databaseUrlOf`. Reading only `prepared.env` missed the commonest\n // configuration there is: `DATABASE_URL` in `.env` and nowhere else.\n const target = databaseUrlOf(prepared, readEnvFile(projectRoot)) ?? \"\";\n if (!target) {\n console.error(chalk.red(\"✗ No local database to pull into.\"));\n console.error(chalk.gray(\" Set DATABASE_URL in .env, or run `rebase dev` to start the managed one.\"));\n process.exit(1);\n }\n\n const plan = { source, target, anonymize, schemas };\n\n // Said in full, before anything happens. The target is destroyed, and where\n // the data comes to rest on disk is the part people forget.\n console.log(\"\");\n console.log(chalk.bold(\" This will replace your local database.\"));\n console.log(` ${chalk.gray(\"From\")} ${describeTarget(source)}`);\n console.log(` ${chalk.gray(\"Into\")} ${describeTarget(target)}${prepared.dataDir ? chalk.gray(` (${prepared.dataDir})`) : \"\"}`);\n console.log(` ${chalk.gray(\"Data\")} ${anonymize\n ? \"personal-looking columns will be overwritten after the copy\"\n : chalk.yellow(\"copied as-is, including any personal data\")}`);\n if (schemas.length > 0) console.log(` ${chalk.gray(\"Schemas\")} ${schemas.join(\", \")}`);\n console.log(\"\");\n\n if (!rawArgs.includes(\"--yes\") && !rawArgs.includes(\"-y\")) {\n if (!process.stdin.isTTY) {\n console.error(chalk.red(\"✗ This replaces the local database and cannot prompt here.\"));\n console.error(chalk.yellow(\" Re-run with --yes if that is what you intend.\"));\n process.exit(1);\n }\n const { confirmed } = await inquirer.prompt([{\n type: \"confirm\", name: \"confirmed\", message: \"Continue?\", default: false\n }]);\n if (!confirmed) {\n console.log(chalk.gray(\" Nothing was changed.\"));\n\n return;\n }\n }\n\n const dumpFile = path.join(os.tmpdir(), `rebase-pull-${process.pid}.dump`);\n console.log(chalk.gray(\" Dumping…\"));\n // In the form the local database can restore: the managed one takes the\n // rows as INSERTs, because PGlite cannot receive COPY data. A source it\n // cannot reach is said here, in the banner, before anything is emptied.\n const dumped = await dumpSource(plan, dumpFile);\n if (!dumped.ok) {\n for (const line of dumped.lines) console.error(line.startsWith(\"✗\") ? chalk.red(line) : line);\n process.exit(1);\n }\n\n /** What failed, the state the local database is left in, and what to do — see `describeRestoreFailure`. */\n let failure: string[] | null = null;\n let anonymizeFailure: string[] | null = null;\n try {\n console.log(chalk.gray(\" Restoring…\"));\n // Empties the local schemas the copy replaces, then restores into\n // them; `pg_restore --clean` alone left anything local the source\n // lacks in the way. A failure is reported only after whatever did\n // arrive has been anonymized.\n const restored = await restoreCopy(dumped.plan, dumpFile);\n failure = restored.failure ? describeRestoreFailure(restored, describeTarget(source)) : null;\n\n // Before the verdict: a partial copy of personal data on a laptop is\n // still personal data on a laptop.\n if (anonymize && restored.started) {\n anonymizeFailure = await anonymizeTarget(target, describeTarget(source), prepared.database.kind);\n }\n\n // Whatever arrived, whole or partial, anonymized or emptied: pg_dump\n // stripped its grants either way, and a pull that failed is pulled\n // again into a database that should still be readable meanwhile.\n if (restored.started) await restoreAppRole(target);\n } finally {\n fs.rmSync(dumpFile, { force: true });\n }\n\n if (anonymizeFailure) {\n for (const line of anonymizeFailure) console.error(line);\n if (failure) console.error(chalk.red(`✗ ${failure[0]}`));\n process.exit(1);\n }\n\n if (failure) {\n const [what, state, ...advice] = failure;\n console.error(chalk.red(`✗ ${what}`));\n console.error(chalk.yellow(` ${state}`));\n for (const line of advice) console.error(chalk.gray(` ${line}`));\n process.exit(1);\n }\n\n console.log(chalk.green(\"✓ Local database now holds a copy of \" + describeTarget(source)));\n}\n\n/**\n * Give the restored copy back the privileges `pg_dump` stripped.\n *\n * A pull without this ends on a green tick and hands over a database the\n * application cannot read: `--no-privileges` removes every GRANT, so the copy\n * has the source's RLS policies and none of the grants behind them, and the\n * first query as `rebase_user` fails with `permission denied`. Measured — 68\n * policies and 60 grants in, 68 policies and 0 grants out.\n *\n * `ensureAppRole` is the routine boot runs and `rebase db push` runs, so the\n * pulled database ends up in the state a booted one is in, and there is no\n * second description of these grants to drift. `detectConnectionPosture` gates\n * it the same way `db push` does: a connection that cannot create roles reports\n * that rather than failing the pull, which has already succeeded by this point.\n *\n * Failure here is a warning, not an error. The data is restored and correct; a\n * missing grant is repaired by the next `rebase dev` or `rebase db push`, and\n * saying so beats unwinding a copy that is fine.\n */\nasync function restoreAppRole(target: string): Promise<void> {\n const { Client } = await import(\"pg\");\n const { provisionableSchemas } = await import(\"../dev-db/pull\");\n\n const client = new Client({ connectionString: target });\n client.on(\"error\", () => undefined);\n try {\n // Inside the `try`: a refused connection is the same warning as a\n // refused grant, not an exception past the pull's own verdict. And\n // before the driver is loaded, which there is no point in doing for a\n // database that cannot be reached.\n await client.connect();\n const { detectConnectionPosture, ensureAppRole, REBASE_USER_ROLE } =\n await import(\"@rebasepro/server-postgres\");\n const runSql = async (text: string) => (await client.query(text)).rows as Record<string, unknown>[];\n const posture = await detectConnectionPosture(runSql);\n if (!posture.privileged) {\n console.log(chalk.yellow(\n ` ⚠ Could not re-grant the \"${REBASE_USER_ROLE}\" role — this connection may not create roles.`\n ));\n console.log(chalk.gray(\" The copy has its RLS policies but no privileges behind them;\"));\n console.log(chalk.gray(\" `rebase dev` or `rebase db push` will provision them.\"));\n\n return;\n }\n\n const { rows } = await client.query<{ schema: string }>(\n \"SELECT nspname AS \\\"schema\\\" FROM pg_namespace\"\n );\n const schemas = provisionableSchemas(rows);\n await ensureAppRole(runSql, schemas);\n console.log(chalk.gray(\n ` ✓ Re-granted \"${REBASE_USER_ROLE}\" on ${schemas.length} schema(s) — pg_dump strips privileges.`\n ));\n } catch (error) {\n console.log(chalk.yellow(\n ` ⚠ Restored, but could not re-grant \"rebase_user\": ${error instanceof Error ? error.message : String(error)}`\n ));\n console.log(chalk.gray(\" Run `rebase db push` (or start `rebase dev`) to provision it.\"));\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/**\n * Anonymize the restored copy, and say what happened if that did not work.\n *\n * Returns null when the copy is anonymized, and otherwise the lines that say —\n * in red, because `--anonymize` was the developer saying this data must not\n * arrive as it is — what state the local database is in now: emptied of what\n * could not be anonymized, or, when even that failed, holding real data that\n * has to be deleted before anything else.\n */\nasync function anonymizeTarget(\n target: string,\n source: string,\n kind: DevDatabase[\"kind\"]\n): Promise<string[] | null> {\n const { Client } = await import(\"pg\");\n const { anonymizeCopy } = await import(\"../dev-db/pull\");\n\n const deleteIt = kind === \"managed\"\n ? `Delete it now: ${chalk.cyan(\"rebase db reset --yes\")}`\n : kind === \"docker\"\n ? `Delete it now: ${chalk.cyan(\"docker compose down -v\")}`\n : \"Delete it now: drop the restored tables, or the database, before anything else reads it.\";\n const holdsRealData = (reason: string): string[] => [\n chalk.red(`✗ The copy could not be anonymized: ${reason}`),\n chalk.red.bold(` The local database holds an UN-ANONYMIZED copy of ${source}, personal data included.`),\n chalk.yellow(` ${deleteIt}`)\n ];\n\n const client = new Client({ connectionString: target });\n client.on(\"error\", () => undefined);\n try {\n await client.connect();\n } catch (error) {\n return holdsRealData(error instanceof Error ? error.message : String(error));\n }\n\n try {\n const outcome = await anonymizeCopy(client);\n if (outcome.ok) {\n console.log(chalk.green(` ✓ Anonymized ${outcome.tables.length} table(s).`));\n console.log(chalk.gray(\" Name-based and best-effort: a free-text column may still hold personal data.\"));\n\n return null;\n }\n if (outcome.emptyError !== null) {\n return [...holdsRealData(outcome.error), chalk.red(` Emptying the affected tables failed too: ${outcome.emptyError}`)];\n }\n\n return [\n chalk.red(`✗ The copy could not be anonymized: ${outcome.error}`),\n chalk.yellow(\" Nothing was anonymized — the pass is one transaction — so the tables it would have\"),\n chalk.yellow(\" rewritten were emptied instead, with every row that references them:\"),\n ...(outcome.emptied.length > 0 ? [chalk.gray(` ${outcome.emptied.join(\", \")}`)] : []),\n chalk.gray(` The rest of the copy of ${source} is in place. Fix that error and pull again.`)\n ];\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/**\n * Start the compose database a `db … --docker` was asked to talk to.\n *\n * `--docker` resolved the compose URL and stopped there, so every `db`\n * subcommand carrying it reached a container nobody had started —\n * `ECONNREFUSED 127.0.0.1:5436`, two lines, no diagnosis — including the\n * commands the managed-database refusals send readers to `--docker` for.\n *\n * `rebase dev --docker`'s preflight, called with the compose URL and nothing\n * to push: this is not a schema step, and `rebase db push --docker` is the\n * push. A failure here is reported and not fatal — the command runs and its\n * own connection error follows, which is the same contract `dev` keeps.\n */\nexport async function ensureDockerDatabase(projectRoot: string, rawArgs: readonly string[]): Promise<void> {\n const { ensureDevDatabase } = await import(\"../utils/dev-preflight\");\n const { resolveProjectDatabase } = await import(\"../dev-db/prepare\");\n\n // `--docker` on this command line, or on the last `rebase dev`: a command\n // that follows the remembered choice reaches the same container, so it has\n // to be up for the same reason. Only when that choice is the one that wins —\n // a DATABASE_URL anywhere outranks it, typed flag or not, and then there is\n // nothing to start: `prepareDatabaseEnv` says the flag was ignored.\n const resolved = resolveProjectDatabase(projectRoot, {\n flagUrl: readFlagValue(rawArgs, \"--database-url\"),\n flagDocker: rawArgs.includes(\"--docker\")\n });\n if (resolved.kind !== \"docker\") return;\n\n const composeUrl = resolved.url;\n if (!composeUrl) {\n // `prepareDatabaseEnv` raises the full message a moment later; saying\n // it twice would be worse than saying it once, in its own words.\n return;\n }\n\n await ensureDevDatabase({\n projectRoot,\n databaseUrl: composeUrl,\n disabled: false,\n // Never a push. `rebase db push --docker` is one, and it runs next.\n hasCollections: false,\n pushSchema: async () => undefined,\n log: message => console.log(message)\n });\n}\n\n/**\n * You cannot delete the branch you are standing on.\n *\n * Not a new rule — it was always refused, by a message about a database the\n * developer had never named. After `switch feature_x` the resolved DSN *is*\n * `rb_feature_x`, so `BranchService.deleteBranch` compared it against the\n * connected database, found them equal, and answered `✗ Cannot delete the main\n * database.` The main database is precisely what the developer was not on.\n *\n * Answered here because the pointer is the CLI's: the driver runs as a child\n * process that has never heard of it, and cannot tell \"the branch you are on\"\n * from \"the main database\" — those are the same connection string to it.\n */\nasync function refuseDeletingActiveBranch(projectRoot: string, rawArgs: readonly string[]): Promise<void> {\n const [, , , name] = commandWords(rawArgs, \"db\");\n if (!name) return;\n\n const { readActiveBranch } = await import(\"../dev-db/branch-pointer\");\n const active = readActiveBranch(projectRoot);\n if (active?.name !== name) return;\n\n const off = \"rebase db branch switch --off\";\n const del = `rebase db branch delete ${name}`;\n const column = Math.max(off.length, del.length) + 4;\n\n console.error(\"\");\n console.error(chalk.red(`✗ You are on branch \"${name}\" — leave it before deleting it.`));\n console.error(\"\");\n console.error(chalk.gray(` Every database command in this checkout is pointed at ${active.database},`));\n console.error(chalk.gray(\" including this one, so the delete would be asking that database to drop\"));\n console.error(chalk.gray(\" itself.\"));\n console.error(\"\");\n console.error(` ${chalk.cyan(off)}${\" \".repeat(column - off.length)}back to the main database`);\n console.error(` ${chalk.cyan(del)}${\" \".repeat(column - del.length)}then this works`);\n console.error(\"\");\n process.exit(1);\n}\n\n/** The `branch` actions that read or write the registry — every one but `switch`. */\nconst REGISTRY_ACTIONS = new Set([\"list\", \"create\", \"delete\", \"info\", \"prune\"]);\n\n/**\n * Every `branch` action runs against the parent, where the registry lives.\n *\n * `rebase.branches` is written in the database branches are made *from*, and a\n * branch is a `CREATE DATABASE … TEMPLATE` copy — so the copy carries a\n * snapshot of that table taken at branch time, and every branch made since is\n * missing from it. After `switch feature_x`, `branch list` connected to\n * `rb_feature_x` and answered `No branches found. Create one with: rebase db\n * branch create <name>` while `branch switch` with no argument, one command\n * earlier, had said `● On branch feature_x`.\n *\n * The same snapshot answered `create`, `delete`, `info` and `prune`: a branch\n * created from a switched checkout was recorded only in the copy, so `list`\n * never showed it and `delete` from the main checkout said \"not found\" while\n * its database stayed; `info` and `delete` could not find a branch made after\n * the one this checkout is on. The Branches pane in Studio was fixed the same\n * way (`REBASE_BRANCH_PARENT_DATABASE`).\n *\n * `create` still copies what this checkout is on — a branch of the branch, a\n * thing the developer asked for by switching first — so it is given\n * `--from <the branch's database>` unless it names a source itself.\n *\n * Resolved with `branch: null` — the same rule `switch` uses to find what to\n * branch *from* — and relayed as `--database-url`, which the driver honours\n * over anything it would resolve for itself.\n */\nasync function onParentDatabase(projectRoot: string, rawArgs: string[], action: string): Promise<string[]> {\n // An explicit `--database-url` is the developer naming the database; this\n // never overrides one.\n if (readFlagValue(rawArgs, \"--database-url\") !== null) return rawArgs;\n\n const { readActiveBranch } = await import(\"../dev-db/branch-pointer\");\n const active = readActiveBranch(projectRoot);\n if (!active) return rawArgs;\n\n const { readEnvFile } = await import(\"../utils/project\");\n const { resolveDevDatabase } = await import(\"../dev-db/resolve\");\n const { resolveComposeUrl } = await import(\"../dev-db/prepare\");\n\n const { readLastDevDocker } = await import(\"../dev-db/last-dev-database\");\n\n const envFile = readEnvFile(projectRoot);\n const parent = resolveDevDatabase({\n flagDocker: rawArgs.includes(\"--docker\"),\n lastDevDocker: readLastDevDocker(projectRoot),\n env: process.env,\n envFile,\n branch: null,\n composeUrl: resolveComposeUrl(projectRoot, envFile)\n });\n const url = (parent.kind === \"managed\" ? null : parent.url)?.trim();\n if (!url) return rawArgs;\n\n console.log(chalk.gray(` ● On branch ${active.name} — using the main database, where the branch registry lives.`));\n\n const from = action === \"create\" && readFlagValue(rawArgs, \"--from\") === null\n ? [\"--from\", active.database]\n : [];\n\n return [...rawArgs, ...from, \"--database-url\", url];\n}\n\n/**\n * The flags `rebase db branch switch` takes, the relayed database flags and\n * `--debug` included.\n */\nconst SWITCH_FLAGS = [\"--off\", \"--main\", \"--database-url\", \"--docker\", \"--debug\"] as const;\n\n/**\n * Refuse a flag `switch` does not take, naming the one it was probably meant to be.\n *\n * `switch` is answered here, never by the driver, so the driver's strict\n * branch flags do not reach it: `rebase db branch switch --of` reported the\n * current branch, exit 0, instead of leaving it.\n */\nexport function assertSwitchFlags(rawArgs: readonly string[]): void {\n for (const word of rawArgs.slice(2)) {\n if (!word.startsWith(\"-\")) continue;\n const flag = word.split(\"=\")[0];\n if ((SWITCH_FLAGS as readonly string[]).includes(flag)) continue;\n const near = suggestCommand(flag.replace(/^-+/, \"\"), SWITCH_FLAGS.map(known => known.slice(2)));\n throw new UsageError(\n `\\`rebase db branch switch\\` has no option ${flag}` +\n (near ? ` — did you mean --${near}?` : \" — it takes --off (or --main) and a branch name.\") +\n \" Nothing was changed.\"\n );\n }\n}\n\n/**\n * `rebase db branch switch <name>` — point this checkout at a branch.\n *\n * The step branching was missing. `create` copied the database in about a\n * second and then printed `Database: rb_feature_auth` and stopped: there was no\n * `switch`, no `--branch` on `rebase dev`, and no `REBASE_BRANCH`. The only way\n * to use a branch was to hand-edit `DATABASE_URL`, while the documentation said\n * \"the CLI updates your local development configuration\" — it did not, and the\n * `.env` was byte-identical afterwards.\n *\n * Three things it insists on:\n *\n * - **The branch has to exist.** Writing a pointer to a database that was never\n * created turns a typo into a connection error on the *next* command, which\n * is the one place it cannot be explained. Checked against\n * `rebase.branches` and `pg_database` both, because a branch dropped outside\n * Rebase leaves the metadata row behind.\n *\n * - **It says what changed, and how to undo it.** A command that silently\n * redirects every subsequent database operation owes the reader the database\n * name it moved to and the words that move it back.\n *\n * - **It never edits `.env`.** See `branch-pointer.ts`.\n */\nasync function switchBranch(projectRoot: string, rawArgs: readonly string[]): Promise<void> {\n assertSwitchFlags(rawArgs);\n\n const { branchDatabaseName, clearActiveBranch, databaseNameOf, readActiveBranch, writeActiveBranch } =\n await import(\"../dev-db/branch-pointer\");\n const { readEnvFile } = await import(\"../utils/project\");\n const { resolveDevDatabase } = await import(\"../dev-db/resolve\");\n const { resolveComposeUrl } = await import(\"../dev-db/prepare\");\n const { readLastDevDocker } = await import(\"../dev-db/last-dev-database\");\n\n // Read as a flag rather than as the name in the third position, so\n // `switch --off` and `switch feature --off` mean the same thing. The doc\n // verifier reads a command's flags out of exactly this shape, which is the\n // other reason: a flag it cannot see is one it reports as unrunnable in\n // every page that documents it.\n const goingOff = rawArgs.includes(\"--off\") || rawArgs.includes(\"--main\");\n\n // [\"db\", \"branch\", \"switch\", <name>], with any flags taken back out —\n // `rebase --debug db branch switch feature` read the name as \"switch\".\n const name = commandWords(rawArgs, \"db\")[3];\n\n // The database to branch from, resolved by the ordered rule every sibling\n // uses. This read `readEnvFile(projectRoot).DATABASE_URL` and nothing else,\n // so `export DATABASE_URL=…; rebase db branch create x` created a branch and\n // `rebase db branch switch x` then answered \"This project has no\n // DATABASE_URL, so there is no database to branch from\" — about a project\n // that had one, in the shell, where `branching.md` documents it as rule (2)\n // and `create` had just read it.\n //\n // `branch: null`, deliberately: this command is what sets the pointer, and\n // the pointer that exists must never become the base of the next switch —\n // that is how a branch of a branch of a branch happens by accident.\n const envFile = readEnvFile(projectRoot);\n const resolved = resolveDevDatabase({\n flagUrl: readFlagValue(rawArgs, \"--database-url\"),\n flagDocker: rawArgs.includes(\"--docker\"),\n lastDevDocker: readLastDevDocker(projectRoot),\n env: process.env,\n envFile,\n branch: null,\n composeUrl: resolveComposeUrl(projectRoot, envFile)\n });\n const base = (resolved.kind === \"managed\" ? null : resolved.url)?.trim() || undefined;\n\n // `switch` with no argument reports rather than changes. \"Which branch am I\n // on\" is asked far more often than \"move me\", and answering it should not\n // require guessing a flag.\n if (!name && !goingOff) {\n const active = readActiveBranch(projectRoot);\n console.log(\"\");\n if (active) {\n console.log(` ${chalk.green(\"●\")} On branch ${chalk.bold(active.name)} ${chalk.gray(`(${active.database})`)}`);\n console.log(chalk.gray(` Back to the main database: ${chalk.cyan(\"rebase db branch switch --off\")}`));\n } else {\n const main = base ? databaseNameOf(base) : null;\n console.log(` ${chalk.gray(\"●\")} On the main database${main ? chalk.gray(` (${main})`) : \"\"}`);\n console.log(chalk.gray(` Switch to a branch: ${chalk.cyan(\"rebase db branch switch <name>\")}`));\n }\n console.log(\"\");\n\n return;\n }\n\n if (goingOff) {\n const active = readActiveBranch(projectRoot);\n clearActiveBranch(projectRoot);\n console.log(\"\");\n console.log(active\n ? chalk.green(` ✓ Back on the main database${base ? ` (${databaseNameOf(base)})` : \"\"}.`)\n : chalk.gray(\" Already on the main database.\"));\n console.log(\"\");\n\n return;\n }\n\n if (!base) {\n console.error(chalk.red(\"✗ There is no database to branch from.\"));\n console.error(chalk.gray(resolved.kind === \"managed\"\n ? \" This project is on the managed development database, which serves exactly one —\"\n : \" --docker needs a docker-compose.yml with a db service, and this project has none —\"));\n console.error(chalk.gray(\" and branching copies a database. Set DATABASE_URL in .env or in your\"));\n console.error(chalk.gray(\" shell, or run `rebase dev --docker`.\"));\n process.exit(1);\n }\n\n const database = branchDatabaseName(name);\n\n // Verified before the pointer is written, not after.\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: base });\n try {\n await client.connect();\n } catch (error) {\n console.error(chalk.red(`✗ Could not reach the database to check that branch \"${name}\" exists.`));\n console.error(chalk.gray(` ${error instanceof Error ? error.message : String(error)}`));\n process.exit(1);\n }\n try {\n const { rows } = await client.query<{ registered: boolean; present: boolean }>(\n `SELECT EXISTS (SELECT 1 FROM rebase.branches WHERE name = $1) AS registered,\n EXISTS (SELECT 1 FROM pg_database WHERE datname = $2) AS present`,\n [name, database]\n ).catch(() => ({ rows: [{ registered: false, present: false }] }));\n\n const { registered, present } = rows[0] ?? { registered: false, present: false };\n if (!present) {\n console.error(chalk.red(`✗ Branch \"${name}\" does not exist.`));\n console.error(registered\n // The metadata row outlives a database dropped with plain SQL.\n ? chalk.gray(` It is registered but its database (${database}) is gone — someone dropped it outside Rebase.`)\n : chalk.gray(` ${chalk.cyan(\"rebase db branch list\")} shows the ones that do.`));\n process.exit(1);\n }\n } finally {\n await client.end();\n }\n\n writeActiveBranch(projectRoot, { name, database });\n\n console.log(\"\");\n console.log(chalk.green(` ✓ Switched to branch \"${name}\".`));\n console.log(chalk.gray(` Database: ${database}`));\n console.log(chalk.gray(\" Every rebase command in this checkout now uses it — dev, db push, migrate.\"));\n console.log(chalk.gray(` Back to the main database: ${chalk.cyan(\"rebase db branch switch --off\")}`));\n console.log(\"\");\n}\n\n/**\n * What each `rebase db <action>` does and takes.\n *\n * Kept here rather than delegated to the driver because the driver is reached\n * by *running* it — which is exactly what `--help` must not do. The page is\n * deliberately short: the authority on a flag is the command's own spec, and\n * `check-doc-commands.mjs` holds every command written in this repository's\n * markdown to it. What a reader needs from here is which subcommands exist and\n * what the destructive ones want before they will run.\n */\n/** The database flags every driver command takes; `db url --help` has its own wording. */\nconst DATABASE_FLAGS_HELP =\n \"--database-url <url> names the database; --docker uses the compose one, starting it if needed.\";\n\nconst DB_ACTION_HELP: Record<string, { usage: string; summary: string; notes?: string[] }> = {\n push: {\n usage: \"rebase db push [--collections <dir>] [--dry-run] [--allow-destructive] [--yes]\",\n summary: \"Apply the schema straight to the database. Development only — it does not write a migration.\",\n notes: [\n \"--dry-run prints the SQL and applies nothing. Read it before you approve it.\",\n \"A change that drops data, or re-keys a table (every row gets a new id), needs --allow-destructive.\",\n `--collections <dir>: ${COLLECTIONS_FLAG_HELP}.`,\n DATABASE_FLAGS_HELP\n ]\n },\n generate: {\n usage: \"rebase db generate [--collections <dir>]\",\n summary: \"Generate the Drizzle schema, the Postgres DDL and a SQL migration file from the collections.\",\n notes: [\n \"A migration that drops or narrows data is named when it is written. It is still written.\",\n `--collections <dir>: ${COLLECTIONS_FLAG_HELP}.`,\n DATABASE_FLAGS_HELP\n ]\n },\n migrate: {\n usage: \"rebase db migrate [--baseline <version>] [--refuse-destructive] [amount]\",\n summary: \"Run the pending migration files against the database.\",\n notes: [\n \"--refuse-destructive dry-runs the pending files and applies nothing when one drops or narrows data.\",\n \"--baseline <version> records that version as already applied and starts from the next one.\",\n \"It is what a database Rebase has already booted against needs: boot ensures the schema, so the first migration would try to create tables that are already there.\",\n \"The version is the numeric prefix of a file in drizzle/migrations.\",\n DATABASE_FLAGS_HELP\n ]\n },\n branch: {\n // Every action the dispatch answers and every flag its specs declare.\n // The page is kept here rather than delegated because reaching the\n // driver's own `printBranchHelp` means *running* the driver, which is\n // what `--help` must not do — so `help-coverage.test.ts` holds the two\n // to each other instead. It went two releases without learning `prune`,\n // `--from`, `--force` or `--older-than`, all four of which the dispatch\n // answers and the docs teach.\n usage: \"rebase db branch <create|list|switch|delete|info|prune> [name]\",\n summary: \"Database branching.\",\n notes: [\n \"create <name> [--from <source>] copies an existing database, files and all.\",\n \"switch <name> points this checkout at a branch; every later command uses it.\",\n \"switch with no name reports where you are; switch --off returns to the main database.\",\n \"prune [--older-than <14|14d|2w>] removes branches nothing is using, and the entries that drifted.\",\n \"prune --include-dev-diff also removes the Atlas scratch databases `db push` leaves behind.\",\n \"prune asks before it drops anything; --yes, -y answers for you, which is the form a CI job wants.\",\n \"--force disconnects other sessions first — Postgres refuses to copy or drop a database anything is connected to, usually your own `rebase dev`.\"\n ]\n },\n backup: {\n usage: \"rebase db backup [--out <path|s3://…>]\",\n summary: \"Create a pg_dump backup. --out is resolved against the directory you are standing in.\",\n notes: [\n \"--output is accepted as an alias, as it is on `rebase build`.\",\n \"`rebase db backup list` lists them, the way `rebase cloud db backup list` does.\"\n ]\n },\n backups: {\n usage: \"rebase db backups list [--out <path|s3://…>]\",\n summary: \"List stored backups.\",\n notes: [\"`rebase db backup list` is the same command, spelled the cloud family's way.\"]\n },\n url: {\n usage: \"rebase db url [--database-url <url>] [--docker]\",\n summary: \"Print the connection string this project uses. Nothing else goes to stdout, so it pipes.\",\n notes: [\n \"psql \\\"$(rebase db url)\\\"\",\n \"Starts the managed database if it is not already running.\",\n \"--database-url and --docker answer for the database `rebase dev` would pick with the same flag.\",\n \"After `rebase dev --docker` it prints the Docker database without the flag, as every db command does.\"\n ]\n },\n restore: {\n usage: \"rebase db restore <dump> [--target-db <name>] [--create-db] [--clean] [--yes]\",\n summary: \"Restore a backup with pg_restore.\",\n notes: [\n \"Destructive: on a terminal it asks first, and with no terminal it refuses without --yes.\",\n \"Into a database that already holds what the backup creates, it needs --clean, and changes nothing without it.\"\n ]\n },\n pull: {\n usage: \"rebase db pull --from <url> [--schema <name>] [--anonymize] [--yes]\",\n summary: \"Copy another database into local development. One-directional by design — it can never push.\",\n notes: [\"The target is not selectable: --database-url is refused, so this can never write to a remote database.\"]\n },\n stop: { usage: \"rebase db stop\", summary: \"Stop the managed development database. Data is kept.\" },\n reset: {\n usage: \"rebase db reset [--yes]\",\n summary: \"Delete the managed development database and start over.\",\n notes: [\"Destructive, and the data exists only on this machine.\"]\n }\n};\n\n/** Every subcommand the family dispatches — the help table's keys. */\nexport const DB_SUBCOMMANDS = Object.keys(DB_ACTION_HELP);\n\nfunction printDbHelp(action?: string) {\n const entry = action ? DB_ACTION_HELP[action] : undefined;\n if (entry) {\n console.log(`\n${chalk.bold(`rebase db ${action}`)}\n\n ${entry.summary}\n\n${chalk.green.bold(\"Usage\")}\n ${chalk.blue(entry.usage)}\n${entry.notes?.length ? `\\n${chalk.green.bold(\"Notes\")}\\n${entry.notes.map(n => ` ${chalk.gray(`• ${n}`)}`).join(\"\\n\")}\\n` : \"\"}\n${chalk.gray(\"Run `rebase db --help` for every subcommand.\")}\n`);\n return;\n }\n\n console.log(`\n${chalk.bold(\"rebase db\")} — Database management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase db ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"url\")} Print the connection string this project uses (pipes into psql)\n ${chalk.blue.bold(\"pull\")} Copy another database into local dev (--from <url>, --anonymize)\n ${chalk.blue.bold(\"stop\")} Stop the managed development database (data is kept)\n ${chalk.blue.bold(\"reset\")} Delete the managed development database and start over\n ${chalk.blue.bold(\"push\")} Apply schema directly to database (development)\n ${chalk.blue.bold(\"generate\")} Generate migration files\n ${chalk.blue.bold(\"migrate\")} Run pending migrations\n ${chalk.blue.bold(\"branch\")} Database branching (create, list, switch, delete, info, prune)\n ${chalk.blue.bold(\"backup\")} Create a backup with pg_dump (--out <path|s3://…>)\n ${chalk.blue.bold(\"restore\")} Restore a backup with pg_restore (destructive; asks, or --yes)\n ${chalk.blue.bold(\"backups\")} List stored backups (db backup list is the same)\n\n${chalk.green.bold(\"Examples\")}\n${dbExamples(devDatabaseKind())}\n ${chalk.gray(\"# Back up to a local directory, then to object storage\")}\n rebase db backup --out ./backups\n rebase db backup --out s3://my-private-bucket/backups\n\n ${chalk.gray(\"# Restore into a fresh database (safe: does not touch the live one)\")}\n rebase db restore ./backups/rebase-app-20260714T030000Z.dump --create-db --target-db app_restored\n`);\n}\n\n/**\n * The examples, which are not the same on the managed development database.\n *\n * Every one of the four the help used to lead with — `db push`, `db generate`,\n * `db migrate`, `db branch` — is refused there, by guards in this same file\n * that explain exactly why. So on the project the CLI had just scaffolded, the\n * first thing `rebase db --help` offered was a command that answers with a\n * refusal, and the reader's most likely conclusion is that their install is\n * broken.\n *\n * Exported for its test.\n */\nexport function dbExamples(kind: DevDatabase[\"kind\"] | null): string {\n if (kind === \"managed\") {\n return ` ${chalk.gray(\"# Quick development workflow (this project is on the managed database)\")}\n rebase schema generate\n rebase dev ${chalk.gray(\"# boot applies your collections to it, additively\")}\n rebase db push ${chalk.gray(\"# also drops, renames and narrows columns\")}\n\n ${chalk.gray(\"# branch needs a Postgres of your own\")}\n rebase dev --docker ${chalk.gray(\"# starts one; or uncomment DATABASE_URL in .env\")}\n\n`;\n }\n\n return ` ${chalk.gray(\"# Quick development workflow\")}\n rebase schema generate && rebase db push\n\n ${chalk.gray(\"# Production migration workflow\")}\n rebase db generate\n rebase db migrate\n\n ${chalk.gray(\"# Create a database branch and work on it\")}\n rebase db branch create feature_auth\n rebase db branch switch feature_auth\n rebase db branch switch --off\n\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,aAAa,SAA4B,SAA2B;CAChF,MAAM,QAAQ,QAAQ,MAAM,CAAC,CAAC,CAAC,QAAO,UAAS,CAAC,MAAM,WAAW,GAAG,CAAC;CACrE,MAAM,QAAQ,MAAM,QAAQ,OAAO;CACnC,OAAO,UAAU,KAAK,CAAC,IAAI,MAAM,MAAM,KAAK;AAChD;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,gBAAgB,SAA4B,SAA2B;CACnF,MAAM,OAAO,QAAQ,MAAM,CAAC;CAC5B,MAAM,QAAQ,KAAK,WAAU,UAAS,UAAU,OAAO;CACvD,IAAI,SAAS,GAAG,OAAO,CAAC,GAAG,IAAI;CAC/B,OAAO,CAAC,GAAG,KAAK,MAAM,KAAK,GAAG,GAAG,KAAK,MAAM,GAAG,KAAK,CAAC;AACzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACTA,SAAS,SAAS,OAAyB;CACvC,IAAI,EAAE,iBAAiB,QAAQ,OAAO;CACtC,MAAM,UAAU;CAChB,OAAO,OAAO,QAAQ,aAAa,YAAY,OAAO,QAAQ,WAAW;AAC7E;AAEA,SAAgB,mBAAmB,OAAsB;CACrD,IAAI,SAAS,KAAK,KAAK,EAAE,iBAAiB,QAAQ;CAKlD,MAAM,UAAU;CAChB,MAAM,UAAU,OAAO,QAAQ,oBAAoB,WAC7C,QAAQ,kBACR,MAAM;CACZ,IAAI,SAAS,QAAQ,MAAM,MAAM,IAAI,KAAK,SAAS,CAAC;AACxD;;;;;;;;;;;;;;;;;;;;;;ACjBA,SAAgB,cACZ,UACA,SACkB;CAIlB,MAAM,SAAS,UAAsC,SAAS,MAAM,KAAK,IAAI,QAAQ,KAAA;CAErF,OAAO,MAAM,SAAS,IAAI,YAAY,K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