@rebasepro/server-postgres 0.30.1 → 0.31.0-canary.g59cd6fd

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,1458 +0,0 @@
1
- import { createRequire as __createRequire } from "module";
2
- __createRequire(import.meta.url);
3
- import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
4
- import { a as diagnoseDbError, r as deepestErrorMessage, u as parseHostInfo } from "./cli-errors-DYTxnLbW.js";
5
- import { i as outError, r as out, t as chalk } from "./source-fZb92pN8.js";
6
- import { n as planSchema, t as columnPgType } from "./plan-schema-vJd3UEmT.js";
7
- import { t as generateSchema } from "./generate-drizzle-schema-logic-LTLZvt6r.js";
8
- import { i as renderPgType } from "./render-ddl-Ci3S_SoI.js";
9
- import { r as readGeneratedSchemaDrift, t as describeSchemaDifference } from "./generated-schema-diff-By4dxyTH.js";
10
- import { n as describeDeclarationDifferences, t as compareGeneratedDeclarations } from "./generated-schema-staleness-BvNF3i-s.js";
11
- import { loadCollectionsFromDirectory } from "@rebasepro/server";
12
- import { DEFAULT_DATA_SOURCE_KEY, computeSchemaVersion, getDeclaredSubcollections, isManyToMany, isPostgresCollectionConfig } from "@rebasepro/types";
13
- import { effectiveAccess, fieldKeyForColumn, findRelation, getTableName, isRelationRequired, relationalCollections, resolveCollectionRelations, resolveJunctionSpecs, restrictedFieldNames, sortCollectionsBySlug, toCollectionAccessor, toSafeIdentifier } from "@rebasepro/common";
14
- import { toPostgresIdentifier, toSnakeCase } from "@rebasepro/utils";
15
- import * as fs$1 from "fs";
16
- import { promises } from "fs";
17
- import { pathToFileURL } from "url";
18
- //#region ../codegen/dist/index.es.js
19
- /**
20
- * A schema that cannot be expressed as a valid TypeScript file.
21
- *
22
- * Thrown rather than emitted. The generator used to concatenate whatever it was
23
- * given, so a slug that collided with another one, or that was not an
24
- * identifier, produced a file that either failed to compile or — worse —
25
- * compiled while quietly routing one collection to another's slug.
26
- */
27
- var CodegenError = class extends Error {
28
- constructor(message) {
29
- super(message);
30
- this.name = "CodegenError";
31
- }
32
- };
33
- var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
34
- /**
35
- * A property name for the emitted TypeScript: verbatim when it is a valid
36
- * identifier, quoted otherwise.
37
- *
38
- * Every key that reaches the output goes through here. Column names are not
39
- * required to be identifiers — `"order"`, `"user id"`, a quoted Postgres
40
- * identifier — and the previous behaviour of camel-casing them into shape
41
- * renamed the column in the type while the wire kept the original, so the
42
- * generated `Row` described fields that did not exist.
43
- */
44
- function emitKey(key) {
45
- return IDENTIFIER.test(key) ? key : JSON.stringify(key);
46
- }
47
- /**
48
- * A string literal, escaped.
49
- *
50
- * `"${value}"` was the previous form. A value containing a quote closed the
51
- * literal early, which at best broke the file and at worst let a slug from a
52
- * remote contract inject top-level statements into a file the developer
53
- * compiles and bundles.
54
- */
55
- function emitString(value) {
56
- return JSON.stringify(value);
57
- }
58
- /** The `id`s of an enum declared as an array, an array of `{ id }`, or an object map. */
59
- function enumIds(raw) {
60
- if (Array.isArray(raw)) return raw.map((entry) => entry && typeof entry === "object" ? entry.id : entry);
61
- if (raw && typeof raw === "object") return Object.keys(raw);
62
- return [];
63
- }
64
- function propertyToTypeScriptType(prop) {
65
- switch (prop.type) {
66
- case "string": {
67
- const sp = prop;
68
- if (sp.enum) {
69
- const ids = enumIds(sp.enum);
70
- if (ids.length === 0) return "string";
71
- return ids.map((v) => emitString(String(v))).join(" | ");
72
- }
73
- return "string";
74
- }
75
- case "number": {
76
- const np = prop;
77
- if (np.enum) {
78
- const ids = enumIds(np.enum);
79
- const numbers = ids.map(Number);
80
- if (ids.length === 0 || numbers.some((n) => !Number.isFinite(n))) return "number";
81
- return numbers.map((n) => String(n)).join(" | ");
82
- }
83
- return "number";
84
- }
85
- case "boolean": return "boolean";
86
- case "date": return "string";
87
- case "geopoint": return "{ latitude: number; longitude: number; }";
88
- case "reference": return "string | number";
89
- case "relation": return "string | number";
90
- case "map": {
91
- const mapProp = prop;
92
- if (mapProp.properties) return `{ ${Object.entries(mapProp.properties).map(([k, v]) => {
93
- const child = v;
94
- const optional = !child.validation?.required;
95
- const type = propertyToTypeScriptType(child);
96
- return `${emitKey(k)}${optional ? "?" : ""}: ${optional ? `${type} | null` : type};`;
97
- }).join(" ")} }`;
98
- return "Record<string, unknown>";
99
- }
100
- case "array": {
101
- const arrProp = prop;
102
- if (arrProp.of) return `Array<${propertyToTypeScriptType(arrProp.of)}>`;
103
- return "Array<unknown>";
104
- }
105
- case "vector": return "number[]";
106
- case "binary": return "string";
107
- default: return "unknown";
108
- }
109
- }
110
- /**
111
- * Unwrap a relation target that arrived as a module namespace rather than the
112
- * collection itself — `target: () => import("./authors")` is a common slip.
113
- */
114
- function resolveTargetCollection(relation) {
115
- try {
116
- let target = relation.target();
117
- if (target && (target.default || target.__esModule)) target = target.default ?? target;
118
- return target;
119
- } catch {
120
- return;
121
- }
122
- }
123
- /** The TypeScript type of a foreign key: whatever the target's primary key is. */
124
- function foreignKeyType(relation) {
125
- const target = resolveTargetCollection(relation);
126
- if (!target?.properties) return "string | number";
127
- const idProp = Object.entries(target.properties).find(([_, p]) => p.isId);
128
- if (!idProp) return "string | number";
129
- return idProp[1].type === "number" ? "number" : "string";
130
- }
131
- /**
132
- * The property's `isId`, on the property kinds that declare one.
133
- *
134
- * `Property` is a union and only `StringProperty`, `NumberProperty` and
135
- * `DateProperty` carry `isId`, so it cannot be read off the union directly — which is what
136
- * double-casting `prop` to `Record<string, unknown>` was for, twice. The union
137
- * discriminates on `type`, so narrowing gets there with no claim at all, and
138
- * with the declared type (`boolean | "manual" | "uuid" | string`) intact
139
- * instead of flattened to `unknown`.
140
- */
141
- function declaredIsId(prop) {
142
- return prop.type === "string" || prop.type === "number" || prop.type === "date" ? prop.isId : void 0;
143
- }
144
- /** Whether a property is the collection's primary key. */
145
- function isPrimaryKey(prop) {
146
- return Boolean(declaredIsId(prop));
147
- }
148
- /**
149
- * Whether the server assigns this primary key, so a write does not have to.
150
- * `true` and `"manual"` both mean the caller supplies it.
151
- */
152
- function isAutoAssignedId(prop) {
153
- const isId = declaredIsId(prop);
154
- return Boolean(isId) && isId !== "manual" && isId !== true;
155
- }
156
- /**
157
- * The type an *included* relation arrives as: the target's own row, inlined.
158
- *
159
- * This is what the read pipeline actually serves — `toRestRow` puts the
160
- * target's flat columns where the relation was, and the SDK and the HTTP API
161
- * both go through it. It is deliberately *not* a `{ __type: "relation" }`
162
- * envelope: that shape is the admin's view-model and never reaches a
163
- * developer's `find()`.
164
- *
165
- * Falls back to an open record when the target is not part of this generation
166
- * run, since there is no `Row` to point at.
167
- */
168
- function includedRelationType(relation, accessors) {
169
- const slug = resolveTargetCollection(relation)?.slug ?? relation.targetSlug;
170
- const accessor = slug ? accessors.get(slug) : void 0;
171
- const rowType = accessor ? `Database[${emitString(accessor)}]["Row"]` : "Record<string, unknown>";
172
- const pivot = relation.kind === "manyToMany" ? pivotType(relation.through.properties, "read") : void 0;
173
- const elementType = pivot ? `${rowType} & { _pivot?: ${pivot} }` : rowType;
174
- return relation.cardinality === "many" ? `Array<${elementType}>` : elementType;
175
- }
176
- /**
177
- * Map every slug to the property name it is reachable under on `client.data`.
178
- *
179
- * The accessor is a safe identifier because `client.data.myNotes` is the point
180
- * of generating this at all, and `collectionsDictionary` maps it back to the
181
- * slug the wire uses. Two slugs that safe down to the same identifier cannot
182
- * both have it: the interface would not compile, and the dictionary — an object
183
- * literal — would silently keep only the last, routing one collection's reads
184
- * to the other's table. There is no defensible way to pick, so this refuses.
185
- */
186
- function buildAccessors(collections) {
187
- const accessors = /* @__PURE__ */ new Map();
188
- const bySafeName = /* @__PURE__ */ new Map();
189
- for (const collection of collections) {
190
- const slug = collection.slug;
191
- if (typeof slug !== "string" || slug.length === 0) throw new CodegenError("A collection has no slug, so it has no name to generate a type for. Every collection needs a unique `slug`.");
192
- const safe = toSafeIdentifier(slug);
193
- 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.`);
194
- const accessor = toCollectionAccessor(slug);
195
- if (accessor !== safe) console.warn(`[codegen] The collection ${emitString(slug)} would be \`client.data.${safe}\`, a name the client reserves, so its typed accessor is \`client.data.${accessor}\`. \`client.data.collection(${emitString(slug)})\` reaches it too.`);
196
- const existing = bySafeName.get(accessor);
197
- if (existing !== void 0) throw new CodegenError(`The collections ${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.`);
198
- bySafeName.set(accessor, slug);
199
- accessors.set(slug, accessor);
200
- }
201
- return accessors;
202
- }
203
- /**
204
- * A column's type on a write: its own type (a date also as a `Date`), or
205
- * `null` too when it is not required.
206
- *
207
- * `Row` has typed a non-required column `T | null` for a while; its write twins
208
- * did not, so the one way to clear a value — `update(id, { publishedAt: null })`,
209
- * `{ authorId: null }` to unassign, the edit-form round trip of a row that came
210
- * back with nulls in it — was a compile error the server would have accepted.
211
- * A primary key is never null, required or not.
212
- */
213
- function writableType(prop, tsType) {
214
- const written = prop.type === "date" ? `${tsType} | Date` : tsType;
215
- return prop.validation?.required || isPrimaryKey(prop) ? written : `${written} | null`;
216
- }
217
- /** One emitted `key: type;` line, already indented. */
218
- function line(key, type, optional) {
219
- return ` ${emitKey(key)}${optional ? "?" : ""}: ${type};`;
220
- }
221
- /**
222
- * The keys nobody can reach take off the API surface — in *both* directions.
223
- *
224
- * `excludeFromApi` means one thing: the API surface does not mention this
225
- * property. `Row` already honoured that; `Insert` and `Update` deliberately did
226
- * not, on the reading that the column is stripped from responses rather than
227
- * from writes. That left the generated types as the one place a password hash
228
- * was still named, and it invited a client to send one. The server refuses
229
- * such a field on a write (`VALIDATION_EXCLUDED_FIELDS`), so nothing generated
230
- * advertises it.
231
- *
232
- * Read through `effectiveAccess`, so the flag and its longhand
233
- * `access: { read: [], write: [] }` produce the same file. A *role* rule is
234
- * deliberately not honoured here and `Row` is unchanged by one: a generated type
235
- * is one shape for every caller, and there is no `Row` that is right for both a
236
- * reader who holds `hr` and one who does not. The server is the enforcement
237
- * point; the types describe the surface a caller may name.
238
- *
239
- * Every spelling the server restricts, read from the server's own function
240
- * (`restrictedFieldNames`): the property name, its column name, and — for a
241
- * closed to-one relation — the foreign key that names the same row. Keying on
242
- * the property and column alone, which this used to, kept `authorId` on all
243
- * three types for an `excludeFromApi` `author`, though the server strips it
244
- * from every read and refuses it on every write.
245
- */
246
- function excludedApiKeys(collection) {
247
- const unreadable = closedNames(collection, "read");
248
- const unwritable = closedNames(collection, "write");
249
- return new Set([...unreadable].filter((name) => unwritable.has(name)));
250
- }
251
- /**
252
- * The names nobody may read (or write), as the server judges them: no viewer
253
- * is the trusted plane, which every role-naming rule admits, so what is left
254
- * is exactly the empty rules.
255
- *
256
- * `restrictedFieldNames` resolves the relations of a closed relation property
257
- * to find its foreign key. When those cannot be resolved — already warned
258
- * about by the caller — the property and column names are still closed.
259
- */
260
- function closedNames(collection, kind) {
261
- try {
262
- return restrictedFieldNames(collection, void 0, kind).refused;
263
- } catch {
264
- const names = /* @__PURE__ */ new Set();
265
- for (const [key, rawProp] of Object.entries(collection.properties ?? {})) {
266
- const prop = rawProp;
267
- if (effectiveAccess(prop)?.[kind]?.length !== 0) continue;
268
- names.add(key);
269
- if (prop.columnName) names.add(prop.columnName);
270
- }
271
- return names;
272
- }
273
- }
274
- /**
275
- * The keys nobody may write: `access: { write: [] }`, readable or not.
276
- *
277
- * Off `Insert` and `Update` for the same reason `excludedApiKeys` takes a
278
- * hidden property off all three — except that a field everyone can read but
279
- * nobody can write stays on `Row`. The server refuses one on any write with
280
- * `VALIDATION_EXCLUDED_FIELDS`, for every caller, `admin` included, so a
281
- * generated `create({ computed })` compiled and could only ever be a 400.
282
- *
283
- * A write rule naming *roles* is not this: some caller can write it, and one
284
- * generated shape cannot say which. A closed to-one relation's foreign key is:
285
- * the server refuses `reviewerId` exactly as it refuses `reviewer`.
286
- */
287
- function unwritableKeys(collection) {
288
- return closedNames(collection, "write");
289
- }
290
- function generateTypedefs(input) {
291
- const collections = sortCollectionsBySlug(input);
292
- const accessors = buildAccessors(collections);
293
- const lines = [
294
- "/**",
295
- " * This file was auto-generated by Rebase.",
296
- " * Do not make direct changes to the file.",
297
- " */",
298
- "",
299
- "export interface Database {"
300
- ];
301
- for (const collection of collections) {
302
- const properties = collection.properties ?? {};
303
- let resolvedRelations = {};
304
- try {
305
- resolvedRelations = resolveCollectionRelations(collection);
306
- } catch (e) {
307
- console.warn(`[rebase] Could not resolve the relations of "${collection.slug}", so its generated type has no relation fields and none of their foreign-key columns. This is usually a circular import in the collection files — make sure the target is \`() => otherCollection\` and not evaluated at module load.\n ${e instanceof Error ? e.message : String(e)}`);
308
- }
309
- const declared = getDeclaredSubcollections(collection);
310
- let subcollectionCount = 0;
311
- if (declared) try {
312
- subcollectionCount = declared().length;
313
- } catch {
314
- subcollectionCount = -1;
315
- }
316
- if (subcollectionCount !== 0) console.warn(`[rebase] "${collection.slug}" declares ${subcollectionCount < 0 ? "" : `${subcollectionCount} `}subcollection(s), which are not part of the generated Database: they are reached over a nested path (\`data/${collection.slug}/<id>/<relation>\`), not as a top-level accessor. Register a subcollection as a collection of its own if you want a typed accessor for it.`);
317
- lines.push(` ${emitKey(accessors.get(collection.slug))}: {`);
318
- lines.push(" Row: {");
319
- const emittedKeys = /* @__PURE__ */ new Set();
320
- const excluded = excludedApiKeys(collection);
321
- for (const key of excluded) emittedKeys.add(key);
322
- for (const [key, rawProp] of Object.entries(properties)) {
323
- const prop = rawProp;
324
- if (prop.type === "relation") continue;
325
- if (excluded.has(key)) continue;
326
- const tsType = propertyToTypeScriptType(prop);
327
- const isRequired = Boolean(prop.validation?.required) || isPrimaryKey(prop);
328
- lines.push(line(key, isRequired ? tsType : `${tsType} | null`, !isRequired));
329
- emittedKeys.add(key);
330
- }
331
- for (const [relKey, relation] of Object.entries(resolvedRelations)) if (relation.kind === "belongsTo" && relation.localKey) {
332
- const fkKey = fieldKeyForColumn(collection, relation.localKey);
333
- if (emittedKeys.has(fkKey)) continue;
334
- const fkType = foreignKeyType(relation);
335
- const shadowedByInclude = relKey === fkKey;
336
- const tsType = shadowedByInclude ? `${fkType} | ${includedRelationType(relation, accessors)}` : fkType;
337
- const isRequired = isRelationRequired(collection, relation) && !shadowedByInclude;
338
- lines.push(line(fkKey, isRequired ? tsType : `${tsType} | null`, !isRequired));
339
- emittedKeys.add(fkKey);
340
- }
341
- for (const [key, relation] of Object.entries(resolvedRelations)) {
342
- if (emittedKeys.has(key)) continue;
343
- lines.push(line(key, includedRelationType(relation, accessors), true));
344
- emittedKeys.add(key);
345
- }
346
- for (const [key, rawProp] of Object.entries(properties)) {
347
- if (rawProp.type !== "relation") continue;
348
- if (emittedKeys.has(key)) continue;
349
- lines.push(line(key, "Record<string, unknown>", true));
350
- emittedKeys.add(key);
351
- }
352
- lines.push(" };");
353
- lines.push(" Insert: {");
354
- const notWritable = /* @__PURE__ */ new Set([...excluded, ...unwritableKeys(collection)]);
355
- emittedKeys.clear();
356
- for (const key of notWritable) emittedKeys.add(key);
357
- for (const [key, rawProp] of Object.entries(properties)) {
358
- const prop = rawProp;
359
- if (prop.type === "relation") continue;
360
- if (notWritable.has(key)) continue;
361
- const tsType = propertyToTypeScriptType(prop);
362
- const isOptional = !prop.validation?.required || isAutoAssignedId(prop) || Boolean(prop.databaseDefault);
363
- lines.push(line(key, writableType(prop, tsType), isOptional));
364
- emittedKeys.add(key);
365
- }
366
- const eitherSpelling = emitWritableRelations(lines, collection, properties, resolvedRelations, emittedKeys, false);
367
- lines.push(eitherSpelling.length === 0 ? " };" : ` } & ${eitherSpelling.join(" & ")};`);
368
- lines.push(" Update: {");
369
- emittedKeys.clear();
370
- for (const key of notWritable) emittedKeys.add(key);
371
- for (const [key, rawProp] of Object.entries(properties)) {
372
- const prop = rawProp;
373
- if (prop.type === "relation") continue;
374
- if (isPrimaryKey(prop)) continue;
375
- if (notWritable.has(key)) continue;
376
- lines.push(line(key, writableType(prop, propertyToTypeScriptType(prop)), true));
377
- emittedKeys.add(key);
378
- }
379
- emitWritableRelations(lines, collection, properties, resolvedRelations, emittedKeys, true);
380
- lines.push(" };");
381
- const includable = Object.entries(resolvedRelations).filter(([key]) => !excluded.has(key));
382
- if (includable.length === 0) lines.push(" Relations: Record<never, never>;");
383
- else lines.push(" Relations: {");
384
- for (const [key, relation] of includable) {
385
- const slug = resolveTargetCollection(relation)?.slug ?? relation.targetSlug;
386
- const accessor = slug ? accessors.get(slug) : void 0;
387
- lines.push(` ${emitKey(key)}: ${accessor ? emitString(accessor) : "never"};`);
388
- }
389
- if (includable.length > 0) lines.push(" };");
390
- lines.push(` Slug: ${emitString(collection.slug)};`);
391
- lines.push(" };");
392
- }
393
- lines.push("}");
394
- lines.push("");
395
- lines.push("export type CollectionName = keyof Database;");
396
- lines.push("");
397
- lines.push("export const collectionsDictionary = {");
398
- for (const collection of collections) lines.push(` ${emitKey(accessors.get(collection.slug))}: ${emitString(collection.slug)},`);
399
- lines.push("} as const;");
400
- lines.push("");
401
- lines.push("export type CollectionsDictionary = typeof collectionsDictionary;");
402
- lines.push("");
403
- lines.push(...includeHelperLines());
404
- return lines.join("\n");
405
- }
406
- /**
407
- * The `include` type machinery, emitted into the generated file.
408
- *
409
- * It lives here rather than in `@rebasepro/types` because it is the *graph*
410
- * that makes it work, and the graph only exists once a project's collections
411
- * have been generated. `IncludeSpec` in `@rebasepro/types` is deliberately
412
- * unconstrained — a hand-written row type has no relations in it to check
413
- * against — and these narrow it for a project that does have them.
414
- *
415
- * Two things a caller gets:
416
- *
417
- * - `IncludeFor<"posts">` — an include whose keys are relations that exist,
418
- * recursively, so `include: { comments: { include: { authr: true } } }` is a
419
- * compile error rather than a 400 at runtime.
420
- * - `RowWith<"posts", I>` — the row a read with that include returns, where
421
- * every included relation is **present** rather than optional. `Row` types a
422
- * relation as optional because it is absent from every read that did not ask
423
- * for it; once a read has asked, `row.author.name` should not need a `?.`.
424
- *
425
- * The depth bound matches the server's (`MAX_INCLUDE_DEPTH`), and is spelled as
426
- * a decrementing tuple because TypeScript has no arithmetic — `Prev[3]` is `2`.
427
- * Without a bound, a self-referencing relation makes the type infinite and the
428
- * compiler gives up with "type instantiation is excessively deep".
429
- */
430
- function includeHelperLines() {
431
- return [
432
- "/** Which collection each of `A`'s relations reaches. */",
433
- "export type RelationsOf<A extends CollectionName> =",
434
- " Database[A] extends { Relations: infer R } ? R : Record<string, never>;",
435
- "",
436
- "/** The names of `A`'s relations. */",
437
- "export type RelationKeys<A extends CollectionName> = keyof RelationsOf<A> & string;",
438
- "",
439
- "/** The collection a relation reaches, or `never` when it left this project. */",
440
- "export type RelationTarget<A extends CollectionName, K extends RelationKeys<A>> =",
441
- " RelationsOf<A>[K] extends CollectionName ? RelationsOf<A>[K] : never;",
442
- "",
443
- "/** Counts `IncludeFor` down; TypeScript has no arithmetic. */",
444
- "type Prev = [never, 0, 1, 2, 3];",
445
- "",
446
- "/**",
447
- " * Per-relation options, minus `include` — which `IncludeFor` supplies at",
448
- " * the next depth so the nested keys are checked against the *target's*",
449
- " * relations rather than this collection's.",
450
- " */",
451
- "export interface IncludeOptionsFor<A extends CollectionName, K extends RelationKeys<A>, D extends number> {",
452
- " limit?: number;",
453
- " where?: Record<string, unknown>;",
454
- " logical?: unknown;",
455
- " orderBy?: unknown;",
456
- " fields?: string[];",
457
- " include?: RelationTarget<A, K> extends CollectionName",
458
- " ? IncludeFor<RelationTarget<A, K>, Prev[D]>",
459
- " : never;",
460
- "}",
461
- "",
462
- "/**",
463
- " * An `include` for collection `A`: its relation names, dotted paths, or the",
464
- " * parametrised tree — with every key checked against the relations that",
465
- " * actually exist, at every level.",
466
- " */",
467
- "export type IncludeFor<A extends CollectionName, D extends number = 3> =",
468
- " D extends 0",
469
- " ? never",
470
- " : | readonly (RelationKeys<A> | \"*\")[]",
471
- " | { [K in RelationKeys<A>]?: true | IncludeOptionsFor<A, K, D> };",
472
- "",
473
- "/** The relation names an include asks for at the top level. */",
474
- "type IncludedKeys<A extends CollectionName, I> =",
475
- " I extends readonly (infer K)[]",
476
- " ? Extract<K, RelationKeys<A>>",
477
- " : Extract<keyof I, RelationKeys<A>>;",
478
- "",
479
- "/**",
480
- " * The row a read with include `I` returns: `Row`, with every included",
481
- " * relation made **required**.",
482
- " *",
483
- " * `Row` types a relation as optional because it is absent from every read",
484
- " * that did not name it. Once a read has named it, it is there — and having",
485
- " * to write `row.author?.name` after asking for the author is the type",
486
- " * describing a possibility the query already ruled out.",
487
- " */",
488
- "export type RowWith<A extends CollectionName, I> =",
489
- " Database[A][\"Row\"] & Required<Pick<Database[A][\"Row\"], IncludedKeys<A, I> & keyof Database[A][\"Row\"]>>;",
490
- ""
491
- ];
492
- }
493
- /**
494
- * The two ways a write can name a `belongsTo` target, both of which the server
495
- * accepts: the foreign key under its own wire name (`{ authorId: 5 }`, which
496
- * passes through to the `author_id` column untouched) and the relation
497
- * *property* (`{ author: 5 }`, which the write transformer maps onto that
498
- * column).
499
- *
500
- * Only the first was generated, so the documented and idiomatic write shape was
501
- * a type error.
502
- *
503
- * The second form is emitted under the **property key**, not the resolved
504
- * relation name, because that is what the transformer keys off: it looks the
505
- * payload key up in `properties` and only treats it as a relation if what it
506
- * finds there is one. A relation whose `relationName` differs from its property
507
- * key is reachable as the property and not as the name, so emitting the name
508
- * would have offered a key that writes to a column that does not exist.
509
- *
510
- * A **required** `belongsTo` is satisfied by either spelling — the server's
511
- * required check reads both (`write-validation.ts`). Emitting each name as a
512
- * required key made a create name the same row twice to compile. So on an
513
- * `Insert` both names go in optional, and the requirement comes back as one
514
- * returned `({ authorId: T } | { author: T })` for the caller to intersect
515
- * with the object. Both stay in the object so `keyof Insert` still names them.
516
- */
517
- function emitWritableRelations(lines, collection, properties, resolvedRelations, emittedKeys, allOptional) {
518
- const spellings = /* @__PURE__ */ new Map();
519
- const addSpelling = (relation, key) => {
520
- if (emittedKeys.has(key)) return;
521
- const keys = spellings.get(relation) ?? [];
522
- if (!keys.includes(key)) keys.push(key);
523
- spellings.set(relation, keys);
524
- };
525
- for (const relation of Object.values(resolvedRelations)) if (relation.kind === "belongsTo" && relation.localKey) addSpelling(relation, fieldKeyForColumn(collection, relation.localKey));
526
- for (const [key, rawProp] of Object.entries(properties)) {
527
- if (rawProp.type !== "relation") continue;
528
- const relation = findRelation(resolvedRelations, key);
529
- if (relation?.kind === "belongsTo" && relation.localKey) addSpelling(relation, key);
530
- }
531
- const eitherSpelling = [];
532
- const emit = (key, relation) => {
533
- if (emittedKeys.has(key)) return;
534
- const required = isRelationRequired(collection, relation);
535
- const type = required ? foreignKeyType(relation) : `${foreignKeyType(relation)} | null`;
536
- const names = spellings.get(relation) ?? [key];
537
- const oneOfSeveral = required && !allOptional && names.length > 1;
538
- lines.push(line(key, type, allOptional || !required || oneOfSeveral));
539
- emittedKeys.add(key);
540
- if (oneOfSeveral && names[0] === key) eitherSpelling.push(`(${names.map((name) => `{ ${emitKey(name)}: ${type} }`).join(" | ")})`);
541
- };
542
- for (const relation of Object.values(resolvedRelations)) if (relation.kind === "belongsTo" && relation.localKey) emit(fieldKeyForColumn(collection, relation.localKey), relation);
543
- for (const [key, rawProp] of Object.entries(properties)) {
544
- if (rawProp.type !== "relation") continue;
545
- const relation = findRelation(resolvedRelations, key);
546
- if (relation?.kind === "belongsTo" && relation.localKey) emit(key, relation);
547
- }
548
- for (const [key, rawProp] of Object.entries(properties)) {
549
- if (rawProp.type !== "relation" || emittedKeys.has(key)) continue;
550
- const relation = findRelation(resolvedRelations, key);
551
- const toOneWritable = relation?.kind === "hasOne" || relation?.kind === "via" && relation.cardinality === "one" && relation.writable;
552
- if (!relation || !toOneWritable) continue;
553
- lines.push(line(key, `${foreignKeyType(relation)} | null`, true));
554
- emittedKeys.add(key);
555
- }
556
- for (const [key, relation] of Object.entries(resolvedRelations)) {
557
- if (relation.cardinality !== "many" || !relation.writable) continue;
558
- if (emittedKeys.has(key)) continue;
559
- const fk = foreignKeyType(relation);
560
- const pivot = relation.kind === "manyToMany" ? pivotType(relation.through.properties, "write") : void 0;
561
- const element = `${fk} | { id: ${fk}${pivot ? `; _pivot?: ${pivot}` : ""} }`;
562
- lines.push(line(key, `Array<${element}>`, true));
563
- emittedKeys.add(key);
564
- }
565
- return eitherSpelling;
566
- }
567
- /**
568
- * The `_pivot` a many-to-many link carries: the junction's payload columns,
569
- * typed as a row's columns are on a read and as a write's on a write. `undefined`
570
- * when the junction declares none, so there is no `_pivot` to name.
571
- */
572
- function pivotType(pivotProperties, direction) {
573
- const entries = Object.entries(pivotProperties);
574
- if (entries.length === 0) return void 0;
575
- return `{ ${entries.map(([key, rawProp]) => {
576
- const prop = rawProp;
577
- const tsType = propertyToTypeScriptType(prop);
578
- const required = Boolean(prop.validation?.required);
579
- const type = direction === "write" ? writableType(prop, tsType) : required ? tsType : `${tsType} | null`;
580
- return `${emitKey(key)}${required && direction === "read" ? "" : "?"}: ${type};`;
581
- }).join(" ")} }`;
582
- }
583
- //#endregion
584
- //#region src/schema/doctor.ts
585
- /**
586
- * Rebase Schema Doctor — Three-way schema drift detection.
587
- *
588
- * Compares:
589
- * 1. Collection definitions → Generated Drizzle schema (staleness check)
590
- * 2. Collection definitions → Live PostgreSQL database (structural drift)
591
- *
592
- * Run via: rebase doctor
593
- */
594
- var doctor_exports = /* @__PURE__ */ __exportAll({
595
- checkCollectionsVsDatabase: () => checkCollectionsVsDatabase,
596
- checkCollectionsVsSchema: () => checkCollectionsVsSchema,
597
- checkCollectionsVsSdk: () => checkCollectionsVsSdk,
598
- generatedSchemaDriftIssues: () => generatedSchemaDriftIssues,
599
- getExpectedColumnType: () => getExpectedColumnType,
600
- junctionKeyIssues: () => junctionKeyIssues,
601
- loadCollections: () => loadCollections,
602
- missingExtensionIssues: () => missingExtensionIssues,
603
- orphanedJunctionIssues: () => orphanedJunctionIssues,
604
- primaryKeyIssues: () => primaryKeyIssues,
605
- renderReport: () => renderReport,
606
- runDoctor: () => runDoctor,
607
- schemaStampIssues: () => schemaStampIssues,
608
- typeMismatchFix: () => typeMismatchFix
609
- });
610
- /**
611
- * Resolve the SQL column name for a property.
612
- * Uses the explicit `columnName` when set (e.g. from introspection),
613
- * falling back to `toSnakeCase(propName)` for manually-authored collections.
614
- */
615
- var resolveColumnName = (propName, prop) => {
616
- if (prop && "columnName" in prop && typeof prop.columnName === "string") return prop.columnName;
617
- return toSnakeCase(propName);
618
- };
619
- /**
620
- * How `information_schema.columns.data_type` spells a planned column type.
621
- *
622
- * The catalogue's names are its own — `character varying`, not `varchar`;
623
- * `ARRAY` for every array whatever its element; `USER-DEFINED` for an enum, a
624
- * `vector`, and anything else identified by name rather than by shape. So the
625
- * translation has to exist somewhere. What must *not* exist twice is the step
626
- * before it: which column a property compiles to.
627
- *
628
- * This function was that second step — a fourth copy of the property switch,
629
- * kept "in sync" with the generators by a comment, and already out of step
630
- * (`geopoint` answered `null` here, so the one type that was genuinely
631
- * unpersistable was the one the doctor never checked). It reads the schema plan
632
- * now.
633
- */
634
- var INFORMATION_SCHEMA_NAMES = {
635
- text: "text",
636
- varchar: "character varying",
637
- char: "character",
638
- uuid: "uuid",
639
- enum: "USER-DEFINED",
640
- smallint: "smallint",
641
- integer: "integer",
642
- bigint: "bigint",
643
- smallserial: "smallint",
644
- serial: "integer",
645
- bigserial: "bigint",
646
- real: "real",
647
- doublePrecision: "double precision",
648
- numeric: "numeric",
649
- boolean: "boolean",
650
- timestamptz: "timestamp with time zone",
651
- date: "date",
652
- time: "time without time zone",
653
- json: "json",
654
- jsonb: "jsonb",
655
- vector: "USER-DEFINED",
656
- bytea: "bytea",
657
- tsvector: "USER-DEFINED",
658
- array: "ARRAY"
659
- };
660
- /**
661
- * The `data_type` the database should report for a property's column, or `null`
662
- * when there is nothing to compare.
663
- *
664
- * `null` covers the two honest cases: a `relation`, whose column is derived from
665
- * the relation rather than from the property, and a configuration the planner
666
- * refuses outright — which is a problem the doctor's other phases report with a
667
- * message, not a type mismatch to invent one for.
668
- */
669
- function getExpectedColumnType(prop) {
670
- if (prop.type === "relation") return null;
671
- const collection = {
672
- slug: "__doctor__",
673
- table: "__doctor__",
674
- properties: { __column__: prop }
675
- };
676
- try {
677
- return INFORMATION_SCHEMA_NAMES[columnPgType("__column__", prop, collection, () => void 0).kind];
678
- } catch {
679
- return null;
680
- }
681
- }
682
- /**
683
- * Re-exported so callers keep importing it from here, but the implementation is
684
- * now shared with the runtime and the generators — a doctor that disagreed with
685
- * the policy generator about which files are collections would compare the
686
- * wrong thing.
687
- */
688
- async function loadCollections(collectionsPath) {
689
- return loadCollectionsFromDirectory(collectionsPath);
690
- }
691
- async function checkCollectionsVsSchema(collections, schemaFilePath) {
692
- const issues = [];
693
- if (!fs$1.existsSync(schemaFilePath)) {
694
- issues.push({
695
- severity: "error",
696
- category: "schema_stale",
697
- message: "Generated schema file does not exist.",
698
- fix: "Run `rebase schema generate`"
699
- });
700
- return {
701
- passed: false,
702
- issues
703
- };
704
- }
705
- const postgresCollections = relationalCollections(collections);
706
- if (postgresCollections.length === 0) return {
707
- passed: true,
708
- issues
709
- };
710
- try {
711
- const differences = compareGeneratedDeclarations(generateSchema(postgresCollections), await promises.readFile(schemaFilePath, "utf-8"));
712
- if (differences.length > 0) issues.push({
713
- severity: "warning",
714
- category: "schema_stale",
715
- message: `Generated schema is out of date — collection definitions have changed since last generation. Differs in: ${describeDeclarationDifferences(differences)}.`,
716
- fix: "Run `rebase schema generate`"
717
- });
718
- } catch (err) {
719
- const message = err instanceof Error ? err.message : String(err);
720
- issues.push({
721
- severity: "warning",
722
- category: "schema_stale",
723
- message: `Could not regenerate schema for comparison: ${message}`,
724
- fix: "Run `rebase schema generate` to verify"
725
- });
726
- }
727
- return {
728
- passed: issues.length === 0,
729
- issues
730
- };
731
- }
732
- async function checkCollectionsVsSdk(collections, sdkFilePath) {
733
- const issues = [];
734
- if (!fs$1.existsSync(sdkFilePath)) {
735
- issues.push({
736
- severity: "info",
737
- category: "sdk_not_generated",
738
- message: "Typed SDK not generated (optional).",
739
- fix: "Run `rebase generate-sdk` if you want typed collection access"
740
- });
741
- return {
742
- passed: true,
743
- issues,
744
- notApplicable: "not generated (optional)"
745
- };
746
- }
747
- try {
748
- const expectedSdk = generateTypedefs(collections);
749
- const actualSdk = await promises.readFile(sdkFilePath, "utf-8");
750
- const normalize = (s) => s.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "").replace(/\s+/g, " ").trim();
751
- if (normalize(expectedSdk) !== normalize(actualSdk)) issues.push({
752
- severity: "warning",
753
- category: "sdk_stale",
754
- message: "Generated SDK types are out of date — collection definitions have changed since last SDK generation.",
755
- fix: "Run `rebase generate-sdk`"
756
- });
757
- } catch (err) {
758
- const message = err instanceof Error ? err.message : String(err);
759
- if (err instanceof Error && err.name === "CodegenError") issues.push({
760
- severity: "error",
761
- category: "sdk_ungeneratable",
762
- message: `The typed SDK cannot be generated from these collections: ${message}`,
763
- fix: "Fix the collection definitions named above, then run `rebase generate-sdk`"
764
- });
765
- else issues.push({
766
- severity: "warning",
767
- category: "sdk_stale",
768
- message: `Could not regenerate SDK types for comparison: ${message}`,
769
- fix: "Run `rebase generate-sdk` to verify"
770
- });
771
- }
772
- return {
773
- passed: issues.length === 0,
774
- issues
775
- };
776
- }
777
- /**
778
- * Extensions the collections need, that the database does not have installed.
779
- *
780
- * Only `vector` today, and only because a `{ type: "vector" }` property plans a
781
- * column of a type that will not exist. Rebase installs it only where a project
782
- * has said it may (`database({ extensions: ["vector"] })`), so the absence is
783
- * often correct configuration and a wrong deployment — which is exactly why the
784
- * report has to name it rather than the first failing INSERT.
785
- *
786
- * Exported for its test.
787
- */
788
- function missingExtensionIssues(collections, installed) {
789
- if (!collections.some((collection) => Object.values(collection.properties ?? {}).some((property) => property?.type === "vector")) || installed.has("vector")) return [];
790
- return [{
791
- severity: "error",
792
- category: "missing_table",
793
- message: "A collection declares a `{ type: \"vector\" }` property and the pgvector extension is not installed on this database.",
794
- 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;"
795
- }];
796
- }
797
- /**
798
- * The stamp the runtime wrote, against the collections on disk.
799
- *
800
- * A stamp that disagrees means this database was provisioned from a different
801
- * set of collections than the ones in this checkout — a colleague's branch, an
802
- * older deploy, a tenant somebody else migrated. Everything else in this report
803
- * is then describing a schema somebody else created, which is worth knowing
804
- * before acting on any of it.
805
- *
806
- * A warning, not an error, and never a direction: the stamp is a hash, so it
807
- * can say the two disagree and never which is ahead. `null` — never stamped —
808
- * is not a finding: every database provisioned before the stamp existed reads
809
- * that way, and so does every fresh one.
810
- */
811
- async function schemaStampIssues(pool, collections) {
812
- let stamped = null;
813
- try {
814
- if (!(await pool.query(`SELECT to_regclass('"rebase"."schema_meta"') IS NOT NULL AS present`)).rows[0]?.present) return [];
815
- stamped = (await pool.query(`SELECT value FROM "rebase"."schema_meta" WHERE key = 'collections_schema_version' LIMIT 1`)).rows[0]?.value ?? null;
816
- } catch {
817
- return [];
818
- }
819
- if (!stamped) return [];
820
- const expected = computeSchemaVersion(collections);
821
- if (stamped === expected) return [];
822
- return [{
823
- severity: "warning",
824
- category: "schema_stale",
825
- message: `This database was provisioned from a different set of collections (stamp ${stamped.slice(0, 12)}…, this checkout computes ${expected.slice(0, 12)}…).`,
826
- 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 collections."
827
- }];
828
- }
829
- /** `"public"."posts"` — quoted, for a statement the reader will paste. */
830
- var quotedTable = (schema, table) => `"${schema}"."${table}"`;
831
- /**
832
- * What to do about a column whose type is not the one the collection plans.
833
- *
834
- * Both ways out, because the doctor cannot know which side is right: the
835
- * property moved, or the database did. Putting the property back always clears
836
- * the finding; converting the column clears it when every value converts.
837
- */
838
- function typeMismatchFix(schema, table, column, actual, planned) {
839
- const back = `Either put the property back to the column's type (${actual}), or`;
840
- if (!planned) return `${back} run a migration that converts the column.`;
841
- const type = renderPgType(planned);
842
- 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};`;
843
- }
844
- /**
845
- * The table's primary key against the one the collection reads it by.
846
- *
847
- * Rebase addresses a row by the key the plan names — the `isId` property, or
848
- * the implicit `id` — so a table keyed on other columns, or on none, serves
849
- * reads and writes against a key that does not hold. An error, because that is
850
- * what it is at runtime.
851
- */
852
- function primaryKeyIssues(tablePlan, dbPk, displayName) {
853
- const expected = tablePlan.primaryKey;
854
- if (dbPk.length === expected.length && [...dbPk].sort().join("\0") === [...expected].sort().join("\0")) return [];
855
- const table = quotedTable(tablePlan.schema, tablePlan.table);
856
- const keyList = expected.map((c) => `"${c}"`).join(", ");
857
- if (dbPk.length === 0) return [{
858
- severity: "error",
859
- category: "primary_key_mismatch",
860
- table: displayName,
861
- expected: expected.join(", "),
862
- actual: "(none)",
863
- message: `Table "${displayName}" has no primary key; the collection reads its rows by ${keyList}.`,
864
- fix: `ALTER TABLE ${table} ADD PRIMARY KEY (${keyList});`
865
- }];
866
- const only = expected.some((column) => !dbPk.includes(column)) ? "only " : "";
867
- 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}.`;
868
- return [{
869
- severity: "error",
870
- category: "primary_key_mismatch",
871
- table: displayName,
872
- expected: expected.join(", "),
873
- actual: dbPk.join(", "),
874
- message: `Table "${displayName}" is keyed on (${dbPk.join(", ")}), but the collection reads its rows by ${keyList}.`,
875
- fix
876
- }];
877
- }
878
- /**
879
- * A junction's two key columns: present, typed like the keys they point at,
880
- * and the table keyed on the pair. Order is not compared — boot and `db push`
881
- * have built the key in both orders, and either one serves the same rows.
882
- */
883
- function junctionKeyIssues(junctionPlan, dbColumns, dbPk, displayName) {
884
- const issues = [];
885
- const byName = new Map(dbColumns.map((c) => [c.column_name, c]));
886
- for (const column of junctionPlan.columns) {
887
- const dbCol = byName.get(column.column);
888
- if (!dbCol) {
889
- issues.push({
890
- severity: "error",
891
- category: "missing_column",
892
- table: displayName,
893
- column: column.column,
894
- message: `Junction table "${displayName}" has no "${column.column}" column.`,
895
- fix: "Run `rebase db push` or `rebase db generate && rebase db migrate`"
896
- });
897
- continue;
898
- }
899
- const expected = INFORMATION_SCHEMA_NAMES[column.type.kind];
900
- if (dbCol.data_type !== expected) issues.push({
901
- severity: "warning",
902
- category: "type_mismatch",
903
- table: displayName,
904
- column: column.column,
905
- expected,
906
- actual: dbCol.data_type,
907
- message: `Junction column "${column.column}" in "${displayName}" is ${dbCol.data_type}, but the key it points at is ${expected}.`,
908
- fix: typeMismatchFix(junctionPlan.schema, junctionPlan.table, column.column, dbCol.data_type, column.type)
909
- });
910
- }
911
- issues.push(...primaryKeyIssues(junctionPlan, dbPk, displayName));
912
- return issues;
913
- }
914
- /** A table as the other issues name it: bare in `public`, `schema.table` elsewhere. */
915
- function displayTableOf(difference, collections) {
916
- const collection = difference.collection ? collections.find((c) => c.slug === difference.collection) : void 0;
917
- const schema = collection && isPostgresCollectionConfig(collection) ? collection.schema : void 0;
918
- return schema && schema !== "public" ? `${schema}.${difference.table}` : difference.table;
919
- }
920
- /** Which of the doctor's own categories already says what a boot difference says. */
921
- var COVERING_CATEGORY = {
922
- "missing-table": "missing_table",
923
- "missing-column": "missing_column",
924
- type: "type_mismatch",
925
- nullability: "nullability_mismatch",
926
- "extra-column": "extra_column"
927
- };
928
- /** What to do about one boot difference, said the way the boot warning says it. */
929
- function generatedDriftFix(difference) {
930
- switch (difference.kind) {
931
- 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 the collections 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 the collections changed since schema.generated.ts was written, run `rebase schema generate` first.";
932
- 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 the collections changed since schema.generated.ts was written, run `rebase schema generate` first.";
933
- case "type": return "`rebase db push` converts it (it asks first when values may not convert), or a migration does. If the collections changed since schema.generated.ts was written, run `rebase schema generate` first.";
934
- case "missing-column": return "`rebase db push` adds it. If the collections changed since schema.generated.ts was written, run `rebase schema generate` first.";
935
- case "missing-table": return "Run `rebase db push` or `rebase db generate && rebase db migrate`";
936
- }
937
- }
938
- /**
939
- * Boot's drift warnings, as doctor issues — one per difference, in boot's own
940
- * words ({@link describeSchemaDifference}), and a warning, as boot raises them.
941
- *
942
- * Except where an issue the collections-side checks above already raised says
943
- * the same thing: a missing table, a missing column or a type mismatch on the
944
- * same column. Nullability and columns no collection declares are boot's alone;
945
- * the doctor never compared them, which is how it came to say "In sync" beside
946
- * a boot that had just warned about both.
947
- */
948
- function generatedSchemaDriftIssues(differences, already, collections) {
949
- const bare = (table) => table?.split(".").pop();
950
- 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));
951
- return differences.filter((difference) => !covered(difference)).map((difference) => ({
952
- severity: "warning",
953
- category: COVERING_CATEGORY[difference.kind],
954
- table: displayTableOf(difference, collections),
955
- ...difference.column ? { column: difference.column } : {},
956
- ...difference.generated ? { expected: difference.generated } : {},
957
- ...difference.live ? { actual: difference.live } : {},
958
- message: describeSchemaDifference(difference),
959
- fix: generatedDriftFix(difference)
960
- }));
961
- }
962
- /**
963
- * The collections whose tables the default database holds — the filter boot
964
- * applies before it reads the catalogue, for the same reason: a collection
965
- * routed to `database("analytics")` has no table here.
966
- */
967
- function defaultSourceCollections(collections) {
968
- return collections.filter((c) => !c.dataSource || c.dataSource === DEFAULT_DATA_SOURCE_KEY);
969
- }
970
- async function checkCollectionsVsDatabase(collections, databaseUrl, options = {}) {
971
- const issues = [];
972
- const pgModule = await import("pg");
973
- const { Pool } = pgModule.default ?? pgModule;
974
- const pool = new Pool({ connectionString: databaseUrl });
975
- const schemas = Array.from(/* @__PURE__ */ new Set([
976
- "public",
977
- "rebase",
978
- ...relationalCollections(collections).filter(isPostgresCollectionConfig).map((c) => c.schema).filter((s) => !!s)
979
- ]));
980
- try {
981
- const tablesResult = await pool.query(`SELECT table_schema, table_name
982
- FROM information_schema.tables
983
- WHERE table_schema = ANY($1) AND table_type = 'BASE TABLE'`, [schemas]);
984
- const existingTables = new Set(tablesResult.rows.map((r) => r.table_schema === "public" ? r.table_name : `${r.table_schema}.${r.table_name}`));
985
- const viewsResult = await pool.query(`SELECT n.nspname AS table_schema, c.relname AS table_name
986
- FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
987
- WHERE n.nspname = ANY($1) AND c.relkind IN ('v', 'm')`, [schemas]);
988
- const existingViews = new Set(viewsResult.rows.map((r) => r.table_schema === "public" ? r.table_name : `${r.table_schema}.${r.table_name}`));
989
- const extensionsResult = await pool.query("SELECT extname FROM pg_extension");
990
- const installedExtensions = new Set(extensionsResult.rows.map((r) => r.extname));
991
- issues.push(...missingExtensionIssues(collections, installedExtensions));
992
- issues.push(...await schemaStampIssues(pool, collections));
993
- const columnsResult = await pool.query(`SELECT table_schema, table_name, column_name, data_type, is_nullable, udt_name
994
- FROM information_schema.columns
995
- WHERE table_schema = ANY($1)
996
- ORDER BY table_schema, table_name, ordinal_position`, [schemas]);
997
- const columnsByTable = /* @__PURE__ */ new Map();
998
- for (const row of columnsResult.rows) {
999
- const tableSchema = row.table_schema;
1000
- const tableName = row.table_name;
1001
- const key = tableSchema === "public" ? tableName : `${tableSchema}.${tableName}`;
1002
- if (!columnsByTable.has(key)) columnsByTable.set(key, []);
1003
- columnsByTable.get(key).push(row);
1004
- }
1005
- const enumsResult = await pool.query(`SELECT n.nspname AS enum_schema, t.typname AS enum_name, e.enumlabel AS enum_value
1006
- FROM pg_type t
1007
- JOIN pg_namespace n ON n.oid = t.typnamespace
1008
- JOIN pg_enum e ON t.oid = e.enumtypid
1009
- ORDER BY n.nspname, t.typname, e.enumsortorder`);
1010
- const enumsByName = /* @__PURE__ */ new Map();
1011
- for (const row of enumsResult.rows) {
1012
- const key = `${row.enum_schema}.${row.enum_name}`;
1013
- if (!enumsByName.has(key)) enumsByName.set(key, []);
1014
- enumsByName.get(key).push(row.enum_value);
1015
- }
1016
- const pksResult = await pool.query(`SELECT n.nspname AS table_schema, c.relname AS table_name,
1017
- array_agg(a.attname::text ORDER BY array_position(i.indkey::int2[], a.attnum)) AS columns
1018
- FROM pg_index i
1019
- JOIN pg_class c ON c.oid = i.indrelid
1020
- JOIN pg_namespace n ON n.oid = c.relnamespace
1021
- JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY(i.indkey::int2[])
1022
- WHERE i.indisprimary AND n.nspname = ANY($1)
1023
- GROUP BY n.nspname, c.relname`, [schemas]);
1024
- const pksByTable = /* @__PURE__ */ new Map();
1025
- for (const row of pksResult.rows) pksByTable.set(row.table_schema === "public" ? row.table_name : `${row.table_schema}.${row.table_name}`, row.columns);
1026
- const fksResult = await pool.query(`SELECT
1027
- tc.constraint_name,
1028
- tc.table_schema,
1029
- tc.table_name,
1030
- kcu.column_name,
1031
- ccu.table_schema AS foreign_table_schema,
1032
- ccu.table_name AS foreign_table_name,
1033
- ccu.column_name AS foreign_column_name
1034
- FROM information_schema.table_constraints AS tc
1035
- JOIN information_schema.key_column_usage AS kcu
1036
- ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
1037
- JOIN information_schema.constraint_column_usage AS ccu
1038
- ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
1039
- WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = ANY($1)`, [schemas]);
1040
- const fksByTable = /* @__PURE__ */ new Map();
1041
- for (const row of fksResult.rows) {
1042
- const tableSchema = row.table_schema;
1043
- const tableName = row.table_name;
1044
- const key = tableSchema === "public" ? tableName : `${tableSchema}.${tableName}`;
1045
- if (!fksByTable.has(key)) fksByTable.set(key, []);
1046
- fksByTable.get(key).push(row);
1047
- }
1048
- const postgresCollections = relationalCollections(collections);
1049
- const junctionSpecs = resolveJunctionSpecs(postgresCollections);
1050
- let plan;
1051
- try {
1052
- plan = planSchema(postgresCollections);
1053
- } catch {
1054
- plan = void 0;
1055
- }
1056
- const tablePlans = new Map((plan?.tables ?? []).map((t) => [t.qualified, t]));
1057
- const checkedJunctions = /* @__PURE__ */ new Set();
1058
- for (const collection of postgresCollections) {
1059
- const tableName = getTableName(collection);
1060
- const schemaName = collection.schema || "public";
1061
- const fullTableName = schemaName === "public" ? tableName : `${schemaName}.${tableName}`;
1062
- if (isPostgresCollectionConfig(collection) && collection.view) {
1063
- if (!existingViews.has(fullTableName)) issues.push({
1064
- severity: "error",
1065
- category: "missing_table",
1066
- table: fullTableName,
1067
- message: `View "${fullTableName}" does not exist in the database.`,
1068
- fix: "Run `rebase db push` or `rebase db generate && rebase db migrate`"
1069
- });
1070
- continue;
1071
- }
1072
- if (!existingTables.has(fullTableName)) {
1073
- issues.push({
1074
- severity: "error",
1075
- category: "missing_table",
1076
- table: fullTableName,
1077
- message: `Table "${fullTableName}" does not exist in the database.`,
1078
- fix: "Run `rebase db push` or `rebase db generate && rebase db migrate`"
1079
- });
1080
- continue;
1081
- }
1082
- const dbColumns = columnsByTable.get(fullTableName) ?? [];
1083
- const dbColumnMap = new Map(dbColumns.map((c) => [c.column_name, c]));
1084
- const tablePlan = tablePlans.get(`${schemaName}.${tableName}`);
1085
- if (tablePlan) issues.push(...primaryKeyIssues(tablePlan, pksByTable.get(fullTableName) ?? [], fullTableName));
1086
- for (const [propName, prop] of Object.entries(collection.properties ?? {})) {
1087
- if (prop.type === "relation") {
1088
- const relation = findRelation(resolveCollectionRelations(collection), prop.relation?.relationName ?? propName);
1089
- if (relation?.kind === "belongsTo") {
1090
- const fkColName = relation.localKey;
1091
- if (!dbColumnMap.has(fkColName)) issues.push({
1092
- severity: "error",
1093
- category: "missing_column",
1094
- table: fullTableName,
1095
- column: fkColName,
1096
- message: `Foreign key column "${fkColName}" for relation "${propName}" is missing from table "${fullTableName}".`,
1097
- fix: "Run `rebase db push` or `rebase db generate && rebase db migrate`"
1098
- });
1099
- const tableFks = fksByTable.get(fullTableName) ?? [];
1100
- let targetTableName = "unknown";
1101
- let targetSchemaName = "public";
1102
- try {
1103
- const targetColl = relation.target();
1104
- targetTableName = getTableName(targetColl);
1105
- targetSchemaName = targetColl.schema || "public";
1106
- } catch {}
1107
- const hasFk = tableFks.some((fk) => fk.column_name === fkColName && fk.foreign_table_name === targetTableName && fk.foreign_table_schema === targetSchemaName);
1108
- if (dbColumnMap.has(fkColName) && !hasFk) issues.push({
1109
- severity: "warning",
1110
- category: "missing_foreign_key",
1111
- table: fullTableName,
1112
- column: fkColName,
1113
- message: `Column "${fkColName}" exists but has no FOREIGN KEY constraint referencing "${targetSchemaName === "public" ? targetTableName : `${targetSchemaName}.${targetTableName}`}".`,
1114
- fix: "Run `rebase db push` or add the constraint manually"
1115
- });
1116
- }
1117
- continue;
1118
- }
1119
- const colName = resolveColumnName(propName, prop);
1120
- const dbCol = dbColumnMap.get(colName);
1121
- if (!dbCol) {
1122
- issues.push({
1123
- severity: "error",
1124
- category: "missing_column",
1125
- table: fullTableName,
1126
- column: colName,
1127
- message: `Column "${colName}" is defined in collection "${collection.slug}" but missing from table "${fullTableName}".`,
1128
- fix: "Run `rebase db push` or `rebase db generate && rebase db migrate`"
1129
- });
1130
- continue;
1131
- }
1132
- const expectedType = getExpectedColumnType(prop);
1133
- if (expectedType) {
1134
- const actualType = dbCol.data_type;
1135
- let isMismatch = actualType !== expectedType;
1136
- if (prop.type === "vector" && dbCol.udt_name !== "vector") isMismatch = true;
1137
- if (prop.type === "array") {
1138
- const ap = prop;
1139
- let expectedColType = ap.columnType;
1140
- if (!expectedColType && ap.of && !Array.isArray(ap.of)) {
1141
- const ofProp = ap.of;
1142
- if (ofProp.type === "string") expectedColType = "text[]";
1143
- else if (ofProp.type === "number") expectedColType = ofProp.validation?.integer ? "integer[]" : "numeric[]";
1144
- else if (ofProp.type === "boolean") expectedColType = "boolean[]";
1145
- }
1146
- if (expectedColType && expectedColType.endsWith("[]")) if (actualType !== "ARRAY") isMismatch = true;
1147
- else {
1148
- const expectedUdt = expectedColType === "text[]" ? "_text" : expectedColType === "integer[]" ? "_int4" : expectedColType === "boolean[]" ? "_bool" : expectedColType === "numeric[]" ? "_numeric" : "";
1149
- if (expectedUdt && dbCol.udt_name !== expectedUdt) isMismatch = true;
1150
- }
1151
- }
1152
- if (isMismatch) {
1153
- const planned = tablePlan?.columns.find((c) => c.column === colName)?.type;
1154
- issues.push({
1155
- severity: "warning",
1156
- category: "type_mismatch",
1157
- table: fullTableName,
1158
- column: colName,
1159
- expected: prop.type === "vector" ? "vector" : expectedType,
1160
- actual: dbCol.udt_name === "vector" ? "vector" : actualType,
1161
- message: `Column "${colName}" in table "${fullTableName}": expected type "${prop.type === "vector" ? "vector" : expectedType}" but found "${dbCol.udt_name === "vector" ? "vector" : actualType}".`,
1162
- fix: typeMismatchFix(schemaName, tableName, colName, actualType, planned)
1163
- });
1164
- }
1165
- }
1166
- if (prop.type === "string" && prop.enum) {
1167
- const enumValues = prop.enum;
1168
- if (enumValues) {
1169
- const enumName = toPostgresIdentifier(`${tableName}_${colName}`);
1170
- const dbEnumValues = enumsByName.get(`${schemaName}.${enumName}`);
1171
- if (!dbEnumValues) issues.push({
1172
- severity: "warning",
1173
- category: "missing_enum",
1174
- table: fullTableName,
1175
- column: colName,
1176
- expected: enumName,
1177
- message: `Enum type "${schemaName}"."${enumName}" is defined in collection but not found in the database.`,
1178
- fix: "Run `rebase db push` or `rebase db generate && rebase db migrate`"
1179
- });
1180
- else {
1181
- const expectedValues = Array.isArray(enumValues) ? enumValues.map((v) => typeof v === "string" ? v : String(v.id)) : Object.keys(enumValues);
1182
- const missing = expectedValues.filter((v) => !dbEnumValues.includes(v));
1183
- const extra = dbEnumValues.filter((v) => !expectedValues.includes(v));
1184
- if (missing.length > 0 || extra.length > 0) {
1185
- const parts = [];
1186
- if (missing.length > 0) parts.push(`missing: ${missing.join(", ")}`);
1187
- if (extra.length > 0) parts.push(`extra in DB: ${extra.join(", ")}`);
1188
- issues.push({
1189
- severity: "warning",
1190
- category: "enum_value_mismatch",
1191
- table: fullTableName,
1192
- column: colName,
1193
- expected: expectedValues.join(", "),
1194
- actual: dbEnumValues.join(", "),
1195
- message: `Enum values for "${colName}" in table "${fullTableName}" are out of sync (${parts.join("; ")}).`,
1196
- 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` : "")
1197
- });
1198
- }
1199
- }
1200
- }
1201
- }
1202
- }
1203
- const resolvedRelations = resolveCollectionRelations(collection);
1204
- for (const relation of Object.values(resolvedRelations)) if (isManyToMany(relation)) {
1205
- const junctionTable = relation.through.table.split(".").pop() ?? relation.through.table;
1206
- const junctionSchema = junctionSpecs.get(junctionTable)?.schema ?? "public";
1207
- const fullJunctionTable = junctionSchema === "public" ? junctionTable : `${junctionSchema}.${junctionTable}`;
1208
- if (!existingTables.has(fullJunctionTable)) issues.push({
1209
- severity: "error",
1210
- category: "missing_table",
1211
- table: fullJunctionTable,
1212
- message: `Junction table "${fullJunctionTable}" for many-to-many relation "${relation.relationName}" is missing.`,
1213
- fix: "Run `rebase db push` or `rebase db generate && rebase db migrate`"
1214
- });
1215
- else if (!checkedJunctions.has(fullJunctionTable)) {
1216
- checkedJunctions.add(fullJunctionTable);
1217
- const junctionPlan = tablePlans.get(`${junctionSchema}.${junctionTable}`);
1218
- if (junctionPlan) issues.push(...junctionKeyIssues(junctionPlan, columnsByTable.get(fullJunctionTable) ?? [], pksByTable.get(fullJunctionTable) ?? [], fullJunctionTable));
1219
- }
1220
- }
1221
- }
1222
- if (plan) issues.push(...orphanedJunctionIssues(plan, columnsByTable, pksByTable, fksByTable));
1223
- if (options.generated) {
1224
- const differences = await readGeneratedSchemaDrift({
1225
- client: pool,
1226
- generated: options.generated,
1227
- collections: defaultSourceCollections(collections),
1228
- defaultSchema: "public"
1229
- });
1230
- issues.push(...generatedSchemaDriftIssues(differences, issues, collections));
1231
- }
1232
- } finally {
1233
- await pool.end();
1234
- }
1235
- return {
1236
- passed: !issues.some((issue) => issue.severity !== "info"),
1237
- issues
1238
- };
1239
- }
1240
- /**
1241
- * A `public` table in the junction shape that no collection declares.
1242
- *
1243
- * The shape is the planner's: exactly two columns, together the primary key,
1244
- * each a single-column foreign key to a collection's table. Renaming or
1245
- * removing a many-to-many leaves such a table behind — push and boot only
1246
- * create — with every link row still in it and nothing reading it.
1247
- *
1248
- * Info, never more: the table may be data somebody still wants. The remedy is
1249
- * shown, never run.
1250
- */
1251
- function orphanedJunctionIssues(plan, columnsByTable, pksByTable, fksByTable) {
1252
- const declared = new Set(plan.tables.map((table) => table.qualified));
1253
- const collectionTables = new Set(plan.tables.filter((table) => table.kind === "collection").map((table) => table.qualified));
1254
- const issues = [];
1255
- for (const [table, columns] of columnsByTable) {
1256
- if (table.includes(".") || declared.has(`public.${table}`)) continue;
1257
- if (columns.length !== 2 || (pksByTable.get(table) ?? []).length !== 2) continue;
1258
- const byConstraint = /* @__PURE__ */ new Map();
1259
- for (const fk of fksByTable.get(table) ?? []) {
1260
- const target = `${fk.foreign_table_schema}.${fk.foreign_table_name}`;
1261
- byConstraint.set(fk.constraint_name, [...byConstraint.get(fk.constraint_name) ?? [], {
1262
- column: fk.column_name,
1263
- target
1264
- }]);
1265
- }
1266
- const links = [...byConstraint.values()];
1267
- if (links.length !== 2 || links.some((link) => link.length !== 1)) continue;
1268
- if (new Set(links.map(([link]) => link.column)).size !== 2) continue;
1269
- if (!links.every(([link]) => collectionTables.has(link.target))) continue;
1270
- const targets = links.map(([link]) => link.target.replace(/^public\./, ""));
1271
- issues.push({
1272
- severity: "info",
1273
- category: "orphaned_junction",
1274
- table,
1275
- message: `Table "${table}" links "${targets[0]}" and "${targets[1]}" like a many-to-many junction, but no collection declares it — left behind by a renamed or removed relation?`,
1276
- fix: `DROP TABLE "public"."${table}";`
1277
- });
1278
- }
1279
- return issues;
1280
- }
1281
- function renderReport(report) {
1282
- out();
1283
- out(chalk.bold(" 🩺 Rebase Schema Doctor"));
1284
- out(chalk.gray(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"));
1285
- out();
1286
- renderPhase("Collections → Generated Schema", report.collectionsToSchema);
1287
- renderPhase("Collections → Database", report.schemaToDatabase);
1288
- renderPhase("Collections → SDK Types", report.collectionsToSdk);
1289
- out(chalk.gray(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"));
1290
- const { passed, skipped, notApplicable, warnings, errors } = report.summary;
1291
- const parts = [];
1292
- parts.push(chalk.green(`${passed} passed`));
1293
- if (skipped > 0) parts.push(chalk.yellow(`${skipped} skipped`));
1294
- if (notApplicable > 0) parts.push(chalk.gray(`${notApplicable} not applicable`));
1295
- if (warnings > 0) parts.push(chalk.yellow(`${warnings} warnings`));
1296
- if (errors > 0) parts.push(chalk.red(`${errors} errors`));
1297
- out(` Summary: ${parts.join(", ")}`);
1298
- out();
1299
- if (errors > 0) out(chalk.red.bold(" ✗ Schema drift detected. Run the suggested fixes above."));
1300
- else if (warnings > 0) out(chalk.yellow.bold(" ⚠ Minor issues detected. Consider running the suggested fixes."));
1301
- 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.`));
1302
- else out(chalk.green.bold(" ✓ All schemas are in sync!"));
1303
- out();
1304
- }
1305
- function renderPhase(label, phase) {
1306
- if (phase.skipped) {
1307
- out(` ${chalk.yellow("⏭")} ${label}: ${chalk.yellow(`skipped (${phase.skipped})`)}`);
1308
- out();
1309
- return;
1310
- }
1311
- if (phase.notApplicable) {
1312
- out(` ${chalk.gray("➖")} ${label}: ${chalk.gray(phase.notApplicable)}`);
1313
- for (const issue of phase.issues.filter((i) => i.severity === "info")) out(` ${chalk.gray(issue.fix)}`);
1314
- out();
1315
- return;
1316
- }
1317
- const issues = phase.issues;
1318
- const errorCount = issues.filter((i) => i.severity === "error").length;
1319
- const warnCount = issues.filter((i) => i.severity === "warning").length;
1320
- const infoIssues = issues.filter((i) => i.severity === "info");
1321
- if (errorCount === 0 && warnCount === 0) out(` ${chalk.green("✅")} ${label}: ${chalk.green("In sync")}`);
1322
- else {
1323
- const parts = [];
1324
- if (errorCount > 0) parts.push(`${errorCount} error${errorCount > 1 ? "s" : ""}`);
1325
- if (warnCount > 0) parts.push(`${warnCount} warning${warnCount > 1 ? "s" : ""}`);
1326
- out(` ${chalk.yellow("⚠️")} ${label}: ${chalk.yellow(parts.join(", "))}`);
1327
- }
1328
- out();
1329
- for (const issue of infoIssues) {
1330
- const fixPart = issue.fix ? chalk.gray(` — ${issue.fix}`) : "";
1331
- out(` ${chalk.gray("ℹ")} ${chalk.gray(issue.message)}${fixPart}`);
1332
- out();
1333
- }
1334
- for (const issue of issues.filter((i) => i.severity !== "info")) {
1335
- const severityIcon = issue.severity === "error" ? chalk.red("✗") : chalk.yellow("⚠");
1336
- const categoryLabel = formatCategory(issue.category);
1337
- out(` ${chalk.gray("┌─")} ${severityIcon} ${chalk.bold(categoryLabel)} ${chalk.gray("─".repeat(Math.max(0, 42 - categoryLabel.length)))}`);
1338
- if (issue.table) {
1339
- const colPart = issue.column ? ` │ Column: ${chalk.cyan(issue.column)}` : "";
1340
- out(` ${chalk.gray("│")} Table: ${chalk.cyan(issue.table)}${colPart}`);
1341
- }
1342
- if (issue.expected && issue.actual) out(` ${chalk.gray("│")} Expected: ${chalk.green(issue.expected)} │ Actual: ${chalk.red(issue.actual)}`);
1343
- out(` ${chalk.gray("│")} ${issue.message}`);
1344
- out(` ${chalk.gray("│")} Fix: ${chalk.blue(issue.fix)}`);
1345
- out(` ${chalk.gray("└" + "─".repeat(48))}`);
1346
- out();
1347
- }
1348
- }
1349
- function formatCategory(cat) {
1350
- return {
1351
- missing_table: "Missing Table",
1352
- missing_column: "Missing Column",
1353
- type_mismatch: "Type Mismatch",
1354
- nullability_mismatch: "Nullability Mismatch",
1355
- extra_column: "Extra Column",
1356
- missing_constraint: "Missing Constraint",
1357
- primary_key_mismatch: "Primary Key Mismatch",
1358
- schema_stale: "Stale Schema",
1359
- missing_enum: "Missing Enum",
1360
- enum_value_mismatch: "Enum Value Mismatch",
1361
- missing_foreign_key: "Missing Foreign Key",
1362
- orphaned_junction: "Orphaned Junction Table",
1363
- sdk_stale: "Stale SDK Types",
1364
- sdk_not_generated: "SDK Types Not Generated",
1365
- sdk_ungeneratable: "SDK Cannot Be Generated"
1366
- }[cat];
1367
- }
1368
- var isRecord = (value) => typeof value === "object" && value !== null;
1369
- /**
1370
- * The `tables` export of `schema.generated.ts`, imported as boot imports it.
1371
- *
1372
- * Nothing, and no error, when the file is not there: phase 1 reports that, and
1373
- * boot then has nothing to compare either.
1374
- */
1375
- async function loadGeneratedTables(schemaPath) {
1376
- if (!fs$1.existsSync(schemaPath)) return {};
1377
- try {
1378
- const module = await import(pathToFileURL(schemaPath).href);
1379
- return isRecord(module) && isRecord(module.tables) ? { tables: module.tables } : {};
1380
- } catch (err) {
1381
- return { error: err instanceof Error ? err.message : String(err) };
1382
- }
1383
- }
1384
- async function runDoctor(options) {
1385
- out();
1386
- out(chalk.bold(" 🩺 Loading collections..."));
1387
- const collections = await loadCollections(options.collectionsPath);
1388
- if (collections.length === 0) {
1389
- outError(chalk.red(" ✗ No collections found."));
1390
- process.exit(1);
1391
- }
1392
- out(chalk.gray(` Found ${collections.length} collection(s)`));
1393
- out();
1394
- out(chalk.gray(" Checking Collections → Generated Schema..."));
1395
- const collectionsToSchema = await checkCollectionsVsSchema(collections, options.schemaPath);
1396
- let schemaToDatabase;
1397
- if (options.databaseUrl) {
1398
- out(chalk.gray(" Checking Collections → Database..."));
1399
- try {
1400
- const generated = await loadGeneratedTables(options.schemaPath);
1401
- schemaToDatabase = await checkCollectionsVsDatabase(collections, options.databaseUrl, { generated: generated.tables });
1402
- if (generated.error) {
1403
- schemaToDatabase.issues.push({
1404
- severity: "warning",
1405
- category: "schema_stale",
1406
- message: `schema.generated.ts could not be loaded, so it was not compared against the database as boot compares it: ${generated.error}`,
1407
- fix: "Run `rebase schema generate`, then `rebase doctor` again"
1408
- });
1409
- schemaToDatabase.passed = false;
1410
- }
1411
- } catch (err) {
1412
- const banner = diagnoseDbError(err, options.databaseUrl);
1413
- if (banner) outError(banner);
1414
- const reason = deepestErrorMessage(err) ?? (err instanceof Error ? err.message : String(err));
1415
- schemaToDatabase = {
1416
- passed: false,
1417
- issues: [],
1418
- skipped: `could not reach ${parseHostInfo(options.databaseUrl)} — ${reason}`,
1419
- blocked: true
1420
- };
1421
- }
1422
- } else {
1423
- schemaToDatabase = {
1424
- passed: false,
1425
- issues: [],
1426
- skipped: "DATABASE_URL not set"
1427
- };
1428
- out(chalk.yellow(" ⚠ DATABASE_URL not set — skipping database comparison."));
1429
- out(chalk.gray(" Set DATABASE_URL in your .env to enable full drift detection."));
1430
- }
1431
- out(chalk.gray(" Checking Collections → SDK Types..."));
1432
- const collectionsToSdk = await checkCollectionsVsSdk(collections, options.sdkPath);
1433
- const phases = [
1434
- collectionsToSchema,
1435
- schemaToDatabase,
1436
- collectionsToSdk
1437
- ];
1438
- const allIssues = phases.flatMap((p) => p.issues);
1439
- const summary = {
1440
- passed: phases.filter((p) => p.passed && !p.skipped && !p.notApplicable).length,
1441
- skipped: phases.filter((p) => p.skipped).length,
1442
- notApplicable: phases.filter((p) => p.notApplicable && !p.skipped).length,
1443
- warnings: allIssues.filter((i) => i.severity === "warning").length,
1444
- errors: allIssues.filter((i) => i.severity === "error").length
1445
- };
1446
- const report = {
1447
- collectionsToSchema,
1448
- collectionsToSdk,
1449
- schemaToDatabase,
1450
- summary
1451
- };
1452
- renderReport(report);
1453
- return report;
1454
- }
1455
- //#endregion
1456
- export { loadCollections as n, runDoctor as r, doctor_exports as t };
1457
-
1458
- //# sourceMappingURL=doctor-Kg1oUK0Q.js.map