@rebasepro/cli 0.25.0 → 0.26.0

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 (190) hide show
  1. package/README.md +2 -1
  2. package/bin/rebase.js +143 -4
  3. package/dist/{agent-setup-B5AKHOgt.js → agent-setup-D9mHRZ5R.js} +125 -3
  4. package/dist/agent-setup-D9mHRZ5R.js.map +1 -0
  5. package/dist/{api-keys-Tm7zvAPe.js → api-keys-CyJ26KEJ.js} +41 -10
  6. package/dist/api-keys-CyJ26KEJ.js.map +1 -0
  7. package/dist/{apps-BsU_ILbP.js → apps-CnLDV5b6.js} +6 -7
  8. package/dist/{apps-BsU_ILbP.js.map → apps-CnLDV5b6.js.map} +1 -1
  9. package/dist/{atlas-dev-database-OWtqnG7W.js → atlas-dev-database-BODqdCWt.js} +4 -4
  10. package/dist/{atlas-dev-database-OWtqnG7W.js.map → atlas-dev-database-BODqdCWt.js.map} +1 -1
  11. package/dist/{auth-Vl2hFKXP.js → auth-dII2jCO1.js} +10 -8
  12. package/dist/auth-dII2jCO1.js.map +1 -0
  13. package/dist/{branch-pointer-9DnwkFJJ.js → branch-pointer-BQUF6lYa.js} +1 -1
  14. package/dist/{build-BBgT8EJZ.js → build-Cza7ZQrp.js} +6 -7
  15. package/dist/{build-BBgT8EJZ.js.map → build-Cza7ZQrp.js.map} +1 -1
  16. package/dist/{bundle-DtCCCr4w.js → bundle-C6yEtMJ-.js} +53 -5
  17. package/dist/bundle-C6yEtMJ-.js.map +1 -0
  18. package/dist/bundle.d.ts +14 -0
  19. package/dist/{cloud-BpH0_bmV.js → cloud-BdnmqQaZ.js} +8528 -4342
  20. package/dist/cloud-BdnmqQaZ.js.map +1 -0
  21. package/dist/collections-dir-DlvDhime.js +69 -0
  22. package/dist/collections-dir-DlvDhime.js.map +1 -0
  23. package/dist/commands/agent-setup.d.ts +58 -0
  24. package/dist/commands/api-keys.d.ts +13 -0
  25. package/dist/commands/cloud/activity.d.ts +25 -0
  26. package/dist/commands/cloud/app-key.d.ts +18 -0
  27. package/dist/commands/cloud/auth.d.ts +1 -0
  28. package/dist/commands/cloud/billing-invoices.d.ts +39 -0
  29. package/dist/commands/cloud/claim.d.ts +7 -0
  30. package/dist/commands/cloud/context.d.ts +115 -6
  31. package/dist/commands/cloud/deploy-summary.d.ts +162 -0
  32. package/dist/commands/cloud/deploy.d.ts +64 -0
  33. package/dist/commands/cloud/env.d.ts +24 -0
  34. package/dist/commands/cloud/index.d.ts +13 -1
  35. package/dist/commands/cloud/init.d.ts +143 -0
  36. package/dist/commands/cloud/login-flow.d.ts +51 -0
  37. package/dist/commands/cloud/notifications.d.ts +28 -0
  38. package/dist/commands/cloud/orgs.d.ts +13 -0
  39. package/dist/commands/cloud/previews.d.ts +123 -0
  40. package/dist/commands/cloud/resources.d.ts +68 -14
  41. package/dist/commands/cloud/runtime-logs.d.ts +176 -0
  42. package/dist/commands/cloud/service-key.d.ts +15 -0
  43. package/dist/commands/cloud/token-capabilities.d.ts +61 -8
  44. package/dist/commands/cloud/tokens.d.ts +18 -3
  45. package/dist/commands/cloud/usage.d.ts +63 -0
  46. package/dist/commands/dev.d.ts +22 -0
  47. package/dist/commands/doctor.d.ts +1 -1
  48. package/dist/commands/generate-view.d.ts +94 -0
  49. package/dist/commands/generate_sdk.d.ts +19 -2
  50. package/dist/commands/init.d.ts +20 -0
  51. package/dist/commands/skills.d.ts +4 -3
  52. package/dist/commands/start.d.ts +10 -0
  53. package/dist/commands/storage.d.ts +4 -0
  54. package/dist/commands/upgrade.d.ts +12 -0
  55. package/dist/commands/verify.d.ts +96 -0
  56. package/dist/{consent-ClRHmcxf.js → consent-BD7F29T3.js} +2 -2
  57. package/dist/{consent-ClRHmcxf.js.map → consent-BD7F29T3.js.map} +1 -1
  58. package/dist/{console-CEGm0XNc.js → console-BXB6-8GT.js} +12 -6
  59. package/dist/console-BXB6-8GT.js.map +1 -0
  60. package/dist/{context-CyflUrKg.js → context-GUxkZm-S.js} +482 -26
  61. package/dist/context-GUxkZm-S.js.map +1 -0
  62. package/dist/{daemon-CknkDjd6.js → daemon-Cp7oNXth.js} +160 -5
  63. package/dist/daemon-Cp7oNXth.js.map +1 -0
  64. package/dist/{daemon-entry-CbLRrgzy.js → daemon-entry-zOC1revO.js} +6 -3
  65. package/dist/daemon-entry-zOC1revO.js.map +1 -0
  66. package/dist/{db-CRNpA5mH.js → db-KzlqddGD.js} +101 -54
  67. package/dist/db-KzlqddGD.js.map +1 -0
  68. package/dist/{derive-CsoFGAnK.js → derive-ae9UOoOB.js} +2 -2
  69. package/dist/{derive-CsoFGAnK.js.map → derive-ae9UOoOB.js.map} +1 -1
  70. package/dist/{dev-C0pbMmhS.js → dev-DTqVMgB3.js} +231 -44
  71. package/dist/dev-DTqVMgB3.js.map +1 -0
  72. package/dist/dev-db/daemon.d.ts +41 -0
  73. package/dist/dev-db/pull.d.ts +33 -5
  74. package/dist/dev-db/state.d.ts +9 -0
  75. package/dist/{dev-preflight-unHpiYO1.js → dev-preflight-Cxv3TiD1.js} +73 -27
  76. package/dist/dev-preflight-Cxv3TiD1.js.map +1 -0
  77. package/dist/{dev-server-B1UYifZJ.js → dev-server-OJsUGZEB.js} +14 -3
  78. package/dist/dev-server-OJsUGZEB.js.map +1 -0
  79. package/dist/{doctor-CATRdWm6.js → doctor-BRWOlqeG.js} +14 -12
  80. package/dist/doctor-BRWOlqeG.js.map +1 -0
  81. package/dist/{eject-DuasTr-F.js → eject-DABcDnPN.js} +3 -4
  82. package/dist/{eject-DuasTr-F.js.map → eject-DABcDnPN.js.map} +1 -1
  83. package/dist/{fold-static-hDHtDfTq.js → fold-static-BnAK-anQ.js} +3 -3
  84. package/dist/{fold-static-hDHtDfTq.js.map → fold-static-BnAK-anQ.js.map} +1 -1
  85. package/dist/generate-view-IFwCADvb.js +662 -0
  86. package/dist/generate-view-IFwCADvb.js.map +1 -0
  87. package/dist/{generate_sdk-Cvg5jjJF.js → generate_sdk-BvcWvoUh.js} +49 -13
  88. package/dist/generate_sdk-BvcWvoUh.js.map +1 -0
  89. package/dist/index.es.js +58 -40
  90. package/dist/index.es.js.map +1 -1
  91. package/dist/{init-BWAwHPtz.js → init-CaU6GhwI.js} +50 -62
  92. package/dist/init-CaU6GhwI.js.map +1 -0
  93. package/dist/invoked-command-CG_rIa_o.js +55 -0
  94. package/dist/invoked-command-CG_rIa_o.js.map +1 -0
  95. package/dist/last-dev-database-DpW5dfoX.js +2 -0
  96. package/dist/{manifest-DRp0UVTj.js → manifest-BtzDy7KQ.js} +36 -3
  97. package/dist/{manifest-DRp0UVTj.js.map → manifest-BtzDy7KQ.js.map} +1 -1
  98. package/dist/{normalize-imports-BoBVh5tU.js → normalize-imports-D0zXlM6g.js} +3 -3
  99. package/dist/{normalize-imports-BoBVh5tU.js.map → normalize-imports-D0zXlM6g.js.map} +1 -1
  100. package/dist/{path-flags-BFgG9V6y.js → path-flags-DNvtEi2-.js} +5 -4
  101. package/dist/path-flags-DNvtEi2-.js.map +1 -0
  102. package/dist/{prepare-DdnU70z8.js → prepare-CTw9NEkh.js} +5 -4
  103. package/dist/{prepare-DdnU70z8.js.map → prepare-CTw9NEkh.js.map} +1 -1
  104. package/dist/project-CasK56vN.js +701 -0
  105. package/dist/project-CasK56vN.js.map +1 -0
  106. package/dist/{pull-C3PXduzl.js → pull-DDMpsZ5r.js} +131 -24
  107. package/dist/pull-DDMpsZ5r.js.map +1 -0
  108. package/dist/refusal-ReeeGP8a.js +26 -0
  109. package/dist/refusal-ReeeGP8a.js.map +1 -0
  110. package/dist/resolve-D647F1LA.js +2 -0
  111. package/dist/{resources-BdNRDEAy.js → resources-CPSC5Kcu.js} +4 -5
  112. package/dist/{resources-BdNRDEAy.js.map → resources-CPSC5Kcu.js.map} +1 -1
  113. package/dist/{schema-B0-p6T1O.js → schema-BSXwZSiI.js} +9 -8
  114. package/dist/schema-BSXwZSiI.js.map +1 -0
  115. package/dist/{skills-DfnTeyRz.js → skills-BU2flMOy.js} +52 -8
  116. package/dist/skills-BU2flMOy.js.map +1 -0
  117. package/dist/{start-BmEZkS0n.js → start-mVb6upwY.js} +20 -7
  118. package/dist/start-mVb6upwY.js.map +1 -0
  119. package/dist/{state-CCB-FAQ9.js → state-CYdBvnwA.js} +3 -2
  120. package/dist/state-CYdBvnwA.js.map +1 -0
  121. package/dist/static-syntax-check.d.ts +64 -0
  122. package/dist/{status-BJ26yZOo.js → status-BREvtzJm.js} +8 -9
  123. package/dist/{status-BJ26yZOo.js.map → status-BREvtzJm.js.map} +1 -1
  124. package/dist/{storage-DKPUBTWG.js → storage-DtOXGflp.js} +159 -16
  125. package/dist/storage-DtOXGflp.js.map +1 -0
  126. package/dist/{telemetry-EMFRVRQi.js → telemetry-CgwJPVMO.js} +2 -2
  127. package/dist/{telemetry-EMFRVRQi.js.map → telemetry-CgwJPVMO.js.map} +1 -1
  128. package/dist/{telemetry-m9czTNGR.js → telemetry-DwK5RQJl.js} +4 -4
  129. package/dist/{telemetry-m9czTNGR.js.map → telemetry-DwK5RQJl.js.map} +1 -1
  130. package/dist/{upgrade-DjihWuZL.js → upgrade-B7sVwL8S.js} +26 -4
  131. package/dist/{upgrade-DjihWuZL.js.map → upgrade-B7sVwL8S.js.map} +1 -1
  132. package/dist/utils/args.d.ts +32 -3
  133. package/dist/utils/boot-retry.d.ts +41 -0
  134. package/dist/utils/collections-dir.d.ts +14 -0
  135. package/dist/utils/dev-preflight.d.ts +34 -1
  136. package/dist/utils/dev-server.d.ts +11 -0
  137. package/dist/utils/path-flags.d.ts +2 -1
  138. package/dist/utils/project.d.ts +5 -1
  139. package/dist/utils/tool-stdio.d.ts +1 -1
  140. package/dist/utils/unknown-command.d.ts +4 -0
  141. package/dist/verify-D7UsV_qe.js +730 -0
  142. package/dist/verify-D7UsV_qe.js.map +1 -0
  143. package/package.json +9 -7
  144. package/templates/eject/backend/src/index.ts +9 -1
  145. package/templates/generated-schemas/ecommerce.ts +3 -0
  146. package/templates/overlays/baas/ai-instructions.md +13 -0
  147. package/templates/resource-graphs/blank.json +25 -0
  148. package/templates/resource-graphs/blog.json +28 -0
  149. package/templates/resource-graphs/ecommerce.json +28 -0
  150. package/templates/resource-graphs/headless.json +22 -0
  151. package/templates/template/.claude/hooks/post-edit-collection.sh +99 -0
  152. package/templates/template/.claude/settings.json +17 -0
  153. package/templates/template/.env.example +15 -5
  154. package/templates/template/ai-instructions.md +21 -1
  155. package/templates/template/config/collections/presets/ecommerce/index.ts +23 -0
  156. package/templates/template/docker-compose.yml +4 -1
  157. package/templates/template/frontend/package.json +1 -0
  158. package/templates/template/frontend/src/App.tsx +10 -9
  159. package/templates/views/AppView.tsx.tmpl +138 -0
  160. package/templates/views/EntityView.tsx.tmpl +64 -0
  161. package/templates/views/index.ts.tmpl +8 -0
  162. package/dist/agent-setup-B5AKHOgt.js.map +0 -1
  163. package/dist/api-keys-Tm7zvAPe.js.map +0 -1
  164. package/dist/args-BX0YD14a.js +0 -266
  165. package/dist/args-BX0YD14a.js.map +0 -1
  166. package/dist/auth-Vl2hFKXP.js.map +0 -1
  167. package/dist/bundle-DtCCCr4w.js.map +0 -1
  168. package/dist/cloud-BpH0_bmV.js.map +0 -1
  169. package/dist/console-CEGm0XNc.js.map +0 -1
  170. package/dist/context-CyflUrKg.js.map +0 -1
  171. package/dist/daemon-CknkDjd6.js.map +0 -1
  172. package/dist/daemon-entry-CbLRrgzy.js.map +0 -1
  173. package/dist/db-CRNpA5mH.js.map +0 -1
  174. package/dist/dev-C0pbMmhS.js.map +0 -1
  175. package/dist/dev-preflight-unHpiYO1.js.map +0 -1
  176. package/dist/dev-server-B1UYifZJ.js.map +0 -1
  177. package/dist/doctor-CATRdWm6.js.map +0 -1
  178. package/dist/generate_sdk-Cvg5jjJF.js.map +0 -1
  179. package/dist/init-BWAwHPtz.js.map +0 -1
  180. package/dist/last-dev-database-c_dKz1S3.js +0 -2
  181. package/dist/path-flags-BFgG9V6y.js.map +0 -1
  182. package/dist/project-Wp2zoyeN.js +0 -349
  183. package/dist/project-Wp2zoyeN.js.map +0 -1
  184. package/dist/pull-C3PXduzl.js.map +0 -1
  185. package/dist/resolve-CNQjsatH.js +0 -2
  186. package/dist/schema-B0-p6T1O.js.map +0 -1
  187. package/dist/skills-DfnTeyRz.js.map +0 -1
  188. package/dist/start-BmEZkS0n.js.map +0 -1
  189. package/dist/state-CCB-FAQ9.js.map +0 -1
  190. package/dist/storage-DKPUBTWG.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state-CYdBvnwA.js","names":[],"sources":["../src/dev-db/state.ts"],"sourcesContent":["/**\n * The managed database's state file, and the rules for trusting it.\n *\n * The daemon outlives the command that started it — `rebase db push` in one\n * terminal and `rebase dev` in another have to reach the *same* PGlite, because\n * two processes opening one data directory would corrupt it. So the daemon\n * records where it is, and every command reads that record.\n *\n * A record on disk is a claim, not a fact. The process it names may have been\n * killed, the machine may have rebooted and handed the pid to something else,\n * and the port may now belong to a stranger. {@link readState} therefore only\n * parses; deciding whether a record is live is {@link isDaemonAlive}'s job, and\n * it asks the daemon rather than the operating system.\n */\n\nimport { createHash } from \"crypto\";\nimport fs from \"fs\";\nimport { DEFAULT_RESOURCE_KEY, resourceEnvSuffix } from \"@rebasepro/types\";\nimport net from \"net\";\nimport path from \"path\";\n\n/** Everything under here is generated and gitignored. */\nexport const DEV_DB_DIR = \".rebase\";\n/** PGlite's own data directory. Deleting it is what `--reset` means. */\nexport const DATA_DIR_NAME = \"pgdata\";\n/** The record the daemon writes once it is accepting connections. */\nexport const STATE_FILE_NAME = \"pglite.json\";\n/**\n * Held by whoever is currently starting a daemon.\n *\n * Without it, `rebase dev` and `rebase db push` started in the same second both\n * see no state file, both spawn, and two processes open one PGlite data\n * directory — the exact corruption the single-daemon design exists to prevent.\n * Observed as `ENOTEMPTY` during cleanup, which is the harmless way for it to\n * show up; the harmful way is a damaged database.\n */\nexport const START_LOCK_NAME = \"starting.lock\";\n/**\n * The port each managed database last listened on, by key.\n *\n * Kept apart from the state file because it has to outlive the daemon: the\n * state file is cleared on every stop, and it is what a stopped daemon's\n * successor reads to come back where the last one was. See\n * {@link chooseManagedPort}.\n */\nexport const PORTS_FILE_NAME = \"pglite-ports.json\";\n\nexport interface DaemonState {\n /** TCP port the socket server is listening on, chosen when it started. */\n port: number;\n /** The daemon process. Used only as a fast negative check. */\n pid: number;\n /** Absolute path of the PGlite data directory this daemon has open. */\n dataDir: string;\n /** ISO timestamp, for diagnostics. */\n startedAt: string;\n /**\n * A random token the daemon also answers with over the wire, on\n * {@link identityPort}.\n *\n * Without it, \"is the daemon alive?\" degrades to \"is something listening on\n * that port?\", which is a different question and answers yes for whatever\n * process happened to take the port after a reboot. Rebase would then send\n * migrations to a stranger.\n */\n token: string;\n /** Loopback port that answers the identity check. */\n identityPort: number;\n /**\n * The additional databases this daemon serves, by declared key.\n *\n * One PGlite instance each — PGlite is one database per instance, so\n * `database(\"analytics\")` is a second data directory and a second port,\n * not a `CREATE DATABASE`. Started on demand when a command asks for the\n * key over the identity socket, and recorded here so `rebase status` and\n * a reset can see them. The default database is the fields above.\n */\n databases?: Record<string, { port: number; dataDir: string }>;\n /**\n * The version of the CLI that started this daemon.\n *\n * The daemon outlives the command that started it, and the database proxy\n * runs inside it — so after `rebase upgrade` the old proxy, and its bugs,\n * kept serving until `rebase db stop` or thirty idle minutes. A daemon\n * started before this was recorded has none; see `daemonOutdated`.\n */\n cliVersion?: string;\n}\n\nexport function devDbDir(projectRoot: string): string {\n return path.join(projectRoot, DEV_DB_DIR);\n}\n\nexport function dataDir(projectRoot: string): string {\n return path.join(devDbDir(projectRoot), DATA_DIR_NAME);\n}\n\n/**\n * The data directory for an additional declared database.\n *\n * `pgdata__analytics`: the key spelled the way its variable is, so the\n * directory beside `pgdata` and `DATABASE_URL__ANALYTICS` are visibly the\n * same thing.\n */\nexport function additionalDataDir(projectRoot: string, key: string): string {\n return path.join(devDbDir(projectRoot), `${DATA_DIR_NAME}${resourceEnvSuffix(key).toLowerCase()}`);\n}\n\nexport function stateFile(projectRoot: string): string {\n return path.join(devDbDir(projectRoot), STATE_FILE_NAME);\n}\n\nexport function startLockFile(projectRoot: string): string {\n return path.join(devDbDir(projectRoot), START_LOCK_NAME);\n}\n\n/**\n * Take the start lock, or report that somebody else holds it.\n *\n * `wx` is the whole mechanism: create-if-absent is a single atomic syscall, so\n * exactly one of two racing processes can succeed no matter how close together\n * they arrive.\n *\n * A lock older than `staleAfterMs` is broken rather than waited on — the holder\n * may have been killed between creating it and starting anything, and a\n * developer should never have to know this file exists in order to unstick\n * their project.\n */\nexport function acquireStartLock(projectRoot: string, staleAfterMs: number): boolean {\n const target = startLockFile(projectRoot);\n fs.mkdirSync(devDbDir(projectRoot), { recursive: true });\n\n const attempt = (): boolean => {\n try {\n const handle = fs.openSync(target, \"wx\");\n fs.writeSync(handle, `${process.pid} ${new Date().toISOString()}\\n`);\n fs.closeSync(handle);\n\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n\n return false;\n }\n };\n\n if (attempt()) return true;\n\n try {\n // Clamped at zero: a filesystem whose timestamp granularity rounds the\n // mtime *up* reports a negative age for a lock created moments ago,\n // and a negative age is below every threshold — so `staleAfterMs: 0`,\n // which means \"break any lock\", would refuse to break one.\n const age = Math.max(0, Date.now() - fs.statSync(target).mtimeMs);\n if (age < staleAfterMs) return false;\n fs.unlinkSync(target);\n } catch {\n // Vanished under us, which means the holder finished. Either way the\n // next attempt is the answer.\n }\n\n return attempt();\n}\n\nexport function releaseStartLock(projectRoot: string): void {\n try {\n fs.unlinkSync(startLockFile(projectRoot));\n } catch {\n // Already released is the desired end state.\n }\n}\n\n/**\n * Parse the record, or `null` for anything that is not one.\n *\n * Every failure is the same answer — absent — because every failure has the\n * same remedy: start a daemon. A corrupt state file is not worth an error\n * message to a user who never wrote it.\n */\nexport function readState(projectRoot: string): DaemonState | null {\n let raw: string;\n try {\n raw = fs.readFileSync(stateFile(projectRoot), \"utf8\");\n } catch {\n return null;\n }\n\n try {\n const parsed = JSON.parse(raw) as Partial<DaemonState>;\n if (\n typeof parsed.port !== \"number\" ||\n !Number.isInteger(parsed.port) ||\n parsed.port <= 0 ||\n parsed.port > 65535 ||\n typeof parsed.pid !== \"number\" ||\n typeof parsed.dataDir !== \"string\" ||\n typeof parsed.token !== \"string\" ||\n parsed.token.length === 0 ||\n typeof parsed.identityPort !== \"number\" ||\n !Number.isInteger(parsed.identityPort) ||\n parsed.identityPort <= 0 ||\n parsed.identityPort > 65535\n ) {\n return null;\n }\n\n // Only well-formed entries survive: a malformed one is treated as\n // absent, and the next ensure asks the daemon for it again.\n const databases: Record<string, { port: number; dataDir: string }> = {};\n if (parsed.databases && typeof parsed.databases === \"object\") {\n for (const [key, entry] of Object.entries(parsed.databases)) {\n if (\n entry && typeof entry.port === \"number\" && Number.isInteger(entry.port)\n && entry.port > 0 && entry.port <= 65535 && typeof entry.dataDir === \"string\"\n ) {\n databases[key] = { port: entry.port, dataDir: entry.dataDir };\n }\n }\n }\n\n return {\n port: parsed.port,\n pid: parsed.pid,\n dataDir: parsed.dataDir,\n startedAt: typeof parsed.startedAt === \"string\" ? parsed.startedAt : \"\",\n token: parsed.token,\n identityPort: parsed.identityPort,\n ...(Object.keys(databases).length > 0 ? { databases } : {}),\n ...(typeof parsed.cliVersion === \"string\" && parsed.cliVersion.trim() ? { cliVersion: parsed.cliVersion.trim() } : {})\n };\n } catch {\n return null;\n }\n}\n\nexport function writeState(projectRoot: string, state: DaemonState): void {\n fs.mkdirSync(devDbDir(projectRoot), { recursive: true });\n // Written whole then moved, so a reader never sees half a record — commands\n // poll this file while the daemon is starting.\n const target = stateFile(projectRoot);\n const temporary = `${target}.${process.pid}.tmp`;\n fs.writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\\n`, \"utf8\");\n fs.renameSync(temporary, target);\n}\n\nexport function clearState(projectRoot: string): void {\n try {\n fs.unlinkSync(stateFile(projectRoot));\n } catch {\n // Already gone is the desired end state.\n }\n}\n\n/** Is *some* process with this pid running? A fast, cheap negative check. */\nexport function pidRunning(pid: number): boolean {\n try {\n // Signal 0 performs the permission and existence checks without\n // delivering anything.\n process.kill(pid, 0);\n\n return true;\n } catch (error) {\n // EPERM means it exists and belongs to someone else, which for our\n // purposes is still \"running\".\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/** Can a TCP connection be opened to this port on loopback? */\nexport function portAccepting(port: number, timeoutMs = 1000): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = new net.Socket();\n const settle = (answer: boolean) => {\n socket.removeAllListeners();\n socket.destroy();\n resolve(answer);\n };\n socket.setTimeout(timeoutMs);\n socket.once(\"connect\", () => settle(true));\n socket.once(\"timeout\", () => settle(false));\n socket.once(\"error\", () => settle(false));\n socket.connect(port, \"127.0.0.1\");\n });\n}\n\n/**\n * Ask a port for a free one, then hand back the number.\n *\n * Deliberately not the probe `rebase init` uses: that one has a documented\n * failure where a port is free to probe and unusable to publish. This binds on\n * loopback only, which is also where the daemon listens, so a port that binds\n * here binds there.\n */\nexport function findFreePort(): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = net.createServer();\n server.once(\"error\", reject);\n server.listen(0, \"127.0.0.1\", () => {\n const address = server.address();\n if (address === null || typeof address === \"string\") {\n server.close(() => reject(new Error(\"Could not determine a free port.\")));\n\n return;\n }\n const { port } = address;\n server.close(() => resolve(port));\n });\n });\n}\n\n/** Where a project's derived database port falls: 25432–26431. */\nconst MANAGED_PORT_FIRST = 25432;\nconst MANAGED_PORT_SPAN = 1000;\n\n/**\n * The port a project's managed database tries first when nothing is recorded:\n * derived from the project path, and for an additional database from its key\n * too, so two projects — and a project's two databases — rarely ask for the\n * same one.\n *\n * Below every ephemeral range (Linux hands out 32768 and up, macOS 49152 and\n * up), so an outgoing connection's source port never sits on it, and clear of\n * the ports `rebase dev` derives for the backend (3001–3999), the admin panel\n * (5173–5372) and the compose database (5433–5632).\n */\nexport function derivedManagedPort(projectRoot: string, key: string = DEFAULT_RESOURCE_KEY): number {\n const seed = key === DEFAULT_RESOURCE_KEY ? path.resolve(projectRoot) : `${path.resolve(projectRoot)}\\0${key}`;\n const digest = createHash(\"sha256\").update(seed).digest();\n return MANAGED_PORT_FIRST + (digest.readUInt32BE(0) % MANAGED_PORT_SPAN);\n}\n\nfunction portsFile(projectRoot: string): string {\n return path.join(devDbDir(projectRoot), PORTS_FILE_NAME);\n}\n\n/** The port each database last listened on, by key; empty when nothing is recorded or the record is unreadable. */\nfunction readRecordedPorts(projectRoot: string): Record<string, number> {\n try {\n const parsed: unknown = JSON.parse(fs.readFileSync(portsFile(projectRoot), \"utf8\"));\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return {};\n const ports: Record<string, number> = {};\n for (const [key, port] of Object.entries(parsed)) {\n if (typeof port === \"number\" && Number.isInteger(port) && port > 0 && port <= 65535) ports[key] = port;\n }\n return ports;\n } catch {\n return {};\n }\n}\n\n/**\n * Remember where these databases listen, merged into what is recorded.\n *\n * Best effort: a `.rebase/` that cannot be written costs the next start its\n * preference, not the start itself.\n */\nexport function recordManagedPorts(projectRoot: string, ports: Record<string, number>): void {\n try {\n fs.mkdirSync(devDbDir(projectRoot), { recursive: true });\n const merged = { ...readRecordedPorts(projectRoot), ...ports };\n const target = portsFile(projectRoot);\n const temporary = `${target}.${process.pid}.tmp`;\n fs.writeFileSync(temporary, `${JSON.stringify(merged, null, 2)}\\n`, \"utf8\");\n fs.renameSync(temporary, target);\n } catch {\n // See above.\n }\n}\n\n/** Can a server listen on this loopback port right now? */\nexport function portBindable(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer();\n server.once(\"error\", () => resolve(false));\n server.listen(port, \"127.0.0.1\", () => server.close(() => resolve(true)));\n });\n}\n\n/**\n * The port a managed database should listen on: where it listened last time,\n * else the one derived from the project path, else any free one.\n *\n * Stable on purpose. A backend holds the URL it was started with, and a pool\n * reconnects to the same address on its own — so a database that comes back on\n * the port it had is one a running `rebase dev` recovers from without a\n * restart. It used to be whatever the operating system handed out, and a `rebase\n * db stop` followed by any command that starts it again left the backend\n * dialling a port nothing listened on, answering 503 until dev was restarted.\n *\n * @param canBind stands in for {@link portBindable} in the tests.\n */\nexport async function chooseManagedPort(\n projectRoot: string,\n key: string = DEFAULT_RESOURCE_KEY,\n canBind: (port: number) => Promise<boolean> = portBindable\n): Promise<number> {\n const candidates = [readRecordedPorts(projectRoot)[key], derivedManagedPort(projectRoot, key)];\n for (const port of new Set(candidates.filter((candidate): candidate is number => candidate !== undefined))) {\n if (await canBind(port)) return port;\n }\n return findFreePort();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,aAAa;;AAE1B,IAAa,gBAAgB;;AAE7B,IAAa,kBAAkB;;;;;;;;;;AAU/B,IAAa,kBAAkB;;;;;;;;;AAS/B,IAAa,kBAAkB;AA4C/B,SAAgB,SAAS,aAA6B;CAClD,OAAO,KAAK,KAAK,aAAa,UAAU;AAC5C;AAEA,SAAgB,QAAQ,aAA6B;CACjD,OAAO,KAAK,KAAK,SAAS,WAAW,GAAG,aAAa;AACzD;;;;;;;;AASA,SAAgB,kBAAkB,aAAqB,KAAqB;CACxE,OAAO,KAAK,KAAK,SAAS,WAAW,GAAG,GAAG,gBAAgB,kBAAkB,GAAG,CAAC,CAAC,YAAY,GAAG;AACrG;AAEA,SAAgB,UAAU,aAA6B;CACnD,OAAO,KAAK,KAAK,SAAS,WAAW,GAAG,eAAe;AAC3D;AAEA,SAAgB,cAAc,aAA6B;CACvD,OAAO,KAAK,KAAK,SAAS,WAAW,GAAG,eAAe;AAC3D;;;;;;;;;;;;;AAcA,SAAgB,iBAAiB,aAAqB,cAA+B;CACjF,MAAM,SAAS,cAAc,WAAW;CACxC,GAAG,UAAU,SAAS,WAAW,GAAG,EAAE,WAAW,KAAK,CAAC;CAEvD,MAAM,gBAAyB;EAC3B,IAAI;GACA,MAAM,SAAS,GAAG,SAAS,QAAQ,IAAI;GACvC,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,QAAQ,IAAI;EAC3C,GAAG,cAAc,WAAW,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,EAAE,KAAK,MAAM;EAC1E,GAAG,WAAW,WAAW,MAAM;CACnC,QAAQ,CAER;AACJ;;AAGA,SAAgB,aAAa,MAAgC;CACzD,OAAO,IAAI,SAAS,YAAY;EAC5B,MAAM,SAAS,IAAI,aAAa;EAChC,OAAO,KAAK,eAAe,QAAQ,KAAK,CAAC;EACzC,OAAO,OAAO,MAAM,mBAAmB,OAAO,YAAY,QAAQ,IAAI,CAAC,CAAC;CAC5E,CAAC;AACL;;;;;;;;;;;;;;AAeA,eAAsB,kBAClB,aACA,MAAc,sBACd,UAA8C,cAC/B;CACf,MAAM,aAAa,CAAC,kBAAkB,WAAW,CAAC,CAAC,MAAM,mBAAmB,aAAa,GAAG,CAAC;CAC7F,KAAK,MAAM,QAAQ,IAAI,IAAI,WAAW,QAAQ,cAAmC,cAAc,KAAA,CAAS,CAAC,GACrG,IAAI,MAAM,QAAQ,IAAI,GAAG,OAAO;CAEpC,OAAO,aAAa;AACxB"}
@@ -0,0 +1,64 @@
1
+ /** One syntax error, located the way an editor wants it: 1-based line and column. */
2
+ export interface StaticSyntaxError {
3
+ /** The file, relative to the directory the caller asked to show paths from. */
4
+ file: string;
5
+ line: number;
6
+ column: number;
7
+ message: string;
8
+ /** The offending source line, trimmed to something printable. */
9
+ excerpt?: string;
10
+ }
11
+ export interface StaticSyntaxReport {
12
+ /** JavaScript files plus inline scripts parsed. */
13
+ checked: number;
14
+ errors: StaticSyntaxError[];
15
+ }
16
+ /** How a source is run: a classic script, a module, or unknown (a `.js` file). */
17
+ export type ScriptKind = "script" | "module" | "auto";
18
+ interface ParseFailure {
19
+ line: number;
20
+ /** 0-based, as acorn reports it. */
21
+ column: number;
22
+ /** Offset into the source, used to pick the more informative of two parses. */
23
+ pos: number;
24
+ message: string;
25
+ }
26
+ /**
27
+ * Parse one source and return its first syntax error, or null.
28
+ *
29
+ * A `.js` file can be loaded either way — `<script src>` runs it as a classic
30
+ * script, `<script type="module">` or an `import` as a module — and each mode
31
+ * rejects code the other accepts (`import` in a script, `with` in a module).
32
+ * So `auto` accepts a source that parses either way, and when neither does,
33
+ * reports the parse that got further: that is the one that tripped over the
34
+ * actual mistake rather than over the choice of mode.
35
+ */
36
+ export declare function findSyntaxError(source: string, kind: ScriptKind, cjs?: boolean): ParseFailure | null;
37
+ /** An inline script found in an HTML document, positioned in that document. */
38
+ export interface InlineScript {
39
+ source: string;
40
+ kind: "script" | "module";
41
+ /** 1-based line of the script body's first character. */
42
+ line: number;
43
+ /** 0-based column of that character. */
44
+ column: number;
45
+ }
46
+ /**
47
+ * The inline scripts of an HTML document that a browser would run as
48
+ * JavaScript, each with the position its body starts at.
49
+ *
50
+ * HTML comments are blanked first, keeping every newline, so a commented-out
51
+ * `<script>` is not checked and the line numbers of everything after it are
52
+ * still right.
53
+ */
54
+ export declare function inlineScripts(html: string): InlineScript[];
55
+ /**
56
+ * Parse every JavaScript file and inline script under `dir`.
57
+ *
58
+ * `displayRoot` is what reported paths are relative to: the project root, so
59
+ * an error reads `web/cloud.js:42:7` and can be opened as written.
60
+ */
61
+ export declare function checkStaticSyntax(dir: string, displayRoot?: string): StaticSyntaxReport;
62
+ /** The errors as the lines a person reads: `file:line:col message`, then the line itself. */
63
+ export declare function formatSyntaxErrors(errors: StaticSyntaxError[], limit?: number): string[];
64
+ export {};
@@ -1,11 +1,10 @@
1
- import { d as readEnvFile, i as failAsJson, p as requireProjectRoot } from "./project-Wp2zoyeN.js";
2
- import { n as parseCommandArgs, r as wantsHelp } from "./args-BX0YD14a.js";
3
- import { d as findBackendApp, g as resolveBackendPaths, o as ManifestError, p as loadManifest } from "./manifest-DRp0UVTj.js";
4
- import { c as withImplicitDefaults, n as deriveOptionsFor, o as readResourceGraphFile, r as deriveResourceGraph, s as serializeResourceGraph, t as RESOURCE_GRAPH_FILENAME } from "./derive-CsoFGAnK.js";
5
- import { a as parseLoopbackDsn, o as probeTcp } from "./dev-preflight-unHpiYO1.js";
6
- import { i as managedUrl, r as findRunningDaemon } from "./daemon-CknkDjd6.js";
7
- import { resolveProjectDatabaseAndBranch } from "./prepare-DdnU70z8.js";
8
- import { describeTarget } from "./pull-C3PXduzl.js";
1
+ import { d as readEnvFile, i as failAsJson, p as requireProjectRoot, w as wantsHelp, x as parseCommandArgs } from "./project-CasK56vN.js";
2
+ import { d as findBackendApp, g as resolveBackendPaths, o as ManifestError, p as loadManifest } from "./manifest-BtzDy7KQ.js";
3
+ import { c as withImplicitDefaults, n as deriveOptionsFor, o as readResourceGraphFile, r as deriveResourceGraph, s as serializeResourceGraph, t as RESOURCE_GRAPH_FILENAME } from "./derive-ae9UOoOB.js";
4
+ import { a as parseLoopbackDsn, o as probeTcp } from "./dev-preflight-Cxv3TiD1.js";
5
+ import { i as managedUrl, r as findRunningDaemon } from "./daemon-Cp7oNXth.js";
6
+ import { resolveProjectDatabaseAndBranch } from "./prepare-CTw9NEkh.js";
7
+ import { describeTarget } from "./pull-DDMpsZ5r.js";
9
8
  import chalk from "chalk";
10
9
  import fs from "fs";
11
10
  import path from "path";
@@ -428,4 +427,4 @@ async function statusCommand(rawArgs) {
428
427
  //#endregion
429
428
  export { statusCommand };
430
429
 
431
- //# sourceMappingURL=status-BJ26yZOo.js.map
430
+ //# sourceMappingURL=status-BREvtzJm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"status-BJ26yZOo.js","names":[],"sources":["../src/resources/status.ts","../src/commands/status.ts"],"sourcesContent":["/**\n * What a project declared, what the environment binds it to, and whether the\n * two meet.\n *\n * ## Why this exists\n *\n * Every piece of this was already knowable and none of it was visible in one\n * place. `rebase resources` lists what you declared. The environment holds the\n * variables. The resolvers decide whether a source is usable. So the question a\n * developer actually has — *\"why does uploading to `media` answer 501\"* — could\n * only be answered by knowing the suffix rule, deriving the variable name by\n * hand, and checking it against a `.env` they had to find first.\n *\n * The answer is mechanical, so it should be printed rather than taught.\n *\n * ## Why it calls the resolvers instead of re-deciding\n *\n * The verdict comes from `resolveDataSources` and `resolveStorageBackend` — the\n * same functions that run at boot. A status view that decided for itself what\n * \"configured\" means would be a second implementation of the rule, and the\n * first time it disagreed it would be reassuring a developer about a deployment\n * that is about to refuse to start.\n *\n * The variable *names* come from each kind's `envBases`, and the verdicts from\n * the resolver `@rebasepro/server` registers per kind — one object per kind,\n * held to `envBases` by `resource-env-bases.test.ts`. A kind this view has\n * never heard of is judged by whatever resolver its package registered.\n */\nimport { withImplicitDefaults } from \"./derive\";\nimport {\n DEFAULT_RESOURCE_KEY,\n envBasesForResource,\n resourceEnvSuffix,\n resourceToDataSource,\n type ResourceDeclaration,\n type ResourceGraph\n} from \"@rebasepro/types\";\n\n/** One environment variable a resource reads, and whether it is there. */\nexport interface ResourceBinding {\n /** The variable this resource reads, suffix included. */\n name: string;\n set: boolean;\n /**\n * The account-scoped name consulted when `name` is unset.\n *\n * Only provider-level bindings have one, and only when the resource named\n * an `account`. Shown because a developer looking at an unset\n * `S3_ACCESS_KEY_ID__MEDIA` needs to know it is not the whole story.\n */\n fallback?: { name: string; set: boolean };\n}\n\n/** Whether a declared resource can actually be reached. */\nexport type ResourceState =\n /** Bound and usable. */\n | \"ready\"\n /** Nothing set for it. Legal for a bucket, fatal for a database. */\n | \"unconfigured\"\n /** Set, and set wrongly. The deployment refuses to start. */\n | \"broken\";\n\nexport interface ResourceStatus {\n kind: string;\n key: string;\n engine: string;\n transport: string;\n /** Present when this resource shares another's credentials. */\n account?: string;\n /** True for a resource nobody declared, which exists anyway. */\n implicit: boolean;\n bindings: ResourceBinding[];\n state: ResourceState;\n /** What this means, in the terms the developer will meet it in. */\n detail: string;\n /** Set when a local directory stands in for this engine, in development. */\n standsIn?: string;\n /** What in the project reaches this resource, from the graph. */\n usedBy?: readonly string[];\n}\n\nexport type EnvBag = Record<string, string | undefined>;\n\n/** Set, and not set to the empty string — which the resolvers treat as absent. */\nfunction isSet(env: EnvBag, name: string): boolean {\n const value = env[name];\n return typeof value === \"string\" && value !== \"\";\n}\n\n/**\n * The bindings one declaration reads, in the order a reader should scan them.\n *\n * A `direct`-transport resource gets none: the browser reaches it with a\n * provider SDK and the backend binds nothing for it, so listing variables would\n * invite someone to set variables that are never read.\n */\nexport function bindingsFor(\n declaration: ResourceDeclaration,\n env: EnvBag,\n accountScopedBases: readonly string[]\n): ResourceBinding[] {\n if (declaration.transport !== \"server\") return [];\n\n const suffix = resourceEnvSuffix(declaration.key);\n const account = typeof declaration.options.account === \"string\"\n ? resourceEnvSuffix(declaration.options.account)\n : undefined;\n\n return envBasesForResource(declaration).map((base) => {\n const name = `${base}${suffix}`;\n const binding: ResourceBinding = { name, set: isSet(env, name) };\n\n // Only the provider-level bindings fall back, and only for a resource\n // that named an account. The bucket name never does — it is what\n // distinguishes one source from another.\n if (account !== undefined && !binding.set && accountScopedBases.includes(base)) {\n binding.fallback = { name: `${base}${account}`, set: isSet(env, `${base}${account}`) };\n }\n return binding;\n });\n}\n\n/**\n * What the managed development database covers, when a project is on it.\n *\n * `rebase init` leaves `DATABASE_URL` commented out on purpose and the managed\n * PGlite fills the vacuum — the documented first-run state. Judging that state\n * by the environment alone produced `○ (default) postgres · DATABASE_URL not\n * set` and the remedy \"set DATABASE_URL\", at the same moment `rebase db url`\n * was printing a working connection string for the same project and\n * `rebase dev` was serving from it. The status view was reading the one place\n * the answer deliberately is not.\n *\n * Resolved by the caller, because deciding it needs the project's `.env`, its\n * branch pointer and its compose file, and this module stays free of all three.\n */\nexport interface ManagedDatabaseStatus {\n /**\n * The daemon's connection string, or null when it is not running.\n *\n * Null is not an error: the managed database exists per project and starts\n * on demand. It only means there is nothing to run the whole-set check\n * against, and the row says so rather than implying a misconfiguration.\n */\n url: string | null;\n}\n\n/**\n * The compose `db` service, when a project is on Postgres in Docker.\n *\n * `rebase dev --docker` is remembered, and every command follows it with the\n * scaffold's `DATABASE_URL` still commented out — so, judged by `.env` alone,\n * this view said the default database had no connection string while `rebase\n * dev --docker` served the project from it. Unlike the managed database it\n * stands in for the default only: `dev --docker` hands the backend\n * `DATABASE_URL` and nothing else, so a second declared database still needs\n * its own variable.\n */\nexport interface DockerDatabaseStatus {\n /** The compose service's connection string, which the runtime is given as `DATABASE_URL`. */\n url: string;\n /** What the default database's row says it is. */\n detail: string;\n}\n\n/**\n * The resolver-side of status, as `@rebasepro/server` registers it per kind.\n *\n * Passed in rather than imported so this module stays testable without a\n * server, and so a kind registered by a plugin is judged by the resolver the\n * plugin brought with it rather than by a switch here.\n */\nexport interface StatusResolvers {\n /** `resourceResolver(kind)` from `@rebasepro/server`. */\n resolverFor: (kind: string) => {\n accountScoped?: readonly string[];\n resolve: (\n declaration: ResourceDeclaration,\n env: EnvBag,\n context: { production: boolean; defaultBasePath: string }\n ) => { state: \"ready\" | \"unbound\" | \"blocked\" | \"code\"; detail?: string; standsIn?: string };\n } | undefined;\n /** `resolveDataSources` from `@rebasepro/server`, for the whole-set check. */\n resolveDataSources: (env: EnvBag, definitions: unknown) => unknown;\n /** Whether the process being judged is production. Status judges for development by default. */\n production?: boolean;\n /**\n * Set when this project runs on the managed development database.\n *\n * Absent for a project that named its own connection string, and absent in\n * production — where an unset `DATABASE_URL` is the failure it has always\n * been.\n */\n managedDatabase?: ManagedDatabaseStatus;\n /** Set when this project runs on Postgres in Docker. Absent in production, like the managed one. */\n dockerDatabase?: DockerDatabaseStatus;\n}\n\n/**\n * The environment plus the managed database's URL, for the whole-set check.\n *\n * A copy: the bindings a reader sees are computed against the real `.env`, so\n * nothing here can make the view claim a variable is set that is not. This is\n * only what `resolveDataSources` is handed, and it is handed it so the check\n * judges the environment the runtime would actually get rather than throwing\n * \"Data source \"(default)\" has no connection string\" about a database that is\n * running and reachable.\n */\nfunction withManagedUrls(env: EnvBag, graph: ResourceGraph, url: string): EnvBag {\n const filled: EnvBag = { ...env };\n const keys = [\n DEFAULT_RESOURCE_KEY,\n ...graph.resources.filter(r => r.kind === \"database\").map(r => r.key)\n ];\n for (const key of keys) {\n const name = `DATABASE_URL${resourceEnvSuffix(key)}`;\n if (!isSet(filled, name)) filled[name] = url;\n }\n\n return filled;\n}\n\n/**\n * The environment with the default database's URL filled in, when `.env` leaves it out.\n *\n * What a database's resolver is judged against. The resolver checks a source\n * alongside the default one, so a second database bound by its own\n * `DATABASE_URL__ANALYTICS` was marked ✗ with `Data source \"(default)\" has no\n * connection string` — on a project whose default the managed database or the\n * compose service provides, and whose boot worked. Judged against the\n * environment the runtime actually gets, it is judged on its own string.\n */\nfunction withDefaultUrl(env: EnvBag, url: string | null | undefined): EnvBag {\n if (!url || isSet(env, \"DATABASE_URL\")) return env;\n\n return { ...env, DATABASE_URL: url };\n}\n\n/**\n * Resolve every declared resource against an environment.\n *\n * Each kind's verdict comes from the resolver `@rebasepro/server` registered\n * for it — the same one boot calls — so this view cannot say \"ready\" about a\n * binding boot would refuse. A kind with no resolver is reported as such\n * rather than skipped: a resource nobody shows is one nobody remembers to\n * configure, and a kind this runtime cannot bind is exactly what boot will\n * refuse by name.\n *\n * `resolveDataSources` is then run once over the whole set, so anything it\n * would refuse across sources (a driver package it cannot resolve for a custom\n * engine) is reported rather than missed by a view that only looked per row.\n */\nexport function computeStatus(\n graph: ResourceGraph,\n env: EnvBag,\n resolvers: StatusResolvers\n): { resources: ResourceStatus[]; blocked?: string } {\n const resources: ResourceStatus[] = [];\n const production = resolvers.production ?? false;\n const managed = resolvers.managedDatabase;\n const docker = resolvers.dockerDatabase;\n /** The default database's URL as the runtime gets it, when `.env` does not name one. */\n const devDefaultUrl = managed?.url ?? docker?.url ?? null;\n /** Database rows the managed database answered for, so `blocked` can skip them. */\n let managedCovered = 0;\n\n for (const { declaration, implicit } of withImplicitDefaults(graph)) {\n const resolver = resolvers.resolverFor(declaration.kind);\n const bindings = bindingsFor(declaration, env, resolver?.accountScoped ?? []);\n const base: Omit<ResourceStatus, \"state\" | \"detail\"> = {\n kind: declaration.kind,\n key: declaration.key,\n engine: declaration.engine,\n transport: declaration.transport,\n ...(typeof declaration.options.account === \"string\"\n ? { account: declaration.options.account }\n : {}),\n implicit,\n bindings,\n ...(declaration.usedBy && declaration.usedBy.length > 0 ? { usedBy: declaration.usedBy } : {})\n };\n\n if (!resolver) {\n resources.push({\n ...base,\n state: \"broken\",\n detail: `this runtime has no resolver for a \"${declaration.kind}\" — boot refuses it by name. ` +\n \"Upgrade @rebasepro/server, or remove the declaration.\"\n });\n continue;\n }\n\n // Answered before the resolver, because the resolver reads the\n // environment and the whole point of the managed database is that the\n // environment is deliberately empty. Only for a database nobody bound:\n // a developer who set `DATABASE_URL__ANALYTICS` to a warehouse of their\n // own has said which database that is, and the managed one fills a\n // vacuum, never a choice.\n if (managed && declaration.kind === \"database\" && bindings.every(b => !b.set && !b.fallback?.set)) {\n managedCovered += 1;\n resources.push({\n ...base,\n state: \"ready\",\n detail: managed.url\n ? \"the managed development database (PGlite), this project only\"\n : \"the managed development database (PGlite), this project only — \"\n + \"not running; start it with `rebase dev`\"\n });\n continue;\n }\n\n // The default database on Docker: the compose service, unless `.env`\n // names one itself.\n if (docker && declaration.kind === \"database\" && declaration.key === DEFAULT_RESOURCE_KEY\n && bindings.every(b => !b.set && !b.fallback?.set)) {\n resources.push({ ...base, state: \"ready\", detail: docker.detail });\n continue;\n }\n\n const judged = declaration.kind === \"database\" ? withDefaultUrl(env, devDefaultUrl) : env;\n const verdict = resolver.resolve(declaration, judged, { production, defaultBasePath: \"uploads\" });\n switch (verdict.state) {\n case \"ready\":\n resources.push({\n ...base,\n state: \"ready\",\n ...(verdict.standsIn ? { standsIn: verdict.standsIn } : {}),\n detail: verdict.detail ?? \"\"\n });\n break;\n case \"code\":\n resources.push({ ...base, state: \"ready\", detail: verdict.detail ?? \"needs no environment configuration\" });\n break;\n case \"unbound\":\n resources.push({ ...base, state: \"unconfigured\", detail: verdict.detail ?? \"declared, not configured\" });\n break;\n case \"blocked\":\n resources.push({\n ...base,\n // A database the environment names nothing for is the\n // ordinary first-run state, and reads as unconfigured; a\n // binding that is set and set wrongly is broken.\n state: implicit || bindings.every(b => !b.set && !b.fallback?.set) ? \"unconfigured\" : \"broken\",\n detail: verdict.detail ?? \"boot refuses this binding\"\n });\n break;\n }\n }\n\n // Only asked when every row already looks fine. Its failures overlap with\n // the per-resource ones, and a banner repeating a line printed two rows\n // above teaches nothing — what it is here for is the failure no row models,\n // such as a custom engine whose driver package cannot be resolved.\n let blocked: string | undefined;\n // Not run when the managed database answered for a row and is not running:\n // there is no connection string to check the set against, and inventing one\n // to keep the check formally \"run\" is how a green tick gets printed for\n // work nobody did. The row says the daemon is down; that is the finding.\n const managedSetUnknown = managedCovered > 0 && !managed?.url;\n if (resources.every(r => r.state === \"ready\") && !managedSetUnknown) {\n try {\n resolvers.resolveDataSources(\n // The managed URL for the rows it answered for, so the whole-set\n // check judges the same environment the runtime would get.\n managed?.url ? withManagedUrls(env, graph, managed.url) : withDefaultUrl(env, docker?.url),\n graph.resources.filter(r => r.kind === \"database\").map(resourceToDataSource)\n );\n } catch (err) {\n blocked = err instanceof Error ? err.message : String(err);\n }\n }\n\n return { resources, ...(blocked !== undefined ? { blocked } : {}) };\n}\n","/**\n * `rebase status` — what this project is, and whether it can reach its things.\n *\n * The model a developer has to hold is small and was nowhere visible:\n *\n * rebase.json where the code is, and who runs the server\n * config/resources.ts what the project needs\n * the environment how to reach each of them\n *\n * Everything else — `rebase.resources.json`, the bundle manifest — is a\n * generated copy of the middle one, for readers that cannot run the code. A\n * developer never writes them and should not have to think about them.\n *\n * This command prints the three together, resolved. It exists because the\n * question people actually arrive with — \"why does uploading to `media` answer\n * 501\" — was answerable only by knowing the `<BASE>__<KEY>` suffix rule,\n * deriving the variable name by hand, and checking it against a `.env` they had\n * to find first. Every step of that is mechanical, so it is printed instead.\n */\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { failAsJson, readEnvFile, requireProjectRoot } from \"../utils/project\";\nimport { findBackendApp, loadManifest, ManifestError, resolveBackendPaths } from \"../manifest\";\nimport { deriveOptionsFor, deriveResourceGraph, RESOURCE_GRAPH_FILENAME, readResourceGraphFile, serializeResourceGraph } from \"../resources/derive\";\nimport { computeStatus, type DockerDatabaseStatus, type ManagedDatabaseStatus, type ResourceStatus } from \"../resources/status\";\nimport { findRunningDaemon, managedUrl } from \"../dev-db/daemon\";\nimport { type ResolvedBranch, resolveProjectDatabaseAndBranch } from \"../dev-db/prepare\";\nimport { describeTarget } from \"../dev-db/pull\";\nimport { parseLoopbackDsn, probeTcp } from \"../utils/dev-preflight\";\nimport type { RebaseBackendAppConfig } from \"@rebasepro/types\";\n\nfunction usage(): void {\n console.log(`\n${chalk.bold(\"rebase status\")} — what this project declares, and whether it is configured\n\n${chalk.bold(\"Usage\")}\n rebase status Show every resource and the variables it reads\n rebase status --json The same, as JSON\n\n${chalk.bold(\"Reads\")}\n rebase.json which apps exist, and who owns the server process\n <config>/resources.ts the databases, buckets, topics and queues declared\n backend/crons, backend/functions the crons and functions, by filename\n .env whether each one's variables are set\n`);\n}\n\nconst MARK = {\n ready: chalk.green(\"✓\"),\n unconfigured: chalk.yellow(\"○\"),\n broken: chalk.red(\"✗\")\n} as const;\n\nfunction printResource(status: ResourceStatus): void {\n const name = status.key === \"(default)\" ? chalk.bold(\"(default)\") : chalk.bold(status.key);\n const tags = [chalk.gray(status.engine)];\n if (status.transport !== \"server\") tags.push(chalk.yellow(status.transport));\n if (status.account) tags.push(chalk.gray(`account:${status.account}`));\n if (status.implicit) tags.push(chalk.gray(\"implicit\"));\n // A stand-in is not a binding. It is shown in yellow beside a green tick:\n // uploads work here, and the same declaration answers 501 in production\n // until the variable is set.\n if (status.standsIn) tags.push(chalk.yellow(`local stand-in for ${status.standsIn}`));\n\n console.log(` ${MARK[status.state]} ${name} ${tags.join(\" · \")}`);\n if (status.usedBy && status.usedBy.length > 0) {\n console.log(` ${chalk.gray(\"used by\")} ${chalk.gray(status.usedBy.join(\", \"))}`);\n }\n\n let hiddenOptional = 0;\n for (const binding of status.bindings) {\n if (binding.set) {\n console.log(` ${chalk.green(\"✓\")} ${chalk.gray(binding.name)}`);\n } else if (binding.fallback?.set) {\n // Not a gap: the account form is the variable this bucket is\n // actually reading, and showing only the unset per-key name would\n // send someone to set the one they were deliberately avoiding.\n console.log(` ${chalk.green(\"✓\")} ${chalk.gray(binding.fallback.name)} ${chalk.gray(`(shared, for ${binding.name})`)}`);\n } else if (status.state === \"ready\") {\n // It resolved without this one, so this one is optional — which is\n // the resolver's answer, not a second table of required names kept\n // here. Listing seven unset optionals under a working database is\n // how a status view teaches people to skim past the line that\n // matters.\n hiddenOptional += 1;\n } else {\n const also = binding.fallback ? chalk.gray(` or ${binding.fallback.name}`) : \"\";\n console.log(` ${chalk.gray(\"·\")} ${chalk.gray(binding.name)}${also} ${chalk.gray(\"not set\")}`);\n }\n }\n if (hiddenOptional > 0) {\n console.log(chalk.gray(` ${hiddenOptional} optional variable${hiddenOptional === 1 ? \"\" : \"s\"} not set`));\n }\n\n if (status.detail) {\n const colour = status.state === \"broken\" ? chalk.red : status.state === \"unconfigured\" ? chalk.yellow : chalk.gray;\n console.log(` ${colour(`└ ${status.detail}`)}`);\n }\n}\n\n/** Which database `rebase status` reports the project on, and what it hands the status view about it. */\nexport interface StatusDatabase {\n managedDatabase?: ManagedDatabaseStatus;\n dockerDatabase?: DockerDatabaseStatus;\n /** The branch this checkout is on, when the database is one. */\n branch: ResolvedBranch | null;\n /** A switched-to branch the managed database cannot serve. */\n ignoredBranch: string | null;\n}\n\n/**\n * Which database this project is on, decided by the same ordered rule\n * `rebase dev` and `rebase db url` use — and read from the project's `.env`,\n * not from this shell: `rebase status` asks what *this project* is on.\n *\n * Nothing is started. `status` is a question, and a question that boots a\n * 180 MB Postgres to answer itself is a different command. So a managed\n * database that is not running is reported as exactly that, rather than as a\n * project with no database; and a compose database likewise, after a probe of\n * its port.\n *\n * `envFile` is the parsed `.env`; production stands nothing in, because there\n * an unset `DATABASE_URL` is the failure it has always been.\n *\n * Exported for its tests.\n */\nexport async function statusDatabase(projectRoot: string, envFile: Record<string, string>): Promise<StatusDatabase> {\n const { database, branch, ignoredBranch } = resolveProjectDatabaseAndBranch(projectRoot, { env: {} });\n if (envFile.NODE_ENV === \"production\") return { branch, ignoredBranch };\n\n if (database.kind === \"managed\") {\n const daemon = await findRunningDaemon(projectRoot);\n return { managedDatabase: { url: daemon ? managedUrl(daemon.port) : null }, branch, ignoredBranch };\n }\n\n if (database.kind === \"docker\" && database.url) {\n const target = parseLoopbackDsn(database.url);\n const listening = target ? await probeTcp(target.host, target.port) : true;\n const which = branch ? `branch \"${branch.name}\" (${branch.database}) of Postgres in Docker` : \"Postgres in Docker\";\n return {\n dockerDatabase: {\n url: database.url,\n detail: which + \", as the last `rebase dev --docker` did · \" + describeTarget(database.url)\n + (listening ? \"\" : \" — not running; `rebase dev --docker` starts it\")\n },\n branch,\n ignoredBranch\n };\n }\n\n return { branch, ignoredBranch };\n}\n\nexport async function statusCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) return usage();\n\n const { flags } = parseCommandArgs({\n spec: { \"--json\": Boolean },\n rawArgs,\n commandWords: 1,\n command: \"status\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n\n // Every exit below has a `--json` arm, because `--json` means stdout holds\n // one JSON object on *every* exit of the command. It used to mean that for\n // the one failure `requireProjectRoot` owns and nothing else, so a caller\n // parsing stdout got an envelope outside a project and an empty stream\n // inside a broken one — the case it actually has to handle.\n const asJson = Boolean(flags[\"--json\"]);\n\n let backend: { name: string; app: RebaseBackendAppConfig };\n try {\n const loaded = loadManifest(projectRoot);\n const found = findBackendApp(loaded.manifest);\n if (!found) {\n if (asJson) {\n failAsJson(\n \"This project declares no backend app, so it declares no resources.\",\n \"no_backend_app\",\n \"Add a backend app to rebase.json, or run `rebase apps init`.\"\n );\n }\n console.error(chalk.red(\"This project declares no backend app, so it declares no resources.\"));\n process.exitCode = 1;\n return;\n }\n backend = found;\n } catch (err) {\n if (err instanceof ManifestError) {\n if (asJson) {\n failAsJson(err.message, \"manifest_invalid\", \"Fix rebase.json, then run this again.\",\n err.issues.map(issue => ({ path: issue.path, message: issue.message })));\n }\n console.error(chalk.red(err.message));\n for (const issue of err.issues) console.error(` ${chalk.gray(issue.path)} ${issue.message}`);\n process.exitCode = 1;\n return;\n }\n throw err;\n }\n\n const { name: backendName, app: backendApp } = backend;\n const paths = resolveBackendPaths(backendApp, projectRoot);\n\n const { graph, issues } = await deriveResourceGraph(deriveOptionsFor(projectRoot, backendApp));\n if (issues.length > 0) {\n if (asJson) {\n failAsJson(\n `${issues.length} problem(s) in the declared resources.`,\n \"resource_declaration_invalid\",\n \"Fix the declarations the issues name, then run this again.\",\n issues.map(issue => ({ path: issue.path, message: issue.message }))\n );\n }\n console.error(chalk.red(`\\n✗ ${issues.length} problem(s) in the declared resources:\\n`));\n for (const issue of issues) console.error(` ${chalk.bold(issue.path)} ${issue.message}`);\n console.error(\"\");\n process.exitCode = 1;\n return;\n }\n\n // The project's own `.env`, not this process's environment: `rebase status`\n // is asking what a deployment of THIS repository would do, and the shell a\n // developer happens to be standing in is not that.\n const env = readEnvFile(projectRoot);\n\n const production = env.NODE_ENV === \"production\";\n const { managedDatabase, dockerDatabase, branch, ignoredBranch } = await statusDatabase(projectRoot, env);\n\n const server = await import(\"@rebasepro/server\");\n const { resources, blocked } = computeStatus(graph, env, {\n resolverFor: server.resourceResolver as never,\n resolveDataSources: server.resolveDataSources as never,\n // Judged as production when the .env says so; a stand-in local\n // directory for an unbound bucket is only ever offered to development.\n production,\n ...(managedDatabase ? { managedDatabase } : {}),\n ...(dockerDatabase ? { dockerDatabase } : {})\n });\n\n if (asJson) {\n console.log(JSON.stringify({\n backend: backendName,\n runtime: backendApp.runtime,\n ...(branch ? { branch: { name: branch.name, database: branch.database } } : {}),\n resources,\n blocked\n }, null, 2));\n return;\n }\n\n const ownership = backendApp.runtime === \"managed\"\n ? \"Rebase's runtime boots your bundle\"\n : \"this project builds its own image and entrypoint\";\n\n console.log(\"\");\n console.log(` ${chalk.bold(backendName)} ${chalk.gray(\"·\")} ${chalk.cyan(backendApp.runtime)} ${chalk.gray(ownership)}`);\n // Named whether or not it exists, and said plainly when it does not. A\n // project with no `resources.ts` is legal — it has one default database and\n // one default bucket — but \"declared in <a file you do not have>\" reads as\n // a broken install rather than as the default it is.\n const resourcesFile = path.join(paths.config, \"resources.ts\");\n const declaresAnything = fs.existsSync(path.join(projectRoot, resourcesFile));\n console.log(` ${chalk.gray(\"declared in\")} ${chalk.gray(resourcesFile)}${\n declaresAnything ? \"\" : chalk.gray(\" (none — the defaults below are implicit)\")}`);\n console.log(` ${chalk.gray(\"configured by\")} ${chalk.gray(\".env\")}`);\n // Every database command in this checkout uses the branch, so the view\n // says so: a switch made yesterday is easy to forget.\n if (branch) {\n console.log(` ${chalk.gray(\"on branch\")} ${chalk.bold(branch.name)} ${chalk.gray(`(${branch.database})`)}`\n + chalk.gray(` — ${chalk.cyan(\"rebase db branch switch --off\")} returns to ${branch.parent ?? \"the main database\"}`));\n } else if (ignoredBranch) {\n console.log(` ${chalk.yellow(\"○\")} ${chalk.gray(`switched to branch \"${ignoredBranch}\", which the managed database cannot serve — it uses the main one`)}`);\n }\n\n const kinds = [...new Set(resources.map(r => r.kind))];\n for (const kind of kinds) {\n console.log(\"\");\n console.log(` ${chalk.bold.underline(`${kind}s`)}`);\n for (const status of resources.filter(r => r.kind === kind)) printResource(status);\n }\n\n if (blocked) {\n console.log(\"\");\n console.log(` ${chalk.red(\"✗\")} ${chalk.red(blocked)}`);\n }\n\n // Only worth a line when it is wrong. A generated file that matches its\n // declarations is not news, and a status view that reports its own\n // bookkeeping as an item trains people to skim past the items that matter.\n //\n // Nor is one that has not been written yet: `rebase build` writes it on\n // every build and says \"commit it\" when it changes, so a project that has\n // never been built — every fresh scaffold — has nothing wrong with it.\n // `rebase resources --check` is the gate that refuses a missing one.\n const committed = readResourceGraphFile(projectRoot);\n if (committed !== null && committed !== serializeResourceGraph(graph)) {\n console.log(\"\");\n console.log(` ${chalk.yellow(\"○\")} ${RESOURCE_GRAPH_FILENAME} is stale — ${chalk.blue(\"rebase resources --write\")}`);\n console.log(chalk.gray(\" a host reads it to decide what to provision before it runs anything\"));\n }\n\n console.log(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoFA,SAAS,MAAM,KAAa,MAAuB;CAC/C,MAAM,QAAQ,IAAI;CAClB,OAAO,OAAO,UAAU,YAAY,UAAU;AAClD;;;;;;;;AASA,SAAgB,YACZ,aACA,KACA,oBACiB;CACjB,IAAI,YAAY,cAAc,UAAU,OAAO,CAAC;CAEhD,MAAM,SAAS,kBAAkB,YAAY,GAAG;CAChD,MAAM,UAAU,OAAO,YAAY,QAAQ,YAAY,WACjD,kBAAkB,YAAY,QAAQ,OAAO,IAC7C,KAAA;CAEN,OAAO,oBAAoB,WAAW,CAAC,CAAC,KAAK,SAAS;EAClD,MAAM,OAAO,GAAG,OAAO;EACvB,MAAM,UAA2B;GAAE;GAAM,KAAK,MAAM,KAAK,IAAI;EAAE;EAK/D,IAAI,YAAY,KAAA,KAAa,CAAC,QAAQ,OAAO,mBAAmB,SAAS,IAAI,GACzE,QAAQ,WAAW;GAAE,MAAM,GAAG,OAAO;GAAW,KAAK,MAAM,KAAK,GAAG,OAAO,SAAS;EAAE;EAEzF,OAAO;CACX,CAAC;AACL;;;;;;;;;;;AAwFA,SAAS,gBAAgB,KAAa,OAAsB,KAAqB;CAC7E,MAAM,SAAiB,EAAE,GAAG,IAAI;CAChC,MAAM,OAAO,CACT,sBACA,GAAG,MAAM,UAAU,QAAO,MAAK,EAAE,SAAS,UAAU,CAAC,CAAC,KAAI,MAAK,EAAE,GAAG,CACxE;CACA,KAAK,MAAM,OAAO,MAAM;EACpB,MAAM,OAAO,eAAe,kBAAkB,GAAG;EACjD,IAAI,CAAC,MAAM,QAAQ,IAAI,GAAG,OAAO,QAAQ;CAC7C;CAE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H,QAAQ,IAAI,MAAM,KAAK,2EAA2E,CAAC;CACvG;CAEA,QAAQ,IAAI,EAAE;AAClB"}
1
+ {"version":3,"file":"status-BREvtzJm.js","names":[],"sources":["../src/resources/status.ts","../src/commands/status.ts"],"sourcesContent":["/**\n * What a project declared, what the environment binds it to, and whether the\n * two meet.\n *\n * ## Why this exists\n *\n * Every piece of this was already knowable and none of it was visible in one\n * place. `rebase resources` lists what you declared. The environment holds the\n * variables. The resolvers decide whether a source is usable. So the question a\n * developer actually has — *\"why does uploading to `media` answer 501\"* — could\n * only be answered by knowing the suffix rule, deriving the variable name by\n * hand, and checking it against a `.env` they had to find first.\n *\n * The answer is mechanical, so it should be printed rather than taught.\n *\n * ## Why it calls the resolvers instead of re-deciding\n *\n * The verdict comes from `resolveDataSources` and `resolveStorageBackend` — the\n * same functions that run at boot. A status view that decided for itself what\n * \"configured\" means would be a second implementation of the rule, and the\n * first time it disagreed it would be reassuring a developer about a deployment\n * that is about to refuse to start.\n *\n * The variable *names* come from each kind's `envBases`, and the verdicts from\n * the resolver `@rebasepro/server` registers per kind — one object per kind,\n * held to `envBases` by `resource-env-bases.test.ts`. A kind this view has\n * never heard of is judged by whatever resolver its package registered.\n */\nimport { withImplicitDefaults } from \"./derive\";\nimport {\n DEFAULT_RESOURCE_KEY,\n envBasesForResource,\n resourceEnvSuffix,\n resourceToDataSource,\n type ResourceDeclaration,\n type ResourceGraph\n} from \"@rebasepro/types\";\n\n/** One environment variable a resource reads, and whether it is there. */\nexport interface ResourceBinding {\n /** The variable this resource reads, suffix included. */\n name: string;\n set: boolean;\n /**\n * The account-scoped name consulted when `name` is unset.\n *\n * Only provider-level bindings have one, and only when the resource named\n * an `account`. Shown because a developer looking at an unset\n * `S3_ACCESS_KEY_ID__MEDIA` needs to know it is not the whole story.\n */\n fallback?: { name: string; set: boolean };\n}\n\n/** Whether a declared resource can actually be reached. */\nexport type ResourceState =\n /** Bound and usable. */\n | \"ready\"\n /** Nothing set for it. Legal for a bucket, fatal for a database. */\n | \"unconfigured\"\n /** Set, and set wrongly. The deployment refuses to start. */\n | \"broken\";\n\nexport interface ResourceStatus {\n kind: string;\n key: string;\n engine: string;\n transport: string;\n /** Present when this resource shares another's credentials. */\n account?: string;\n /** True for a resource nobody declared, which exists anyway. */\n implicit: boolean;\n bindings: ResourceBinding[];\n state: ResourceState;\n /** What this means, in the terms the developer will meet it in. */\n detail: string;\n /** Set when a local directory stands in for this engine, in development. */\n standsIn?: string;\n /** What in the project reaches this resource, from the graph. */\n usedBy?: readonly string[];\n}\n\nexport type EnvBag = Record<string, string | undefined>;\n\n/** Set, and not set to the empty string — which the resolvers treat as absent. */\nfunction isSet(env: EnvBag, name: string): boolean {\n const value = env[name];\n return typeof value === \"string\" && value !== \"\";\n}\n\n/**\n * The bindings one declaration reads, in the order a reader should scan them.\n *\n * A `direct`-transport resource gets none: the browser reaches it with a\n * provider SDK and the backend binds nothing for it, so listing variables would\n * invite someone to set variables that are never read.\n */\nexport function bindingsFor(\n declaration: ResourceDeclaration,\n env: EnvBag,\n accountScopedBases: readonly string[]\n): ResourceBinding[] {\n if (declaration.transport !== \"server\") return [];\n\n const suffix = resourceEnvSuffix(declaration.key);\n const account = typeof declaration.options.account === \"string\"\n ? resourceEnvSuffix(declaration.options.account)\n : undefined;\n\n return envBasesForResource(declaration).map((base) => {\n const name = `${base}${suffix}`;\n const binding: ResourceBinding = { name, set: isSet(env, name) };\n\n // Only the provider-level bindings fall back, and only for a resource\n // that named an account. The bucket name never does — it is what\n // distinguishes one source from another.\n if (account !== undefined && !binding.set && accountScopedBases.includes(base)) {\n binding.fallback = { name: `${base}${account}`, set: isSet(env, `${base}${account}`) };\n }\n return binding;\n });\n}\n\n/**\n * What the managed development database covers, when a project is on it.\n *\n * `rebase init` leaves `DATABASE_URL` commented out on purpose and the managed\n * PGlite fills the vacuum — the documented first-run state. Judging that state\n * by the environment alone produced `○ (default) postgres · DATABASE_URL not\n * set` and the remedy \"set DATABASE_URL\", at the same moment `rebase db url`\n * was printing a working connection string for the same project and\n * `rebase dev` was serving from it. The status view was reading the one place\n * the answer deliberately is not.\n *\n * Resolved by the caller, because deciding it needs the project's `.env`, its\n * branch pointer and its compose file, and this module stays free of all three.\n */\nexport interface ManagedDatabaseStatus {\n /**\n * The daemon's connection string, or null when it is not running.\n *\n * Null is not an error: the managed database exists per project and starts\n * on demand. It only means there is nothing to run the whole-set check\n * against, and the row says so rather than implying a misconfiguration.\n */\n url: string | null;\n}\n\n/**\n * The compose `db` service, when a project is on Postgres in Docker.\n *\n * `rebase dev --docker` is remembered, and every command follows it with the\n * scaffold's `DATABASE_URL` still commented out — so, judged by `.env` alone,\n * this view said the default database had no connection string while `rebase\n * dev --docker` served the project from it. Unlike the managed database it\n * stands in for the default only: `dev --docker` hands the backend\n * `DATABASE_URL` and nothing else, so a second declared database still needs\n * its own variable.\n */\nexport interface DockerDatabaseStatus {\n /** The compose service's connection string, which the runtime is given as `DATABASE_URL`. */\n url: string;\n /** What the default database's row says it is. */\n detail: string;\n}\n\n/**\n * The resolver-side of status, as `@rebasepro/server` registers it per kind.\n *\n * Passed in rather than imported so this module stays testable without a\n * server, and so a kind registered by a plugin is judged by the resolver the\n * plugin brought with it rather than by a switch here.\n */\nexport interface StatusResolvers {\n /** `resourceResolver(kind)` from `@rebasepro/server`. */\n resolverFor: (kind: string) => {\n accountScoped?: readonly string[];\n resolve: (\n declaration: ResourceDeclaration,\n env: EnvBag,\n context: { production: boolean; defaultBasePath: string }\n ) => { state: \"ready\" | \"unbound\" | \"blocked\" | \"code\"; detail?: string; standsIn?: string };\n } | undefined;\n /** `resolveDataSources` from `@rebasepro/server`, for the whole-set check. */\n resolveDataSources: (env: EnvBag, definitions: unknown) => unknown;\n /** Whether the process being judged is production. Status judges for development by default. */\n production?: boolean;\n /**\n * Set when this project runs on the managed development database.\n *\n * Absent for a project that named its own connection string, and absent in\n * production — where an unset `DATABASE_URL` is the failure it has always\n * been.\n */\n managedDatabase?: ManagedDatabaseStatus;\n /** Set when this project runs on Postgres in Docker. Absent in production, like the managed one. */\n dockerDatabase?: DockerDatabaseStatus;\n}\n\n/**\n * The environment plus the managed database's URL, for the whole-set check.\n *\n * A copy: the bindings a reader sees are computed against the real `.env`, so\n * nothing here can make the view claim a variable is set that is not. This is\n * only what `resolveDataSources` is handed, and it is handed it so the check\n * judges the environment the runtime would actually get rather than throwing\n * \"Data source \"(default)\" has no connection string\" about a database that is\n * running and reachable.\n */\nfunction withManagedUrls(env: EnvBag, graph: ResourceGraph, url: string): EnvBag {\n const filled: EnvBag = { ...env };\n const keys = [\n DEFAULT_RESOURCE_KEY,\n ...graph.resources.filter(r => r.kind === \"database\").map(r => r.key)\n ];\n for (const key of keys) {\n const name = `DATABASE_URL${resourceEnvSuffix(key)}`;\n if (!isSet(filled, name)) filled[name] = url;\n }\n\n return filled;\n}\n\n/**\n * The environment with the default database's URL filled in, when `.env` leaves it out.\n *\n * What a database's resolver is judged against. The resolver checks a source\n * alongside the default one, so a second database bound by its own\n * `DATABASE_URL__ANALYTICS` was marked ✗ with `Data source \"(default)\" has no\n * connection string` — on a project whose default the managed database or the\n * compose service provides, and whose boot worked. Judged against the\n * environment the runtime actually gets, it is judged on its own string.\n */\nfunction withDefaultUrl(env: EnvBag, url: string | null | undefined): EnvBag {\n if (!url || isSet(env, \"DATABASE_URL\")) return env;\n\n return { ...env, DATABASE_URL: url };\n}\n\n/**\n * Resolve every declared resource against an environment.\n *\n * Each kind's verdict comes from the resolver `@rebasepro/server` registered\n * for it — the same one boot calls — so this view cannot say \"ready\" about a\n * binding boot would refuse. A kind with no resolver is reported as such\n * rather than skipped: a resource nobody shows is one nobody remembers to\n * configure, and a kind this runtime cannot bind is exactly what boot will\n * refuse by name.\n *\n * `resolveDataSources` is then run once over the whole set, so anything it\n * would refuse across sources (a driver package it cannot resolve for a custom\n * engine) is reported rather than missed by a view that only looked per row.\n */\nexport function computeStatus(\n graph: ResourceGraph,\n env: EnvBag,\n resolvers: StatusResolvers\n): { resources: ResourceStatus[]; blocked?: string } {\n const resources: ResourceStatus[] = [];\n const production = resolvers.production ?? false;\n const managed = resolvers.managedDatabase;\n const docker = resolvers.dockerDatabase;\n /** The default database's URL as the runtime gets it, when `.env` does not name one. */\n const devDefaultUrl = managed?.url ?? docker?.url ?? null;\n /** Database rows the managed database answered for, so `blocked` can skip them. */\n let managedCovered = 0;\n\n for (const { declaration, implicit } of withImplicitDefaults(graph)) {\n const resolver = resolvers.resolverFor(declaration.kind);\n const bindings = bindingsFor(declaration, env, resolver?.accountScoped ?? []);\n const base: Omit<ResourceStatus, \"state\" | \"detail\"> = {\n kind: declaration.kind,\n key: declaration.key,\n engine: declaration.engine,\n transport: declaration.transport,\n ...(typeof declaration.options.account === \"string\"\n ? { account: declaration.options.account }\n : {}),\n implicit,\n bindings,\n ...(declaration.usedBy && declaration.usedBy.length > 0 ? { usedBy: declaration.usedBy } : {})\n };\n\n if (!resolver) {\n resources.push({\n ...base,\n state: \"broken\",\n detail: `this runtime has no resolver for a \"${declaration.kind}\" — boot refuses it by name. ` +\n \"Upgrade @rebasepro/server, or remove the declaration.\"\n });\n continue;\n }\n\n // Answered before the resolver, because the resolver reads the\n // environment and the whole point of the managed database is that the\n // environment is deliberately empty. Only for a database nobody bound:\n // a developer who set `DATABASE_URL__ANALYTICS` to a warehouse of their\n // own has said which database that is, and the managed one fills a\n // vacuum, never a choice.\n if (managed && declaration.kind === \"database\" && bindings.every(b => !b.set && !b.fallback?.set)) {\n managedCovered += 1;\n resources.push({\n ...base,\n state: \"ready\",\n detail: managed.url\n ? \"the managed development database (PGlite), this project only\"\n : \"the managed development database (PGlite), this project only — \"\n + \"not running; start it with `rebase dev`\"\n });\n continue;\n }\n\n // The default database on Docker: the compose service, unless `.env`\n // names one itself.\n if (docker && declaration.kind === \"database\" && declaration.key === DEFAULT_RESOURCE_KEY\n && bindings.every(b => !b.set && !b.fallback?.set)) {\n resources.push({ ...base, state: \"ready\", detail: docker.detail });\n continue;\n }\n\n const judged = declaration.kind === \"database\" ? withDefaultUrl(env, devDefaultUrl) : env;\n const verdict = resolver.resolve(declaration, judged, { production, defaultBasePath: \"uploads\" });\n switch (verdict.state) {\n case \"ready\":\n resources.push({\n ...base,\n state: \"ready\",\n ...(verdict.standsIn ? { standsIn: verdict.standsIn } : {}),\n detail: verdict.detail ?? \"\"\n });\n break;\n case \"code\":\n resources.push({ ...base, state: \"ready\", detail: verdict.detail ?? \"needs no environment configuration\" });\n break;\n case \"unbound\":\n resources.push({ ...base, state: \"unconfigured\", detail: verdict.detail ?? \"declared, not configured\" });\n break;\n case \"blocked\":\n resources.push({\n ...base,\n // A database the environment names nothing for is the\n // ordinary first-run state, and reads as unconfigured; a\n // binding that is set and set wrongly is broken.\n state: implicit || bindings.every(b => !b.set && !b.fallback?.set) ? \"unconfigured\" : \"broken\",\n detail: verdict.detail ?? \"boot refuses this binding\"\n });\n break;\n }\n }\n\n // Only asked when every row already looks fine. Its failures overlap with\n // the per-resource ones, and a banner repeating a line printed two rows\n // above teaches nothing — what it is here for is the failure no row models,\n // such as a custom engine whose driver package cannot be resolved.\n let blocked: string | undefined;\n // Not run when the managed database answered for a row and is not running:\n // there is no connection string to check the set against, and inventing one\n // to keep the check formally \"run\" is how a green tick gets printed for\n // work nobody did. The row says the daemon is down; that is the finding.\n const managedSetUnknown = managedCovered > 0 && !managed?.url;\n if (resources.every(r => r.state === \"ready\") && !managedSetUnknown) {\n try {\n resolvers.resolveDataSources(\n // The managed URL for the rows it answered for, so the whole-set\n // check judges the same environment the runtime would get.\n managed?.url ? withManagedUrls(env, graph, managed.url) : withDefaultUrl(env, docker?.url),\n graph.resources.filter(r => r.kind === \"database\").map(resourceToDataSource)\n );\n } catch (err) {\n blocked = err instanceof Error ? err.message : String(err);\n }\n }\n\n return { resources, ...(blocked !== undefined ? { blocked } : {}) };\n}\n","/**\n * `rebase status` — what this project is, and whether it can reach its things.\n *\n * The model a developer has to hold is small and was nowhere visible:\n *\n * rebase.json where the code is, and who runs the server\n * config/resources.ts what the project needs\n * the environment how to reach each of them\n *\n * Everything else — `rebase.resources.json`, the bundle manifest — is a\n * generated copy of the middle one, for readers that cannot run the code. A\n * developer never writes them and should not have to think about them.\n *\n * This command prints the three together, resolved. It exists because the\n * question people actually arrive with — \"why does uploading to `media` answer\n * 501\" — was answerable only by knowing the `<BASE>__<KEY>` suffix rule,\n * deriving the variable name by hand, and checking it against a `.env` they had\n * to find first. Every step of that is mechanical, so it is printed instead.\n */\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { failAsJson, readEnvFile, requireProjectRoot } from \"../utils/project\";\nimport { findBackendApp, loadManifest, ManifestError, resolveBackendPaths } from \"../manifest\";\nimport { deriveOptionsFor, deriveResourceGraph, RESOURCE_GRAPH_FILENAME, readResourceGraphFile, serializeResourceGraph } from \"../resources/derive\";\nimport { computeStatus, type DockerDatabaseStatus, type ManagedDatabaseStatus, type ResourceStatus } from \"../resources/status\";\nimport { findRunningDaemon, managedUrl } from \"../dev-db/daemon\";\nimport { type ResolvedBranch, resolveProjectDatabaseAndBranch } from \"../dev-db/prepare\";\nimport { describeTarget } from \"../dev-db/pull\";\nimport { parseLoopbackDsn, probeTcp } from \"../utils/dev-preflight\";\nimport type { RebaseBackendAppConfig } from \"@rebasepro/types\";\n\nfunction usage(): void {\n console.log(`\n${chalk.bold(\"rebase status\")} — what this project declares, and whether it is configured\n\n${chalk.bold(\"Usage\")}\n rebase status Show every resource and the variables it reads\n rebase status --json The same, as JSON\n\n${chalk.bold(\"Reads\")}\n rebase.json which apps exist, and who owns the server process\n <config>/resources.ts the databases, buckets, topics and queues declared\n backend/crons, backend/functions the crons and functions, by filename\n .env whether each one's variables are set\n`);\n}\n\nconst MARK = {\n ready: chalk.green(\"✓\"),\n unconfigured: chalk.yellow(\"○\"),\n broken: chalk.red(\"✗\")\n} as const;\n\nfunction printResource(status: ResourceStatus): void {\n const name = status.key === \"(default)\" ? chalk.bold(\"(default)\") : chalk.bold(status.key);\n const tags = [chalk.gray(status.engine)];\n if (status.transport !== \"server\") tags.push(chalk.yellow(status.transport));\n if (status.account) tags.push(chalk.gray(`account:${status.account}`));\n if (status.implicit) tags.push(chalk.gray(\"implicit\"));\n // A stand-in is not a binding. It is shown in yellow beside a green tick:\n // uploads work here, and the same declaration answers 501 in production\n // until the variable is set.\n if (status.standsIn) tags.push(chalk.yellow(`local stand-in for ${status.standsIn}`));\n\n console.log(` ${MARK[status.state]} ${name} ${tags.join(\" · \")}`);\n if (status.usedBy && status.usedBy.length > 0) {\n console.log(` ${chalk.gray(\"used by\")} ${chalk.gray(status.usedBy.join(\", \"))}`);\n }\n\n let hiddenOptional = 0;\n for (const binding of status.bindings) {\n if (binding.set) {\n console.log(` ${chalk.green(\"✓\")} ${chalk.gray(binding.name)}`);\n } else if (binding.fallback?.set) {\n // Not a gap: the account form is the variable this bucket is\n // actually reading, and showing only the unset per-key name would\n // send someone to set the one they were deliberately avoiding.\n console.log(` ${chalk.green(\"✓\")} ${chalk.gray(binding.fallback.name)} ${chalk.gray(`(shared, for ${binding.name})`)}`);\n } else if (status.state === \"ready\") {\n // It resolved without this one, so this one is optional — which is\n // the resolver's answer, not a second table of required names kept\n // here. Listing seven unset optionals under a working database is\n // how a status view teaches people to skim past the line that\n // matters.\n hiddenOptional += 1;\n } else {\n const also = binding.fallback ? chalk.gray(` or ${binding.fallback.name}`) : \"\";\n console.log(` ${chalk.gray(\"·\")} ${chalk.gray(binding.name)}${also} ${chalk.gray(\"not set\")}`);\n }\n }\n if (hiddenOptional > 0) {\n console.log(chalk.gray(` ${hiddenOptional} optional variable${hiddenOptional === 1 ? \"\" : \"s\"} not set`));\n }\n\n if (status.detail) {\n const colour = status.state === \"broken\" ? chalk.red : status.state === \"unconfigured\" ? chalk.yellow : chalk.gray;\n console.log(` ${colour(`└ ${status.detail}`)}`);\n }\n}\n\n/** Which database `rebase status` reports the project on, and what it hands the status view about it. */\nexport interface StatusDatabase {\n managedDatabase?: ManagedDatabaseStatus;\n dockerDatabase?: DockerDatabaseStatus;\n /** The branch this checkout is on, when the database is one. */\n branch: ResolvedBranch | null;\n /** A switched-to branch the managed database cannot serve. */\n ignoredBranch: string | null;\n}\n\n/**\n * Which database this project is on, decided by the same ordered rule\n * `rebase dev` and `rebase db url` use — and read from the project's `.env`,\n * not from this shell: `rebase status` asks what *this project* is on.\n *\n * Nothing is started. `status` is a question, and a question that boots a\n * 180 MB Postgres to answer itself is a different command. So a managed\n * database that is not running is reported as exactly that, rather than as a\n * project with no database; and a compose database likewise, after a probe of\n * its port.\n *\n * `envFile` is the parsed `.env`; production stands nothing in, because there\n * an unset `DATABASE_URL` is the failure it has always been.\n *\n * Exported for its tests.\n */\nexport async function statusDatabase(projectRoot: string, envFile: Record<string, string>): Promise<StatusDatabase> {\n const { database, branch, ignoredBranch } = resolveProjectDatabaseAndBranch(projectRoot, { env: {} });\n if (envFile.NODE_ENV === \"production\") return { branch, ignoredBranch };\n\n if (database.kind === \"managed\") {\n const daemon = await findRunningDaemon(projectRoot);\n return { managedDatabase: { url: daemon ? managedUrl(daemon.port) : null }, branch, ignoredBranch };\n }\n\n if (database.kind === \"docker\" && database.url) {\n const target = parseLoopbackDsn(database.url);\n const listening = target ? await probeTcp(target.host, target.port) : true;\n const which = branch ? `branch \"${branch.name}\" (${branch.database}) of Postgres in Docker` : \"Postgres in Docker\";\n return {\n dockerDatabase: {\n url: database.url,\n detail: which + \", as the last `rebase dev --docker` did · \" + describeTarget(database.url)\n + (listening ? \"\" : \" — not running; `rebase dev --docker` starts it\")\n },\n branch,\n ignoredBranch\n };\n }\n\n return { branch, ignoredBranch };\n}\n\nexport async function statusCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) return usage();\n\n const { flags } = parseCommandArgs({\n spec: { \"--json\": Boolean },\n rawArgs,\n commandWords: 1,\n command: \"status\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n\n // Every exit below has a `--json` arm, because `--json` means stdout holds\n // one JSON object on *every* exit of the command. It used to mean that for\n // the one failure `requireProjectRoot` owns and nothing else, so a caller\n // parsing stdout got an envelope outside a project and an empty stream\n // inside a broken one — the case it actually has to handle.\n const asJson = Boolean(flags[\"--json\"]);\n\n let backend: { name: string; app: RebaseBackendAppConfig };\n try {\n const loaded = loadManifest(projectRoot);\n const found = findBackendApp(loaded.manifest);\n if (!found) {\n if (asJson) {\n failAsJson(\n \"This project declares no backend app, so it declares no resources.\",\n \"no_backend_app\",\n \"Add a backend app to rebase.json, or run `rebase apps init`.\"\n );\n }\n console.error(chalk.red(\"This project declares no backend app, so it declares no resources.\"));\n process.exitCode = 1;\n return;\n }\n backend = found;\n } catch (err) {\n if (err instanceof ManifestError) {\n if (asJson) {\n failAsJson(err.message, \"manifest_invalid\", \"Fix rebase.json, then run this again.\",\n err.issues.map(issue => ({ path: issue.path, message: issue.message })));\n }\n console.error(chalk.red(err.message));\n for (const issue of err.issues) console.error(` ${chalk.gray(issue.path)} ${issue.message}`);\n process.exitCode = 1;\n return;\n }\n throw err;\n }\n\n const { name: backendName, app: backendApp } = backend;\n const paths = resolveBackendPaths(backendApp, projectRoot);\n\n const { graph, issues } = await deriveResourceGraph(deriveOptionsFor(projectRoot, backendApp));\n if (issues.length > 0) {\n if (asJson) {\n failAsJson(\n `${issues.length} problem(s) in the declared resources.`,\n \"resource_declaration_invalid\",\n \"Fix the declarations the issues name, then run this again.\",\n issues.map(issue => ({ path: issue.path, message: issue.message }))\n );\n }\n console.error(chalk.red(`\\n✗ ${issues.length} problem(s) in the declared resources:\\n`));\n for (const issue of issues) console.error(` ${chalk.bold(issue.path)} ${issue.message}`);\n console.error(\"\");\n process.exitCode = 1;\n return;\n }\n\n // The project's own `.env`, not this process's environment: `rebase status`\n // is asking what a deployment of THIS repository would do, and the shell a\n // developer happens to be standing in is not that.\n const env = readEnvFile(projectRoot);\n\n const production = env.NODE_ENV === \"production\";\n const { managedDatabase, dockerDatabase, branch, ignoredBranch } = await statusDatabase(projectRoot, env);\n\n const server = await import(\"@rebasepro/server\");\n const { resources, blocked } = computeStatus(graph, env, {\n resolverFor: server.resourceResolver as never,\n resolveDataSources: server.resolveDataSources as never,\n // Judged as production when the .env says so; a stand-in local\n // directory for an unbound bucket is only ever offered to development.\n production,\n ...(managedDatabase ? { managedDatabase } : {}),\n ...(dockerDatabase ? { dockerDatabase } : {})\n });\n\n if (asJson) {\n console.log(JSON.stringify({\n backend: backendName,\n runtime: backendApp.runtime,\n ...(branch ? { branch: { name: branch.name, database: branch.database } } : {}),\n resources,\n blocked\n }, null, 2));\n return;\n }\n\n const ownership = backendApp.runtime === \"managed\"\n ? \"Rebase's runtime boots your bundle\"\n : \"this project builds its own image and entrypoint\";\n\n console.log(\"\");\n console.log(` ${chalk.bold(backendName)} ${chalk.gray(\"·\")} ${chalk.cyan(backendApp.runtime)} ${chalk.gray(ownership)}`);\n // Named whether or not it exists, and said plainly when it does not. A\n // project with no `resources.ts` is legal — it has one default database and\n // one default bucket — but \"declared in <a file you do not have>\" reads as\n // a broken install rather than as the default it is.\n const resourcesFile = path.join(paths.config, \"resources.ts\");\n const declaresAnything = fs.existsSync(path.join(projectRoot, resourcesFile));\n console.log(` ${chalk.gray(\"declared in\")} ${chalk.gray(resourcesFile)}${\n declaresAnything ? \"\" : chalk.gray(\" (none — the defaults below are implicit)\")}`);\n console.log(` ${chalk.gray(\"configured by\")} ${chalk.gray(\".env\")}`);\n // Every database command in this checkout uses the branch, so the view\n // says so: a switch made yesterday is easy to forget.\n if (branch) {\n console.log(` ${chalk.gray(\"on branch\")} ${chalk.bold(branch.name)} ${chalk.gray(`(${branch.database})`)}`\n + chalk.gray(` — ${chalk.cyan(\"rebase db branch switch --off\")} returns to ${branch.parent ?? \"the main database\"}`));\n } else if (ignoredBranch) {\n console.log(` ${chalk.yellow(\"○\")} ${chalk.gray(`switched to branch \"${ignoredBranch}\", which the managed database cannot serve — it uses the main one`)}`);\n }\n\n const kinds = [...new Set(resources.map(r => r.kind))];\n for (const kind of kinds) {\n console.log(\"\");\n console.log(` ${chalk.bold.underline(`${kind}s`)}`);\n for (const status of resources.filter(r => r.kind === kind)) printResource(status);\n }\n\n if (blocked) {\n console.log(\"\");\n console.log(` ${chalk.red(\"✗\")} ${chalk.red(blocked)}`);\n }\n\n // Only worth a line when it is wrong. A generated file that matches its\n // declarations is not news, and a status view that reports its own\n // bookkeeping as an item trains people to skim past the items that matter.\n //\n // Nor is one that has not been written yet: `rebase build` writes it on\n // every build and says \"commit it\" when it changes, so a project that has\n // never been built — every fresh scaffold — has nothing wrong with it.\n // `rebase resources --check` is the gate that refuses a missing one.\n const committed = readResourceGraphFile(projectRoot);\n if (committed !== null && committed !== serializeResourceGraph(graph)) {\n console.log(\"\");\n console.log(` ${chalk.yellow(\"○\")} ${RESOURCE_GRAPH_FILENAME} is stale — ${chalk.blue(\"rebase resources --write\")}`);\n console.log(chalk.gray(\" a host reads it to decide what to provision before it runs anything\"));\n }\n\n console.log(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoFA,SAAS,MAAM,KAAa,MAAuB;CAC/C,MAAM,QAAQ,IAAI;CAClB,OAAO,OAAO,UAAU,YAAY,UAAU;AAClD;;;;;;;;AASA,SAAgB,YACZ,aACA,KACA,oBACiB;CACjB,IAAI,YAAY,cAAc,UAAU,OAAO,CAAC;CAEhD,MAAM,SAAS,kBAAkB,YAAY,GAAG;CAChD,MAAM,UAAU,OAAO,YAAY,QAAQ,YAAY,WACjD,kBAAkB,YAAY,QAAQ,OAAO,IAC7C,KAAA;CAEN,OAAO,oBAAoB,WAAW,CAAC,CAAC,KAAK,SAAS;EAClD,MAAM,OAAO,GAAG,OAAO;EACvB,MAAM,UAA2B;GAAE;GAAM,KAAK,MAAM,KAAK,IAAI;EAAE;EAK/D,IAAI,YAAY,KAAA,KAAa,CAAC,QAAQ,OAAO,mBAAmB,SAAS,IAAI,GACzE,QAAQ,WAA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UAAU,GAAG,KAAK,EAAE,GAAG;EACnD,KAAK,MAAM,UAAU,UAAU,QAAO,MAAK,EAAE,SAAS,IAAI,GAAG,cAAc,MAAM;CACrF;CAEA,IAAI,SAAS;EACT,QAAQ,IAAI,EAAE;EACd,QAAQ,IAAI,KAAK,MAAM,IAAI,GAAG,EAAE,GAAG,MAAM,IAAI,OAAO,GAAG;CAC3D;CAUA,MAAM,YAAY,sBAAsB,WAAW;CACnD,IAAI,cAAc,QAAQ,cAAc,uBAAuB,KAAK,GAAG;EACnE,QAAQ,IAAI,EAAE;EACd,QAAQ,IAAI,KAAK,MAAM,OAAO,GAAG,EAAE,GAAG,wBAAwB,cAAc,MAAM,KAAK,0BAA0B,GAAG;EACpH,QAAQ,IAAI,MAAM,KAAK,2EAA2E,CAAC;CACvG;CAEA,QAAQ,IAAI,EAAE;AAClB"}
@@ -1,7 +1,6 @@
1
- import { d as readEnvFile, p as requireProjectRoot } from "./project-Wp2zoyeN.js";
2
- import { a as unknownCommand, n as parseCommandArgs, r as wantsHelp, t as UsageError } from "./args-BX0YD14a.js";
1
+ import { E as unknownCommand, b as UsageError, d as readEnvFile, p as requireProjectRoot, w as wantsHelp, x as parseCommandArgs } from "./project-CasK56vN.js";
3
2
  import { t as cliUserAgent } from "./version-Buyyo1ut.js";
4
- import { describeFailure, requireBackendUrl } from "./api-keys-Tm7zvAPe.js";
3
+ import { describeFailure, requireBackendUrl } from "./api-keys-CyJ26KEJ.js";
5
4
  import chalk from "chalk";
6
5
  import { RebaseApiError } from "@rebasepro/client";
7
6
  import readline from "node:readline/promises";
@@ -35,6 +34,8 @@ var MOVE_FLAGS = {
35
34
  "--delete-source": Boolean,
36
35
  "--json": Boolean
37
36
  };
37
+ /** How often a running scan is asked about. A setting so the tests need not wait. */
38
+ var orphanScanPolling = { intervalMs: 1e3 };
38
39
  /** The project's backend, holding the service key — the `admin` role, every scope. */
39
40
  function connect() {
40
41
  const projectRoot = requireProjectRoot();
@@ -133,6 +134,93 @@ async function confirm(question) {
133
134
  prompt.close();
134
135
  }
135
136
  }
137
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
138
+ /** Whether an error is a backend without the route asked for, as opposed to a source it does not serve. */
139
+ var isMissingRoute = (error) => error instanceof RebaseApiError && error.status === 404 && error.code !== "UNKNOWN_STORAGE_SOURCE" && error.code !== "STORAGE_SCAN_NOT_FOUND";
140
+ /** One line of a running scan's progress, rewritten in place on a terminal. */
141
+ function progressLine(text, quiet) {
142
+ if (!quiet && process.stdout.isTTY) process.stdout.write(`\r\x1b[2K ${text}`);
143
+ }
144
+ function endProgressLine(quiet) {
145
+ if (!quiet && process.stdout.isTTY) process.stdout.write("\n");
146
+ }
147
+ /** Ask for a scan's record until `done` says so, printing its progress. */
148
+ async function pollScan(backend, id, sourceQuery, done, describe, quiet) {
149
+ let noted = false;
150
+ for (;;) {
151
+ let state;
152
+ try {
153
+ state = await backend.request("GET", `/orphans/scans/${encodeURIComponent(id)}${sourceQuery}`);
154
+ } catch (error) {
155
+ endProgressLine(quiet);
156
+ fail("Failed to read the scan's progress", error, backend.baseUrl);
157
+ }
158
+ if (done(state)) {
159
+ endProgressLine(quiet);
160
+ return state;
161
+ }
162
+ progressLine(describe(state), quiet);
163
+ const note = state.note ?? state.deletion?.note;
164
+ if (note && !noted && !quiet) {
165
+ noted = true;
166
+ endProgressLine(quiet);
167
+ console.log(chalk.yellow(` ${note}`));
168
+ }
169
+ await sleep(orphanScanPolling.intervalMs);
170
+ }
171
+ }
172
+ /**
173
+ * Scan for orphans: started on the backend and asked about until it is done,
174
+ * so a scan longer than any request timeout still finishes. A backend from
175
+ * before scans ran in the background is asked the old way, in one request.
176
+ */
177
+ async function scanForOrphans(backend, query, sourceQuery, quiet) {
178
+ let started;
179
+ try {
180
+ started = await backend.request("POST", `/orphans/scans?${query}`);
181
+ } catch (error) {
182
+ if (!isMissingRoute(error)) fail("Failed to start a storage scan", error, backend.baseUrl);
183
+ try {
184
+ return { report: await backend.request("GET", `/orphans?${query}`) };
185
+ } catch (legacyError) {
186
+ fail("Failed to scan storage", legacyError, backend.baseUrl);
187
+ }
188
+ }
189
+ if (!quiet && started.runner === "in-process") console.log(chalk.gray(" This backend runs no job queue, so the scan runs inside the server process, in the background. A restart of that process stops it."));
190
+ const finished = await pollScan(backend, started.id, sourceQuery, (state) => state.status === "completed" || state.status === "failed", (state) => state.status === "queued" ? "Waiting for the scan to start…" : `Scanning "${state.storageId}": ${state.progress.filesScanned} file(s) listed, ${state.progress.rowsScanned} row(s) read, ${state.progress.collectionsScanned}/${state.progress.collectionsTotal} collection(s)` + (state.progress.unscanned.length > 0 ? `, ${state.progress.unscanned.length} unreadable` : "") + "…", quiet);
191
+ if (finished.status === "failed" || !finished.result) {
192
+ console.error(chalk.red(`✗ The scan failed: ${finished.error ?? "no reason was recorded"}`));
193
+ process.exit(1);
194
+ }
195
+ return {
196
+ report: {
197
+ storageId: finished.storageId,
198
+ ...finished.result
199
+ },
200
+ scanId: finished.id
201
+ };
202
+ }
203
+ /** Delete a completed scan's orphans, in the background, and wait for it. */
204
+ async function deleteFromScan(backend, scanId, sourceQuery, quiet) {
205
+ const deleteQuery = new URLSearchParams(sourceQuery.replace(/^\?/, ""));
206
+ deleteQuery.set("scan", scanId);
207
+ try {
208
+ await backend.request("DELETE", `/orphans?${deleteQuery}`);
209
+ } catch (error) {
210
+ fail("Failed to delete unused files", error, backend.baseUrl);
211
+ }
212
+ const deletion = (await pollScan(backend, scanId, sourceQuery, (state) => state.deletion?.status === "completed" || state.deletion?.status === "failed", (state) => {
213
+ const progress = state.deletion?.progress;
214
+ if (!progress || state.deletion?.status === "queued") return "Waiting for the delete to start…";
215
+ return progress.phase === "deleting" ? `Deleting: ${progress.deleted} of ${progress.candidates} file(s)…` : `Checking every row again before deleting: ${progress.rowsScanned} row(s) read, ${progress.collectionsScanned}/${progress.collectionsTotal} collection(s)…`;
216
+ }, quiet)).deletion;
217
+ return {
218
+ deleted: deletion.result?.deleted ?? [],
219
+ failed: deletion.result?.failed ?? [],
220
+ kept: deletion.result?.kept ?? [],
221
+ ...deletion.status === "failed" ? { error: deletion.error ?? "no reason was recorded" } : {}
222
+ };
223
+ }
136
224
  async function orphans(rawArgs) {
137
225
  const { flags } = parseCommandArgs({
138
226
  spec: ORPHANS_FLAGS,
@@ -145,16 +233,16 @@ async function orphans(rawArgs) {
145
233
  if (!Number.isFinite(olderThan) || olderThan < 0) throw new UsageError("--older-than takes a number of hours, 0 or more.");
146
234
  const query = new URLSearchParams({ olderThanHours: String(olderThan) });
147
235
  if (flags["--source"]) query.set("storageId", flags["--source"]);
236
+ const sourceQuery = flags["--source"] ? `?${new URLSearchParams({ storageId: flags["--source"] })}` : "";
237
+ const quiet = flags["--json"] === true;
148
238
  const backend = connect();
149
- let report;
150
- try {
151
- report = await backend.request("GET", `/orphans?${query}`);
152
- } catch (error) {
153
- fail("Failed to scan storage", error, backend.baseUrl);
154
- }
239
+ const { report, scanId } = await scanForOrphans(backend, query, sourceQuery, quiet);
155
240
  if (!flags["--delete"]) {
156
241
  if (flags["--json"]) {
157
- console.log(JSON.stringify(report, null, 2));
242
+ console.log(JSON.stringify({
243
+ ...report,
244
+ ...scanId ? { scanId } : {}
245
+ }, null, 2));
158
246
  return;
159
247
  }
160
248
  console.log("");
@@ -184,18 +272,25 @@ async function orphans(rawArgs) {
184
272
  }
185
273
  }
186
274
  let result;
187
- try {
275
+ if (scanId) result = await deleteFromScan(backend, scanId, sourceQuery, quiet);
276
+ else try {
188
277
  result = await backend.request("DELETE", `/orphans?${query}`);
189
278
  } catch (error) {
190
279
  fail("Failed to delete unused files", error, backend.baseUrl);
191
280
  }
192
- if (flags["--json"]) console.log(JSON.stringify(result, null, 2));
281
+ if (flags["--json"]) console.log(JSON.stringify({
282
+ storageId: report.storageId,
283
+ ...result,
284
+ recent: report.recent
285
+ }, null, 2));
193
286
  else {
287
+ if (result.error) console.error(chalk.red(` ✗ ${result.error}`));
194
288
  console.log(chalk.green(` ✓ Deleted ${result.deleted.length} file(s).`));
289
+ for (const kept of result.kept ?? []) console.log(chalk.yellow(` Kept ${kept.key}: ${kept.reason}`));
195
290
  for (const failure of result.failed) console.error(chalk.red(` ✗ ${failure.key}: ${failure.error}`));
196
291
  console.log("");
197
292
  }
198
- if (result.failed.length > 0) process.exitCode = 1;
293
+ if (result.failed.length > 0 || result.error) process.exitCode = 1;
199
294
  }
200
295
  async function move(rawArgs) {
201
296
  const { flags } = parseCommandArgs({
@@ -238,17 +333,60 @@ async function move(rawArgs) {
238
333
  if (!flags["--json"] && process.stdout.isTTY) process.stdout.write(`\r ${counts.copied} copied, ${counts.exists} already there, ${counts.failed} failed…`);
239
334
  cursor = page.cursor;
240
335
  } while (cursor);
336
+ const verified = await listLeftBehind(backend, {
337
+ from,
338
+ to,
339
+ prefix: flags["--prefix"],
340
+ deleteSource: flags["--delete-source"] === true
341
+ }, flags["--json"] === true);
342
+ const reported = new Set(failures.map((failure) => failure.key));
343
+ const leftBehind = verified?.filter((entry) => !reported.has(entry.key)) ?? [];
241
344
  if (flags["--json"]) console.log(JSON.stringify({
242
345
  ...counts,
243
- failures
346
+ failures,
347
+ verified: verified !== void 0,
348
+ notMoved: verified ?? []
244
349
  }, null, 2));
245
350
  else {
246
351
  if (process.stdout.isTTY) process.stdout.write("\n");
247
352
  console.log(chalk.green(` ✓ ${counts.copied} copied, ${counts.exists} already there${flags["--delete-source"] ? `, ${counts.deleted} deleted from the source` : ""}.`));
248
353
  for (const failure of failures) console.error(chalk.red(` ✗ ${failure.key}: ${failure.error ?? "failed"}`));
354
+ if (verified === void 0) console.log(chalk.gray(" This backend cannot list the source again (it needs a backend newer than 0.25.1), so the CLI did not check for files the move left behind."));
355
+ else if (leftBehind.length > 0) {
356
+ console.error(chalk.red(` ✗ Listed again, the source holds ${leftBehind.length} more file(s) the move did not report: ${leftBehind.length} file(s) were not moved.`));
357
+ for (const entry of leftBehind) console.error(chalk.red(` ${entry.key}: ${entry.reason}`));
358
+ console.error(chalk.gray(" Run the same move again to pick them up."));
359
+ }
249
360
  if (counts.copied + counts.exists > 0 && !flags["--delete-source"]) console.log(chalk.gray(" The source keeps its copies. Point the property at the new source, then run again with --delete-source."));
250
361
  }
251
- if (failures.length > 0) process.exitCode = 1;
362
+ if (failures.length > 0 || leftBehind.length > 0) process.exitCode = 1;
363
+ }
364
+ /**
365
+ * Every file under the moved folder the move did not move, read by the
366
+ * backend's `/move/verify` — or `undefined` from a backend without it.
367
+ */
368
+ async function listLeftBehind(backend, request, quiet) {
369
+ const notMoved = [];
370
+ let cursor;
371
+ let checked = 0;
372
+ do {
373
+ let page;
374
+ try {
375
+ page = await backend.request("POST", "/move/verify", {
376
+ ...request,
377
+ ...cursor ? { cursor } : {},
378
+ limit: 500
379
+ });
380
+ } catch (error) {
381
+ if (error instanceof RebaseApiError && error.status === 404 && error.code !== "UNKNOWN_STORAGE_SOURCE") return void 0;
382
+ fail("Failed to list the source again after the move", error, backend.baseUrl);
383
+ }
384
+ checked += page.checked;
385
+ notMoved.push(...page.notMoved);
386
+ if (!quiet && process.stdout.isTTY) process.stdout.write(`\r Checking the source again: ${checked} file(s) listed…`);
387
+ cursor = page.cursor;
388
+ } while (cursor);
389
+ return notMoved;
252
390
  }
253
391
  async function storageCommand(subcommand, rawArgs) {
254
392
  if (!subcommand || subcommand === "--help" || wantsHelp(rawArgs)) {
@@ -297,10 +435,15 @@ ${chalk.green.bold("Notes")}
297
435
  panel uploads a file before the row that names it is saved. Files your own
298
436
  tables name, outside collections, are not seen: check before deleting.
299
437
 
438
+ The scan runs on the backend in the background — a ${chalk.blue("storage.orphans")} job
439
+ on the job queue, or inside the server process when there is none — and the
440
+ CLI shows its progress until it is done. ${chalk.blue("--delete")} deletes from that scan
441
+ only; the backend reads every row again and asks for each file again first.
442
+
300
443
  Both read ${chalk.blue("REBASE_SERVICE_KEY")} from .env and need the backend running.
301
444
  `);
302
445
  }
303
446
  //#endregion
304
447
  export { STORAGE_SUBCOMMANDS, storageCommand };
305
448
 
306
- //# sourceMappingURL=storage-DKPUBTWG.js.map
449
+ //# sourceMappingURL=storage-DtOXGflp.js.map