@rebasepro/cli 0.23.0 → 0.24.1-canary.g19596ef

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 (186) hide show
  1. package/README.md +19 -3
  2. package/bin/rebase.js +4 -1
  3. package/dist/agent-setup-B31F00DC.js +324 -0
  4. package/dist/agent-setup-B31F00DC.js.map +1 -0
  5. package/dist/api-keys-Bl1I9q7M.js +525 -0
  6. package/dist/api-keys-Bl1I9q7M.js.map +1 -0
  7. package/dist/apps-CNgQJjg5.js +340 -0
  8. package/dist/apps-CNgQJjg5.js.map +1 -0
  9. package/dist/args-BnmsEXvu.js +109 -0
  10. package/dist/args-BnmsEXvu.js.map +1 -0
  11. package/dist/atlas-dev-database-D_LP_Woq.js +62 -0
  12. package/dist/atlas-dev-database-D_LP_Woq.js.map +1 -0
  13. package/dist/auth-aySHEF45.js +414 -0
  14. package/dist/auth-aySHEF45.js.map +1 -0
  15. package/dist/branch-pointer-DvSHBjjz.js +2 -0
  16. package/dist/build-DIHWIqO4.js +336 -0
  17. package/dist/build-DIHWIqO4.js.map +1 -0
  18. package/dist/bundle-CqURVN-K.js +1621 -0
  19. package/dist/bundle-CqURVN-K.js.map +1 -0
  20. package/dist/bundle.d.ts +12 -3
  21. package/dist/cli.d.ts +23 -2
  22. package/dist/cloud-DjByQlkW.js +9667 -0
  23. package/dist/cloud-DjByQlkW.js.map +1 -0
  24. package/dist/collection-drift-BKj_BoMq.js +106 -0
  25. package/dist/collection-drift-BKj_BoMq.js.map +1 -0
  26. package/dist/commands/__test_support__/parser-specs.d.ts +13 -0
  27. package/dist/commands/agent-setup.d.ts +116 -0
  28. package/dist/commands/api-keys.d.ts +86 -23
  29. package/dist/commands/apps.d.ts +17 -0
  30. package/dist/commands/auth.d.ts +7 -0
  31. package/dist/commands/build.d.ts +5 -1
  32. package/dist/commands/cloud/auth.d.ts +4 -3
  33. package/dist/commands/cloud/bundle-deploy.d.ts +45 -0
  34. package/dist/commands/cloud/context.d.ts +44 -5
  35. package/dist/commands/cloud/cron.d.ts +53 -0
  36. package/dist/commands/cloud/debug.d.ts +134 -0
  37. package/dist/commands/cloud/index.d.ts +89 -12
  38. package/dist/commands/cloud/token-capabilities.d.ts +76 -0
  39. package/dist/commands/cloud/tokens.d.ts +23 -0
  40. package/dist/commands/console.d.ts +12 -0
  41. package/dist/commands/db.d.ts +79 -25
  42. package/dist/commands/dev.d.ts +181 -13
  43. package/dist/commands/doctor.d.ts +5 -0
  44. package/dist/commands/generate_sdk.d.ts +29 -2
  45. package/dist/commands/init.d.ts +115 -14
  46. package/dist/commands/schema.d.ts +6 -0
  47. package/dist/commands/skills.d.ts +126 -7
  48. package/dist/commands/start.d.ts +44 -0
  49. package/dist/commands/storage.d.ts +46 -0
  50. package/dist/commands/upgrade.d.ts +1 -0
  51. package/dist/consent-ClRHmcxf.js +76 -0
  52. package/dist/consent-ClRHmcxf.js.map +1 -0
  53. package/dist/console-D6SJf8k_.js +102 -0
  54. package/dist/console-D6SJf8k_.js.map +1 -0
  55. package/dist/context-BqhRydBg.js +1234 -0
  56. package/dist/context-BqhRydBg.js.map +1 -0
  57. package/dist/{daemon-entry-LTFKtpHy.js → daemon-entry-Da-D3rmH.js} +3 -4
  58. package/dist/daemon-entry-Da-D3rmH.js.map +1 -0
  59. package/dist/daemon-pzsQwDHa.js +2 -0
  60. package/dist/db-B7RuNuaQ.js +1312 -0
  61. package/dist/db-B7RuNuaQ.js.map +1 -0
  62. package/dist/derive-Dl0z2OWi.js +484 -0
  63. package/dist/derive-Dl0z2OWi.js.map +1 -0
  64. package/dist/dev-CYr_WXan.js +1599 -0
  65. package/dist/dev-CYr_WXan.js.map +1 -0
  66. package/dist/dev-db/atlas-dev-database.d.ts +32 -0
  67. package/dist/dev-db/daemon-entry.d.ts +13 -0
  68. package/dist/dev-db/daemon.d.ts +10 -0
  69. package/dist/dev-db/last-dev-database.d.ts +41 -0
  70. package/dist/dev-db/prepare.d.ts +29 -3
  71. package/dist/dev-db/pull.d.ts +90 -5
  72. package/dist/dev-db/resolve.d.ts +26 -2
  73. package/dist/dev-preflight-B-LYyBf1.js +2 -0
  74. package/dist/dev-server-DG8Tt-uf.js +96 -0
  75. package/dist/dev-server-DG8Tt-uf.js.map +1 -0
  76. package/dist/doctor-BP8cZ-7F.js +771 -0
  77. package/dist/doctor-BP8cZ-7F.js.map +1 -0
  78. package/dist/eject-DizdoecV.js +335 -0
  79. package/dist/eject-DizdoecV.js.map +1 -0
  80. package/dist/fold-static-BC9CYicw.js +201 -0
  81. package/dist/fold-static-BC9CYicw.js.map +1 -0
  82. package/dist/fold-static.d.ts +26 -3
  83. package/dist/function-portability-BIvlvR9q.js +265 -0
  84. package/dist/function-portability-BIvlvR9q.js.map +1 -0
  85. package/dist/generate_sdk-BPqdJc3Q.js +489 -0
  86. package/dist/generate_sdk-BPqdJc3Q.js.map +1 -0
  87. package/dist/index.es.js +199 -22095
  88. package/dist/index.es.js.map +1 -1
  89. package/dist/init-Utstvh2Q.js +1149 -0
  90. package/dist/init-Utstvh2Q.js.map +1 -0
  91. package/dist/last-dev-database-B58g89uA.js +2 -0
  92. package/dist/manifest-DRp0UVTj.js +880 -0
  93. package/dist/manifest-DRp0UVTj.js.map +1 -0
  94. package/dist/manifest.d.ts +56 -4
  95. package/dist/normalize-imports-X0Tgze9y.js +107 -0
  96. package/dist/normalize-imports-X0Tgze9y.js.map +1 -0
  97. package/dist/package-manager-DSEOwTqM.js +193 -0
  98. package/dist/package-manager-DSEOwTqM.js.map +1 -0
  99. package/dist/path-flags-BFgG9V6y.js +91 -0
  100. package/dist/path-flags-BFgG9V6y.js.map +1 -0
  101. package/dist/precompress.d.ts +17 -0
  102. package/dist/prepare-CDN6lSpz.js +1236 -0
  103. package/dist/prepare-CDN6lSpz.js.map +1 -0
  104. package/dist/{project-3WCbrrfW.js → project-Wp2zoyeN.js} +34 -184
  105. package/dist/project-Wp2zoyeN.js.map +1 -0
  106. package/dist/pull-CrGYMEsy.js +458 -0
  107. package/dist/pull-CrGYMEsy.js.map +1 -0
  108. package/dist/resolve-B2O-wKKk.js +2 -0
  109. package/dist/resources-FD7AfZx8.js +183 -0
  110. package/dist/resources-FD7AfZx8.js.map +1 -0
  111. package/dist/schema-DMdr431S.js +125 -0
  112. package/dist/schema-DMdr431S.js.map +1 -0
  113. package/dist/skills-DTFibT1m.js +642 -0
  114. package/dist/skills-DTFibT1m.js.map +1 -0
  115. package/dist/start-DEa-hOBh.js +267 -0
  116. package/dist/start-DEa-hOBh.js.map +1 -0
  117. package/dist/{state-C59Elrnt.js → state-Do7ZJYkF.js} +49 -4
  118. package/dist/state-Do7ZJYkF.js.map +1 -0
  119. package/dist/status-DxnJTekv.js +352 -0
  120. package/dist/status-DxnJTekv.js.map +1 -0
  121. package/dist/storage-DyVq-f_F.js +303 -0
  122. package/dist/storage-DyVq-f_F.js.map +1 -0
  123. package/dist/telemetry/identity.d.ts +10 -1
  124. package/dist/telemetry-C8Uq8phb.js +129 -0
  125. package/dist/telemetry-C8Uq8phb.js.map +1 -0
  126. package/dist/telemetry-EMFRVRQi.js +351 -0
  127. package/dist/telemetry-EMFRVRQi.js.map +1 -0
  128. package/dist/unknown-command-DNwDcX3w.js +98 -0
  129. package/dist/unknown-command-DNwDcX3w.js.map +1 -0
  130. package/dist/upgrade-CtZtRkTE.js +1332 -0
  131. package/dist/upgrade-CtZtRkTE.js.map +1 -0
  132. package/dist/upgrade.d.ts +38 -5
  133. package/dist/utils/dev-preflight.d.ts +47 -5
  134. package/dist/utils/dev-server.d.ts +30 -0
  135. package/dist/utils/path-flags.d.ts +31 -0
  136. package/dist/utils/project.d.ts +16 -0
  137. package/dist/utils/temp-archive.d.ts +9 -0
  138. package/dist/version-Buyyo1ut.js +58 -0
  139. package/dist/version-Buyyo1ut.js.map +1 -0
  140. package/package.json +7 -7
  141. package/templates/eject/Dockerfile +4 -2
  142. package/templates/eject/backend/src/env.ts +1 -1
  143. package/templates/eject/backend/src/index.ts +42 -4
  144. package/templates/eject/docker-compose.custom.yml +8 -4
  145. package/templates/generated-schemas/blank.ts +40 -0
  146. package/templates/generated-schemas/blog.ts +127 -0
  147. package/templates/generated-schemas/ecommerce.ts +93 -0
  148. package/templates/overlays/baas/ai-instructions.md +1 -1
  149. package/templates/overlays/baas/config/package.json +1 -0
  150. package/templates/overlays/baas/config/storage.ts +5 -3
  151. package/templates/overlays/baas/package.json +1 -0
  152. package/templates/template/.cursorrules +1 -1
  153. package/templates/template/.env.example +20 -10
  154. package/templates/template/.github/copilot-instructions.md +1 -1
  155. package/templates/template/.mcp.json +2 -2
  156. package/templates/template/.windsurfrules +1 -1
  157. package/templates/template/AGENTS.md +1 -1
  158. package/templates/template/CLAUDE.md +1 -1
  159. package/templates/template/README.md +21 -15
  160. package/templates/template/ai-instructions.md +5 -4
  161. package/templates/template/backend/functions/hello.ts +8 -0
  162. package/templates/template/backend/package.json +1 -1
  163. package/templates/template/config/resources.ts +7 -6
  164. package/templates/template/config/storage.ts +5 -3
  165. package/templates/template/docker-compose.yml +15 -9
  166. package/templates/template/frontend/vite.config.ts +13 -3
  167. package/templates/template/gitignore +6 -1
  168. package/templates/template/package.json +5 -3
  169. package/templates/template/scripts/example.ts +6 -4
  170. package/templates/template/tsconfig.json +25 -0
  171. package/dist/branch-pointer-dBiClJ0p.js +0 -111
  172. package/dist/branch-pointer-dBiClJ0p.js.map +0 -1
  173. package/dist/constraints-DKGbNfUW.js +0 -48
  174. package/dist/constraints-DKGbNfUW.js.map +0 -1
  175. package/dist/daemon-DR9Tk0La.js +0 -355
  176. package/dist/daemon-DR9Tk0La.js.map +0 -1
  177. package/dist/daemon-entry-LTFKtpHy.js.map +0 -1
  178. package/dist/dev-preflight-CNLl4rdo.js +0 -367
  179. package/dist/dev-preflight-CNLl4rdo.js.map +0 -1
  180. package/dist/project-3WCbrrfW.js.map +0 -1
  181. package/dist/pull-Dywm5FWP.js +0 -232
  182. package/dist/pull-Dywm5FWP.js.map +0 -1
  183. package/dist/resolve-BAeRUBhg.js +0 -74
  184. package/dist/resolve-BAeRUBhg.js.map +0 -1
  185. package/dist/state-C59Elrnt.js.map +0 -1
  186. package/templates/template/backend/src/schema.generated.ts +0 -13
@@ -0,0 +1,1312 @@
1
+ import { i as recordEvent } from "./telemetry-EMFRVRQi.js";
2
+ import { _ as resolveTsxLoader, f as requireBackendDir, g as resolveTsx, h as resolvePluginCliScript, l as getActiveBackendPlugin, n as dependenciesNotInstalled, o as findEnvFile, p as requireProjectRoot } from "./project-Wp2zoyeN.js";
3
+ import { n as parseCommandArgs } from "./args-BnmsEXvu.js";
4
+ import { t as unknownCommand } from "./unknown-command-DNwDcX3w.js";
5
+ import { r as refuseMissingCollectionsPath, t as COLLECTIONS_FLAG_HELP } from "./path-flags-BFgG9V6y.js";
6
+ import { DEV_DATABASE_KIND_ENV, devDatabaseKind } from "./prepare-CDN6lSpz.js";
7
+ import chalk from "chalk";
8
+ import fs from "fs";
9
+ import os from "os";
10
+ import path from "path";
11
+ import inquirer from "inquirer";
12
+ import { execa } from "execa";
13
+ //#region src/utils/command-words.ts
14
+ /**
15
+ * The words that name a command, with the flags taken back out.
16
+ *
17
+ * `rawArgs` is the whole of `process.argv`, and reading the command's words at
18
+ * fixed indices off it assumes nothing precedes them. Something routinely does:
19
+ * `--debug` is what `bin/rebase.js` prints after every failure as the thing to
20
+ * re-run with, so it is the single most likely token to appear before a command
21
+ * word, and it shifted every index by one.
22
+ *
23
+ * What that cost is not a bad error message. `rebase db branch switch feature`
24
+ * writes a per-checkout pointer that the CLI owns; the driver, running as a
25
+ * child process, cannot persist it and does not try. The dispatch found
26
+ * `switch` by position, so `rebase --debug db branch switch feature` missed the
27
+ * CLI's branch and handed the line to the driver — which reported success and
28
+ * left the checkout on the main database. Every subsequent `dev`, `push` and
29
+ * `backup` then ran against the wrong database, believing it was the branch,
30
+ * which is the exact failure branching exists to prevent.
31
+ *
32
+ * The words are anchored on the command name rather than taken from position
33
+ * zero, because a flag written in the space form (`--database-url <url>`) leaves
34
+ * its value behind as a bare token and no parser at this level knows which
35
+ * flags take values. Anchoring survives that: the value would have to be the
36
+ * literal command name to fool it.
37
+ *
38
+ * Returns `[]` when the command name is not on the line at all.
39
+ */
40
+ function commandWords(rawArgs, command) {
41
+ const words = rawArgs.slice(2).filter((token) => !token.startsWith("-"));
42
+ const start = words.indexOf(command);
43
+ return start === -1 ? [] : words.slice(start);
44
+ }
45
+ /**
46
+ * The line to hand a spawned driver, starting at the command word.
47
+ *
48
+ * The same defect one layer down, and it does not degrade gracefully: the
49
+ * driver reads its domain from `args[0]`, so `rebase --debug db push` spawned
50
+ * it with `["--debug", "db", "push"]` and it answered "Unknown domain command:
51
+ * --debug" — for a flag the CLI itself tells you to add after any failure.
52
+ *
53
+ * Tokens written *before* the command word are moved after it rather than
54
+ * dropped. Dropping them would be the same class of bug in the other direction:
55
+ * `rebase --database-url postgres://… db push` would silently lose the flag that
56
+ * says which database to touch. Appending keeps each flag next to its value, and
57
+ * `arg` reads flags wherever they appear.
58
+ *
59
+ * Falls back to `rawArgs.slice(2)` when the command word is not on the line,
60
+ * which is what an internally synthesised argv looks like.
61
+ */
62
+ function argsFromCommand(rawArgs, command) {
63
+ const tail = rawArgs.slice(2);
64
+ const start = tail.findIndex((token) => token === command);
65
+ if (start <= 0) return [...tail];
66
+ return [...tail.slice(start), ...tail.slice(0, start)];
67
+ }
68
+ //#endregion
69
+ //#region src/utils/spawn-error.ts
70
+ /**
71
+ * What to say when a spawned child process fails.
72
+ *
73
+ * Two failures arrive through the same `catch` and need opposite treatment:
74
+ *
75
+ * - **The child ran and exited non-zero.** It had inherited stdio, so it has
76
+ * already printed its own diagnostics. execa's "Command failed with exit
77
+ * code 1: …" is a second, worse copy of the same news with the whole argv
78
+ * appended.
79
+ * - **The child never started.** ENOENT on the tsx binary, EACCES on a script
80
+ * that lost its permissions, ENOMEM on a full machine. Nobody printed
81
+ * anything, because nothing ran. `schema.ts` and `doctor.ts` both swallowed
82
+ * these — `catch { process.exit(1); }`, the error not even bound — so
83
+ * `rebase schema generate` against a broken tsx exited 1 in silence, and so
84
+ * did `rebase doctor`, the command whose entire job is to say what is wrong.
85
+ *
86
+ * The tsx symlink surviving a cleaned pnpm store is the ordinary way to get
87
+ * here: `resolveLocalBin` finds the symlink, so "dependencies are not
88
+ * installed" never fires, and the spawn is where it breaks.
89
+ *
90
+ * ## Why the message is not what decides it
91
+ *
92
+ * `db.ts` did make this distinction, by testing the message against
93
+ * `/Command failed|exited with code/i` — and that test is wrong for every case
94
+ * it was written to catch. execa prefixes **all** of them the same way:
95
+ *
96
+ * Command failed with exit code 3: /bin/sh -c 'exit 3'
97
+ * Command failed with ENOENT: /…/tsx x⏎spawn /…/tsx ENOENT
98
+ * Command failed with EACCES: /…/tsx x⏎spawn /…/tsx EACCES
99
+ *
100
+ * So the filter matched the spawn failures too and `db push` was as silent as
101
+ * the other two. The structured fields do distinguish them: a child that ran
102
+ * has a numeric `exitCode` (or a `signal`, if something killed it), and a child
103
+ * that never started has neither — only an errno in `code`.
104
+ */
105
+ /** Did the process start? Only then has anything else already been printed. */
106
+ function childRan(error) {
107
+ if (!(error instanceof Error)) return false;
108
+ const failure = error;
109
+ return typeof failure.exitCode === "number" || typeof failure.signal === "string";
110
+ }
111
+ function reportSpawnFailure(error) {
112
+ if (childRan(error) || !(error instanceof Error)) return;
113
+ const failure = error;
114
+ const message = typeof failure.originalMessage === "string" ? failure.originalMessage : error.message;
115
+ if (message) console.error(chalk.red(`✗ ${message}`));
116
+ }
117
+ //#endregion
118
+ //#region src/commands/db.ts
119
+ /**
120
+ * CLI command: rebase db <action>
121
+ */
122
+ /**
123
+ * The connection string a prepared database actually answers on.
124
+ *
125
+ * One function, because `db url` and `db pull` disagreed about it and the
126
+ * disagreement was a dead command: `prepareDatabaseEnv` returns `env: {}` for a
127
+ * plain external database — the connection string is already somewhere the
128
+ * child looks — so `db pull`'s `prepared.env.DATABASE_URL ?? process.env
129
+ * .DATABASE_URL` was empty for the standard `.env` configuration and answered
130
+ * `✗ No local database to pull into.` on a project whose `rebase db url` had
131
+ * just printed one. Exporting the same URL in the shell made it work, which is
132
+ * the shape of a bug nobody reports as one.
133
+ *
134
+ * `readEnvFile` is passed in rather than imported: this module loads
135
+ * `../utils/project` dynamically everywhere else, and the callers already have
136
+ * it open.
137
+ */
138
+ function databaseUrlOf(prepared, envFile) {
139
+ const named = (value) => value && value.trim() ? value : void 0;
140
+ return named(prepared.env.DATABASE_URL) ?? named(prepared.database.kind === "managed" ? void 0 : prepared.database.url) ?? named(envFile.DATABASE_URL) ?? named(process.env.DATABASE_URL);
141
+ }
142
+ /**
143
+ * A destination that names a remote store rather than a local path.
144
+ *
145
+ * Matched as "scheme://" generally, not as a list of the schemes we support:
146
+ * an unknown scheme is still not something to join onto a filesystem path, and
147
+ * a Windows drive letter ("C:\backups") has no "//" so it stays a path.
148
+ */
149
+ var REMOTE_DESTINATION_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
150
+ /**
151
+ * The flags whose value is a local path, on every line the CLI relays.
152
+ *
153
+ * All three spellings of the destination, because the driver accepts all
154
+ * three: `backup-cli.ts` maps `--output` and `-o` onto `--out`, and `rebase db
155
+ * backup --help` advertises `--output` as an alias. Only `--out` and `-o` were
156
+ * absolutised once, so the one spelling the help page names was the one that
157
+ * landed in `backend/` — and the success line still echoed the path as typed.
158
+ *
159
+ * And `--collections`, which was not absolutised at all: from the project root,
160
+ * `rebase schema generate --collections ./config/collections` was "not found",
161
+ * while the same spelling worked for `generate-sdk`. See `utils/path-flags.ts`.
162
+ */
163
+ var LOCAL_PATH_FLAGS = [
164
+ "--out",
165
+ "--output",
166
+ "-o",
167
+ "--collections",
168
+ "-c"
169
+ ];
170
+ /**
171
+ * Rewrite local path arguments so they mean what the user typed.
172
+ *
173
+ * The plugin CLI is spawned with `cwd: backendDir` — it has to be, because that
174
+ * is where the plugin and its dependencies resolve from. But the developer runs
175
+ * `rebase db` from the project root, so a relative `--out ./backups` was being
176
+ * resolved against `backend/` and landed in `backend/backups`, while the
177
+ * success line echoed the path as typed. The file was real and the reported
178
+ * location was wrong, which is the worst way for a backup command to behave.
179
+ * `rebase db --help` documents exactly this invocation.
180
+ *
181
+ * Absolutising here rather than inside the plugin keeps the fix where the cwd
182
+ * is actually changed, and leaves the plugin usable on its own terms.
183
+ */
184
+ function absolutizeLocalPathArgs(args, cwd, pathFlags = LOCAL_PATH_FLAGS) {
185
+ const takesPath = (flag) => pathFlags.includes(flag);
186
+ /**
187
+ * Flags whose next token is a value, not a positional.
188
+ *
189
+ * Mirrors the `arg` specs in `@rebasepro/server-postgres`'s backup CLI.
190
+ * Needed only to find the `db restore` dump argument: without it,
191
+ * `restore --target-db app_restored ./x.dump` treats `app_restored` as the
192
+ * positional — it is the first token not starting with `-` — and turns a
193
+ * database name into a path while leaving the real dump path unresolved.
194
+ */
195
+ const VALUE_FLAGS = /* @__PURE__ */ new Set([
196
+ "--out",
197
+ "--output",
198
+ "-o",
199
+ "--target-db",
200
+ "--exclude-schema",
201
+ "--row-security-role"
202
+ ]);
203
+ const out = [...args];
204
+ for (let i = 0; i < out.length; i++) {
205
+ const arg = out[i];
206
+ const eq = arg.indexOf("=");
207
+ if (eq > 0 && takesPath(arg.slice(0, eq))) {
208
+ const value = arg.slice(eq + 1);
209
+ if (value && !REMOTE_DESTINATION_RE.test(value)) out[i] = `${arg.slice(0, eq)}=${path.resolve(cwd, value)}`;
210
+ continue;
211
+ }
212
+ if (takesPath(arg)) {
213
+ const value = out[i + 1];
214
+ if (value && !value.startsWith("-") && !REMOTE_DESTINATION_RE.test(value)) {
215
+ out[i + 1] = path.resolve(cwd, value);
216
+ i++;
217
+ }
218
+ }
219
+ }
220
+ const restoreAt = out.indexOf("restore");
221
+ if (restoreAt !== -1) for (let i = restoreAt + 1; i < out.length; i++) {
222
+ const arg = out[i];
223
+ if (arg.startsWith("-")) {
224
+ if (!arg.includes("=") && VALUE_FLAGS.has(arg)) i++;
225
+ continue;
226
+ }
227
+ if (!REMOTE_DESTINATION_RE.test(arg)) out[i] = path.resolve(cwd, arg);
228
+ break;
229
+ }
230
+ return out;
231
+ }
232
+ /**
233
+ /**
234
+ * Read `--flag value` or `--flag=value` out of the raw argv.
235
+ *
236
+ * This command forwards its arguments to the driver plugin rather than parsing
237
+ * them, so the two flags the CLI itself acts on are picked out by hand instead
238
+ * of adding a spec that would then have to strip them back out again.
239
+ */
240
+ function readFlagValue(rawArgs, flag) {
241
+ for (let index = 0; index < rawArgs.length; index += 1) {
242
+ const arg = rawArgs[index];
243
+ if (arg === flag) return rawArgs[index + 1] ?? null;
244
+ if (arg.startsWith(`${flag}=`)) return arg.slice(flag.length + 1);
245
+ }
246
+ return null;
247
+ }
248
+ /**
249
+ * Run a database subcommand through the active driver's CLI, throwing on
250
+ * failure instead of exiting.
251
+ *
252
+ * `dbCommand` below turns every failure into `process.exit(1)`, which is right
253
+ * for a command the user invoked directly and wrong for a caller that has more
254
+ * to do afterwards — `rebase dev` runs a schema push during start-up and must
255
+ * survive it failing. Exiting is therefore the wrapper's job, not this
256
+ * function's.
257
+ *
258
+ * The database is resolved *here* rather than in the wrapper, so the schema
259
+ * push `rebase dev` performs during start-up reaches the managed database too.
260
+ */
261
+ /**
262
+ * The `db` subcommands that plan their work with Atlas.
263
+ *
264
+ * Atlas computes a diff by replaying the desired schema into a **second, empty
265
+ * database** and comparing. That is why these three are listed and `backup` and
266
+ * `restore` are not — those shell out to `pg_dump`, which fails loudly on its
267
+ * own. `branch` is refused too, but for its own reason and with its own
268
+ * message: see {@link refuseBranchOnManagedDatabase}.
269
+ */
270
+ var ATLAS_BACKED_SUBCOMMANDS = /* @__PURE__ */ new Set([
271
+ "push",
272
+ "generate",
273
+ "migrate"
274
+ ]);
275
+ /**
276
+ * A managed-database refusal, raised so the caller decides what it costs.
277
+ *
278
+ * These two guards used to `process.exit(1)` where they stood. That is right
279
+ * for `rebase db push`, typed by a person, and catastrophic for the same code
280
+ * reached from inside `rebase dev`: the dev server's first-boot schema push
281
+ * runs in-process, so an exit there took the whole dev server down — with a
282
+ * `try/catch` around it written expressly to prevent that, which could never
283
+ * run. The first `rebase dev --docker` of every scaffold died this way.
284
+ *
285
+ * So the refusal is a value now. It carries the block it wants printed rather
286
+ * than printing it, because who prints (and whether printing is even right) is
287
+ * the caller's question: `dbCommand` prints it and exits 1, and `rebase dev`
288
+ * keeps serving.
289
+ */
290
+ var ManagedDatabaseRefusal = class extends Error {
291
+ /** The lines to print, in order, already coloured. */
292
+ lines;
293
+ constructor(summary, lines) {
294
+ super(summary);
295
+ this.name = "ManagedDatabaseRefusal";
296
+ this.lines = lines;
297
+ }
298
+ };
299
+ /** Print a refusal exactly as the guards used to print it themselves. */
300
+ function printManagedDatabaseRefusal(refusal) {
301
+ for (const line of refusal.lines) console.error(line);
302
+ }
303
+ /**
304
+ * The variable the driver reads for Atlas's dev database
305
+ * (`ATLAS_DEV_URL_ENV` in `@rebasepro/server-postgres`, which this CLI does not
306
+ * depend on).
307
+ */
308
+ var ATLAS_DEV_URL_ENV = "REBASE_ATLAS_DEV_URL";
309
+ /**
310
+ * The variable that tells the driver where `rebase` was run
311
+ * (`INVOCATION_CWD_ENV` in `@rebasepro/server-postgres`). The driver runs in
312
+ * `backend/`, so a path it resolves itself, such as `db backup`'s default
313
+ * `./backups`, needs to know the directory the developer meant.
314
+ */
315
+ var INVOCATION_CWD_ENV = "REBASE_INVOCATION_CWD";
316
+ /** Loaded only when a command needs one: PGlite is 25 MB of WASM. */
317
+ var startAtlasDevDatabase = async () => (await import("./atlas-dev-database-D_LP_Woq.js")).startAtlasDevDatabase();
318
+ /**
319
+ * The empty database an Atlas-backed subcommand plans against, on the managed
320
+ * development database.
321
+ *
322
+ * **PGlite serves exactly one database.** Atlas computes a change by replaying
323
+ * the desired schema into a second, empty one; on a real server the driver
324
+ * makes it as `<db>_dev_diff`, but `CREATE DATABASE` against PGlite reports
325
+ * success and creates nothing, so Atlas connected straight back to the
326
+ * database it was comparing and stopped with `connected database is not
327
+ * clean`. These commands were refused outright on the managed database — and
328
+ * with them every way to drop, rename or narrow a column there, since boot
329
+ * only adds.
330
+ *
331
+ * So a throwaway second PGlite is started for the command instead — in
332
+ * memory, in this process, gone when the command ends — and handed to the
333
+ * driver as `REBASE_ATLAS_DEV_URL`. Nothing else about the push changes: the
334
+ * destructive gate is the driver's, and holds as it does everywhere.
335
+ *
336
+ * `undefined` when none is needed: another database kind (the driver makes its
337
+ * own), a subcommand that is not Atlas's, or a `REBASE_ATLAS_DEV_URL` the
338
+ * developer set. When one cannot be started — PGlite is an optional
339
+ * dependency — the old refusal stands, with the reason.
340
+ */
341
+ async function atlasDevDatabaseFor(rawArgs, kind, env, start = startAtlasDevDatabase) {
342
+ if (kind !== "managed") return void 0;
343
+ const [domain, subcommand] = commandWords(rawArgs, "db");
344
+ if (domain !== "db" || !ATLAS_BACKED_SUBCOMMANDS.has(subcommand ?? "")) return void 0;
345
+ if (env["REBASE_ATLAS_DEV_URL"]?.trim()) return void 0;
346
+ try {
347
+ return await start();
348
+ } catch (err) {
349
+ const summary = `rebase db ${subcommand} could not start the database Atlas plans against.`;
350
+ throw new ManagedDatabaseRefusal(summary, [
351
+ "",
352
+ chalk.red(` ✗ ${summary}`),
353
+ chalk.gray(` ${err instanceof Error ? err.message : String(err)}`),
354
+ "",
355
+ chalk.gray(" Atlas plans every change against a second, empty database. On the managed"),
356
+ chalk.gray(" database that is a throwaway PGlite, started for the command."),
357
+ "",
358
+ chalk.gray(` ${chalk.cyan("rebase dev")} still applies your collections at boot, additively. Otherwise,`),
359
+ chalk.gray(` set ${ATLAS_DEV_URL_ENV} to an empty Postgres database Atlas may fill and clear,`),
360
+ chalk.gray(" or point the project at a real Postgres (uncomment DATABASE_URL in .env)."),
361
+ ""
362
+ ]);
363
+ }
364
+ }
365
+ /**
366
+ * Stop `rebase db branch` before it reports a branch that is not one.
367
+ *
368
+ * **PGlite serves exactly one database**, and this is the second thing that
369
+ * follows from it. `CREATE DATABASE "rb_feature_x" TEMPLATE "postgres"` there
370
+ * writes a `pg_database` catalog row and nothing else. Nothing errors, so the
371
+ * whole feature reports success end to end:
372
+ *
373
+ * $ rebase db branch create feature_x
374
+ * ✓ Branch "feature_x" created successfully.
375
+ * $ rebase db branch list
376
+ * ● feature_x (7.1 MB) — created just now
377
+ *
378
+ * `listBranches` joins `pg_database`, the catalog row is there, and
379
+ * `pg_database_size` answers with the one database's size — so the listing
380
+ * corroborates the lie. Then connecting to `rb_feature_x` reports
381
+ * `current_database()` = `postgres`, and a table created "in the branch" is
382
+ * visible in the parent immediately. Measured on a fresh `rebase init` scaffold.
383
+ *
384
+ * **The branch is the parent.** Every write made in the belief that it is
385
+ * sandboxed lands in the developer's real development database — which is the
386
+ * exact failure branching exists to prevent, announced as a success.
387
+ *
388
+ * So this refuses the whole `branch` domain rather than `create` alone: `list`
389
+ * on the managed database ends with "Create one with: rebase db branch create",
390
+ * an invitation to do the broken thing, and `info` would confirm a size for a
391
+ * database that was never made.
392
+ *
393
+ * Push, generate and migrate had the same problem — Atlas's scratch database
394
+ * is a second database too — and get a throwaway PGlite of their own instead
395
+ * (`atlasDevDatabaseFor` above). A branch cannot: it is meant to keep the
396
+ * project's data, and a throwaway instance has none.
397
+ */
398
+ function refuseBranchOnManagedDatabase(rawArgs, kind) {
399
+ if (kind !== "managed") return;
400
+ const [domain, subcommand] = commandWords(rawArgs, "db");
401
+ if (domain !== "db" || subcommand !== "branch") return;
402
+ const summary = "rebase db branch does not work on the managed development database.";
403
+ throw new ManagedDatabaseRefusal(summary, [
404
+ "",
405
+ chalk.red(` ✗ ${summary}`),
406
+ "",
407
+ chalk.gray(" Branching copies a database with CREATE DATABASE ... TEMPLATE. The managed"),
408
+ chalk.gray(" database is PGlite, which serves exactly one — the copy would be the"),
409
+ chalk.gray(" original, and every write you meant to sandbox would land in it."),
410
+ "",
411
+ chalk.gray(" Branching needs a real Postgres. Either:"),
412
+ chalk.gray(` ${chalk.cyan("rebase dev --docker")} starts one, and branches work against it`),
413
+ chalk.gray(" or uncomment DATABASE_URL in .env to point at your own."),
414
+ ""
415
+ ]);
416
+ }
417
+ /**
418
+ * Resolve the active driver's CLI and the environment it should run in.
419
+ *
420
+ * Shared by the two runners below. Deliberately does NOT resolve a database:
421
+ * `schema generate` reads collection files and writes one file, and starting a
422
+ * database to run it would be a side effect nobody asked for.
423
+ */
424
+ async function resolveDriverCli() {
425
+ const projectRoot = requireProjectRoot();
426
+ const backendDir = requireBackendDir(projectRoot);
427
+ const activePlugin = getActiveBackendPlugin(backendDir);
428
+ if (!activePlugin) throw new Error("Could not detect an active database plugin. Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.");
429
+ const pluginCli = resolvePluginCliScript(backendDir, activePlugin);
430
+ if (!pluginCli) throw new Error(dependenciesNotInstalled(projectRoot));
431
+ const envFile = findEnvFile(projectRoot);
432
+ const env = { ...process.env };
433
+ if (envFile) env.DOTENV_CONFIG_PATH = envFile;
434
+ env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? "";
435
+ return {
436
+ projectRoot,
437
+ backendDir,
438
+ pluginCli,
439
+ env
440
+ };
441
+ }
442
+ /**
443
+ * The one place this CLI spawns the driver's own CLI.
444
+ *
445
+ * There were three, each with its own copy of "tsx for a `.ts` entry, `node`
446
+ * otherwise". That rule was right only while the driver shipped `src/`; once it
447
+ * shipped `dist/cli.js` all three quietly switched to plain `node`, and the
448
+ * driver loads the PROJECT's TypeScript in process:
449
+ *
450
+ * - `schema stale` reads the collections, could not resolve `./authors` onto
451
+ * `authors.ts`, and answered "⏭ Not checked" while exiting 0;
452
+ * - `db push` does the same in `ensureAuthTables`, so `rebase.users` was never
453
+ * created and the push died at "Applying RLS policies" with
454
+ * `relation "rebase.users" does not exist` — on a virgin database, which is
455
+ * the documented bring-your-own-Postgres first run.
456
+ *
457
+ * Two were fixed and the third was missed, because three copies of a decision
458
+ * are three chances to miss one. There is one now, and a gate holds it at one.
459
+ *
460
+ * tsx whenever it is installed — a devDependency of every scaffold, for exactly
461
+ * this reason. Without it a `.ts` entry cannot run at all; a built entry still
462
+ * runs, and the subcommands that never touch the project's TypeScript still work.
463
+ *
464
+ * tsx's loader in one Node (`node --import`) rather than the `tsx` binary,
465
+ * which is a shell shim and a relay Node in front of the same loader: one Node
466
+ * start instead of two, ~50–100 ms on each of the driver runs every `rebase
467
+ * dev` start and every collection save makes. The binary stays the fallback for
468
+ * a tsx whose loader does not resolve as a package — a global install.
469
+ */
470
+ async function spawnDriverCli(resolved, childArgs, options = {}) {
471
+ const { projectRoot, backendDir, pluginCli, env } = resolved;
472
+ const stdio = options.quiet ? "pipe" : "inherit";
473
+ const tsxBin = resolveTsx(projectRoot);
474
+ const tsxLoader = resolveTsxLoader(projectRoot);
475
+ if (!tsxBin && !tsxLoader && pluginCli.endsWith(".ts")) throw new Error(dependenciesNotInstalled(projectRoot));
476
+ const [command, ...prefix] = tsxLoader ? [
477
+ process.execPath,
478
+ "--import",
479
+ tsxLoader
480
+ ] : [tsxBin ?? "node"];
481
+ await execa(command, [
482
+ ...prefix,
483
+ pluginCli,
484
+ ...childArgs
485
+ ], {
486
+ cwd: backendDir,
487
+ stdio,
488
+ env
489
+ });
490
+ }
491
+ /** @deprecated Use {@link spawnDriverCli}. Kept as the internal name callers use. */
492
+ var execDriverCli = spawnDriverCli;
493
+ /**
494
+ * Run a `schema` subcommand through the active driver's CLI.
495
+ *
496
+ * Separate from {@link runDriverDbCommand} because it must NOT resolve a
497
+ * database. `rebase dev` calls this before the database exists, which is the
498
+ * whole point: the generated schema has to be right before anything reads it.
499
+ * Throws rather than exiting — the caller has more to do.
500
+ */
501
+ async function runDriverSchemaCommand(rawArgs, options = {}) {
502
+ await execDriverCli(await resolveDriverCli(), rawArgs.slice(2), options);
503
+ }
504
+ async function runDriverDbCommand(rawArgs, options = {}) {
505
+ const projectRoot = requireProjectRoot();
506
+ const backendDir = requireBackendDir(projectRoot);
507
+ const activePlugin = getActiveBackendPlugin(backendDir);
508
+ if (!activePlugin) throw new Error("Could not detect an active database plugin. Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.");
509
+ const pluginCli = resolvePluginCliScript(backendDir, activePlugin);
510
+ if (!pluginCli) throw new Error(dependenciesNotInstalled(projectRoot));
511
+ const envFile = findEnvFile(projectRoot);
512
+ const env = { ...process.env };
513
+ if (envFile) env.DOTENV_CONFIG_PATH = envFile;
514
+ env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? "";
515
+ const { resolveProjectDatabase } = await import("./prepare-CDN6lSpz.js");
516
+ refuseBranchOnManagedDatabase(rawArgs, resolveProjectDatabase(projectRoot, {
517
+ flagUrl: readFlagValue(rawArgs, "--database-url"),
518
+ flagDocker: rawArgs.includes("--docker")
519
+ }).kind);
520
+ const { prepareDatabaseEnv, managedNotices } = await import("./prepare-CDN6lSpz.js");
521
+ const prepared = await prepareDatabaseEnv(projectRoot, {
522
+ flagUrl: readFlagValue(rawArgs, "--database-url"),
523
+ flagDocker: rawArgs.includes("--docker"),
524
+ onProgress: (message) => {
525
+ if (!options.quiet) console.log(chalk.gray(` ${message}`));
526
+ }
527
+ });
528
+ Object.assign(env, prepared.env);
529
+ if (!options.quiet) for (const line of managedNotices(prepared)) console.log(chalk.gray(` ${line}`));
530
+ const atlasDev = await atlasDevDatabaseFor(rawArgs, prepared.database.kind, env);
531
+ if (atlasDev) env[ATLAS_DEV_URL_ENV] = atlasDev.url;
532
+ env[INVOCATION_CWD_ENV] = process.cwd();
533
+ const childArgs = absolutizeLocalPathArgs(argsFromCommand(rawArgs, "db"), process.cwd());
534
+ try {
535
+ await spawnDriverCli({
536
+ projectRoot,
537
+ backendDir,
538
+ pluginCli,
539
+ env
540
+ }, childArgs, options);
541
+ } finally {
542
+ await atlasDev?.stop();
543
+ }
544
+ }
545
+ async function dbCommand(subcommand, rawArgs) {
546
+ if (!subcommand || subcommand === "--help" || rawArgs.includes("--help") || rawArgs.includes("-h")) {
547
+ printDbHelp(subcommand === "--help" ? void 0 : subcommand);
548
+ return;
549
+ }
550
+ if (!DB_ACTION_HELP[subcommand]) unknownCommand(subcommand, Object.keys(DB_ACTION_HELP), "db");
551
+ const projectRoot = requireProjectRoot();
552
+ recordEvent("cli.db", { subcommand: subcommand ?? "none" }, { projectRoot });
553
+ if (subcommand === "stop" || subcommand === "reset") {
554
+ await manageLocalDatabase(subcommand, projectRoot, rawArgs);
555
+ return;
556
+ }
557
+ await ensureDockerDatabase(projectRoot, rawArgs);
558
+ if (subcommand === "pull") {
559
+ await pullIntoLocal(projectRoot, rawArgs);
560
+ return;
561
+ }
562
+ if (subcommand === "url") {
563
+ await printDatabaseUrl(projectRoot, rawArgs);
564
+ return;
565
+ }
566
+ if (subcommand === "branch" && commandWords(rawArgs, "db")[2] === "switch") {
567
+ await switchBranch(projectRoot, rawArgs);
568
+ return;
569
+ }
570
+ let driverArgs = rawArgs;
571
+ if (subcommand === "branch") {
572
+ const action = commandWords(rawArgs, "db")[2];
573
+ if (action === "delete") await refuseDeletingActiveBranch(projectRoot, rawArgs);
574
+ if (action && REGISTRY_ACTIONS.has(action)) driverArgs = await onParentDatabase(projectRoot, rawArgs, action);
575
+ }
576
+ refuseMissingCollectionsPath(driverArgs, process.cwd(), requireBackendDir(projectRoot));
577
+ try {
578
+ await runDriverDbCommand(driverArgs);
579
+ } catch (error) {
580
+ if (error instanceof ManagedDatabaseRefusal) {
581
+ printManagedDatabaseRefusal(error);
582
+ process.exit(1);
583
+ }
584
+ reportSpawnFailure(error);
585
+ process.exit(1);
586
+ }
587
+ }
588
+ /**
589
+ * `rebase db url` — the connection string this project is using, on stdout.
590
+ *
591
+ * The managed database is the one case where nothing on disk names it: `.env`
592
+ * ships `DATABASE_URL` commented out on purpose, the port is derived from the
593
+ * project path, and the data lives under `.rebase/`. A headless project has no
594
+ * admin panel to open either, so before this there was no way to point `psql`,
595
+ * a GUI client or a seeding script at the database `rebase dev` had just
596
+ * created — short of reading the CLI's source.
597
+ *
598
+ * Resolution is the same ordered rule every other command uses, so this prints
599
+ * your own `DATABASE_URL` when you have set one rather than inventing a second
600
+ * answer. Nothing but the URL goes to stdout, so it pipes:
601
+ *
602
+ * psql "$(rebase db url)"
603
+ *
604
+ * It starts the managed database if it is not running, because a connection
605
+ * string for a database nobody is serving is not an answer.
606
+ */
607
+ async function printDatabaseUrl(projectRoot, rawArgs) {
608
+ parseCommandArgs({
609
+ spec: {
610
+ "--database-url": String,
611
+ "--docker": Boolean
612
+ },
613
+ rawArgs: [...rawArgs],
614
+ commandWords: 2,
615
+ command: "db url",
616
+ maxPositionals: 0
617
+ });
618
+ const { prepareDatabaseEnv } = await import("./prepare-CDN6lSpz.js");
619
+ const { readEnvFile } = await import("./project-Wp2zoyeN.js").then((n) => n.u);
620
+ const url = databaseUrlOf(await prepareDatabaseEnv(projectRoot, {
621
+ flagUrl: readFlagValue(rawArgs, "--database-url"),
622
+ flagDocker: rawArgs.includes("--docker"),
623
+ quiet: true,
624
+ onProgress: (message) => console.error(chalk.gray(` ${message}`))
625
+ }), readEnvFile(projectRoot));
626
+ if (!url) {
627
+ console.error(chalk.red(" ✗ This project has no database URL to print."));
628
+ console.error(chalk.gray(" Set DATABASE_URL in .env, or run `rebase dev` to start the managed one."));
629
+ process.exit(1);
630
+ }
631
+ console.log(url);
632
+ }
633
+ /**
634
+ * `rebase db stop` and `rebase db reset`, for the managed database only.
635
+ *
636
+ * `reset` deletes the data directory rather than dropping schemas: "give me an
637
+ * empty database" is the only thing anyone means by it, and doing it by
638
+ * removing the directory cannot leave a half-dropped schema behind.
639
+ */
640
+ async function manageLocalDatabase(subcommand, projectRoot, rawArgs) {
641
+ const { resetManagedDatabase, stopManagedDatabase, findRunningDaemon } = await import("./daemon-pzsQwDHa.js");
642
+ const { dataDir } = await import("./state-Do7ZJYkF.js").then((n) => n.d);
643
+ const nothingHere = () => {
644
+ const kind = devDatabaseKind(projectRoot);
645
+ const verb = subcommand === "stop" ? "was not running" : "does not exist";
646
+ if (kind && kind !== "managed") return ` The managed development database (PGlite) ${verb}; this project uses its own DATABASE_URL, which is untouched.`;
647
+ return subcommand === "stop" ? " The managed development database (PGlite) was not running." : " There is no managed development database (PGlite) to reset.";
648
+ };
649
+ if (subcommand === "stop") {
650
+ const stopped = await stopManagedDatabase(projectRoot);
651
+ console.log(stopped ? chalk.green("✓ Development database stopped. Data is kept — `rebase dev` will start it again.") : chalk.gray(nothingHere()));
652
+ return;
653
+ }
654
+ const running = await findRunningDaemon(projectRoot);
655
+ const hasData = fs.existsSync(dataDir(projectRoot));
656
+ if (!running && !hasData) {
657
+ console.log(chalk.gray(nothingHere()));
658
+ return;
659
+ }
660
+ if (!rawArgs.includes("--yes") && !rawArgs.includes("-y")) {
661
+ if (!process.stdin.isTTY) {
662
+ console.error(chalk.red("✗ `rebase db reset` deletes the local database and cannot prompt here."));
663
+ console.error(chalk.yellow(" Re-run with --yes if that is what you intend."));
664
+ process.exit(1);
665
+ }
666
+ const { confirmed } = await inquirer.prompt([{
667
+ type: "confirm",
668
+ name: "confirmed",
669
+ message: `Delete the development database at ${dataDir(projectRoot)}? This cannot be undone.`,
670
+ default: false
671
+ }]);
672
+ if (!confirmed) {
673
+ console.log(chalk.gray(" Left alone."));
674
+ return;
675
+ }
676
+ }
677
+ await resetManagedDatabase(projectRoot);
678
+ console.log(chalk.green("✓ Development database deleted. `rebase dev` will create a fresh one."));
679
+ }
680
+ /**
681
+ * `rebase db pull --from <url>` — copy another database's contents into local
682
+ * development.
683
+ *
684
+ * Deliberately one-directional. There is no flag that makes this push, because
685
+ * a tool that can copy in both directions eventually copies in the wrong one,
686
+ * and the wrong one here means overwriting production with a laptop.
687
+ */
688
+ async function pullIntoLocal(projectRoot, rawArgs) {
689
+ const { describeTarget, dumpArgs, dumpEnv, findPgTool, restoreArgs, restoreEnv, restoreOutcome } = await import("./pull-CrGYMEsy.js");
690
+ const { prepareDatabaseEnv } = await import("./prepare-CDN6lSpz.js");
691
+ const { readEnvFile } = await import("./project-Wp2zoyeN.js").then((n) => n.u);
692
+ const source = readFlagValue(rawArgs, "--from");
693
+ if (!source) {
694
+ console.error(chalk.red("✗ `rebase db pull` needs a source: --from <connection-string>"));
695
+ console.error(chalk.gray(" Example: rebase db pull --from \"$PRODUCTION_DATABASE_URL\""));
696
+ process.exit(1);
697
+ }
698
+ const schemas = rawArgs.flatMap((arg, index) => arg === "--schema" && rawArgs[index + 1] ? [rawArgs[index + 1]] : []);
699
+ const anonymize = rawArgs.includes("--anonymize");
700
+ for (const tool of ["pg_dump", "pg_restore"]) if (!await findPgTool(tool)) {
701
+ console.error(chalk.red(`✗ \`${tool}\` is not on PATH, and this command cannot run without it.`));
702
+ console.error(chalk.gray(" Install the PostgreSQL client tools, e.g. `brew install libpq`."));
703
+ process.exit(1);
704
+ }
705
+ const targetFlag = readFlagValue(rawArgs, "--database-url");
706
+ if (targetFlag !== null) {
707
+ console.error(chalk.red("✗ `rebase db pull` does not take --database-url."));
708
+ console.error("");
709
+ console.error(chalk.gray(" The target is always this project's local development database. There is"));
710
+ console.error(chalk.gray(" no flag that makes this write somewhere else, deliberately: a command that"));
711
+ console.error(chalk.gray(" can copy in both directions eventually copies in the wrong one."));
712
+ console.error("");
713
+ console.error(chalk.gray(` To read from another database, that is ${chalk.cyan("--from")}:`));
714
+ console.error(chalk.gray(` rebase db pull --from ${targetFlag}`));
715
+ process.exit(1);
716
+ }
717
+ const prepared = await prepareDatabaseEnv(projectRoot, {
718
+ flagDocker: rawArgs.includes("--docker"),
719
+ onProgress: (message) => console.log(chalk.gray(` ${message}`))
720
+ });
721
+ const target = databaseUrlOf(prepared, readEnvFile(projectRoot)) ?? "";
722
+ if (!target) {
723
+ console.error(chalk.red("✗ No local database to pull into."));
724
+ console.error(chalk.gray(" Set DATABASE_URL in .env, or run `rebase dev` to start the managed one."));
725
+ process.exit(1);
726
+ }
727
+ const plan = {
728
+ source,
729
+ target,
730
+ anonymize,
731
+ schemas
732
+ };
733
+ console.log("");
734
+ console.log(chalk.bold(" This will replace your local database."));
735
+ console.log(` ${chalk.gray("From")} ${describeTarget(source)}`);
736
+ console.log(` ${chalk.gray("Into")} ${describeTarget(target)}${prepared.dataDir ? chalk.gray(` (${prepared.dataDir})`) : ""}`);
737
+ console.log(` ${chalk.gray("Data")} ${anonymize ? "personal-looking columns will be overwritten after the copy" : chalk.yellow("copied as-is, including any personal data")}`);
738
+ if (schemas.length > 0) console.log(` ${chalk.gray("Schemas")} ${schemas.join(", ")}`);
739
+ console.log("");
740
+ if (!rawArgs.includes("--yes") && !rawArgs.includes("-y")) {
741
+ if (!process.stdin.isTTY) {
742
+ console.error(chalk.red("✗ This replaces the local database and cannot prompt here."));
743
+ console.error(chalk.yellow(" Re-run with --yes if that is what you intend."));
744
+ process.exit(1);
745
+ }
746
+ const { confirmed } = await inquirer.prompt([{
747
+ type: "confirm",
748
+ name: "confirmed",
749
+ message: "Continue?",
750
+ default: false
751
+ }]);
752
+ if (!confirmed) {
753
+ console.log(chalk.gray(" Nothing was changed."));
754
+ return;
755
+ }
756
+ }
757
+ const dumpFile = path.join(os.tmpdir(), `rebase-pull-${process.pid}.dump`);
758
+ let failure = null;
759
+ let anonymizeFailure = null;
760
+ try {
761
+ console.log(chalk.gray(" Dumping…"));
762
+ await execa("pg_dump", [
763
+ ...dumpArgs(plan),
764
+ "--file",
765
+ dumpFile
766
+ ], {
767
+ stdio: [
768
+ "ignore",
769
+ "inherit",
770
+ "inherit"
771
+ ],
772
+ env: dumpEnv(plan)
773
+ });
774
+ console.log(chalk.gray(" Restoring…"));
775
+ const restored = restoreOutcome(await execa("pg_restore", restoreArgs(plan, dumpFile), {
776
+ env: restoreEnv(plan),
777
+ stdin: "ignore",
778
+ stdout: "inherit",
779
+ stderr: ["pipe", "inherit"],
780
+ reject: false
781
+ }));
782
+ failure = restored.failure;
783
+ if (anonymize && restored.started) anonymizeFailure = await anonymizeTarget(target, describeTarget(source), prepared.database.kind);
784
+ if (restored.started) await restoreAppRole(target);
785
+ } finally {
786
+ fs.rmSync(dumpFile, { force: true });
787
+ }
788
+ if (anonymizeFailure) {
789
+ for (const line of anonymizeFailure) console.error(line);
790
+ if (failure) console.error(chalk.red(`✗ ${failure}`));
791
+ process.exit(1);
792
+ }
793
+ if (failure) {
794
+ console.error(chalk.red(`✗ ${failure}`));
795
+ console.error(chalk.yellow(` The local database holds an incomplete copy of ${describeTarget(source)}.`));
796
+ console.error(chalk.gray(" Fix what the errors above name — often an extension or a role the source has — and pull again."));
797
+ process.exit(1);
798
+ }
799
+ console.log(chalk.green("✓ Local database now holds a copy of " + describeTarget(source)));
800
+ }
801
+ /**
802
+ * Give the restored copy back the privileges `pg_dump` stripped.
803
+ *
804
+ * A pull without this ends on a green tick and hands over a database the
805
+ * application cannot read: `--no-privileges` removes every GRANT, so the copy
806
+ * has the source's RLS policies and none of the grants behind them, and the
807
+ * first query as `rebase_user` fails with `permission denied`. Measured — 68
808
+ * policies and 60 grants in, 68 policies and 0 grants out.
809
+ *
810
+ * `ensureAppRole` is the routine boot runs and `rebase db push` runs, so the
811
+ * pulled database ends up in the state a booted one is in, and there is no
812
+ * second description of these grants to drift. `detectConnectionPosture` gates
813
+ * it the same way `db push` does: a connection that cannot create roles reports
814
+ * that rather than failing the pull, which has already succeeded by this point.
815
+ *
816
+ * Failure here is a warning, not an error. The data is restored and correct; a
817
+ * missing grant is repaired by the next `rebase dev` or `rebase db push`, and
818
+ * saying so beats unwinding a copy that is fine.
819
+ */
820
+ async function restoreAppRole(target) {
821
+ const { Client } = await import("pg");
822
+ const { provisionableSchemas } = await import("./pull-CrGYMEsy.js");
823
+ const client = new Client({ connectionString: target });
824
+ client.on("error", () => void 0);
825
+ try {
826
+ await client.connect();
827
+ const { detectConnectionPosture, ensureAppRole, REBASE_USER_ROLE } = await import("@rebasepro/server-postgres");
828
+ const runSql = async (text) => (await client.query(text)).rows;
829
+ if (!(await detectConnectionPosture(runSql)).privileged) {
830
+ console.log(chalk.yellow(` ⚠ Could not re-grant the "${REBASE_USER_ROLE}" role — this connection may not create roles.`));
831
+ console.log(chalk.gray(" The copy has its RLS policies but no privileges behind them;"));
832
+ console.log(chalk.gray(" `rebase dev` or `rebase db push` will provision them."));
833
+ return;
834
+ }
835
+ const { rows } = await client.query("SELECT nspname AS \"schema\" FROM pg_namespace");
836
+ const schemas = provisionableSchemas(rows);
837
+ await ensureAppRole(runSql, schemas);
838
+ console.log(chalk.gray(` ✓ Re-granted "${REBASE_USER_ROLE}" on ${schemas.length} schema(s) — pg_dump strips privileges.`));
839
+ } catch (error) {
840
+ console.log(chalk.yellow(` ⚠ Restored, but could not re-grant "rebase_user": ${error instanceof Error ? error.message : String(error)}`));
841
+ console.log(chalk.gray(" Run `rebase db push` (or start `rebase dev`) to provision it."));
842
+ } finally {
843
+ await client.end().catch(() => void 0);
844
+ }
845
+ }
846
+ /**
847
+ * Anonymize the restored copy, and say what happened if that did not work.
848
+ *
849
+ * Returns null when the copy is anonymized, and otherwise the lines that say —
850
+ * in red, because `--anonymize` was the developer saying this data must not
851
+ * arrive as it is — what state the local database is in now: emptied of what
852
+ * could not be anonymized, or, when even that failed, holding real data that
853
+ * has to be deleted before anything else.
854
+ */
855
+ async function anonymizeTarget(target, source, kind) {
856
+ const { Client } = await import("pg");
857
+ const { anonymizeCopy } = await import("./pull-CrGYMEsy.js");
858
+ const deleteIt = kind === "managed" ? `Delete it now: ${chalk.cyan("rebase db reset --yes")}` : kind === "docker" ? `Delete it now: ${chalk.cyan("docker compose down -v")}` : "Delete it now: drop the restored tables, or the database, before anything else reads it.";
859
+ const holdsRealData = (reason) => [
860
+ chalk.red(`✗ The copy could not be anonymized: ${reason}`),
861
+ chalk.red.bold(` The local database holds an UN-ANONYMIZED copy of ${source}, personal data included.`),
862
+ chalk.yellow(` ${deleteIt}`)
863
+ ];
864
+ const client = new Client({ connectionString: target });
865
+ client.on("error", () => void 0);
866
+ try {
867
+ await client.connect();
868
+ } catch (error) {
869
+ return holdsRealData(error instanceof Error ? error.message : String(error));
870
+ }
871
+ try {
872
+ const outcome = await anonymizeCopy(client);
873
+ if (outcome.ok) {
874
+ console.log(chalk.green(` ✓ Anonymized ${outcome.tables.length} table(s).`));
875
+ console.log(chalk.gray(" Name-based and best-effort: a free-text column may still hold personal data."));
876
+ return null;
877
+ }
878
+ if (outcome.emptyError !== null) return [...holdsRealData(outcome.error), chalk.red(` Emptying the affected tables failed too: ${outcome.emptyError}`)];
879
+ return [
880
+ chalk.red(`✗ The copy could not be anonymized: ${outcome.error}`),
881
+ chalk.yellow(" Nothing was anonymized — the pass is one transaction — so the tables it would have"),
882
+ chalk.yellow(" rewritten were emptied instead, with every row that references them:"),
883
+ ...outcome.emptied.length > 0 ? [chalk.gray(` ${outcome.emptied.join(", ")}`)] : [],
884
+ chalk.gray(` The rest of the copy of ${source} is in place. Fix that error and pull again.`)
885
+ ];
886
+ } finally {
887
+ await client.end().catch(() => void 0);
888
+ }
889
+ }
890
+ /**
891
+ * Start the compose database a `db … --docker` was asked to talk to.
892
+ *
893
+ * `--docker` resolved the compose URL and stopped there, so every `db`
894
+ * subcommand carrying it reached a container nobody had started —
895
+ * `ECONNREFUSED 127.0.0.1:5436`, two lines, no diagnosis — including the
896
+ * commands the managed-database refusals send readers to `--docker` for.
897
+ *
898
+ * `rebase dev --docker`'s preflight, called with the compose URL and nothing
899
+ * to push: this is not a schema step, and `rebase db push --docker` is the
900
+ * push. A failure here is reported and not fatal — the command runs and its
901
+ * own connection error follows, which is the same contract `dev` keeps.
902
+ */
903
+ async function ensureDockerDatabase(projectRoot, rawArgs) {
904
+ const { ensureDevDatabase } = await import("./dev-preflight-B-LYyBf1.js");
905
+ const { resolveProjectDatabase } = await import("./prepare-CDN6lSpz.js");
906
+ const resolved = resolveProjectDatabase(projectRoot, {
907
+ flagUrl: readFlagValue(rawArgs, "--database-url"),
908
+ flagDocker: rawArgs.includes("--docker")
909
+ });
910
+ if (resolved.kind !== "docker") return;
911
+ const composeUrl = resolved.url;
912
+ if (!composeUrl) return;
913
+ await ensureDevDatabase({
914
+ projectRoot,
915
+ databaseUrl: composeUrl,
916
+ disabled: false,
917
+ hasCollections: false,
918
+ pushSchema: async () => void 0,
919
+ log: (message) => console.log(message)
920
+ });
921
+ }
922
+ /**
923
+ * You cannot delete the branch you are standing on.
924
+ *
925
+ * Not a new rule — it was always refused, by a message about a database the
926
+ * developer had never named. After `switch feature_x` the resolved DSN *is*
927
+ * `rb_feature_x`, so `BranchService.deleteBranch` compared it against the
928
+ * connected database, found them equal, and answered `✗ Cannot delete the main
929
+ * database.` The main database is precisely what the developer was not on.
930
+ *
931
+ * Answered here because the pointer is the CLI's: the driver runs as a child
932
+ * process that has never heard of it, and cannot tell "the branch you are on"
933
+ * from "the main database" — those are the same connection string to it.
934
+ */
935
+ async function refuseDeletingActiveBranch(projectRoot, rawArgs) {
936
+ const [, , , name] = commandWords(rawArgs, "db");
937
+ if (!name) return;
938
+ const { readActiveBranch } = await import("./branch-pointer-DvSHBjjz.js");
939
+ const active = readActiveBranch(projectRoot);
940
+ if (active?.name !== name) return;
941
+ const off = "rebase db branch switch --off";
942
+ const del = `rebase db branch delete ${name}`;
943
+ const column = Math.max(29, del.length) + 4;
944
+ console.error("");
945
+ console.error(chalk.red(`✗ You are on branch "${name}" — leave it before deleting it.`));
946
+ console.error("");
947
+ console.error(chalk.gray(` Every database command in this checkout is pointed at ${active.database},`));
948
+ console.error(chalk.gray(" including this one, so the delete would be asking that database to drop"));
949
+ console.error(chalk.gray(" itself."));
950
+ console.error("");
951
+ console.error(` ${chalk.cyan(off)}${" ".repeat(column - 29)}back to the main database`);
952
+ console.error(` ${chalk.cyan(del)}${" ".repeat(column - del.length)}then this works`);
953
+ console.error("");
954
+ process.exit(1);
955
+ }
956
+ /** The `branch` actions that read or write the registry — every one but `switch`. */
957
+ var REGISTRY_ACTIONS = /* @__PURE__ */ new Set([
958
+ "list",
959
+ "create",
960
+ "delete",
961
+ "info",
962
+ "prune"
963
+ ]);
964
+ /**
965
+ * Every `branch` action runs against the parent, where the registry lives.
966
+ *
967
+ * `rebase.branches` is written in the database branches are made *from*, and a
968
+ * branch is a `CREATE DATABASE … TEMPLATE` copy — so the copy carries a
969
+ * snapshot of that table taken at branch time, and every branch made since is
970
+ * missing from it. After `switch feature_x`, `branch list` connected to
971
+ * `rb_feature_x` and answered `No branches found. Create one with: rebase db
972
+ * branch create <name>` while `branch switch` with no argument, one command
973
+ * earlier, had said `● On branch feature_x`.
974
+ *
975
+ * The same snapshot answered `create`, `delete`, `info` and `prune`: a branch
976
+ * created from a switched checkout was recorded only in the copy, so `list`
977
+ * never showed it and `delete` from the main checkout said "not found" while
978
+ * its database stayed; `info` and `delete` could not find a branch made after
979
+ * the one this checkout is on. The Branches pane in Studio was fixed the same
980
+ * way (`REBASE_BRANCH_PARENT_DATABASE`).
981
+ *
982
+ * `create` still copies what this checkout is on — a branch of the branch, a
983
+ * thing the developer asked for by switching first — so it is given
984
+ * `--from <the branch's database>` unless it names a source itself.
985
+ *
986
+ * Resolved with `branch: null` — the same rule `switch` uses to find what to
987
+ * branch *from* — and relayed as `--database-url`, which the driver honours
988
+ * over anything it would resolve for itself.
989
+ */
990
+ async function onParentDatabase(projectRoot, rawArgs, action) {
991
+ if (readFlagValue(rawArgs, "--database-url") !== null) return rawArgs;
992
+ const { readActiveBranch } = await import("./branch-pointer-DvSHBjjz.js");
993
+ const active = readActiveBranch(projectRoot);
994
+ if (!active) return rawArgs;
995
+ const { readEnvFile } = await import("./project-Wp2zoyeN.js").then((n) => n.u);
996
+ const { resolveDevDatabase } = await import("./resolve-B2O-wKKk.js");
997
+ const { resolveComposeUrl } = await import("./prepare-CDN6lSpz.js");
998
+ const { readLastDevDocker } = await import("./last-dev-database-B58g89uA.js");
999
+ const envFile = readEnvFile(projectRoot);
1000
+ const parent = resolveDevDatabase({
1001
+ flagDocker: rawArgs.includes("--docker"),
1002
+ lastDevDocker: readLastDevDocker(projectRoot),
1003
+ env: process.env,
1004
+ envFile,
1005
+ branch: null,
1006
+ composeUrl: resolveComposeUrl(projectRoot, envFile)
1007
+ });
1008
+ const url = (parent.kind === "managed" ? null : parent.url)?.trim();
1009
+ if (!url) return rawArgs;
1010
+ console.log(chalk.gray(` ● On branch ${active.name} — using the main database, where the branch registry lives.`));
1011
+ const from = action === "create" && readFlagValue(rawArgs, "--from") === null ? ["--from", active.database] : [];
1012
+ return [
1013
+ ...rawArgs,
1014
+ ...from,
1015
+ "--database-url",
1016
+ url
1017
+ ];
1018
+ }
1019
+ /**
1020
+ * `rebase db branch switch <name>` — point this checkout at a branch.
1021
+ *
1022
+ * The step branching was missing. `create` copied the database in about a
1023
+ * second and then printed `Database: rb_feature_auth` and stopped: there was no
1024
+ * `switch`, no `--branch` on `rebase dev`, and no `REBASE_BRANCH`. The only way
1025
+ * to use a branch was to hand-edit `DATABASE_URL`, while the documentation said
1026
+ * "the CLI updates your local development configuration" — it did not, and the
1027
+ * `.env` was byte-identical afterwards.
1028
+ *
1029
+ * Three things it insists on:
1030
+ *
1031
+ * - **The branch has to exist.** Writing a pointer to a database that was never
1032
+ * created turns a typo into a connection error on the *next* command, which
1033
+ * is the one place it cannot be explained. Checked against
1034
+ * `rebase.branches` and `pg_database` both, because a branch dropped outside
1035
+ * Rebase leaves the metadata row behind.
1036
+ *
1037
+ * - **It says what changed, and how to undo it.** A command that silently
1038
+ * redirects every subsequent database operation owes the reader the database
1039
+ * name it moved to and the words that move it back.
1040
+ *
1041
+ * - **It never edits `.env`.** See `branch-pointer.ts`.
1042
+ */
1043
+ async function switchBranch(projectRoot, rawArgs) {
1044
+ const { branchDatabaseName, clearActiveBranch, databaseNameOf, readActiveBranch, writeActiveBranch } = await import("./branch-pointer-DvSHBjjz.js");
1045
+ const { readEnvFile } = await import("./project-Wp2zoyeN.js").then((n) => n.u);
1046
+ const { resolveDevDatabase } = await import("./resolve-B2O-wKKk.js");
1047
+ const { resolveComposeUrl } = await import("./prepare-CDN6lSpz.js");
1048
+ const { readLastDevDocker } = await import("./last-dev-database-B58g89uA.js");
1049
+ const goingOff = rawArgs.includes("--off") || rawArgs.includes("--main");
1050
+ const name = commandWords(rawArgs, "db")[3];
1051
+ const envFile = readEnvFile(projectRoot);
1052
+ const resolved = resolveDevDatabase({
1053
+ flagUrl: readFlagValue(rawArgs, "--database-url"),
1054
+ flagDocker: rawArgs.includes("--docker"),
1055
+ lastDevDocker: readLastDevDocker(projectRoot),
1056
+ env: process.env,
1057
+ envFile,
1058
+ branch: null,
1059
+ composeUrl: resolveComposeUrl(projectRoot, envFile)
1060
+ });
1061
+ const base = (resolved.kind === "managed" ? null : resolved.url)?.trim() || void 0;
1062
+ if (!name && !goingOff) {
1063
+ const active = readActiveBranch(projectRoot);
1064
+ console.log("");
1065
+ if (active) {
1066
+ console.log(` ${chalk.green("●")} On branch ${chalk.bold(active.name)} ${chalk.gray(`(${active.database})`)}`);
1067
+ console.log(chalk.gray(` Back to the main database: ${chalk.cyan("rebase db branch switch --off")}`));
1068
+ } else {
1069
+ const main = base ? databaseNameOf(base) : null;
1070
+ console.log(` ${chalk.gray("●")} On the main database${main ? chalk.gray(` (${main})`) : ""}`);
1071
+ console.log(chalk.gray(` Switch to a branch: ${chalk.cyan("rebase db branch switch <name>")}`));
1072
+ }
1073
+ console.log("");
1074
+ return;
1075
+ }
1076
+ if (goingOff) {
1077
+ const active = readActiveBranch(projectRoot);
1078
+ clearActiveBranch(projectRoot);
1079
+ console.log("");
1080
+ console.log(active ? chalk.green(` ✓ Back on the main database${base ? ` (${databaseNameOf(base)})` : ""}.`) : chalk.gray(" Already on the main database."));
1081
+ console.log("");
1082
+ return;
1083
+ }
1084
+ if (!base) {
1085
+ console.error(chalk.red("✗ There is no database to branch from."));
1086
+ console.error(chalk.gray(resolved.kind === "managed" ? " This project is on the managed development database, which serves exactly one —" : " --docker needs a docker-compose.yml with a db service, and this project has none —"));
1087
+ console.error(chalk.gray(" and branching copies a database. Set DATABASE_URL in .env or in your"));
1088
+ console.error(chalk.gray(" shell, or run `rebase dev --docker`."));
1089
+ process.exit(1);
1090
+ }
1091
+ const database = branchDatabaseName(name);
1092
+ const { Client } = await import("pg");
1093
+ const client = new Client({ connectionString: base });
1094
+ try {
1095
+ await client.connect();
1096
+ } catch (error) {
1097
+ console.error(chalk.red(`✗ Could not reach the database to check that branch "${name}" exists.`));
1098
+ console.error(chalk.gray(` ${error instanceof Error ? error.message : String(error)}`));
1099
+ process.exit(1);
1100
+ }
1101
+ try {
1102
+ const { rows } = await client.query(`SELECT EXISTS (SELECT 1 FROM rebase.branches WHERE name = $1) AS registered,
1103
+ EXISTS (SELECT 1 FROM pg_database WHERE datname = $2) AS present`, [name, database]).catch(() => ({ rows: [{
1104
+ registered: false,
1105
+ present: false
1106
+ }] }));
1107
+ const { registered, present } = rows[0] ?? {
1108
+ registered: false,
1109
+ present: false
1110
+ };
1111
+ if (!present) {
1112
+ console.error(chalk.red(`✗ Branch "${name}" does not exist.`));
1113
+ console.error(registered ? chalk.gray(` It is registered but its database (${database}) is gone — someone dropped it outside Rebase.`) : chalk.gray(` ${chalk.cyan("rebase db branch list")} shows the ones that do.`));
1114
+ process.exit(1);
1115
+ }
1116
+ } finally {
1117
+ await client.end();
1118
+ }
1119
+ writeActiveBranch(projectRoot, {
1120
+ name,
1121
+ database
1122
+ });
1123
+ console.log("");
1124
+ console.log(chalk.green(` ✓ Switched to branch "${name}".`));
1125
+ console.log(chalk.gray(` Database: ${database}`));
1126
+ console.log(chalk.gray(" Every rebase command in this checkout now uses it — dev, db push, migrate."));
1127
+ console.log(chalk.gray(` Back to the main database: ${chalk.cyan("rebase db branch switch --off")}`));
1128
+ console.log("");
1129
+ }
1130
+ /**
1131
+ * What each `rebase db <action>` does and takes.
1132
+ *
1133
+ * Kept here rather than delegated to the driver because the driver is reached
1134
+ * by *running* it — which is exactly what `--help` must not do. The page is
1135
+ * deliberately short: the authority on a flag is the command's own spec, and
1136
+ * `check-doc-commands.mjs` holds every command written in this repository's
1137
+ * markdown to it. What a reader needs from here is which subcommands exist and
1138
+ * what the destructive ones want before they will run.
1139
+ */
1140
+ /** The database flags every driver command takes; `db url --help` has its own wording. */
1141
+ var DATABASE_FLAGS_HELP = "--database-url <url> names the database; --docker uses the compose one, starting it if needed.";
1142
+ var DB_ACTION_HELP = {
1143
+ push: {
1144
+ usage: "rebase db push [--collections <dir>] [--dry-run] [--allow-destructive] [--yes]",
1145
+ summary: "Apply the schema straight to the database. Development only — it does not write a migration.",
1146
+ notes: [
1147
+ "--dry-run prints the SQL and applies nothing. Read it before you approve it.",
1148
+ "A change that drops data, or re-keys a table (every row gets a new id), needs --allow-destructive.",
1149
+ `--collections <dir>: ${COLLECTIONS_FLAG_HELP}.`,
1150
+ DATABASE_FLAGS_HELP
1151
+ ]
1152
+ },
1153
+ generate: {
1154
+ usage: "rebase db generate [--collections <dir>]",
1155
+ summary: "Generate the Drizzle schema, the Postgres DDL and a SQL migration file from the collections.",
1156
+ notes: [
1157
+ "A migration that drops or narrows data is named when it is written. It is still written.",
1158
+ `--collections <dir>: ${COLLECTIONS_FLAG_HELP}.`,
1159
+ DATABASE_FLAGS_HELP
1160
+ ]
1161
+ },
1162
+ migrate: {
1163
+ usage: "rebase db migrate [--baseline <version>] [--refuse-destructive] [amount]",
1164
+ summary: "Run the pending migration files against the database.",
1165
+ notes: [
1166
+ "--refuse-destructive dry-runs the pending files and applies nothing when one drops or narrows data.",
1167
+ "--baseline <version> records that version as already applied and starts from the next one.",
1168
+ "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.",
1169
+ "The version is the numeric prefix of a file in drizzle/migrations.",
1170
+ DATABASE_FLAGS_HELP
1171
+ ]
1172
+ },
1173
+ branch: {
1174
+ usage: "rebase db branch <create|list|switch|delete|info|prune> [name]",
1175
+ summary: "Database branching.",
1176
+ notes: [
1177
+ "create <name> [--from <source>] copies an existing database, files and all.",
1178
+ "switch <name> points this checkout at a branch; every later command uses it.",
1179
+ "switch with no name reports where you are; switch --off returns to the main database.",
1180
+ "prune [--older-than <14|14d|2w>] removes branches nothing is using, and the entries that drifted.",
1181
+ "prune --include-dev-diff also removes the Atlas scratch databases `db push` leaves behind.",
1182
+ "prune asks before it drops anything; --yes, -y answers for you, which is the form a CI job wants.",
1183
+ "--force disconnects other sessions first — Postgres refuses to copy or drop a database anything is connected to, usually your own `rebase dev`."
1184
+ ]
1185
+ },
1186
+ backup: {
1187
+ usage: "rebase db backup [--out <path|s3://…>]",
1188
+ summary: "Create a pg_dump backup. --out is resolved against the directory you are standing in.",
1189
+ notes: ["--output is accepted as an alias, as it is on `rebase build`.", "`rebase db backup list` lists them, the way `rebase cloud db backup list` does."]
1190
+ },
1191
+ backups: {
1192
+ usage: "rebase db backups list [--out <path|s3://…>]",
1193
+ summary: "List stored backups.",
1194
+ notes: ["`rebase db backup list` is the same command, spelled the cloud family's way."]
1195
+ },
1196
+ url: {
1197
+ usage: "rebase db url [--database-url <url>] [--docker]",
1198
+ summary: "Print the connection string this project uses. Nothing else goes to stdout, so it pipes.",
1199
+ notes: [
1200
+ "psql \"$(rebase db url)\"",
1201
+ "Starts the managed database if it is not already running.",
1202
+ "--database-url and --docker answer for the database `rebase dev` would pick with the same flag.",
1203
+ "After `rebase dev --docker` it prints the Docker database without the flag, as every db command does."
1204
+ ]
1205
+ },
1206
+ restore: {
1207
+ usage: "rebase db restore <dump> [--target-db <name>] [--create-db] --yes",
1208
+ summary: "Restore a backup with pg_restore.",
1209
+ notes: ["Destructive, and refuses to run without --yes."]
1210
+ },
1211
+ pull: {
1212
+ usage: "rebase db pull --from <url> [--schema <name>] [--anonymize] [--yes]",
1213
+ summary: "Copy another database into local development. One-directional by design — it can never push.",
1214
+ notes: ["The target is not selectable: --database-url is refused, so this can never write to a remote database."]
1215
+ },
1216
+ stop: {
1217
+ usage: "rebase db stop",
1218
+ summary: "Stop the managed development database. Data is kept."
1219
+ },
1220
+ reset: {
1221
+ usage: "rebase db reset [--yes]",
1222
+ summary: "Delete the managed development database and start over.",
1223
+ notes: ["Destructive, and the data exists only on this machine."]
1224
+ }
1225
+ };
1226
+ /** Every subcommand the family dispatches — the help table's keys. */
1227
+ var DB_SUBCOMMANDS = Object.keys(DB_ACTION_HELP);
1228
+ function printDbHelp(action) {
1229
+ const entry = action ? DB_ACTION_HELP[action] : void 0;
1230
+ if (entry) {
1231
+ console.log(`
1232
+ ${chalk.bold(`rebase db ${action}`)}
1233
+
1234
+ ${entry.summary}
1235
+
1236
+ ${chalk.green.bold("Usage")}
1237
+ ${chalk.blue(entry.usage)}
1238
+ ${entry.notes?.length ? `\n${chalk.green.bold("Notes")}\n${entry.notes.map((n) => ` ${chalk.gray(`• ${n}`)}`).join("\n")}\n` : ""}
1239
+ ${chalk.gray("Run `rebase db --help` for every subcommand.")}
1240
+ `);
1241
+ return;
1242
+ }
1243
+ console.log(`
1244
+ ${chalk.bold("rebase db")} — Database management commands
1245
+
1246
+ ${chalk.green.bold("Usage")}
1247
+ rebase db ${chalk.blue("<command>")} [options]
1248
+
1249
+ ${chalk.green.bold("Commands")}
1250
+ ${chalk.gray("(Commands are provided by your active database driver plugin)")}
1251
+ ${chalk.blue.bold("url")} Print the connection string this project uses (pipes into psql)
1252
+ ${chalk.blue.bold("pull")} Copy another database into local dev (--from <url>, --anonymize)
1253
+ ${chalk.blue.bold("stop")} Stop the managed development database (data is kept)
1254
+ ${chalk.blue.bold("reset")} Delete the managed development database and start over
1255
+ ${chalk.blue.bold("push")} Apply schema directly to database (development)
1256
+ ${chalk.blue.bold("generate")} Generate migration files
1257
+ ${chalk.blue.bold("migrate")} Run pending migrations
1258
+ ${chalk.blue.bold("branch")} Database branching (create, list, switch, delete, info, prune)
1259
+ ${chalk.blue.bold("backup")} Create a backup with pg_dump (--out <path|s3://…>)
1260
+ ${chalk.blue.bold("restore")} Restore a backup with pg_restore (destructive; needs --yes)
1261
+ ${chalk.blue.bold("backups")} List stored backups (db backup list is the same)
1262
+
1263
+ ${chalk.green.bold("Examples")}
1264
+ ${dbExamples(devDatabaseKind())}
1265
+ ${chalk.gray("# Back up to a local directory, then to object storage")}
1266
+ rebase db backup --out ./backups
1267
+ rebase db backup --out s3://my-private-bucket/backups
1268
+
1269
+ ${chalk.gray("# Restore into a fresh database (safe: does not touch the live one)")}
1270
+ rebase db restore ./backups/rebase-app-20260714T030000Z.dump --create-db --target-db app_restored
1271
+ `);
1272
+ }
1273
+ /**
1274
+ * The examples, which are not the same on the managed development database.
1275
+ *
1276
+ * Every one of the four the help used to lead with — `db push`, `db generate`,
1277
+ * `db migrate`, `db branch` — is refused there, by guards in this same file
1278
+ * that explain exactly why. So on the project the CLI had just scaffolded, the
1279
+ * first thing `rebase db --help` offered was a command that answers with a
1280
+ * refusal, and the reader's most likely conclusion is that their install is
1281
+ * broken.
1282
+ *
1283
+ * Exported for its test.
1284
+ */
1285
+ function dbExamples(kind) {
1286
+ if (kind === "managed") return ` ${chalk.gray("# Quick development workflow (this project is on the managed database)")}
1287
+ rebase schema generate
1288
+ rebase dev ${chalk.gray("# boot applies your collections to it, additively")}
1289
+ rebase db push ${chalk.gray("# also drops, renames and narrows columns")}
1290
+
1291
+ ${chalk.gray("# branch needs a Postgres of your own")}
1292
+ rebase dev --docker ${chalk.gray("# starts one; or uncomment DATABASE_URL in .env")}
1293
+
1294
+ `;
1295
+ return ` ${chalk.gray("# Quick development workflow")}
1296
+ rebase schema generate && rebase db push
1297
+
1298
+ ${chalk.gray("# Production migration workflow")}
1299
+ rebase db generate
1300
+ rebase db migrate
1301
+
1302
+ ${chalk.gray("# Create a database branch and work on it")}
1303
+ rebase db branch create feature_auth
1304
+ rebase db branch switch feature_auth
1305
+ rebase db branch switch --off
1306
+
1307
+ `;
1308
+ }
1309
+ //#endregion
1310
+ export { DB_SUBCOMMANDS, absolutizeLocalPathArgs, dbCommand, ensureDockerDatabase, argsFromCommand as n, resolveDriverCli, runDriverDbCommand, runDriverSchemaCommand, spawnDriverCli, reportSpawnFailure as t };
1311
+
1312
+ //# sourceMappingURL=db-B7RuNuaQ.js.map