@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,16 +1,33 @@
1
1
  /**
2
- * Patches all PgArray columns on the given tables to handle NULL values safely.
2
+ * Read a Postgres array literal (`{a,"b c",NULL,"NULL"}`, nested
3
+ * `{{1,2},{3,4}}`) into its items, each as the text Postgres wrote — an
4
+ * unquoted `NULL` as `null`.
3
5
  *
4
- * Drizzle ORM's `PgArray.mapFromDriverValue` calls `value.map(...)` without
5
- * guarding against `null`. When a PostgreSQL native array column (`text[]`,
6
- * `integer[]`, etc.) contains NULL, the pg driver returns `null` in JavaScript,
7
- * and `null.map(...)` throws `TypeError: value.map is not a function`.
6
+ * Drizzle's own parser reads an unquoted `NULL` as the four-letter string, so
7
+ * a `date[]` / `timestamptz[]` / enum array holding a null item (the types the
8
+ * drivers leave to drizzle as text) served `"NULL"` in its place. A quoted
9
+ * `"NULL"` is the string.
8
10
  *
9
- * This function walks every column of every registered table and, for any
10
- * `PgArray` column, wraps its `mapFromDriverValue` to return `null` when the
11
- * database value is nullish.
11
+ * An explicit lower bound (`[0:1]={…}`) is skipped: the items are what is
12
+ * served, not their subscripts.
13
+ */
14
+ export declare function parsePgArrayLiteral(literal: string): unknown[];
15
+ /**
16
+ * Patches every native array column (`PgArray`) of the given tables so a
17
+ * read hands back what the array holds, nulls included.
18
+ *
19
+ * Drizzle's `PgArray.mapFromDriverValue` has two faults this replaces:
20
+ *
21
+ * - it calls `value.map(...)` on a NULL column — `TypeError: value.map is
22
+ * not a function` — so a null array is served as `null` here;
23
+ * - it maps every item through the item column, a null item included, and
24
+ * parses a text literal's unquoted `NULL` as the string `"NULL"`: a null
25
+ * item of a `bigint[]` came back `0` (`Number(null)`), of a `date[]`,
26
+ * `timestamptz[]` or enum array `"NULL"`. A null item stays `null` here,
27
+ * and only the others go through the item column's own mapping.
12
28
  *
13
- * This is a workaround for a known Drizzle ORM issue. Should be removed once
14
- * Drizzle handles nullable arrays natively.
29
+ * Applied where the runtime builds its tables (`buildDrizzleTablesFromSchema`),
30
+ * so every table a driver reads through carries it. Idempotent: a mark on the
31
+ * column, so a table patched twice is wrapped once.
15
32
  */
16
33
  export declare function patchPgArrayNullSafety(tables: Record<string, unknown>): void;
@@ -6,7 +6,7 @@
6
6
  * 5-character alphanumeric `code` such as `42P01`) and translate it into
7
7
  * a message that is safe and helpful to show to end-users.
8
8
  */
9
- import type { CollectionConfig } from "@rebasepro/types";
9
+ import type { TableDescriptor } from "@rebasepro/types";
10
10
  import { extractCauseMessage } from "./error-cause.js";
11
11
  /** Shape of PostgreSQL errors with diagnostic metadata. */
12
12
  export interface PostgresError extends Error {
@@ -132,7 +132,7 @@ export interface PgFieldViolation {
132
132
  * empty list is the honest answer; inventing a field is worse than saying
133
133
  * nothing, because a form will mark the wrong input red.
134
134
  */
135
- export declare function pgFieldViolations(pgError: PostgresError, collection?: CollectionConfig): PgFieldViolation[];
135
+ export declare function pgFieldViolations(pgError: PostgresError, table?: TableDescriptor): PgFieldViolation[];
136
136
  /**
137
137
  * Translate a raw PostgreSQL error into a user-friendly message.
138
138
  *
@@ -142,7 +142,7 @@ export declare function pgFieldViolations(pgError: PostgresError, collection?: C
142
142
  */
143
143
  export declare function pgErrorToFriendlyMessage(pgError: PostgresError, context: string, options?: {
144
144
  verbose?: boolean;
145
- collection?: CollectionConfig;
145
+ table?: TableDescriptor;
146
146
  }): {
147
147
  message: string;
148
148
  code: string;
@@ -162,7 +162,7 @@ export declare function pgErrorToFriendlyMessage(pgError: PostgresError, context
162
162
  * (the `ApiError` code, or the PG SQLSTATE).
163
163
  */
164
164
  export declare function sanitizeErrorForClient(error: unknown, context: string, options?: {
165
- collection?: CollectionConfig;
165
+ table?: TableDescriptor;
166
166
  }): {
167
167
  message: string;
168
168
  code?: string;
@@ -1,8 +1,6 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
4
- import { isPostgresCollectionConfig } from "@rebasepro/types";
5
- import { getTableName } from "@rebasepro/common";
6
4
  import { toPostgresIdentifier } from "@rebasepro/utils";
7
5
  //#region src/schema/vector-index.ts
8
6
  var vector_index_exports = /* @__PURE__ */ __exportAll({
@@ -13,8 +11,8 @@ var vector_index_exports = /* @__PURE__ */ __exportAll({
13
11
  VECTOR_EXTENSION_OPT_IN: () => VECTOR_EXTENSION_OPT_IN,
14
12
  VECTOR_EXTENSION_SCHEMA: () => VECTOR_EXTENSION_SCHEMA,
15
13
  VectorIndexConfigError: () => VectorIndexConfigError,
16
- buildVectorColumnSpecs: () => buildVectorColumnSpecs,
17
- buildVectorIndexPlan: () => buildVectorIndexPlan,
14
+ buildTableVectorColumnSpecs: () => buildTableVectorColumnSpecs,
15
+ buildTableVectorIndexPlan: () => buildTableVectorIndexPlan,
18
16
  vectorColumnDefinition: () => vectorColumnDefinition,
19
17
  vectorColumnType: () => vectorColumnType,
20
18
  vectorDimensionGuard: () => vectorDimensionGuard,
@@ -55,7 +53,6 @@ var VectorIndexConfigError = class extends Error {
55
53
  this.name = "VectorIndexConfigError";
56
54
  }
57
55
  };
58
- var isVectorProperty = (prop) => !!prop && typeof prop === "object" && prop.type === "vector";
59
56
  var asDistances = (config, label) => {
60
57
  const raw = config.distance ?? "cosine";
61
58
  const list = Array.isArray(raw) ? raw : [raw];
@@ -91,37 +88,66 @@ var parametersFor = (method, config, label) => {
91
88
  for (const key of ["m", "efConstruction"]) if (config[key] !== void 0) throw new VectorIndexConfigError(`${label}: \`index.${key}\` only applies to \`method: "hnsw"\`. Remove it, or switch the method.`);
92
89
  return config.lists !== void 0 ? [["lists", config.lists]] : [];
93
90
  };
91
+ /** pgvector's name for each table-model metric — the lowering's `DISTANCE_OF`. */
92
+ var DISTANCE_OF_METRIC = {
93
+ cosine: "cosine",
94
+ l2: "l2",
95
+ ip: "inner_product"
96
+ };
94
97
  /**
95
- * Every ANN index a collection's vector properties call for.
96
- *
97
- * `resolveColumn` is passed in rather than imported so that this module stays
98
- * free of the DDL generator, which imports *it*. Both callers hand it the same
99
- * `resolveColumnName`, and a contract test asserts the names agree.
98
+ * pgvector's name for a metric, refusing one the table model does not have —
99
+ * a JavaScript config is not held to the `VectorMetric` union, and an unknown
100
+ * metric must not quietly become the default distance.
100
101
  */
101
- var buildVectorIndexPlan = (collection, resolveColumn) => {
102
+ var distanceOfMetric = (metric, label) => {
103
+ if (!Object.prototype.hasOwnProperty.call(DISTANCE_OF_METRIC, metric)) throw new VectorIndexConfigError(`${label}: \`index.metric\` is "${String(metric)}", which is not a pgvector metric. Use ${Object.keys(DISTANCE_OF_METRIC).map((m) => `"${m}"`).join(", ")}.`);
104
+ return DISTANCE_OF_METRIC[metric];
105
+ };
106
+ /** A column's `.vectorIndex()` options, under the index builder's names. */
107
+ var vectorIndexConfigOf = (options, label) => {
108
+ if (options === false) return false;
109
+ const config = {};
110
+ if (options.method !== void 0) config.method = options.method;
111
+ if (options.metric !== void 0) config.distance = typeof options.metric === "string" ? distanceOfMetric(options.metric, label) : options.metric.map((metric) => distanceOfMetric(metric, label));
112
+ if (options.m !== void 0) config.m = options.m;
113
+ if (options.efConstruction !== void 0) config.efConstruction = options.efConstruction;
114
+ if (options.lists !== void 0) config.lists = options.lists;
115
+ return config;
116
+ };
117
+ /** A table descriptor's vector columns. */
118
+ var vectorTableOf = (table) => ({
119
+ schema: table.schema,
120
+ table: table.table,
121
+ columns: table.columns.flatMap((column) => column.type.kind !== "vector" ? [] : [{
122
+ label: `${table.slug}.${column.key}`,
123
+ column: column.column,
124
+ dimensions: column.type.dimensions,
125
+ index: column.vectorIndex === void 0 ? void 0 : vectorIndexConfigOf(column.vectorIndex, `${table.slug}.${column.key}`),
126
+ unique: column.unique === true,
127
+ required: !column.nullable
128
+ }])
129
+ });
130
+ /** Every ANN index a table's vector columns call for, read from its descriptor. */
131
+ var buildTableVectorIndexPlan = (table) => vectorIndexPlanFrom(vectorTableOf(table));
132
+ var vectorIndexPlanFrom = ({ schema, table, columns }) => {
102
133
  const specs = [];
103
134
  const skipped = [];
104
- const properties = collection.properties ?? {};
105
- const table = getTableName(collection);
106
- const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
107
- for (const [propName, prop] of Object.entries(properties)) {
108
- if (!isVectorProperty(prop)) continue;
109
- if (prop.index === false) continue;
110
- const label = `${collection.slug}.${propName}`;
111
- const column = resolveColumn(propName, prop);
112
- const config = prop.index ?? {};
135
+ for (const source of columns) {
136
+ if (source.index === false) continue;
137
+ const { label, column, dimensions } = source;
138
+ const config = source.index ?? {};
113
139
  const method = config.method ?? "hnsw";
114
140
  if (method !== "hnsw" && method !== "ivfflat") throw new VectorIndexConfigError(`${label}: \`index.method\` is "${method}". Use "hnsw" or "ivfflat".`);
115
141
  const distances = asDistances(config, label);
116
142
  const parameters = parametersFor(method, config, label);
117
- if (!Number.isInteger(prop.dimensions) || prop.dimensions <= 0) throw new VectorIndexConfigError(`${label}: \`dimensions\` is ${JSON.stringify(prop.dimensions)}. It must be a positive integer.`);
118
- if (prop.dimensions > 2e3) {
143
+ if (!Number.isInteger(dimensions) || dimensions <= 0) throw new VectorIndexConfigError(`${label}: \`dimensions\` is ${JSON.stringify(dimensions)}. It must be a positive integer.`);
144
+ if (dimensions > 2e3) {
119
145
  skipped.push({
120
146
  schema,
121
147
  table,
122
148
  column,
123
- dimensions: prop.dimensions,
124
- reason: `pgvector cannot index a vector wider than ${MAX_INDEXABLE_VECTOR_DIMENSIONS} dimensions, and ${label} declares ${prop.dimensions}. The column works and \`vectorSearch\` still answers, as an exact scan. To index it, reduce the dimensions (many embedding models support a shorter output) or set \`index: false\` to state that the scan is intended.`
149
+ dimensions,
150
+ reason: `pgvector cannot index a vector wider than ${MAX_INDEXABLE_VECTOR_DIMENSIONS} dimensions, and ${label} declares ${dimensions}. The column works and \`vectorSearch\` still answers, as an exact scan. To index it, reduce the dimensions (many embedding models support a shorter output) or set \`index: false\` to state that the scan is intended.`
125
151
  });
126
152
  continue;
127
153
  }
@@ -147,7 +173,7 @@ var buildVectorIndexPlan = (collection, resolveColumn) => {
147
173
  * `CONCURRENTLY` is deliberately absent, for the same reason it is absent from
148
174
  * `searchIndexStatements`: this form is replayed as part of a migration, where
149
175
  * a concurrent build is not allowed. The boot-time ensure rewrites it — see
150
- * `ensureCollectionTables`.
176
+ * `ensureTables`.
151
177
  */
152
178
  var vectorIndexStatement = (spec) => {
153
179
  const params = spec.parameters.length ? ` WITH (${spec.parameters.map(([key, value]) => `${key} = ${value}`).join(", ")})` : "";
@@ -219,33 +245,15 @@ var vectorExtensionHint = (message) => {
219
245
  return `
220
246
  pgvector is not installed on this database, and Rebase installs it only where a database says it may: add \`${VECTOR_EXTENSION_OPT_IN}\` in config/resources.ts, or install it once by hand with \`CREATE EXTENSION vector;\`. Either way the server needs an image that ships the library — the scaffold's \`pgvector/pgvector:pg18\` does, a stock \`postgres:18\` does not. Rebase then creates the column and its ANN index automatically — see the \`index\` option on the property.`;
221
247
  };
222
- /**
223
- * Every vector column a collection declares.
224
- *
225
- * Wider than {@link buildVectorIndexPlan} on purpose: that one answers "what
226
- * gets an ANN index", and skips both a property with `index: false` and one too
227
- * wide to index. Either still needs its column.
228
- */
229
- var buildVectorColumnSpecs = (collection, resolveColumn) => {
230
- const table = getTableName(collection);
231
- const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
232
- const specs = [];
233
- for (const [propName, prop] of Object.entries(collection.properties ?? {})) {
234
- if (!isVectorProperty(prop)) continue;
235
- const validation = prop.validation;
236
- let modifiers = "";
237
- if (validation?.unique) modifiers += " UNIQUE";
238
- if (validation?.required) modifiers += " NOT NULL";
239
- specs.push({
240
- schema,
241
- table,
242
- column: resolveColumn(propName, prop),
243
- dimensions: prop.dimensions,
244
- modifiers
245
- });
246
- }
247
- return specs;
248
- };
248
+ /** Every vector column a table declares, read from its descriptor. */
249
+ var buildTableVectorColumnSpecs = (table) => vectorColumnSpecsFrom(vectorTableOf(table));
250
+ var vectorColumnSpecsFrom = ({ schema, table, columns }) => columns.map((source) => ({
251
+ schema,
252
+ table,
253
+ column: source.column,
254
+ dimensions: source.dimensions,
255
+ modifiers: `${source.unique ? " UNIQUE" : ""}${source.required ? " NOT NULL" : ""}`
256
+ }));
249
257
  /** The column type — the one place `VECTOR(n)` is spelled. */
250
258
  var vectorColumnType = (spec) => `VECTOR(${spec.dimensions})`;
251
259
  /** The column definition as it appears inside `CREATE TABLE`. */
@@ -293,6 +301,6 @@ END
293
301
  $rebase_vector$;`;
294
302
  };
295
303
  //#endregion
296
- export { vectorDimensionGuard as a, vectorExtensionStatement as c, vectorIndexStatements as d, vector_index_exports as f, vectorColumnDefinition as i, vectorIndexNames as l, buildVectorColumnSpecs as n, vectorExtensionDeclared as o, buildVectorIndexPlan as r, vectorExtensionHint as s, VECTOR_EXTENSION_OPT_IN as t, vectorIndexStatement as u };
304
+ export { vectorDimensionGuard as a, vectorExtensionStatement as c, vectorIndexStatements as d, vector_index_exports as f, vectorColumnDefinition as i, vectorIndexNames as l, buildTableVectorColumnSpecs as n, vectorExtensionDeclared as o, buildTableVectorIndexPlan as r, vectorExtensionHint as s, VECTOR_EXTENSION_OPT_IN as t, vectorIndexStatement as u };
297
305
 
298
- //# sourceMappingURL=vector-index-DsQ3V2d2.js.map
306
+ //# sourceMappingURL=vector-index-VSh3ufTd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vector-index-VSh3ufTd.js","names":[],"sources":["../src/schema/vector-index.ts"],"sourcesContent":["/**\n * The one place a `{ type: \"vector\" }` property becomes an ANN index.\n *\n * Without an index, pgvector answers `ORDER BY embedding <=> $1` by computing\n * the distance to every row and sorting — exact, and linear. That is the right\n * answer at ten thousand rows and the wrong one at a million, which is why the\n * default here is to build an index rather than to leave the column bare.\n *\n * ## The operator class is not a detail\n *\n * An index is built for exactly one operator class, and the planner uses it\n * only for the operator that class implements. `vector_cosine_ops` answers\n * `<=>` and nothing else; a query asking for `<->` against a cosine index gets\n * a sequential scan and no error. So the default indexed distance here is\n * `cosine`, because `cosine` is what `vectorSearch` measures with when the\n * caller does not say — see `DrizzleConditionBuilder.buildVectorSearch`. The\n * two defaults have to agree, and this comment is the reason they do.\n *\n * ## Why 2000 dimensions is a ceiling and not an error\n *\n * pgvector cannot index a `vector` wider than 2000 dimensions with either\n * method. A 3072-dimension embedding (`text-embedding-3-large`) is therefore\n * storable and searchable but not indexable. Refusing the boot over that would\n * make a working configuration unbootable; silently indexing it is impossible.\n * So the column is created, the index is skipped, and the reason is reported.\n *\n * Like `search-column.ts`, this module exists so that the DDL generator and the\n * boot-time ensure render the *same* specification rather than describing the\n * same index twice, differently. `contracts/derived-names.txt` records the\n * names both produce, and CI fails if they diverge.\n *\n * ## And why the column itself is described here too\n *\n * `VECTOR(n)` is a type Atlas cannot be shown. It has to materialise the\n * desired state in a dev database to diff against, that database is created\n * empty and *emptied again* by Atlas at the start of every run, and nothing in\n * the free tier can put `CREATE EXTENSION vector` back — so a `schema.sql`\n * mentioning the type fails with `type \"vector\" does not exist` on every push,\n * for good. Search hit the same wall for its own reasons and took the same way\n * out: the objects leave `schema.sql`, Atlas is told to exclude them, and\n * Rebase applies them itself. See `generatePostgresVectorDdl`.\n */\nimport type {\n TableDescriptor,\n VectorIndexOptions,\n VectorMetric\n} from \"@rebasepro/types\";\nimport { toPostgresIdentifier } from \"@rebasepro/utils\";\n\n/**\n * A pgvector distance as the index plan names it — one operator class each,\n * spelled the way `vectorSearch`'s `distance` spells it.\n */\nexport type VectorDistance = \"cosine\" | \"l2\" | \"inner_product\";\n\n/** How one column's ANN index is built: what a column's `VectorIndexOptions` resolves to. */\nexport interface VectorIndexConfig {\n /** `hnsw` (the default) or `ivfflat`. */\n method?: \"hnsw\" | \"ivfflat\";\n /** The distance(s) indexed, one index each; `cosine` by default. */\n distance?: VectorDistance | VectorDistance[];\n /** HNSW: connections per node. */\n m?: number;\n /** HNSW: candidate-list size while building. */\n efConstruction?: number;\n /** IVFFlat: number of partitions. */\n lists?: number;\n}\n\n/**\n * The widest `vector` pgvector will build an HNSW or IVFFlat index over.\n * Storage and exact search are unaffected by this limit.\n */\nexport const MAX_INDEXABLE_VECTOR_DIMENSIONS = 2000;\n\n/** The distance indexed when a property does not name one. */\nexport const DEFAULT_VECTOR_DISTANCE: VectorDistance = \"cosine\";\n\n/** The index method used when a property does not name one. */\nexport const DEFAULT_VECTOR_INDEX_METHOD = \"hnsw\" as const;\n\n/**\n * Operator class per distance. These strings are part of the database contract:\n * they appear in `CREATE INDEX`, so renaming one renames an index.\n */\nconst OPERATOR_CLASS: Record<VectorDistance, string> = {\n cosine: \"vector_cosine_ops\",\n l2: \"vector_l2_ops\",\n inner_product: \"vector_ip_ops\"\n};\n\n/** Short, stable tag per distance, used to name the index. */\nconst DISTANCE_TAG: Record<VectorDistance, string> = {\n cosine: \"cosine\",\n l2: \"l2\",\n inner_product: \"ip\"\n};\n\nexport interface VectorIndexSpec {\n schema: string;\n table: string;\n column: string;\n indexName: string;\n method: \"hnsw\" | \"ivfflat\";\n distance: VectorDistance;\n operatorClass: string;\n /** Rendered into `WITH (...)`; empty when every parameter is defaulted. */\n parameters: Array<[string, number]>;\n}\n\n/** A vector column that will not be indexed, and why. */\nexport interface SkippedVectorIndex {\n schema: string;\n table: string;\n column: string;\n dimensions: number;\n reason: string;\n}\n\nexport interface VectorIndexPlan {\n specs: VectorIndexSpec[];\n skipped: SkippedVectorIndex[];\n}\n\nexport class VectorIndexConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"VectorIndexConfigError\";\n }\n}\n\nconst asDistances = (config: VectorIndexConfig, label: string): VectorDistance[] => {\n const raw = config.distance ?? DEFAULT_VECTOR_DISTANCE;\n const list = Array.isArray(raw) ? raw : [raw];\n if (list.length === 0) {\n throw new VectorIndexConfigError(\n `${label}: \\`index.distance\\` is an empty array. Name at least one distance, or set \\`index: false\\` to create no index.`\n );\n }\n const seen = new Set<VectorDistance>();\n for (const distance of list) {\n if (!(distance in OPERATOR_CLASS)) {\n throw new VectorIndexConfigError(\n `${label}: \\`index.distance\\` is \"${distance}\", which is not a pgvector distance. Use ${Object.keys(OPERATOR_CLASS).map(d => `\"${d}\"`).join(\", \")}.`\n );\n }\n if (seen.has(distance)) {\n throw new VectorIndexConfigError(`${label}: \\`index.distance\\` lists \"${distance}\" twice.`);\n }\n seen.add(distance);\n }\n return list;\n};\n\nconst assertPositiveInteger = (value: number | undefined, key: string, label: string): void => {\n if (value === undefined) return;\n if (!Number.isInteger(value) || value <= 0) {\n throw new VectorIndexConfigError(\n `${label}: \\`index.${key}\\` is ${JSON.stringify(value)}. It must be a positive integer.`\n );\n }\n};\n\n/**\n * Index parameters for one method. Parameters belonging to the *other* method\n * are rejected rather than ignored, because a silently dropped `lists` on an\n * HNSW index reads, from the config, exactly like a tuned index.\n */\nconst parametersFor = (\n method: \"hnsw\" | \"ivfflat\",\n config: VectorIndexConfig,\n label: string\n): Array<[string, number]> => {\n assertPositiveInteger(config.m, \"m\", label);\n assertPositiveInteger(config.efConstruction, \"efConstruction\", label);\n assertPositiveInteger(config.lists, \"lists\", label);\n\n if (method === \"hnsw\") {\n if (config.lists !== undefined) {\n throw new VectorIndexConfigError(\n `${label}: \\`index.lists\\` only applies to \\`method: \"ivfflat\"\\`. Remove it, or switch the method.`\n );\n }\n const params: Array<[string, number]> = [];\n if (config.m !== undefined) params.push([\"m\", config.m]);\n if (config.efConstruction !== undefined) params.push([\"ef_construction\", config.efConstruction]);\n return params;\n }\n\n for (const key of [\"m\", \"efConstruction\"] as const) {\n if (config[key] !== undefined) {\n throw new VectorIndexConfigError(\n `${label}: \\`index.${key}\\` only applies to \\`method: \"hnsw\"\\`. Remove it, or switch the method.`\n );\n }\n }\n return config.lists !== undefined ? [[\"lists\", config.lists]] : [];\n};\n\n/**\n * One vector column as both builders read it, whichever door it came through:\n * a table descriptor's column or a lowered collection's property.\n */\ninterface VectorColumnSource {\n /** `<slug>.<key>`, for a refusal. */\n label: string;\n column: string;\n dimensions: number;\n /** `false`: no index; `undefined`: the default one. */\n index: VectorIndexConfig | false | undefined;\n unique: boolean;\n required: boolean;\n}\n\n/** The table the vector columns are on, and its vector columns in column order. */\ninterface VectorTableSource {\n schema: string;\n table: string;\n columns: VectorColumnSource[];\n}\n\n/** pgvector's name for each table-model metric — the lowering's `DISTANCE_OF`. */\nconst DISTANCE_OF_METRIC: Record<VectorMetric, VectorDistance> = {\n cosine: \"cosine\",\n l2: \"l2\",\n ip: \"inner_product\"\n};\n\n/**\n * pgvector's name for a metric, refusing one the table model does not have —\n * a JavaScript config is not held to the `VectorMetric` union, and an unknown\n * metric must not quietly become the default distance.\n */\nconst distanceOfMetric = (metric: VectorMetric, label: string): VectorDistance => {\n if (!Object.prototype.hasOwnProperty.call(DISTANCE_OF_METRIC, metric)) {\n throw new VectorIndexConfigError(\n `${label}: \\`index.metric\\` is \"${String(metric)}\", which is not a pgvector metric. ` +\n `Use ${Object.keys(DISTANCE_OF_METRIC).map(m => `\"${m}\"`).join(\", \")}.`\n );\n }\n return DISTANCE_OF_METRIC[metric];\n};\n\n/** A column's `.vectorIndex()` options, under the index builder's names. */\nconst vectorIndexConfigOf = (options: VectorIndexOptions | false, label: string): VectorIndexConfig | false => {\n if (options === false) return false;\n const config: VectorIndexConfig = {};\n if (options.method !== undefined) config.method = options.method;\n if (options.metric !== undefined) {\n config.distance = typeof options.metric === \"string\"\n ? distanceOfMetric(options.metric, label)\n : options.metric.map(metric => distanceOfMetric(metric, label));\n }\n if (options.m !== undefined) config.m = options.m;\n if (options.efConstruction !== undefined) config.efConstruction = options.efConstruction;\n if (options.lists !== undefined) config.lists = options.lists;\n return config;\n};\n\n/** A table descriptor's vector columns. */\nconst vectorTableOf = (table: TableDescriptor): VectorTableSource => ({\n schema: table.schema,\n table: table.table,\n columns: table.columns.flatMap(column => column.type.kind !== \"vector\" ? [] : [{\n label: `${table.slug}.${column.key}`,\n column: column.column,\n dimensions: column.type.dimensions,\n index: column.vectorIndex === undefined ? undefined : vectorIndexConfigOf(column.vectorIndex, `${table.slug}.${column.key}`),\n unique: column.unique === true,\n required: !column.nullable\n }])\n});\n\n/** Every ANN index a table's vector columns call for, read from its descriptor. */\nexport const buildTableVectorIndexPlan = (table: TableDescriptor): VectorIndexPlan =>\n vectorIndexPlanFrom(vectorTableOf(table));\n\nconst vectorIndexPlanFrom = ({ schema, table, columns }: VectorTableSource): VectorIndexPlan => {\n const specs: VectorIndexSpec[] = [];\n const skipped: SkippedVectorIndex[] = [];\n\n for (const source of columns) {\n if (source.index === false) continue;\n\n const { label, column, dimensions } = source;\n const config: VectorIndexConfig = source.index ?? {};\n const method = config.method ?? DEFAULT_VECTOR_INDEX_METHOD;\n\n if (method !== \"hnsw\" && method !== \"ivfflat\") {\n throw new VectorIndexConfigError(\n `${label}: \\`index.method\\` is \"${method}\". Use \"hnsw\" or \"ivfflat\".`\n );\n }\n\n // Read before the dimension gate so a malformed block is reported even\n // on a column too wide to index — the config is wrong either way.\n const distances = asDistances(config, label);\n const parameters = parametersFor(method, config, label);\n\n if (!Number.isInteger(dimensions) || dimensions <= 0) {\n throw new VectorIndexConfigError(\n `${label}: \\`dimensions\\` is ${JSON.stringify(dimensions)}. It must be a positive integer.`\n );\n }\n\n if (dimensions > MAX_INDEXABLE_VECTOR_DIMENSIONS) {\n skipped.push({\n schema,\n table,\n column,\n dimensions,\n reason:\n `pgvector cannot index a vector wider than ${MAX_INDEXABLE_VECTOR_DIMENSIONS} dimensions, and ` +\n `${label} declares ${dimensions}. The column works and \\`vectorSearch\\` still answers, as an ` +\n `exact scan. To index it, reduce the dimensions (many embedding models support a shorter output) ` +\n `or set \\`index: false\\` to state that the scan is intended.`\n });\n continue;\n }\n\n for (const distance of distances) {\n specs.push({\n schema,\n table,\n column,\n // Distance is in the name because one column may carry an index\n // per distance, and two indexes cannot share a name. The method\n // is in it because switching methods is a different index, not\n // a redefinition of the same one — `CREATE INDEX IF NOT EXISTS`\n // would otherwise keep the old one and report success.\n indexName: toPostgresIdentifier(`${table}_${column}_${method}_${DISTANCE_TAG[distance]}`),\n method,\n distance,\n operatorClass: OPERATOR_CLASS[distance],\n parameters\n });\n }\n }\n\n return { specs, skipped };\n};\n\n/**\n * The `CREATE INDEX` for one spec.\n *\n * `CONCURRENTLY` is deliberately absent, for the same reason it is absent from\n * `searchIndexStatements`: this form is replayed as part of a migration, where\n * a concurrent build is not allowed. The boot-time ensure rewrites it — see\n * `ensureTables`.\n */\nexport const vectorIndexStatement = (spec: VectorIndexSpec): string => {\n const params = spec.parameters.length\n ? ` WITH (${spec.parameters.map(([key, value]) => `${key} = ${value}`).join(\", \")})`\n : \"\";\n return (\n `CREATE INDEX IF NOT EXISTS \"${spec.indexName}\" ON \"${spec.schema}\".\"${spec.table}\" ` +\n `USING ${spec.method} (\"${spec.column}\" ${spec.operatorClass})${params};`\n );\n};\n\n/** Every statement for a plan, in a stable order. */\nexport const vectorIndexStatements = (plan: VectorIndexPlan): string[] =>\n plan.specs.map(vectorIndexStatement);\n\n/** The index names a plan creates — what the derived-names contract records. */\nexport const vectorIndexNames = (plan: VectorIndexPlan): string[] =>\n plan.specs.map(spec => spec.indexName);\n\n// ── The column, for the file Rebase applies itself ──────────────────────────\n\nconst quote = (v: string): string => `'${v.replace(/'/g, \"''\")}'`;\n\n/**\n * The schema pgvector's types are installed into.\n *\n * `WITH SCHEMA public` for the same load-bearing reason `searchExtensionStatements`\n * gives: an unqualified `CREATE EXTENSION` lands in the first schema on\n * `search_path`, which is `\"$user\", public` — and the scaffold's role is named\n * `rebase`, the same as a schema the generator creates. Left to itself the\n * extension would install into `rebase`, and every unqualified `VECTOR(n)`\n * below would fail to resolve.\n */\nexport const VECTOR_EXTENSION_SCHEMA = \"public\";\n\n/** The extension name a database has to name to let Rebase install pgvector. */\nexport const VECTOR_EXTENSION = \"vector\";\n\n/**\n * How a project says Rebase may install pgvector, quoted into the messages that\n * have to name it. Spelled once so the option and the advice cannot drift.\n */\nexport const VECTOR_EXTENSION_OPT_IN = `database({ extensions: [\"${VECTOR_EXTENSION}\"] })`;\n\n/** Did the project give Rebase leave to install pgvector? */\nexport const vectorExtensionDeclared = (extensions: readonly string[] | undefined): boolean =>\n (extensions ?? []).includes(VECTOR_EXTENSION);\n\n/**\n * Install pgvector — emitted only when the database asked for it.\n *\n * Opt-in because installing an extension is a decision with a deployment behind\n * it: the image has to ship the library, the role has to be allowed to install\n * it, and a managed provider has to have it on an allow-list. None of that is\n * visible from inside the connection, so Rebase does not decide it. See\n * `DatabaseOptions.extensions`.\n *\n * Withholding the statement is not withholding the *column*: the column is\n * still created, and Postgres refuses it with `type \"vector\" does not exist`\n * on a database where pgvector was never installed by hand. That error is the\n * one this design accepts, and `vectorExtensionHint` is what makes it name\n * {@link VECTOR_EXTENSION_OPT_IN} rather than nothing.\n */\nexport const vectorExtensionStatement = (): string =>\n `CREATE EXTENSION IF NOT EXISTS ${VECTOR_EXTENSION} WITH SCHEMA ${VECTOR_EXTENSION_SCHEMA};`;\n\n/**\n * The missing-pgvector explanation, appended to whichever error revealed it.\n *\n * Two readers, needing opposite things, which is why the branch is on the error\n * text rather than on the configuration:\n *\n * - **`type \"vector\" does not exist`** — nobody opted in and the database has\n * no pgvector. The fix is one line of config they cannot guess, so naming\n * the option *is* the hint.\n * - **the install itself failed** — the config is already right, and repeating\n * the option would send them to edit a correct line. What is missing is the\n * library on the server, or the grant.\n *\n * Lives here rather than beside either caller because both need it: the boot\n * ensure raises the first through its action applier, and `rebase db push`\n * raises it out of `applyVectorDdl`. A hint on only one path is how a bare\n * `type \"vector\" does not exist` reaches somebody — which is the thing this\n * exists to prevent.\n */\nexport const vectorExtensionHint = (message: string): string => {\n const installRefused = /extension \"vector\" is not available/i.test(message)\n || /(permission denied to create extension|must be (superuser|owner).{0,40}extension)/i.test(message);\n if (installRefused) {\n return (\n \"\\n pgvector was declared and could not be installed. It is a server extension, so it needs an image \" +\n \"that ships the library (the scaffold's `pgvector/pgvector:pg18` does; a stock `postgres:18` does not) \" +\n \"and a role allowed to run `CREATE EXTENSION vector;`. Managed Postgres usually allows it once the \" +\n \"extension is on the provider's allow-list.\"\n );\n }\n if (!/type \"(vector|halfvec|sparsevec)\" does not exist/i.test(message)) return \"\";\n return (\n \"\\n pgvector is not installed on this database, and Rebase installs it only where a database says it may: \" +\n `add \\`${VECTOR_EXTENSION_OPT_IN}\\` in config/resources.ts, or install it once by hand with ` +\n \"`CREATE EXTENSION vector;`. Either way the server needs an image that ships the library — the scaffold's \" +\n \"`pgvector/pgvector:pg18` does, a stock `postgres:18` does not. Rebase then creates the column and its ANN \" +\n \"index automatically — see the `index` option on the property.\"\n );\n};\n\n/** One `{ type: \"vector\" }` property, as a column. */\nexport interface VectorColumnSpec {\n schema: string;\n table: string;\n column: string;\n dimensions: number;\n /** Rendered after the type, in the generator's order: UNIQUE then NOT NULL. */\n modifiers: string;\n}\n\n/** Every vector column a table declares, read from its descriptor. */\nexport const buildTableVectorColumnSpecs = (table: TableDescriptor): VectorColumnSpec[] =>\n vectorColumnSpecsFrom(vectorTableOf(table));\n\n// Assembled in the CREATE TABLE generator's order, so the column this file\n// adds and the column `schema.sql` used to declare are the same column. A\n// vector column is never a primary key and carries no SQL-level default,\n// which is what leaves only these two modifiers.\nconst vectorColumnSpecsFrom = ({ schema, table, columns }: VectorTableSource): VectorColumnSpec[] =>\n columns.map(source => ({\n schema,\n table,\n column: source.column,\n dimensions: source.dimensions,\n modifiers: `${source.unique ? \" UNIQUE\" : \"\"}${source.required ? \" NOT NULL\" : \"\"}`\n }));\n\n/** The column type — the one place `VECTOR(n)` is spelled. */\nexport const vectorColumnType = (spec: Pick<VectorColumnSpec, \"dimensions\">): string =>\n `VECTOR(${spec.dimensions})`;\n\n/** The column definition as it appears inside `CREATE TABLE`. */\nexport const vectorColumnDefinition = (spec: VectorColumnSpec): string =>\n `\"${spec.column}\" ${vectorColumnType(spec)}${spec.modifiers}`;\n\n/**\n * Refuse — or perform — a `dimensions` change that `ADD COLUMN IF NOT EXISTS`\n * would otherwise swallow.\n *\n * Without this the file *launders* the change: the ADD is a no-op against a\n * column that exists, so a project that went from 384 to 768 dimensions would\n * push clean, keep a 384-wide column, and fail on the next insert with a\n * message about the row rather than about the config. Atlas used to catch this\n * — it owned the column and planned the `ALTER … TYPE` — and taking the column\n * out of its sight is exactly what makes the guard necessary.\n *\n * The widening is performed when the column holds no values, because that is\n * the case Atlas handled and it is the common one: a developer changing\n * embedding models before there are any embeddings. With values present the\n * conversion is pgvector's to reject — every stored vector is the old width —\n * so this refuses first and names the statement to run afterwards.\n *\n * `atttypmod` on a `vector` column *is* the dimension count: pgvector stores it\n * directly rather than offsetting it the way `varchar` does. `-1` means the\n * column was declared as a bare `vector`, which is drift in the same sense.\n */\nexport const vectorDimensionGuard = (spec: VectorColumnSpec): string => {\n const relation = `\"${spec.schema}\".\"${spec.table}\"`;\n return `DO $rebase_vector$\nDECLARE actual int;\nBEGIN\n SELECT a.atttypmod INTO actual\n FROM pg_attribute a\n JOIN pg_type t ON t.oid = a.atttypid\n WHERE a.attrelid = ${quote(relation)}::regclass\n AND a.attname = ${quote(spec.column)}\n AND NOT a.attisdropped\n AND t.typname = 'vector';\n IF actual IS NOT NULL AND actual <> ${spec.dimensions} THEN\n IF EXISTS (SELECT 1 FROM ${relation} WHERE \"${spec.column}\" IS NOT NULL) THEN\n RAISE EXCEPTION 'Rebase: ${spec.schema}.${spec.table}.\"${spec.column}\" declares ${spec.dimensions} dimensions but the column is vector(%), and it already holds values of the old width. pgvector cannot convert them. Re-embed the rows at ${spec.dimensions} dimensions (or clear the column), then re-apply: ALTER TABLE ${relation} ALTER COLUMN \"${spec.column}\" TYPE ${vectorColumnType(spec)};', actual;\n END IF;\n ALTER TABLE ${relation} ALTER COLUMN \"${spec.column}\" TYPE ${vectorColumnType(spec)};\n END IF;\nEND\n$rebase_vector$;`;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyEA,IAAa,kCAAkC;;AAG/C,IAAa,0BAA0C;;AAGvD,IAAa,8BAA8B;;;;;AAM3C,IAAM,iBAAiD;CACnD,QAAQ;CACR,IAAI;CACJ,eAAe;AACnB;;AAGA,IAAM,eAA+C;CACjD,QAAQ;CACR,IAAI;CACJ,eAAe;AACnB;AA4BA,IAAa,yBAAb,cAA4C,MAAM;CAC9C,YAAY,SAAiB;EACzB,MAAM,OAAO;EACb,KAAK,OAAO;CAChB;AACJ;AAEA,IAAM,eAAe,QAA2B,UAAoC;CAChF,MAAM,MAAM,OAAO,YAAA;CACnB,MAAM,OAAO,MAAM,QAAQ,GAAG,IAAI,MAAM,CAAC,GAAG;CAC5C,IAAI,KAAK,WAAW,GAChB,MAAM,IAAI,uBACN,GAAG,MAAM,gHACb;CAEJ,MAAM,uBAAO,IAAI,IAAoB;CACrC,KAAK,MAAM,YAAY,MAAM;EACzB,IAAI,EAAE,YAAY,iBACd,MAAM,IAAI,uBACN,GAAG,MAAM,2BAA2B,SAAS,2CAA2C,OAAO,KAAK,cAAc,CAAC,CAAC,KAAI,MAAK,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,EACtJ;EAEJ,IAAI,KAAK,IAAI,QAAQ,GACjB,MAAM,IAAI,uBAAuB,GAAG,MAAM,8BAA8B,SAAS,SAAS;EAE9F,KAAK,IAAI,QAAQ;CACrB;CACA,OAAO;AACX;AAEA,IAAM,yBAAyB,OAA2B,KAAa,UAAwB;CAC3F,IAAI,UAAU,KAAA,GAAW;CACzB,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
2
2
  __createRequire(import.meta.url);
3
3
  import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
4
- import { A as budgetSendBuffers, M as terminateIfBacklogged, N as assertReadRequestReadable, ct as SqlResultTooLargeError, it as effectiveSqlRole, j as reapSilentSockets, lt as isNestedPath, ot as sqlRoleRanAs, st as SQL_RESULT_BYTE_BUDGET, ut as resolveNestedPath } from "./open-rebase-40paQfVW.js";
5
- import { r as BranchingUnsupportedError } from "./BranchService-CrXvcES2.js";
6
- import { ApiError, DATABASE_UNAVAILABLE_MESSAGE, RUNTIME_DEFAULT_MAX_BODY_SIZE, assertFieldOpsValid, assertNestedWriteAllowed, assertNoFieldOpsOnCreate, assertNoUserUpsert, assertUserCreationBodyValid, assertWriteRequestValid, createUserThroughAuthCollection, decideImpersonation, declaredErrorAnswer, extractUserFromToken, getAccessModel, isDatabaseUnreachable, logger, resolveConflictTarget, resolveRequireAuth, safeCompare } from "@rebasepro/server";
4
+ import { A as reapSilentSockets, at as SQL_RESULT_BYTE_BUDGET, ct as resolveNestedPath, it as sqlRoleRanAs, j as terminateIfBacklogged, k as budgetSendBuffers, lt as assertReadRequestReadable, nt as effectiveSqlRole, ot as SqlResultTooLargeError, st as isNestedPath } from "./open-rebase-4kisUF_k.js";
5
+ import { r as BranchingUnsupportedError } from "./BranchService-USp1AvZB.js";
6
+ import { ApiError, DATABASE_UNAVAILABLE_MESSAGE, RUNTIME_DEFAULT_MAX_BODY_SIZE, assertFieldOpsValid, assertNestedWriteAllowed, assertNoFieldOpsOnCreate, assertNoUserUpsert, assertUserCreationBodyValid, assertWriteRequestValid, createUserThroughAuthTable, decideImpersonation, declaredErrorAnswer, extractUserFromToken, getAccessModel, isAuthTable, isDatabaseUnreachable, logger, resolveConflictTarget, resolveRequireAuth, safeCompare } from "@rebasepro/server";
7
7
  import { ANONYMOUS_USER_ID, ListLimitError, hasAdminRole, isSQLAdmin, isSchemaAdmin, resolveClientListLimit, scopeGrants, scopesForRoles } from "@rebasepro/types";
8
- import { UnknownFilterOperatorError, deserializeFilter, redactSqlLiterals } from "@rebasepro/common";
8
+ import { UnknownFilterOperatorError, deserializeFilter, redactSqlLiterals, relationOf } from "@rebasepro/common";
9
9
  import { unref } from "@rebasepro/utils";
10
10
  import { WebSocket, WebSocketServer } from "ws";
11
11
  import { inspect } from "util";
@@ -403,7 +403,7 @@ var PUBLIC_TYPES = /* @__PURE__ */ new Set([
403
403
  function assertKnownCollection(registry, path) {
404
404
  if (!registry || typeof path !== "string") return;
405
405
  const root = path.split("/").find((segment) => segment !== "");
406
- if (root !== void 0 && !registry.getCollectionByPath(root)) throw ApiError.notFound(`Unknown collection '${root}'.`);
406
+ if (root !== void 0 && !registry.tableNamed(root)) throw ApiError.notFound(`Unknown table '${root}'.`);
407
407
  }
408
408
  /**
409
409
  * Recursively extract the deepest error message from an error's cause chain (e.g., Drizzle wrapping a PG error).
@@ -1129,13 +1129,16 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1129
1129
  */
1130
1130
  const assertWriteRequest = (path, values, status) => {
1131
1131
  if (!path || !values || typeof values !== "object") return;
1132
- const collection = driver.registry?.getCollectionByPath(path);
1133
- if (!collection) return;
1134
- assertWriteRequestValid(values, collection, {
1135
- viewer: { roles: clientSessions.get(clientId)?.user?.roles ?? ["anon"] },
1136
- status
1132
+ const table = driver.registry?.tableAt(path)?.descriptor;
1133
+ if (!table) return;
1134
+ const session = clientSessions.get(clientId);
1135
+ const registry = driver.registry;
1136
+ assertWriteRequestValid(values, table, {
1137
+ viewer: { roles: session?.user?.roles ?? ["anon"] },
1138
+ status,
1139
+ relatedTables: (name) => (registry?.getTable(name) ?? registry?.getTableBySqlName(name))?.descriptor
1137
1140
  });
1138
- assertFieldOpsValid(values, collection);
1141
+ assertFieldOpsValid(values, table);
1139
1142
  };
1140
1143
  /**
1141
1144
  * Apply the REST layer's read check to a socket request: no
@@ -1150,15 +1153,15 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1150
1153
  */
1151
1154
  const assertReadRequest = (path, request) => {
1152
1155
  if (!path) return;
1153
- let collection;
1156
+ let served;
1154
1157
  try {
1155
- collection = driver.registry?.getCollectionByPath(path);
1158
+ served = driver.registry?.tableAt(path);
1156
1159
  } catch {
1157
1160
  return;
1158
1161
  }
1159
- if (!collection) return;
1162
+ if (!served || !driver.registry) return;
1160
1163
  const session = clientSessions.get(clientId);
1161
- assertReadRequestReadable(request, collection, { roles: session?.user?.roles ?? ["anon"] });
1164
+ assertReadRequestReadable(request, served, { roles: session?.user?.roles ?? ["anon"] }, driver.registry);
1162
1165
  };
1163
1166
  /**
1164
1167
  * Refuse a write through a nested path that sets a relation
@@ -1166,32 +1169,39 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1166
1169
  * apply, from the same function. The body is checked by
1167
1170
  * `assertWriteRequest`; this is what the address writes.
1168
1171
  *
1169
- * Silent for a root path, and for a nested one the registry
1170
- * cannot walk: the driver refuses that with its own message.
1172
+ * Silent only for a root path. A nested path this check cannot
1173
+ * judge is refused here, never waved through to the driver: a
1174
+ * path the registry cannot walk throws the walk's own error
1175
+ * (the one the driver would answer with), and a hop whose
1176
+ * parent, relation or target has no served table is refused
1177
+ * outright — a skipped check is a write nobody judged.
1171
1178
  */
1172
1179
  const assertNestedWrite = (path, kind) => {
1173
- if (typeof path !== "string" || !isNestedPath(path) || !driver.registry) return;
1174
- let hop;
1175
- try {
1176
- hop = resolveNestedPath(path, driver.registry);
1177
- } catch {
1178
- return;
1179
- }
1180
- if (!hop) return;
1180
+ if (typeof path !== "string" || !isNestedPath(path)) return;
1181
+ const registry = driver.registry;
1182
+ if (!registry) throw ApiError.forbidden(`A write through '${path}' cannot be checked: this server has no table registry.`, "FIELD_NOT_WRITABLE");
1183
+ const hop = resolveNestedPath(path, registry);
1184
+ const parent = hop?.parent.descriptor;
1185
+ const relation = parent && hop && relationOf(parent, hop.relation.name);
1186
+ const target = relation && registry.getTable(relation.target)?.descriptor;
1187
+ if (!parent || !relation || !target) throw ApiError.forbidden(`A write through '${path}' is refused: its parent table, relation or target table is not served here.`, "FIELD_NOT_WRITABLE");
1181
1188
  const session = clientSessions.get(clientId);
1182
- assertNestedWriteAllowed(hop, kind, path, { roles: session?.user?.roles ?? ["anon"] });
1189
+ assertNestedWriteAllowed({
1190
+ parent,
1191
+ relation,
1192
+ target
1193
+ }, kind, path, { roles: session?.user?.roles ?? ["anon"] }, (name) => (registry.getTable(name) ?? registry.getTableBySqlName(name))?.descriptor);
1183
1194
  };
1184
- /** The auth collection at `path`, or `undefined` for any other. */
1195
+ /** The auth table at `path`, or `undefined` for any other. */
1185
1196
  const authCollectionAt = (path) => {
1186
1197
  if (typeof path !== "string") return void 0;
1187
- let collection;
1198
+ let served;
1188
1199
  try {
1189
- collection = driver.registry?.getCollectionByPath(path);
1200
+ served = driver.registry?.tableAt(path);
1190
1201
  } catch {
1191
1202
  return;
1192
1203
  }
1193
- const auth = collection?.auth;
1194
- return auth === true || !!auth && typeof auth === "object" && auth.enabled === true ? collection : void 0;
1204
+ return served && isAuthTable(served.descriptor) ? { table: served.descriptor } : void 0;
1195
1205
  };
1196
1206
  /**
1197
1207
  * The auth collection's rows are the users, so a write to one
@@ -1211,9 +1221,9 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1211
1221
  */
1212
1222
  const upsertOptions = (request) => {
1213
1223
  if (request.upsert !== true) return {};
1214
- if (typeof request.path === "string" && isNestedPath(request.path)) throw ApiError.badRequest("An upsert is not accepted on a nested path: a row it matched would be moved under this parent. Send the upsert to the collection directly.", "INVALID_CONFLICT_TARGET");
1215
- const collection = driver.registry?.getCollectionByPath(request.path);
1216
- const onConflict = collection ? resolveConflictTarget(request.onConflict, collection, { where: "`onConflict`" }) : void 0;
1224
+ if (typeof request.path === "string" && isNestedPath(request.path)) throw ApiError.badRequest("An upsert is not accepted on a nested path: a row it matched would be moved under this parent. Send the upsert to the table directly.", "INVALID_CONFLICT_TARGET");
1225
+ const table = driver.registry?.tableAt(request.path)?.descriptor;
1226
+ const onConflict = table ? resolveConflictTarget(request.onConflict, table, { where: "`onConflict`" }) : void 0;
1217
1227
  return {
1218
1228
  upsert: true,
1219
1229
  ...onConflict && { onConflict }
@@ -1267,6 +1277,7 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1267
1277
  {
1268
1278
  wsDebug("📄 [WebSocket Server] Processing FETCH_ENTITY request");
1269
1279
  const request = payload;
1280
+ assertReadRequest(request.path, { include: request.include });
1270
1281
  const row = await (await getScopedDelegate()).fetchOne(request);
1271
1282
  wsDebug("📄 [WebSocket Server] FETCH_ENTITY result:", row);
1272
1283
  const response = {
@@ -1287,13 +1298,13 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1287
1298
  colors: true
1288
1299
  }));
1289
1300
  const upsertedUsers = request.upsert === true ? authCollectionAt(request.path) : void 0;
1290
- if (upsertedUsers) assertNoUserUpsert(authAdapter, upsertedUsers);
1301
+ if (upsertedUsers) assertNoUserUpsert(authAdapter, upsertedUsers.table);
1291
1302
  const usersCollection = request.status !== "existing" && request.upsert !== true && authAdapter?.prepareUserCreation ? authCollectionAt(request.path) : void 0;
1292
1303
  const caller = { roles: clientSessions.get(clientId)?.user?.roles ?? ["anon"] };
1293
1304
  if (usersCollection) {
1294
1305
  const body = request.values ?? {};
1295
1306
  assertUserCreationBodyValid(authAdapter, usersCollection, body, caller);
1296
- assertNoFieldOpsOnCreate(body, "A create", usersCollection);
1307
+ assertNoFieldOpsOnCreate(body, "A create", usersCollection.table);
1297
1308
  } else assertWriteRequest(request.path, request.values, request.status);
1298
1309
  assertNestedWrite(request.path, request.id === void 0 || request.status !== "existing" ? "create" : "update");
1299
1310
  const delegate = await getScopedDelegate();
@@ -1309,7 +1320,7 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1309
1320
  status: request.status,
1310
1321
  ...upsertOptions(request)
1311
1322
  });
1312
- const created = usersCollection ? await createUserThroughAuthCollection(authAdapter, usersCollection, values ?? {}, caller, write) : void 0;
1323
+ const created = usersCollection ? await createUserThroughAuthTable(authAdapter, usersCollection, values ?? {}, caller, write) : void 0;
1313
1324
  const row = created ? {
1314
1325
  ...created.row,
1315
1326
  ...created.delivery
@@ -1358,9 +1369,9 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1358
1369
  case "CHECK_UNIQUE_FIELD":
1359
1370
  {
1360
1371
  wsDebug("🔍 [WebSocket Server] Processing CHECK_UNIQUE_FIELD request");
1361
- const { path, name, value, id, collection } = payload;
1372
+ const { path, name, value, id } = payload;
1362
1373
  if (typeof name === "string") assertReadRequest(path, { filter: { [name]: ["==", value] } });
1363
- const isUnique = await (await getScopedDelegate()).checkUniqueField(path, name, value, id, collection);
1374
+ const isUnique = await (await getScopedDelegate()).checkUniqueField(path, name, value, id);
1364
1375
  wsDebug("🔍 [WebSocket Server] CHECK_UNIQUE_FIELD result:", isUnique);
1365
1376
  const response = {
1366
1377
  type: "CHECK_UNIQUE_FIELD_SUCCESS",
@@ -1698,4 +1709,4 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1698
1709
  //#endregion
1699
1710
  export { createPostgresWebSocket as a, websocket_exports as c, TOO_MANY_SOCKETS_CLOSE_CODE as i, PUBLIC_TYPES as n, isSocketRealtimeService as o, SESSION_ENDED_CLOSE_CODE as r, socketRealtimeMissing as s, ADMIN_PLANE_TYPES as t };
1700
1711
 
1701
- //# sourceMappingURL=websocket-B7ex6AQM.js.map
1712
+ //# sourceMappingURL=websocket-BevXvwfo.js.map