@rebasepro/server-postgres 0.30.0 → 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 (248) hide show
  1. package/README.md +11 -8
  2. package/dist/{BranchService-CrXvcES2.js → BranchService-USp1AvZB.js} +3 -3
  3. package/dist/{BranchService-CrXvcES2.js.map → BranchService-USp1AvZB.js.map} +1 -1
  4. package/dist/PostgresBackendDriver.d.ts +99 -54
  5. package/dist/PostgresBootstrapper.d.ts +12 -27
  6. package/dist/auth/ensure-tables.d.ts +16 -5
  7. package/dist/auth/schema-version.d.ts +2 -2
  8. package/dist/auth/services.d.ts +2 -3
  9. package/dist/{auth-users-columns-C72EMoDJ.js → auth-users-columns-BpfgbkxZ.js} +2 -16
  10. package/dist/auth-users-columns-BpfgbkxZ.js.map +1 -0
  11. package/dist/{backup-cli-CTKCOLpX.js → backup-cli-DbKyEj6c.js} +4 -4
  12. package/dist/{backup-cli-CTKCOLpX.js.map → backup-cli-DbKyEj6c.js.map} +1 -1
  13. package/dist/{boot-ddl-CqGIwSYx.js → boot-ddl-5H2bL_80.js} +2 -2
  14. package/dist/{boot-ddl-CqGIwSYx.js.map → boot-ddl-5H2bL_80.js.map} +1 -1
  15. package/dist/{cli-console-DBPw-oAz.js → cli-console-DsRgGSBR.js} +65 -39
  16. package/dist/cli-console-DsRgGSBR.js.map +1 -0
  17. package/dist/cli-console.d.ts +16 -13
  18. package/dist/cli-flags.d.ts +8 -9
  19. package/dist/cli-helpers.d.ts +15 -11
  20. package/dist/{cli-errors-DYTxnLbW.js → cli-schema-dir-CiN0ephV.js} +184 -70
  21. package/dist/cli-schema-dir-CiN0ephV.js.map +1 -0
  22. package/dist/cli-schema-dir.d.ts +64 -0
  23. package/dist/cli.js +192 -257
  24. package/dist/cli.js.map +1 -1
  25. package/dist/data-transformer.d.ts +50 -19
  26. package/dist/{database-preflight-iBpT7-vv.js → database-preflight-bfnIBnjM.js} +5 -5
  27. package/dist/database-preflight-bfnIBnjM.js.map +1 -0
  28. package/dist/{deferred-index-build-BCU9RoHK.js → deferred-index-build-CcSDA7wE.js} +69 -13
  29. package/dist/deferred-index-build-CcSDA7wE.js.map +1 -0
  30. package/dist/{ensure-collection-policies-Bo-_fDAy.js → ensure-policies-rRmXb5bt.js} +31 -31
  31. package/dist/ensure-policies-rRmXb5bt.js.map +1 -0
  32. package/dist/{ensure-collection-tables-DCJINkT_.js → ensure-tables-Bvm-F2wW.js} +44 -37
  33. package/dist/ensure-tables-Bvm-F2wW.js.map +1 -0
  34. package/dist/{ensure-tables-BPGaGh0y.js → ensure-tables-CC8p_AK3.js} +34 -29
  35. package/dist/ensure-tables-CC8p_AK3.js.map +1 -0
  36. package/dist/{enum-labels-kept-YAgOZS4I.js → enum-labels-kept-FlX9SHdf.js} +8 -8
  37. package/dist/enum-labels-kept-FlX9SHdf.js.map +1 -0
  38. package/dist/{generate-drizzle-schema-DcrFr7YX.js → generate-drizzle-schema-SJMXxzPI.js} +12 -12
  39. package/dist/generate-drizzle-schema-SJMXxzPI.js.map +1 -0
  40. package/dist/{generate-drizzle-schema-logic-LTLZvt6r.js → generate-drizzle-schema-logic-DL7R1rAF.js} +15 -8
  41. package/dist/generate-drizzle-schema-logic-DL7R1rAF.js.map +1 -0
  42. package/dist/{generate-files-CsaVzatS.js → generate-files-tlJ9_lGI.js} +23 -30
  43. package/dist/generate-files-tlJ9_lGI.js.map +1 -0
  44. package/dist/{generate-next-step-DgK5BlBn.js → generate-next-step-CO09dovd.js} +3 -3
  45. package/dist/generate-next-step-CO09dovd.js.map +1 -0
  46. package/dist/{generate-postgres-ddl-logic-Dg0bcENZ.js → generate-postgres-ddl-logic-B8huc03c.js} +51 -21
  47. package/dist/generate-postgres-ddl-logic-B8huc03c.js.map +1 -0
  48. package/dist/{generated-schema-diff-By4dxyTH.js → generated-schema-diff-DoT2dYDe.js} +297 -279
  49. package/dist/generated-schema-diff-DoT2dYDe.js.map +1 -0
  50. package/dist/{generated-schema-staleness-BvNF3i-s.js → generated-schema-staleness-YBVq2kTn.js} +21 -29
  51. package/dist/generated-schema-staleness-YBVq2kTn.js.map +1 -0
  52. package/dist/history/ensure-history-table.d.ts +22 -0
  53. package/dist/index.d.ts +8 -2
  54. package/dist/index.es.js +201 -25
  55. package/dist/index.es.js.map +1 -1
  56. package/dist/interfaces.d.ts +3 -4
  57. package/dist/{introspect-db-queries-DevUrzll.js → introspect-db-queries-BgiRQqtR.js} +7 -2
  58. package/dist/introspect-db-queries-BgiRQqtR.js.map +1 -0
  59. package/dist/introspect-tables-Cw_A-kk4.js +2086 -0
  60. package/dist/introspect-tables-Cw_A-kk4.js.map +1 -0
  61. package/dist/load-tables-B1Re74ng.js +92 -0
  62. package/dist/load-tables-B1Re74ng.js.map +1 -0
  63. package/dist/{migrate-baseline-CmWXL7qx.js → migrate-baseline-DZmekgpD.js} +19 -32
  64. package/dist/migrate-baseline-DZmekgpD.js.map +1 -0
  65. package/dist/{migrate-policy-stamps-BN_Qad6c.js → migrate-policy-stamps-B_acrUQB.js} +18 -19
  66. package/dist/migrate-policy-stamps-B_acrUQB.js.map +1 -0
  67. package/dist/model/PostgresTableRegistry.d.ts +159 -0
  68. package/dist/model/build-registry.d.ts +25 -0
  69. package/dist/model/refresh-relational-schema.d.ts +24 -0
  70. package/dist/model/runtime-table.d.ts +53 -0
  71. package/dist/{collections → model}/validate-relations.d.ts +15 -21
  72. package/dist/{open-rebase-40paQfVW.js → open-rebase-4kisUF_k.js} +3946 -3870
  73. package/dist/open-rebase-4kisUF_k.js.map +1 -0
  74. package/dist/open-rebase.d.ts +16 -15
  75. package/dist/{pg-error-utils-DJHjCF7-.js → pg-error-utils-BT5NzGFZ.js} +17 -20
  76. package/dist/pg-error-utils-BT5NzGFZ.js.map +1 -0
  77. package/dist/plan-schema-Hbtjhge3.js +1633 -0
  78. package/dist/plan-schema-Hbtjhge3.js.map +1 -0
  79. package/dist/{policy-drift-C-m0uWHH.js → policy-drift-BVMyqHSa.js} +29 -29
  80. package/dist/policy-drift-BVMyqHSa.js.map +1 -0
  81. package/dist/{push-index-adoption-Cp7oZxSl.js → push-index-adoption-hpHTyXMR.js} +7 -7
  82. package/dist/push-index-adoption-hpHTyXMR.js.map +1 -0
  83. package/dist/{push-index-prebuild-DbwKGtQT.js → push-index-prebuild-Bty9F7bD.js} +6 -6
  84. package/dist/push-index-prebuild-Bty9F7bD.js.map +1 -0
  85. package/dist/{push-kept-defaults-CLcgsEPt.js → push-kept-defaults-Bst4MDup.js} +13 -16
  86. package/dist/push-kept-defaults-Bst4MDup.js.map +1 -0
  87. package/dist/{push-legacy-renames-BthD0E9W.js → push-legacy-renames-bB4bM6br.js} +6 -6
  88. package/dist/push-legacy-renames-bB4bM6br.js.map +1 -0
  89. package/dist/{push-policy-plan-BgcrroxQ.js → push-policy-plan-BI8U4BOD.js} +11 -11
  90. package/dist/push-policy-plan-BI8U4BOD.js.map +1 -0
  91. package/dist/{render-ddl-Ci3S_SoI.js → render-ddl-D4n86NHz.js} +14 -7
  92. package/dist/render-ddl-D4n86NHz.js.map +1 -0
  93. package/dist/{request-role-cli-Dy1EgJU9.js → request-role-cli-BdRzdE87.js} +11 -11
  94. package/dist/{request-role-cli-Dy1EgJU9.js.map → request-role-cli-BdRzdE87.js.map} +1 -1
  95. package/dist/{request-role-migration-GHTJnPMV.js → request-role-migration-C8aq_TO3.js} +2 -2
  96. package/dist/{request-role-migration-GHTJnPMV.js.map → request-role-migration-C8aq_TO3.js.map} +1 -1
  97. package/dist/{rls-enforcement-Cc_UhOxb.js → rls-enforcement-DB5HHj96.js} +19 -19
  98. package/dist/rls-enforcement-DB5HHj96.js.map +1 -0
  99. package/dist/{rls-settings-BCGMIig3.js → rls-settings-CmGK2U0a.js} +2 -2
  100. package/dist/rls-settings-CmGK2U0a.js.map +1 -0
  101. package/dist/schema/auth-users-columns.d.ts +1 -11
  102. package/dist/schema/catalogue-schema.d.ts +33 -29
  103. package/dist/schema/classify-change.d.ts +23 -16
  104. package/dist/schema/column-type-drift.d.ts +16 -0
  105. package/dist/schema/config-relations.d.ts +10 -9
  106. package/dist/schema/deferred-index-build.d.ts +1 -1
  107. package/dist/schema/doctor-cli.js +1544 -66
  108. package/dist/schema/doctor-cli.js.map +1 -1
  109. package/dist/schema/doctor-database.d.ts +7 -7
  110. package/dist/schema/doctor-policy-checks.d.ts +4 -4
  111. package/dist/schema/doctor-search-scale.d.ts +14 -14
  112. package/dist/schema/doctor.d.ts +27 -27
  113. package/dist/schema/dynamic-tables.d.ts +6 -5
  114. package/dist/schema/{ensure-collection-policies.d.ts → ensure-policies.d.ts} +20 -20
  115. package/dist/schema/{ensure-collection-tables.d.ts → ensure-tables.d.ts} +11 -11
  116. package/dist/schema/enum-labels-kept.d.ts +6 -6
  117. package/dist/schema/generate-drizzle-schema-logic.d.ts +3 -3
  118. package/dist/schema/generate-drizzle-schema.js +1 -1
  119. package/dist/schema/generate-files.d.ts +6 -6
  120. package/dist/schema/generate-postgres-ddl-logic.d.ts +23 -20
  121. package/dist/schema/generate-postgres-ddl.js +11 -11
  122. package/dist/schema/generate-postgres-ddl.js.map +1 -1
  123. package/dist/schema/generate-schema-commit.d.ts +13 -8
  124. package/dist/schema/generated-schema-diff.d.ts +16 -16
  125. package/dist/schema/generated-schema-staleness.d.ts +11 -11
  126. package/dist/schema/index-adoption.d.ts +4 -4
  127. package/dist/schema/introspect-db-customization.d.ts +47 -0
  128. package/dist/schema/introspect-db-inference.d.ts +30 -9
  129. package/dist/schema/introspect-db-logic.d.ts +79 -110
  130. package/dist/schema/introspect-db-project.d.ts +15 -18
  131. package/dist/schema/introspect-db-queries.d.ts +1 -1
  132. package/dist/schema/introspect-db-search.d.ts +25 -4
  133. package/dist/schema/introspect-db-storage.d.ts +4 -74
  134. package/dist/schema/introspect-db.js +102 -90
  135. package/dist/schema/introspect-db.js.map +1 -1
  136. package/dist/schema/introspect-runtime.d.ts +47 -36
  137. package/dist/schema/introspect-tables.d.ts +182 -0
  138. package/dist/schema/load-tables.d.ts +55 -0
  139. package/dist/schema/migrate-policy-stamps.d.ts +4 -4
  140. package/dist/schema/migration-freshness.d.ts +13 -13
  141. package/dist/schema/plan/column-order.d.ts +82 -0
  142. package/dist/schema/plan/diff-plan.d.ts +9 -3
  143. package/dist/schema/plan/plan-schema.d.ts +55 -52
  144. package/dist/schema/plan/render-drizzle.d.ts +1 -1
  145. package/dist/schema/plan/types.d.ts +24 -15
  146. package/dist/schema/push-index-adoption.d.ts +3 -3
  147. package/dist/schema/push-index-prebuild.d.ts +3 -3
  148. package/dist/schema/push-kept-defaults.d.ts +7 -7
  149. package/dist/schema/push-legacy-renames.d.ts +3 -3
  150. package/dist/schema/push-policy-plan.d.ts +5 -5
  151. package/dist/schema/reconcile-schema.d.ts +5 -5
  152. package/dist/schema/relation-names.d.ts +15 -20
  153. package/dist/schema/render-outputs.d.ts +76 -0
  154. package/dist/schema/search-column.d.ts +11 -43
  155. package/dist/schema/{collection-index.d.ts → table-index.d.ts} +21 -42
  156. package/dist/schema/{collections-schema-version.d.ts → tables-schema-version.d.ts} +8 -2
  157. package/dist/schema/vector-index.d.ts +24 -28
  158. package/dist/{search-column-BM-GV6vH.js → search-column-BO-WND-B.js} +86 -149
  159. package/dist/search-column-BO-WND-B.js.map +1 -0
  160. package/dist/security/caller-sql-columns.d.ts +9 -6
  161. package/dist/security/policy-drift.d.ts +14 -14
  162. package/dist/security/rls-enforcement.d.ts +19 -25
  163. package/dist/security/rls-settings.d.ts +2 -2
  164. package/dist/security/served-table-protection.d.ts +125 -0
  165. package/dist/services/FetchService.d.ts +22 -133
  166. package/dist/services/PersistService.d.ts +6 -17
  167. package/dist/services/RelationService.d.ts +57 -106
  168. package/dist/services/RelationWriteService.d.ts +59 -66
  169. package/dist/services/cdc/identity-columns.d.ts +7 -5
  170. package/dist/services/cdc/junction-tables.d.ts +14 -14
  171. package/dist/services/collection-helpers.d.ts +52 -95
  172. package/dist/services/dataService.d.ts +15 -12
  173. package/dist/services/field-op-sql.d.ts +11 -9
  174. package/dist/services/field-viewer.d.ts +12 -11
  175. package/dist/services/hidden-columns.d.ts +30 -0
  176. package/dist/services/index.d.ts +1 -1
  177. package/dist/services/junction-writes.d.ts +37 -18
  178. package/dist/services/nested-path.d.ts +18 -18
  179. package/dist/services/read-field-access.d.ts +23 -7
  180. package/dist/services/read-scope.d.ts +10 -9
  181. package/dist/services/realtimeService.d.ts +25 -10
  182. package/dist/services/relation-tables.d.ts +97 -0
  183. package/dist/services/row-pipeline.d.ts +50 -69
  184. package/dist/services/soft-delete.d.ts +25 -24
  185. package/dist/services/table-hooks.d.ts +146 -0
  186. package/dist/services/view-access.d.ts +7 -7
  187. package/dist/services/write-transaction-scope.d.ts +1 -1
  188. package/dist/{source-fZb92pN8.js → source-VxbrQojV.js} +111 -79
  189. package/dist/source-VxbrQojV.js.map +1 -0
  190. package/dist/{collections-schema-version-D7bDI0PJ.js → tables-schema-version-YvZIBlOP.js} +12 -6
  191. package/dist/tables-schema-version-YvZIBlOP.js.map +1 -0
  192. package/dist/utils/drizzle-conditions.d.ts +70 -84
  193. package/dist/utils/pg-array-null-patch.d.ts +27 -10
  194. package/dist/utils/pg-error-utils.d.ts +4 -4
  195. package/dist/{vector-index-DsQ3V2d2.js → vector-index-VSh3ufTd.js} +62 -54
  196. package/dist/vector-index-VSh3ufTd.js.map +1 -0
  197. package/dist/{websocket-B7ex6AQM.js → websocket-BevXvwfo.js} +51 -40
  198. package/dist/websocket-BevXvwfo.js.map +1 -0
  199. package/dist/websocket.d.ts +2 -2
  200. package/package.json +7 -7
  201. package/dist/auth-users-columns-C72EMoDJ.js.map +0 -1
  202. package/dist/cli-collections-path.d.ts +0 -31
  203. package/dist/cli-console-DBPw-oAz.js.map +0 -1
  204. package/dist/cli-errors-DYTxnLbW.js.map +0 -1
  205. package/dist/collections/PostgresCollectionRegistry.d.ts +0 -47
  206. package/dist/collections/buildRegistry.d.ts +0 -27
  207. package/dist/collections-schema-version-D7bDI0PJ.js.map +0 -1
  208. package/dist/column-plan-helpers-BeSztMor.js +0 -161
  209. package/dist/column-plan-helpers-BeSztMor.js.map +0 -1
  210. package/dist/database-preflight-iBpT7-vv.js.map +0 -1
  211. package/dist/deferred-index-build-BCU9RoHK.js.map +0 -1
  212. package/dist/doctor-Kg1oUK0Q.js +0 -1458
  213. package/dist/doctor-Kg1oUK0Q.js.map +0 -1
  214. package/dist/ensure-collection-policies-Bo-_fDAy.js.map +0 -1
  215. package/dist/ensure-collection-tables-DCJINkT_.js.map +0 -1
  216. package/dist/ensure-tables-BPGaGh0y.js.map +0 -1
  217. package/dist/enum-labels-kept-YAgOZS4I.js.map +0 -1
  218. package/dist/generate-drizzle-schema-DcrFr7YX.js.map +0 -1
  219. package/dist/generate-drizzle-schema-logic-LTLZvt6r.js.map +0 -1
  220. package/dist/generate-files-CsaVzatS.js.map +0 -1
  221. package/dist/generate-next-step-DgK5BlBn.js.map +0 -1
  222. package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +0 -1
  223. package/dist/generated-schema-diff-By4dxyTH.js.map +0 -1
  224. package/dist/generated-schema-staleness-BvNF3i-s.js.map +0 -1
  225. package/dist/introspect-db-logic-DWqAEURB.js +0 -2047
  226. package/dist/introspect-db-logic-DWqAEURB.js.map +0 -1
  227. package/dist/introspect-db-queries-DevUrzll.js.map +0 -1
  228. package/dist/migrate-baseline-CmWXL7qx.js.map +0 -1
  229. package/dist/migrate-policy-stamps-BN_Qad6c.js.map +0 -1
  230. package/dist/open-rebase-40paQfVW.js.map +0 -1
  231. package/dist/pg-error-utils-DJHjCF7-.js.map +0 -1
  232. package/dist/plan-schema-vJd3UEmT.js +0 -1604
  233. package/dist/plan-schema-vJd3UEmT.js.map +0 -1
  234. package/dist/policy-drift-C-m0uWHH.js.map +0 -1
  235. package/dist/push-index-adoption-Cp7oZxSl.js.map +0 -1
  236. package/dist/push-index-prebuild-DbwKGtQT.js.map +0 -1
  237. package/dist/push-kept-defaults-CLcgsEPt.js.map +0 -1
  238. package/dist/push-legacy-renames-BthD0E9W.js.map +0 -1
  239. package/dist/push-policy-plan-BgcrroxQ.js.map +0 -1
  240. package/dist/render-ddl-Ci3S_SoI.js.map +0 -1
  241. package/dist/rls-enforcement-Cc_UhOxb.js.map +0 -1
  242. package/dist/rls-settings-BCGMIig3.js.map +0 -1
  243. package/dist/schema/column-plan-helpers.d.ts +0 -161
  244. package/dist/schema/introspect-db-naming.d.ts +0 -10
  245. package/dist/search-column-BM-GV6vH.js.map +0 -1
  246. package/dist/source-fZb92pN8.js.map +0 -1
  247. package/dist/vector-index-DsQ3V2d2.js.map +0 -1
  248. package/dist/websocket-B7ex6AQM.js.map +0 -1
@@ -1,15 +1,1494 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __createRequire } from "module";
3
3
  __createRequire(import.meta.url);
4
- import { a as buildSearchColumnSpec } from "../search-column-BM-GV6vH.js";
5
- import { a as diagnoseDbError } from "../cli-errors-DYTxnLbW.js";
6
- import { C as warnOnAnonymousGrants, S as validatePolicyPgRoles } from "../rls-enforcement-Cc_UhOxb.js";
7
- import { n as describeFailure, t as chalk } from "../source-fZb92pN8.js";
8
- import { i as hasDrift, r as formatPolicyDrift, t as checkPolicyDrift } from "../policy-drift-C-m0uWHH.js";
9
- import { n as loadCollections, r as runDoctor } from "../doctor-Kg1oUK0Q.js";
10
- import { isPostgresCollectionConfig } from "@rebasepro/types";
11
- import { getTableName, relationalCollections, resolveJunctionSpecs } from "@rebasepro/common";
4
+ import { i as buildTableSearchColumnSpec } from "../search-column-BO-WND-B.js";
5
+ import { c as diagnoseDbError, o as deepestErrorMessage, p as parseHostInfo } from "../cli-schema-dir-CiN0ephV.js";
6
+ import { C as warnOnAnonymousGrants, S as validatePolicyPgRoles } from "../rls-enforcement-DB5HHj96.js";
7
+ import { i as outError, n as describeFailure, r as out, t as chalk } from "../source-VxbrQojV.js";
8
+ import { n as planSchema, t as pgTypeOf } from "../plan-schema-Hbtjhge3.js";
9
+ import { t as generateSchema } from "../generate-drizzle-schema-logic-DL7R1rAF.js";
10
+ import { i as renderPgType } from "../render-ddl-D4n86NHz.js";
11
+ import { n as loadTableSchema, r as loadTables, t as defaultDatabaseSchemaVersion } from "../load-tables-B1Re74ng.js";
12
+ import { r as readGeneratedSchemaDrift, t as describeSchemaDifference } from "../generated-schema-diff-DoT2dYDe.js";
13
+ import { i as hasDrift, r as formatPolicyDrift, t as checkPolicyDrift } from "../policy-drift-BVMyqHSa.js";
14
+ import { n as describeDeclarationDifferences, t as compareGeneratedDeclarations } from "../generated-schema-staleness-YBVq2kTn.js";
15
+ import { describeMismatch } from "@rebasepro/server";
16
+ import { DEFAULT_DATA_SOURCE_KEY, LEGACY_SCHEMA_VERSION_PREFIX, isNumericColumnType, isTemporalColumnType } from "@rebasepro/types";
17
+ import { isIlikeSearchable, relationsOfKind, resolveTableJunctions, sortCollectionsBySlug, sortTablesBySlug, toSafeIdentifier, toTableAccessor } from "@rebasepro/common";
18
+ import { toPostgresIdentifier } from "@rebasepro/utils";
12
19
  import path from "path";
20
+ import * as fs$1 from "fs";
21
+ import { promises } from "fs";
22
+ import { pathToFileURL } from "url";
23
+ //#region ../codegen/dist/index.es.js
24
+ /**
25
+ * A schema that cannot be expressed as a valid TypeScript file.
26
+ *
27
+ * Thrown rather than emitted. The generator used to concatenate whatever it was
28
+ * given, so a slug that collided with another one, or that was not an
29
+ * identifier, produced a file that either failed to compile or — worse —
30
+ * compiled while quietly routing one table to another's slug.
31
+ *
32
+ * @group SDK generation
33
+ */
34
+ var CodegenError = class extends Error {
35
+ constructor(message) {
36
+ super(message);
37
+ this.name = "CodegenError";
38
+ }
39
+ };
40
+ var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
41
+ /**
42
+ * A property name for the emitted TypeScript: verbatim when it is a valid
43
+ * identifier, quoted otherwise.
44
+ *
45
+ * Every key that reaches the output goes through here. Column keys are not
46
+ * required to be identifiers — `"order"`, `"user id"`, a quoted Postgres
47
+ * identifier — and the previous behaviour of camel-casing them into shape
48
+ * renamed the column in the type while the wire kept the original, so the
49
+ * generated `Row` described fields that did not exist.
50
+ */
51
+ function emitKey(key) {
52
+ return IDENTIFIER.test(key) ? key : JSON.stringify(key);
53
+ }
54
+ /**
55
+ * A string literal, escaped.
56
+ *
57
+ * `"${value}"` was the previous form. A value containing a quote closed the
58
+ * literal early, which at best broke the file and at worst let a slug from a
59
+ * remote schema inject top-level statements into a file the developer
60
+ * compiles and bundles.
61
+ */
62
+ function emitString(value) {
63
+ return JSON.stringify(value);
64
+ }
65
+ var GEOPOINT_TYPE = "{ latitude: number; longitude: number; }";
66
+ /** A closed value set as a union of literals: strings escaped, numbers only when every value is one. */
67
+ function literalUnion(values, numeric) {
68
+ if (values.length === 0) return void 0;
69
+ if (numeric) {
70
+ const numbers = values.map(Number);
71
+ if (numbers.some((n) => !Number.isFinite(n))) return void 0;
72
+ return numbers.map((n) => String(n)).join(" | ");
73
+ }
74
+ return values.map((v) => emitString(String(v))).join(" | ");
75
+ }
76
+ /**
77
+ * The TypeScript type of a value of one Postgres type, as the wire serves it.
78
+ *
79
+ * A Postgres enum and a `.oneOf()` set are literal unions; a timestamp, a date
80
+ * and a time are ISO strings; `bytea` is base64; a vector is its numbers; a
81
+ * type Rebase serves but does not create (`other`) is `unknown`.
82
+ */
83
+ function scalarType(type, oneOf) {
84
+ if (type.kind === "enum") return literalUnion(type.values, false) ?? "string";
85
+ if (isNumericColumnType(type)) return (oneOf && literalUnion(oneOf, true)) ?? "number";
86
+ switch (type.kind) {
87
+ case "text":
88
+ case "varchar":
89
+ case "char":
90
+ case "uuid": return (oneOf && literalUnion(oneOf, false)) ?? "string";
91
+ case "boolean": return "boolean";
92
+ case "timestamptz":
93
+ case "date":
94
+ case "time": return "string";
95
+ case "vector": return "number[]";
96
+ case "bytea": return "string";
97
+ case "json":
98
+ case "jsonb": return "Record<string, unknown>";
99
+ default: return "unknown";
100
+ }
101
+ }
102
+ /**
103
+ * The TypeScript type of a JSON document, from the shape the table declares.
104
+ *
105
+ * An object types its declared fields — a field the shape does not mark
106
+ * `required` may be absent or null — and an open object (`additional`) with no
107
+ * declared field is a record. A typed block list (`json.oneOf`) is the union of
108
+ * its blocks, each a `{ <typeField>: "<variant>"; <valueField>: … }`.
109
+ */
110
+ function jsonType(shape) {
111
+ switch (shape.kind) {
112
+ case "string": return (shape.oneOf && literalUnion(shape.oneOf, false)) ?? "string";
113
+ case "number": return (shape.oneOf && literalUnion(shape.oneOf, true)) ?? "number";
114
+ case "boolean": return "boolean";
115
+ case "date": return "string";
116
+ case "geopoint": return GEOPOINT_TYPE;
117
+ case "object": {
118
+ const entries = Object.entries(shape.fields);
119
+ if (entries.length === 0 && shape.additional) return "Record<string, unknown>";
120
+ return `{ ${entries.map(([key, field]) => {
121
+ const optional = !field.required;
122
+ const type = jsonType(field);
123
+ return `${emitKey(key)}${optional ? "?" : ""}: ${optional ? `${type} | null` : type};`;
124
+ }).join(" ")} }`;
125
+ }
126
+ case "array": return `Array<${jsonType(shape.of)}>`;
127
+ case "oneOf": {
128
+ const variants = Object.entries(shape.variants);
129
+ if (variants.length === 0 || shape.typeField === shape.valueField) return "unknown";
130
+ return variants.map(([name, variant]) => `{ ${emitKey(shape.typeField)}: ${emitString(name)}; ${emitKey(shape.valueField)}: ${jsonType(variant)}; }`).join(" | ");
131
+ }
132
+ default: return "unknown";
133
+ }
134
+ }
135
+ /** The TypeScript type of a column's value on a read. */
136
+ function columnType(column) {
137
+ if (column.semantic === "geopoint") return GEOPOINT_TYPE;
138
+ if (column.json && (column.type.kind === "json" || column.type.kind === "jsonb")) return jsonType(column.json);
139
+ if (column.type.kind === "array") return `Array<${scalarType(column.type.of, column.element?.oneOf)}>`;
140
+ return scalarType(column.type, column.oneOf);
141
+ }
142
+ /**
143
+ * The TypeScript type of a key: `number` for a numeric column, `string` for
144
+ * every other — what a foreign key, a link written by the relation's name and
145
+ * a to-many membership hold.
146
+ */
147
+ function keyType(column) {
148
+ if (!column) return "string | number";
149
+ return isNumericColumnType(column.type) ? "number" : "string";
150
+ }
151
+ /**
152
+ * A column's type on a write: its own type (a temporal column also as a
153
+ * `Date`), or `null` too when it is nullable.
154
+ *
155
+ * `Row` has typed a nullable column `T | null` for a while; its write twins
156
+ * did not, so the one way to clear a value — `update(id, { publishedAt: null })`,
157
+ * `{ authorId: null }` to unassign, the edit-form round trip of a row that came
158
+ * back with nulls in it — was a compile error the server would have accepted.
159
+ * A primary key is never null.
160
+ */
161
+ function writableType(column, tsType) {
162
+ const written = isTemporalColumnType(column.type) ? `${tsType} | Date` : tsType;
163
+ return column.nullable ? `${written} | null` : written;
164
+ }
165
+ /**
166
+ * Whether a create may leave the column out: it may be null, or the database
167
+ * or the server fills it — a default of any kind (a literal, SQL, a random
168
+ * uuid, an identity, one the database owns), a serial, a stamp.
169
+ */
170
+ function insertOptional(column) {
171
+ if (column.nullable) return true;
172
+ if (column.default !== void 0 || column.stamp !== void 0) return true;
173
+ const kind = column.type.kind;
174
+ return kind === "smallserial" || kind === "serial" || kind === "bigserial";
175
+ }
176
+ /** Nobody may read it: `.private()`, or `access({ read: [] })`. */
177
+ function unreadable(column) {
178
+ return column.private === true || column.access?.read?.length === 0;
179
+ }
180
+ /** Nobody may write it: `.private()`, `.readOnly()`, generated, or `access({ write: [] })`. */
181
+ function unwritable(column) {
182
+ return column.private === true || column.readOnly === true || column.generated !== void 0 || column.access?.write?.length === 0;
183
+ }
184
+ /** One emitted `key: type;` line, already indented. */
185
+ function line(key, type, optional) {
186
+ return ` ${emitKey(key)}${optional ? "?" : ""}: ${type};`;
187
+ }
188
+ /**
189
+ * Map every slug to the property name it is reachable under on `client.data`.
190
+ *
191
+ * The accessor is a safe identifier because `client.data.myNotes` is the point
192
+ * of generating this at all, and `tablesDictionary` maps it back to the
193
+ * slug the wire uses. Two slugs that safe down to the same identifier cannot
194
+ * both have it: the interface would not compile, and the dictionary — an object
195
+ * literal — would silently keep only the last, routing one table's reads to
196
+ * the other's. There is no defensible way to pick, so this refuses.
197
+ */
198
+ function buildAccessors(tables) {
199
+ const accessors = /* @__PURE__ */ new Map();
200
+ const bySafeName = /* @__PURE__ */ new Map();
201
+ for (const table of tables) {
202
+ const slug = table.slug;
203
+ if (typeof slug !== "string" || slug.length === 0) throw new CodegenError("A table has no slug, so it has no name to generate a type for. Every table needs a unique `slug`.");
204
+ const safe = toSafeIdentifier(slug);
205
+ if (safe.length === 0) throw new CodegenError(`The slug ${emitString(slug)} has no characters that can form a property name, so it cannot be reached as \`client.data.<name>\`. Use a slug containing letters, digits, underscores or dashes.`);
206
+ const accessor = toTableAccessor(slug);
207
+ if (accessor !== safe) console.warn(`[codegen] The table ${emitString(slug)} would be \`client.data.${safe}\`, a name the client reserves, so its typed accessor is \`client.data.${accessor}\`. \`client.data.table(${emitString(slug)})\` reaches it too.`);
208
+ const existing = bySafeName.get(accessor);
209
+ if (existing !== void 0) throw new CodegenError(`The tables ${emitString(existing)} and ${emitString(slug)} both generate the accessor "${accessor}", so only one of them could be reached from the generated client and the other's reads would silently go to the wrong table. Rename one of the slugs.`);
210
+ bySafeName.set(accessor, slug);
211
+ accessors.set(slug, accessor);
212
+ }
213
+ return accessors;
214
+ }
215
+ /** The single key column of a table, or its first, for the type a link to it holds. */
216
+ function keyColumnOf(table) {
217
+ if (!table) return void 0;
218
+ const key = table.primaryKey[0];
219
+ return key === void 0 ? void 0 : table.columns.find((column) => column.key === key);
220
+ }
221
+ /**
222
+ * The type a link to a relation's target holds: whatever the target's key is —
223
+ * or, for a target outside this run, whatever the `belongsTo`'s own foreign-key
224
+ * column holds.
225
+ */
226
+ function targetKeyType(relation, run, plan) {
227
+ const own = relation.kind === "belongsTo" ? plan.byKey.get(relation.localField) : void 0;
228
+ return keyType(keyColumnOf(run.bySlug.get(relation.target)) ?? own);
229
+ }
230
+ /** Two column types that a foreign key may hold between: identical, a serial read as its integer. */
231
+ function sameKeyType(a, b) {
232
+ const plain = (type) => {
233
+ switch (type.kind) {
234
+ case "smallserial": return { kind: "smallint" };
235
+ case "serial": return { kind: "integer" };
236
+ case "bigserial": return { kind: "bigint" };
237
+ default: return type;
238
+ }
239
+ };
240
+ return JSON.stringify(plain(a)) === JSON.stringify(plain(b));
241
+ }
242
+ /**
243
+ * The key a foreign-key column is served under when a relation derives it:
244
+ * `author_id` → `authorId`, each later segment keeping its own casing. The
245
+ * same rule as `toWireKey` in `@rebasepro/utils` (which this package does not
246
+ * depend on); used only to recognise such a column, never to name one.
247
+ */
248
+ function derivedFieldKey(localKey) {
249
+ const segments = localKey.split(/[-_ ]+/).filter(Boolean);
250
+ if (segments.length <= 1) return localKey;
251
+ return segments.map((segment, index) => index === 0 ? segment.charAt(0).toLowerCase() + segment.slice(1) : segment.charAt(0).toUpperCase() + segment.slice(1)).join("");
252
+ }
253
+ /**
254
+ * Whether a `belongsTo`'s column is nothing but the link: the column the
255
+ * relation would derive (its key the derived key of `localKey`, the target's
256
+ * key type, no rule, default or flag of its own), over a constraint.
257
+ *
258
+ * Such a column is listed with the relations, after the table's own columns —
259
+ * where a derived foreign key always is, so declaring the column a relation
260
+ * would derive does not move it in the generated types.
261
+ */
262
+ function isLinkOnly(column, relation, run) {
263
+ if (!relation.constraint) return false;
264
+ if (column.derived) return true;
265
+ if (derivedFieldKey(relation.localKey) !== column.key) return false;
266
+ if (column.primaryKey || column.default !== void 0 || column.generated !== void 0 || column.readOnly || column.private) return false;
267
+ if (column.access !== void 0 || column.stamp !== void 0 || column.validate !== void 0 || column.oneOf !== void 0) return false;
268
+ if (column.description !== void 0 || column.storage !== void 0 || column.semantic !== void 0) return false;
269
+ if (column.vectorIndex !== void 0 || column.json !== void 0 || column.element !== void 0 || column.transforms !== void 0) return false;
270
+ const targetKey = keyColumnOf(run.bySlug.get(relation.target));
271
+ return targetKey === void 0 || sameKeyType(column.type, targetKey.type);
272
+ }
273
+ function planTable(table, run) {
274
+ const byKey = new Map(table.columns.map((column) => [column.key, column]));
275
+ const linkColumns = /* @__PURE__ */ new Set();
276
+ const links = [];
277
+ for (const relation of table.relations) {
278
+ if (relation.kind !== "belongsTo") continue;
279
+ const column = byKey.get(relation.localField);
280
+ const listedWithRelation = column !== void 0 && isLinkOnly(column, relation, run);
281
+ if (listedWithRelation && column) linkColumns.add(column.key);
282
+ links.push({
283
+ relation,
284
+ column: listedWithRelation ? column : void 0
285
+ });
286
+ }
287
+ const excluded = /* @__PURE__ */ new Set();
288
+ const unwritableKeys = /* @__PURE__ */ new Set();
289
+ for (const column of table.columns) {
290
+ const closedWrite = unwritable(column);
291
+ if (closedWrite) unwritableKeys.add(column.key);
292
+ if (closedWrite && unreadable(column)) excluded.add(column.key);
293
+ }
294
+ for (const relation of table.relations) {
295
+ if (relation.kind !== "belongsTo") continue;
296
+ if (excluded.has(relation.localField)) excluded.add(relation.name);
297
+ if (unwritableKeys.has(relation.localField)) unwritableKeys.add(relation.name);
298
+ }
299
+ for (const key of excluded) unwritableKeys.add(key);
300
+ return {
301
+ table,
302
+ columns: table.columns.filter((column) => !linkColumns.has(column.key)),
303
+ links,
304
+ excluded,
305
+ unwritable: unwritableKeys,
306
+ byKey
307
+ };
308
+ }
309
+ /**
310
+ * The type an *included* relation arrives as: the target's own row, inlined.
311
+ *
312
+ * This is what the read pipeline actually serves — the target's flat columns
313
+ * where the relation was, through the SDK and the HTTP API alike. It is
314
+ * deliberately *not* a `{ __type: "relation" }` envelope: that shape is the
315
+ * panel's view-model and never reaches a developer's `find()`.
316
+ *
317
+ * Falls back to an open record when the target is not part of this generation
318
+ * run, since there is no `Row` to point at.
319
+ */
320
+ function includedRelationType(relation, run) {
321
+ const accessor = run.accessors.get(relation.target);
322
+ const rowType = accessor ? `Database[${emitString(accessor)}]["Row"]` : "Record<string, unknown>";
323
+ const pivot = relation.kind === "manyToMany" ? pivotType(relation.through.pivot, "read") : void 0;
324
+ const elementType = pivot ? `${rowType} & { _pivot?: ${pivot} }` : rowType;
325
+ return relation.cardinality === "many" ? `Array<${elementType}>` : elementType;
326
+ }
327
+ /**
328
+ * Generate the typed SDK's `database.types.ts` from table descriptors — what
329
+ * `compileTables` produces, `GET /api/schema/tables` serves and introspection
330
+ * reports.
331
+ *
332
+ * Emits `Database` (per table: `Row`, `Insert`, `Update`, `Relations`, `Slug`),
333
+ * `TableName`, `tablesDictionary`, `TablesDictionary` and the
334
+ * `include` helpers `RelationsOf`, `RelationKeys`, `RelationTarget`,
335
+ * `IncludeOptionsFor`, `IncludeFor` and `RowWith`.
336
+ *
337
+ * Deterministic: tables are emitted in slug order whatever order they arrive
338
+ * in, so `rebase doctor` can regenerate in memory and diff against the file.
339
+ *
340
+ * @throws {CodegenError} when two slugs produce one accessor, or a slug has
341
+ * nothing an accessor can be built from.
342
+ *
343
+ * @group SDK generation
344
+ */
345
+ function generateTypedefs(input) {
346
+ const tables = sortCollectionsBySlug(input);
347
+ const run = {
348
+ accessors: buildAccessors(tables),
349
+ bySlug: new Map(tables.map((table) => [table.slug, table]))
350
+ };
351
+ const lines = [
352
+ "/**",
353
+ " * This file was auto-generated by Rebase.",
354
+ " * Do not make direct changes to the file.",
355
+ " */",
356
+ "",
357
+ "export interface Database {"
358
+ ];
359
+ for (const table of tables) {
360
+ const plan = planTable(table, run);
361
+ lines.push(` ${emitKey(run.accessors.get(table.slug))}: {`);
362
+ emitRow(lines, plan, run);
363
+ if (table.kind === "view") {
364
+ lines.push(" Insert: never;");
365
+ lines.push(" Update: never;");
366
+ } else {
367
+ emitInsert(lines, plan, run);
368
+ emitUpdate(lines, plan, run);
369
+ }
370
+ emitRelations(lines, plan, run);
371
+ lines.push(` Slug: ${emitString(table.slug)};`);
372
+ lines.push(" };");
373
+ }
374
+ lines.push("}");
375
+ lines.push("");
376
+ lines.push("export type TableName = keyof Database;");
377
+ lines.push("");
378
+ lines.push("export const tablesDictionary = {");
379
+ for (const table of tables) lines.push(` ${emitKey(run.accessors.get(table.slug))}: ${emitString(table.slug)},`);
380
+ lines.push("} as const;");
381
+ lines.push("");
382
+ lines.push("export type TablesDictionary = typeof tablesDictionary;");
383
+ lines.push("");
384
+ lines.push(...includeHelperLines());
385
+ return lines.join("\n");
386
+ }
387
+ /**
388
+ * `Row` — what a read serves.
389
+ *
390
+ * ## A `belongsTo` has three shapes, and all three are typed
391
+ *
392
+ * 1. **Write** — `Insert`/`Update` accept *either* the foreign key under its
393
+ * own wire name (`{ authorId: 5 }`) or the relation's name
394
+ * (`{ author: 5 }`). Emitted by `emitWritableRelations`.
395
+ * 2. **Read** — a row carries `authorId`. Always: it is a column.
396
+ * 3. **Read with `include`** — the target's own row arrives under `author`.
397
+ * Optional, because it is absent from every read that did not name it; the
398
+ * generated `RowWith` makes it required for a read that did.
399
+ *
400
+ * `fields` narrows which columns a read returns, but a column is optional here
401
+ * only because the value may be null, never because the caller might not have
402
+ * asked for it: a projection is a choice made at one call site.
403
+ */
404
+ function emitRow(lines, plan, run) {
405
+ lines.push(" Row: {");
406
+ const emitted = new Set(plan.excluded);
407
+ for (const column of plan.columns) {
408
+ if (emitted.has(column.key)) continue;
409
+ const type = columnType(column);
410
+ lines.push(line(column.key, column.nullable ? `${type} | null` : type, column.nullable));
411
+ emitted.add(column.key);
412
+ }
413
+ for (const { relation, column } of plan.links) {
414
+ if (!column || emitted.has(column.key)) continue;
415
+ const type = targetKeyType(relation, run, plan);
416
+ lines.push(line(column.key, column.nullable ? `${type} | null` : type, column.nullable));
417
+ emitted.add(column.key);
418
+ }
419
+ for (const relation of plan.table.relations) {
420
+ if (emitted.has(relation.name)) continue;
421
+ lines.push(line(relation.name, includedRelationType(relation, run), true));
422
+ emitted.add(relation.name);
423
+ }
424
+ lines.push(" };");
425
+ }
426
+ /**
427
+ * `Insert` — what `create()` accepts: no hidden column and nothing nobody may
428
+ * write; a column the database or the server fills may be left out.
429
+ */
430
+ function emitInsert(lines, plan, run) {
431
+ lines.push(" Insert: {");
432
+ const emitted = new Set(plan.unwritable);
433
+ for (const column of plan.columns) {
434
+ if (emitted.has(column.key)) continue;
435
+ lines.push(line(column.key, writableType(column, columnType(column)), insertOptional(column)));
436
+ emitted.add(column.key);
437
+ }
438
+ const eitherSpelling = emitWritableRelations(lines, plan, run, emitted, false);
439
+ lines.push(eitherSpelling.length === 0 ? " };" : ` } & ${eitherSpelling.join(" & ")};`);
440
+ }
441
+ /**
442
+ * `Update` — everything optional, and the primary key left out: an update
443
+ * addresses a row by its key, it does not reassign one.
444
+ */
445
+ function emitUpdate(lines, plan, run) {
446
+ lines.push(" Update: {");
447
+ const emitted = new Set(plan.unwritable);
448
+ for (const column of plan.columns) {
449
+ if (column.primaryKey || emitted.has(column.key)) continue;
450
+ lines.push(line(column.key, writableType(column, columnType(column)), true));
451
+ emitted.add(column.key);
452
+ }
453
+ emitWritableRelations(lines, plan, run, emitted, true);
454
+ lines.push(" };");
455
+ }
456
+ /**
457
+ * `Relations` — which relations the table has, and which table each one
458
+ * reaches. Not a shape a read returns: it is the *graph*, and `include` is the
459
+ * one parameter that needs it. `IncludeFor` walks it to constrain an include's
460
+ * keys at every level, and `RowWith` reads it to make an included relation
461
+ * non-optional on the row that comes back.
462
+ *
463
+ * Emitted as the accessor NAME rather than the target's `Row`, so a
464
+ * self-referencing relation is a finite string instead of a type that expands
465
+ * forever. A table with no relations gets `Record<never, never>`, not `{}`,
466
+ * which typescript-eslint's `no-empty-object-type` refuses in every project
467
+ * that lints its generated SDK. A hidden relation is left out: the server
468
+ * answers an include naming one as it answers a typo.
469
+ */
470
+ function emitRelations(lines, plan, run) {
471
+ const includable = plan.table.relations.filter((relation) => !plan.excluded.has(relation.name));
472
+ if (includable.length === 0) {
473
+ lines.push(" Relations: Record<never, never>;");
474
+ return;
475
+ }
476
+ lines.push(" Relations: {");
477
+ for (const relation of includable) {
478
+ const accessor = run.accessors.get(relation.target);
479
+ lines.push(` ${emitKey(relation.name)}: ${accessor ? emitString(accessor) : "never"};`);
480
+ }
481
+ lines.push(" };");
482
+ }
483
+ /**
484
+ * The `include` type machinery, emitted into the generated file.
485
+ *
486
+ * It lives here rather than in `@rebasepro/types` because it is the *graph*
487
+ * that makes it work, and the graph only exists once a project's tables have
488
+ * been generated. `IncludeSpec` in `@rebasepro/types` is deliberately
489
+ * unconstrained; these narrow it for a project that has relations.
490
+ *
491
+ * - `IncludeFor<"posts">` — an include whose keys are relations that exist,
492
+ * recursively, so a typo is a compile error rather than a 400 at runtime.
493
+ * - `RowWith<"posts", I>` — the row a read with that include returns, where
494
+ * every included relation is **present** rather than optional.
495
+ *
496
+ * The depth bound matches the server's (`MAX_INCLUDE_DEPTH`), and is spelled as
497
+ * a decrementing tuple because TypeScript has no arithmetic — `Prev[3]` is `2`.
498
+ */
499
+ function includeHelperLines() {
500
+ return [
501
+ "/** Which table each of `A`'s relations reaches. */",
502
+ "export type RelationsOf<A extends TableName> =",
503
+ " Database[A] extends { Relations: infer R } ? R : Record<string, never>;",
504
+ "",
505
+ "/** The names of `A`'s relations. */",
506
+ "export type RelationKeys<A extends TableName> = keyof RelationsOf<A> & string;",
507
+ "",
508
+ "/** The table a relation reaches, or `never` when it left this project. */",
509
+ "export type RelationTarget<A extends TableName, K extends RelationKeys<A>> =",
510
+ " RelationsOf<A>[K] extends TableName ? RelationsOf<A>[K] : never;",
511
+ "",
512
+ "/** Counts `IncludeFor` down; TypeScript has no arithmetic. */",
513
+ "type Prev = [never, 0, 1, 2, 3];",
514
+ "",
515
+ "/**",
516
+ " * Per-relation options, minus `include` — which `IncludeFor` supplies at",
517
+ " * the next depth so the nested keys are checked against the *target's*",
518
+ " * relations rather than this table's.",
519
+ " */",
520
+ "export interface IncludeOptionsFor<A extends TableName, K extends RelationKeys<A>, D extends number> {",
521
+ " limit?: number;",
522
+ " where?: Record<string, unknown>;",
523
+ " logical?: unknown;",
524
+ " orderBy?: unknown;",
525
+ " fields?: string[];",
526
+ " include?: RelationTarget<A, K> extends TableName",
527
+ " ? IncludeFor<RelationTarget<A, K>, Prev[D]>",
528
+ " : never;",
529
+ "}",
530
+ "",
531
+ "/**",
532
+ " * An `include` for table `A`: its relation names, dotted paths, or the",
533
+ " * parametrised tree — with every key checked against the relations that",
534
+ " * actually exist, at every level.",
535
+ " */",
536
+ "export type IncludeFor<A extends TableName, D extends number = 3> =",
537
+ " D extends 0",
538
+ " ? never",
539
+ " : | readonly (RelationKeys<A> | \"*\")[]",
540
+ " | { [K in RelationKeys<A>]?: true | IncludeOptionsFor<A, K, D> };",
541
+ "",
542
+ "/** The relation names an include asks for at the top level. */",
543
+ "type IncludedKeys<A extends TableName, I> =",
544
+ " I extends readonly (infer K)[]",
545
+ " ? Extract<K, RelationKeys<A>>",
546
+ " : Extract<keyof I, RelationKeys<A>>;",
547
+ "",
548
+ "/**",
549
+ " * The row a read with include `I` returns: `Row`, with every included",
550
+ " * relation made **required**.",
551
+ " *",
552
+ " * `Row` types a relation as optional because it is absent from every read",
553
+ " * that did not name it. Once a read has named it, it is there — and having",
554
+ " * to write `row.author?.name` after asking for the author is the type",
555
+ " * describing a possibility the query already ruled out.",
556
+ " */",
557
+ "export type RowWith<A extends TableName, I> =",
558
+ " Database[A][\"Row\"] & Required<Pick<Database[A][\"Row\"], IncludedKeys<A, I> & keyof Database[A][\"Row\"]>>;",
559
+ ""
560
+ ];
561
+ }
562
+ /**
563
+ * Every relation write the server performs, typed.
564
+ *
565
+ * - A `belongsTo` is written under either of two names: its foreign key's wire
566
+ * key (`{ authorId: 5 }`) and the relation's name (`{ author: 5 }`), which
567
+ * the server maps onto the column — the second only over a constraint
568
+ * (`rel.belongsTo(…, { constraint: false })` keeps a bare column, written by
569
+ * its key alone). A **required** `belongsTo` is satisfied by either: on an
570
+ * `Insert` both names go in optional, and the requirement comes back as one
571
+ * returned `({ authorId: T } | { author: T })` for the caller to intersect
572
+ * with the object. Both stay in the object so `keyof Insert` names them.
573
+ * - A `hasOne`, and a single-hop to-one `via`, is written by naming the target
574
+ * row; `null` unlinks it.
575
+ * - A to-many membership (`hasMany`, `manyToMany`, a single-hop to-many `via`)
576
+ * is written as the targets' keys, or `{ id }`, or `{ id, _pivot }` where the
577
+ * junction declares payload columns. A multi-hop `via` is read-only.
578
+ *
579
+ * The target's key type is the one `Row` uses for the link.
580
+ */
581
+ function emitWritableRelations(lines, plan, run, emittedKeys, allOptional) {
582
+ const spellings = /* @__PURE__ */ new Map();
583
+ const addSpelling = (relation, key) => {
584
+ if (emittedKeys.has(key)) return;
585
+ const keys = spellings.get(relation) ?? [];
586
+ if (!keys.includes(key)) keys.push(key);
587
+ spellings.set(relation, keys);
588
+ };
589
+ for (const { relation } of plan.links) addSpelling(relation, relation.localField);
590
+ for (const { relation } of plan.links) if (relation.constraint) addSpelling(relation, relation.name);
591
+ const eitherSpelling = [];
592
+ const emit = (key, relation) => {
593
+ if (emittedKeys.has(key)) return;
594
+ const required = plan.byKey.get(relation.localField)?.nullable === false;
595
+ const type = required ? targetKeyType(relation, run, plan) : `${targetKeyType(relation, run, plan)} | null`;
596
+ const names = spellings.get(relation) ?? [key];
597
+ const oneOfSeveral = required && !allOptional && names.length > 1;
598
+ lines.push(line(key, type, allOptional || !required || oneOfSeveral));
599
+ emittedKeys.add(key);
600
+ if (oneOfSeveral && names[0] === key) eitherSpelling.push(`(${names.map((name) => `{ ${emitKey(name)}: ${type} }`).join(" | ")})`);
601
+ };
602
+ for (const { relation } of plan.links) emit(relation.localField, relation);
603
+ for (const { relation } of plan.links) if (relation.constraint) emit(relation.name, relation);
604
+ for (const relation of plan.table.relations) {
605
+ if (emittedKeys.has(relation.name)) continue;
606
+ if (!(relation.kind === "hasOne" || relation.kind === "via" && relation.cardinality === "one" && relation.writable)) continue;
607
+ lines.push(line(relation.name, `${targetKeyType(relation, run, plan)} | null`, true));
608
+ emittedKeys.add(relation.name);
609
+ }
610
+ for (const relation of plan.table.relations) {
611
+ if (relation.cardinality !== "many" || emittedKeys.has(relation.name)) continue;
612
+ if (relation.kind === "via" && !relation.writable) continue;
613
+ const fk = targetKeyType(relation, run, plan);
614
+ const pivot = relation.kind === "manyToMany" ? pivotType(relation.through.pivot, "write") : void 0;
615
+ const element = `${fk} | { id: ${fk}${pivot ? `; _pivot?: ${pivot}` : ""} }`;
616
+ lines.push(line(relation.name, `Array<${element}>`, true));
617
+ emittedKeys.add(relation.name);
618
+ }
619
+ return eitherSpelling;
620
+ }
621
+ /**
622
+ * The `_pivot` a many-to-many link carries: the junction's payload columns,
623
+ * typed as a row's columns are on a read and as a write's on a write.
624
+ * `undefined` when the junction declares none, so there is no `_pivot` to name.
625
+ */
626
+ function pivotType(pivot, direction) {
627
+ if (pivot.length === 0) return void 0;
628
+ return `{ ${pivot.map((column) => {
629
+ const tsType = columnType(column);
630
+ const required = !column.nullable;
631
+ const type = direction === "write" ? writableType(column, tsType) : required ? tsType : `${tsType} | null`;
632
+ return `${emitKey(column.key)}${required && direction === "read" ? "" : "?"}: ${type};`;
633
+ }).join(" ")} }`;
634
+ }
635
+ //#endregion
636
+ //#region src/schema/doctor.ts
637
+ /**
638
+ * Rebase Schema Doctor — Three-way schema drift detection.
639
+ *
640
+ * Compares:
641
+ * 1. Collection definitions → Generated Drizzle schema (staleness check)
642
+ * 2. Collection definitions → Live PostgreSQL database (structural drift)
643
+ *
644
+ * Run via: rebase doctor
645
+ */
646
+ /**
647
+ * How `information_schema.columns.data_type` spells a planned column type.
648
+ *
649
+ * The catalogue's names are its own — `character varying`, not `varchar`;
650
+ * `ARRAY` for every array whatever its element; `USER-DEFINED` for an enum, a
651
+ * `vector`, and anything else identified by name rather than by shape. So the
652
+ * translation has to exist somewhere. What must *not* exist twice is the step
653
+ * before it: which column a property compiles to.
654
+ *
655
+ * This function was that second step — a fourth copy of the property switch,
656
+ * kept "in sync" with the generators by a comment, and already out of step
657
+ * (`geopoint` answered `null` here, so the one type that was genuinely
658
+ * unpersistable was the one the doctor never checked). It reads the schema plan
659
+ * now.
660
+ */
661
+ var INFORMATION_SCHEMA_NAMES = {
662
+ text: "text",
663
+ varchar: "character varying",
664
+ char: "character",
665
+ uuid: "uuid",
666
+ enum: "USER-DEFINED",
667
+ smallint: "smallint",
668
+ integer: "integer",
669
+ bigint: "bigint",
670
+ smallserial: "smallint",
671
+ serial: "integer",
672
+ bigserial: "bigint",
673
+ real: "real",
674
+ doublePrecision: "double precision",
675
+ numeric: "numeric",
676
+ boolean: "boolean",
677
+ timestamptz: "timestamp with time zone",
678
+ date: "date",
679
+ time: "time without time zone",
680
+ json: "json",
681
+ jsonb: "jsonb",
682
+ vector: "USER-DEFINED",
683
+ bytea: "bytea",
684
+ tsvector: "USER-DEFINED",
685
+ array: "ARRAY"
686
+ };
687
+ /**
688
+ * {@link INFORMATION_SCHEMA_NAMES} for any planned type, or `null` for a
689
+ * `col.custom()` type: its `data_type` is whatever the catalogue calls that
690
+ * type (`inet`, `int4range`, `USER-DEFINED` for PostGIS), so the boot diff
691
+ * compares it against `format_type` instead, and the doctor has nothing to add.
692
+ */
693
+ var informationSchemaName = (type) => type.kind === "custom" ? null : INFORMATION_SCHEMA_NAMES[type.kind];
694
+ /**
695
+ * The planned Postgres type of a column of `table`, through the planner's own
696
+ * `pgTypeOf` — or `undefined` for a type the planner refuses (an array of
697
+ * documents, an enum with no labels), which is a problem the doctor's other
698
+ * phases report with a message, not a type mismatch to invent one for.
699
+ */
700
+ function plannedColumnType(table, column) {
701
+ try {
702
+ return pgTypeOf(column.type, {
703
+ schema: table.schema,
704
+ table: table.table,
705
+ owner: table.slug,
706
+ propName: column.key,
707
+ column: column.column
708
+ });
709
+ } catch {
710
+ return;
711
+ }
712
+ }
713
+ /**
714
+ * `information_schema.columns.udt_name` of a native array of this element
715
+ * type — the array's `data_type` is `ARRAY` whatever it holds, so the element
716
+ * is told apart here. `undefined` for an element this does not name.
717
+ */
718
+ var ARRAY_UDT_NAMES = {
719
+ text: "_text",
720
+ varchar: "_varchar",
721
+ char: "_bpchar",
722
+ uuid: "_uuid",
723
+ smallint: "_int2",
724
+ integer: "_int4",
725
+ bigint: "_int8",
726
+ real: "_float4",
727
+ doublePrecision: "_float8",
728
+ numeric: "_numeric",
729
+ boolean: "_bool",
730
+ timestamptz: "_timestamptz",
731
+ date: "_date",
732
+ time: "_time"
733
+ };
734
+ async function checkTablesVsSchema(tables, schemaFilePath) {
735
+ const issues = [];
736
+ if (!fs$1.existsSync(schemaFilePath)) {
737
+ issues.push({
738
+ severity: "error",
739
+ category: "schema_stale",
740
+ message: "Generated schema file does not exist.",
741
+ fix: "Run `rebase schema generate`"
742
+ });
743
+ return {
744
+ passed: false,
745
+ issues
746
+ };
747
+ }
748
+ if (tables.length === 0) return {
749
+ passed: true,
750
+ issues
751
+ };
752
+ try {
753
+ const differences = compareGeneratedDeclarations(generateSchema(tables), await promises.readFile(schemaFilePath, "utf-8"));
754
+ if (differences.length > 0) issues.push({
755
+ severity: "warning",
756
+ category: "schema_stale",
757
+ message: `Generated schema is out of date — table definitions have changed since last generation. Differs in: ${describeDeclarationDifferences(differences)}.`,
758
+ fix: "Run `rebase schema generate`"
759
+ });
760
+ } catch (err) {
761
+ const message = err instanceof Error ? err.message : String(err);
762
+ issues.push({
763
+ severity: "warning",
764
+ category: "schema_stale",
765
+ message: `Could not regenerate schema for comparison: ${message}`,
766
+ fix: "Run `rebase schema generate` to verify"
767
+ });
768
+ }
769
+ return {
770
+ passed: issues.length === 0,
771
+ issues
772
+ };
773
+ }
774
+ async function checkTablesVsSdk(descriptors, sdkFilePath) {
775
+ const issues = [];
776
+ if (!fs$1.existsSync(sdkFilePath)) {
777
+ issues.push({
778
+ severity: "info",
779
+ category: "sdk_not_generated",
780
+ message: "Typed SDK not generated (optional).",
781
+ fix: "Run `rebase generate-sdk` if you want typed table access"
782
+ });
783
+ return {
784
+ passed: true,
785
+ issues,
786
+ notApplicable: "not generated (optional)"
787
+ };
788
+ }
789
+ try {
790
+ const expectedSdk = generateTypedefs(descriptors);
791
+ const actualSdk = await promises.readFile(sdkFilePath, "utf-8");
792
+ const normalize = (s) => s.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "").replace(/\s+/g, " ").trim();
793
+ if (normalize(expectedSdk) !== normalize(actualSdk)) issues.push({
794
+ severity: "warning",
795
+ category: "sdk_stale",
796
+ message: "Generated SDK types are out of date — table definitions have changed since last SDK generation.",
797
+ fix: "Run `rebase generate-sdk`"
798
+ });
799
+ } catch (err) {
800
+ const message = err instanceof Error ? err.message : String(err);
801
+ if (err instanceof Error && err.name === "CodegenError") issues.push({
802
+ severity: "error",
803
+ category: "sdk_ungeneratable",
804
+ message: `The typed SDK cannot be generated from these tables: ${message}`,
805
+ fix: "Fix the table definitions named above, then run `rebase generate-sdk`"
806
+ });
807
+ else issues.push({
808
+ severity: "warning",
809
+ category: "sdk_stale",
810
+ message: `Could not regenerate SDK types for comparison: ${message}`,
811
+ fix: "Run `rebase generate-sdk` to verify"
812
+ });
813
+ }
814
+ return {
815
+ passed: issues.length === 0,
816
+ issues
817
+ };
818
+ }
819
+ /**
820
+ * Extensions the tables need, that the database does not have installed.
821
+ *
822
+ * Only `vector` today, and only because a `col.vector()` column plans a
823
+ * column of a type that will not exist. Rebase installs it only where a project
824
+ * has said it may (`database({ extensions: ["vector"] })`), so the absence is
825
+ * often correct configuration and a wrong deployment — which is exactly why the
826
+ * report has to name it rather than the first failing INSERT.
827
+ *
828
+ * Exported for its test.
829
+ */
830
+ function missingExtensionIssues(tables, installed) {
831
+ if (!tables.some((table) => table.columns.some((column) => column.type.kind === "vector")) || installed.has("vector")) return [];
832
+ return [{
833
+ severity: "error",
834
+ category: "missing_table",
835
+ message: "A table declares a vector column (`col.vector(...)`) and the pgvector extension is not installed on this database.",
836
+ fix: "Declare it — `database({ extensions: [\"vector\"] })` in config/resources.ts — and use an image that ships the library (the scaffold's pgvector/pgvector:pg18; a stock postgres:18 does not). Or install it once by hand: CREATE EXTENSION vector;"
837
+ }];
838
+ }
839
+ /**
840
+ * The stamp the runtime wrote, against the tables on disk (their compiled
841
+ * descriptors, which is what the stamp is computed over).
842
+ *
843
+ * A stamp that disagrees means this database was provisioned from a different
844
+ * set of tables than the ones in this checkout — a colleague's branch, an
845
+ * older deploy, a tenant somebody else migrated. Everything else in this report
846
+ * is then describing a schema somebody else created, which is worth knowing
847
+ * before acting on any of it.
848
+ *
849
+ * A warning, not an error, and never a direction: the stamp is a hash, so it
850
+ * can say the two disagree and never which is ahead. `null` — never stamped —
851
+ * is not a finding: every database provisioned before the stamp existed reads
852
+ * that way, and so does every fresh one.
853
+ */
854
+ async function schemaStampIssues(pool, expected) {
855
+ let stamped = null;
856
+ try {
857
+ if (!(await pool.query(`SELECT to_regclass('"rebase"."schema_meta"') IS NOT NULL AS present`)).rows[0]?.present) return [];
858
+ stamped = (await pool.query(`SELECT value FROM "rebase"."schema_meta" WHERE key = 'collections_schema_version' LIMIT 1`)).rows[0]?.value ?? null;
859
+ } catch {
860
+ return [];
861
+ }
862
+ if (!stamped) return [];
863
+ if (stamped === expected) return [];
864
+ if (stamped.startsWith(LEGACY_SCHEMA_VERSION_PREFIX)) return [{
865
+ severity: "warning",
866
+ category: "schema_stale",
867
+ message: describeMismatch(stamped, expected),
868
+ fix: "Run `rebase db push` (or boot the process that owns the schema) once to restamp it."
869
+ }];
870
+ return [{
871
+ severity: "warning",
872
+ category: "schema_stale",
873
+ message: `This database was provisioned from a different set of tables (stamp ${stamped}, this checkout computes ${expected}).`,
874
+ fix: "A hash says the two disagree, never which is ahead. Check you are pointed at the database you think you are; then `rebase db push` to bring it to these tables."
875
+ }];
876
+ }
877
+ /** `"public"."posts"` — quoted, for a statement the reader will paste. */
878
+ var quotedTable = (schema, table) => `"${schema}"."${table}"`;
879
+ /**
880
+ * What to do about a column whose type is not the one the collection plans.
881
+ *
882
+ * Both ways out, because the doctor cannot know which side is right: the
883
+ * property moved, or the database did. Putting the property back always clears
884
+ * the finding; converting the column clears it when every value converts.
885
+ */
886
+ function typeMismatchFix(schema, table, column, actual, planned) {
887
+ const back = `Either put the property back to the column's type (${actual}), or`;
888
+ if (!planned) return `${back} run a migration that converts the column.`;
889
+ const type = renderPgType(planned);
890
+ return `${back} convert the column when you can watch it (every value must convert): ALTER TABLE ${quotedTable(schema, table)} ALTER COLUMN "${column}" TYPE ${type} USING "${column}"::${type};`;
891
+ }
892
+ /**
893
+ * The table's primary key against the one the collection reads it by.
894
+ *
895
+ * Rebase addresses a row by the key the plan names — the `isId` property, or
896
+ * the implicit `id` — so a table keyed on other columns, or on none, serves
897
+ * reads and writes against a key that does not hold. An error, because that is
898
+ * what it is at runtime.
899
+ */
900
+ function primaryKeyIssues(tablePlan, dbPk, displayName) {
901
+ const expected = tablePlan.primaryKey;
902
+ if (dbPk.length === expected.length && [...dbPk].sort().join("\0") === [...expected].sort().join("\0")) return [];
903
+ const table = quotedTable(tablePlan.schema, tablePlan.table);
904
+ const keyList = expected.map((c) => `"${c}"`).join(", ");
905
+ if (dbPk.length === 0) return [{
906
+ severity: "error",
907
+ category: "primary_key_mismatch",
908
+ table: displayName,
909
+ expected: expected.join(", "),
910
+ actual: "(none)",
911
+ message: `Table "${displayName}" has no primary key; the table definition reads its rows by ${keyList}.`,
912
+ fix: `ALTER TABLE ${table} ADD PRIMARY KEY (${keyList});`
913
+ }];
914
+ const only = expected.some((column) => !dbPk.includes(column)) ? "only " : "";
915
+ const fix = dbPk.length === 1 ? `Mark ${only}the property for column "${dbPk[0]}" with \`isId\` — the table is keyed on it — or re-key the table on ${keyList}.` : `Mark ${only}the properties for columns ${dbPk.map((c) => `"${c}"`).join(", ")} with \`isId\` — together they are the table's composite key — or re-key the table on ${keyList}.`;
916
+ return [{
917
+ severity: "error",
918
+ category: "primary_key_mismatch",
919
+ table: displayName,
920
+ expected: expected.join(", "),
921
+ actual: dbPk.join(", "),
922
+ message: `Table "${displayName}" is keyed on (${dbPk.join(", ")}), but the table definition reads its rows by ${keyList}.`,
923
+ fix
924
+ }];
925
+ }
926
+ /**
927
+ * A junction's two key columns: present, typed like the keys they point at,
928
+ * and the table keyed on the pair. Order is not compared — boot and `db push`
929
+ * have built the key in both orders, and either one serves the same rows.
930
+ */
931
+ function junctionKeyIssues(junctionPlan, dbColumns, dbPk, displayName) {
932
+ const issues = [];
933
+ const byName = new Map(dbColumns.map((c) => [c.column_name, c]));
934
+ for (const column of junctionPlan.columns) {
935
+ const dbCol = byName.get(column.column);
936
+ if (!dbCol) {
937
+ issues.push({
938
+ severity: "error",
939
+ category: "missing_column",
940
+ table: displayName,
941
+ column: column.column,
942
+ message: `Junction table "${displayName}" has no "${column.column}" column.`,
943
+ fix: "Run `rebase db push` or `rebase db generate && rebase db migrate`"
944
+ });
945
+ continue;
946
+ }
947
+ const expected = informationSchemaName(column.type);
948
+ if (expected !== null && dbCol.data_type !== expected) issues.push({
949
+ severity: "warning",
950
+ category: "type_mismatch",
951
+ table: displayName,
952
+ column: column.column,
953
+ expected,
954
+ actual: dbCol.data_type,
955
+ message: `Junction column "${column.column}" in "${displayName}" is ${dbCol.data_type}, but the key it points at is ${expected}.`,
956
+ fix: typeMismatchFix(junctionPlan.schema, junctionPlan.table, column.column, dbCol.data_type, column.type)
957
+ });
958
+ }
959
+ issues.push(...primaryKeyIssues(junctionPlan, dbPk, displayName));
960
+ return issues;
961
+ }
962
+ /** A table as the other issues name it: bare in `public`, `schema.table` elsewhere. */
963
+ function displayTableOf(difference, tables) {
964
+ const schema = difference.slug ? tables.find((t) => t.slug === difference.slug)?.schema : void 0;
965
+ return schema && schema !== "public" ? `${schema}.${difference.table}` : difference.table;
966
+ }
967
+ /** Which of the doctor's own categories already says what a boot difference says. */
968
+ var COVERING_CATEGORY = {
969
+ "missing-table": "missing_table",
970
+ "missing-column": "missing_column",
971
+ type: "type_mismatch",
972
+ nullability: "nullability_mismatch",
973
+ "extra-column": "extra_column"
974
+ };
975
+ /** What to do about one boot difference, said the way the boot warning says it. */
976
+ function generatedDriftFix(difference) {
977
+ switch (difference.kind) {
978
+ case "nullability": return difference.generated === "NOT NULL" ? "`rebase db push` applies it; a NOT NULL needs every row filled first (UPDATE the empty ones, or give the property a default). Boot adds one only with a new column on an empty table. If backend/schema changed since schema.generated.ts was written, run `rebase schema generate` first." : "`rebase db push` drops the NOT NULL, which boot never does. If the column should stay required, mark the property `validation: { required: true }`. If backend/schema changed since schema.generated.ts was written, run `rebase schema generate` first.";
979
+ case "extra-column": return "Boot never drops a column, so its data is still there. `rebase db push` removes it (it asks first, since that deletes the data), or a migration does (`rebase db generate`). If a property should still read it, declare it again. If backend/schema changed since schema.generated.ts was written, run `rebase schema generate` first.";
980
+ case "type": return "`rebase db push` converts it (it asks first when values may not convert), or a migration does. If backend/schema changed since schema.generated.ts was written, run `rebase schema generate` first.";
981
+ case "missing-column": return "`rebase db push` adds it. If backend/schema changed since schema.generated.ts was written, run `rebase schema generate` first.";
982
+ case "missing-table": return "Run `rebase db push` or `rebase db generate && rebase db migrate`";
983
+ }
984
+ }
985
+ /**
986
+ * Boot's drift warnings, as doctor issues — one per difference, in boot's own
987
+ * words ({@link describeSchemaDifference}), and a warning, as boot raises them.
988
+ *
989
+ * Except where an issue the collections-side checks above already raised says
990
+ * the same thing: a missing table, a missing column or a type mismatch on the
991
+ * same column. Nullability and columns no collection declares are boot's alone;
992
+ * the doctor never compared them, which is how it came to say "In sync" beside
993
+ * a boot that had just warned about both.
994
+ */
995
+ function generatedSchemaDriftIssues(differences, already, tables) {
996
+ const bare = (table) => table?.split(".").pop();
997
+ const covered = (difference) => already.some((issue) => issue.category === COVERING_CATEGORY[difference.kind] && bare(issue.table) === difference.table && (difference.kind === "missing-table" || issue.column === difference.column));
998
+ return differences.filter((difference) => !covered(difference)).map((difference) => ({
999
+ severity: "warning",
1000
+ category: COVERING_CATEGORY[difference.kind],
1001
+ table: displayTableOf(difference, tables),
1002
+ ...difference.column ? { column: difference.column } : {},
1003
+ ...difference.generated ? { expected: difference.generated } : {},
1004
+ ...difference.live ? { actual: difference.live } : {},
1005
+ message: describeSchemaDifference(difference),
1006
+ fix: generatedDriftFix(difference)
1007
+ }));
1008
+ }
1009
+ /**
1010
+ * The tables the default database holds — the filter boot applies before it
1011
+ * reads the catalogue, for the same reason: a table routed to
1012
+ * `database("analytics")` has no table here.
1013
+ */
1014
+ function defaultDatabaseTables(tables) {
1015
+ return tables.filter((t) => !t.descriptor.database || t.descriptor.database === DEFAULT_DATA_SOURCE_KEY);
1016
+ }
1017
+ async function checkTablesVsDatabase(tables, databaseUrl, options = {}) {
1018
+ const issues = [];
1019
+ const descriptors = tables.map((table) => table.descriptor);
1020
+ const bySlug = new Map(descriptors.map((descriptor) => [descriptor.slug, descriptor]));
1021
+ const pgModule = await import("pg");
1022
+ const { Pool } = pgModule.default ?? pgModule;
1023
+ const pool = new Pool({ connectionString: databaseUrl });
1024
+ const schemas = Array.from(/* @__PURE__ */ new Set([
1025
+ "public",
1026
+ "rebase",
1027
+ ...descriptors.map((d) => d.schema)
1028
+ ]));
1029
+ try {
1030
+ const tablesResult = await pool.query(`SELECT table_schema, table_name
1031
+ FROM information_schema.tables
1032
+ WHERE table_schema = ANY($1) AND table_type = 'BASE TABLE'`, [schemas]);
1033
+ const existingTables = new Set(tablesResult.rows.map((r) => r.table_schema === "public" ? r.table_name : `${r.table_schema}.${r.table_name}`));
1034
+ const viewsResult = await pool.query(`SELECT n.nspname AS table_schema, c.relname AS table_name
1035
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
1036
+ WHERE n.nspname = ANY($1) AND c.relkind IN ('v', 'm')`, [schemas]);
1037
+ const existingViews = new Set(viewsResult.rows.map((r) => r.table_schema === "public" ? r.table_name : `${r.table_schema}.${r.table_name}`));
1038
+ const extensionsResult = await pool.query("SELECT extname FROM pg_extension");
1039
+ const installedExtensions = new Set(extensionsResult.rows.map((r) => r.extname));
1040
+ issues.push(...missingExtensionIssues(descriptors, installedExtensions));
1041
+ if (options.schemaVersion !== void 0) issues.push(...await schemaStampIssues(pool, options.schemaVersion));
1042
+ const columnsResult = await pool.query(`SELECT table_schema, table_name, column_name, data_type, is_nullable, udt_name
1043
+ FROM information_schema.columns
1044
+ WHERE table_schema = ANY($1)
1045
+ ORDER BY table_schema, table_name, ordinal_position`, [schemas]);
1046
+ const columnsByTable = /* @__PURE__ */ new Map();
1047
+ for (const row of columnsResult.rows) {
1048
+ const tableSchema = row.table_schema;
1049
+ const tableName = row.table_name;
1050
+ const key = tableSchema === "public" ? tableName : `${tableSchema}.${tableName}`;
1051
+ if (!columnsByTable.has(key)) columnsByTable.set(key, []);
1052
+ columnsByTable.get(key).push(row);
1053
+ }
1054
+ const enumsResult = await pool.query(`SELECT n.nspname AS enum_schema, t.typname AS enum_name, e.enumlabel AS enum_value
1055
+ FROM pg_type t
1056
+ JOIN pg_namespace n ON n.oid = t.typnamespace
1057
+ JOIN pg_enum e ON t.oid = e.enumtypid
1058
+ ORDER BY n.nspname, t.typname, e.enumsortorder`);
1059
+ const enumsByName = /* @__PURE__ */ new Map();
1060
+ for (const row of enumsResult.rows) {
1061
+ const key = `${row.enum_schema}.${row.enum_name}`;
1062
+ if (!enumsByName.has(key)) enumsByName.set(key, []);
1063
+ enumsByName.get(key).push(row.enum_value);
1064
+ }
1065
+ const pksResult = await pool.query(`SELECT n.nspname AS table_schema, c.relname AS table_name,
1066
+ array_agg(a.attname::text ORDER BY array_position(i.indkey::int2[], a.attnum)) AS columns
1067
+ FROM pg_index i
1068
+ JOIN pg_class c ON c.oid = i.indrelid
1069
+ JOIN pg_namespace n ON n.oid = c.relnamespace
1070
+ JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY(i.indkey::int2[])
1071
+ WHERE i.indisprimary AND n.nspname = ANY($1)
1072
+ GROUP BY n.nspname, c.relname`, [schemas]);
1073
+ const pksByTable = /* @__PURE__ */ new Map();
1074
+ for (const row of pksResult.rows) pksByTable.set(row.table_schema === "public" ? row.table_name : `${row.table_schema}.${row.table_name}`, row.columns);
1075
+ const fksResult = await pool.query(`SELECT
1076
+ tc.constraint_name,
1077
+ tc.table_schema,
1078
+ tc.table_name,
1079
+ kcu.column_name,
1080
+ ccu.table_schema AS foreign_table_schema,
1081
+ ccu.table_name AS foreign_table_name,
1082
+ ccu.column_name AS foreign_column_name
1083
+ FROM information_schema.table_constraints AS tc
1084
+ JOIN information_schema.key_column_usage AS kcu
1085
+ ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
1086
+ JOIN information_schema.constraint_column_usage AS ccu
1087
+ ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
1088
+ WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = ANY($1)`, [schemas]);
1089
+ const fksByTable = /* @__PURE__ */ new Map();
1090
+ for (const row of fksResult.rows) {
1091
+ const tableSchema = row.table_schema;
1092
+ const tableName = row.table_name;
1093
+ const key = tableSchema === "public" ? tableName : `${tableSchema}.${tableName}`;
1094
+ if (!fksByTable.has(key)) fksByTable.set(key, []);
1095
+ fksByTable.get(key).push(row);
1096
+ }
1097
+ const junctions = resolveTableJunctions(sortTablesBySlug(tables).map((t) => t.descriptor));
1098
+ let plan;
1099
+ try {
1100
+ plan = planSchema(tables);
1101
+ } catch {
1102
+ plan = void 0;
1103
+ }
1104
+ const tablePlans = new Map((plan?.tables ?? []).map((t) => [t.qualified, t]));
1105
+ const checkedJunctions = /* @__PURE__ */ new Set();
1106
+ for (const descriptor of descriptors) {
1107
+ const tableName = descriptor.table;
1108
+ const schemaName = descriptor.schema;
1109
+ const fullTableName = schemaName === "public" ? tableName : `${schemaName}.${tableName}`;
1110
+ if (descriptor.kind === "view") {
1111
+ if (!existingViews.has(fullTableName)) issues.push({
1112
+ severity: "error",
1113
+ category: "missing_table",
1114
+ table: fullTableName,
1115
+ message: `View "${fullTableName}" does not exist in the database.`,
1116
+ fix: "Run `rebase db push` or `rebase db generate && rebase db migrate`"
1117
+ });
1118
+ continue;
1119
+ }
1120
+ if (!existingTables.has(fullTableName)) {
1121
+ issues.push({
1122
+ severity: "error",
1123
+ category: "missing_table",
1124
+ table: fullTableName,
1125
+ message: `Table "${fullTableName}" does not exist in the database.`,
1126
+ fix: "Run `rebase db push` or `rebase db generate && rebase db migrate`"
1127
+ });
1128
+ continue;
1129
+ }
1130
+ const dbColumns = columnsByTable.get(fullTableName) ?? [];
1131
+ const dbColumnMap = new Map(dbColumns.map((c) => [c.column_name, c]));
1132
+ const tablePlan = tablePlans.get(`${schemaName}.${tableName}`);
1133
+ if (tablePlan) issues.push(...primaryKeyIssues(tablePlan, pksByTable.get(fullTableName) ?? [], fullTableName));
1134
+ for (const relation of relationsOfKind(descriptor, "belongsTo")) {
1135
+ const fkColName = relation.localKey;
1136
+ if (!dbColumnMap.has(fkColName)) {
1137
+ issues.push({
1138
+ severity: "error",
1139
+ category: "missing_column",
1140
+ table: fullTableName,
1141
+ column: fkColName,
1142
+ message: `Foreign key column "${fkColName}" for relation "${relation.name}" is missing from table "${fullTableName}".`,
1143
+ fix: "Run `rebase db push` or `rebase db generate && rebase db migrate`"
1144
+ });
1145
+ continue;
1146
+ }
1147
+ if (!relation.constraint) continue;
1148
+ const target = bySlug.get(relation.target);
1149
+ const targetTableName = target?.table ?? "unknown";
1150
+ const targetSchemaName = target?.schema ?? "public";
1151
+ if (!(fksByTable.get(fullTableName) ?? []).some((fk) => fk.column_name === fkColName && fk.foreign_table_name === targetTableName && fk.foreign_table_schema === targetSchemaName)) issues.push({
1152
+ severity: "warning",
1153
+ category: "missing_foreign_key",
1154
+ table: fullTableName,
1155
+ column: fkColName,
1156
+ message: `Column "${fkColName}" exists but has no FOREIGN KEY constraint referencing "${targetSchemaName === "public" ? targetTableName : `${targetSchemaName}.${targetTableName}`}".`,
1157
+ fix: "Run `rebase db push` or add the constraint manually"
1158
+ });
1159
+ }
1160
+ for (const column of descriptor.columns) {
1161
+ if (column.foreignKeyOf !== void 0) continue;
1162
+ const colName = column.column;
1163
+ const dbCol = dbColumnMap.get(colName);
1164
+ if (!dbCol) {
1165
+ issues.push({
1166
+ severity: "error",
1167
+ category: "missing_column",
1168
+ table: fullTableName,
1169
+ column: colName,
1170
+ message: `Column "${colName}" is defined in table "${descriptor.slug}" (backend/schema) but missing from table "${fullTableName}".`,
1171
+ fix: "Run `rebase db push` or `rebase db generate && rebase db migrate`"
1172
+ });
1173
+ continue;
1174
+ }
1175
+ const planned = plannedColumnType(descriptor, column);
1176
+ if (!planned) continue;
1177
+ const expectedType = informationSchemaName(planned);
1178
+ if (expectedType) {
1179
+ const actualType = dbCol.data_type;
1180
+ let isMismatch = actualType !== expectedType;
1181
+ if (planned.kind === "vector" && dbCol.udt_name !== "vector") isMismatch = true;
1182
+ if (planned.kind === "array" && actualType === "ARRAY") {
1183
+ const expectedUdt = ARRAY_UDT_NAMES[planned.of.kind];
1184
+ if (expectedUdt && dbCol.udt_name !== expectedUdt) isMismatch = true;
1185
+ }
1186
+ if (isMismatch) {
1187
+ const expectedLabel = planned.kind === "vector" ? "vector" : expectedType;
1188
+ const actualLabel = dbCol.udt_name === "vector" ? "vector" : actualType;
1189
+ issues.push({
1190
+ severity: "warning",
1191
+ category: "type_mismatch",
1192
+ table: fullTableName,
1193
+ column: colName,
1194
+ expected: expectedLabel,
1195
+ actual: actualLabel,
1196
+ message: `Column "${colName}" in table "${fullTableName}": expected type "${expectedLabel}" but found "${actualLabel}".`,
1197
+ fix: typeMismatchFix(schemaName, tableName, colName, actualType, tablePlan?.columns.find((c) => c.column === colName)?.type ?? planned)
1198
+ });
1199
+ }
1200
+ }
1201
+ if (planned.kind === "enum") {
1202
+ const enumName = toPostgresIdentifier(planned.name);
1203
+ const enumSchema = planned.schema;
1204
+ const dbEnumValues = enumsByName.get(`${enumSchema}.${enumName}`);
1205
+ if (!dbEnumValues) issues.push({
1206
+ severity: "warning",
1207
+ category: "missing_enum",
1208
+ table: fullTableName,
1209
+ column: colName,
1210
+ expected: enumName,
1211
+ message: `Enum type "${enumSchema}"."${enumName}" is defined in backend/schema but not found in the database.`,
1212
+ fix: "Run `rebase db push` or `rebase db generate && rebase db migrate`"
1213
+ });
1214
+ else {
1215
+ const expectedValues = planned.labels;
1216
+ const missing = expectedValues.filter((v) => !dbEnumValues.includes(v));
1217
+ const extra = dbEnumValues.filter((v) => !expectedValues.includes(v));
1218
+ if (missing.length > 0 || extra.length > 0) {
1219
+ const parts = [];
1220
+ if (missing.length > 0) parts.push(`missing: ${missing.join(", ")}`);
1221
+ if (extra.length > 0) parts.push(`extra in DB: ${extra.join(", ")}`);
1222
+ issues.push({
1223
+ severity: "warning",
1224
+ category: "enum_value_mismatch",
1225
+ table: fullTableName,
1226
+ column: colName,
1227
+ expected: expectedValues.join(", "),
1228
+ actual: dbEnumValues.join(", "),
1229
+ message: `Enum values for "${colName}" in table "${fullTableName}" are out of sync (${parts.join("; ")}).`,
1230
+ fix: extra.length > 0 && missing.length === 0 ? `PostgreSQL cannot drop an enum label, so \`rebase db push\` leaves ${extra.join(", ")} in place. Harmless unless something still writes it; to retire it, UPDATE its rows to another value, then rewrite the type in a migration (\`rebase db generate\`: CREATE TYPE …, ALTER TABLE … TYPE … USING, DROP TYPE) and \`rebase db migrate\`` : "Run `rebase db push` to add the missing labels" + (extra.length > 0 ? `; it cannot remove ${extra.join(", ")} (PostgreSQL has no ALTER TYPE … DROP VALUE) — retire those with a migration that rewrites the type` : "")
1231
+ });
1232
+ }
1233
+ }
1234
+ }
1235
+ }
1236
+ for (const relation of relationsOfKind(descriptor, "manyToMany")) {
1237
+ const junctionTable = relation.through.table.split(".").pop() ?? relation.through.table;
1238
+ const junctionSchema = junctions.get(junctionTable)?.schema ?? "public";
1239
+ const fullJunctionTable = junctionSchema === "public" ? junctionTable : `${junctionSchema}.${junctionTable}`;
1240
+ if (!existingTables.has(fullJunctionTable)) issues.push({
1241
+ severity: "error",
1242
+ category: "missing_table",
1243
+ table: fullJunctionTable,
1244
+ message: `Junction table "${fullJunctionTable}" for many-to-many relation "${relation.name}" is missing.`,
1245
+ fix: "Run `rebase db push` or `rebase db generate && rebase db migrate`"
1246
+ });
1247
+ else if (!checkedJunctions.has(fullJunctionTable)) {
1248
+ checkedJunctions.add(fullJunctionTable);
1249
+ const junctionPlan = tablePlans.get(`${junctionSchema}.${junctionTable}`);
1250
+ if (junctionPlan) issues.push(...junctionKeyIssues(junctionPlan, columnsByTable.get(fullJunctionTable) ?? [], pksByTable.get(fullJunctionTable) ?? [], fullJunctionTable));
1251
+ }
1252
+ }
1253
+ }
1254
+ if (plan) issues.push(...orphanedJunctionIssues(plan, columnsByTable, pksByTable, fksByTable));
1255
+ if (options.generated) {
1256
+ const differences = await readGeneratedSchemaDrift({
1257
+ client: pool,
1258
+ generated: options.generated,
1259
+ tables: defaultDatabaseTables(tables).map((t) => t.descriptor),
1260
+ defaultSchema: "public"
1261
+ });
1262
+ issues.push(...generatedSchemaDriftIssues(differences, issues, descriptors));
1263
+ }
1264
+ } finally {
1265
+ await pool.end();
1266
+ }
1267
+ return {
1268
+ passed: !issues.some((issue) => issue.severity !== "info"),
1269
+ issues
1270
+ };
1271
+ }
1272
+ /**
1273
+ * A `public` table in the junction shape that no collection declares.
1274
+ *
1275
+ * The shape is the planner's: exactly two columns, together the primary key,
1276
+ * each a single-column foreign key to a collection's table. Renaming or
1277
+ * removing a many-to-many leaves such a table behind — push and boot only
1278
+ * create — with every link row still in it and nothing reading it.
1279
+ *
1280
+ * Info, never more: the table may be data somebody still wants. The remedy is
1281
+ * shown, never run.
1282
+ */
1283
+ function orphanedJunctionIssues(plan, columnsByTable, pksByTable, fksByTable) {
1284
+ const declared = new Set(plan.tables.map((table) => table.qualified));
1285
+ const collectionTables = new Set(plan.tables.filter((table) => table.kind === "collection").map((table) => table.qualified));
1286
+ const issues = [];
1287
+ for (const [table, columns] of columnsByTable) {
1288
+ if (table.includes(".") || declared.has(`public.${table}`)) continue;
1289
+ if (columns.length !== 2 || (pksByTable.get(table) ?? []).length !== 2) continue;
1290
+ const byConstraint = /* @__PURE__ */ new Map();
1291
+ for (const fk of fksByTable.get(table) ?? []) {
1292
+ const target = `${fk.foreign_table_schema}.${fk.foreign_table_name}`;
1293
+ byConstraint.set(fk.constraint_name, [...byConstraint.get(fk.constraint_name) ?? [], {
1294
+ column: fk.column_name,
1295
+ target
1296
+ }]);
1297
+ }
1298
+ const links = [...byConstraint.values()];
1299
+ if (links.length !== 2 || links.some((link) => link.length !== 1)) continue;
1300
+ if (new Set(links.map(([link]) => link.column)).size !== 2) continue;
1301
+ if (!links.every(([link]) => collectionTables.has(link.target))) continue;
1302
+ const targets = links.map(([link]) => link.target.replace(/^public\./, ""));
1303
+ issues.push({
1304
+ severity: "info",
1305
+ category: "orphaned_junction",
1306
+ table,
1307
+ message: `Table "${table}" links "${targets[0]}" and "${targets[1]}" like a many-to-many junction, but no table declares it — left behind by a renamed or removed relation?`,
1308
+ fix: `DROP TABLE "public"."${table}";`
1309
+ });
1310
+ }
1311
+ return issues;
1312
+ }
1313
+ function renderReport(report) {
1314
+ out();
1315
+ out(chalk.bold(" 🩺 Rebase Schema Doctor"));
1316
+ out(chalk.gray(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"));
1317
+ out();
1318
+ renderPhase("Tables → Generated Schema", report.collectionsToSchema);
1319
+ renderPhase("Tables → Database", report.schemaToDatabase);
1320
+ renderPhase("Tables → SDK Types", report.collectionsToSdk);
1321
+ out(chalk.gray(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"));
1322
+ const { passed, skipped, notApplicable, warnings, errors } = report.summary;
1323
+ const parts = [];
1324
+ parts.push(chalk.green(`${passed} passed`));
1325
+ if (skipped > 0) parts.push(chalk.yellow(`${skipped} skipped`));
1326
+ if (notApplicable > 0) parts.push(chalk.gray(`${notApplicable} not applicable`));
1327
+ if (warnings > 0) parts.push(chalk.yellow(`${warnings} warnings`));
1328
+ if (errors > 0) parts.push(chalk.red(`${errors} errors`));
1329
+ out(` Summary: ${parts.join(", ")}`);
1330
+ out();
1331
+ if (errors > 0) out(chalk.red.bold(" ✗ Schema drift detected. Run the suggested fixes above."));
1332
+ else if (warnings > 0) out(chalk.yellow.bold(" ⚠ Minor issues detected. Consider running the suggested fixes."));
1333
+ else if (skipped > 0) out(chalk.yellow.bold(` ⚠ Nothing wrong in the checks that ran, but ${skipped} did not run — this is not a clean bill of health.`));
1334
+ else out(chalk.green.bold(" ✓ All schemas are in sync!"));
1335
+ out();
1336
+ }
1337
+ function renderPhase(label, phase) {
1338
+ if (phase.skipped) {
1339
+ out(` ${chalk.yellow("⏭")} ${label}: ${chalk.yellow(`skipped (${phase.skipped})`)}`);
1340
+ out();
1341
+ return;
1342
+ }
1343
+ if (phase.notApplicable) {
1344
+ out(` ${chalk.gray("➖")} ${label}: ${chalk.gray(phase.notApplicable)}`);
1345
+ for (const issue of phase.issues.filter((i) => i.severity === "info")) out(` ${chalk.gray(issue.fix)}`);
1346
+ out();
1347
+ return;
1348
+ }
1349
+ const issues = phase.issues;
1350
+ const errorCount = issues.filter((i) => i.severity === "error").length;
1351
+ const warnCount = issues.filter((i) => i.severity === "warning").length;
1352
+ const infoIssues = issues.filter((i) => i.severity === "info");
1353
+ if (errorCount === 0 && warnCount === 0) out(` ${chalk.green("✅")} ${label}: ${chalk.green("In sync")}`);
1354
+ else {
1355
+ const parts = [];
1356
+ if (errorCount > 0) parts.push(`${errorCount} error${errorCount > 1 ? "s" : ""}`);
1357
+ if (warnCount > 0) parts.push(`${warnCount} warning${warnCount > 1 ? "s" : ""}`);
1358
+ out(` ${chalk.yellow("⚠️")} ${label}: ${chalk.yellow(parts.join(", "))}`);
1359
+ }
1360
+ out();
1361
+ for (const issue of infoIssues) {
1362
+ const fixPart = issue.fix ? chalk.gray(` — ${issue.fix}`) : "";
1363
+ out(` ${chalk.gray("ℹ")} ${chalk.gray(issue.message)}${fixPart}`);
1364
+ out();
1365
+ }
1366
+ for (const issue of issues.filter((i) => i.severity !== "info")) {
1367
+ const severityIcon = issue.severity === "error" ? chalk.red("✗") : chalk.yellow("⚠");
1368
+ const categoryLabel = formatCategory(issue.category);
1369
+ out(` ${chalk.gray("┌─")} ${severityIcon} ${chalk.bold(categoryLabel)} ${chalk.gray("─".repeat(Math.max(0, 42 - categoryLabel.length)))}`);
1370
+ if (issue.table) {
1371
+ const colPart = issue.column ? ` │ Column: ${chalk.cyan(issue.column)}` : "";
1372
+ out(` ${chalk.gray("│")} Table: ${chalk.cyan(issue.table)}${colPart}`);
1373
+ }
1374
+ if (issue.expected && issue.actual) out(` ${chalk.gray("│")} Expected: ${chalk.green(issue.expected)} │ Actual: ${chalk.red(issue.actual)}`);
1375
+ out(` ${chalk.gray("│")} ${issue.message}`);
1376
+ out(` ${chalk.gray("│")} Fix: ${chalk.blue(issue.fix)}`);
1377
+ out(` ${chalk.gray("└" + "─".repeat(48))}`);
1378
+ out();
1379
+ }
1380
+ }
1381
+ function formatCategory(cat) {
1382
+ return {
1383
+ missing_table: "Missing Table",
1384
+ missing_column: "Missing Column",
1385
+ type_mismatch: "Type Mismatch",
1386
+ nullability_mismatch: "Nullability Mismatch",
1387
+ extra_column: "Extra Column",
1388
+ missing_constraint: "Missing Constraint",
1389
+ primary_key_mismatch: "Primary Key Mismatch",
1390
+ schema_stale: "Stale Schema",
1391
+ missing_enum: "Missing Enum",
1392
+ enum_value_mismatch: "Enum Value Mismatch",
1393
+ missing_foreign_key: "Missing Foreign Key",
1394
+ orphaned_junction: "Orphaned Junction Table",
1395
+ sdk_stale: "Stale SDK Types",
1396
+ sdk_not_generated: "SDK Types Not Generated",
1397
+ sdk_ungeneratable: "SDK Cannot Be Generated"
1398
+ }[cat];
1399
+ }
1400
+ var isRecord = (value) => typeof value === "object" && value !== null;
1401
+ /**
1402
+ * The `tables` export of `schema.generated.ts`, imported as boot imports it.
1403
+ *
1404
+ * Nothing, and no error, when the file is not there: phase 1 reports that, and
1405
+ * boot then has nothing to compare either.
1406
+ */
1407
+ async function loadGeneratedTables(schemaPath) {
1408
+ if (!fs$1.existsSync(schemaPath)) return {};
1409
+ try {
1410
+ const module = await import(pathToFileURL(schemaPath).href);
1411
+ return isRecord(module) && isRecord(module.tables) ? { tables: module.tables } : {};
1412
+ } catch (err) {
1413
+ return { error: err instanceof Error ? err.message : String(err) };
1414
+ }
1415
+ }
1416
+ async function runDoctor(options) {
1417
+ out();
1418
+ out(chalk.bold(" 🩺 Loading tables..."));
1419
+ const loaded = await loadTableSchema(options.schemaDir);
1420
+ const { descriptors, tables } = loaded;
1421
+ if (tables.length === 0) {
1422
+ outError(chalk.red(` ✗ No tables found in ${options.schemaDir} (its index.ts exports none).`));
1423
+ process.exit(1);
1424
+ }
1425
+ out(chalk.gray(` Found ${tables.length} table(s)`));
1426
+ out();
1427
+ out(chalk.gray(" Checking Tables → Generated Schema..."));
1428
+ const collectionsToSchema = await checkTablesVsSchema(tables, options.schemaPath);
1429
+ let schemaToDatabase;
1430
+ if (options.databaseUrl) {
1431
+ out(chalk.gray(" Checking Tables → Database..."));
1432
+ try {
1433
+ const generated = await loadGeneratedTables(options.schemaPath);
1434
+ schemaToDatabase = await checkTablesVsDatabase(tables, options.databaseUrl, {
1435
+ generated: generated.tables,
1436
+ schemaVersion: defaultDatabaseSchemaVersion(loaded)
1437
+ });
1438
+ if (generated.error) {
1439
+ schemaToDatabase.issues.push({
1440
+ severity: "warning",
1441
+ category: "schema_stale",
1442
+ message: `schema.generated.ts could not be loaded, so it was not compared against the database as boot compares it: ${generated.error}`,
1443
+ fix: "Run `rebase schema generate`, then `rebase doctor` again"
1444
+ });
1445
+ schemaToDatabase.passed = false;
1446
+ }
1447
+ } catch (err) {
1448
+ const banner = diagnoseDbError(err, options.databaseUrl);
1449
+ if (banner) outError(banner);
1450
+ const reason = deepestErrorMessage(err) ?? (err instanceof Error ? err.message : String(err));
1451
+ schemaToDatabase = {
1452
+ passed: false,
1453
+ issues: [],
1454
+ skipped: `could not reach ${parseHostInfo(options.databaseUrl)} — ${reason}`,
1455
+ blocked: true
1456
+ };
1457
+ }
1458
+ } else {
1459
+ schemaToDatabase = {
1460
+ passed: false,
1461
+ issues: [],
1462
+ skipped: "DATABASE_URL not set"
1463
+ };
1464
+ out(chalk.yellow(" ⚠ DATABASE_URL not set — skipping database comparison."));
1465
+ out(chalk.gray(" Set DATABASE_URL in your .env to enable full drift detection."));
1466
+ }
1467
+ out(chalk.gray(" Checking Tables → SDK Types..."));
1468
+ const collectionsToSdk = await checkTablesVsSdk(descriptors, options.sdkPath);
1469
+ const phases = [
1470
+ collectionsToSchema,
1471
+ schemaToDatabase,
1472
+ collectionsToSdk
1473
+ ];
1474
+ const allIssues = phases.flatMap((p) => p.issues);
1475
+ const summary = {
1476
+ passed: phases.filter((p) => p.passed && !p.skipped && !p.notApplicable).length,
1477
+ skipped: phases.filter((p) => p.skipped).length,
1478
+ notApplicable: phases.filter((p) => p.notApplicable && !p.skipped).length,
1479
+ warnings: allIssues.filter((i) => i.severity === "warning").length,
1480
+ errors: allIssues.filter((i) => i.severity === "error").length
1481
+ };
1482
+ const report = {
1483
+ collectionsToSchema,
1484
+ collectionsToSdk,
1485
+ schemaToDatabase,
1486
+ summary
1487
+ };
1488
+ renderReport(report);
1489
+ return report;
1490
+ }
1491
+ //#endregion
13
1492
  //#region src/schema/doctor-policy-checks.ts
14
1493
  /**
15
1494
  * The RLS half of `rebase doctor`, and the exit code `--policies` gates CI on.
@@ -29,25 +1508,26 @@ function exitCodeForPolicyGate(status) {
29
1508
  return status === "ok" ? 0 : 1;
30
1509
  }
31
1510
  /**
32
- * Policies actually deployed vs the ones the collections describe, plus policy
1511
+ * Policies actually deployed vs the ones the tables describe, plus policy
33
1512
  * roles this server could never satisfy.
34
1513
  *
35
1514
  * Never reports `ok` for work it did not do — see {@link PolicyCheckStatus}.
36
1515
  */
37
- async function runPolicyChecks(collectionsPath, databaseUrl) {
1516
+ async function runPolicyChecks(schemaDir, databaseUrl) {
38
1517
  if (!databaseUrl) {
39
1518
  console.error(chalk.yellow(" ⚠ No DATABASE_URL — RLS policies were NOT checked"));
40
1519
  return "unchecked";
41
1520
  }
42
- const resolvedPath = path.resolve(process.cwd(), collectionsPath);
1521
+ const resolvedPath = path.resolve(process.cwd(), schemaDir);
43
1522
  let problems = false;
44
1523
  const { Pool } = await import("pg");
45
1524
  const pool = new Pool({ connectionString: databaseUrl });
46
1525
  try {
47
- const collections = await loadCollections(resolvedPath);
48
- if (collections.length === 0) {
49
- console.error(chalk.red(` ✗ No collections found in ${resolvedPath}`));
50
- console.error(chalk.gray(" RLS policies were NOT checked. Pass --collections=<dir> if your collections live elsewhere."));
1526
+ const tables = await loadTables(resolvedPath);
1527
+ const descriptors = tables.map((table) => table.descriptor);
1528
+ if (descriptors.length === 0) {
1529
+ console.error(chalk.red(` ✗ No tables found in ${resolvedPath}`));
1530
+ console.error(chalk.gray(" RLS policies were NOT checked. Pass --schema-dir=<dir> if your tables live elsewhere than backend/schema."));
51
1531
  return "unchecked";
52
1532
  }
53
1533
  const runSql = async (text) => (await pool.query(text)).rows;
@@ -59,21 +1539,21 @@ async function runPolicyChecks(collectionsPath, databaseUrl) {
59
1539
  return "unchecked";
60
1540
  }
61
1541
  try {
62
- await validatePolicyPgRoles(runSql, collections);
1542
+ await validatePolicyPgRoles(runSql, descriptors);
63
1543
  console.log(chalk.green(" ✓ Policy roles are usable by this server"));
64
1544
  } catch (err) {
65
1545
  problems = true;
66
1546
  console.log("");
67
1547
  console.error(chalk.red(err instanceof Error ? err.message : String(err)));
68
1548
  }
69
- warnOnAnonymousGrants(collections);
70
- const drift = await checkPolicyDrift(pool, collections, { adminRoleAvailable: "detect" });
1549
+ warnOnAnonymousGrants(descriptors);
1550
+ const drift = await checkPolicyDrift(pool, tables, { adminRoleAvailable: "detect" });
71
1551
  console.log("");
72
1552
  if (hasDrift(drift)) {
73
1553
  problems = true;
74
- console.log(chalk.yellow(" RLS policies: database does not match your collections"));
1554
+ console.log(chalk.yellow(" RLS policies: database does not match your tables"));
75
1555
  console.log(formatPolicyDrift(drift));
76
- } else console.log(chalk.green(` ✓ RLS policies match your collections (${collections.length} collection(s) checked)`));
1556
+ } else console.log(chalk.green(` ✓ RLS policies match your tables (${descriptors.length} table(s) checked)`));
77
1557
  } catch (err) {
78
1558
  console.error(chalk.red(" ✗ Could not check RLS policies:"), err instanceof Error ? err.message : String(err));
79
1559
  return "unchecked";
@@ -85,13 +1565,13 @@ async function runPolicyChecks(collectionsPath, databaseUrl) {
85
1565
  //#endregion
86
1566
  //#region src/schema/doctor-search-scale.ts
87
1567
  /**
88
- * `rebase doctor`: collections searched by a full scan of a large table.
1568
+ * `rebase doctor`: tables searched by a full scan of a large table.
89
1569
  *
90
1570
  * Without a `search` block, a search — the admin's search box, `?searchString=`,
91
1571
  * `.search()` — is `ILIKE '%term%'` over every text column. A leading `%`
92
1572
  * defeats a B-tree, so each one reads the whole table: on 100k posts a search
93
1573
  * took 326 ms, half for the page and half for its count. Nothing reports it;
94
- * the box just gets slower as the table grows. This names the collections
1574
+ * the box just gets slower as the table grows. This names the tables
95
1575
  * where that has started to matter, and points at the block that fixes it.
96
1576
  *
97
1577
  * A hint, not a failure: it never changes doctor's exit code, and the database
@@ -103,29 +1583,28 @@ async function runPolicyChecks(collectionsPath, databaseUrl) {
103
1583
  /** Above this many rows an unindexed search is worth a word. */
104
1584
  var UNINDEXED_SEARCH_ROWS = 1e4;
105
1585
  /**
106
- * The collections a search reaches without an index: no `search` block (or
107
- * one that does not build), and at least one property the default search
108
- * reads — a `string`, not an enum, not a uuid key (the rule in
109
- * `DrizzleConditionBuilder.buildSearchConditions`).
1586
+ * The tables a search reaches without an index: no `search` block (or one
1587
+ * that does not build), and at least one column the default search reads —
1588
+ * text, without `.oneOf()` ({@link isIlikeSearchable}, the rule the search
1589
+ * conditions use).
110
1590
  */
111
- function ilikeSearchedCollections(collections) {
1591
+ function ilikeSearchedTables(tables) {
112
1592
  const found = [];
113
- for (const collection of relationalCollections(collections)) {
114
- if (!isPostgresCollectionConfig(collection)) continue;
1593
+ for (const table of tables) {
1594
+ if (table.kind === "view") continue;
115
1595
  let indexed;
116
1596
  try {
117
- indexed = buildSearchColumnSpec(collection) !== void 0;
1597
+ indexed = buildTableSearchColumnSpec(table) !== void 0;
118
1598
  } catch {
119
1599
  indexed = false;
120
1600
  }
121
1601
  if (indexed) continue;
122
- const fields = Object.entries(collection.properties ?? {}).filter(([, property]) => property.type === "string" && !property.enum && property.isId !== "uuid").map(([key]) => key);
123
- const table = getTableName(collection);
124
- if (fields.length === 0 || !table) continue;
1602
+ const fields = table.columns.filter((column) => isIlikeSearchable(column)).map((column) => column.key);
1603
+ if (fields.length === 0) continue;
125
1604
  found.push({
126
- slug: collection.slug,
127
- schema: collection.schema ?? "public",
128
- table,
1605
+ slug: table.slug,
1606
+ schema: table.schema,
1607
+ table: table.table,
129
1608
  fields
130
1609
  });
131
1610
  }
@@ -153,25 +1632,25 @@ async function estimateRowCounts(query, schemas) {
153
1632
  WHERE c.relkind IN ('r', 'p') AND n.nspname = ANY($1)`, [schemas]);
154
1633
  return new Map(rows.map((row) => [`${row.schema}.${row.table}`, Number(row.rows)]));
155
1634
  }
156
- /** The report, one warning per collection. */
1635
+ /** The report, one warning per table. */
157
1636
  function formatUnindexedSearches(findings) {
158
1637
  if (findings.length === 0) return [];
159
- const lines = ["", chalk.yellow(` ⚠ ${findings.length} collection(s) searched by reading the whole table:`)];
1638
+ const lines = ["", chalk.yellow(` ⚠ ${findings.length} table(s) searched by reading the whole table:`)];
160
1639
  for (const finding of findings) lines.push(chalk.yellow(` • ${finding.slug} — about ${finding.rows.toLocaleString("en-US")} rows, no \`search\` block: a search is ILIKE '%term%' over ${finding.fields.join(", ")}`));
161
1640
  lines.push(chalk.gray(" Each search reads every row, and its count reads them again. A `search` block indexes it\n (full-text, or `mode: \"hybrid\"` for substrings too): https://rebase.pro/docs/backend/search"));
162
1641
  return lines;
163
1642
  }
164
1643
  /**
165
- * Print the warning for the project at `collectionsPath`, against
1644
+ * Print the warning for the project at `schemaDir`, against
166
1645
  * `databaseUrl`. Never throws and never fails the run: it is a hint, and a
167
1646
  * check that could not run says so in one grey line.
168
1647
  */
169
- async function runSearchScaleCheck(collectionsPath, databaseUrl) {
1648
+ async function runSearchScaleCheck(schemaDir, databaseUrl) {
170
1649
  if (!databaseUrl) return;
171
1650
  const { Client } = await import("pg");
172
1651
  const client = new Client({ connectionString: databaseUrl });
173
1652
  try {
174
- const candidates = ilikeSearchedCollections(await loadCollections(path.resolve(process.cwd(), collectionsPath)));
1653
+ const candidates = ilikeSearchedTables((await loadTables(schemaDir)).map((table) => table.descriptor));
175
1654
  if (candidates.length === 0) return;
176
1655
  await client.connect();
177
1656
  const estimates = await estimateRowCounts((text, values) => client.query(text, values), [...new Set(candidates.map((candidate) => candidate.schema))]);
@@ -193,27 +1672,26 @@ async function runSearchScaleCheck(collectionsPath, databaseUrl) {
193
1672
  * `main()` on import; the rendering and the table list are tested here.
194
1673
  */
195
1674
  /**
196
- * The tables Rebase serves, as the server would list them: every relational
197
- * collection's table in its schema (`public` by default), and every junction
1675
+ * The tables Rebase serves, as the server would list them: every declared
1676
+ * table in its schema (`public` by default), and every junction
198
1677
  * table a many-to-many declares.
199
1678
  */
200
- function managedTablesOf(collections) {
201
- const relational = relationalCollections(collections);
1679
+ function managedTablesOf(descriptors) {
202
1680
  const tables = /* @__PURE__ */ new Map();
203
1681
  const add = (schema, table) => tables.set(`${schema}.${table}`, {
204
1682
  schema,
205
1683
  table
206
1684
  });
207
- for (const collection of relational) add(isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public", getTableName(collection));
208
- for (const spec of resolveJunctionSpecs(relational).values()) add(spec.schema, spec.table);
1685
+ for (const descriptor of descriptors) add(descriptor.schema, descriptor.table);
1686
+ for (const junction of resolveTableJunctions(descriptors).values()) add(junction.schema, junction.table);
209
1687
  return [...tables.values()];
210
1688
  }
211
- /** The schemas Rebase writes to: `public`, `rebase`, and every schema a collection names. */
212
- function preflightSchemasOf(collections) {
1689
+ /** The schemas Rebase writes to: `public`, `rebase`, and every schema a table names. */
1690
+ function preflightSchemasOf(descriptors) {
213
1691
  return Array.from(/* @__PURE__ */ new Set([
214
1692
  "public",
215
1693
  "rebase",
216
- ...relationalCollections(collections).filter(isPostgresCollectionConfig).map((c) => c.schema).filter((s) => !!s)
1694
+ ...descriptors.map((d) => d.schema)
217
1695
  ]));
218
1696
  }
219
1697
  var LEVEL_ORDER = [
@@ -259,7 +1737,7 @@ function preflightStatus(findings) {
259
1737
  }
260
1738
  /**
261
1739
  * Every table in `schemas` but `rebase`: what a project with no declared
262
- * collections serves, since its API is introspected from the database.
1740
+ * tables serves, since its API is introspected from the database.
263
1741
  */
264
1742
  async function everyTableIn(run, schemas) {
265
1743
  const names = schemas.filter((s) => s !== "rebase").map((s) => `'${s.replace(/'/g, "''")}'`);
@@ -279,28 +1757,28 @@ async function everyTableIn(run, schemas) {
279
1757
  * the server sees (`REBASE_RLS_*`, else the roles recorded in the database),
280
1758
  * and print it. Never reports `ok` for a check it could not run.
281
1759
  */
282
- async function runDatabasePreflight(collectionsPath, databaseUrl) {
1760
+ async function runDatabasePreflight(schemaDir, databaseUrl) {
283
1761
  if (!databaseUrl) {
284
1762
  console.error(chalk.yellow(" ⚠ No DATABASE_URL — the database preflight did NOT run"));
285
1763
  return "unchecked";
286
1764
  }
287
- const { loadCollections } = await import("../doctor-Kg1oUK0Q.js").then((n) => n.t);
288
- const { preflightDatabase } = await import("../database-preflight-iBpT7-vv.js");
289
- const { readRecordedRequestRoles } = await import("../rls-enforcement-Cc_UhOxb.js").then((n) => n.y);
290
- const { cliRlsSettings } = await import("../rls-settings-BCGMIig3.js").then((n) => n.a);
1765
+ const { loadTables } = await import("../load-tables-B1Re74ng.js").then((n) => n.i);
1766
+ const { preflightDatabase } = await import("../database-preflight-bfnIBnjM.js");
1767
+ const { readRecordedRequestRoles } = await import("../rls-enforcement-DB5HHj96.js").then((n) => n.y);
1768
+ const { cliRlsSettings } = await import("../rls-settings-CmGK2U0a.js").then((n) => n.a);
291
1769
  const { Pool } = await import("pg");
292
1770
  const pool = new Pool({ connectionString: databaseUrl });
293
1771
  try {
294
1772
  const run = async (text) => (await pool.query(text)).rows;
295
- const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
1773
+ const descriptors = (await loadTables(schemaDir)).map((table) => table.descriptor);
296
1774
  const existing = new Set((await run("SELECT nspname FROM pg_namespace")).map((row) => String(row.nspname)));
297
- const schemas = preflightSchemasOf(collections).filter((schema) => existing.has(schema));
1775
+ const schemas = preflightSchemasOf(descriptors).filter((schema) => existing.has(schema));
298
1776
  const settings = cliRlsSettings(await readRecordedRequestRoles(run));
299
- let managedTables = managedTablesOf(collections);
1777
+ let managedTables = managedTablesOf(descriptors);
300
1778
  console.log("");
301
1779
  if (managedTables.length === 0) {
302
1780
  managedTables = await everyTableIn(run, schemas);
303
- console.log(chalk.gray(" No declared collections: every table in public is treated as served, as an introspected project serves them."));
1781
+ console.log(chalk.gray(" No declared tables: every table in public is treated as served, as an introspected project serves them."));
304
1782
  }
305
1783
  const findings = await preflightDatabase(run, settings, {
306
1784
  schemas,
@@ -323,12 +1801,12 @@ async function runDatabasePreflight(collectionsPath, databaseUrl) {
323
1801
  * Invoked via tsx by the server-postgres CLI plugin.
324
1802
  */
325
1803
  async function main() {
326
- const collectionsArg = process.argv.find((a) => a.startsWith("--collections="));
1804
+ const schemaDirArg = process.argv.find((a) => a.startsWith("--schema-dir="));
327
1805
  const schemaArg = process.argv.find((a) => a.startsWith("--schema="));
328
1806
  const sdkArg = process.argv.find((a) => a.startsWith("--sdk="));
329
1807
  const policiesOnly = process.argv.includes("--policies");
330
1808
  const databaseOnly = process.argv.includes("--database");
331
- const collectionsPath = collectionsArg?.split("=")[1] ?? path.join("..", "config", "collections");
1809
+ const schemaDir = schemaDirArg?.split("=")[1] ?? "schema";
332
1810
  const schemaPath = schemaArg?.split("=")[1] ?? path.join("src", "schema.generated.ts");
333
1811
  const sdkPath = sdkArg?.split("=")[1] ?? path.join("..", "generated", "sdk", "database.types.ts");
334
1812
  try {
@@ -342,17 +1820,17 @@ async function main() {
342
1820
  } catch {}
343
1821
  const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;
344
1822
  if (policiesOnly || databaseOnly) {
345
- const statuses = [...databaseOnly ? [await runDatabasePreflight(collectionsPath, databaseUrl)] : [], ...policiesOnly ? [await runPolicyChecks(collectionsPath, databaseUrl)] : []];
1823
+ const statuses = [...databaseOnly ? [await runDatabasePreflight(schemaDir, databaseUrl)] : [], ...policiesOnly ? [await runPolicyChecks(schemaDir, databaseUrl)] : []];
346
1824
  process.exit(statuses.some((status) => exitCodeForPolicyGate(status) !== 0) ? 1 : 0);
347
1825
  }
348
1826
  const report = await runDoctor({
349
- collectionsPath: path.resolve(process.cwd(), collectionsPath),
1827
+ schemaDir: path.resolve(process.cwd(), schemaDir),
350
1828
  schemaPath: path.resolve(process.cwd(), schemaPath),
351
1829
  sdkPath: path.resolve(process.cwd(), sdkPath),
352
1830
  databaseUrl: databaseUrl ?? void 0
353
1831
  });
354
- const policyStatus = await runPolicyChecks(collectionsPath, databaseUrl);
355
- await runSearchScaleCheck(collectionsPath, databaseUrl);
1832
+ const policyStatus = await runPolicyChecks(schemaDir, databaseUrl);
1833
+ await runSearchScaleCheck(schemaDir, databaseUrl);
356
1834
  const blocked = [
357
1835
  report.collectionsToSchema,
358
1836
  report.schemaToDatabase,