@rebasepro/server-postgres 0.16.0 → 0.16.1-canary.g041c925

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 (90) hide show
  1. package/dist/PostgresAdapter.d.ts +1 -1
  2. package/dist/PostgresBackendDriver.d.ts +16 -7
  3. package/dist/PostgresBootstrapper.d.ts +6 -6
  4. package/dist/auth/services.d.ts +1 -1
  5. package/dist/backup/backup-cron.d.ts +1 -1
  6. package/dist/backup/backup-service.d.ts +2 -2
  7. package/dist/backup/index.d.ts +4 -4
  8. package/dist/{backup-service-BZoixhVl.js → backup-service-FN6V3rVi.js} +4 -4
  9. package/dist/{backup-service-BZoixhVl.js.map → backup-service-FN6V3rVi.js.map} +1 -1
  10. package/dist/collections/PostgresCollectionRegistry.d.ts +1 -1
  11. package/dist/collections/buildRegistry.d.ts +1 -1
  12. package/dist/collections/validate-relations.d.ts +1 -1
  13. package/dist/{connection-BuZ97wsr.js → connection-GOKU3Hu5.js} +34 -7
  14. package/dist/connection-GOKU3Hu5.js.map +1 -0
  15. package/dist/connection.d.ts +16 -0
  16. package/dist/data-transformer.d.ts +1 -1
  17. package/dist/{ensure-collection-policies-BVFb2olB.js → ensure-collection-policies-B01cv9UC.js} +4 -4
  18. package/dist/{ensure-collection-policies-BVFb2olB.js.map → ensure-collection-policies-B01cv9UC.js.map} +1 -1
  19. package/dist/{auth-users-columns-CgyPWQ18.js → ensure-collection-tables-CvW6tbI7.js} +1482 -12
  20. package/dist/ensure-collection-tables-CvW6tbI7.js.map +1 -0
  21. package/dist/index.d.ts +16 -16
  22. package/dist/index.es.js +2183 -1817
  23. package/dist/index.es.js.map +1 -1
  24. package/dist/{rls-bootstrap-sql-B5Sajku6.js → rls-bootstrap-sql-DAwWHs81.js} +3 -3
  25. package/dist/{rls-bootstrap-sql-B5Sajku6.js.map → rls-bootstrap-sql-DAwWHs81.js.map} +1 -1
  26. package/dist/{rls-enforcement-Ch0T6OwW.js → rls-enforcement-eSahD7ec.js} +13 -3
  27. package/dist/rls-enforcement-eSahD7ec.js.map +1 -0
  28. package/dist/schema/classify-change.d.ts +82 -0
  29. package/dist/schema/dynamic-tables.d.ts +1 -1
  30. package/dist/schema/ensure-collection-policies.d.ts +1 -1
  31. package/dist/schema/ensure-collection-tables.d.ts +93 -2
  32. package/dist/schema/generate-schema-commit.d.ts +136 -0
  33. package/dist/schema/generated-schema-staleness.d.ts +19 -0
  34. package/dist/schema/introspect-db-constraints.d.ts +1 -1
  35. package/dist/schema/introspect-db-logic.d.ts +3 -3
  36. package/dist/schema/introspect-db-project.d.ts +1 -1
  37. package/dist/schema/introspect-db-queries.d.ts +1 -1
  38. package/dist/schema/introspect-db-structure.d.ts +2 -2
  39. package/dist/schema/introspect-runtime.d.ts +1 -1
  40. package/dist/schema/vector-index.d.ts +88 -0
  41. package/dist/services/BranchService.d.ts +2 -2
  42. package/dist/services/FetchService.d.ts +4 -4
  43. package/dist/services/PersistService.d.ts +5 -5
  44. package/dist/services/RelationService.d.ts +3 -3
  45. package/dist/services/RelationWriteService.d.ts +3 -3
  46. package/dist/services/cdc/junction-tables.d.ts +1 -1
  47. package/dist/services/cdc/trigger-cdc.d.ts +1 -1
  48. package/dist/services/channel-bus/PostgresChannelBus.d.ts +1 -1
  49. package/dist/services/channel-bus/index.d.ts +2 -2
  50. package/dist/services/collection-helpers.d.ts +1 -1
  51. package/dist/services/dataService.d.ts +10 -10
  52. package/dist/services/index.d.ts +4 -4
  53. package/dist/services/junction-writes.d.ts +2 -2
  54. package/dist/services/nested-path.d.ts +1 -1
  55. package/dist/services/realtimeService.d.ts +3 -3
  56. package/dist/services/row-pipeline.d.ts +1 -1
  57. package/dist/services/write-denial.d.ts +1 -1
  58. package/dist/{src-BBFsDaeA.js → src-DolrXONo.js} +93 -1
  59. package/dist/src-DolrXONo.js.map +1 -0
  60. package/dist/utils/drizzle-conditions.d.ts +2 -2
  61. package/dist/{websocket-BVgDVO-V.js → websocket-7Dp77lTh.js} +43 -6
  62. package/dist/websocket-7Dp77lTh.js.map +1 -0
  63. package/dist/websocket.d.ts +29 -2
  64. package/package.json +7 -7
  65. package/src/PostgresBackendDriver.ts +41 -2
  66. package/src/backup/backup-service.ts +1 -1
  67. package/src/cli-helpers.ts +3 -2
  68. package/src/connection.ts +37 -3
  69. package/src/databasePoolManager.ts +5 -2
  70. package/src/schema/classify-change.ts +436 -0
  71. package/src/schema/ensure-collection-tables.test.ts +168 -1
  72. package/src/schema/ensure-collection-tables.ts +344 -14
  73. package/src/schema/generate-drizzle-schema-logic.ts +23 -11
  74. package/src/schema/generate-drizzle-schema.ts +13 -2
  75. package/src/schema/generate-postgres-ddl-logic.ts +16 -1
  76. package/src/schema/generate-postgres-ddl.ts +13 -2
  77. package/src/schema/generate-schema-commit.ts +242 -0
  78. package/src/schema/generated-schema-staleness.ts +114 -1
  79. package/src/schema/vector-index.ts +278 -0
  80. package/src/services/collection-helpers.ts +3 -2
  81. package/src/websocket.ts +36 -2
  82. package/dist/auth-users-columns-CgyPWQ18.js.map +0 -1
  83. package/dist/connection-BuZ97wsr.js.map +0 -1
  84. package/dist/ensure-collection-tables-BY1pHRD_.js +0 -840
  85. package/dist/ensure-collection-tables-BY1pHRD_.js.map +0 -1
  86. package/dist/rls-enforcement-Ch0T6OwW.js.map +0 -1
  87. package/dist/src-BBFsDaeA.js.map +0 -1
  88. package/dist/utils/table-classification.d.ts +0 -8
  89. package/dist/websocket-BVgDVO-V.js.map +0 -1
  90. package/src/utils/table-classification.ts +0 -16
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-DolrXONo.js","names":[],"sources":["../../types/src/types/filter-operators.ts","../../types/src/types/data_source.ts","../../types/src/types/collections.ts","../../types/src/types/rls-functions.ts","../../types/src/types/resources.ts","../../types/src/types/resource_kinds.ts"],"sourcesContent":["/**\n * Canonical filter operators and REST wire-format mappings.\n *\n * `WhereFilterOp` is THE operator type used at every layer — from React\n * components through the SDK, server, and down to the database driver.\n *\n * PostgREST short-codes (`eq`, `gt`, `cs`, …) exist **only** at the\n * HTTP wire boundary, handled by `serializeFilter` / `deserializeFilter`\n * in `@rebasepro/common`.\n *\n * ┌──────────────────────┬───────────────┬──────────────────────────────┐\n * │ Canonical │ REST short │ Meaning │\n * ├──────────────────────┼───────────────┼──────────────────────────────┤\n * │ \"==\" │ \"eq\" │ Equal │\n * │ \"!=\" │ \"neq\" │ Not equal │\n * │ \">\" │ \"gt\" │ Greater than │\n * │ \">=\" │ \"gte\" │ Greater than or equal │\n * │ \"<\" │ \"lt\" │ Less than │\n * │ \"<=\" │ \"lte\" │ Less than or equal │\n * │ \"in\" │ \"in\" │ Value in list │\n * │ \"not-in\" │ \"nin\" │ Value not in list │\n * │ \"array-contains\" │ \"cs\" │ Array contains element │\n * │ \"array-contains-any\" │ \"csa\" │ Array contains any of │\n * │ \"like\" │ \"like\" │ SQL LIKE (case-sensitive) │\n * │ \"ilike\" │ \"ilike\" │ SQL ILIKE (case-insensitive) │\n * │ \"not-like\" │ \"nlike\" │ NOT LIKE (case-sensitive) │\n * │ \"not-ilike\" │ \"nilike\" │ NOT ILIKE (case-insensitive) │\n * │ \"is-null\" │ \"isnull\" │ Field IS NULL │\n * │ \"is-not-null\" │ \"notnull\" │ Field IS NOT NULL │\n * └──────────────────────┴───────────────┴──────────────────────────────┘\n *\n * Pattern matching (`like`/`ilike`) uses SQL wildcard syntax: `%` matches any\n * sequence of characters, `_` matches a single character. On MongoDB these are\n * translated to anchored regular expressions; Firestore has no native pattern\n * matching and rejects these operators (use `searchString` instead).\n *\n * @module\n */\n\n/**\n * Canonical sort representation: `[fieldName, direction]`.\n *\n * Used in `FindParams.orderBy`, `collection.sort`, and `FilterPreset.sort`.\n * The colon-string form (`\"field:direction\"`) exists only at the HTTP wire\n * boundary, handled by `serializeOrderBy` / `deserializeOrderBy` in\n * `@rebasepro/common`.\n *\n * @group Models\n */\nexport type OrderByTuple<Key extends string = string> = [Key, \"asc\" | \"desc\"];\n\n/**\n * One sort key, or several applied in order of significance.\n *\n * ```ts\n * orderBy: [\"created_at\", \"desc\"] // one key\n * orderBy: [[\"roles\", \"asc\"], [\"created_at\", \"desc\"]] // roles, then newest first\n * ```\n *\n * The two forms are told apart by whether the first element is itself an\n * array, so a single tuple never needs wrapping and every existing caller\n * keeps working unchanged. `normalizeOrderBy` in `@rebasepro/common` collapses\n * both to the list form, which is what every layer below the call site speaks.\n *\n * Ties on the last key are broken by the row id, so a multi-key sort is a\n * total order and pages over it neither repeat nor skip rows.\n *\n * @group Models\n */\nexport type OrderBySpec<Key extends string = string> =\n | OrderBySortTuple<Key>\n | OrderBySortTuple<Key>[];\n\n/**\n * A sort key: a field name, or an aggregate over a to-many relation.\n *\n * @group Models\n */\nexport type SortKey<Key extends string = string> = Key | RelationAggregateSort;\n\n/**\n * `[sortKey, direction]` — the authoring form of {@link OrderByTuple}, which\n * additionally accepts a {@link RelationAggregateSort} object.\n *\n * The object never reaches a driver: `normalizeOrderBy` in `@rebasepro/common`\n * encodes it to its string spelling on the way down, and everything below that\n * point speaks plain `OrderByTuple`. See {@link RelationAggregateSort} for why\n * the wire form is a string.\n *\n * @group Models\n */\nexport type OrderBySortTuple<Key extends string = string> = [SortKey<Key>, \"asc\" | \"desc\"];\n\n/**\n * The aggregate functions a relation sort can apply.\n *\n * Five, and no `array_agg`/`string_agg`: an aggregate used as a sort key has to\n * produce something with an order, and these are the ones that do.\n *\n * @group Models\n */\nexport type RelationAggregateFn = \"min\" | \"max\" | \"count\" | \"sum\" | \"avg\";\n\n/**\n * Order rows by an aggregate over the rows a to-many relation reaches —\n * \"candidates, oldest waiting first\", \"clients, busiest first\".\n *\n * ```ts\n * // The date of each candidate's earliest open application.\n * orderBy: [[{ relation: \"applications\", field: \"created_at\", agg: \"min\" }, \"asc\"]]\n *\n * // How many applications each candidate has.\n * orderBy: [[{ relation: \"applications\", agg: \"count\" }, \"desc\"]]\n * ```\n *\n * This is the half of a queue that cannot be worked around client-side. A\n * *filter* over a relation can be approximated by denormalising a flag onto the\n * row; an *ordering* cannot be approximated at all once the result set is\n * paged, because the client only ever holds one page and the page was chosen by\n * the wrong order.\n *\n * Rows the relation reaches nothing from sort last ascending and first\n * descending — the placement Postgres gives a `NULL`, stated rather than\n * inherited, because the keyset comparison behind cursor paging has to agree\n * with it exactly. Ties are broken by the row id, so the order is total and\n * paging over it neither repeats nor skips.\n *\n * Compiled by the driver into a correlated subquery, so it is subject to the\n * reader's own row-level security on the target table: a related row the reader\n * cannot see does not contribute to the aggregate. Offered only where\n * {@link DataSourceCapabilities.relationAggregateSorts} says the driver can\n * compile it.\n *\n * @group Models\n */\nexport interface RelationAggregateSort {\n /** The to-many relation to aggregate over, by its name on this collection. */\n relation: string;\n\n /** The aggregate to apply. */\n agg: RelationAggregateFn;\n\n /**\n * The column of the *target* to aggregate. Required by every function\n * except `count`, which counts the related rows themselves when it is\n * omitted — and counts the rows whose column is non-null when it is not.\n */\n field?: string;\n}\n\n/** The wire spelling of a {@link RelationAggregateSort}: `min(applications.created_at)`. */\nconst RELATION_AGGREGATE_SORT_PATTERN = /^(min|max|count|sum|avg)\\(([^().]+)(?:\\.([^()]+))?\\)$/;\n\n/**\n * A {@link RelationAggregateSort} as a single string — `min(applications.created_at)`,\n * `count(applications)`.\n *\n * The wire form is a string because every layer below the call site already is\n * one: `OrderByTuple` is `[string, direction]`, the REST parameter is\n * `?orderBy=key:direction`, the driver contract takes `orderBy?: string |\n * OrderByTuple[]`, and a cursor names its keys by string. `_score` established\n * the same pattern — a sort key that is not a column, spelled as one — and this\n * reuses it rather than widening five signatures to carry an object that would\n * be flattened at the end anyway.\n *\n * SQL's own spelling, so the key reads as what it compiles to. Neither `:` nor\n * `,` appears in it, which is what keeps it safe in the colon-delimited wire\n * shorthand.\n *\n * @group Models\n */\nexport function encodeRelationAggregateSort(sort: RelationAggregateSort): string {\n return `${sort.agg}(${sort.relation}${sort.field ? `.${sort.field}` : \"\"})`;\n}\n\n/**\n * Read the string spelling back, or `undefined` if it is not one.\n *\n * `undefined` rather than a throw: this is asked of *every* sort key to find\n * out which kind it is, and an ordinary column name is not an error.\n *\n * @group Models\n */\nexport function parseRelationAggregateSort(key: string): RelationAggregateSort | undefined {\n const match = RELATION_AGGREGATE_SORT_PATTERN.exec(key);\n if (!match) return undefined;\n const [, agg, relation, field] = match;\n // `min()` and friends have nothing to aggregate without a column, and a\n // key that parses to a half-built sort would resolve to no expression and\n // be dropped — leaving the rows unsorted while the caller believes\n // otherwise. `count` is the one function that means something on its own.\n if (!field && agg !== \"count\") return undefined;\n return { agg: agg as RelationAggregateFn, relation, ...(field && { field }) };\n}\n\n/** Is this sort key the object form rather than a field name? */\nexport function isRelationAggregateSort(key: unknown): key is RelationAggregateSort {\n return typeof key === \"object\" && key !== null &&\n typeof (key as RelationAggregateSort).relation === \"string\" &&\n typeof (key as RelationAggregateSort).agg === \"string\";\n}\n\n/** A sort key in the single-string form every layer below the call site speaks. */\nexport function sortKeyToString(key: SortKey): string {\n return isRelationAggregateSort(key) ? encodeRelationAggregateSort(key) : key;\n}\n\n/**\n * Canonical filter operators supported across all database backends.\n * Each DB driver translates these to its native query format.\n *\n * @group Models\n */\nexport type WhereFilterOp =\n | \"<\"\n | \"<=\"\n | \"==\"\n | \"!=\"\n | \">=\"\n | \">\"\n | \"array-contains\"\n | \"in\"\n | \"not-in\"\n | \"array-contains-any\"\n | \"like\"\n | \"ilike\"\n | \"not-like\"\n | \"not-ilike\"\n | \"is-null\"\n | \"is-not-null\";\n\n/**\n * Used to define filters applied in collections.\n *\n * A single condition is a tuple `[operator, value]`.\n * Multiple conditions on the same field use an array of tuples.\n *\n * @example\n * // Single condition per field\n * { status: [\"==\", \"active\"], price: [\">=\", 9.99] }\n *\n * // Multiple conditions on one field\n * { age: [[\">=\", 18], [\"<\", 65]] }\n *\n * // Array operators\n * { role: [\"in\", [\"admin\", \"editor\"]] }\n * { tags: [\"array-contains\", \"featured\"] }\n *\n * // Pattern matching (SQL wildcards: % and _)\n * { name: [\"ilike\", \"%john%\"] }\n * { slug: [\"like\", \"post-%\"] }\n *\n * // Null checks (the value is ignored; `null` is conventional)\n * { deleted_at: [\"is-null\", null] }\n * { published_at: [\"is-not-null\", null] }\n *\n * @group Models\n */\nexport type FilterValues<Key extends string> =\n Partial<Record<Key, [WhereFilterOp, unknown] | [WhereFilterOp, unknown][]>>;\n\n/**\n * The field names a query may address on a row type: every column, plus a\n * dotted path reaching inside one — or *through a relation* to a column of the\n * related row.\n *\n * A dotted path is not checked at all, in either direction. That is a\n * deliberate loosening, and it is worth being exact about what it costs. The\n * root used to be checked: `\"meta.tag\"` required a `meta` column. It cannot\n * stay checked, because the other thing a dotted path now means is\n * `\"applications.status\"` — and `applications` is a *relation*, which comes\n * from the collection's `relations` and is not a column of `M` at all. There is\n * nothing in a generated row type that could validate one. `FindParams.include`\n * is `string[]` for exactly this reason and says so.\n *\n * So the guarantee moves rather than disappears: an unresolvable path is a 400\n * from the driver, not a silently dropped condition. See\n * `UnknownFilterFieldsMode` in `@rebasepro/server-postgres` — dropping a filter\n * key *widens* the read to every row, which is why that resolution fails\n * closed. A typo'd relation path is refused at runtime with the target\n * collection's real column list in the message.\n *\n * Undotted keys are unaffected and still checked against `keyof M`.\n *\n * When `M` is left at its default `Record<string, unknown>`, `keyof M` is\n * `string` and this collapses to `string`, so every query stays permissive.\n * That is what keeps an untyped `createRebaseClient()` behaving exactly as it\n * did before the row type was threaded through.\n *\n * @group Models\n */\nexport type FieldPath<M extends Record<string, unknown> = Record<string, unknown>> =\n | Extract<keyof M, string>\n | `${string}.${string}`;\n\n/**\n * Relaxed filter type that also accepts pre-serialized PostgREST strings.\n * **Internal only** — used at the wire-format boundary\n * (`serializeFilter` / `deserializeFilter` in `@rebasepro/common`).\n *\n * Application code, UI components, and SDK consumers should use\n * {@link FilterValues} instead.\n *\n * @internal\n */\nexport type WireFilterValues<Key extends string> =\n Partial<Record<Key, [WhereFilterOp, unknown] | [WhereFilterOp, unknown][] | string>>;\n\n/**\n * A pre-defined filter preset for quick access in the collection toolbar.\n * Users can select a preset to instantly apply a set of filters and\n * optionally a sort order.\n *\n * @group Models\n */\nexport interface FilterPreset<Key extends string = string> {\n /**\n * Display label shown in the preset menu.\n * If omitted, a summary is auto-generated from the filter keys.\n */\n label?: string;\n\n /**\n * The filter values to apply when this preset is selected.\n */\n filterValues: FilterValues<Key>;\n\n /**\n * Optional sort override to apply alongside the filter values.\n * One key, or several in order of significance.\n */\n sort?: OrderBySpec<Key>;\n}\n\n/**\n * PostgREST short-code operators. Wire format only — these never appear\n * in application code. Used by `serializeFilter`/`deserializeFilter`\n * in `@rebasepro/common`.\n */\nexport type RestFilterOp =\n | \"eq\" | \"neq\"\n | \"gt\" | \"gte\"\n | \"lt\" | \"lte\"\n | \"in\" | \"nin\"\n | \"cs\" | \"csa\"\n | \"like\" | \"ilike\"\n | \"nlike\" | \"nilike\"\n | \"isnull\" | \"notnull\";\n\n/** Maps canonical operators to their REST short-code equivalents. */\nexport const CANONICAL_TO_REST: Readonly<Record<WhereFilterOp, RestFilterOp>> = {\n \"==\": \"eq\",\n \"!=\": \"neq\",\n \">\": \"gt\",\n \">=\": \"gte\",\n \"<\": \"lt\",\n \"<=\": \"lte\",\n \"in\": \"in\",\n \"not-in\": \"nin\",\n \"array-contains\": \"cs\",\n \"array-contains-any\": \"csa\",\n \"like\": \"like\",\n \"ilike\": \"ilike\",\n \"not-like\": \"nlike\",\n \"not-ilike\": \"nilike\",\n \"is-null\": \"isnull\",\n \"is-not-null\": \"notnull\"\n};\n\n/** Maps REST short-code operators to their canonical equivalents. */\nexport const REST_TO_CANONICAL: Readonly<Record<RestFilterOp, WhereFilterOp>> = {\n \"eq\": \"==\",\n \"neq\": \"!=\",\n \"gt\": \">\",\n \"gte\": \">=\",\n \"lt\": \"<\",\n \"lte\": \"<=\",\n \"in\": \"in\",\n \"nin\": \"not-in\",\n \"cs\": \"array-contains\",\n \"csa\": \"array-contains-any\",\n \"like\": \"like\",\n \"ilike\": \"ilike\",\n \"nlike\": \"not-like\",\n \"nilike\": \"not-ilike\",\n \"isnull\": \"is-null\",\n \"notnull\": \"is-not-null\"\n};\n\n/**\n * Operators that test for null/not-null and therefore ignore their value.\n * Codecs normalize the value of these conditions to `null`.\n */\nexport const NULL_OPS: ReadonlySet<WhereFilterOp> = new Set<WhereFilterOp>([\n \"is-null\", \"is-not-null\"\n]);\n\n/**\n * Every canonical operator, in a stable order. Useful for engine capability\n * declarations ({@link DataSourceCapabilities.filterOperators}) and for\n * building operator subsets.\n * @group Models\n */\nexport const ALL_WHERE_FILTER_OPS: readonly WhereFilterOp[] = [\n \"<\", \"<=\", \"==\", \"!=\", \">=\", \">\",\n \"in\", \"not-in\",\n \"array-contains\", \"array-contains-any\",\n \"like\", \"ilike\", \"not-like\", \"not-ilike\",\n \"is-null\", \"is-not-null\"\n];\n\n/** All canonical operator strings for runtime validation. */\nconst CANONICAL_OPS: ReadonlySet<string> = new Set<WhereFilterOp>(ALL_WHERE_FILTER_OPS);\n\n/**\n * The REST table as a `Map`, because the key `toCanonicalOp` is handed comes\n * off the wire.\n *\n * Indexed as a plain object, every `Object.prototype` member answered:\n * `toCanonicalOp(\"valueOf\")` returned the inherited *function* as though it\n * were a `WhereFilterOp`, and every caller here treats a defined result as\n * \"known operator\". Same defect the REST codec's own lookup tables were\n * converted away from in `filter-dialect.ts`; this is the copy that survived\n * one package over, and it now sits under the operator validation the REST\n * parser does, which would otherwise have admitted `[\"constructor\", x]`.\n */\nconst REST_OP_LOOKUP: ReadonlyMap<string, WhereFilterOp> = new Map<string, WhereFilterOp>(\n Object.entries(REST_TO_CANONICAL) as [string, WhereFilterOp][]\n);\n\n/**\n * Resolve any operator string (canonical or REST short-code) to its\n * canonical `WhereFilterOp` form. Returns `undefined` for unknown operators.\n *\n * @example\n * toCanonicalOp(\"==\") // \"==\"\n * toCanonicalOp(\"eq\") // \"==\"\n * toCanonicalOp(\"cs\") // \"array-contains\"\n * toCanonicalOp(\"xyz\") // undefined\n */\nexport function toCanonicalOp(op: string): WhereFilterOp | undefined {\n if (CANONICAL_OPS.has(op)) return op as WhereFilterOp;\n return REST_OP_LOOKUP.get(op);\n}\n","import { ALL_WHERE_FILTER_OPS, WhereFilterOp } from \"./filter-operators\";\n\n/**\n * Describes the capabilities and features supported by a data source (driver).\n *\n * Each driver (Postgres, Firebase, MongoDB, etc.) declares which features it\n * supports. The admin uses this descriptor to:\n * - Show/hide editor tabs (e.g. Relations for SQL, Subcollections for Firebase)\n * - Filter the property type picker (e.g. `relation` for SQL, `reference` for Firebase)\n * - Toggle driver-specific form controls (e.g. `columnType` for SQL)\n *\n * @group Models\n */\nexport interface DataSourceCapabilities {\n /** Unique driver key (e.g. \"postgres\", \"firestore\", \"mongodb\") */\n key: string;\n\n /** Human-readable label for the UI (e.g. \"PostgreSQL\", \"Firebase / Firestore\") */\n label: string;\n\n // ── Feature flags ─────────────────────────────────────────────────\n /** Does this source support SQL-style relations (JOINs)? */\n supportsRelations: boolean;\n\n /** Does this source support nested subcollections? */\n supportsSubcollections: boolean;\n\n /** Does this source support Row Level Security policies? */\n supportsRLS: boolean;\n\n /** Does this source support document references (Firebase-style)? */\n supportsReferences: boolean;\n\n /** Does this source support SQL column type annotations? */\n supportsColumnTypes: boolean;\n\n /** Does this source support real-time listeners? */\n supportsRealtime: boolean;\n\n /**\n * Does this source store vectors natively?\n *\n * `VectorProperty` carries a `dimensions` and is pgvector-shaped. It was\n * the one driver-specific property kind with no flag to gate it, so unlike\n * every other field in this descriptor there was not even a runtime answer\n * to appeal to — a Firestore collection could declare an embedding column\n * and no driver would do anything with it.\n */\n supportsVectors: boolean;\n\n /**\n * Canonical filter operators this engine can execute.\n *\n * The admin UI intersects this set with the property-type defaults and\n * any per-property narrowing (`property.ui.filterOperators`) to decide\n * which operators to offer in filter fields — so an engine that cannot\n * run `ilike` (e.g. Firestore) never shows a \"Contains\" filter that\n * would throw at query time.\n */\n filterOperators: readonly WhereFilterOp[];\n\n /**\n * Relation kinds this engine's driver can compile into a filter.\n *\n * Only `belongsTo` puts a column on the row being filtered; the others are\n * answered with a correlated subquery over the junction or the target\n * table, which not every driver can build. An engine with no relations at\n * all declares none.\n *\n * The admin uses this to decide whether a relation column offers a filter\n * control. Offering one an engine cannot answer is not cosmetic: a driver\n * that drops the key it cannot resolve *widens* the read to every row, and\n * one that fails closed answers a control the admin itself put on screen\n * with a 400.\n *\n * Optional, so a third-party driver registered before this existed still\n * compiles. Omitted means {@link DEFAULT_FILTERABLE_RELATION_KINDS} — the\n * one kind that is a plain column comparison, which every relational\n * driver can do. The subquery kinds are a real capability and have to be\n * claimed rather than assumed: assuming them wrongly is the widening.\n */\n filterableRelationKinds?: readonly string[];\n\n /**\n * Can a filter address a *column of the related row* — `applications.status`\n * — rather than only the related row's id?\n *\n * A separate capability from {@link filterableRelationKinds} because it is\n * a separate subquery: the id filter stops at the junction, one of these\n * reaches the target table and compares one of its columns. A driver can\n * do the first and not the second.\n *\n * Optional and defaulting to **false**, for the reason the relation kinds\n * default narrow: an unclaimed capability that the admin assumes is there\n * produces a control whose query the driver answers by dropping the key —\n * and a dropped filter key widens the read to every row.\n *\n * Meaningless without {@link supportsRelations}; a driver with no relations\n * has nothing to reach through.\n */\n supportsRelationFieldFilters?: boolean;\n\n /**\n * Can a sort key be an aggregate over a to-many relation — \"oldest waiting\n * first\", \"busiest first\"?\n *\n * Compiled as a correlated scalar subquery in `ORDER BY`, which a document\n * store cannot express at all. Optional and defaulting to **false**.\n *\n * A wrongly claimed sort capability fails differently from a wrongly\n * claimed filter one, and worse in one respect: a driver that cannot\n * resolve the key drops the `ORDER BY` and answers 200 with rows in\n * whatever order the database pleased, which reads as a sorted list. Paging\n * over that repeats and skips rows.\n */\n relationAggregateSorts?: boolean;\n\n // ── Admin capability flags ───────────────────────────────────────\n /** Does this source support SQL admin operations (SQL editor, EXPLAIN, etc.)? */\n supportsSQLAdmin: boolean;\n\n /** Does this source support document admin operations (aggregation, stats)? */\n supportsDocumentAdmin: boolean;\n\n /** Does this source support schema admin (unmapped tables, table metadata)? */\n supportsSchemaAdmin: boolean;\n}\n\n/**\n * Subset of DataSourceCapabilities containing only feature flags.\n * Useful when you only need to check capabilities without UI metadata.\n * @group Models\n */\nexport type DataSourceFeatures = Omit<DataSourceCapabilities, \"key\" | \"label\">;\n\n/**\n * The default data-source key, used when a collection does not name a\n * `dataSource`. Shared by the frontend router and the backend driver\n * registry so both agree on \"the default database\".\n * @group Models\n */\nexport const DEFAULT_DATA_SOURCE_KEY = \"(default)\";\n\n/**\n * How the *frontend* reaches a data source.\n *\n * - `\"server\"` — through the Rebase backend (the `RebaseClient`). The backend\n * holds the actual database adapter and routes by data-source key. This is\n * the default and covers Postgres, MongoDB, and any other server-mediated\n * engine.\n * - `\"direct\"` — straight from the client to the external backend via its own\n * SDK driver (e.g. Firestore). The Rebase backend is not in the data path.\n * - `\"custom\"` — a developer-supplied {@link DataDriver}, transport unspecified.\n *\n * @group Models\n */\nexport type DataSourceTransport = \"server\" | \"direct\" | \"custom\";\n\n/**\n * Declarative definition of a data source — a named place data lives.\n *\n * Declared once and shared front and back: the frontend uses it to decide\n * transport (client vs direct driver), the backend uses the same `key` to\n * resolve a database adapter, and the editor derives capabilities from\n * `engine`. Collections reference a definition by its `key` via\n * `collection.dataSource`.\n *\n * @group Models\n */\nexport interface DataSourceDefinition {\n /**\n * Unique identifier for this data source. Collections point at it via\n * `dataSource`. Defaults to {@link DEFAULT_DATA_SOURCE_KEY}.\n */\n key: string;\n\n /**\n * The engine backing this data source (e.g. `\"postgres\"`, `\"mongodb\"`,\n * `\"firestore\"`, or a custom id). Determines the\n * {@link DataSourceCapabilities} surfaced in the editor.\n */\n engine: string;\n\n /**\n * How the frontend reaches this source. Optional — when omitted it is\n * inferred: `\"direct\"` if the definition carries a client-side driver,\n * `\"server\"` otherwise.\n */\n transport?: DataSourceTransport;\n\n /**\n * The physical database/schema/Firestore-database within the engine.\n * Threaded to drivers/adapters as the existing `databaseId` runtime\n * parameter. Defaults to the engine's own default.\n */\n databaseId?: string;\n\n /** Human-readable label for the UI. */\n label?: string;\n}\n\n/**\n * The resolved data source for a collection: the single source of truth that\n * the frontend router, backend registry, and editor all derive from.\n * Produced by `resolveDataSource(collection, registry)`.\n *\n * @group Models\n */\nexport interface ResolvedDataSource {\n /** Data-source key (routing key, shared front + back). */\n key: string;\n /** Engine backing the source (drives capabilities). */\n engine: string;\n /** Frontend transport. */\n transport: DataSourceTransport;\n /** Within-engine instance, if any (the `databaseId` runtime param). */\n databaseId?: string;\n /** Capabilities derived from {@link engine}. */\n capabilities: DataSourceCapabilities;\n}\n\n/**\n * Relation kinds assumed filterable when a driver does not say.\n *\n * `belongsTo` alone: its filter is a comparison on a column of the row being\n * filtered, the one shape that needs no query construction a driver might not\n * have. Everything else is a correlated subquery over another table.\n *\n * @group Models\n */\nexport const DEFAULT_FILTERABLE_RELATION_KINDS: readonly string[] = [\"belongsTo\"];\n\n// ── Built-in driver capabilities ─────────────────────────────────────\n\n/** @group Models */\nexport const POSTGRES_CAPABILITIES: DataSourceCapabilities = {\n key: \"postgres\",\n label: \"PostgreSQL\",\n supportsRelations: true,\n supportsSubcollections: false,\n supportsRLS: true,\n supportsReferences: false,\n supportsColumnTypes: true,\n supportsRealtime: true,\n supportsVectors: true,\n filterOperators: ALL_WHERE_FILTER_OPS,\n // `via` is absent: its join path is authored source → target with no\n // stated inverse, so the driver has nothing to reverse into a filter.\n filterableRelationKinds: [\"belongsTo\", \"manyToMany\", \"hasMany\", \"hasOne\"],\n supportsRelationFieldFilters: true,\n relationAggregateSorts: true,\n supportsSQLAdmin: true,\n supportsDocumentAdmin: false,\n supportsSchemaAdmin: true\n};\n\n/** @group Models */\nexport const FIREBASE_CAPABILITIES: DataSourceCapabilities = {\n key: \"firestore\",\n label: \"Firebase / Firestore\",\n supportsRelations: false,\n supportsSubcollections: true,\n supportsRLS: false,\n supportsReferences: true,\n supportsColumnTypes: false,\n supportsRealtime: true,\n supportsVectors: false,\n // Firestore has no SQL pattern matching — the driver throws on the LIKE\n // family, so the UI must never offer it.\n filterOperators: ALL_WHERE_FILTER_OPS.filter(op =>\n op !== \"like\" && op !== \"ilike\" && op !== \"not-like\" && op !== \"not-ilike\"),\n // No relations at all — a document store links by reference. Nothing to\n // reach through, so neither of the two relation-reaching features either.\n filterableRelationKinds: [],\n supportsRelationFieldFilters: false,\n relationAggregateSorts: false,\n supportsSQLAdmin: false,\n supportsDocumentAdmin: false,\n supportsSchemaAdmin: false\n};\n\n/** @group Models */\nexport const MONGODB_CAPABILITIES: DataSourceCapabilities = {\n key: \"mongodb\",\n label: \"MongoDB\",\n supportsRelations: false,\n supportsSubcollections: true,\n supportsRLS: false,\n supportsReferences: true,\n supportsColumnTypes: false,\n supportsRealtime: false,\n supportsVectors: false,\n filterOperators: ALL_WHERE_FILTER_OPS,\n filterableRelationKinds: [],\n supportsRelationFieldFilters: false,\n relationAggregateSorts: false,\n supportsSQLAdmin: false,\n supportsDocumentAdmin: true,\n supportsSchemaAdmin: true\n};\n\n/**\n * Fallback capabilities when the driver is unknown.\n * Enables everything so nothing is hidden unexpectedly.\n * @group Models\n */\nexport const DEFAULT_CAPABILITIES: DataSourceCapabilities = {\n key: \"(default)\",\n label: \"Default\",\n supportsRelations: true,\n supportsSubcollections: true,\n supportsRLS: true,\n supportsReferences: true,\n supportsColumnTypes: true,\n supportsRealtime: true,\n supportsVectors: true,\n filterOperators: ALL_WHERE_FILTER_OPS,\n // The exception to this descriptor's \"enable everything\" rule. The other\n // flags hide a tab or a picker when they are wrong; this one decides\n // whether a query is sent that an unknown driver may answer by dropping\n // the condition — which returns every row rather than none.\n filterableRelationKinds: DEFAULT_FILTERABLE_RELATION_KINDS,\n // Narrow for the same reason, and more sharply. An unknown driver that is\n // assumed to compile these answers by dropping the key: the filter widens\n // the read to every row, and the sort comes back unordered while looking\n // sorted. Both have to be claimed.\n supportsRelationFieldFilters: false,\n relationAggregateSorts: false,\n supportsSQLAdmin: true,\n supportsDocumentAdmin: true,\n supportsSchemaAdmin: true\n};\n\nconst CAPABILITIES_REGISTRY: Record<string, DataSourceCapabilities> = {\n postgres: POSTGRES_CAPABILITIES,\n firestore: FIREBASE_CAPABILITIES,\n mongodb: MONGODB_CAPABILITIES,\n \"(default)\": DEFAULT_CAPABILITIES\n};\n\n/**\n * Look up capabilities for a given engine key.\n * If `engine` is undefined or not found, returns `DEFAULT_CAPABILITIES`.\n * @group Models\n */\nexport function getDataSourceCapabilities(engine?: string): DataSourceCapabilities {\n if (!engine) return POSTGRES_CAPABILITIES; // postgres is the default engine\n return CAPABILITIES_REGISTRY[engine] ?? DEFAULT_CAPABILITIES;\n}\n\n/**\n * Register custom capabilities for a third-party driver.\n * @group Models\n */\nexport function registerDataSourceCapabilities(capabilities: DataSourceCapabilities): void {\n CAPABILITIES_REGISTRY[capabilities.key] = capabilities;\n}\n","import type { CollectionCallbacks } from \"./entity_callbacks\";\n\nimport type { EnumValues, Properties, PostgresProperties, FirebaseProperties, MongoProperties } from \"./properties\";\n\nimport type { User } from \"../users\";\nimport type { EmailSendResult } from \"../controllers/email\";\nimport type { Relation } from \"./relations\";\nimport type { SecurityRule } from \"./security_rules\";\nimport { getDataSourceCapabilities } from \"./data_source\";\nimport type { WhereFilterOp, FilterValues, FilterPreset } from \"./filter-operators\";\nimport type { SearchConfig } from \"./search\";\n\n/**\n * Base interface containing all driver-agnostic collection properties.\n * Use {@link PostgresCollectionConfig} or {@link FirebaseCollectionConfig} for\n * driver-specific type safety, or {@link CollectionConfig} when you\n * need to handle any collection regardless of backend.\n *\n * @group Models\n */\nexport interface BaseCollectionConfig<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User> {\n\n /**\n * The collection's identity. Required, and the value nearly everything else\n * keys on:\n *\n * - the REST path — `/api/data/<slug>`\n * - the SDK accessor — `client.data.<slug>` / `client.data.collection(\"<slug>\")`\n * - the admin panel's URL\n * - the target of a `reference` or `relation` property\n *\n * Conventionally kebab-case and plural (`blog-posts`). It is independent of\n * {@link table}: the slug is what callers say, the table is where the rows\n * live, and renaming one does not rename the other.\n *\n * Treat it as frozen once anything has shipped against it — changing a slug\n * changes every URL and every generated accessor at once.\n *\n * @example\n * defineCollection({\n * slug: \"blog-posts\", // /api/data/blog-posts, client.data.blogPosts\n * table: \"posts\",\n * properties: { … }\n * })\n */\n slug: string;\n\n /**\n * Name of the collection, typically plural.\n * E.g. `Products`, `Blog`\n */\n name: string;\n\n /**\n * Singular name of an entry in this collection\n * E.g. `Product`, `Blog entry`\n */\n singularName?: string;\n\n /**\n * Optional description of this view. You can use Markdown.\n */\n description?: string;\n\n /**\n * Child collections nested under entities of this collection.\n * Populated automatically during normalization from driver-specific fields\n * (e.g. Firebase `subcollections`, Postgres `relations` with many-cardinality).\n *\n * Custom drivers can set this directly to expose child collections to the UI.\n */\n childCollections?: () => CollectionConfig<Record<string, unknown>>[];\n\n\n /**\n * The data source this collection belongs to — the routing key shared by\n * the frontend router and the backend driver registry. It points at a\n * {@link DataSourceDefinition} registered on `<Rebase dataSources>` (front)\n * and `initializeRebaseBackend({ dataSources })` (back).\n *\n * If not specified, the default data source `\"(default)\"` is used, which\n * for a standard Rebase app is the server-mediated Postgres backend.\n *\n * @example\n * // Default data source (server-mediated Postgres)\n * { slug: \"products\" }\n *\n * // A direct-transport Firestore data source registered as \"analytics\"\n * { slug: \"events\", dataSource: \"analytics\" }\n */\n dataSource?: string;\n\n /**\n * The database engine backing this collection (`\"postgres\"`, `\"firestore\"`,\n * `\"mongodb\"`, or a custom id).\n *\n * On concrete collection types ({@link PostgresCollectionConfig},\n * {@link FirebaseCollectionConfig}, {@link MongoDBCollectionConfig}) this is a literal\n * discriminant. On the base type it is optional and gets stamped\n * automatically during collection normalization from the registered\n * {@link DataSourceDefinition}.\n *\n * Prefer setting {@link dataSource} and letting the engine be resolved.\n */\n engine?: string;\n\n /**\n * Which database within the engine.\n * - For Firestore: The Firestore database ID (e.g., for multi-database projects)\n * - For PostgreSQL: Schema or database name\n * - For MongoDB: Database name\n *\n * If not specified, the default database of the engine is used. Resolved\n * from the collection's {@link DataSourceDefinition} when omitted here.\n */\n databaseId?: string;\n\n /**\n * Set of properties that compose a entity\n */\n properties: Properties;\n\n\n\n\n\n\n\n\n\n\n\n\n /**\n * Mark this collection as an authentication collection.\n * When true, this collection is used for user management, login, password hashing, and invitation flows.\n */\n auth?: boolean | AuthCollectionConfig;\n\n\n\n\n\n\n\n /**\n * Row-level authorization rules for this collection.\n *\n * Driver-agnostic on purpose, unlike `disableDefaultPolicies`, `table` and\n * `relations`, which are declared on {@link PostgresCollectionConfig} only.\n * The rules are a *contract* — who may read or write which rows — and each\n * engine enforces it its own way:\n *\n * - **Postgres** compiles them to real `CREATE POLICY` statements and lets\n * the database enforce them (see {@link PostgresCollectionConfig.securityRules},\n * which narrows this with the raw-SQL details).\n * - **MongoDB** translates them into a query filter it AND-s into every\n * read and write, honouring `access`, `ownerField`, `roles`, `mode` and\n * the `operation`/`operations` selectors, and making a best effort at raw\n * `using`/`withCheck` SQL.\n * - **Firestore** does not implement them at all; its own rules language is\n * evaluated by Google, not from here. `supportsRLS` on\n * {@link DataSourceCapabilities} reports which engines generate policies,\n * which is not the same question as whether an engine honours a rule.\n */\n securityRules?: readonly SecurityRule[];\n\n /**\n * This interface defines all the callbacks that can be used when a entity\n * is being created, updated or deleted.\n * Useful for adding your own logic or blocking the execution of the operation.\n */\n readonly callbacks?: CollectionCallbacks<M, USER>;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n /**\n * User id of the owner of this collection. This is used only by plugins, or if you\n * are writing custom code\n */\n ownerId?: string;\n\n /**\n * Arbitrary key-value metadata for external consumers.\n * Not interpreted by Rebase — passed through serialization unchanged.\n * Used by domain apps to store custom per-collection config.\n */\n metadata?: Record<string, unknown>;\n\n\n\n\n /**\n * If set to true, changes to the entity will be saved in a subcollection.\n * This prop has no effect if the history plugin is not enabled\n */\n history?: boolean;\n\n /**\n * Whether a write naming a field this collection does not declare is\n * rejected with a 400. Defaults to `true`.\n *\n * Set to `false` where a column really does exist that the config never\n * declared — populated by a trigger, or introspected rather than declared —\n * and callers need to write it. The column still has to exist: the driver\n * checks the key against the table's own columns whatever this is set to,\n * because a key with no column behind it is not passed to the database and\n * refused, it is dropped from the statement and answered 201.\n *\n * It does not let a typo through to Postgres for Postgres to judge. That is\n * what this flag was documented as doing, and no such judgment ever\n * happened.\n */\n strictWrites?: boolean;\n\n\n\n\n\n\n\n\n}\n\n// ── Driver-specific collection types ──────────────────────────────────\n\n/**\n * A collection backed by PostgreSQL (or any SQL database).\n * Adds support for SQL-style relations (JOINs) and Row Level Security.\n *\n * Use this type instead of {@link CollectionConfig} when you want\n * compile-time safety that only SQL-relevant fields appear.\n *\n * @group Models\n */\nexport interface PostgresCollectionConfig<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User>\n extends BaseCollectionConfig<M, USER> {\n properties: PostgresProperties;\n\n /**\n * The database engine for this collection. For Postgres collections this\n * can be omitted (Postgres is the default) or set to `\"postgres\"`.\n */\n engine?: \"postgres\" | undefined;\n\n /**\n * The PostgreSQL table name for this collection.\n */\n table: string;\n\n /**\n * The PostgreSQL schema name for this table.\n * E.g. \"public\", \"rebase\", \"auth\".\n * If not specified, \"public\" is used (or the default search path).\n */\n schema?: string;\n\n /**\n * For SQL databases, you can define the relations between collections here.\n * Relations describe JOINs, foreign keys, and junction tables.\n */\n relations?: Relation[];\n\n /**\n * Security rules for this collection (PostgreSQL Row Level Security).\n * When defined, the schema generator will enable RLS on the table and\n * create the corresponding PostgreSQL policies.\n *\n * Supports three levels of expressiveness:\n * 1. **Convenience shortcuts** — `ownerField`, `access`, `roles`\n * 2. **Raw SQL** — `using` and `withCheck` for full PostgreSQL power\n * 3. **Combined** — mix shortcuts with `roles` for common patterns\n *\n * The authenticated user context is available in raw SQL via:\n * - `rebase.uid()` — the current user's ID\n * - `rebase.roles()` — comma-separated app role IDs\n * - `rebase.jwt()` — full JWT claims as JSONB\n */\n securityRules?: readonly SecurityRule[];\n\n /**\n * Opt out of the framework's default Row Level Security policies.\n *\n * The schema generator automatically injects, for every collection, a\n * baseline SELECT policy granting the trusted server context and the\n * `admin` role read access (reads run under a restricted role, so RLS\n * default-denies without it). For auth collections it additionally injects\n * a self-read policy (`id = rebase.uid()`) and an admin-only write gate\n * (INSERT/UPDATE/DELETE require the `admin` role or the trusted server\n * context), making privileged columns such as `roles` safe by default.\n *\n * Author-defined `securityRules` are permissive and broaden access on top\n * of these defaults. Set this flag to `true` to remove the defaults\n * entirely and take full responsibility for the collection's RLS.\n *\n * @default false\n */\n disableDefaultPolicies?: boolean;\n\n /**\n * Opt in to Postgres full-text search for this collection.\n *\n * Omit it and `.search()` keeps its existing behaviour exactly — an\n * `ILIKE '%term%'` across top-level string properties. Declare it and the\n * collection gains one generated `tsvector` column and a GIN index, and\n * `.search()` compiles to a ranked `@@ websearch_to_tsquery` against them.\n *\n * Postgres-only, like {@link VectorProperty}: the block is rejected at boot\n * on other engines rather than silently ignored.\n *\n * @see SearchConfig\n */\n search?: SearchConfig;\n}\n\n/**\n * A collection backed by Firebase / Firestore.\n * Adds support for subcollections (nested document collections).\n *\n * Use this type instead of {@link CollectionConfig} when you want\n * compile-time safety that only Firestore-relevant fields appear.\n *\n * @group Models\n */\nexport interface FirebaseCollectionConfig<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User>\n extends BaseCollectionConfig<M, USER> {\n /**\n * The database engine for this collection. Must be set to `\"firestore\"`.\n */\n engine: \"firestore\";\n\n /**\n * Set of properties that compose a entity.\n * Firestore collections support `reference` properties but not `relation`.\n */\n properties: FirebaseProperties;\n\n /**\n * The Firestore collection path to query. Defaults to `slug` if not set.\n * Use this when the Firestore path differs from the slug\n * (e.g., when a PostgreSQL collection already uses the same slug).\n *\n * @example\n * ```typescript\n * const fsCustomer: FirebaseCollectionConfig = {\n * slug: \"fs_customer\", // URL: /c/fs_customer\n * path: \"customer\", // Firestore path: customer\n * name: \"Customers (Firestore)\",\n * engine: \"firestore\",\n * properties: { ... }\n * };\n * ```\n */\n path?: string;\n\n /**\n * You can add subcollections to your entity in the same way you define the root\n * collections. The collections added here will be displayed when opening\n * the side dialog of a entity.\n */\n subcollections?: () => CollectionConfig<Record<string, unknown>>[];\n}\n\n/**\n * A collection backed by MongoDB.\n *\n * Use this type instead of {@link CollectionConfig} when you want\n * compile-time safety that only MongoDB-relevant fields appear.\n *\n * @group Models\n */\nexport interface MongoDBCollectionConfig<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User>\n extends BaseCollectionConfig<M, USER> {\n\n /**\n * The database engine for this collection. Must be set to `\"mongodb\"`.\n */\n engine: \"mongodb\";\n\n /**\n * Set of properties that compose a entity.\n * MongoDB collections support `reference` properties but not `relation`.\n */\n properties: MongoProperties;\n\n /**\n * The MongoDB collection name to use. Defaults to `slug` if not set.\n * Use this when the MongoDB collection name differs from the slug\n * (e.g., when a PostgreSQL collection already uses the same slug).\n *\n * @example\n * ```typescript\n * const mongoCustomer: MongoDBCollectionConfig = {\n * slug: \"mongo_customer\", // URL: /c/mongo_customer\n * path: \"customer\", // MongoDB collection: customer\n * name: \"Customers (MongoDB)\",\n * engine: \"mongodb\",\n * properties: { ... }\n * };\n * ```\n */\n path?: string;\n}\n\n/**\n * A collection backed by any data source.\n * This is a discriminated union — use {@link PostgresCollectionConfig},\n * {@link FirebaseCollectionConfig}, or {@link MongoDBCollectionConfig} for\n * driver-specific type safety.\n *\n * @group Models\n */\nexport type CollectionConfig<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User> =\n | PostgresCollectionConfig<M, USER>\n | FirebaseCollectionConfig<M, USER>\n | MongoDBCollectionConfig<M, USER>;\n\n/**\n * A collection of *any* row type.\n *\n * `CollectionConfig` is **invariant** in `M`: `callbacks` both consumes `M`\n * (`AfterReadProps<M>`) and produces it, so neither direction of assignment\n * holds. `CollectionConfig<SomeRow>` is therefore not assignable to a bare\n * `CollectionConfig`, whose `M` defaults to `Record<string, unknown>`.\n *\n * That matters wherever a collection is merely *referred to* rather than read\n * from. `defineCollection` returns a config whose `M` is inferred from the\n * properties — the whole point of it — so a field typed `() => CollectionConfig`\n * rejects every collection the builder produces, and `target: () => otherCollection`\n * (the documented way to point a relation at its other end) does not compile in\n * any project that uses the builder.\n *\n * `any` is deliberate and is what it is for here: these positions never read the\n * target's rows, they only identify which collection is meant, so there is no\n * type safety to preserve and invariance is pure obstruction.\n *\n * @group Models\n */\nexport type AnyCollectionConfig = CollectionConfig<any, any>;\n\n/**\n * Type guard for PostgreSQL collections.\n * Returns true if the collection uses the Postgres engine (or the default engine).\n *\n * Generic over the *input* type, and narrows by intersection rather than\n * replacement. Narrowing to a bare `PostgresCollectionConfig` discarded whatever\n * the caller actually had — most visibly the admin panel's view model, whose\n * flattened presentation fields vanished the moment a collection passed through\n * one of these guards.\n *\n * @group Models\n */\nexport function isPostgresCollectionConfig<C extends CollectionConfig<any, any>>(\n collection: C\n): collection is C & PostgresCollectionConfig<any, any> {\n return !collection.engine || collection.engine === \"postgres\";\n}\n\n/**\n * Narrows to the SQL collection fields — `table`, `relations`,\n * `disableDefaultPolicies` — by asking the engine's declared capabilities\n * rather than by naming Postgres.\n *\n * The two halves of this already existed and were never joined. The engine\n * split (`PostgresCollectionConfig` / `FirebaseCollectionConfig` /\n * `MongoDBCollectionConfig`) said which fields belong to which engine at the\n * type level; {@link DataSourceCapabilities} said the same thing at runtime,\n * down to a `supportsRelations` flag. So call sites guarded on the capability\n * and then read a field the base type had to declare for them — which is why\n * those fields were on the base, and why a MongoDB collection could be written\n * with a `table`.\n *\n * Prefer this over {@link isPostgresCollectionConfig} wherever the question is\n * \"does this collection live in a SQL table\", so a custom SQL engine\n * registered through `registerDataSourceCapabilities` is included.\n *\n * @group Models\n */\nexport function isRelationalCollectionConfig<C extends CollectionConfig<any, any>>(\n collection: C\n): collection is C & PostgresCollectionConfig<any, any> {\n return getDataSourceCapabilities(collection.engine).supportsRelations;\n}\n\n/**\n * Type guard for Firebase / Firestore collections.\n * @group Models\n */\nexport function isFirebaseCollectionConfig<C extends CollectionConfig<any, any>>(\n collection: C\n): collection is C & FirebaseCollectionConfig<any, any> {\n return collection.engine === \"firestore\";\n}\n\n/**\n * Type guard for MongoDB collections.\n * @group Models\n */\nexport function isMongoDBCollectionConfig<C extends CollectionConfig<any, any>>(\n collection: C\n): collection is C & MongoDBCollectionConfig<any, any> {\n return collection.engine === \"mongodb\";\n}\n\n/**\n * Returns the data path for a collection.\n * For Firestore or MongoDB collections with a `path`, returns that value;\n * otherwise falls back to `slug`.\n */\nexport function getCollectionDataPath<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User>(\n collection: CollectionConfig<M, USER>\n): string {\n if (isFirebaseCollectionConfig(collection) && collection.path) {\n return collection.path;\n }\n if (isMongoDBCollectionConfig(collection) && collection.path) {\n return collection.path;\n }\n return collection.slug;\n}\n\n/**\n * Reads a collection's driver-declared subcollections thunk (the `subcollections`\n * field) independent of engine identity, so engine-agnostic code doesn't have to\n * type-guard against a specific driver. Returns `undefined` when the collection\n * declares none.\n *\n * Pair with `getDataSourceCapabilities(engine).supportsSubcollections` to decide\n * whether the engine honours subcollections at all before reading them.\n * @group Models\n */\nexport function getDeclaredSubcollections<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User>(\n collection: CollectionConfig<M, USER>\n): (() => CollectionConfig<Record<string, unknown>>[]) | undefined {\n return (collection as FirebaseCollectionConfig<M, USER>).subcollections;\n}\n\n/**\n * Where the rows in an {@link EntityChildView} come from.\n *\n * The two are not the same thing, and conflating them is what made a Postgres\n * relation borrow Firestore's addressing:\n *\n * - `subcollection` is **containment**. The rows live under the parent; the\n * path is their identity, and they cannot exist without it. This is what\n * Firestore has natively.\n * - `relation` is a **link**. The rows are an ordinary collection, narrowed to\n * those the parent reaches. `owned` means the child carries the parent's\n * foreign key and belongs to it alone; `linked` means the row is shared\n * through a junction, so what the parent controls is the link, not the row.\n *\n * @group Models\n */\nexport type ChildViewSource =\n | { kind: \"subcollection\" }\n | {\n kind: \"relation\";\n relationKey: string;\n mode: \"owned\" | \"linked\";\n /**\n * Slug of the collection the rows actually live in.\n *\n * Distinct from the view's `key`, which is the relation. A `linked` view\n * needs both: the key addresses the parent's set, and this addresses the\n * whole collection to pick an existing row out of.\n */\n targetSlug: string;\n };\n\n/**\n * A list of rows rendered inside an entity view — the tab under a record.\n *\n * This is a *presentation* descriptor, which is the whole point: rendering a\n * related list as a tab used to require minting a child `CollectionConfig` with\n * its own slug, which dragged a URL grammar, a path resolver and a second\n * read/write pipeline along with it. A tab needs a key, a collection to list,\n * and to know where its rows come from.\n *\n * @group Models\n */\nexport interface EntityChildView<M extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * Stable identifier for this view: the tab id and the path segment.\n *\n * For a relation this is the **relation key** — the name the backend\n * resolves a nested path segment by — not the target collection's slug.\n * Those differ whenever a relation is named, which is every inline relation\n * property, and the mismatch is why such a tab used to open onto an error.\n */\n key: string;\n\n /** The collection whose rows this view lists, with any overrides applied. */\n collection: CollectionConfig<M>;\n\n source: ChildViewSource;\n}\n\n\nexport type { WhereFilterOp, FilterValues, WireFilterValues, FilterPreset } from \"./filter-operators\";\n\n\nexport type InferCollectionConfigType<S extends CollectionConfig> = S extends CollectionConfig<infer M> ? M : never;\n\n/**\n * Configuration for authentication collections.\n *\n * Controls what happens when admins create users, reset passwords,\n * and which entity actions are auto-injected.\n *\n * Use `auth: true` as sugar for `{ enabled: true }` with all defaults.\n *\n * @example Override user creation\n * ```ts\n * auth: {\n * enabled: true,\n * onCreateUser: async (values, ctx) => {\n * const hash = await ctx.hashPassword(\"welcome123\");\n * return {\n * values: { ...values, passwordHash: hash, emailVerified: true },\n * temporaryPassword: \"welcome123\",\n * };\n * },\n * }\n * ```\n *\n * @example Disable the reset-password entity action\n * ```ts\n * auth: {\n * enabled: true,\n * actions: { resetPassword: false },\n * }\n * ```\n *\n * @group Models\n */\nexport interface AuthCollectionConfig {\n /** Set to true to mark this collection as the authentication collection. */\n enabled: boolean;\n\n /**\n * Called when an admin creates a user via the collection REST API.\n *\n * Default: generate password → hash → normalize email → save →\n * send invitation email (or return temp password if no email configured).\n *\n * Override to implement custom invitation flows, LDAP sync, etc.\n */\n onCreateUser?: (\n values: Record<string, unknown>,\n ctx: AuthCollectionContext\n ) => Promise<AuthCollectionCreateResult>;\n\n /**\n * Called when an admin resets a user's password via the admin panel.\n *\n * Default: generate reset token → send email (or generate + return temp password).\n * Override for custom reset flows.\n */\n onResetPassword?: (\n uid: string,\n ctx: AuthCollectionContext\n ) => Promise<AuthCollectionResetResult>;\n\n /**\n * Control which auth-specific entity actions are auto-injected.\n *\n * Default: `{ resetPassword: true }` — the framework auto-injects\n * the built-in `resetPasswordAction` into the collection's entity actions.\n *\n * Set to `false` to disable, or pass a custom `EntityAction` to replace the UI.\n *\n * The object form is an `EntityAction` from `@rebasepro/admin-types`, typed\n * here as `object` because it is a React component with admin controllers in\n * its props and nothing on the server reads it — only whether the built-in\n * action is injected, which is the boolean.\n */\n actions?: {\n resetPassword?: boolean | object;\n };\n}\n\n/**\n * Context provided to collection-level auth hooks.\n *\n * This is a simplified facade over the server internals —\n * it exposes only what's needed for custom auth flows without\n * coupling collection config to internal interfaces.\n *\n * @group Models\n */\nexport interface AuthCollectionContext {\n /** Hash a password using the configured algorithm (scrypt by default). */\n hashPassword: (password: string) => Promise<string>;\n /**\n * Send an email. Only available when email service is configured.\n *\n * Resolves with what the provider reported — the assigned Message-ID, most\n * usefully — so a hook that sends a message can store the id and later\n * thread a reply back to it. Callers that do not care may ignore it.\n */\n sendEmail?: (options: { to: string; subject: string; html: string; text?: string }) => Promise<EmailSendResult>;\n /** Whether the email service is configured and available. */\n emailConfigured: boolean;\n /** The app name from email config (for templates). */\n appName: string;\n /** The base URL for password reset links. */\n resetPasswordUrl: string;\n}\n\n/**\n * Result of a collection-level `onCreateUser` hook.\n * @group Models\n */\nexport interface AuthCollectionCreateResult {\n /** Processed values to persist (must include passwordHash, NOT raw password). */\n values: Record<string, unknown>;\n /** If set, shown to the admin in the creation result dialog. */\n temporaryPassword?: string;\n /** Whether an invitation email was sent. */\n invitationSent?: boolean;\n}\n\n/**\n * Result of a collection-level `onResetPassword` hook.\n * @group Models\n */\nexport interface AuthCollectionResetResult {\n /** If set, shown to the admin. */\n temporaryPassword?: string;\n /** Whether a reset email was sent. */\n invitationSent?: boolean;\n}\n","/**\n * The SQL helper functions RLS policies call, and the schema they live in.\n *\n * ## One schema, and it is ours\n *\n * Rebase creates exactly one schema in a project's database: `rebase`. These\n * three functions live in it alongside the framework's own tables, and that is\n * the whole contract — a reader can look at a database and know precisely which\n * namespace belongs to the framework and that nothing else was touched.\n *\n * It used to be two. `uid()`, `jwt()` and `roles()` sat in a schema called\n * `auth`, which is Supabase's name, chosen so that a developer who had written\n * Supabase RLS would recognise `auth.uid()`. The familiarity was real but the\n * name was not Rebase's to take, and taking it had a concrete cost: pointing\n * Rebase at a database that already had a Supabase `auth` schema meant\n * `CREATE OR REPLACE FUNCTION auth.uid() RETURNS text` against Supabase's\n * `RETURNS uuid`, which Postgres rejects outright —\n *\n * ERROR: cannot change return type of existing function\n * HINT: Use DROP FUNCTION auth.uid() first.\n *\n * — and the failure landed inside a catch-all that logged a warning and carried\n * on, leaving a database with auth tables, no helper functions, and policies\n * calling functions that did not exist. Under `rebase db migrate` the same\n * statements aborted the migration instead.\n *\n * `rebase.uid()` collides with nobody. A Supabase database keeps its `auth`\n * schema untouched and gains a `rebase` one, which is what a gradual migration\n * needs.\n *\n * ## Why functions at all, rather than inlining `current_setting`\n *\n * Because the indirection has already been spent once. `uid()` resolves\n * `app.uid` and falls back to the pre-rename `app.user_id`, so that during a\n * rolling deploy — old and new pods serving one database — both eras resolve\n * the principal. That was a single `CREATE OR REPLACE`. Inlined into policy\n * bodies it would have been a rewrite of every policy on every table.\n *\n * ## Why the name is not configurable\n *\n * A policy body is stored SQL: Postgres parses `USING (…)` once and keeps it, so\n * these strings are written into every policy in every database Rebase has\n * provisioned. Everything that reads policies back — the SQL-to-policy parser\n * behind the admin UI, the drift checker, `rls-check` — would have to know the\n * configured value to recognise its own output. One frozen name is the feature.\n */\n\n/** The schema Rebase owns. The only schema Rebase creates. */\nexport const REBASE_SCHEMA = \"rebase\";\n\n/**\n * The principal of the current request, as text, or NULL in the server context.\n *\n * Never NULL for a user request — an anonymous one carries\n * {@link ANONYMOUS_USER_ID} — which is what makes `IS NULL` a reliable test for\n * the trusted server plane and `IS NOT NULL` a tautology.\n */\nexport const RLS_UID_SQL = `${REBASE_SCHEMA}.uid()`;\n\n/** The request's roles as a comma-separated string, for `string_to_array`. */\nexport const RLS_ROLES_SQL = `${REBASE_SCHEMA}.roles()`;\n\n/** The request's JWT claims as `jsonb`, or `{}`. */\nexport const RLS_JWT_SQL = `${REBASE_SCHEMA}.jwt()`;\n\n/**\n * The pre-1.0 spellings, for recognising policies and hand-written SQL that\n * predate the move.\n *\n * Kept because policies outlive the server that wrote them: a database migrated\n * by an older release still holds `auth.uid()` in its policy bodies until the\n * next push or boot recompiles them, and anything that reads policies back has\n * to recognise both eras or report the framework's own output as foreign drift.\n * Also used to give a project whose `securityRules` contain raw `auth.uid()` a\n * message naming the replacement, instead of a parse failure.\n */\nexport const LEGACY_RLS_SCHEMA = \"auth\";\nexport const LEGACY_RLS_UID_SQL = `${LEGACY_RLS_SCHEMA}.uid()`;\nexport const LEGACY_RLS_ROLES_SQL = `${LEGACY_RLS_SCHEMA}.roles()`;\nexport const LEGACY_RLS_JWT_SQL = `${LEGACY_RLS_SCHEMA}.jwt()`;\n\n/**\n * Rewrites the pre-1.0 function calls in a fragment of policy SQL.\n *\n * Deliberately anchored on a word boundary and the schema qualifier, so a column\n * called `auth_uid` or a table named `auth` is left alone.\n */\nexport function rewriteLegacyRlsFunctions(sql: string): string {\n return sql.replace(\n /\\bauth\\.(uid|jwt|roles)\\s*\\(\\s*\\)/gi,\n (_match, fn: string) => `${REBASE_SCHEMA}.${fn.toLowerCase()}()`\n );\n}\n\n/** Whether a fragment of SQL still calls the pre-1.0 functions. */\nexport function usesLegacyRlsFunctions(sql: string): boolean {\n return /\\bauth\\.(uid|jwt|roles)\\s*\\(\\s*\\)/i.test(sql);\n}\n","/**\n * The resource graph: one declaration site for every named thing a project needs.\n *\n * ## The rule\n *\n * **Every named resource is declared with a constructor in config code.** A\n * database, a bucket, a topic and whatever kind comes next are all spelled the\n * same way, so \"where do I declare my second one\" has one answer instead of one\n * answer per kind.\n *\n * ```ts\n * export const main = database(\"main\");\n * export const media = bucket(\"media\", { transport: \"direct\" });\n * export const signups = topic<SignupEvent>(\"signups\");\n * ```\n *\n * ## Declaration is not binding\n *\n * A declaration says a resource *exists* and what shape it has. It never says\n * how to reach it — that is a property of the environment, not of the project,\n * and it differs between a laptop, a self-hosted box and a tenant in the cloud.\n * Binding lives in `@rebasepro/server`'s boot path, reading environment\n * variables or an infrastructure config file, and it keys off the logical name\n * declared here.\n *\n * This split is the whole point. Before it, storage topology was hand-written\n * into `rebase.json` while database topology lived in TypeScript, and the\n * boundary between them was a fact about what the control plane could read\n * before a build — a platform implementation detail that a developer had no way\n * to derive. Worse, storage could be declared in *both* places, and the merge\n * silently kept the JSON's engine and discarded the code's.\n *\n * ## Why a registry rather than a fixed union\n *\n * Kinds register themselves. Adding pub/sub, a cache or a search index must not\n * require editing a manifest schema, a validator and three switch statements —\n * that cost is exactly why the last two kinds ended up in different homes.\n */\n\n/** How a client reaches a resource. */\nexport type ResourceTransport =\n /** Through the backend. The default, and the only one that needs no client SDK. */\n | \"server\"\n /** A provider SDK talks to the resource directly; the backend is not in the path. */\n | \"direct\";\n\n/**\n * A resource kind, as registered.\n *\n * `engines` is an allowlist rather than documentation. An unrecognised engine\n * used to be a free string that passed every check and failed later, further\n * from the typo that caused it — `\"s2\"` for `\"s3\"` reached the runtime. Anything\n * genuinely outside the list is spelled `custom:<id>`, which says so at the call\n * site instead of looking like a typo.\n */\nexport interface ResourceKindSpec {\n /** The kind's name, as it appears in a declaration and in the graph. */\n kind: string;\n /** Engines this kind ships with. `custom:<id>` is always additionally valid. */\n engines: readonly string[];\n /** Used when a declaration names none. */\n defaultEngine: string;\n /**\n * Environment variable base names this kind binds from, in the order a\n * binder should try them. A resource keyed `analytics` reads\n * `<BASE>__ANALYTICS`; the default-keyed resource reads `<BASE>` unsuffixed,\n * so a single-resource project configured the obvious way declares nothing.\n */\n envBases: readonly string[];\n /**\n * The subset of `envBases` that matters for a given engine.\n *\n * The binder reads every base and takes whichever is set — harmless, and it\n * keeps binding tolerant. A GENERATOR cannot be that relaxed: `rebase eject\n * infra` writing S3_BUCKET, GCS_BUCKET, STORAGE_BUCKET and\n * STORAGE_PUBLIC_URL for a `local` bucket hands somebody four variables of\n * which three are noise, and a config file full of irrelevant keys is one\n * nobody reads carefully.\n *\n * Keyed by engine; an engine with no entry falls back to all of them, which\n * is the honest answer for one this package has never heard of.\n */\n envBasesByEngine?: Readonly<Record<string, readonly string[]>>;\n /** Option keys this kind accepts beyond the common ones, for validation. */\n optionKeys?: readonly string[];\n /**\n * Whether a project implicitly has one of these even when it declares\n * nothing. True for databases — a backend without one is not a backend —\n * and false for topics, where zero is the normal number.\n */\n implicitDefault?: boolean;\n}\n\n/** The key a resource takes when a project declares only one of its kind. */\nexport const DEFAULT_RESOURCE_KEY = \"(default)\";\n\n/** A declared resource, as it appears in the graph. */\nexport interface ResourceDeclaration {\n kind: string;\n /** Unique within its kind. What a binder looks up and what an env suffix is built from. */\n key: string;\n engine: string;\n transport: ResourceTransport;\n label?: string;\n /** Kind-specific options, validated against the kind's `optionKeys`. */\n options: Readonly<Record<string, unknown>>;\n}\n\n/**\n * The value a constructor returns.\n *\n * Carries its own declaration so config code can hold it and pass it around,\n * and stringifies to its key so it drops into the places that still take one.\n * Collections name a data source by string today; a handle works there without\n * the collection API having to change, which keeps this a config redesign\n * rather than a rewrite of the data layer.\n */\nexport interface ResourceHandle extends ResourceDeclaration {\n toString(): string;\n}\n\nconst BRAND = Symbol.for(\"@rebasepro/types.resource\");\n\n/** Whether a value is a resource handle rather than a plain string key. */\nexport function isResourceHandle(value: unknown): value is ResourceHandle {\n return typeof value === \"object\" && value !== null && BRAND in value;\n}\n\n/** The key a resource reference names, whether it is a handle or already a key. */\nexport function resourceKeyOf(ref: string | ResourceHandle): string {\n return isResourceHandle(ref) ? ref.key : ref;\n}\n\n/**\n * The process-wide registry.\n *\n * Keyed off `globalThis` through a shared symbol rather than held in a module\n * local, because a module local is per *copy* of this package. A project that\n * ends up with two copies of `@rebasepro/types` — which a partially-linked\n * `node_modules` produces, and which has already caused a phantom\n * \"JWT secret not configured\" bug in this repo — would otherwise register into\n * one registry and read from the other, and see an empty graph with nothing\n * anywhere to explain it.\n */\ninterface Registry {\n kinds: Map<string, ResourceKindSpec>;\n declarations: Map<string, ResourceDeclaration>;\n}\n\nconst GLOBAL_KEY = Symbol.for(\"@rebasepro/types.resourceRegistry\");\n\nfunction registry(): Registry {\n const g = globalThis as unknown as Record<symbol, Registry | undefined>;\n let existing = g[GLOBAL_KEY];\n if (!existing) {\n existing = { kinds: new Map(), declarations: new Map() };\n g[GLOBAL_KEY] = existing;\n }\n return existing;\n}\n\n/** `kind:key`, the graph's primary key. */\nfunction declarationId(kind: string, key: string): string {\n return `${kind}:${key}`;\n}\n\n/** Register a resource kind. Idempotent for an identical spec; throws on a conflicting one. */\nexport function registerResourceKind(spec: ResourceKindSpec): void {\n const existing = registry().kinds.get(spec.kind);\n if (existing && JSON.stringify(existing) !== JSON.stringify(spec)) {\n throw new Error(\n `Resource kind \"${spec.kind}\" is already registered with a different definition. ` +\n \"Two packages cannot define the same kind.\"\n );\n }\n registry().kinds.set(spec.kind, spec);\n}\n\n/** Every registered kind, for validators and for `rebase doctor`. */\nexport function resourceKinds(): ResourceKindSpec[] {\n return [...registry().kinds.values()];\n}\n\n/** One registered kind, or undefined. */\nexport function resourceKind(kind: string): ResourceKindSpec | undefined {\n return registry().kinds.get(kind);\n}\n\n/** Options every kind accepts. */\nexport interface DeclareOptions {\n engine?: string;\n transport?: ResourceTransport;\n label?: string;\n [option: string]: unknown;\n}\n\nconst COMMON_OPTION_KEYS = [\"engine\", \"transport\", \"label\"] as const;\n\n/** Whether an engine is one the kind knows, or an explicit `custom:` opt-out. */\nexport function isValidEngine(spec: ResourceKindSpec, engine: string): boolean {\n return engine.startsWith(\"custom:\") || spec.engines.includes(engine);\n}\n\n/**\n * Declare a resource. The primitive every kind's constructor is built from.\n *\n * Redeclaring the same `kind:key` with a *different* shape throws rather than\n * merging. Merging is what the old storage path did, and it silently discarded\n * one of the two engines — a declaration accepted and then ignored, which is\n * the failure this whole model exists to remove. Redeclaring it identically is\n * fine: a config module evaluated twice must not be an error.\n */\nexport function declareResource(\n kind: string,\n key: string = DEFAULT_RESOURCE_KEY,\n options: DeclareOptions = {}\n): ResourceHandle {\n const spec = registry().kinds.get(kind);\n if (!spec) {\n const known = [...registry().kinds.keys()].sort().join(\", \") || \"none\";\n throw new Error(\n `Unknown resource kind \"${kind}\". Registered kinds: ${known}. ` +\n \"Call registerResourceKind() before declaring one.\"\n );\n }\n\n if (!key || typeof key !== \"string\" || key.trim() === \"\") {\n throw new Error(`A ${kind} needs a non-empty key.`);\n }\n\n const engine = options.engine ?? spec.defaultEngine;\n if (!isValidEngine(spec, engine)) {\n throw new Error(\n `Unknown ${kind} engine \"${engine}\" for \"${key}\". ` +\n `Known engines: ${spec.engines.join(\", \")}. ` +\n `An engine this build does not ship is spelled \"custom:${engine}\", ` +\n \"which says so at the call site rather than failing later.\"\n );\n }\n\n const allowed = new Set<string>([...COMMON_OPTION_KEYS, ...(spec.optionKeys ?? [])]);\n const unknown = Object.keys(options).filter(k => !allowed.has(k));\n if (unknown.length > 0) {\n throw new Error(\n `Unknown option(s) on ${kind} \"${key}\": ${unknown.join(\", \")}. ` +\n `A ${kind} accepts: ${[...allowed].sort().join(\", \")}.`\n );\n }\n\n const extra: Record<string, unknown> = {};\n for (const k of spec.optionKeys ?? []) {\n if (options[k] !== undefined) extra[k] = options[k];\n }\n\n const declaration: ResourceDeclaration = {\n kind,\n key,\n engine,\n transport: options.transport ?? \"server\",\n ...(options.label !== undefined ? { label: options.label } : {}),\n options: Object.freeze(extra)\n };\n\n const id = declarationId(kind, key);\n const previous = registry().declarations.get(id);\n if (previous) {\n if (JSON.stringify(previous) !== JSON.stringify(declaration)) {\n throw new Error(\n `${kind} \"${key}\" is declared twice with different configuration. ` +\n \"Declare it once and export it — two declarations of one resource is \" +\n \"the ambiguity this model exists to remove, so it is refused rather \" +\n \"than merged.\"\n );\n }\n } else {\n registry().declarations.set(id, declaration);\n }\n\n const handle = {\n ...declaration,\n toString() { return key; },\n [BRAND]: true as const\n };\n return handle as ResourceHandle;\n}\n\n/** Every declared resource, in declaration order, optionally filtered by kind. */\nexport function declaredResources(kind?: string): ResourceDeclaration[] {\n const all = [...registry().declarations.values()];\n return kind ? all.filter(r => r.kind === kind) : all;\n}\n\n/**\n * Forget every declaration, keeping registered kinds.\n *\n * For tests and for a CLI that evaluates more than one project in a process.\n * Kinds survive because they are registered by module import, which will not\n * happen a second time.\n */\nexport function resetDeclaredResources(): void {\n registry().declarations.clear();\n}\n\n/**\n * The env-var suffix a resource's bindings use: `__ANALYTICS` for `analytics`,\n * and nothing at all for the default-keyed one.\n *\n * The default takes no suffix so that a project with one database configured\n * through plain `DATABASE_URL` keeps working having declared nothing — the\n * overwhelmingly common project must not have to say so.\n */\nexport function resourceEnvSuffix(key: string): string {\n if (key === DEFAULT_RESOURCE_KEY) return \"\";\n return `__${key.toUpperCase().replace(/[^A-Z0-9]+/g, \"_\").replace(/^_+|_+$/g, \"\")}`;\n}\n\n/**\n * Two resources of a kind whose keys differ but whose env suffixes do not.\n *\n * `media-files` and `media_files` both become `__MEDIA_FILES`, so one would\n * silently read the other's configuration. Returned rather than thrown so the\n * caller can report it with the rest of a validation pass.\n */\nexport function findEnvSuffixCollision(keys: readonly string[]): { a: string; b: string; suffix: string } | null {\n const seen = new Map<string, string>();\n for (const key of keys) {\n const suffix = resourceEnvSuffix(key);\n const previous = seen.get(suffix);\n if (previous !== undefined && previous !== key) return { a: previous, b: key, suffix };\n seen.set(suffix, key);\n }\n return null;\n}\n\n/**\n * The whole graph, as recorded in a manifest and read by a host.\n *\n * `version` is the graph format, not the project's. A host reading a graph it\n * does not understand must say so rather than provision half of it.\n */\nexport interface ResourceGraph {\n version: 1;\n resources: ResourceDeclaration[];\n}\n\n/** The current graph format version. */\nexport const RESOURCE_GRAPH_VERSION = 1 as const;\n\n/** Build a graph from the current declarations, sorted for a stable diff. */\nexport function buildResourceGraph(): ResourceGraph {\n const resources = declaredResources().slice().sort(\n (a, b) => a.kind.localeCompare(b.kind) || a.key.localeCompare(b.key)\n );\n return { version: RESOURCE_GRAPH_VERSION, resources };\n}\n\n/**\n * The environment variables worth writing for a resource, given its engine.\n *\n * Falls back to every base the kind reads when the engine is unknown — a\n * `custom:` engine gets the full list rather than an empty one, because\n * guessing narrow would silently omit the variable it actually needs.\n */\nexport function envBasesForResource(declaration: ResourceDeclaration): readonly string[] {\n const spec = resourceKind(declaration.kind);\n if (!spec) return [];\n return spec.envBasesByEngine?.[declaration.engine] ?? spec.envBases;\n}\n","/**\n * The kinds Rebase ships, and the constructors a project declares them with.\n *\n * Each kind is registered rather than hardcoded, so a fourth one arrives\n * without editing a manifest schema, a validator and a switch statement. That\n * cost is precisely why databases and buckets ended up declared in different\n * files with different rules — the cheapest thing to do was always to bolt the\n * new kind onto whichever home was nearest.\n *\n * A kind owns its engine list. `custom:<id>` is always accepted, so a build\n * that ships an engine this package has never heard of says so at the call site\n * instead of looking like a typo of one that exists.\n */\nimport {\n DEFAULT_RESOURCE_KEY,\n declareResource,\n declaredResources,\n registerResourceKind,\n type DeclareOptions,\n type ResourceHandle,\n type ResourceTransport\n} from \"./resources\";\n\n// ── database ─────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n kind: \"database\",\n engines: [\"postgres\", \"mongodb\", \"firestore\", \"sqlite\"],\n defaultEngine: \"postgres\",\n // REBASE_DRIVER overrides the engine's default driver package; the pool\n // ceiling is per-source because one source can be a single-session PGlite\n // and another a real server.\n envBases: [\"DATABASE_URL\", \"REBASE_DRIVER\", \"REBASE_DB_POOL_MAX\"],\n // No per-engine narrowing: every engine binds from the same three, and the\n // driver package that differs between them is named by REBASE_DRIVER either\n // way.\n optionKeys: [\"databaseId\", \"migrations\"],\n // A backend without a database is not a backend, so one exists whether or\n // not a project says so.\n implicitDefault: true\n});\n\n/** Options a database accepts beyond the common ones. */\nexport interface DatabaseOptions extends DeclareOptions {\n /**\n * The physical database or schema within the engine, when it differs from\n * the engine's own default. Threaded to drivers as `databaseId`.\n */\n databaseId?: string;\n /** Directory of migration files, relative to the config directory. */\n migrations?: string;\n}\n\n/** A database handle. Collections point at it via `dataSource`. */\nexport type DatabaseHandle = ResourceHandle;\n\n/**\n * Declare a database.\n *\n * ```ts\n * export const main = database(); // the default one\n * export const analytics = database(\"analytics\"); // reads DATABASE_URL__ANALYTICS\n * ```\n */\nexport function database(key: string = DEFAULT_RESOURCE_KEY, options: DatabaseOptions = {}): DatabaseHandle {\n return declareResource(\"database\", key, options);\n}\n\n// ── bucket ───────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n kind: \"bucket\",\n engines: [\"local\", \"s3\", \"gcs\", \"azure\", \"firebase\"],\n defaultEngine: \"local\",\n envBases: [\"S3_BUCKET\", \"GCS_BUCKET\", \"STORAGE_BUCKET\", \"STORAGE_PUBLIC_URL\"],\n envBasesByEngine: {\n local: [\"STORAGE_BUCKET\"],\n s3: [\"S3_BUCKET\", \"STORAGE_ENDPOINT\", \"STORAGE_REGION\", \"STORAGE_PUBLIC_URL\"],\n gcs: [\"GCS_BUCKET\", \"STORAGE_PUBLIC_URL\"],\n azure: [\"STORAGE_BUCKET\", \"STORAGE_PUBLIC_URL\"],\n firebase: [\"STORAGE_BUCKET\", \"STORAGE_PUBLIC_URL\"]\n },\n optionKeys: [\"publicRead\", \"prefix\"],\n // Storage is genuinely optional: plenty of projects store nothing.\n implicitDefault: false\n});\n\n/** Options a bucket accepts beyond the common ones. */\nexport interface BucketOptions extends DeclareOptions {\n /**\n * Whether objects are world-readable by default.\n *\n * Declared rather than inferred from the engine, because the two have\n * disagreed before: a private object served through a cacheable public URL\n * is a data leak that nothing errors on.\n */\n publicRead?: boolean;\n /** Key prefix within the bucket, for sharing one bucket between sources. */\n prefix?: string;\n}\n\n/** A bucket handle. Storage properties point at it via `storageSource`. */\nexport type BucketHandle = ResourceHandle;\n\n/**\n * Declare a bucket.\n *\n * ```ts\n * export const media = bucket(\"media\", { transport: \"direct\" });\n * ```\n *\n * `transport: \"direct\"` means a provider SDK talks to the bucket and the\n * backend is not in the upload path.\n */\nexport function bucket(key: string = DEFAULT_RESOURCE_KEY, options: BucketOptions = {}): BucketHandle {\n return declareResource(\"bucket\", key, options);\n}\n\n// ── topic ────────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n kind: \"topic\",\n // `jobs` is the durable local implementation: a topic fans out to one job\n // row per subscription, so each subscriber retries on its own schedule and\n // a failure is a row somebody can look at rather than a lost message.\n engines: [\"jobs\"],\n defaultEngine: \"jobs\",\n envBases: [\"REBASE_TOPIC_URL\"],\n optionKeys: [\"delivery\", \"maxAttempts\"],\n implicitDefault: false\n});\n\n/**\n * How hard the runtime tries to deliver.\n *\n * Only `at-least-once` is implemented, and it is the honest name for what a\n * retrying queue does: a handler must tolerate seeing the same event twice.\n * `at-most-once` is listed so a future transport can offer it without the\n * option changing shape, and is refused today rather than silently upgraded.\n */\nexport type TopicDelivery = \"at-least-once\" | \"at-most-once\";\n\n/** Options a topic accepts beyond the common ones. */\nexport interface TopicOptions extends DeclareOptions {\n delivery?: TopicDelivery;\n /** Attempts per subscription before a message is left failed. Default 5. */\n maxAttempts?: number;\n}\n\n/**\n * What a subscription does with an event.\n *\n * `attempt` counts from 1. Worth branching on: the first delivery and the\n * fourth are the same call, but the fourth is where it is worth logging loudly.\n */\nexport type TopicHandler<T> = (event: T, context: { attempt: number; topic: string; subscription: string }) => Promise<void> | void;\n\n/** A declared subscription, as recorded in the graph and wired at boot. */\nexport interface TopicSubscription<T = unknown> {\n topic: string;\n name: string;\n handler: TopicHandler<T>;\n maxAttempts?: number;\n}\n\n/**\n * What a topic publishes through.\n *\n * Installed by `@rebasepro/server` at boot. Absent — in the CLI evaluating\n * config to derive the graph, or in a unit test — publishing throws a message\n * naming the cause, rather than resolving and dropping the event. A publish\n * that silently does nothing is the failure mode a queue exists to prevent.\n */\nexport interface TopicRuntime {\n publish(topic: string, event: unknown): Promise<void>;\n}\n\nconst runtimeHolder: { current: TopicRuntime | null } = { current: null };\n\n/** Install the transport topics publish through. Called by the server at boot. */\nexport function setTopicRuntime(runtime: TopicRuntime | null): void {\n runtimeHolder.current = runtime;\n}\n\nconst subscriptions: TopicSubscription[] = [];\n\n/** Every declared subscription, for the worker to wire and the graph to record. */\nexport function declaredSubscriptions(topic?: string): TopicSubscription[] {\n return topic ? subscriptions.filter(s => s.topic === topic) : subscriptions.slice();\n}\n\n/** Forget declared subscriptions. For tests, alongside `resetDeclaredResources`. */\nexport function resetDeclaredSubscriptions(): void {\n subscriptions.length = 0;\n}\n\n/** A topic handle, carrying its payload type. */\nexport interface TopicHandle<T> extends ResourceHandle {\n /**\n * Publish an event.\n *\n * Resolves once the event is durably recorded for every subscription, not\n * once they have run. Enqueued inside a transaction that rolls back, it was\n * never published.\n */\n publish(event: T): Promise<void>;\n /**\n * Declare a subscription.\n *\n * The name is its identity: it is what the job row records, what a retry\n * counts against, and what a second subscription must not collide with.\n */\n subscription(name: string, handler: TopicHandler<T>, options?: { maxAttempts?: number }): void;\n}\n\n/**\n * Declare a topic.\n *\n * ```ts\n * export const signups = topic<{ userId: string }>(\"signups\");\n * signups.subscription(\"send-welcome\", async (event) => { … });\n * await signups.publish({ userId });\n * ```\n */\nexport function topic<T = unknown>(key: string, options: TopicOptions = {}): TopicHandle<T> {\n if (options.delivery === \"at-most-once\") {\n throw new Error(\n `Topic \"${key}\" asks for at-most-once delivery, which no shipped transport implements. ` +\n \"The durable queue behind topics retries, so it is at-least-once and a handler must \" +\n \"tolerate seeing an event twice. Refused rather than quietly given the other guarantee.\"\n );\n }\n const handle = declareResource(\"topic\", key, options);\n\n return {\n ...handle,\n toString() { return key; },\n async publish(event: T): Promise<void> {\n const runtime = runtimeHolder.current;\n if (!runtime) {\n throw new Error(\n `Cannot publish to topic \"${key}\": no topic runtime is installed. ` +\n \"Publishing works inside a running Rebase backend; this looks like config \" +\n \"being evaluated outside one (a build, a script, or a test without a harness).\"\n );\n }\n await runtime.publish(key, event);\n },\n subscription(name: string, handler: TopicHandler<T>, subOptions: { maxAttempts?: number } = {}): void {\n if (!name || name.trim() === \"\") {\n throw new Error(`A subscription on topic \"${key}\" needs a non-empty name.`);\n }\n if (subscriptions.some(s => s.topic === key && s.name === name)) {\n throw new Error(\n `Topic \"${key}\" already has a subscription named \"${name}\". ` +\n \"The name is what a job row records and what a retry counts against, so two \" +\n \"cannot share one.\"\n );\n }\n subscriptions.push({\n topic: key,\n name,\n handler: handler as TopicHandler<unknown>,\n ...(subOptions.maxAttempts !== undefined ? { maxAttempts: subOptions.maxAttempts } : {})\n });\n }\n } as TopicHandle<T>;\n}\n\n// ── Handing declarations to the frontend ─────────────────────────────────────\n\n/**\n * The declared databases, in the shape `<Rebase dataSources>` takes.\n *\n * The frontend needs to know which sources exist and how they are reached — a\n * `direct`-transport source is one the browser talks to itself — and it imports\n * the same config package the backend does. Without these it would mean writing\n * the list a second time, by hand, next to the declarations, which is precisely\n * the two-homes problem this model removed everywhere else.\n *\n * ```tsx\n * import \"../config/resources\"; // registers them\n * import { declaredDataSources, declaredStorageSources } from \"@rebasepro/types\";\n *\n * <Rebase dataSources={declaredDataSources()} storageSources={declaredStorageSources()} />\n * ```\n *\n * The import is what registers them, so a bundler that drops an unused module\n * would leave this empty — hence the side-effect import above rather than a\n * bare re-export.\n */\nexport function declaredDataSources(): { key: string; engine: string; transport: ResourceTransport; label?: string }[] {\n return declaredResources(\"database\").map(r => ({\n key: r.key,\n engine: r.engine,\n transport: r.transport,\n ...(r.label !== undefined ? { label: r.label } : {})\n }));\n}\n\n/** The declared buckets, in the shape `<Rebase storageSources>` takes. */\nexport function declaredStorageSources(): { key: string; engine: string; transport: ResourceTransport; label?: string }[] {\n return declaredResources(\"bucket\").map(r => ({\n key: r.key,\n engine: r.engine,\n transport: r.transport,\n ...(r.label !== undefined ? { label: r.label } : {})\n }));\n}\n"],"mappings":";;;;;AAuJA,IAAM,kCAAkC;;;;;;;;;;;;;;;;;;;AAoBxC,SAAgB,4BAA4B,MAAqC;CAC7E,OAAO,GAAG,KAAK,IAAI,GAAG,KAAK,WAAW,KAAK,QAAQ,IAAI,KAAK,UAAU,GAAG;AAC7E;;;;;;;;;AAUA,SAAgB,2BAA2B,KAAgD;CACvF,MAAM,QAAQ,gCAAgC,KAAK,GAAG;CACtD,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,GAAG,KAAK,UAAU,SAAS;CAKjC,IAAI,CAAC,SAAS,QAAQ,SAAS,OAAO,KAAA;CACtC,OAAO;EAAO;EAA4B;EAAU,GAAI,SAAS,EAAE,MAAM;CAAG;AAChF;;AAGA,SAAgB,wBAAwB,KAA4C;CAChF,OAAO,OAAO,QAAQ,YAAY,QAAQ,QACtC,OAAQ,IAA8B,aAAa,YACnD,OAAQ,IAA8B,QAAQ;AACtD;;AAGA,SAAgB,gBAAgB,KAAsB;CAClD,OAAO,wBAAwB,GAAG,IAAI,4BAA4B,GAAG,IAAI;AAC7E;;AAiJA,IAAa,oBAAmE;CAC5E,MAAM;CACN,MAAM;CACN,KAAK;CACL,MAAM;CACN,KAAK;CACL,MAAM;CACN,MAAM;CACN,UAAU;CACV,kBAAkB;CAClB,sBAAsB;CACtB,QAAQ;CACR,SAAS;CACT,YAAY;CACZ,aAAa;CACb,WAAW;CACX,eAAe;AACnB;;AAGA,IAAa,oBAAmE;CAC5E,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,MAAM;CACN,O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,qBAAqB;CACjB,MAAM;CAIN,SAAS,CAAC,MAAM;CAChB,eAAe;CACf,UAAU,CAAC,kBAAkB;CAC7B,YAAY,CAAC,YAAY,aAAa;CACtC,iBAAiB;AACrB,CAAC"}
@@ -1,8 +1,8 @@
1
1
  import { SQL } from "drizzle-orm";
2
2
  import { AnyPgColumn, PgTable } from "drizzle-orm/pg-core";
3
3
  import { CollectionConfig, FilterValues, WhereFilterOp, LogicalCondition, FilterCondition, ResolvedRelation, ResolvedBelongsTo, ResolvedForeignKeyOnTarget, ResolvedManyToMany, type RelationAggregateSort } from "@rebasepro/types";
4
- import { type SearchColumnSpec } from "../schema/search-column";
5
- import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry";
4
+ import { type SearchColumnSpec } from "../schema/search-column.js";
5
+ import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry.js";
6
6
  /**
7
7
  * What to do with a filter field that resolves to no column at all.
8
8
  *
@@ -1,9 +1,9 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  import process from "process";
3
3
  __createRequire(import.meta.url);
4
- import { c as __exportAll } from "./connection-BuZ97wsr.js";
4
+ import { u as __exportAll } from "./connection-GOKU3Hu5.js";
5
5
  import { n as resolveClientListLimit, r as ANONYMOUS_USER_ID, t as ListLimitError } from "./data_driver-ULAyJEi9.js";
6
- import "./src-BBFsDaeA.js";
6
+ import "./src-DolrXONo.js";
7
7
  import { ApiError, assertWriteRequestValid, extractUserFromToken, logger, resolveRequireAuth, safeCompare } from "@rebasepro/server";
8
8
  import { WebSocketServer } from "ws";
9
9
  import { inspect } from "util";
@@ -24,7 +24,11 @@ function isSchemaAdmin(admin) {
24
24
  }
25
25
  //#endregion
26
26
  //#region src/websocket.ts
27
- var websocket_exports = /* @__PURE__ */ __exportAll({ createPostgresWebSocket: () => createPostgresWebSocket });
27
+ var websocket_exports = /* @__PURE__ */ __exportAll({
28
+ ADMIN_ONLY_TYPES: () => ADMIN_ONLY_TYPES,
29
+ PUBLIC_TYPES: () => PUBLIC_TYPES,
30
+ createPostgresWebSocket: () => createPostgresWebSocket
31
+ });
28
32
  /** Maximum messages per client per window */
29
33
  var WS_RATE_LIMIT = 2e3;
30
34
  /** Rate limit window in milliseconds (60 seconds) */
@@ -54,11 +58,28 @@ var CHANNEL_MESSAGE_TYPES = /* @__PURE__ */ new Set([
54
58
  "presence_state",
55
59
  "channel_history"
56
60
  ]);
57
- /** Admin-only WebSocket message types */
61
+ /**
62
+ * WebSocket message types that require an admin session.
63
+ *
64
+ * Exported so the test can READ it. It used to be private, and the test that
65
+ * exists to make "a privileged verb added without a role check" impossible held
66
+ * a hand-typed copy of the same nine strings — so it agreed with itself, and
67
+ * `FETCH_APPLICATION_ROLES` was added to neither. That verb runs
68
+ * `SELECT DISTINCT unnest(roles)` over the users table through `executeSql`,
69
+ * which is the owner connection and not subject to RLS, so any authenticated
70
+ * non-admin could enumerate every role in the project — and any anonymous
71
+ * socket could, on a deployment with `requireAuth: false`.
72
+ *
73
+ * The list is no longer the whole guarantee. `PUBLIC_TYPES` below is its
74
+ * counterpart, and a test asserts that every `case` this file handles appears
75
+ * in exactly one of the two — so a verb added to neither fails rather than
76
+ * defaulting to reachable.
77
+ */
58
78
  var ADMIN_ONLY_TYPES = /* @__PURE__ */ new Set([
59
79
  "EXECUTE_SQL",
60
80
  "FETCH_DATABASES",
61
81
  "FETCH_ROLES",
82
+ "FETCH_APPLICATION_ROLES",
62
83
  "FETCH_UNMAPPED_TABLES",
63
84
  "FETCH_TABLE_METADATA",
64
85
  "FETCH_CURRENT_DATABASE",
@@ -67,6 +88,22 @@ var ADMIN_ONLY_TYPES = /* @__PURE__ */ new Set([
67
88
  "LIST_BRANCHES"
68
89
  ]);
69
90
  /**
91
+ * Message types deliberately reachable by a non-admin session.
92
+ *
93
+ * Data operations, gated per row by RLS and per request by the same write
94
+ * checks the REST layer applies — not by this list. It exists so that "which
95
+ * bucket is this verb in" is a question with an answer for every verb, and
96
+ * adding one without answering it is a test failure.
97
+ */
98
+ var PUBLIC_TYPES = /* @__PURE__ */ new Set([
99
+ "FETCH_COLLECTION",
100
+ "FETCH_ONE",
101
+ "COUNT",
102
+ "SAVE",
103
+ "DELETE",
104
+ "CHECK_UNIQUE_FIELD"
105
+ ]);
106
+ /**
70
107
  * Recursively extract the deepest error message from an error's cause chain (e.g., Drizzle wrapping a PG error).
71
108
  */
72
109
  function extractErrorMessage(error) {
@@ -609,6 +646,6 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
609
646
  });
610
647
  }
611
648
  //#endregion
612
- export { websocket_exports as n, createPostgresWebSocket as t };
649
+ export { websocket_exports as i, PUBLIC_TYPES as n, createPostgresWebSocket as r, ADMIN_ONLY_TYPES as t };
613
650
 
614
- //# sourceMappingURL=websocket-BVgDVO-V.js.map
651
+ //# sourceMappingURL=websocket-7Dp77lTh.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket-7Dp77lTh.js","names":[],"sources":["../../types/src/types/backend.ts","../src/websocket.ts"],"sourcesContent":["import type { CollectionConfig, FilterValues, WhereFilterOp } from \"./collections\";\nimport type { OrderByTuple } from \"./filter-operators\";\nimport type { LogicalCondition } from \"../controllers/data\";\nimport type { AuthAdapter } from \"./auth_adapter\";\nimport type { HistoryConfig } from \"../controllers/client\";\nimport type { ChannelBusSetting } from \"./channel_bus\";\nimport type { SchemaEditingAdmin } from \"./schema_editing\";\n\n// =============================================================================\n// DATABASE CONNECTION INTERFACES\n// =============================================================================\n\n/**\n * Abstract database connection interface.\n * Represents a connection to any database system.\n */\nexport interface DatabaseConnection {\n /**\n * Type identifier for this database (e.g., 'postgres', 'mongodb', 'mysql')\n */\n readonly type: string;\n\n /**\n * Whether the connection is currently active\n */\n readonly isConnected?: boolean;\n\n /**\n * Close the database connection and release resources.\n */\n close?(): Promise<void>;\n}\n\n// =============================================================================\n// QUERY BUILDING INTERFACES\n// =============================================================================\n\n/**\n * A single filter condition for database queries\n */\nexport interface QueryFilter {\n field: string;\n operator: WhereFilterOp;\n value: unknown;\n}\n\n/**\n * Options for fetching a collection of entities\n */\nexport interface FetchCollectionOptions<M extends Record<string, unknown> = Record<string, unknown>> {\n filter?: FilterValues<Extract<keyof M, string>>;\n /** See `FetchCollectionProps.orderBy`: a field name plus `order`, or a list of tuples. */\n orderBy?: string | OrderByTuple[];\n order?: \"desc\" | \"asc\";\n limit?: number;\n offset?: number;\n startAfter?: unknown;\n searchString?: string;\n databaseId?: string;\n collection?: CollectionConfig;\n}\n\n/**\n * Options for searching entities\n */\nexport interface SearchOptions<M extends Record<string, unknown> = Record<string, unknown>> {\n filter?: FilterValues<Extract<keyof M, string>>;\n /** See `FetchCollectionProps.orderBy`: a field name plus `order`, or a list of tuples. */\n orderBy?: string | OrderByTuple[];\n order?: \"desc\" | \"asc\";\n limit?: number;\n databaseId?: string;\n collection?: CollectionConfig;\n}\n\n/**\n * Options for counting entities\n */\nexport interface CountOptions<M extends Record<string, unknown> = Record<string, unknown>> {\n filter?: FilterValues<Extract<keyof M, string>>;\n /**\n * An `or(...)`/`and(...)` group, alongside `filter`.\n *\n * Counted as well as fetched, or `total` describes a different set of rows\n * from the one that was served — the same reason `filter` is here.\n */\n logical?: LogicalCondition;\n searchString?: string;\n databaseId?: string;\n}\n\n/**\n * Abstract condition builder interface.\n * Implementations translate Rebase filter conditions to database-specific queries.\n *\n * Note: This interface can be implemented as instance methods or as a class with static methods.\n * For static implementations (like DrizzleConditionBuilder), use the ConditionBuilderStatic type.\n *\n * @template T The type of condition returned by the builder (e.g., SQL for PostgreSQL, Filter<Document> for MongoDB)\n */\nexport interface ConditionBuilder<T = unknown> {\n /**\n * Build filter conditions from Rebase FilterValues\n */\n buildFilterConditions<M extends Record<string, unknown>>(\n filter: FilterValues<Extract<keyof M, string>>,\n collectionPath: string,\n ...args: unknown[]\n ): T[];\n\n /**\n * Build search conditions for text search\n */\n buildSearchConditions(\n searchString: string,\n properties: Record<string, unknown>,\n ...args: unknown[]\n ): T[];\n\n /**\n * Combine multiple conditions with AND operator\n */\n combineConditionsWithAnd(conditions: T[]): T | undefined;\n\n /**\n * Combine multiple conditions with OR operator\n */\n combineConditionsWithOr(conditions: T[]): T | undefined;\n}\n\n/**\n * Static condition builder type for implementations using static methods.\n * Use this type when the class provides static methods rather than instance methods.\n *\n * @example\n * // DrizzleConditionBuilder satisfies this type\n * const builder: ConditionBuilderStatic<SQL> = DrizzleConditionBuilder;\n */\nexport type ConditionBuilderStatic<T = unknown> = {\n buildFilterConditions<M extends Record<string, unknown>>(\n filter: FilterValues<Extract<keyof M, string>>,\n ...args: unknown[]\n ): T[];\n buildSearchConditions(\n searchString: string,\n properties: Record<string, unknown>,\n ...args: unknown[]\n ): T[];\n combineConditionsWithAnd(conditions: T[]): T | undefined;\n combineConditionsWithOr(conditions: T[]): T | undefined;\n};\n\n// =============================================================================\n// ENTITY REPOSITORY INTERFACES\n// =============================================================================\n\n/**\n * Abstract entity repository interface.\n * Handles all CRUD operations for entities in the database.\n *\n * Implementations should handle:\n * - Entity serialization/deserialization\n * - Relation resolution\n * - ID generation and conversion\n */\nexport interface DataRepository {\n /**\n * Fetch a single entity by ID\n */\n fetchOne<M extends Record<string, unknown>>(\n collectionPath: string,\n id: string | number,\n databaseId?: string\n ): Promise<Record<string, unknown> | undefined>;\n\n /**\n * Fetch a collection of entities with optional filtering, ordering, and pagination\n */\n fetchCollection<M extends Record<string, unknown>>(\n collectionPath: string,\n options?: FetchCollectionOptions<M>\n ): Promise<Record<string, unknown>[]>;\n\n /**\n * Search entities by text\n */\n searchRows<M extends Record<string, unknown>>(\n collectionPath: string,\n searchString: string,\n options?: SearchOptions<M>\n ): Promise<Record<string, unknown>[]>;\n\n /**\n * Count entities in a collection\n */\n count<M extends Record<string, unknown>>(\n collectionPath: string,\n options?: CountOptions<M>\n ): Promise<number>;\n\n /**\n * Save a entity (create or update)\n */\n save<M extends Record<string, unknown>>(\n collectionPath: string,\n values: Partial<M>,\n id?: string | number,\n databaseId?: string\n ): Promise<Record<string, unknown>>;\n\n /**\n * Delete a entity by ID\n */\n delete(\n collectionPath: string,\n id: string | number,\n databaseId?: string\n ): Promise<void>;\n\n /**\n * Check if a field value is unique in a collection\n */\n checkUniqueField(\n collectionPath: string,\n fieldName: string,\n value: unknown,\n excludeEntityId?: string,\n databaseId?: string\n ): Promise<boolean>;\n\n}\n\n// =============================================================================\n// REALTIME INTERFACES\n// =============================================================================\n\n/**\n * Configuration for subscribing to a collection\n */\nexport interface CollectionSubscriptionConfig {\n clientId: string;\n path: string;\n filter?: unknown;\n /**\n * An `or(...)`/`and(...)` group, applied alongside `filter`.\n *\n * Declared here because a subscription is a query, and every field a query\n * has this one needs too. It was missing, so the type-checked boundary\n * dropped it: the client sent the group, nothing rejected it, and the\n * subscription re-fetched with the group gone — pushing every row the\n * caller's policies allowed rather than the ones they asked for. The same\n * defect `FetchCollectionProps.logical` documents, one layer up.\n */\n logical?: LogicalCondition;\n /**\n * Where the subscription's page starts. Missing for the same reason, with\n * a quieter symptom: a subscriber watching page two was pushed page one,\n * and a `collection_update` frame carries no window for it to notice with.\n */\n offset?: number;\n /** See `FetchCollectionProps.orderBy`: a field name plus `order`, or a list of tuples. */\n orderBy?: string | OrderByTuple[];\n order?: \"desc\" | \"asc\";\n limit?: number;\n startAfter?: unknown;\n databaseId?: string;\n searchString?: string;\n /** Ask each row which declared search field matched. */\n searchExplain?: boolean;\n}\n\n/**\n * Configuration for subscribing to a single entity\n */\nexport interface SingleSubscriptionConfig {\n clientId: string;\n path: string;\n id: string | number;\n}\n\n/**\n * Opt-in retention for one set of broadcast channels.\n *\n * Retention is configured on the server and nowhere else. A channel is created\n * by whoever names it, so letting a client ask for its own history depth would\n * let any visitor commit the backend to unbounded storage; and presence-only or\n * notification-only channels — the overwhelming majority — must not pay for a\n * feature they never use. With no rules configured nothing is written, no table\n * is created, and broadcast behaves exactly as it did before history existed.\n */\nexport interface ChannelRetentionRule {\n /**\n * Channel name to match. Either exact (`\"doc:42\"`) or a trailing-`*` prefix\n * (`\"doc:*\"`). Deliberately not a full glob or RegExp: this decides what\n * gets written to disk, and a rule whose blast radius is not obvious at a\n * glance is the wrong shape for that.\n */\n match: string;\n /** Keep at most this many of the most recent messages per channel. */\n limit?: number;\n /**\n * Keep messages for at most this long. Accepts a millisecond count or a\n * short duration string (`\"30s\"`, `\"15m\"`, `\"24h\"`, `\"7d\"`).\n */\n ttl?: number | string;\n}\n\n/**\n * Server-side realtime options.\n *\n * The channel bus contract and its config live in `./channel_bus` so that a\n * transport shipped as its own package depends on the contract alone.\n */\nexport interface RealtimeChannelsConfig {\n /**\n * Retention rules, most specific first — the first match wins. Omitted or\n * empty means no channel retains anything.\n */\n channels?: ChannelRetentionRule[];\n /**\n * How channel broadcast and presence reach other backend instances.\n * Defaults to `{ type: \"memory\" }` — i.e. they don't.\n */\n bus?: ChannelBusSetting;\n}\n\n/**\n * Abstract realtime provider interface.\n * Handles real-time subscriptions and notifications for entity changes.\n */\nexport interface RealtimeProvider {\n /**\n * Subscribe to collection changes\n */\n subscribeToCollection(\n subscriptionId: string,\n config: CollectionSubscriptionConfig,\n callback?: (rows: Record<string, unknown>[]) => void\n ): void;\n\n /**\n * Subscribe to single entity changes\n */\n subscribeToOne(\n subscriptionId: string,\n config: SingleSubscriptionConfig,\n callback?: (row: Record<string, unknown> | null) => void\n ): void;\n\n /**\n * Unsubscribe from a subscription\n */\n unsubscribe(subscriptionId: string): void;\n\n /**\n * Notify all relevant subscribers of a entity update\n */\n notifyUpdate(\n path: string,\n id: string,\n row: Record<string, unknown> | null,\n databaseId?: string\n ): Promise<void>;\n\n /**\n * Called when the HTTP server is ready and listening.\n * Useful for providers that need the server address for callbacks.\n */\n onServerReady?(serverInfo: { port: number; hostname?: string }): void;\n\n /**\n * Gracefully shut down the realtime provider.\n * Called during server shutdown to clean up resources.\n */\n destroy?(): Promise<void>;\n\n /**\n * Stop the internal LISTEN client (e.g., PostgreSQL LISTEN/NOTIFY).\n * Called during graceful shutdown before closing database connections.\n */\n stopListening?(): Promise<void>;\n}\n\n// =============================================================================\n// COLLECTION REGISTRY INTERFACES\n// =============================================================================\n\n/**\n * Abstract collection registry interface.\n * Manages registration and lookup of entity collections.\n */\nexport interface CollectionRegistryInterface {\n /**\n * Register a collection\n */\n register(collection: CollectionConfig): void;\n\n /**\n * Get a collection by its path\n */\n getCollectionByPath(path: string): CollectionConfig | undefined;\n\n /**\n * Get all registered collections\n */\n getCollections(): CollectionConfig[];\n\n /**\n * Get the currently registered global callbacks, if any.\n */\n getGlobalCallbacks(): any | undefined;\n}\n\n// =============================================================================\n// DATA TRANSFORMER INTERFACES\n// =============================================================================\n\n/**\n * Abstract data transformer interface.\n * Handles serialization/deserialization between frontend and database formats.\n */\nexport interface DataTransformer {\n /**\n * Transform entity data for storage in the database\n */\n serializeToDatabase<M extends Record<string, unknown>>(\n entity: M,\n collection: CollectionConfig\n ): Record<string, unknown>;\n\n /**\n * Transform database data back to entity format\n */\n deserializeFromDatabase<M extends Record<string, unknown>>(\n data: Record<string, unknown>,\n collection: CollectionConfig\n ): Promise<M>;\n}\n\n// =============================================================================\n// DATABASE ADMIN — CAPABILITY-SPECIFIC INTERFACES (1.3)\n// =============================================================================\n\n/**\n * Administrative operations for SQL-based databases (PostgreSQL, MySQL, etc.).\n * Used by the SQL Editor, RLS Editor, and schema browser.\n *\n * @group Admin\n */\nexport interface SQLAdmin {\n /**\n * Execute raw SQL against the database.\n */\n executeSql(sql: string, options?: { database?: string; role?: string; params?: unknown[] }): Promise<Record<string, unknown>[]>;\n\n /**\n * Fetch the available databases on the server.\n */\n fetchAvailableDatabases?(): Promise<string[]>;\n\n /**\n * Fetch the available *native PostgreSQL* database roles (from `pg_roles`).\n *\n * These are connection-level roles — what the SQL editor can `SET ROLE` to,\n * and what `SecurityRule.pgRoles` targets. They are NOT application roles;\n * for those use {@link fetchApplicationRoles}.\n */\n fetchAvailableRoles?(): Promise<string[]>;\n\n /**\n * Fetch the *application-level* roles in use in this project.\n *\n * These are the strings stored on the users table's `roles` column and\n * exposed to policies as `rebase.roles()` — what `SecurityRule.roles`\n * matches against. Distinct from {@link fetchAvailableRoles}; the two are\n * not interchangeable.\n */\n fetchApplicationRoles?(): Promise<string[]>;\n\n /**\n * Fetch the current database name.\n */\n fetchCurrentDatabase?(): Promise<string | undefined>;\n}\n\n/**\n * Administrative operations for document-based databases (MongoDB, Firestore, etc.).\n * Used by future document administration tools.\n *\n * @group Admin\n */\nexport interface DocumentAdmin {\n /**\n * Execute an aggregation pipeline or equivalent query.\n */\n executeAggregate?(pipeline: Record<string, unknown>[]): Promise<Record<string, unknown>[]>;\n\n /**\n * Fetch statistics for a collection (document count, size, etc.).\n */\n fetchCollectionStats?(collectionName: string): Promise<{ count: number; sizeBytes?: number }>;\n}\n\n/**\n * Administrative operations for schema management.\n * Shared across SQL and document databases.\n *\n * @group Admin\n */\nexport interface SchemaAdmin {\n /**\n * Fetch database tables/collections not yet mapped to a Rebase collection.\n */\n fetchUnmappedTables?(mappedPaths?: string[]): Promise<string[]>;\n\n /**\n * Fetch column/field metadata for a single table/collection.\n * The return type is generic — SQL backends return TableMetadata,\n * document backends may return a different shape.\n */\n fetchTableMetadata?(tableName: string): Promise<unknown>;\n}\n\n/**\n * Metadata for a database branch.\n * @group Admin\n */\nexport interface BranchInfo {\n /** Branch name (without prefix). */\n name: string;\n /** The database this branch was created from. */\n parentDatabase: string;\n /** When the branch was created. */\n createdAt: Date;\n /** Size in bytes, if available from the server. */\n sizeBytes?: number;\n}\n\n/**\n * Administrative operations for database branching.\n * Allows creating isolated database copies for development/preview workflows.\n *\n * @group Admin\n */\nexport interface BranchAdmin {\n /** Create a new branch (database copy) from the current or specified source database. */\n createBranch(name: string, options?: { source?: string }): Promise<BranchInfo>;\n\n /** Delete a branch database. Cannot delete the main/default database. */\n deleteBranch(name: string): Promise<void>;\n\n /** List all branches (databases that were created via branching). */\n listBranches(): Promise<BranchInfo[]>;\n\n /** Get info about a specific branch. */\n getBranchInfo(name: string): Promise<BranchInfo | undefined>;\n}\n\n/**\n * Union type for all admin capabilities.\n * A backend may implement any combination of these interfaces.\n *\n * Use type guards (`isSQLAdmin`, `isDocumentAdmin`, `isSchemaAdmin`, `isBranchAdmin`)\n * to safely narrow the type before calling methods.\n *\n * @group Admin\n */\nexport type DatabaseAdmin = Partial<SQLAdmin> & Partial<DocumentAdmin> & Partial<SchemaAdmin>\n & Partial<BranchAdmin> & Partial<SchemaEditingAdmin>;\n\n/**\n * Type guard: can this admin plan a live schema change?\n *\n * Planning is engine-specific — it renders DDL, a Drizzle schema and the\n * declarative SQL artifacts — so the implementation lives in the driver\n * package. The server detects the capability structurally, exactly as it does\n * for SQL, rather than importing an engine it is supposed to know nothing\n * about.\n *\n * @group Admin\n */\nexport function isSchemaEditingAdmin(admin: DatabaseAdmin | undefined): admin is SchemaEditingAdmin {\n return !!admin && typeof (admin as SchemaEditingAdmin).planSchemaChange === \"function\";\n}\n\n/**\n * Type guard: does this admin support SQL operations?\n * @group Admin\n */\nexport function isSQLAdmin(admin: DatabaseAdmin | undefined): admin is SQLAdmin {\n return !!admin && typeof (admin as SQLAdmin).executeSql === \"function\";\n}\n\n/**\n * Type guard: does this admin support document operations?\n * @group Admin\n */\nexport function isDocumentAdmin(admin: DatabaseAdmin | undefined): admin is DocumentAdmin {\n return !!admin && (\n typeof (admin as DocumentAdmin).executeAggregate === \"function\" ||\n typeof (admin as DocumentAdmin).fetchCollectionStats === \"function\"\n );\n}\n\n/**\n * Type guard: does this admin support schema management?\n * @group Admin\n */\nexport function isSchemaAdmin(admin: DatabaseAdmin | undefined): admin is SchemaAdmin {\n return !!admin && (\n typeof (admin as SchemaAdmin).fetchUnmappedTables === \"function\" ||\n typeof (admin as SchemaAdmin).fetchTableMetadata === \"function\"\n );\n}\n\n/**\n * Type guard: does this admin support database branching?\n * @group Admin\n */\nexport function isBranchAdmin(admin: DatabaseAdmin | undefined): admin is BranchAdmin {\n return !!admin && typeof (admin as BranchAdmin).createBranch === \"function\";\n}\n\n// =============================================================================\n// LIFECYCLE INTERFACES (1.4)\n// =============================================================================\n\n/**\n * Health check result returned by `healthCheck()`.\n * @group Lifecycle\n */\nexport interface HealthCheckResult {\n /** Whether the backend is healthy and able to serve requests. */\n healthy: boolean;\n /** Round-trip latency to the database in milliseconds. */\n latencyMs: number;\n /** Optional details (e.g., pool stats, replication lag). */\n details?: Record<string, unknown>;\n}\n\n/**\n * Lifecycle contract for backend components that hold resources\n * (database connections, WebSocket pools, timers, etc.).\n *\n * All methods are optional — simple backends (e.g., in-memory) can skip them.\n * @group Lifecycle\n */\nexport interface BackendLifecycle {\n /**\n * Initialize the backend: open connections, run migrations, seed data.\n * Called once during startup. Idempotent.\n */\n initialize?(): Promise<void>;\n\n /**\n * Check whether the backend is healthy and reachable.\n * Should be fast (< 1 s) and safe to call frequently.\n */\n healthCheck?(): Promise<HealthCheckResult>;\n\n /**\n * Gracefully shut down: close connections, flush buffers, cancel timers.\n * After calling `destroy()`, no other methods should be called.\n */\n destroy?(): Promise<void>;\n}\n\n// =============================================================================\n// BACKEND FACTORY INTERFACES\n// =============================================================================\n\n/**\n * Configuration for creating a database backend\n */\nexport interface BackendConfig {\n /**\n * Type of database backend\n */\n type: string;\n\n /**\n * Database connection (implementation-specific)\n */\n connection: unknown;\n\n /**\n * Schema definition (implementation-specific, e.g., Drizzle schema for PostgreSQL)\n */\n schema?: unknown;\n}\n\n/**\n * A complete backend instance with all required services.\n *\n * Now includes optional lifecycle management and admin capabilities.\n */\nexport interface BackendInstance extends BackendLifecycle {\n /**\n * Entity repository for CRUD operations\n */\n entityRepository: DataRepository;\n\n /**\n * Realtime provider for subscriptions\n */\n realtimeProvider: RealtimeProvider;\n\n /**\n * Collection registry\n */\n collectionRegistry: CollectionRegistryInterface;\n\n /**\n * The underlying database connection\n */\n connection: DatabaseConnection;\n\n /**\n * Administrative operations (SQL, schema, documents).\n * What's available depends on the backend type — use type guards\n * (`isSQLAdmin`, `isSchemaAdmin`, etc.) to narrow.\n */\n admin?: DatabaseAdmin;\n}\n\n/**\n * Factory function type for creating backend instances\n */\nexport type BackendFactory<TConfig extends BackendConfig = BackendConfig> =\n (config: TConfig) => BackendInstance;\n\n// =============================================================================\n// BACKEND BOOTSTRAPPER (1.2)\n// =============================================================================\n\n/**\n * A `BackendBootstrapper` encapsulates all driver-specific initialization logic.\n *\n * Instead of hard-coding Postgres setup into `initializeRebaseBackend()`,\n * each database backend provides its own bootstrapper that knows how to:\n * - Create the DataDriver from a config object\n * - Optionally initialize auth tables\n * - Optionally create a realtime service\n * - Mount driver-specific API routes\n *\n * The main `initializeRebaseBackend()` becomes a **coordinator** that iterates\n * registered bootstrappers, calls their hooks, and wires the results together.\n *\n * @group Backend\n *\n * @example\n * ```typescript\n * // Third-party MySQL bootstrapper\n * const mysqlBootstrapper: BackendBootstrapper = {\n * type: \"mysql\",\n * initializeDriver: async (config) => new MySQLDataDriver(config.connection),\n * initializeRealtime: async (config) => new MySQLChangeStreamRealtime(config.connection),\n * };\n *\n * initializeRebaseBackend({\n * ...config,\n * bootstrappers: [postgresBootstrapper, mysqlBootstrapper]\n * });\n * ```\n */\nexport interface BackendBootstrapper {\n /**\n * Which driver type this bootstrapper handles.\n * Must match the `type` field on the driver config object\n * (e.g., `\"postgres\"`, `\"mongodb\"`, `\"mysql\"`).\n */\n type: string;\n\n /**\n * Unique identifier for this bootstrapper instance.\n * Used to register the driver in the driver registry.\n * Defaults to `type` if not set.\n */\n id?: string;\n\n /**\n * Whether this bootstrapper provides the default driver.\n * When true, the coordinator uses this driver as the primary one.\n */\n isDefault?: boolean;\n\n /**\n * Run database migrations for this driver.\n * Called by the coordinator after all drivers are initialized.\n */\n runMigrations?(config: unknown, driverResult: InitializedDriver): Promise<void>;\n\n /**\n * Create a DataDriver from the given config.\n * This is the only **required** method.\n */\n initializeDriver(config: unknown): Promise<InitializedDriver>;\n\n /**\n * Initialize auth tables / services if this driver supports them.\n * Return undefined if auth is not supported by this backend.\n */\n initializeAuth?(config: unknown, driverResult: InitializedDriver): Promise<BootstrappedAuth | undefined>;\n\n /**\n * Initialize history tables / services if this driver supports them.\n * Return undefined if history is not supported by this backend.\n */\n initializeHistory?(config: HistoryConfig, driverResult: InitializedDriver): Promise<{ historyService: unknown } | undefined>;\n\n /**\n * Create a realtime provider for this driver.\n * Return undefined if the driver does not support realtime.\n */\n initializeRealtime?(config: unknown, driverResult: InitializedDriver): Promise<RealtimeProvider | undefined>;\n\n /**\n * Mount any driver-specific HTTP routes (e.g., custom admin endpoints).\n * Called after all drivers are initialized.\n */\n mountRoutes?(app: unknown, basePath: string, driverResult: InitializedDriver): void;\n\n /**\n * Return admin capabilities for this driver.\n */\n getAdmin?(driverResult: InitializedDriver): DatabaseAdmin | undefined;\n\n /**\n * Bring the database's collection tables up to date, additively.\n *\n * Optional because it is only meaningful for schema-ful drivers. A managed\n * runtime boots a compiled project against a database it has never seen; auth\n * tables are ensured on boot but collection tables were created by nothing,\n * so every data request answered 500 on a missing relation. The CLI's `db\n * push` cannot fill the gap — it needs Atlas, and the runtime image ships no\n * CLI.\n *\n * Implementations MUST be additive-only: create missing tables, columns and\n * enum types, and never drop, narrow or rewrite anything. This runs\n * unattended against live customer data with nobody reading a diff, so the\n * destructive half stays a deliberate migration.\n *\n * `driverResult` is optional: this runs before `initializeDriver`, and only\n * the bundle path has a pre-init stand-in to pass. An adapter built by an\n * application already holds its own connection and MUST use it when this is\n * `undefined` — dereferencing it unconditionally works for managed tenants\n * and breaks every app that builds its own adapter.\n */\n ensureCollectionSchema?(\n collections: unknown[],\n driverResult?: InitializedDriver,\n log?: (message: string) => void\n ): Promise<{ applied: number }>;\n\n /**\n * Apply the collections' row-level-security policies, additively and\n * idempotently — the companion to {@link ensureCollectionSchema}.\n *\n * That method creates the tables; a table with RLS disabled and no policies\n * is not servable, because authenticated requests run as a restricted role:\n * a read with no `SELECT` policy returns nothing (a public collection\n * answers 401) and a write with no `INSERT`/`UPDATE` policy is denied. The\n * `db push` CLI applies these from the same collections, but it cannot reach\n * a managed tenant's in-cluster database — the runtime, already connected,\n * is the only thing that can.\n *\n * MUST be idempotent (re-run on every boot) and MUST NOT be destructive.\n * Runs after auth initialization, because the generated policies call the\n * `auth.*` helper functions and `CREATE POLICY` validates they exist.\n */\n ensureCollectionPolicies?(\n collections: unknown[],\n driverResult?: InitializedDriver,\n log?: (message: string) => void\n ): Promise<{ applied: number }>;\n\n /**\n * Read the collections schema version this database was last provisioned\n * from, or `null` when nothing has ever stamped it.\n *\n * The companion to {@link stampCollectionsSchemaVersion}: one process writes\n * what it applied, every other process compares itself to it. This is what\n * lets a split deployment — several processes over one database, only one of\n * which provisions — notice that a unit is serving against a schema it was\n * not built for. That failure is otherwise silent in both directions: a\n * column that does not exist is a SQL error on one route, and a policy that\n * was never applied is a 200 with no rows.\n *\n * `null` is not an error and MUST NOT be treated as one — every database\n * provisioned before the stamp existed reads this way, and so does every\n * fresh one until its first provisioning boot finishes.\n */\n readCollectionsSchemaVersion?(\n driverResult?: InitializedDriver\n ): Promise<string | null>;\n\n /**\n * Record the collections schema version this process just applied.\n *\n * Called only by the process that provisions, and only after both\n * {@link ensureCollectionSchema} and {@link ensureCollectionPolicies} have\n * run — a stamp written before the policies would claim a schema that is\n * only half in place, and the half that is missing is the one that fails\n * without an error.\n */\n stampCollectionsSchemaVersion?(\n version: string,\n driverResult?: InitializedDriver\n ): Promise<void>;\n\n /**\n * Initialize WebSocket server for realtime operations.\n */\n initializeWebsockets?(server: unknown, realtimeService: RealtimeProvider, driver: import(\"../controllers/data_driver\").DataDriver, config?: unknown, authAdapter?: AuthAdapter): Promise<void> | void;\n}\n\n/**\n * Result of `BackendBootstrapper.initializeDriver()`.\n * @group Backend\n */\nexport interface InitializedDriver {\n /** The DataDriver instance, ready for use. */\n driver: import(\"../controllers/data_driver\").DataDriver;\n\n /** The realtime service, if the driver created one during init. */\n realtimeProvider?: RealtimeProvider;\n\n /** A collection registry to register schema / tables into. */\n collectionRegistry?: CollectionRegistryInterface;\n\n /**\n * Collections the driver derived from the live database schema.\n *\n * Set by drivers that introspect in `baas` mode; the server serves these\n * instead of collections loaded from config files.\n */\n collections?: import(\"./collections\").CollectionConfig[];\n\n /** The underlying database connection (for lifecycle management). */\n connection?: DatabaseConnection;\n\n /**\n * Opaque handle that the bootstrapper can use in subsequent hooks\n * (e.g., `initializeAuth`, `mountRoutes`) to access driver internals.\n * Not used by the coordinator.\n */\n internals?: unknown;\n}\n\n/**\n * Result of `BackendBootstrapper.initializeAuth()`.\n * @group Backend\n */\nexport interface BootstrappedAuth {\n /** User management service. */\n userService: unknown;\n /** Role management service (optional, roles are now simple strings). */\n roleService?: unknown;\n /** Email service (optional). */\n emailService?: unknown;\n /** Combined Auth Repository for unified token and user management. */\n authRepository?: unknown;\n /**\n * Whether the auth schema in the database is one this runtime can serve.\n *\n * Folded into `healthCheck()` so a schema mismatch shows up as a degraded\n * health response. Without it, a server whose auth is entirely broken still\n * reports healthy — the database connection it probes is fine, and the\n * mismatch is only discovered one failed login at a time.\n */\n schemaHealthCheck?(): Promise<AuthSchemaHealth>;\n}\n\n/**\n * Result of {@link BootstrappedAuth.schemaHealthCheck}.\n * @group Lifecycle\n */\nexport interface AuthSchemaHealth {\n /** False when this runtime cannot be trusted to serve auth against this database. */\n healthy: boolean;\n /** Human-readable descriptions of each mismatch found. Empty when healthy. */\n problems: string[];\n /** Auth schema version recorded in the database, when it records one. */\n databaseVersion?: number | null;\n /** Auth schema version this runtime expects. */\n runtimeVersion?: number;\n}\n","import { RealtimeService } from \"./services/realtimeService\";\nimport { PostgresBackendDriver } from \"./PostgresBackendDriver\";\nimport type { DataDriver, DeleteProps, FetchCollectionProps, FetchOneProps, SaveProps, TableMetadata, BranchInfo, AuthAdapter } from \"@rebasepro/types\";\nimport { ANONYMOUS_USER_ID, isSQLAdmin, isSchemaAdmin, resolveClientListLimit, ListLimitError } from \"@rebasepro/types\";\nimport type { User } from \"@rebasepro/types\";\n\nimport { WebSocketServer, WebSocket } from \"ws\";\nimport { Server } from \"http\";\nimport { inspect } from \"util\";\nimport { extractUserFromToken, AccessTokenPayload, safeCompare, resolveRequireAuth, assertWriteRequestValid, ApiError } from \"@rebasepro/server\";\nimport { logger } from \"@rebasepro/server\";\n\n/** Minimal subset of RebaseAuthConfig used by the WebSocket layer. */\ninterface WsAuthConfig {\n requireAuth?: boolean;\n jwtSecret?: string;\n /**\n * Same static server-to-server secret the HTTP middleware accepts. Without\n * it here, a service key authenticates over HTTP but not over the socket —\n * so any SDK client using one (scripts, cron, server-to-server) connects,\n * fails realtime auth with \"jwt malformed\", and silently gets no events.\n */\n serviceKey?: string;\n}\n\n/**\n * Normalized user identity for WebSocket sessions.\n */\ninterface WsUserIdentity {\n uid: string;\n roles: string[];\n isAdmin: boolean;\n}\n\ninterface ClientSession {\n ws: WebSocket;\n user?: WsUserIdentity;\n authenticated: boolean;\n /** Sliding window message counter for rate limiting */\n messageCount: number;\n messageWindowStart: number;\n /** The same window, counted separately for channel frames. */\n channelMessageCount: number;\n channelWindowStart: number;\n}\n\n\n/** Maximum messages per client per window */\nconst WS_RATE_LIMIT = 2000;\n/** Rate limit window in milliseconds (60 seconds) */\nconst WS_RATE_WINDOW_MS = 60_000;\n\n/**\n * Channel frames get their own budget, because they are a different workload.\n *\n * 2000/minute is 33/second, which is generous for queries and subscriptions and\n * an order of magnitude below what the documented channel idiom asks for: the\n * capacity note in `docs/backend/realtime.md` uses 60 fps cursor movement as\n * its worked example, and the presence idiom re-`track()`s on every move, so\n * one client sustaining that sends ~120 frames/second — 7200 a minute. Sharing\n * one counter meant the cursor stream ate the query budget and then froze for\n * the rest of the window.\n *\n * The number is sized to that documented workload and nothing more; it is not\n * a considered product limit (see `docs/channel-authorization.md`).\n */\nconst WS_CHANNEL_RATE_LIMIT = 7200;\n\n/** Frames counted against the channel budget rather than the general one. */\nconst CHANNEL_MESSAGE_TYPES = new Set([\n \"join_channel\",\n \"leave_channel\",\n \"broadcast\",\n \"presence_track\",\n \"presence_untrack\",\n \"presence_state\",\n \"channel_history\"\n]);\n\n/**\n * WebSocket message types that require an admin session.\n *\n * Exported so the test can READ it. It used to be private, and the test that\n * exists to make \"a privileged verb added without a role check\" impossible held\n * a hand-typed copy of the same nine strings — so it agreed with itself, and\n * `FETCH_APPLICATION_ROLES` was added to neither. That verb runs\n * `SELECT DISTINCT unnest(roles)` over the users table through `executeSql`,\n * which is the owner connection and not subject to RLS, so any authenticated\n * non-admin could enumerate every role in the project — and any anonymous\n * socket could, on a deployment with `requireAuth: false`.\n *\n * The list is no longer the whole guarantee. `PUBLIC_TYPES` below is its\n * counterpart, and a test asserts that every `case` this file handles appears\n * in exactly one of the two — so a verb added to neither fails rather than\n * defaulting to reachable.\n */\nexport const ADMIN_ONLY_TYPES = new Set([\n \"EXECUTE_SQL\",\n \"FETCH_DATABASES\",\n \"FETCH_ROLES\",\n \"FETCH_APPLICATION_ROLES\",\n \"FETCH_UNMAPPED_TABLES\",\n \"FETCH_TABLE_METADATA\",\n \"FETCH_CURRENT_DATABASE\",\n \"CREATE_BRANCH\",\n \"DELETE_BRANCH\",\n \"LIST_BRANCHES\"\n]);\n\n/**\n * Message types deliberately reachable by a non-admin session.\n *\n * Data operations, gated per row by RLS and per request by the same write\n * checks the REST layer applies — not by this list. It exists so that \"which\n * bucket is this verb in\" is a question with an answer for every verb, and\n * adding one without answering it is a test failure.\n */\nexport const PUBLIC_TYPES = new Set([\n \"FETCH_COLLECTION\",\n \"FETCH_ONE\",\n \"COUNT\",\n \"SAVE\",\n \"DELETE\",\n \"CHECK_UNIQUE_FIELD\"\n]);\n\n/**\n * Recursively extract the deepest error message from an error's cause chain (e.g., Drizzle wrapping a PG error).\n */\nfunction extractErrorMessage(error: unknown): string {\n if (!error) return \"Unknown error\";\n if (error instanceof Error) {\n if (\"cause\" in error && error.cause) {\n return extractErrorMessage(error.cause);\n }\n return error.message;\n }\n if (typeof error === \"object\" && \"message\" in error && typeof (error as { message: unknown }).message === \"string\") {\n return (error as { message: string }).message;\n }\n return String(error);\n}\n\n/**\n * Check if the current session belongs to an admin user.\n */\nfunction isAdminSession(session: ClientSession | undefined): boolean {\n if (!session?.user) return false;\n // Fast path: new adapter-aware sessions set isAdmin directly\n if (session.user.isAdmin) return true;\n if (!session.user.roles) return false;\n return session.user.roles.some((r) => r === \"admin\");\n}\n\nexport function createPostgresWebSocket(\n server: Server,\n realtimeService: RealtimeService,\n driver: PostgresBackendDriver,\n authConfig?: WsAuthConfig,\n authAdapter?: AuthAdapter\n) {\n // Session map scoped to this factory invocation — prevents stale sessions\n // leaking across hot reloads or multiple factory calls.\n const clientSessions = new Map<string, ClientSession>();\n\n const isProduction = process.env.NODE_ENV === \"production\";\n /** Debug logger that is suppressed in production to prevent PII/data leaks */\n const wsDebug = (...args: unknown[]) => { if (!isProduction) console.debug(...args); };\n const wss = new WebSocketServer({ server });\n\n // Handle errors on the WSS so that EADDRINUSE from the underlying HTTP\n // server doesn't surface as an unhandled 'error' event and crash the\n // process. The dev-mode `listenWithPortRetry` utility handles retry\n // logic on the HTTP server side — we just need the WSS not to throw.\n wss.on(\"error\", (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\") {\n // Silently absorbed — listenWithPortRetry will retry the next port\n return;\n }\n logger.error(\"❌ [WebSocket Server] Error\", { error: err });\n });\n\n // The same predicate the HTTP data routes use, from the same function —\n // this socket is the other enforcement point for one product decision, and\n // while it computed the answer itself it computed a different one. See\n // `resolveRequireAuth` for what its local copy got wrong and why a `false`\n // here grants access rather than skipping a check.\n const requireAuth = !!authAdapter || resolveRequireAuth(authConfig as never);\n\n if (requireAuth && !authAdapter && !authConfig?.jwtSecret && !authConfig?.serviceKey) {\n logger.warn(\n \"🔐 [WebSocket Server] Authentication is required but no adapter, jwtSecret or \" +\n \"serviceKey is configured — no client can complete AUTH, so every realtime \" +\n \"message will be refused with UNAUTHORIZED.\"\n );\n }\n\n wss.on(\"connection\", (ws) => {\n const clientId = `client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n wsDebug(`WebSocket client connected: ${clientId}`);\n\n // Initialize client session\n clientSessions.set(clientId, { ws,\nauthenticated: !requireAuth,\nmessageCount: 0,\nmessageWindowStart: Date.now(),\nchannelMessageCount: 0,\nchannelWindowStart: Date.now() });\n realtimeService.addClient(clientId, ws);\n\n ws.on(\"close\", () => {\n wsDebug(`WebSocket client disconnected: ${clientId}`);\n clientSessions.delete(clientId);\n });\n\n // Route all messages through RealtimeService for unified handling\n ws.on(\"message\", async (message) => {\n let requestId: string | undefined;\n try {\n const {\n type,\n payload,\n requestId: reqId\n } = JSON.parse(message.toString());\n requestId = reqId; // Capture requestId for use in catch block\n\n wsDebug(`[WS] ${clientId} → ${type}`, requestId ? `(${requestId})` : \"\");\n\n // Handle authentication first\n // Helper: send a canonical error frame\n const sendError = (errType: \"ERROR\" | \"AUTH_ERROR\", code: string, msg: string) => {\n ws.send(JSON.stringify({\n type: errType,\n requestId,\n payload: { error: { message: msg,\ncode } }\n }));\n };\n\n if (type === \"AUTHENTICATE\") {\n const { token } = payload || {};\n if (!token) {\n sendError(\"AUTH_ERROR\", \"INVALID_INPUT\", \"Token is required\");\n return;\n }\n\n // Use the auth adapter when available (custom auth, Clerk, etc.)\n // Fall back to JWT extraction otherwise.\n let verifiedUser: WsUserIdentity | null = null;\n\n if (authAdapter) {\n try {\n const adapterUser = authAdapter.verifyToken\n ? await authAdapter.verifyToken(token)\n : await authAdapter.verifyRequest(new Request(\"http://localhost/_ws_auth\", {\n headers: { Authorization: `Bearer ${token}` }\n }));\n\n if (adapterUser) {\n verifiedUser = {\n uid: adapterUser.uid,\n roles: adapterUser.roles,\n isAdmin: adapterUser.isAdmin\n };\n }\n } catch {\n // Adapter threw — treat as invalid token\n }\n } else if (authConfig?.serviceKey && safeCompare(token, authConfig.serviceKey)) {\n // Service key: a static secret, not a JWT. Checked\n // before verification, mirroring the HTTP middleware —\n // verifying it as a JWT can only ever fail.\n verifiedUser = { uid: \"service\", roles: [\"admin\"], isAdmin: true };\n } else {\n // Standard JWT path\n const jwtPayload = extractUserFromToken(token);\n if (jwtPayload) {\n verifiedUser = {\n uid: jwtPayload.uid,\n roles: jwtPayload.roles ?? [],\n isAdmin: (jwtPayload.roles ?? []).some((r: string) => r === \"admin\")\n };\n }\n }\n\n if (verifiedUser) {\n const session = clientSessions.get(clientId);\n if (session) {\n session.user = verifiedUser;\n session.authenticated = true;\n }\n wsDebug(`[WS] replying AUTH_SUCCESS for requestId ${requestId}`);\n ws.send(JSON.stringify({\n type: \"AUTH_SUCCESS\",\n requestId,\n payload: { uid: verifiedUser.uid,\nroles: verifiedUser.roles }\n }));\n wsDebug(`🔐 [WebSocket Server] Client ${clientId} authenticated as ${verifiedUser.uid}`);\n } else {\n wsDebug(`[WS] replying AUTH_ERROR for requestId ${requestId} (invalid token)`);\n sendError(\"AUTH_ERROR\", \"INVALID_TOKEN\", \"Invalid or expired token\");\n }\n return;\n }\n\n // Check authentication for protected operations\n if (requireAuth) {\n const session = clientSessions.get(clientId);\n if (!session?.authenticated) {\n sendError(\"ERROR\", \"UNAUTHORIZED\", \"Authentication required\");\n return;\n }\n }\n\n // Rate limiting: reject if client exceeds message limit.\n // Channel frames are counted against their own budget — see\n // WS_CHANNEL_RATE_LIMIT for why one shared counter starved them.\n {\n const session = clientSessions.get(clientId);\n if (session) {\n const now = Date.now();\n const isChannelFrame = CHANNEL_MESSAGE_TYPES.has(type);\n if (isChannelFrame) {\n if (now - session.channelWindowStart > WS_RATE_WINDOW_MS) {\n session.channelMessageCount = 0;\n session.channelWindowStart = now;\n }\n session.channelMessageCount++;\n if (session.channelMessageCount > WS_CHANNEL_RATE_LIMIT) {\n sendError(\"ERROR\", \"RATE_LIMITED\", \"Too many channel messages. Please slow down.\");\n return;\n }\n } else {\n if (now - session.messageWindowStart > WS_RATE_WINDOW_MS) {\n session.messageCount = 0;\n session.messageWindowStart = now;\n }\n session.messageCount++;\n if (session.messageCount > WS_RATE_LIMIT) {\n sendError(\"ERROR\", \"RATE_LIMITED\", \"Too many requests. Please slow down.\");\n return;\n }\n }\n }\n }\n\n // Admin-only operations require admin role\n if (ADMIN_ONLY_TYPES.has(type)) {\n const session = clientSessions.get(clientId);\n if (!isAdminSession(session)) {\n sendError(\"ERROR\", \"FORBIDDEN\", \"Admin access required for this operation\");\n return;\n }\n }\n\n /**\n * Apply the REST layer's write checks to a socket payload.\n *\n * Silent when the path names no registered collection: the\n * driver decides what a path means, and refusing here would\n * turn \"unknown collection\" into a validation error.\n */\n const assertWriteRequest = (path: string | undefined, values: unknown): void => {\n if (!path || !values || typeof values !== \"object\") return;\n const collection = driver.registry?.getCollectionByPath(path);\n if (!collection) return;\n assertWriteRequestValid(values as Record<string, unknown>, collection);\n };\n\n // Helper to get correctly scoped delegate for the current request\n const getScopedDelegate = async (): Promise<DataDriver> => {\n const session = clientSessions.get(clientId);\n // Check if the driver supports RLS-scoped delegates\n if (typeof driver.withAuth === \"function\") {\n try {\n const userForAuth: User = session?.user\n ? {\n uid: session.user.uid,\n displayName: null,\n email: null,\n photoURL: null,\n providerId: \"websocket\",\n isAnonymous: false,\n roles: session.user.roles ?? []\n }\n : {\n uid: ANONYMOUS_USER_ID,\n displayName: null,\n email: null,\n photoURL: null,\n providerId: \"websocket\",\n isAnonymous: true,\n roles: [\"anon\"]\n };\n return await driver.withAuth(userForAuth);\n } catch (e) {\n logger.error(\"Failed to create RLS scoped delegate for WS request\", { error: e });\n throw new Error(\"Internal authentication error\");\n }\n }\n return driver;\n };\n\n switch (type) {\n case \"FETCH_COLLECTION\": {\n wsDebug(\"📋 [WebSocket Server] Processing FETCH_COLLECTION request\");\n const request: FetchCollectionProps = payload;\n const delegate = await getScopedDelegate();\n // Bound the client-supplied limit with the SAME guarantee\n // the REST ingress and `subscribe_collection` apply\n // (`resolveClientListLimit`). Without it an absent limit\n // reached the driver as `undefined`, which emits no LIMIT\n // clause — one socket frame streamed the whole table, on\n // the one transport that skipped the ceiling every other\n // read path enforces.\n const rows = await delegate.fetchCollection({\n ...request,\n limit: resolveClientListLimit(request.limit, {\n vectorSearch: !!request.vectorSearch\n })\n });\n wsDebug(\"📋 [WebSocket Server] FETCH_COLLECTION result - rows count:\", rows.length);\n const response = {\n type: \"FETCH_COLLECTION_SUCCESS\",\n payload: { rows },\n requestId\n };\n wsDebug(\"📋 [WebSocket Server] Sending FETCH_COLLECTION_SUCCESS response\");\n ws.send(JSON.stringify(response));\n }\n break;\n\n case \"FETCH_ONE\": {\n wsDebug(\"📄 [WebSocket Server] Processing FETCH_ENTITY request\");\n const request: FetchOneProps = payload;\n const delegate = await getScopedDelegate();\n const row = await delegate.fetchOne(request);\n wsDebug(\"📄 [WebSocket Server] FETCH_ENTITY result:\", row);\n const response = {\n type: \"FETCH_ONE_SUCCESS\",\n payload: { row: row ?? null },\n requestId\n };\n wsDebug(\"📄 [WebSocket Server] Sending FETCH_ENTITY_SUCCESS response\");\n ws.send(JSON.stringify(response));\n }\n break;\n\n case \"SAVE\": {\n wsDebug(\"💾 [WebSocket Server] Processing SAVE_ENTITY request\");\n const request: SaveProps = payload;\n wsDebug(\"💾 [WebSocket Server] Saving row with request:\", inspect(request, { depth: null,\ncolors: true }));\n // The same two checks the REST write routes run, on the\n // same input, at the same point. This socket is the\n // other request boundary — the comment on `requireAuth`\n // above says so — and it used to hand the client's\n // payload straight to the driver, so a value the HTTP\n // API answers 400 for was written when it arrived here.\n //\n // The collection comes from the registry by path, never\n // from `request.collection`: that field is client-\n // supplied, and reading the rules out of it would let\n // the caller choose which rules to be checked against.\n assertWriteRequest(request.path, request.values as Record<string, unknown>);\n const delegate = await getScopedDelegate();\n const row = await delegate.save(request);\n wsDebug(\"💾 [WebSocket Server] SAVE_ENTITY result:\", inspect(row, { depth: null,\ncolors: true }));\n const response = {\n type: \"SAVE_SUCCESS\",\n payload: { row },\n requestId\n };\n wsDebug(\"💾 [WebSocket Server] Sending SAVE_ENTITY_SUCCESS response\");\n ws.send(JSON.stringify(response));\n }\n break;\n\n case \"DELETE\": {\n wsDebug(\"🗑️ [WebSocket Server] Processing DELETE_ENTITY request\");\n const request: DeleteProps = payload;\n wsDebug(\"🗑️ [WebSocket Server] Deleting row:\", request.row);\n const delegate = await getScopedDelegate();\n await delegate.delete(request);\n wsDebug(\"🗑️ [WebSocket Server] DELETE_ENTITY completed successfully\");\n const response = {\n type: \"DELETE_SUCCESS\",\n payload: { success: true },\n requestId\n };\n wsDebug(\"🗑️ [WebSocket Server] Sending DELETE_ENTITY_SUCCESS response\");\n ws.send(JSON.stringify(response));\n }\n break;\n\n case \"CHECK_UNIQUE_FIELD\": {\n wsDebug(\"🔍 [WebSocket Server] Processing CHECK_UNIQUE_FIELD request\");\n const {\n path,\n name,\n value,\n id,\n collection\n } = payload;\n const delegate = await getScopedDelegate();\n const isUnique = await delegate.checkUniqueField(path, name, value, id, collection);\n wsDebug(\"🔍 [WebSocket Server] CHECK_UNIQUE_FIELD result:\", isUnique);\n const response = {\n type: \"CHECK_UNIQUE_FIELD_SUCCESS\",\n payload: { isUnique },\n requestId\n };\n wsDebug(\"🔍 [WebSocket Server] Sending CHECK_UNIQUE_FIELD_SUCCESS response\");\n ws.send(JSON.stringify(response));\n }\n break;\n\n\n case \"COUNT\": {\n // Deliberately NOT routed through `resolveClientListLimit`:\n // this answers with a scalar, and the driver drops `limit`\n // on the way to `SELECT count(*)`. Clamping here could only\n // ever make `total` describe fewer rows than the collection\n // holds — the page size is the caller's business, the total\n // is not.\n const request: FetchCollectionProps = payload;\n const delegate = await getScopedDelegate();\n const count = await delegate.count!(request);\n const response = {\n type: \"COUNT_SUCCESS\",\n payload: { count },\n requestId\n };\n ws.send(JSON.stringify(response));\n }\n break;\n\n case \"EXECUTE_SQL\": {\n const { sql, options } = payload;\n try {\n const delegate = await getScopedDelegate();\n const admin = delegate.admin;\n if (!isSQLAdmin(admin)) {\n sendError(\"ERROR\", \"NOT_SUPPORTED\", \"SQL execution is not available for this driver.\");\n break;\n }\n const result = await admin.executeSql(sql, options);\n if (process.env.NODE_ENV !== \"production\") {\n wsDebug(`⚡ [WebSocket Server] SQL executed. Returned ${Array.isArray(result) ? result.length : \"non-array\"} rows.`);\n }\n const auditSession = clientSessions.get(clientId);\n // Through `logger`, not `console.log`: this line is\n // emitted in production, and a bare console call\n // has no severity, no timestamp, no JSON envelope\n // and no LOG_LEVEL gate, so it lands in Cloud\n // Logging as unstructured text the queries written\n // for every other line cannot match.\n //\n // The bound values are counted, never written — the\n // statement is the audit signal, the parameters are\n // whatever row the operator was touching. (stdout is\n // not an audit sink either; a real trail belongs in\n // a table with an actor and a retention policy.)\n logger.info(\"[SQL Audit] WebSocket SQL execution\", {\n sql: typeof sql === \"string\" ? sql.substring(0, 500) : String(sql),\n database: options?.database,\n role: options?.role,\n paramCount: Array.isArray(options?.params) ? options.params.length : 0,\n resultRows: Array.isArray(result) ? result.length : \"unknown\",\n uid: auditSession?.user?.uid ?? \"unknown\",\n roles: auditSession?.user?.roles ?? [],\n isAdmin: auditSession?.user?.isAdmin ?? false,\n requestId\n });\n const response = {\n type: \"EXECUTE_SQL_SUCCESS\",\n payload: { result },\n requestId\n };\n ws.send(JSON.stringify(response));\n } catch (sqlError: unknown) {\n // This is a query execution error (e.g., syntax error, permission denied).\n // We return it cleanly to the client without logging a server stack trace.\n const errMsg = extractErrorMessage(sqlError);\n sendError(\"ERROR\", \"SQL_ERROR\", errMsg);\n }\n }\n break;\n\n case \"FETCH_DATABASES\": {\n wsDebug(\"📚 [WebSocket Server] Processing FETCH_DATABASES request\");\n const delegate = await getScopedDelegate();\n const admin = delegate.admin;\n let databases: string[] = [];\n if (isSQLAdmin(admin) && admin.fetchAvailableDatabases) {\n databases = await admin.fetchAvailableDatabases();\n }\n wsDebug(`📚 [WebSocket Server] Fetched ${databases.length} databases.`);\n const response = {\n type: \"FETCH_DATABASES_SUCCESS\",\n payload: { databases },\n requestId\n };\n ws.send(JSON.stringify(response));\n }\n break;\n\n case \"FETCH_ROLES\": {\n wsDebug(\"👤 [WebSocket Server] Processing FETCH_ROLES request\");\n const delegate = await getScopedDelegate();\n const admin = delegate.admin;\n let roles: string[] = [];\n if (isSQLAdmin(admin) && admin.fetchAvailableRoles) {\n roles = await admin.fetchAvailableRoles();\n }\n wsDebug(`👤 [WebSocket Server] Fetched ${roles.length} roles.`);\n const response = {\n type: \"FETCH_ROLES_SUCCESS\",\n payload: { roles },\n requestId\n };\n ws.send(JSON.stringify(response));\n }\n break;\n\n case \"FETCH_APPLICATION_ROLES\": {\n wsDebug(\"👤 [WebSocket Server] Processing FETCH_APPLICATION_ROLES request\");\n const delegate = await getScopedDelegate();\n const admin = delegate.admin;\n let roles: string[] = [];\n if (isSQLAdmin(admin) && admin.fetchApplicationRoles) {\n roles = await admin.fetchApplicationRoles();\n }\n wsDebug(`👤 [WebSocket Server] Fetched ${roles.length} application roles.`);\n const response = {\n type: \"FETCH_APPLICATION_ROLES_SUCCESS\",\n payload: { roles },\n requestId\n };\n ws.send(JSON.stringify(response));\n }\n break;\n\n case \"FETCH_CURRENT_DATABASE\": {\n wsDebug(\"📚 [WebSocket Server] Processing FETCH_CURRENT_DATABASE request\");\n const delegate = await getScopedDelegate();\n const admin = delegate.admin;\n let database: string | undefined = undefined;\n if (isSQLAdmin(admin) && admin.fetchCurrentDatabase) {\n database = await admin.fetchCurrentDatabase();\n }\n const response = {\n type: \"FETCH_CURRENT_DATABASE_SUCCESS\",\n payload: { database },\n requestId\n };\n ws.send(JSON.stringify(response));\n }\n break;\n\n case \"FETCH_UNMAPPED_TABLES\": {\n wsDebug(\"📋 [WebSocket Server] Processing FETCH_UNMAPPED_TABLES request\");\n const delegate = await getScopedDelegate();\n const admin = delegate.admin;\n let tables: string[] = [];\n if (isSchemaAdmin(admin) && admin.fetchUnmappedTables) {\n tables = await admin.fetchUnmappedTables(payload?.mappedPaths);\n }\n wsDebug(`📋 [WebSocket Server] Fetched ${tables.length} unmapped tables.`);\n const response = {\n type: \"FETCH_UNMAPPED_TABLES_SUCCESS\",\n payload: { tables },\n requestId\n };\n ws.send(JSON.stringify(response));\n }\n break;\n\n case \"FETCH_TABLE_METADATA\": {\n wsDebug(\"📋 [WebSocket Server] Processing FETCH_TABLE_METADATA request\");\n const { tableName } = payload;\n const delegate = await getScopedDelegate();\n const admin = delegate.admin;\n let metadata: TableMetadata | undefined;\n if (isSchemaAdmin(admin) && admin.fetchTableMetadata) {\n metadata = await admin.fetchTableMetadata(tableName) as TableMetadata;\n }\n wsDebug(`📋 [WebSocket Server] Fetched metadata for table '${tableName}'. (${metadata?.columns?.length ?? 0} columns)`);\n const response = {\n type: \"FETCH_TABLE_METADATA_SUCCESS\",\n payload: { metadata },\n requestId\n };\n ws.send(JSON.stringify(response));\n }\n break;\n\n case \"CREATE_BRANCH\": {\n wsDebug(\"🌿 [WebSocket Server] Processing CREATE_BRANCH request\");\n const { name, options } = payload;\n const delegate = await getScopedDelegate();\n if (!delegate.admin?.createBranch) {\n sendError(\"ERROR\", \"NOT_SUPPORTED\", \"Database branching is not available. Configure adminConnectionString.\");\n break;\n }\n const branch: BranchInfo = await delegate.admin.createBranch(name, options);\n wsDebug(`🌿 [WebSocket Server] Branch created: ${branch.name}`);\n const response = {\n type: \"CREATE_BRANCH_SUCCESS\",\n payload: { branch },\n requestId\n };\n ws.send(JSON.stringify(response));\n }\n break;\n\n case \"DELETE_BRANCH\": {\n wsDebug(\"🗑️ [WebSocket Server] Processing DELETE_BRANCH request\");\n const { name: branchName } = payload;\n const delegate = await getScopedDelegate();\n if (!delegate.admin?.deleteBranch) {\n sendError(\"ERROR\", \"NOT_SUPPORTED\", \"Database branching is not available.\");\n break;\n }\n await delegate.admin.deleteBranch(branchName);\n wsDebug(`🗑️ [WebSocket Server] Branch deleted: ${branchName}`);\n const response = {\n type: \"DELETE_BRANCH_SUCCESS\",\n payload: { success: true },\n requestId\n };\n ws.send(JSON.stringify(response));\n }\n break;\n\n case \"LIST_BRANCHES\": {\n wsDebug(\"🌿 [WebSocket Server] Processing LIST_BRANCHES request\");\n const delegate = await getScopedDelegate();\n let branches: BranchInfo[] = [];\n if (delegate.admin?.listBranches) {\n branches = await delegate.admin.listBranches();\n }\n wsDebug(`🌿 [WebSocket Server] Listed ${branches.length} branches.`);\n const response = {\n type: \"LIST_BRANCHES_SUCCESS\",\n payload: { branches },\n requestId\n };\n ws.send(JSON.stringify(response));\n }\n break;\n\n // Route subscription messages, broadcast channels, and presence to RealtimeService\n case \"subscribe_collection\":\n case \"subscribe_one\":\n case \"unsubscribe\":\n case \"join_channel\":\n case \"leave_channel\":\n case \"broadcast\":\n case \"presence_track\":\n case \"presence_untrack\":\n case \"presence_state\":\n case \"channel_history\": {\n wsDebug(\"🔄 [WebSocket Server] Routing realtime message to RealtimeService:\", type);\n // Attach auth context from the WS session so RLS-aware refetches work\n const session = clientSessions.get(clientId);\n const authContext = session?.user\n ? { uid: session.user.uid,\nroles: session.user.roles ?? [] }\n : { uid: ANONYMOUS_USER_ID,\nroles: [\"anon\"] };\n // Let RealtimeService handle these messages\n await realtimeService.handleClientMessage(clientId, {\n type,\n payload,\n subscriptionId: payload?.subscriptionId\n }, authContext);\n break;\n }\n\n default:\n logger.error(\"❌ [WebSocket Server] Unknown message type\", { detail: type });\n }\n } catch (error: unknown) {\n // A refused `limit` is the caller's mistake, not a server fault.\n // Left to the generic branch below it answers INTERNAL_ERROR\n // with the message suppressed in production — so the one thing\n // that would tell the caller what to send instead is exactly\n // what gets dropped. Answered here the way\n // `subscribe_collection` already answers it: INVALID_LIMIT,\n // message intact. The text names the ceiling and nothing else.\n if (error instanceof ListLimitError) {\n logger.warn(`[WebSocket Server] Refused a list read: ${error.message}`);\n ws.send(JSON.stringify({\n type: \"ERROR\",\n requestId,\n payload: { error: { message: error.message,\ncode: \"INVALID_LIMIT\" } }\n }));\n return;\n }\n // A refused write is the caller's mistake, and its message is\n // the only thing that says what to send instead — the same\n // reasoning as `ListLimitError` above. Left to the generic\n // branch it becomes INTERNAL_ERROR with the text dropped in\n // production, so the socket would refuse the write and decline\n // to say why.\n if (error instanceof ApiError || (error as Error)?.name === \"ApiError\") {\n const apiError = error as ApiError;\n logger.warn(`[WebSocket Server] Refused a write: ${apiError.message}`);\n ws.send(JSON.stringify({\n type: \"ERROR\",\n requestId,\n payload: { error: { message: apiError.message,\ncode: apiError.code } }\n }));\n return;\n }\n logger.error(\"💥 [WebSocket Server] Error handling message\", { error: error });\n if (error instanceof Error) {\n logger.error(\"Stack trace\", { detail: error.stack });\n }\n // Unwrap the cause chain: a Drizzle failure reports itself as\n // \"Failed query: <sql> params:\", which tells the user nothing and\n // echoes the statement back at them. The reason is in the cause.\n const errorMessage = process.env.NODE_ENV === \"production\"\n ? \"An unexpected error occurred\"\n : extractErrorMessage(error);\n const errorResponse = {\n type: \"ERROR\",\n requestId,\n payload: {\n error: {\n message: errorMessage,\n code: \"INTERNAL_ERROR\"\n }\n }\n };\n ws.send(JSON.stringify(errorResponse));\n }\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AA6kBA,SAAgB,WAAW,OAAqD;CAC5E,OAAO,CAAC,CAAC,SAAS,OAAQ,MAAmB,eAAe;AAChE;;;;;AAiBA,SAAgB,cAAc,OAAwD;CAClF,OAAO,CAAC,CAAC,UACL,OAAQ,MAAsB,wBAAwB,cACtD,OAAQ,MAAsB,uBAAuB;AAE7D;;;;;;;;;ACrjBA,IAAM,gBAAgB;;AAEtB,IAAM,oBAAoB;;;;;;;;;;;;;;;AAgB1B,IAAM,wBAAwB;;AAG9B,IAAM,wCAAwB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;AACJ,CAAC;;;;;;;;;;;;;;;;;;AAmBD,IAAa,mCAAmB,IAAI,IAAI;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ,CAAC;;;;;;;;;AAUD,IAAa,+BAAe,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;AACJ,CAAC;;;;AAKD,SAAS,oBAAoB,OAAwB;CACjD,IAAI,CAAC,OAAO,OAAO;CACnB,IAAI,iBAAiB,OAAO;EACxB,IAAI,WAAW,SAAS,MAAM,OA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,MAAM;MACN;MACA,SAAS,EAAE,OAAO;OAAE,SAAS,MAAM;OAC3D,MAAM;MAAgB,EAAE;KACJ,CAAC,CAAC;KACF;IACJ;IAOA,IAAI,iBAAiB,YAAa,OAAiB,SAAS,YAAY;KACpE,MAAM,WAAW;KACjB,OAAO,KAAK,uCAAuC,SAAS,SAAS;KACrE,GAAG,KAAK,KAAK,UAAU;MACnB,MAAM;MACN;MACA,SAAS,EAAE,OAAO;OAAE,SAAS,SAAS;OAC9D,MAAM,SAAS;MAAK,EAAE;KACF,CAAC,CAAC;KACF;IACJ;IACA,OAAO,MAAM,gDAAgD,EAAS,MAAM,CAAC;IAC7E,IAAI,iBAAiB,OACjB,OAAO,MAAM,eAAe,EAAE,QAAQ,MAAM,MAAM,CAAC;IAKvD,MAAM,eAAA,QAAA,IAAA,aAAwC,eACxC,iCACA,oBAAoB,KAAK;IAC/B,MAAM,gBAAgB;KAClB,MAAM;KACN;KACA,SAAS,EACL,OAAO;MACH,SAAS;MACT,MAAM;KACV,EACJ;IACJ;IACA,GAAG,KAAK,KAAK,UAAU,aAAa,CAAC;GACzC;EACJ,CAAC;CACL,CAAC;AACL"}
@@ -1,5 +1,5 @@
1
- import { RealtimeService } from "./services/realtimeService";
2
- import { PostgresBackendDriver } from "./PostgresBackendDriver";
1
+ import { RealtimeService } from "./services/realtimeService.js";
2
+ import { PostgresBackendDriver } from "./PostgresBackendDriver.js";
3
3
  import type { AuthAdapter } from "@rebasepro/types";
4
4
  import { Server } from "http";
5
5
  /** Minimal subset of RebaseAuthConfig used by the WebSocket layer. */
@@ -14,5 +14,32 @@ interface WsAuthConfig {
14
14
  */
15
15
  serviceKey?: string;
16
16
  }
17
+ /**
18
+ * WebSocket message types that require an admin session.
19
+ *
20
+ * Exported so the test can READ it. It used to be private, and the test that
21
+ * exists to make "a privileged verb added without a role check" impossible held
22
+ * a hand-typed copy of the same nine strings — so it agreed with itself, and
23
+ * `FETCH_APPLICATION_ROLES` was added to neither. That verb runs
24
+ * `SELECT DISTINCT unnest(roles)` over the users table through `executeSql`,
25
+ * which is the owner connection and not subject to RLS, so any authenticated
26
+ * non-admin could enumerate every role in the project — and any anonymous
27
+ * socket could, on a deployment with `requireAuth: false`.
28
+ *
29
+ * The list is no longer the whole guarantee. `PUBLIC_TYPES` below is its
30
+ * counterpart, and a test asserts that every `case` this file handles appears
31
+ * in exactly one of the two — so a verb added to neither fails rather than
32
+ * defaulting to reachable.
33
+ */
34
+ export declare const ADMIN_ONLY_TYPES: Set<string>;
35
+ /**
36
+ * Message types deliberately reachable by a non-admin session.
37
+ *
38
+ * Data operations, gated per row by RLS and per request by the same write
39
+ * checks the REST layer applies — not by this list. It exists so that "which
40
+ * bucket is this verb in" is a question with an answer for every verb, and
41
+ * adding one without answering it is a test failure.
42
+ */
43
+ export declare const PUBLIC_TYPES: Set<string>;
17
44
  export declare function createPostgresWebSocket(server: Server, realtimeService: RealtimeService, driver: PostgresBackendDriver, authConfig?: WsAuthConfig, authAdapter?: AuthAdapter): void;
18
45
  export {};