@rebasepro/cli 0.30.1 → 0.31.0-canary.g902a0ce

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 (283) hide show
  1. package/README.md +8 -7
  2. package/dist/{agent-setup-0uyfC7VX.js → agent-setup-DqAcoDcn.js} +10 -5
  3. package/dist/{agent-setup-0uyfC7VX.js.map → agent-setup-DqAcoDcn.js.map} +1 -1
  4. package/dist/{api-keys-Dfw5-9s1.js → api-keys-eIUjMqWn.js} +8 -7
  5. package/dist/api-keys-eIUjMqWn.js.map +1 -0
  6. package/dist/{apps-MKQbgDtN.js → apps-DExO4PEl.js} +8 -7
  7. package/dist/apps-DExO4PEl.js.map +1 -0
  8. package/dist/{project-CasK56vN.js → args-CaCcrYE1.js} +2 -351
  9. package/dist/args-CaCcrYE1.js.map +1 -0
  10. package/dist/{atlas-dev-database-BODqdCWt.js → atlas-dev-database-DOCKk6ht.js} +2 -2
  11. package/dist/{atlas-dev-database-BODqdCWt.js.map → atlas-dev-database-DOCKk6ht.js.map} +1 -1
  12. package/dist/{auth-Bv0rTbQX.js → auth-CyADghFQ.js} +7 -6
  13. package/dist/{auth-Bv0rTbQX.js.map → auth-CyADghFQ.js.map} +1 -1
  14. package/dist/backend-guard-C0mVkXBw.js +162 -0
  15. package/dist/backend-guard-C0mVkXBw.js.map +1 -0
  16. package/dist/{branch-pointer-BQUF6lYa.js → branch-pointer-DMPyvZoK.js} +1 -1
  17. package/dist/{build-BuKTnec8.js → build-CA5R07tw.js} +29 -9
  18. package/dist/build-CA5R07tw.js.map +1 -0
  19. package/dist/{bundle-BAH4FCju.js → bundle-DgILeA5b.js} +112 -138
  20. package/dist/bundle-DgILeA5b.js.map +1 -0
  21. package/dist/bundle.d.ts +35 -12
  22. package/dist/cli.d.ts +2 -2
  23. package/dist/{cloud-DtADfWwn.js → cloud-CYMk92iG.js} +72 -71
  24. package/dist/cloud-CYMk92iG.js.map +1 -0
  25. package/dist/cms-directories-BK3vcswg.js +33 -0
  26. package/dist/cms-directories-BK3vcswg.js.map +1 -0
  27. package/dist/codemod/collections-to-tables/ast.d.ts +135 -0
  28. package/dist/codemod/collections-to-tables/backend.d.ts +38 -0
  29. package/dist/codemod/collections-to-tables/command.d.ts +35 -0
  30. package/dist/codemod/collections-to-tables/comments.d.ts +45 -0
  31. package/dist/codemod/collections-to-tables/customization.d.ts +47 -0
  32. package/dist/codemod/collections-to-tables/dynamic-props.d.ts +34 -0
  33. package/dist/codemod/collections-to-tables/export-changes.d.ts +83 -0
  34. package/dist/codemod/collections-to-tables/firestore.d.ts +11 -0
  35. package/dist/codemod/collections-to-tables/helper-hooks.d.ts +41 -0
  36. package/dist/codemod/collections-to-tables/hooks.d.ts +44 -0
  37. package/dist/codemod/collections-to-tables/journal.d.ts +10 -0
  38. package/dist/codemod/collections-to-tables/legacy-shims.d.ts +52 -0
  39. package/dist/codemod/collections-to-tables/load-legacy.d.ts +81 -0
  40. package/dist/codemod/collections-to-tables/migrate.d.ts +20 -0
  41. package/dist/codemod/collections-to-tables/modules.d.ts +127 -0
  42. package/dist/codemod/collections-to-tables/moved-imports.d.ts +70 -0
  43. package/dist/codemod/collections-to-tables/moved-symbols.generated.d.ts +12 -0
  44. package/dist/codemod/collections-to-tables/own.d.ts +10 -0
  45. package/dist/codemod/collections-to-tables/path-aliases.d.ts +26 -0
  46. package/dist/codemod/collections-to-tables/plan-context.d.ts +49 -0
  47. package/dist/codemod/collections-to-tables/print-js.d.ts +44 -0
  48. package/dist/codemod/collections-to-tables/project-files.d.ts +144 -0
  49. package/dist/codemod/collections-to-tables/repoint.d.ts +50 -0
  50. package/dist/codemod/collections-to-tables/row-hands.d.ts +7 -0
  51. package/dist/codemod/collections-to-tables/sdk-calls.d.ts +88 -0
  52. package/dist/codemod/collections-to-tables/skills-step.d.ts +13 -0
  53. package/dist/codemod/collections-to-tables/split-constants.d.ts +42 -0
  54. package/dist/codemod/collections-to-tables/storage-paths.d.ts +28 -0
  55. package/dist/codemod/collections-to-tables/types.d.ts +164 -0
  56. package/dist/codemod/collections-to-tables/verify.d.ts +27 -0
  57. package/dist/codemod/collections-to-tables/vocabulary.d.ts +40 -0
  58. package/dist/command-D5lhW_-B.js +9984 -0
  59. package/dist/command-D5lhW_-B.js.map +1 -0
  60. package/dist/commands/agent-setup.d.ts +6 -2
  61. package/dist/commands/cloud/context.d.ts +1 -1
  62. package/dist/commands/cloud/init.d.ts +2 -2
  63. package/dist/commands/console.d.ts +1 -2
  64. package/dist/commands/db.d.ts +5 -6
  65. package/dist/commands/dev.d.ts +18 -17
  66. package/dist/commands/doctor.d.ts +4 -5
  67. package/dist/commands/eject.d.ts +17 -13
  68. package/dist/commands/generate-view.d.ts +20 -9
  69. package/dist/commands/generate_sdk.d.ts +27 -27
  70. package/dist/commands/init.d.ts +21 -8
  71. package/dist/commands/migrate.d.ts +24 -0
  72. package/dist/commands/schema-reconcile.d.ts +1 -1
  73. package/dist/commands/skills.d.ts +8 -0
  74. package/dist/commands/verify-cms.d.ts +28 -0
  75. package/dist/commands/verify.d.ts +14 -9
  76. package/dist/{consent-BD7F29T3.js → consent-BXLIrMl8.js} +2 -2
  77. package/dist/{consent-BD7F29T3.js.map → consent-BXLIrMl8.js.map} +1 -1
  78. package/dist/{console-CdwIYOMV.js → console-CMjhgMUE.js} +14 -14
  79. package/dist/console-CMjhgMUE.js.map +1 -0
  80. package/dist/{context-AXdAh-q8.js → context--JwaHaZp.js} +6 -5
  81. package/dist/context--JwaHaZp.js.map +1 -0
  82. package/dist/{daemon-Cp7oNXth.js → daemon-w30PsdwV.js} +2 -2
  83. package/dist/{daemon-Cp7oNXth.js.map → daemon-w30PsdwV.js.map} +1 -1
  84. package/dist/{db-DBbKpjYX.js → db-A7XDCIIO.js} +51 -51
  85. package/dist/db-A7XDCIIO.js.map +1 -0
  86. package/dist/{derive-ae9UOoOB.js → derive-C3ezmY-p.js} +105 -133
  87. package/dist/derive-C3ezmY-p.js.map +1 -0
  88. package/dist/dev-db/attver.d.ts +11 -0
  89. package/dist/{dev-preflight-Cxv3TiD1.js → dev-preflight-DjvcV6SK.js} +5 -5
  90. package/dist/dev-preflight-DjvcV6SK.js.map +1 -0
  91. package/dist/{dev-server-OJsUGZEB.js → dev-server-BLxCbQEP.js} +2 -2
  92. package/dist/{dev-server-OJsUGZEB.js.map → dev-server-BLxCbQEP.js.map} +1 -1
  93. package/dist/{dev-C93d4QIv.js → dev-tWwPyWkQ.js} +142 -84
  94. package/dist/dev-tWwPyWkQ.js.map +1 -0
  95. package/dist/{doctor-BBPQUO2g.js → doctor-BBM0dWvZ.js} +39 -62
  96. package/dist/doctor-BBM0dWvZ.js.map +1 -0
  97. package/dist/doctor-environment.d.ts +6 -6
  98. package/dist/{eject-DABcDnPN.js → eject-Bhzd6hgb.js} +25 -16
  99. package/dist/eject-Bhzd6hgb.js.map +1 -0
  100. package/dist/{fold-static-BWzxNn06.js → fold-static-CKewnAPX.js} +5 -3
  101. package/dist/fold-static-CKewnAPX.js.map +1 -0
  102. package/dist/{generate-view-IFwCADvb.js → generate-view-CTOluXvH.js} +160 -89
  103. package/dist/generate-view-CTOluXvH.js.map +1 -0
  104. package/dist/{generate_sdk-DNmNuFuW.js → generate_sdk-De-aLC1L.js} +120 -137
  105. package/dist/generate_sdk-De-aLC1L.js.map +1 -0
  106. package/dist/import-schema-module-Df67TIWj.js +51 -0
  107. package/dist/import-schema-module-Df67TIWj.js.map +1 -0
  108. package/dist/index.es.js +64 -51
  109. package/dist/index.es.js.map +1 -1
  110. package/dist/{init-vL1DWOeC.js → init-Dtl-IcXf.js} +83 -80
  111. package/dist/init-Dtl-IcXf.js.map +1 -0
  112. package/dist/last-dev-database-Dc8cP01o.js +2 -0
  113. package/dist/{manifest-BtzDy7KQ.js → manifest-C3uLDrrJ.js} +115 -40
  114. package/dist/manifest-C3uLDrrJ.js.map +1 -0
  115. package/dist/manifest.d.ts +79 -24
  116. package/dist/migrate-VrKoi3nB.js +138 -0
  117. package/dist/migrate-VrKoi3nB.js.map +1 -0
  118. package/dist/{normalize-imports-Bd5Y4yLp.js → normalize-imports-DwxqEMYq.js} +3 -3
  119. package/dist/{normalize-imports-Bd5Y4yLp.js.map → normalize-imports-DwxqEMYq.js.map} +1 -1
  120. package/dist/path-flags-7O5uPBcQ.js +139 -0
  121. package/dist/path-flags-7O5uPBcQ.js.map +1 -0
  122. package/dist/{prepare-CTw9NEkh.js → prepare-Ccxspoj-.js} +4 -4
  123. package/dist/{prepare-CTw9NEkh.js.map → prepare-Ccxspoj-.js.map} +1 -1
  124. package/dist/project-CLcF5i8c.js +360 -0
  125. package/dist/project-CLcF5i8c.js.map +1 -0
  126. package/dist/project-schema-CsSOG2gE.js +30 -0
  127. package/dist/project-schema-CsSOG2gE.js.map +1 -0
  128. package/dist/{pull-DDMpsZ5r.js → pull-D9WvpDYY.js} +189 -1
  129. package/dist/pull-D9WvpDYY.js.map +1 -0
  130. package/dist/resolve-BY7bSFRT.js +2 -0
  131. package/dist/resources/derive.d.ts +19 -13
  132. package/dist/{resources-CPSC5Kcu.js → resources-Dpfs2y8P.js} +5 -4
  133. package/dist/{resources-CPSC5Kcu.js.map → resources-Dpfs2y8P.js.map} +1 -1
  134. package/dist/{schema-DtLPsXbT.js → schema-DwFDI1iU.js} +41 -39
  135. package/dist/schema-DwFDI1iU.js.map +1 -0
  136. package/dist/schema-dir-Cd1kvYbf.js +98 -0
  137. package/dist/schema-dir-Cd1kvYbf.js.map +1 -0
  138. package/dist/schema-reconcile-Tto54Qbv.js +2 -0
  139. package/dist/schema-text-CpNrsuMe.js +73 -0
  140. package/dist/schema-text-CpNrsuMe.js.map +1 -0
  141. package/dist/{skills-CbwV6vw_.js → skills-CXjA9TWw.js} +54 -10
  142. package/dist/skills-CXjA9TWw.js.map +1 -0
  143. package/dist/{start-YOr3X5Zm.js → start-Bwbtt2W5.js} +7 -10
  144. package/dist/{start-YOr3X5Zm.js.map → start-Bwbtt2W5.js.map} +1 -1
  145. package/dist/{status-BREvtzJm.js → status-DQ_PPz4C.js} +12 -12
  146. package/dist/status-DQ_PPz4C.js.map +1 -0
  147. package/dist/{storage-CO9ouK76.js → storage-iTqj5-Av.js} +12 -11
  148. package/dist/storage-iTqj5-Av.js.map +1 -0
  149. package/dist/{telemetry-DwK5RQJl.js → telemetry-BP_1Cl9r.js} +4 -4
  150. package/dist/{telemetry-DwK5RQJl.js.map → telemetry-BP_1Cl9r.js.map} +1 -1
  151. package/dist/{telemetry-CgwJPVMO.js → telemetry-M3HjlyhZ.js} +2 -2
  152. package/dist/{telemetry-CgwJPVMO.js.map → telemetry-M3HjlyhZ.js.map} +1 -1
  153. package/dist/{upgrade-B7sVwL8S.js → upgrade-oZzJ13jM.js} +5 -4
  154. package/dist/{upgrade-B7sVwL8S.js.map → upgrade-oZzJ13jM.js.map} +1 -1
  155. package/dist/utils/backend-guard.d.ts +47 -0
  156. package/dist/utils/cms-directories.d.ts +6 -0
  157. package/dist/utils/dev-preflight.d.ts +2 -2
  158. package/dist/utils/import-schema-module.d.ts +16 -0
  159. package/dist/utils/path-flags.d.ts +35 -16
  160. package/dist/utils/project-schema.d.ts +40 -0
  161. package/dist/utils/project.d.ts +8 -2
  162. package/dist/utils/schema-dir.d.ts +32 -0
  163. package/dist/utils/schema-drift.d.ts +6 -0
  164. package/dist/utils/schema-text.d.ts +24 -0
  165. package/dist/verify-DkJqhYPI.js +1160 -0
  166. package/dist/verify-DkJqhYPI.js.map +1 -0
  167. package/package.json +11 -8
  168. package/runtime/dev-server.mjs +5 -1
  169. package/templates/eject/Dockerfile +1 -4
  170. package/templates/eject/backend/src/env.ts +1 -1
  171. package/templates/eject/backend/src/index.ts +53 -40
  172. package/templates/eject/docker-compose.custom.yml +1 -1
  173. package/templates/overlays/baas/README.md +39 -12
  174. package/templates/overlays/baas/ai-instructions.md +8 -8
  175. package/templates/overlays/baas/{config → backend}/storage.ts +3 -4
  176. package/templates/overlays/baas/backend/tsconfig.json +10 -12
  177. package/templates/overlays/baas/package.json +1 -2
  178. package/templates/overlays/baas/pnpm-workspace.yaml +0 -1
  179. package/templates/presets/blank/backend/schema/index.ts +19 -0
  180. package/templates/presets/blank/frontend/src/App.tsx +56 -0
  181. package/templates/presets/ecommerce/backend/schema/categories.ts +12 -0
  182. package/templates/presets/ecommerce/backend/schema/index.ts +23 -0
  183. package/templates/presets/ecommerce/backend/schema/orders.ts +13 -0
  184. package/templates/presets/ecommerce/backend/schema/products.ts +18 -0
  185. package/templates/presets/ecommerce/frontend/src/App.tsx +59 -0
  186. package/templates/presets/ecommerce/frontend/src/cms/categories.tsx +12 -0
  187. package/templates/presets/ecommerce/frontend/src/cms/orders.tsx +38 -0
  188. package/templates/presets/ecommerce/frontend/src/cms/products.tsx +27 -0
  189. package/templates/resource-graphs/blank.json +2 -2
  190. package/templates/resource-graphs/blog.json +5 -5
  191. package/templates/resource-graphs/ecommerce.json +5 -5
  192. package/templates/resource-graphs/headless.json +1 -1
  193. package/templates/template/.claude/hooks/post-edit-collection.sh +27 -23
  194. package/templates/template/.cursorrules +2 -2
  195. package/templates/template/.env.example +6 -17
  196. package/templates/template/.github/copilot-instructions.md +2 -2
  197. package/templates/template/.windsurfrules +2 -2
  198. package/templates/template/AGENTS.md +2 -2
  199. package/templates/template/CLAUDE.md +2 -2
  200. package/templates/template/README.md +47 -13
  201. package/templates/template/ai-instructions.md +15 -14
  202. package/templates/template/backend/functions/hello.ts +1 -1
  203. package/templates/template/backend/package.json +0 -2
  204. package/templates/template/{config → backend}/resources.ts +3 -3
  205. package/templates/template/backend/schema/authors.ts +11 -0
  206. package/templates/template/backend/schema/index.ts +29 -0
  207. package/templates/template/backend/schema/posts.ts +29 -0
  208. package/templates/template/backend/schema/tags.ts +9 -0
  209. package/templates/template/backend/schema/users.ts +32 -0
  210. package/templates/template/{config → backend}/storage.ts +4 -4
  211. package/templates/template/backend/tsconfig.json +15 -20
  212. package/templates/template/docker-compose.yml +3 -3
  213. package/templates/template/frontend/package.json +0 -2
  214. package/templates/template/frontend/src/App.tsx +10 -4
  215. package/templates/template/frontend/src/cms/authors.tsx +7 -0
  216. package/templates/template/frontend/src/cms/posts.tsx +27 -0
  217. package/templates/template/frontend/src/cms/tags.tsx +11 -0
  218. package/templates/template/frontend/src/cms/ui-config.json +3 -0
  219. package/templates/template/frontend/src/cms/users.tsx +54 -0
  220. package/templates/template/frontend/src/{virtual.d.ts → vite-env.d.ts} +0 -4
  221. package/templates/template/frontend/vite.config.ts +6 -2
  222. package/templates/template/gitignore +1 -1
  223. package/templates/template/package.json +1 -2
  224. package/templates/template/pnpm-workspace.yaml +0 -1
  225. package/templates/template/scripts/example.ts +3 -3
  226. package/templates/template/tsconfig.json +1 -1
  227. package/templates/views/AppView.tsx.tmpl +4 -4
  228. package/templates/views/EntityView.tsx.tmpl +3 -4
  229. package/dist/api-keys-Dfw5-9s1.js.map +0 -1
  230. package/dist/apps-MKQbgDtN.js.map +0 -1
  231. package/dist/build-BuKTnec8.js.map +0 -1
  232. package/dist/bundle-BAH4FCju.js.map +0 -1
  233. package/dist/cloud-DtADfWwn.js.map +0 -1
  234. package/dist/collection-drift-BKj_BoMq.js +0 -106
  235. package/dist/collection-drift-BKj_BoMq.js.map +0 -1
  236. package/dist/collections-dir-DlvDhime.js +0 -69
  237. package/dist/collections-dir-DlvDhime.js.map +0 -1
  238. package/dist/console-CdwIYOMV.js.map +0 -1
  239. package/dist/context-AXdAh-q8.js.map +0 -1
  240. package/dist/db-DBbKpjYX.js.map +0 -1
  241. package/dist/derive-ae9UOoOB.js.map +0 -1
  242. package/dist/dev-C93d4QIv.js.map +0 -1
  243. package/dist/dev-preflight-Cxv3TiD1.js.map +0 -1
  244. package/dist/doctor-BBPQUO2g.js.map +0 -1
  245. package/dist/eject-DABcDnPN.js.map +0 -1
  246. package/dist/fold-static-BWzxNn06.js.map +0 -1
  247. package/dist/generate-view-IFwCADvb.js.map +0 -1
  248. package/dist/generate_sdk-DNmNuFuW.js.map +0 -1
  249. package/dist/init-vL1DWOeC.js.map +0 -1
  250. package/dist/last-dev-database-DpW5dfoX.js +0 -2
  251. package/dist/manifest-BtzDy7KQ.js.map +0 -1
  252. package/dist/path-flags-DNvtEi2-.js +0 -92
  253. package/dist/path-flags-DNvtEi2-.js.map +0 -1
  254. package/dist/project-CasK56vN.js.map +0 -1
  255. package/dist/pull-DDMpsZ5r.js.map +0 -1
  256. package/dist/resolve-D647F1LA.js +0 -2
  257. package/dist/schema-DtLPsXbT.js.map +0 -1
  258. package/dist/schema-reconcile-DkArN9jF.js +0 -2
  259. package/dist/skills-CbwV6vw_.js.map +0 -1
  260. package/dist/status-BREvtzJm.js.map +0 -1
  261. package/dist/storage-CO9ouK76.js.map +0 -1
  262. package/dist/utils/collection-drift.d.ts +0 -27
  263. package/dist/utils/collections-dir.d.ts +0 -14
  264. package/dist/verify-Y3rWSgfA.js +0 -730
  265. package/dist/verify-Y3rWSgfA.js.map +0 -1
  266. package/templates/overlays/baas/config/index.ts +0 -24
  267. package/templates/overlays/baas/config/package.json +0 -30
  268. package/templates/template/config/cms.d.ts +0 -15
  269. package/templates/template/config/collections/authors.ts +0 -47
  270. package/templates/template/config/collections/index.ts +0 -44
  271. package/templates/template/config/collections/posts.ts +0 -94
  272. package/templates/template/config/collections/presets/blank/index.ts +0 -5
  273. package/templates/template/config/collections/presets/ecommerce/categories.ts +0 -42
  274. package/templates/template/config/collections/presets/ecommerce/index.ts +0 -31
  275. package/templates/template/config/collections/presets/ecommerce/orders.ts +0 -78
  276. package/templates/template/config/collections/presets/ecommerce/products.ts +0 -73
  277. package/templates/template/config/collections/tags.ts +0 -27
  278. package/templates/template/config/collections/users.ts +0 -149
  279. package/templates/template/config/frontend-assets.d.ts +0 -17
  280. package/templates/template/config/index.ts +0 -12
  281. package/templates/template/config/package.json +0 -30
  282. package/templates/template/config/tsconfig.json +0 -35
  283. /package/templates/eject/{config → backend}/resources.ts +0 -0
@@ -0,0 +1,1160 @@
1
+ import { a as wantsHelp, n as parseCommandArgs } from "./args-CaCcrYE1.js";
2
+ import { a as findBackendDir, d as readEnvFile, i as failAsJson, l as getActiveBackendPlugin, p as requireProjectRoot } from "./project-CLcF5i8c.js";
3
+ import { n as resolveSchemaDir } from "./schema-dir-Cd1kvYbf.js";
4
+ import { a as refuseRemovedCollectionsFlag, n as SCHEMA_DIR_FLAG_HELP, r as missingSchemaDir } from "./path-flags-7O5uPBcQ.js";
5
+ import { t as cmsDirectories } from "./cms-directories-BK3vcswg.js";
6
+ import { t as loadProjectSchema } from "./project-schema-CsSOG2gE.js";
7
+ import { a as backendGuardMissingMessage, n as BACKEND_GUARD_FIX, o as backendGuardStates } from "./backend-guard-C0mVkXBw.js";
8
+ import chalk from "chalk";
9
+ import fs from "fs";
10
+ import path from "path";
11
+ import { parseEnvBoolean } from "@rebasepro/types";
12
+ import { isSchemaDefinitionError } from "@rebasepro/common";
13
+ //#region src/commands/verify-cms.ts
14
+ /**
15
+ * `rebase verify`, step "CMS customizations": the project's
16
+ * `customizeTable(...)` calls held to the tables they customize.
17
+ *
18
+ * The panel applies a customization at runtime and, for a slug or a field the
19
+ * tables do not have, only warns in the browser console in development
20
+ * (`applyTableCustomizations`). An agent that misspells a slug, keeps a field
21
+ * after renaming its column, or hides a required column from the form ships a
22
+ * panel that silently ignores the edit — or one that cannot create a record.
23
+ * The post-edit hook runs `rebase verify` after edits under `frontend/src/cms`,
24
+ * so this step is what answers for those files.
25
+ *
26
+ * **Read statically.** A customization module imports `@rebasepro/cms` (React,
27
+ * the browser panel) and the project's own components, so it cannot be
28
+ * imported in Node without the frontend's toolchain. The calls are read with
29
+ * ts-morph instead: the slug, the keys of `fields`, and the literal values of
30
+ * the form options of each field. What a static read cannot see — a slug or
31
+ * options computed at runtime, a spread, a computed key, a `dynamicProps` /
32
+ * `conditions` that hides a field on some records, a global `beforeSave` hook
33
+ * in `backend/hooks.ts` that fills a column — is either reported as not read
34
+ * (`cms-not-static`) or not judged; it is never reported as a problem.
35
+ *
36
+ * Checks (stable ids):
37
+ *
38
+ * - `cms-unknown-table` — `customizeTable("x")` for a slug no table declares.
39
+ * - `cms-unknown-field` — a `fields` key that is neither a column key nor a
40
+ * relation of that table.
41
+ * - `cms-hidden-required` — a field kept off the form (`hiddenInForm`,
42
+ * `readOnly`, `disabled`) whose column is `NOT NULL` with no default, that
43
+ * neither the database nor the server fills, and that the customization does
44
+ * not mark `filledByServer`: no record can be created from the panel. A
45
+ * warning instead of an error when the table declares a `beforeSave` hook
46
+ * (or the column a `beforeSave` transform), which may be what fills it.
47
+ * - `cms-duplicate-customization` — two `customizeTable` calls for one slug.
48
+ * The panel refuses to mount with both.
49
+ * - `cms-not-static` — a call this step could not read (warning).
50
+ * - `cms-ui-config-not-mounted` — `src/cms/ui-config.json` exists, where the
51
+ * collection editor saves presentation in development, but no `<RebaseCMS>`
52
+ * in the frontend passes `uiConfig`: the editor's changes are lost on
53
+ * reload and never ship (warning). Said only when a `<RebaseCMS>` element
54
+ * was found and none of them passes `uiConfig` or spreads props into it.
55
+ * - `cms-backend-guard-missing` — the project has `backend/` and a frontend
56
+ * whose Vite config does not use `rebaseBackendGuard()`: nothing refuses a
57
+ * value import of a table, which would ship its server hooks to every
58
+ * visitor (`utils/backend-guard.ts`). Quiet when the config imports a local
59
+ * module that may add it, and checked whether or not `src/cms` exists.
60
+ */
61
+ /** The package `customizeTable` is imported from. */
62
+ var CMS_PACKAGE = "@rebasepro/cms";
63
+ var CUSTOMIZE = "customizeTable";
64
+ /** The panel's mount, and the file the collection editor writes presentation to in development. */
65
+ var MOUNT = "RebaseCMS";
66
+ var UI_CONFIG_FILE = "ui-config.json";
67
+ var SOURCE = /\.(ts|tsx|mts|js|jsx|mjs)$/;
68
+ var NOT_SOURCE = /\.(d|test|spec)\.[cm]?[jt]sx?$/;
69
+ /** The form options that keep a field from being edited on the form. */
70
+ var OFF_FORM_OPTIONS = [
71
+ "hiddenInForm",
72
+ "readOnly",
73
+ "disabled"
74
+ ];
75
+ function sourceFiles(dir) {
76
+ const out = [];
77
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
78
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
79
+ const full = path.join(dir, entry.name);
80
+ if (entry.isDirectory()) out.push(...sourceFiles(full));
81
+ else if (SOURCE.test(entry.name) && !NOT_SOURCE.test(entry.name)) out.push(full);
82
+ }
83
+ return out.sort();
84
+ }
85
+ var Reader = class {
86
+ tsm;
87
+ constructor(tsm) {
88
+ this.tsm = tsm;
89
+ }
90
+ unwrap(node) {
91
+ const N = this.tsm.Node;
92
+ let current = node;
93
+ while (N.isAsExpression(current) || N.isSatisfiesExpression(current) || N.isParenthesizedExpression(current) || N.isNonNullExpression(current) || N.isTypeAssertion(current)) current = current.getExpression();
94
+ return current;
95
+ }
96
+ /** The initializer of the top-level `const` an identifier names, in its own file. */
97
+ constOf(node) {
98
+ const N = this.tsm.Node;
99
+ if (!N.isIdentifier(node)) return void 0;
100
+ const declaration = node.getSourceFile().getVariableDeclaration(node.getText());
101
+ const statement = declaration?.getVariableStatement();
102
+ if (!declaration || !statement || !N.isSourceFile(statement.getParent())) return void 0;
103
+ if (statement.getDeclarationKind() !== this.tsm.VariableDeclarationKind.Const) return void 0;
104
+ return declaration.getInitializer();
105
+ }
106
+ /** A string a node denotes: a literal, or a same-file `const` holding one. */
107
+ string(node, depth = 0) {
108
+ if (!node || depth > 4) return void 0;
109
+ const N = this.tsm.Node;
110
+ const current = this.unwrap(node);
111
+ if (N.isStringLiteral(current) || N.isNoSubstitutionTemplateLiteral(current)) return current.getLiteralValue();
112
+ const initializer = this.constOf(current);
113
+ return initializer ? this.string(initializer, depth + 1) : void 0;
114
+ }
115
+ /** The object literal a node denotes: itself, or a same-file `const` holding one. */
116
+ object(node, depth = 0) {
117
+ if (!node || depth > 4) return void 0;
118
+ const N = this.tsm.Node;
119
+ const current = this.unwrap(node);
120
+ if (N.isObjectLiteralExpression(current)) return current;
121
+ const initializer = this.constOf(current);
122
+ return initializer ? this.object(initializer, depth + 1) : void 0;
123
+ }
124
+ /** A property's name as written, or undefined for a computed one. */
125
+ name(member) {
126
+ const N = this.tsm.Node;
127
+ if (!N.isPropertyAssignment(member) && !N.isShorthandPropertyAssignment(member) && !N.isMethodDeclaration(member)) return void 0;
128
+ const nameNode = member.getNameNode();
129
+ if (N.isIdentifier(nameNode)) return nameNode.getText();
130
+ if (N.isStringLiteral(nameNode) || N.isNoSubstitutionTemplateLiteral(nameNode)) return nameNode.getLiteralValue();
131
+ if (N.isNumericLiteral(nameNode)) return String(nameNode.getLiteralValue());
132
+ if (N.isComputedPropertyName(nameNode)) return this.string(nameNode.getExpression());
133
+ }
134
+ /** The value of a member: an assignment's initializer, a shorthand's identifier. */
135
+ value(member) {
136
+ const N = this.tsm.Node;
137
+ if (N.isPropertyAssignment(member)) return member.getInitializer();
138
+ if (N.isShorthandPropertyAssignment(member)) return member.getNameNode();
139
+ }
140
+ /** `true` / `false` as written, an object literal as `true` (for `disabled: { … }`), else unknown. */
141
+ flag(node, objectIsTrue) {
142
+ if (!node) return "unknown";
143
+ const N = this.tsm.Node;
144
+ const { SyntaxKind } = this.tsm;
145
+ const current = this.unwrap(node);
146
+ if (current.getKind() === SyntaxKind.TrueKeyword) return true;
147
+ if (current.getKind() === SyntaxKind.FalseKeyword) return false;
148
+ if (objectIsTrue && N.isObjectLiteralExpression(current)) return true;
149
+ return "unknown";
150
+ }
151
+ /** The local names `customizeTable` is bound to, and namespaces of the CMS package. */
152
+ bindings(sf) {
153
+ const names = /* @__PURE__ */ new Set();
154
+ const namespaces = /* @__PURE__ */ new Set();
155
+ for (const declaration of sf.getImportDeclarations()) {
156
+ if (declaration.getModuleSpecifierValue() !== CMS_PACKAGE || declaration.isTypeOnly()) continue;
157
+ const namespace = declaration.getNamespaceImport();
158
+ if (namespace) namespaces.add(namespace.getText());
159
+ for (const named of declaration.getNamedImports()) if (named.getName() === CUSTOMIZE && !named.isTypeOnly()) names.add(named.getAliasNode()?.getText() ?? CUSTOMIZE);
160
+ }
161
+ return {
162
+ names,
163
+ namespaces
164
+ };
165
+ }
166
+ field(key, member) {
167
+ const N = this.tsm.Node;
168
+ const read = {
169
+ key,
170
+ line: member.getStartLineNumber(),
171
+ offForm: [],
172
+ filledByServer: void 0,
173
+ opaque: false
174
+ };
175
+ const options = this.object(this.value(member));
176
+ if (!options) {
177
+ read.opaque = true;
178
+ return read;
179
+ }
180
+ for (const property of options.getProperties()) {
181
+ if (N.isSpreadAssignment(property)) {
182
+ read.opaque = true;
183
+ continue;
184
+ }
185
+ const name = this.name(property);
186
+ if (name === void 0) {
187
+ read.opaque = true;
188
+ continue;
189
+ }
190
+ const value = this.value(property);
191
+ if (name === "filledByServer") read.filledByServer = this.flag(value, false);
192
+ const option = OFF_FORM_OPTIONS.find((candidate) => candidate === name);
193
+ if (option && this.flag(value, option === "disabled") === true) read.offForm.push(option);
194
+ }
195
+ return read;
196
+ }
197
+ /** Every `customizeTable(...)` call in a file, read as far as the source says. */
198
+ customizations(sf, relativeFile) {
199
+ const N = this.tsm.Node;
200
+ const { SyntaxKind } = this.tsm;
201
+ const { names, namespaces } = this.bindings(sf);
202
+ if (names.size === 0 && namespaces.size === 0) return [];
203
+ const out = [];
204
+ for (const call of sf.getDescendantsOfKind(SyntaxKind.CallExpression)) {
205
+ const callee = call.getExpression();
206
+ if (!(N.isIdentifier(callee) && names.has(callee.getText()) || N.isPropertyAccessExpression(callee) && callee.getName() === CUSTOMIZE && namespaces.has(callee.getExpression().getText()))) continue;
207
+ const [slugNode, optionsNode] = call.getArguments();
208
+ const read = {
209
+ slug: "",
210
+ file: relativeFile,
211
+ line: call.getStartLineNumber(),
212
+ fields: [],
213
+ unread: []
214
+ };
215
+ const slug = this.string(slugNode);
216
+ if (slug === void 0) {
217
+ read.unread.push(`the slug \`${slugNode?.getText() ?? ""}\` is not a string literal or a \`const\` of one in this file`);
218
+ out.push(read);
219
+ continue;
220
+ }
221
+ read.slug = slug;
222
+ const options = this.object(optionsNode);
223
+ if (!options) {
224
+ read.unread.push(`the options \`${optionsNode?.getText().split("\n")[0] ?? ""}\` are not an object literal or a \`const\` of one in this file`);
225
+ out.push(read);
226
+ continue;
227
+ }
228
+ let fieldsNode;
229
+ for (const property of options.getProperties()) {
230
+ if (N.isSpreadAssignment(property)) {
231
+ read.unread.push(`\`...${property.getExpression().getText()}\` (line ${property.getStartLineNumber()}) may carry \`fields\``);
232
+ continue;
233
+ }
234
+ if (this.name(property) === "fields") fieldsNode = this.value(property);
235
+ }
236
+ if (fieldsNode) {
237
+ const fields = this.object(fieldsNode);
238
+ if (!fields) read.unread.push(`\`fields\` (line ${fieldsNode.getStartLineNumber()}) is not an object literal or a \`const\` of one in this file`);
239
+ else for (const member of fields.getProperties()) {
240
+ const key = this.name(member);
241
+ if (key === void 0) {
242
+ read.unread.push(`\`${member.getText().split("\n")[0]}\` (line ${member.getStartLineNumber()}) in \`fields\``);
243
+ continue;
244
+ }
245
+ read.fields.push(this.field(key, member));
246
+ }
247
+ }
248
+ out.push(read);
249
+ }
250
+ return out;
251
+ }
252
+ };
253
+ /** Levenshtein distance, for "did you mean". */
254
+ function distance(a, b) {
255
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
256
+ for (let i = 1; i <= a.length; i++) {
257
+ let previous = row[0];
258
+ row[0] = i;
259
+ for (let j = 1; j <= b.length; j++) {
260
+ const current = row[j];
261
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1].toLowerCase() === b[j - 1].toLowerCase() ? 0 : 1));
262
+ previous = current;
263
+ }
264
+ }
265
+ return row[b.length];
266
+ }
267
+ function closest(name, candidates) {
268
+ let best;
269
+ let bestDistance = Math.max(2, Math.floor(name.length / 3)) + 1;
270
+ for (const candidate of candidates) {
271
+ const d = distance(name, candidate);
272
+ if (d < bestDistance) {
273
+ best = candidate;
274
+ bestDistance = d;
275
+ }
276
+ }
277
+ return best;
278
+ }
279
+ var SERIAL_KINDS = /* @__PURE__ */ new Set([
280
+ "smallserial",
281
+ "serial",
282
+ "bigserial"
283
+ ]);
284
+ /**
285
+ * Whether a create may leave the column out and still succeed without the
286
+ * server's help from a hook: it is nullable, has a default (literal, SQL,
287
+ * random uuid, identity, the database's), is a serial, is generated, is
288
+ * stamped or read-only (the server writes it), or is the tenant column (the
289
+ * server fills it from the caller).
290
+ */
291
+ function fillsItself(table, column) {
292
+ return column.nullable || column.default !== void 0 || SERIAL_KINDS.has(column.type.kind) || column.generated !== void 0 || column.stamp !== void 0 || column.readOnly === true || table.tenant?.field === column.key;
293
+ }
294
+ /** The column a field key edits: the column itself, or the foreign key of a `belongsTo` relation. */
295
+ function columnOfField(table, key) {
296
+ return table.columns.find((column) => column.key === key) ?? table.columns.find((column) => column.foreignKeyOf === key);
297
+ }
298
+ function describeOffForm(options) {
299
+ return options.map((option) => `\`${option}\``).join(" and ");
300
+ }
301
+ function checkCustomization(read, table) {
302
+ const findings = [];
303
+ const where = `customizeTable("${read.slug}")`;
304
+ const columnKeys = new Set(table.columns.map((column) => column.key));
305
+ const relationNames = new Set(table.relations.map((relation) => relation.name));
306
+ for (const field of read.fields) {
307
+ const at = {
308
+ table: table.slug,
309
+ file: read.file,
310
+ line: field.line,
311
+ path: `${where}.fields.${field.key}`
312
+ };
313
+ if (!columnKeys.has(field.key) && !relationNames.has(field.key)) {
314
+ const bySqlName = table.columns.find((column) => column.column === field.key);
315
+ const guess = bySqlName?.key ?? closest(field.key, [...columnKeys, ...relationNames]);
316
+ findings.push({
317
+ check: "cms-unknown-field",
318
+ severity: "error",
319
+ ...at,
320
+ message: `${where} customizes \`fields.${field.key}\`, which is neither a column nor a relation of the "${table.slug}" table` + (bySqlName ? ` — that is the SQL name of the column whose key is \`${bySqlName.key}\`.` : "."),
321
+ fix: guess ? `Rename the key to \`${guess}\`${bySqlName ? " (fields are keyed by the column's key, as in `columns`)" : ""}, or remove it.` : "Remove it, or key it by one of the table's columns or relations (`columns` / `relations` in its `defineTable`)."
322
+ });
323
+ continue;
324
+ }
325
+ if (field.offForm.length === 0 || field.filledByServer === true) continue;
326
+ if (field.opaque || field.filledByServer === "unknown") continue;
327
+ const column = columnOfField(table, field.key);
328
+ if (!column || fillsItself(table, column)) continue;
329
+ const hooked = table.hooks?.beforeSave === true || column.transforms?.beforeSave === true;
330
+ const what = column.key === field.key ? `the column \`${column.column}\`` : `its foreign key \`${column.column}\``;
331
+ findings.push({
332
+ check: "cms-hidden-required",
333
+ severity: hooked ? "warning" : "error",
334
+ ...at,
335
+ message: `${where} keeps \`${field.key}\` off the form (${describeOffForm(field.offForm)}), but ${what} is NOT NULL with no default ` + (hooked ? `and only the table's \`beforeSave\` hook could fill it: unless it does, creating a record from the panel fails.` : `and nothing on the server fills it: creating a "${table.slug}" record from the panel always fails.`),
336
+ fix: hooked ? `If the hook fills it on create, say so: \`${field.key}: { …, filledByServer: true }\`. Otherwise let the form edit it.` : `Let the form edit it (drop ${describeOffForm(field.offForm)}), give the column a default in its \`defineTable\` (\`.default(…)\`), or fill it in a \`beforeSave\` hook and mark the field \`filledByServer: true\`.`
337
+ });
338
+ }
339
+ return findings;
340
+ }
341
+ /**
342
+ * Read every `customizeTable(...)` call under the project's customization
343
+ * directories and hold it to `tables`. Never throws on a file it cannot parse
344
+ * as intended: what it cannot read is a `cms-not-static` warning.
345
+ */
346
+ async function checkCmsCustomizations(projectRoot, tables) {
347
+ const directories = cmsDirectories(projectRoot);
348
+ const result = {
349
+ directories: directories.map((dir) => path.relative(projectRoot, dir)),
350
+ customizations: 0,
351
+ findings: []
352
+ };
353
+ result.findings.push(...await backendGuardFindings(projectRoot));
354
+ if (directories.length === 0) return result;
355
+ const tsm = await import("ts-morph");
356
+ const project = new tsm.Project({
357
+ useInMemoryFileSystem: true,
358
+ skipAddingFilesFromTsConfig: true,
359
+ compilerOptions: {
360
+ allowJs: true,
361
+ jsx: tsm.ts.JsxEmit.Preserve,
362
+ noLib: true
363
+ }
364
+ });
365
+ const reader = new Reader(tsm);
366
+ const bySlug = new Map(tables.map((table) => [table.slug, table]));
367
+ const first = /* @__PURE__ */ new Map();
368
+ for (const dir of directories) {
369
+ for (const file of sourceFiles(dir)) {
370
+ const text = fs.readFileSync(file, "utf-8");
371
+ if (!text.includes(CUSTOMIZE)) continue;
372
+ const relativeFile = path.relative(projectRoot, file);
373
+ const sf = project.createSourceFile(file, text, { overwrite: true });
374
+ for (const read of reader.customizations(sf, relativeFile)) {
375
+ result.customizations++;
376
+ const label = read.slug ? `customizeTable("${read.slug}")` : "customizeTable(…)";
377
+ if (read.unread.length > 0) result.findings.push({
378
+ check: "cms-not-static",
379
+ severity: "warning",
380
+ file: read.file,
381
+ line: read.line,
382
+ ...read.slug && {
383
+ table: read.slug,
384
+ path: label
385
+ },
386
+ message: `${label} was not fully checked: ${read.unread.join("; ")}. \`rebase verify\` reads customizations without running them, so only literals in the call are checked.`,
387
+ fix: "Write the slug and the `fields` object as literals in the call (a `const` in the same file also works), or ignore this warning."
388
+ });
389
+ if (!read.slug) continue;
390
+ const earlier = first.get(read.slug);
391
+ if (earlier) {
392
+ result.findings.push({
393
+ check: "cms-duplicate-customization",
394
+ severity: "error",
395
+ table: read.slug,
396
+ file: read.file,
397
+ line: read.line,
398
+ path: label,
399
+ message: `${label} is written twice: here and in ${earlier.file}:${earlier.line}. The panel refuses to start with both.`,
400
+ fix: "Merge them into one `customizeTable` call and remove the other."
401
+ });
402
+ continue;
403
+ }
404
+ first.set(read.slug, read);
405
+ const table = bySlug.get(read.slug);
406
+ if (!table) {
407
+ const guess = closest(read.slug, bySlug.keys());
408
+ result.findings.push({
409
+ check: "cms-unknown-table",
410
+ severity: "error",
411
+ table: read.slug,
412
+ file: read.file,
413
+ line: read.line,
414
+ path: label,
415
+ message: `${label} customizes "${read.slug}", which no table in the schema declares as its slug. The panel ignores it.`,
416
+ fix: guess ? `Did you mean "${guess}"? The first argument is the table's slug (its \`defineTable\` name, unless it sets \`slug\`).` : "Pass the slug of a table the schema index exports (its `defineTable` name, unless it sets `slug`), or remove the customization."
417
+ });
418
+ continue;
419
+ }
420
+ result.findings.push(...checkCustomization(read, table));
421
+ }
422
+ project.removeSourceFile(sf);
423
+ }
424
+ const unmounted = uiConfigNotMounted(tsm, project, projectRoot, dir);
425
+ if (unmounted) result.findings.push(unmounted);
426
+ }
427
+ return result;
428
+ }
429
+ /**
430
+ * The `cms-ui-config-not-mounted` finding for one customization directory, or
431
+ * nothing. Undecided — no `<RebaseCMS>` element found under `src/` (mounted
432
+ * through a wrapper, rendered without JSX) — is nothing, not a warning.
433
+ */
434
+ function uiConfigNotMounted(tsm, project, projectRoot, cmsDir) {
435
+ const uiConfig = path.join(cmsDir, UI_CONFIG_FILE);
436
+ if (!fs.existsSync(uiConfig)) return void 0;
437
+ const N = tsm.Node;
438
+ const { SyntaxKind } = tsm;
439
+ const mounts = [];
440
+ for (const file of sourceFiles(path.dirname(cmsDir))) {
441
+ const text = fs.readFileSync(file, "utf-8");
442
+ if (!text.includes(MOUNT)) continue;
443
+ const sf = project.createSourceFile(file, text, { overwrite: true });
444
+ const names = /* @__PURE__ */ new Set();
445
+ for (const declaration of sf.getImportDeclarations()) {
446
+ if (declaration.getModuleSpecifierValue() !== CMS_PACKAGE) continue;
447
+ for (const named of declaration.getNamedImports()) if (named.getName() === MOUNT) names.add(named.getAliasNode()?.getText() ?? MOUNT);
448
+ }
449
+ const elements = [...sf.getDescendantsOfKind(SyntaxKind.JsxOpeningElement), ...sf.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement)];
450
+ for (const element of elements) {
451
+ if (!names.has(element.getTagNameNode().getText())) continue;
452
+ const passes = element.getAttributes().some((attribute) => N.isJsxSpreadAttribute(attribute) || attribute.getNameNode().getText() === "uiConfig");
453
+ mounts.push({
454
+ file: path.relative(projectRoot, file),
455
+ line: element.getStartLineNumber(),
456
+ passes
457
+ });
458
+ }
459
+ project.removeSourceFile(sf);
460
+ }
461
+ if (mounts.length === 0 || mounts.some((mount) => mount.passes)) return void 0;
462
+ const [first] = mounts;
463
+ return {
464
+ check: "cms-ui-config-not-mounted",
465
+ severity: "warning",
466
+ file: first.file,
467
+ line: first.line,
468
+ message: `${path.relative(projectRoot, uiConfig)} holds what the collection editor saves in development, but \`<RebaseCMS>\` is not given it: presentation edited in the editor is gone after a reload and never ships.`,
469
+ fix: `Import it and pass it: \`import uiConfig from "./cms/${UI_CONFIG_FILE}";\` and \`<RebaseCMS … uiConfig={uiConfig} />\` (the frontend's tsconfig needs \`resolveJsonModule\`).`
470
+ };
471
+ }
472
+ /**
473
+ * `cms-backend-guard-missing`, one per frontend whose Vite config does not use
474
+ * the guard. Nothing for a frontend the static read cannot decide.
475
+ */
476
+ async function backendGuardFindings(projectRoot) {
477
+ return (await backendGuardStates(projectRoot)).filter((state) => state.state === "missing").map((state) => ({
478
+ check: "cms-backend-guard-missing",
479
+ severity: "error",
480
+ file: state.viteConfig,
481
+ line: state.line,
482
+ message: backendGuardMissingMessage(state),
483
+ fix: BACKEND_GUARD_FIX
484
+ }));
485
+ }
486
+ //#endregion
487
+ //#region src/commands/verify.ts
488
+ /**
489
+ * CLI command: rebase verify
490
+ *
491
+ * One command that says whether the tables are safe to ship, fast enough to
492
+ * run after every edit. An agent editing `backend/schema/*.ts` gets a table
493
+ * definition wrong — a relation to a table the index does not export, an
494
+ * `rls: "inherit"` with no `defaultRls`, a table with no primary key — or
495
+ * writes rules that hand every row of a per-user table to everyone; each of
496
+ * those used to surface late: at boot, in review, or never. The project's
497
+ * Claude Code hook (written by `rebase init` and `rebase skills --hooks`) runs
498
+ * this after each edit to a schema file, and CI runs it on every push.
499
+ *
500
+ * Five steps, each reported on its own:
501
+ *
502
+ * 1. **Table definitions** — `backend/schema` loads and compiles through
503
+ * `loadBackendSchema`, the loader the backend boots from, so every problem
504
+ * it would refuse to boot on is a finding here, one per problem.
505
+ * 2. **RLS coverage** — a table with a `user_id` / `owner_id` /
506
+ * `organization_id` / `tenant_id` column whose rules (its own, or the
507
+ * `defaultRls` it inherits) let a role read every row regardless of it.
508
+ * `rls` itself is mandatory, so "no rules at all" is a step-1 error now.
509
+ * 3. **CMS customizations** — every `customizeTable(...)` under
510
+ * `frontend/src/cms`, read statically (`verify-cms.ts`): a slug no table
511
+ * declares, a field that is not a column or relation of its table, a
512
+ * required column kept off the form, one table customized twice. A
513
+ * project without `frontend/src/cms` (headless) skips it.
514
+ * 4. **Migration freshness** — whether `drizzle/migrations` still builds the
515
+ * tables and columns the schema declares (offline), and with `--live`
516
+ * whether the database has applied every migration.
517
+ * 5. **Live RLS audit** — with `--live`, the `@rebasepro/rls-check` catalogue
518
+ * against the project's database, resolved as `db *` resolves it (the
519
+ * managed one unless something names another).
520
+ *
521
+ * `--json` prints one object an agent can act on: every finding carries the
522
+ * file, the dotted path into the table and the fix.
523
+ */
524
+ /** The flags `rebase verify` takes. */
525
+ var VERIFY_FLAGS = {
526
+ "--schema-dir": String,
527
+ "--json": Boolean,
528
+ "--quiet": Boolean,
529
+ "-q": "--quiet",
530
+ "--live": Boolean,
531
+ "--database-url": String,
532
+ "--docker": Boolean
533
+ };
534
+ var VERIFY_FLAG_HELP = {
535
+ "--schema-dir": SCHEMA_DIR_FLAG_HELP,
536
+ "--json": "Print one JSON object: every step, and every finding with its file, path and fix",
537
+ "--quiet, -q": "Print nothing when everything passes; only the problems when something fails",
538
+ "--live": "Also connect to the project's database: check migrations are applied and run the rls-check audit",
539
+ "--database-url": "With --live: audit this database instead of the project's",
540
+ "--docker": "With --live: use the database from docker compose, starting it if needed"
541
+ };
542
+ var STEP_TITLES = {
543
+ schema: "Table definitions",
544
+ rls: "RLS coverage",
545
+ cms: "CMS customizations",
546
+ migrations: "Migration freshness",
547
+ live: "Live RLS audit"
548
+ };
549
+ /**
550
+ * Columns that say "this row belongs to someone". A table carrying one and
551
+ * served without a row filter is the classic multi-tenant leak.
552
+ */
553
+ var OWNER_COLUMNS = [
554
+ "user_id",
555
+ "owner_id",
556
+ "organization_id",
557
+ "tenant_id"
558
+ ];
559
+ var MODULE_EXTENSIONS = [
560
+ ".ts",
561
+ ".mts",
562
+ ".js",
563
+ ".mjs"
564
+ ];
565
+ /**
566
+ * Where a table is written, as far as the files say without running them:
567
+ * the conventional `<schema>/<name>.ts` (or its slug, or its SQL name), else
568
+ * the index that exports it.
569
+ */
570
+ function tableFile(projectRoot, schemaDir, indexFile, names) {
571
+ for (const name of names) for (const extension of MODULE_EXTENSIONS) {
572
+ const candidate = path.join(schemaDir, `${name}${extension}`);
573
+ if (fs.existsSync(candidate)) return path.relative(projectRoot, candidate);
574
+ }
575
+ return indexFile ? path.relative(projectRoot, indexFile) : void 0;
576
+ }
577
+ /**
578
+ * Load the schema the way the backend boots from it. A schema that does not
579
+ * load or does not compile is a set of findings, not a crash — after an
580
+ * agent's edit it is the most likely problem of all.
581
+ */
582
+ async function loadSchema(options) {
583
+ const relative = (file) => path.relative(options.projectRoot, file);
584
+ const indexOf = () => MODULE_EXTENSIONS.map((extension) => path.join(options.schemaDir, `index${extension}`)).find((candidate) => fs.existsSync(candidate)) ?? "";
585
+ try {
586
+ const schema = await loadProjectSchema(options.projectRoot, options.schemaDir, options.moduleAliases);
587
+ const descriptors = schema.compiled.descriptors;
588
+ const files = /* @__PURE__ */ new Map();
589
+ for (const descriptor of descriptors) {
590
+ const file = tableFile(options.projectRoot, options.schemaDir, schema.loaded.indexFile, [
591
+ descriptor.name,
592
+ descriptor.slug,
593
+ descriptor.table
594
+ ]);
595
+ if (file) files.set(descriptor.slug, file);
596
+ }
597
+ return {
598
+ verified: {
599
+ schema,
600
+ descriptors,
601
+ files
602
+ },
603
+ failures: []
604
+ };
605
+ } catch (error) {
606
+ if (isSchemaDefinitionError(error)) {
607
+ const index = indexOf();
608
+ return {
609
+ verified: null,
610
+ failures: error.problems.map((problem) => {
611
+ const file = tableFile(options.projectRoot, options.schemaDir, index, [problem.table]);
612
+ return {
613
+ step: "schema",
614
+ check: "schema-definition",
615
+ severity: "error",
616
+ table: problem.table,
617
+ ...file && { file },
618
+ path: problem.key ? `${problem.table}.${problem.key}` : problem.table,
619
+ message: problem.message,
620
+ fix: "Change the definition as the message says. The backend refuses to boot on the same schema."
621
+ };
622
+ })
623
+ };
624
+ }
625
+ const file = typeof error === "object" && error !== null && "file" in error && typeof error.file === "string" ? relative(error.file) : void 0;
626
+ return {
627
+ verified: null,
628
+ failures: [{
629
+ step: "schema",
630
+ check: "schema-load",
631
+ severity: "error",
632
+ ...file && { file },
633
+ message: error instanceof Error ? error.message : String(error),
634
+ fix: "Fix the module as the message says. The backend refuses to boot on the same files."
635
+ }]
636
+ };
637
+ }
638
+ }
639
+ /** Whether a rule applies to reads. */
640
+ function coversSelect(rule) {
641
+ const operations = rule.operations ?? [rule.operation ?? "all"];
642
+ return operations.includes("select") || operations.includes("all");
643
+ }
644
+ /**
645
+ * A permissive read rule with no row filter: every row, to everyone the rule
646
+ * names. `access: "public"` is the same thing said on purpose, so it is not
647
+ * this; `roles: ["admin"]` restates the default admin read and adds nothing.
648
+ */
649
+ function isUnfilteredRead(rule) {
650
+ if (!coversSelect(rule) || rule.mode === "restrictive") return false;
651
+ if (rule.access === "public" || rule.ownerField || rule.condition) return false;
652
+ if (rule.using !== void 0 && !/^\s*\(?\s*true\s*\)?\s*$/i.test(rule.using)) return false;
653
+ if (rule.using === void 0 && rule.withCheck !== void 0) return false;
654
+ const roles = rule.roles ?? [];
655
+ return !(roles.length > 0 && roles.every((role) => role === "admin"));
656
+ }
657
+ /** A read rule that returns every row to someone: an unfiltered one, or `access: "public"`. */
658
+ function opensEveryRow(rule) {
659
+ return isUnfilteredRead(rule) || rule.access === "public" && coversSelect(rule) && rule.mode !== "restrictive";
660
+ }
661
+ function describeRuleTarget(rule) {
662
+ return rule.roles?.length ? `role${rule.roles.length > 1 ? "s" : ""} ${rule.roles.map((r) => `"${r}"`).join(", ")}` : "every signed-in user";
663
+ }
664
+ function checkRls(verified) {
665
+ const findings = [];
666
+ const defaultsFile = verified.schema.loaded.indexFile ? path.basename(verified.schema.loaded.indexFile) : "the schema index";
667
+ for (const table of verified.descriptors) {
668
+ if (table.kind !== "table" || table.auth) continue;
669
+ if (table.rls.posture !== "rules") continue;
670
+ if (table.tenant) continue;
671
+ const owner = table.columns.find((column) => OWNER_COLUMNS.includes(column.column));
672
+ if (!owner) continue;
673
+ const slug = table.slug;
674
+ const file = verified.files.get(slug);
675
+ const ownerField = owner.column;
676
+ const perUser = ownerField === "user_id" || ownerField === "owner_id";
677
+ const fix = perUser ? `Give it rules of its own: \`rls: [{ operation: "all", ownerField: "${ownerField}" }]\` so each user reaches only their own rows. A table meant to be readable by everyone says so on the table: \`{ operation: "select", access: "public" }\`.` : `Scope it with \`tenant: { field: "${owner.key}", from: { claim: "${ownerField}" } }\` (the claim that carries the caller's tenant), plus the \`rls\` rules that grant access inside a tenant — e.g. \`[{ operation: "select", access: "public" }]\`.`;
678
+ if (table.rls.inherited) {
679
+ const opening = table.rls.rules.find(opensEveryRow);
680
+ if (!opening) continue;
681
+ findings.push({
682
+ step: "rls",
683
+ check: perUser ? "rls-inherited-read" : "rls-inherited-tenant-read",
684
+ severity: perUser ? "warning" : "error",
685
+ table: slug,
686
+ ...file && { file },
687
+ path: `${slug}.rls`,
688
+ message: `"${slug}" has a \`${ownerField}\` column and \`rls: "inherit"\`, so it takes \`defaultRls\` from ${defaultsFile}, which lets ${describeRuleTarget(opening)} read every row regardless of \`${ownerField}\`.`,
689
+ fix
690
+ });
691
+ continue;
692
+ }
693
+ table.rls.rules.forEach((rule, index) => {
694
+ if (!isUnfilteredRead(rule)) return;
695
+ findings.push({
696
+ step: "rls",
697
+ check: "rls-unfiltered-read",
698
+ severity: "warning",
699
+ table: slug,
700
+ ...file && { file },
701
+ path: `${slug}.rls[${index}]`,
702
+ message: `"${slug}" has a \`${ownerField}\` column, and rls[${index}] lets ${describeRuleTarget(rule)} read every row of it with no row filter.`,
703
+ fix: `Filter the rule — \`ownerField: "${ownerField}"\` or a \`condition\` — or, if every row really is meant for ${describeRuleTarget(rule)}, keep it and ignore this warning.`
704
+ });
705
+ });
706
+ }
707
+ return findings;
708
+ }
709
+ var POSTGRES_PLUGIN = "@rebasepro/server-postgres";
710
+ /** Atlas's baseline bit in `atlas_schema_revisions.type`. */
711
+ var REVISION_TYPE_BASELINE = 1;
712
+ /**
713
+ * The migration files the database has not run, as Atlas's own `migrate status`
714
+ * counts them.
715
+ *
716
+ * A file is applied when its version has a row, or when it is at or behind the
717
+ * newest *baseline* row: `migrate apply --baseline V` records V alone, and
718
+ * means "everything up to V is already here". `rebase db migrate --baseline` is
719
+ * what the CLI prescribes for a booted database, so set membership alone
720
+ * reported the earlier migrations of every baselined database as not applied —
721
+ * and prescribed `rebase db migrate`, which answers "No migration files to
722
+ * execute". That run failed forever.
723
+ */
724
+ function pendingMigrations(files, revisions, compare, versionOf) {
725
+ const recorded = new Set(revisions.map((row) => row.version));
726
+ const baseline = revisions.filter((row) => (Number(row.type) & REVISION_TYPE_BASELINE) !== 0).map((row) => row.version).reduce((newest, version) => newest === null || compare(version, newest) > 0 ? version : newest, null);
727
+ return files.filter((file) => {
728
+ const version = versionOf(file);
729
+ if (recorded.has(version)) return false;
730
+ return baseline === null || compare(version, baseline) > 0;
731
+ });
732
+ }
733
+ async function checkMigrations(options, verified, step) {
734
+ const skip = (detail) => {
735
+ step.status = "skipped";
736
+ step.detail = detail;
737
+ return [];
738
+ };
739
+ if (!options.backendDir) return skip("no backend/ directory");
740
+ const plugin = getActiveBackendPlugin(options.backendDir);
741
+ if (plugin !== POSTGRES_PLUGIN) return skip(`migrations are checked for ${POSTGRES_PLUGIN} projects${plugin ? `; this one uses ${plugin}` : ""}`);
742
+ const migrationsDir = path.join(options.backendDir, "drizzle", "migrations");
743
+ const files = fs.existsSync(migrationsDir) ? fs.readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort() : [];
744
+ if (files.length === 0) return skip("no migrations yet — the schema is applied with `rebase db push`; `rebase db generate` starts versioned migrations");
745
+ const relativeDir = path.relative(options.projectRoot, migrationsDir);
746
+ const { findUnmigratedSchema } = await import("@rebasepro/server-postgres");
747
+ const findings = [];
748
+ const fix = "Run `rebase db generate` to write the migration, then `rebase db migrate` to apply it.";
749
+ let changes;
750
+ try {
751
+ changes = findUnmigratedSchema(verified.schema.compiled.tables, files.map((f) => fs.readFileSync(path.join(migrationsDir, f), "utf-8")));
752
+ } catch (error) {
753
+ return [{
754
+ step: "migrations",
755
+ check: "migration-plan",
756
+ severity: "error",
757
+ message: `Could not derive the SQL schema from the tables: ${error instanceof Error ? error.message : String(error)}`,
758
+ fix: "`rebase schema generate` reports the same problem with more context."
759
+ }];
760
+ }
761
+ for (const change of changes) {
762
+ const where = change.column ? `${change.table}.${change.column}` : change.table;
763
+ const message = change.kind === "missing-table" ? `Table ${where} is declared in the schema but no migration in ${relativeDir} creates it.` : change.kind === "missing-column" ? `Column ${where} is declared in the schema but no migration in ${relativeDir} adds it.` : `Column ${where} is no longer declared in the schema, but the migrations in ${relativeDir} still create it.`;
764
+ const file = change.slug ? verified.files.get(change.slug) : void 0;
765
+ findings.push({
766
+ step: "migrations",
767
+ check: change.kind === "removed-column" ? "migration-stale-column" : "migration-missing",
768
+ severity: "error",
769
+ message,
770
+ fix,
771
+ ...change.slug && { table: change.slug },
772
+ ...file && { file }
773
+ });
774
+ }
775
+ step.detail = `${files.length} migration${files.length === 1 ? "" : "s"} in ${relativeDir}`;
776
+ if (options.live && options.databaseUrl) findings.push(...await checkAppliedMigrations(options.databaseUrl, files));
777
+ return findings;
778
+ }
779
+ /** Which migration files the database has not run, from Atlas's revision table. */
780
+ async function checkAppliedMigrations(databaseUrl, files) {
781
+ const client = new (await (import("pg"))).default.Client({
782
+ connectionString: databaseUrl,
783
+ connectionTimeoutMillis: 5e3
784
+ });
785
+ try {
786
+ await client.connect();
787
+ if (!(await client.query("SELECT to_regclass('rebase.atlas_schema_revisions') IS NOT NULL AS present")).rows[0]?.present) return [{
788
+ step: "migrations",
789
+ check: "migration-unapplied",
790
+ severity: "warning",
791
+ message: "The database has no migration history (rebase.atlas_schema_revisions) — it was provisioned with `rebase db push`, or never migrated.",
792
+ fix: "`rebase db migrate --baseline <version>` adopts an existing database; `rebase db migrate` applies the migrations to a new one."
793
+ }];
794
+ const applied = await client.query("SELECT version, type FROM rebase.atlas_schema_revisions WHERE error IS NULL OR error = ''");
795
+ const { compareMigrationVersions, migrationVersionOf } = await import("@rebasepro/server-postgres");
796
+ const pending = pendingMigrations(files, applied.rows.map((row) => ({
797
+ version: row.version,
798
+ type: Number(row.type)
799
+ })), compareMigrationVersions, migrationVersionOf);
800
+ if (pending.length === 0) return [];
801
+ return [{
802
+ step: "migrations",
803
+ check: "migration-unapplied",
804
+ severity: "error",
805
+ message: `${pending.length} migration${pending.length === 1 ? " has" : "s have"} not been applied to the database: ${pending.join(", ")}.`,
806
+ fix: "Run `rebase db migrate`."
807
+ }];
808
+ } catch (error) {
809
+ return [{
810
+ step: "migrations",
811
+ check: "migration-unapplied",
812
+ severity: "warning",
813
+ message: `Could not read the database's migration history: ${error instanceof Error ? error.message : String(error)}`
814
+ }];
815
+ } finally {
816
+ await client.end().catch(() => void 0);
817
+ }
818
+ }
819
+ /** rls-check's severities, folded onto this command's two. `info` is not reported. */
820
+ function liveSeverity(severity) {
821
+ if (severity === "critical" || severity === "high") return "error";
822
+ if (severity === "medium" || severity === "low") return "warning";
823
+ return null;
824
+ }
825
+ /**
826
+ * Why the database `--live` was pointed at cannot be opened, or `null` when it
827
+ * can. Asked once, before the live steps, so an unreachable database is one
828
+ * error rather than a skipped audit and a migration warning: under `--live`
829
+ * the audit was asked for, and a CI run in which it never ran is not green.
830
+ */
831
+ async function databaseUnreachable(databaseUrl) {
832
+ const client = new (await (import("pg"))).default.Client({
833
+ connectionString: databaseUrl,
834
+ connectionTimeoutMillis: 5e3
835
+ });
836
+ try {
837
+ await client.connect();
838
+ return null;
839
+ } catch (error) {
840
+ return error instanceof Error ? error.message : String(error);
841
+ } finally {
842
+ await client.end().catch(() => void 0);
843
+ }
844
+ }
845
+ /**
846
+ * A `USING (true)` read policy Rebase compiled from an `access: "public"`
847
+ * select rule, on a backend that refuses a request with no token.
848
+ *
849
+ * rls-check reads the policy alone, and for the role every signed-in request
850
+ * runs as it is "every row to everyone": critical. But the API answers 401
851
+ * before RLS is consulted unless `AUTH_REQUIRE=false`, so what it grants is
852
+ * every row to every *signed-in* user — exactly what step 2 accepts as a rule
853
+ * said on purpose, and what boot reports as an info line. A fresh blog
854
+ * scaffold failed its own `verify --live` with three such errors. It is a
855
+ * warning here, as an unfiltered read is in step 2; with `AUTH_REQUIRE=false`
856
+ * the rows really are public and it stays an error.
857
+ */
858
+ function isTokenGatedPublicRead(finding, authRequired, isGeneratedPolicyName) {
859
+ if (!authRequired || finding.id !== "policy-always-true") return false;
860
+ const { table, policy } = finding.target;
861
+ if (!table || !policy) return false;
862
+ return isGeneratedPolicyName(policy, table) && policy.startsWith(`${table}_select_`);
863
+ }
864
+ async function checkLive(databaseUrl, step, authRequired) {
865
+ const { scan, CHECKS } = await import("@rebasepro/rls-check");
866
+ const { isGeneratedPolicyName } = await import("@rebasepro/server-postgres");
867
+ let result;
868
+ try {
869
+ result = await scan({
870
+ connectionString: databaseUrl,
871
+ statementTimeoutMs: 1e4
872
+ });
873
+ } catch (error) {
874
+ step.detail = "the audit did not run";
875
+ return [{
876
+ step: "live",
877
+ check: "live-scan-failed",
878
+ severity: "error",
879
+ message: `The live RLS audit failed: ${error instanceof Error ? error.message : String(error)}`,
880
+ fix: "`npx @rebasepro/rls-check <database-url>` runs the same audit on its own and reports the failure in full."
881
+ }];
882
+ }
883
+ step.detail = `${CHECKS.length} rls-check checks against ${result.database.host}/${result.database.name}`;
884
+ const findings = [];
885
+ for (const finding of result.findings) {
886
+ const severity = liveSeverity(finding.severity);
887
+ if (!severity) continue;
888
+ const tokenGated = severity === "error" && isTokenGatedPublicRead(finding, authRequired, isGeneratedPolicyName);
889
+ findings.push({
890
+ step: "live",
891
+ check: finding.id,
892
+ severity: tokenGated ? "warning" : severity,
893
+ message: tokenGated ? `${finding.title} — compiled from an \`access: "public"\` read rule: every signed-in user reads every row. A request with no token is refused by the API (AUTH_REQUIRE is on), so it is not an anonymous read.` : finding.title,
894
+ ...finding.fix && { fix: finding.fix },
895
+ path: finding.target.table ? `${finding.target.schema}.${finding.target.table}` : finding.target.schema
896
+ });
897
+ }
898
+ for (const degraded of result.diagnostics.degraded) findings.push({
899
+ step: "live",
900
+ check: "rls-check-degraded",
901
+ severity: "warning",
902
+ message: `The audit could not read ${degraded.what}: ${degraded.error}. A clean result does not cover it.`
903
+ });
904
+ return findings;
905
+ }
906
+ function settle(step, findings) {
907
+ if (step.status === "skipped") return step;
908
+ const mine = findings.filter((f) => f.step === step.id);
909
+ step.status = mine.some((f) => f.severity === "error") ? "failed" : mine.length > 0 ? "warnings" : "passed";
910
+ return step;
911
+ }
912
+ /**
913
+ * Run every step and return the report. Prints nothing and never exits, so a
914
+ * caller — the command, a test — decides what to do with it.
915
+ */
916
+ async function runVerify(options) {
917
+ const findings = [];
918
+ const steps = [
919
+ "schema",
920
+ "rls",
921
+ "cms",
922
+ "migrations",
923
+ "live"
924
+ ].map((id) => ({
925
+ id,
926
+ title: STEP_TITLES[id],
927
+ status: "passed"
928
+ }));
929
+ const [schemaStep, rlsStep, cmsStep, migrationsStep, liveStep] = steps;
930
+ const schemaDir = path.relative(options.projectRoot, options.schemaDir) || ".";
931
+ const skipAll = (detail) => {
932
+ for (const step of steps) {
933
+ step.status = "skipped";
934
+ step.detail = detail;
935
+ }
936
+ return {
937
+ ok: true,
938
+ schemaDir,
939
+ steps,
940
+ findings,
941
+ summary: {
942
+ errors: 0,
943
+ warnings: 0
944
+ }
945
+ };
946
+ };
947
+ if (!fs.existsSync(options.schemaDir) || !fs.statSync(options.schemaDir).isDirectory()) return skipAll(`no schema directory at ${schemaDir}`);
948
+ const { verified, failures } = await loadSchema(options);
949
+ findings.push(...failures);
950
+ if (verified && !verified.schema.loaded.indexFile) return skipAll(`${schemaDir} has no index.ts, so it declares no tables`);
951
+ if (verified) {
952
+ const tables = verified.descriptors.length;
953
+ schemaStep.detail = `${tables} table${tables === 1 ? "" : "s"}, compiled as the backend boots them`;
954
+ rlsStep.detail = `${tables} table${tables === 1 ? "" : "s"}`;
955
+ findings.push(...checkRls(verified));
956
+ const cms = await checkCmsCustomizations(options.projectRoot, verified.descriptors);
957
+ if (cms.directories.length === 0) {
958
+ cmsStep.status = "skipped";
959
+ cmsStep.detail = "no frontend/src/cms";
960
+ for (const finding of cms.findings) findings.push({
961
+ step: "cms",
962
+ ...finding
963
+ });
964
+ } else {
965
+ cmsStep.detail = `${cms.customizations} customization${cms.customizations === 1 ? "" : "s"} in ${cms.directories.join(", ")}, read without running them`;
966
+ for (const finding of cms.findings) findings.push({
967
+ step: "cms",
968
+ ...finding
969
+ });
970
+ }
971
+ } else for (const step of [rlsStep, cmsStep]) {
972
+ step.status = "skipped";
973
+ step.detail = "fix the table definitions first";
974
+ }
975
+ let liveUrl;
976
+ if (options.live) if (!options.databaseUrl) {
977
+ liveStep.detail = "no database to audit";
978
+ findings.push({
979
+ step: "live",
980
+ check: "live-no-database",
981
+ severity: "error",
982
+ message: options.databaseUnavailable ? `--live was asked for, and the database could not be prepared: ${options.databaseUnavailable}` : "--live was asked for, and no database is configured to audit.",
983
+ fix: "Pass --database-url <url> (or set DATABASE_URL), or run without --live for the offline checks."
984
+ });
985
+ } else {
986
+ const unreachable = await databaseUnreachable(options.databaseUrl);
987
+ if (unreachable) {
988
+ liveStep.detail = "the database did not answer";
989
+ findings.push({
990
+ step: "live",
991
+ check: "live-unreachable",
992
+ severity: "error",
993
+ message: `--live was asked for, and the database could not be reached: ${unreachable}. Neither the migration check nor the RLS audit ran.`,
994
+ fix: "Check the database is running and the URL is right (`rebase db url` prints the one this project resolves), or run without --live for the offline checks."
995
+ });
996
+ } else liveUrl = options.databaseUrl;
997
+ }
998
+ if (!verified) {
999
+ migrationsStep.status = "skipped";
1000
+ migrationsStep.detail = "fix the table definitions first";
1001
+ } else findings.push(...await checkMigrations({
1002
+ ...options,
1003
+ databaseUrl: liveUrl
1004
+ }, verified, migrationsStep));
1005
+ if (!options.live) {
1006
+ liveStep.status = "skipped";
1007
+ liveStep.detail = "pass --live to audit the database";
1008
+ } else if (liveUrl) findings.push(...await checkLive(liveUrl, liveStep, options.authRequired ?? true));
1009
+ steps.forEach((step) => settle(step, findings));
1010
+ const errors = findings.filter((f) => f.severity === "error").length;
1011
+ return {
1012
+ ok: errors === 0,
1013
+ schemaDir,
1014
+ steps,
1015
+ findings,
1016
+ summary: {
1017
+ errors,
1018
+ warnings: findings.length - errors
1019
+ }
1020
+ };
1021
+ }
1022
+ function printFinding(finding) {
1023
+ const mark = finding.severity === "error" ? chalk.red("✗") : chalk.yellow("!");
1024
+ const where = [finding.file && finding.line !== void 0 ? `${finding.file}:${finding.line}` : finding.file, finding.path].filter(Boolean).join(" → ");
1025
+ console.log(` ${mark} ${where ? `${chalk.bold(where)} ` : ""}${finding.message}`);
1026
+ if (finding.fix) console.log(chalk.gray(` fix: ${finding.fix}`));
1027
+ }
1028
+ function summaryLine(report) {
1029
+ const { errors, warnings } = report.summary;
1030
+ return `${errors} error${errors === 1 ? "" : "s"}, ${warnings} warning${warnings === 1 ? "" : "s"}`;
1031
+ }
1032
+ function printReport(report, quiet) {
1033
+ if (quiet) {
1034
+ if (report.findings.length === 0) return;
1035
+ if (!report.ok) console.log(chalk.red(`rebase verify: ${summaryLine(report)}`));
1036
+ for (const finding of report.findings) printFinding(finding);
1037
+ return;
1038
+ }
1039
+ console.log("");
1040
+ console.log(` ${chalk.bold("rebase verify")} ${chalk.gray(report.schemaDir)}`);
1041
+ console.log("");
1042
+ for (const step of report.steps) {
1043
+ const mark = step.status === "passed" ? chalk.green("✓") : step.status === "failed" ? chalk.red("✗") : step.status === "warnings" ? chalk.yellow("!") : chalk.gray("–");
1044
+ const detail = step.detail ? chalk.gray(step.status === "skipped" ? `skipped: ${step.detail}` : step.detail) : "";
1045
+ console.log(` ${mark} ${step.title.padEnd(22)} ${detail}`);
1046
+ }
1047
+ if (report.findings.length > 0) {
1048
+ console.log("");
1049
+ for (const finding of report.findings) printFinding(finding);
1050
+ }
1051
+ console.log("");
1052
+ console.log(report.ok ? chalk.green(` ✓ ${summaryLine(report)}`) : chalk.red(` ✗ ${summaryLine(report)}`));
1053
+ console.log("");
1054
+ }
1055
+ function printVerifyHelp() {
1056
+ console.log(`
1057
+ ${chalk.bold("rebase verify")} — Check the tables are safe to ship
1058
+
1059
+ ${chalk.green.bold("Usage")}
1060
+ rebase verify [options]
1061
+
1062
+ ${chalk.green.bold("Options")}
1063
+ ${Object.entries(VERIFY_FLAG_HELP).map(([flag, help]) => ` ${chalk.blue(flag.padEnd(20))} ${help}`).join("\n")}
1064
+
1065
+ ${chalk.green.bold("Steps")}
1066
+ 1. Table definitions backend/schema loads and compiles as the backend boots it
1067
+ 2. RLS coverage owner and tenant columns are filtered on by the rules that read them
1068
+ 3. CMS customizations frontend/src/cms: each customizeTable names a table, its fields, and a form that can create
1069
+ 4. Migration freshness drizzle/migrations builds every declared table and column
1070
+ 5. Live RLS audit with --live: the rls-check catalogue against the project's database
1071
+
1072
+ Exits 1 when any step reports an error; warnings do not fail. Under --live, a
1073
+ database that is missing or does not answer is an error. Fast and offline
1074
+ without --live: for CI, and for the Claude Code hook that ${chalk.cyan("rebase skills --hooks")} installs.
1075
+ `);
1076
+ }
1077
+ /**
1078
+ * Whether the backend refuses a request with no token: `AUTH_REQUIRE` from the
1079
+ * environment, else `.env`, read as every boolean env var is read
1080
+ * (`parseEnvBoolean`: `false`/`0`/`no`/`off` turn it off). On unless one of
1081
+ * those says otherwise — the runtime's default. Compared raw, `AUTH_REQUIRE=0`
1082
+ * read as "on", and a compiled public read was reported as token-gated on a
1083
+ * backend that serves it to anyone.
1084
+ */
1085
+ function authRequiredFrom(environment, envFile) {
1086
+ return parseEnvBoolean(environment.AUTH_REQUIRE ?? envFile.AUTH_REQUIRE) !== false;
1087
+ }
1088
+ /**
1089
+ * The database `--live` audits, resolved as every other database door resolves
1090
+ * it (`db *`, `console`, `doctor`): `--database-url`, `DATABASE_URL`, `.env`,
1091
+ * `--docker` or the last `rebase dev --docker`, and otherwise the managed
1092
+ * development database — started if it is not running. Reading only
1093
+ * `DATABASE_URL` meant the audit never ran on a fresh scaffold, whose database
1094
+ * is the managed one.
1095
+ *
1096
+ * Progress goes to stderr, so `--json` keeps stdout to the report.
1097
+ */
1098
+ async function resolveLiveDatabase(projectRoot, rawArgs, options) {
1099
+ try {
1100
+ const { ensureDockerDatabase, databaseUrlOf } = await import("./db-A7XDCIIO.js");
1101
+ await ensureDockerDatabase(projectRoot, rawArgs);
1102
+ const { prepareDatabaseEnv } = await import("./prepare-Ccxspoj-.js");
1103
+ return { databaseUrl: databaseUrlOf(await prepareDatabaseEnv(projectRoot, {
1104
+ flagUrl: options.flagUrl,
1105
+ flagDocker: options.flagDocker,
1106
+ quiet: options.quiet,
1107
+ onProgress: options.quiet ? void 0 : (line) => console.error(chalk.gray(` ${line}`))
1108
+ }), readEnvFile(projectRoot)) };
1109
+ } catch (error) {
1110
+ return { databaseUnavailable: error instanceof Error ? error.message : String(error) };
1111
+ }
1112
+ }
1113
+ async function verifyCommand(rawArgs) {
1114
+ if (wantsHelp(rawArgs)) {
1115
+ printVerifyHelp();
1116
+ return;
1117
+ }
1118
+ refuseRemovedCollectionsFlag(rawArgs.slice(2), "verify");
1119
+ const { flags } = parseCommandArgs({
1120
+ spec: VERIFY_FLAGS,
1121
+ rawArgs,
1122
+ commandWords: 1,
1123
+ command: "verify",
1124
+ maxPositionals: 0
1125
+ });
1126
+ const projectRoot = requireProjectRoot();
1127
+ const backendDir = findBackendDir(projectRoot);
1128
+ const typedDir = flags["--schema-dir"];
1129
+ if (typedDir) {
1130
+ const refusal = missingSchemaDir(rawArgs, process.cwd(), backendDir ?? projectRoot, "verify");
1131
+ if (refusal) {
1132
+ if (flags["--json"]) failAsJson(`Schema directory not found: "${typedDir}" (resolved to ${path.resolve(process.cwd(), typedDir)}).`, "schema_dir_not_found", "Leave --schema-dir out (backend/schema is the default), or pass a directory that exists; relative paths are resolved from where you run the command.");
1133
+ console.error("");
1134
+ for (const line of refusal) console.error(line);
1135
+ console.error("");
1136
+ process.exit(1);
1137
+ }
1138
+ }
1139
+ const schemaDir = typedDir ? path.resolve(process.cwd(), typedDir) : resolveSchemaDir(projectRoot);
1140
+ const live = flags["--live"] === true;
1141
+ const report = await runVerify({
1142
+ projectRoot,
1143
+ schemaDir,
1144
+ backendDir,
1145
+ live,
1146
+ ...live ? await resolveLiveDatabase(projectRoot, rawArgs, {
1147
+ flagUrl: flags["--database-url"] ?? null,
1148
+ flagDocker: flags["--docker"] === true,
1149
+ quiet: flags["--quiet"] === true
1150
+ }) : {},
1151
+ authRequired: authRequiredFrom(process.env, readEnvFile(projectRoot))
1152
+ });
1153
+ if (flags["--json"]) console.log(JSON.stringify(report, null, 2));
1154
+ else printReport(report, flags["--quiet"] === true);
1155
+ if (!report.ok) process.exitCode = 1;
1156
+ }
1157
+ //#endregion
1158
+ export { verifyCommand };
1159
+
1160
+ //# sourceMappingURL=verify-DkJqhYPI.js.map