@rebasepro/server-postgres 0.16.1-canary.g2d1aec8 → 0.16.1-canary.g37d7b4f

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 (60) hide show
  1. package/dist/PostgresBackendDriver.d.ts +59 -5
  2. package/dist/{backup-service-BZoixhVl.js → backup-service-BtgHxfFm.js} +5 -4
  3. package/dist/{backup-service-BZoixhVl.js.map → backup-service-BtgHxfFm.js.map} +1 -1
  4. package/dist/cli-helpers.d.ts +41 -0
  5. package/dist/{ensure-collection-tables-jYsvOLZF.js → collection-index-DxJBvVTH.js} +466 -1915
  6. package/dist/collection-index-DxJBvVTH.js.map +1 -0
  7. package/dist/{connection-BuZ97wsr.js → connection-GOKU3Hu5.js} +34 -7
  8. package/dist/connection-GOKU3Hu5.js.map +1 -0
  9. package/dist/connection.d.ts +16 -0
  10. package/dist/{ensure-collection-policies-CVfVHS6o.js → ensure-collection-policies-DFpOl8SM.js} +4 -4
  11. package/dist/{ensure-collection-policies-CVfVHS6o.js.map → ensure-collection-policies-DFpOl8SM.js.map} +1 -1
  12. package/dist/ensure-collection-tables-DMjOkeRy.js +1952 -0
  13. package/dist/ensure-collection-tables-DMjOkeRy.js.map +1 -0
  14. package/dist/index.es.js +20 -7495
  15. package/dist/index.es.js.map +1 -1
  16. package/dist/{rls-bootstrap-sql-B5Sajku6.js → rls-bootstrap-sql-DNzaWd4C.js} +3 -3
  17. package/dist/{rls-bootstrap-sql-B5Sajku6.js.map → rls-bootstrap-sql-DNzaWd4C.js.map} +1 -1
  18. package/dist/{rls-enforcement-CsD7nZDn.js → rls-enforcement-CInuYj1-.js} +14 -4
  19. package/dist/rls-enforcement-CInuYj1-.js.map +1 -0
  20. package/dist/schema/collection-index.d.ts +182 -0
  21. package/dist/schema/generated-schema-staleness.d.ts +19 -0
  22. package/dist/schema/introspect-db-inference.d.ts +1 -1
  23. package/dist/schema/introspect-db-logic.d.ts +4 -4
  24. package/dist/schema/introspect-db-project.d.ts +2 -2
  25. package/dist/{src-BBFsDaeA.js → src-DiDgtX8P.js} +97 -1
  26. package/dist/src-DiDgtX8P.js.map +1 -0
  27. package/dist/websocket-CUnpSe8v.js +8188 -0
  28. package/dist/websocket-CUnpSe8v.js.map +1 -0
  29. package/dist/websocket.d.ts +27 -0
  30. package/package.json +7 -7
  31. package/src/PostgresBackendDriver.ts +150 -59
  32. package/src/backup/backup-service.ts +1 -1
  33. package/src/cli-helpers.ts +117 -2
  34. package/src/cli.ts +22 -0
  35. package/src/connection.ts +37 -3
  36. package/src/databasePoolManager.ts +5 -2
  37. package/src/schema/collection-index.ts +427 -0
  38. package/src/schema/ensure-collection-tables.ts +21 -0
  39. package/src/schema/generate-drizzle-schema-logic.ts +23 -11
  40. package/src/schema/generate-drizzle-schema.ts +13 -2
  41. package/src/schema/generate-postgres-ddl-logic.ts +18 -6
  42. package/src/schema/generate-postgres-ddl.ts +13 -2
  43. package/src/schema/generated-schema-staleness.ts +114 -1
  44. package/src/schema/introspect-db-inference.ts +1 -1
  45. package/src/schema/introspect-db-logic.ts +4 -4
  46. package/src/schema/introspect-db-project.ts +2 -2
  47. package/src/schema/introspect-db.ts +2 -2
  48. package/src/services/collection-helpers.ts +3 -2
  49. package/src/services/realtimeService.ts +17 -4
  50. package/src/websocket.ts +47 -3
  51. package/dist/connection-BuZ97wsr.js.map +0 -1
  52. package/dist/data_driver-ULAyJEi9.js +0 -193
  53. package/dist/data_driver-ULAyJEi9.js.map +0 -1
  54. package/dist/ensure-collection-tables-jYsvOLZF.js.map +0 -1
  55. package/dist/rls-enforcement-CsD7nZDn.js.map +0 -1
  56. package/dist/src-BBFsDaeA.js.map +0 -1
  57. package/dist/utils/table-classification.d.ts +0 -8
  58. package/dist/websocket-BVgDVO-V.js +0 -614
  59. package/dist/websocket-BVgDVO-V.js.map +0 -1
  60. package/src/utils/table-classification.ts +0 -16
@@ -44,7 +44,14 @@ export interface LegacyForeignKeyName {
44
44
  * which is not staleness — it is a table the generator has not been asked about.
45
45
  */
46
46
  function tableBlock(source: string, table: string): string {
47
- const start = source.indexOf(`pgTable("${table}"`);
47
+ // Both forms the generator emits. A collection with `schema: "rebase"` — the
48
+ // auth users collection, in every scaffold — is written as
49
+ // `rebaseSchema.table("users", …)`, so matching only `pgTable(` made this
50
+ // blind to every table outside `public`: the block came back empty, and an
51
+ // empty block reads as "a table the generator has not been asked about".
52
+ // The rename check therefore never inspected them.
53
+ const literal = table.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
54
+ const start = source.search(new RegExp(`(?:pgTable|\\.table)\\(\\s*["']${literal}["']`));
48
55
  if (start === -1) return "";
49
56
  // Generated files put every table in its own `export const`, so the next one
50
57
  // is the end of this block. No brace counting, nothing to get wrong.
@@ -169,3 +176,109 @@ export function describeLegacyForeignKeyNames(found: LegacyForeignKeyName[]): st
169
176
  .map(f => ` • ${f.table}.${f.legacy} → ${f.current} (${f.relation})`)
170
177
  .join("\n");
171
178
  }
179
+
180
+ // ── The other way a generated schema goes stale ──────────────────────────────
181
+ //
182
+ // The rename above is the subtle one: nothing the developer owns changed. The
183
+ // ordinary one is the opposite — a collection or a relation was added and the
184
+ // generator was not re-run, so the checked-in module simply does not describe
185
+ // part of the schema. It fails later and elsewhere: relation validation, or a
186
+ // query against a table the module has never heard of.
187
+ //
188
+ // Still not "is this byte-for-byte what the generator would emit now". This asks
189
+ // only about *names*, which is what the rest of the system reads out of the
190
+ // file, so reformatting the generator cannot make it red.
191
+
192
+ /** Something the collections derive that the generated schema does not declare. */
193
+ export interface MissingGeneratedName {
194
+ /** The table it belongs to, or is. */
195
+ table: string;
196
+ /** The column, when a column is what is missing. */
197
+ column?: string;
198
+ /** `<collection>` or `<collection>.<relation>`, for the message. */
199
+ source: string;
200
+ }
201
+
202
+ /**
203
+ * Tables and derived foreign-key columns the collections name and the generated
204
+ * schema does not.
205
+ *
206
+ * @param generatedSource contents of `backend/src/schema.generated.ts`
207
+ * @param collections the project's collections, as this release reads them
208
+ */
209
+ export function findMissingGeneratedNames(
210
+ generatedSource: string,
211
+ collections: CollectionConfig[]
212
+ ): MissingGeneratedName[] {
213
+ const missing: MissingGeneratedName[] = [];
214
+ const seen = new Set<string>();
215
+
216
+ const report = (table: string, source: string, column?: string): void => {
217
+ const key = `${table}.${column ?? ""}`;
218
+ if (seen.has(key)) return;
219
+ seen.add(key);
220
+ missing.push({ table, source, ...(column ? { column } : {}) });
221
+ };
222
+
223
+ const requireColumn = (table: string, column: string | undefined, source: string): void => {
224
+ if (!table || !column) return;
225
+ const block = tableBlock(generatedSource, table);
226
+ // A table that is absent is reported once, as a table. Listing each of
227
+ // its columns as separately missing would bury the one fact that
228
+ // explains all of them.
229
+ if (!block) return report(table, source);
230
+ if (!declaresColumn(block, column)) report(table, source, column);
231
+ };
232
+
233
+ for (const collection of relationalCollections(collections)) {
234
+ const sourceTable = getTableName(collection);
235
+ if (!tableBlock(generatedSource, sourceTable)) {
236
+ report(sourceTable, collection.slug);
237
+ continue;
238
+ }
239
+
240
+ for (const [name, relation] of Object.entries(resolveCollectionRelations(collection))) {
241
+ const at = `${collection.slug}.${name}`;
242
+
243
+ let target: CollectionConfig | undefined;
244
+ try {
245
+ target = relation.target?.();
246
+ } catch {
247
+ // Its own defect, reported at boot by `validate-relations`.
248
+ continue;
249
+ }
250
+
251
+ switch (relation.kind) {
252
+ case "belongsTo":
253
+ requireColumn(sourceTable, relation.localKey, at);
254
+ break;
255
+
256
+ case "hasOne":
257
+ case "hasMany":
258
+ if (target) requireColumn(getTableName(target), relation.foreignKeyOnTarget, at);
259
+ break;
260
+
261
+ case "manyToMany":
262
+ requireColumn(relation.through.table, relation.through.sourceColumn, at);
263
+ requireColumn(relation.through.table, relation.through.targetColumn, at);
264
+ break;
265
+
266
+ default:
267
+ // `via` joins are written by hand; there is no derived name
268
+ // to be missing.
269
+ break;
270
+ }
271
+ }
272
+ }
273
+
274
+ return missing;
275
+ }
276
+
277
+ /** One-line summary for a log or a CLI notice. */
278
+ export function describeMissingGeneratedNames(missing: MissingGeneratedName[]): string {
279
+ return missing
280
+ .map(m => (m.column
281
+ ? ` • ${m.table}.${m.column} is not declared (${m.source})`
282
+ : ` • table ${m.table} is not declared (${m.source})`))
283
+ .join("\n");
284
+ }
@@ -17,7 +17,7 @@ export function inferPropertyFromData(
17
17
  sampleValues: unknown[],
18
18
  isPk: boolean,
19
19
  /**
20
- * False when generating for a project without `@rebasepro/admin-types`, where
20
+ * False when generating for a project without `@rebasepro/cms-types`, where
21
21
  * `BaseProperty` declares no `admin` field and the block below would not
22
22
  * compile. The type-level inferences (`propType`, `url`, `storage`) are
23
23
  * unaffected — only the form-widget hints are dropped.
@@ -594,7 +594,7 @@ export interface GeneratedFile {
594
594
  *
595
595
  * There are two of them and they are not interchangeable:
596
596
  *
597
- * - `admin-types` — `@rebasepro/admin-types`. Its index side-effect-imports
597
+ * - `admin-types` — `@rebasepro/cms-types`. Its index side-effect-imports
598
598
  * `augment.ts`, so importing it is also what *declares* the `admin` block. Only a
599
599
  * project that depends on the package can resolve it.
600
600
  * - `common` — `@rebasepro/common`. Same key inference, no admin surface, no React
@@ -607,7 +607,7 @@ export interface GeneratedFile {
607
607
  * The last two emit **no admin block, on the collection or on any property**. That is
608
608
  * not a downgrade: `@rebasepro/types` declares no `admin` field at all, so the block
609
609
  * introspection used to emit was a type error in every headless project it was
610
- * written into. See `packages/admin-types/src/augment.ts`.
610
+ * written into. See `packages/cms-types/src/augment.ts`.
611
611
  */
612
612
  export type CollectionBuilder = "admin-types" | "common" | "annotation";
613
613
 
@@ -616,12 +616,12 @@ export type CollectionBuilder = "admin-types" | "common" | "annotation";
616
616
  *
617
617
  * Written as constants rather than inline in the import templates below because
618
618
  * `scripts/headless-guard/check-types.mjs` scans core sources for `from
619
- * "@rebasepro/admin-types"` and cannot tell a real import from one this module
619
+ * "@rebasepro/cms-types"` and cannot tell a real import from one this module
620
620
  * *writes*. It is right to be that blunt — the guard's whole value is that it
621
621
  * cannot be reasoned around — so the string simply never appears in that shape
622
622
  * here. Inlining them back into the templates re-breaks `check:types-headless`.
623
623
  */
624
- export const ADMIN_TYPES_PACKAGE = "@rebasepro/admin-types";
624
+ export const ADMIN_TYPES_PACKAGE = "@rebasepro/cms-types";
625
625
  export const COMMON_PACKAGE = "@rebasepro/common";
626
626
  export const TYPES_PACKAGE = "@rebasepro/types";
627
627
 
@@ -49,10 +49,10 @@ function declaredDependencies(manifestPath: string): Set<string> {
49
49
  * at the moment of generation. The alternatives are all proxies for it: `rebase.json`'s
50
50
  * `apps` block says a CMS scaffold declared an admin app, and a `frontend/` directory
51
51
  * says one was scaffolded, but neither is what the compiler consults, and either can be
52
- * true of a project whose `config` package does not depend on `@rebasepro/admin-types`.
52
+ * true of a project whose `config` package does not depend on `@rebasepro/cms-types`.
53
53
  *
54
54
  * Ambiguity resolves towards the admin panel: a project that declares both packages has
55
- * a panel, and `@rebasepro/admin-types` is the flavour that keeps the `admin` block.
55
+ * a panel, and `@rebasepro/cms-types` is the flavour that keeps the `admin` block.
56
56
  */
57
57
  export function detectCollectionBuilder(outDir: string): CollectionBuilder {
58
58
  let dir = path.resolve(outDir);
@@ -110,12 +110,12 @@ async function main() {
110
110
  const checkFacts = parseCheckConstraints(metadata.checks);
111
111
 
112
112
  // Which builder the generated files may import — read from the manifests
113
- // above `outDir`, because a project without `@rebasepro/admin-types` cannot
113
+ // above `outDir`, because a project without `@rebasepro/cms-types` cannot
114
114
  // resolve that import and has no `admin` block to write into either.
115
115
  const builder = detectCollectionBuilder(outDir);
116
116
  if (builder === "annotation") {
117
117
  outWarn(chalk.yellow(
118
- "⚠ Neither @rebasepro/admin-types nor @rebasepro/common is declared above " +
118
+ "⚠ Neither @rebasepro/cms-types nor @rebasepro/common is declared above " +
119
119
  `${outDir}.`
120
120
  ));
121
121
  outWarn(chalk.gray(
@@ -217,8 +217,9 @@ isUUID });
217
217
  }
218
218
  }
219
219
 
220
- // Default to 'id' if no primary keys are found and it exists in the schema
221
- // This maintains backwards compatibility
220
+ // A collection that declares no primary key gets the implicit `id` column,
221
+ // which is what the schema generators emit for it — so read it back the
222
+ // same way rather than reporting the table as keyless.
222
223
  if (keys.length === 0 && "id" in table) {
223
224
  const idCol = table["id" as keyof typeof table] as AnyPgColumn;
224
225
  const idMeta = getColumnMeta(idCol);
@@ -462,6 +462,23 @@ export class RealtimeService extends EventEmitter implements RealtimeProvider {
462
462
  }
463
463
  }
464
464
 
465
+ // The shared rows go before the announcement, not after it. Every
466
+ // `removePresence` below publishes a departure — to local members and
467
+ // over the bus — while `sendPresenceState` answers a *newly arriving*
468
+ // subscriber from this table. Announcing first leaves a window where the
469
+ // table still lists someone who has left: a client hydrating inside it is
470
+ // handed the ghost, and the diff that would have corrected it was
471
+ // broadcast before that client existed, so it holds the ghost until the
472
+ // TTL sweep rather than for the length of one statement.
473
+ //
474
+ // One statement for every channel the client was in, rather than one per
475
+ // channel below — a disconnect is the common case, not a rare one. The
476
+ // subscription and timer cleanup above stays synchronous on purpose: it
477
+ // is what leaks if the database is slow, and it owes nothing to the
478
+ // shared table. With no bus configured this is a no-op that never awaits
479
+ // a query.
480
+ await this.presenceStoreOp(() => this.presenceStore!.removeClient(clientId), "client removal");
481
+
465
482
  // Remove from all broadcast channels
466
483
  for (const [channel, members] of this.channels.entries()) {
467
484
  if (members.has(clientId)) {
@@ -475,10 +492,6 @@ export class RealtimeService extends EventEmitter implements RealtimeProvider {
475
492
  for (const [channel] of this.presence) {
476
493
  this.removePresence(clientId, channel, { skipStore: true });
477
494
  }
478
-
479
- // One statement for every channel the client was in, rather than one
480
- // per channel above — a disconnect is the common case, not a rare one.
481
- void this.presenceStoreOp(() => this.presenceStore!.removeClient(clientId), "client removal");
482
495
  }
483
496
 
484
497
  private async handleMessage(clientId: string, message: WebSocketMessage, authContext?: SubscriptionAuthContext) {
package/src/websocket.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { RealtimeService } from "./services/realtimeService";
2
- import { PostgresBackendDriver } from "./PostgresBackendDriver";
2
+ import { PostgresBackendDriver, effectiveSqlRole } from "./PostgresBackendDriver";
3
3
  import type { DataDriver, DeleteProps, FetchCollectionProps, FetchOneProps, SaveProps, TableMetadata, BranchInfo, AuthAdapter } from "@rebasepro/types";
4
4
  import { ANONYMOUS_USER_ID, isSQLAdmin, isSchemaAdmin, resolveClientListLimit, ListLimitError } from "@rebasepro/types";
5
5
  import type { User } from "@rebasepro/types";
@@ -77,11 +77,28 @@ const CHANNEL_MESSAGE_TYPES = new Set([
77
77
  "channel_history"
78
78
  ]);
79
79
 
80
- /** Admin-only WebSocket message types */
81
- const ADMIN_ONLY_TYPES = new Set([
80
+ /**
81
+ * WebSocket message types that require an admin session.
82
+ *
83
+ * Exported so the test can READ it. It used to be private, and the test that
84
+ * exists to make "a privileged verb added without a role check" impossible held
85
+ * a hand-typed copy of the same nine strings — so it agreed with itself, and
86
+ * `FETCH_APPLICATION_ROLES` was added to neither. That verb runs
87
+ * `SELECT DISTINCT unnest(roles)` over the users table through `executeSql`,
88
+ * which is the owner connection and not subject to RLS, so any authenticated
89
+ * non-admin could enumerate every role in the project — and any anonymous
90
+ * socket could, on a deployment with `requireAuth: false`.
91
+ *
92
+ * The list is no longer the whole guarantee. `PUBLIC_TYPES` below is its
93
+ * counterpart, and a test asserts that every `case` this file handles appears
94
+ * in exactly one of the two — so a verb added to neither fails rather than
95
+ * defaulting to reachable.
96
+ */
97
+ export const ADMIN_ONLY_TYPES = new Set([
82
98
  "EXECUTE_SQL",
83
99
  "FETCH_DATABASES",
84
100
  "FETCH_ROLES",
101
+ "FETCH_APPLICATION_ROLES",
85
102
  "FETCH_UNMAPPED_TABLES",
86
103
  "FETCH_TABLE_METADATA",
87
104
  "FETCH_CURRENT_DATABASE",
@@ -90,6 +107,23 @@ const ADMIN_ONLY_TYPES = new Set([
90
107
  "LIST_BRANCHES"
91
108
  ]);
92
109
 
110
+ /**
111
+ * Message types deliberately reachable by a non-admin session.
112
+ *
113
+ * Data operations, gated per row by RLS and per request by the same write
114
+ * checks the REST layer applies — not by this list. It exists so that "which
115
+ * bucket is this verb in" is a question with an answer for every verb, and
116
+ * adding one without answering it is a test failure.
117
+ */
118
+ export const PUBLIC_TYPES = new Set([
119
+ "FETCH_COLLECTION",
120
+ "FETCH_ONE",
121
+ "COUNT",
122
+ "SAVE",
123
+ "DELETE",
124
+ "CHECK_UNIQUE_FIELD"
125
+ ]);
126
+
93
127
  /**
94
128
  * Recursively extract the deepest error message from an error's cause chain (e.g., Drizzle wrapping a PG error).
95
129
  */
@@ -533,6 +567,16 @@ colors: true }));
533
567
  sql: typeof sql === "string" ? sql.substring(0, 500) : String(sql),
534
568
  database: options?.database,
535
569
  role: options?.role,
570
+ // The role the statement asked for is above;
571
+ // this is the one it ran as. They used to be
572
+ // assumed identical, so an execution that fell
573
+ // back to the owner was audited under the role
574
+ // it had failed to assume. That fallback is now
575
+ // an error everywhere except the documented
576
+ // `DISABLE_DB_ROLE_SWITCHING` opt-out — which is
577
+ // precisely the case this line still has to
578
+ // report honestly.
579
+ effectiveRole: effectiveSqlRole(options?.role),
536
580
  paramCount: Array.isArray(options?.params) ? options.params.length : 0,
537
581
  resultRows: Array.isArray(result) ? result.length : "unknown",
538
582
  uid: auditSession?.user?.uid ?? "unknown",
@@ -1 +0,0 @@
1
- {"version":3,"file":"connection-BuZ97wsr.js","names":[],"sources":["../src/connection.ts"],"sourcesContent":["import { Pool, PoolConfig } from \"pg\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { logger } from \"@rebasepro/server\";\n\n/**\n * Configuration for the Postgres connection pool.\n *\n * Sensible defaults are provided for production Cloud Run / single-instance\n * deployments. Override via environment variables or explicit config.\n */\nexport interface PostgresPoolConfig {\n /** Maximum number of connections in the pool (default: 20) */\n max?: number;\n /** Close idle connections after this many ms (default: 30 000) */\n idleTimeoutMillis?: number;\n /** Abort connection attempts after this many ms (default: 10 000) */\n connectionTimeoutMillis?: number;\n /** Per-query timeout in ms (default: 30 000) */\n queryTimeout?: number;\n /** Per-statement timeout in ms (default: 30 000) */\n statementTimeout?: number;\n /** Enable TCP keep-alive (default: true) */\n keepAlive?: boolean;\n /**\n * `search_path` pinned on every connection (default: `\"public\"`).\n *\n * Pass `false` to send no `search_path` at all and inherit whatever the\n * server/role defaults to. See {@link pinSearchPath} for why the default\n * is not \"inherit\".\n */\n searchPath?: string | false;\n}\n\nconst DEFAULT_POOL: Required<PostgresPoolConfig> = {\n max: 20,\n searchPath: \"public\",\n idleTimeoutMillis: 30_000,\n connectionTimeoutMillis: 10_000,\n // The client-side read timeout MUST be comfortably above the server-side\n // statement_timeout. When the client timer fires first, node-postgres\n // abandons the in-flight statement but keeps the connection — inside a\n // transaction that leaves the tx open (and any pending ROLLBACK is\n // spliced out of the client queue before it ever reaches the wire), so\n // the pooled connection is returned still in-transaction with its RLS\n // GUCs set. The server abort (SQLSTATE 57014) is the clean path; the\n // client timeout is only a backstop for a dead network.\n queryTimeout: 60_000,\n statementTimeout: 30_000,\n keepAlive: true\n};\n\n/** ReadyForQuery status byte: `I` idle, `T` in transaction, `E` failed transaction. */\nconst TX_IDLE = \"I\";\n\n/**\n * Pin `search_path` into a connection string, so unqualified SQL resolves to a\n * schema this framework chose rather than to one Postgres inferred.\n *\n * Postgres defaults `search_path` to `\"$user\", public`: the *first* candidate\n * is a schema named after the connecting role. Rebase creates a schema called\n * `rebase` (auth, history, api keys), and every template, compose file and\n * deployment doc names the database role `rebase` too — so `$user` resolves to\n * a schema that exists, and every unqualified statement lands there instead of\n * in `public`. The generated Drizzle schema emits bare `pgTable(\"posts\", …)`\n * for any collection without an explicit `schema`, which makes the *runtime's*\n * own reads and writes unqualified; a developer's raw `rebase.sql(...)`, the\n * Studio SQL editor and any hand-written migration are unqualified too. The\n * result is collection tables created in, and served from, `rebase`.\n *\n * Drizzle cannot express the fix on its side: `pgSchema(\"public\")` throws by\n * design (\"just use pgTable() instead\"), so there is no way to emit a\n * public-qualified table from the generator. The pin has to live on the\n * connection.\n *\n * Precedence is deliberate and verified against node-postgres: `options` in\n * the connection string wins over the `options` field passed to `Pool`, so\n * rewriting the URL — rather than setting the field — is what makes this\n * authoritative. Two escape hatches survive it:\n *\n * - an `options` that already mentions `search_path` is left untouched, so a\n * deployment that deliberately pins something else keeps it;\n * - `searchPath: false` (or an unparseable, non-URL connection string) sends\n * nothing and inherits the server default.\n *\n * Anything else in `options` (a `statement_timeout`, say) is preserved and the\n * `search_path` flag is appended to it.\n */\nexport function pinSearchPath(connectionString: string, searchPath: string | false = \"public\"): string {\n if (searchPath === false) return connectionString;\n\n let url: URL;\n try {\n url = new URL(connectionString);\n } catch {\n // Key/value DSNs and anything else we cannot parse are returned as\n // given: a connection that works unpinned beats one we corrupted.\n return connectionString;\n }\n if (url.protocol !== \"postgres:\" && url.protocol !== \"postgresql:\") return connectionString;\n\n const existing = url.searchParams.get(\"options\");\n if (existing && /(^|\\s)-c\\s*search_path\\s*=/.test(existing)) return connectionString;\n\n const flag = `-c search_path=${searchPath}`;\n url.searchParams.set(\"options\", existing ? `${existing} ${flag}` : flag);\n // Re-serialize by hand. `URLSearchParams` writes a space as `+`, which\n // node-postgres happens to decode but libpq does not — and this same string\n // is handed to `pg_dump`/`psql` for backups. Percent-encoding is the form\n // both agree on, and is what the scaffolded `.env` already ships.\n url.search = Array.from(url.searchParams.entries())\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join(\"&\");\n return url.toString();\n}\n\n/**\n * Destroy pool clients that are released while still inside a transaction.\n *\n * pg-pool returns a client to the idle list whenever `release()` is called\n * without an error — even if the connection is still mid-transaction (status\n * `T`/`E`). That happens in practice: drizzle's pool transaction releases in\n * a `finally` after attempting ROLLBACK, and if the ROLLBACK itself fails\n * (e.g. it was queued behind a statement that hit the client-side\n * query_timeout), the client goes back dirty. The next checkout then runs\n * its statements inside the zombie transaction — with the previous request's\n * `app.*` RLS GUCs still applied, which turns unrelated queries into\n * RLS-scoped ones (observed in production as registration failing with\n * SQLSTATE 42501 under a leaked anonymous context).\n *\n * pg-pool emits `release` before it consults its private `_expired` set, so\n * marking the client expired here makes `_release()` destroy it instead of\n * pooling it. Both `client._txStatus` (pg ≥ 8.16) and `pool._expired` are\n * private APIs — feature-detect and fall back to loud logging so an upstream\n * change degrades to observability, never to silent corruption.\n */\nexport function guardPoolAgainstDirtyRelease(pool: Pool, label: string): void {\n pool.on(\"release\", (err: Error | undefined, client: unknown) => {\n if (err) return; // errored clients are already destroyed by pg-pool\n const txStatus = (client as { _txStatus?: string | null })?._txStatus;\n if (typeof txStatus !== \"string\" || txStatus === TX_IDLE) return;\n\n // pg-pool keeps expired clients in a WeakSet (a plain object works too\n // if upstream ever changes it — duck-type on add/has).\n const expired = (pool as unknown as { _expired?: { add(c: object): unknown; has(c: object): boolean } })._expired;\n if (expired && typeof expired.add === \"function\" && typeof expired.has === \"function\" && client && typeof client === \"object\") {\n expired.add(client);\n logger.error(\n `[${label}] Client released back to the pool while still in a transaction ` +\n `(status '${txStatus}') — destroying it so the open transaction and its ` +\n `session state (RLS GUCs) cannot leak into the next request.`\n );\n } else {\n logger.error(\n `[${label}] Client released mid-transaction (status '${txStatus}') but the ` +\n `pool's internal expiry set is unavailable (pg-pool internals changed?). ` +\n `The connection may leak its open transaction into subsequent requests.`\n );\n }\n });\n}\n\n/**\n * Create a Drizzle-backed Postgres connection with a production-grade\n * connection pool.\n *\n * @param connectionString Postgres connection URL\n * @param schema Optional Drizzle schema for the relational API\n * @param poolConfig Optional pool tuning (merged over defaults)\n *\n * @returns `{ db, pool, connectionString }` — the `pool` is exposed so\n * callers can register shutdown hooks (`pool.end()`) or monitor\n * pool metrics.\n */\nexport function createPostgresDatabaseConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = { ...DEFAULT_POOL,\n...poolConfig };\n connectionString = pinSearchPath(connectionString, opts.searchPath);\n\n const pgPoolConfig: PoolConfig = {\n connectionString,\n max: opts.max,\n idleTimeoutMillis: opts.idleTimeoutMillis,\n connectionTimeoutMillis: opts.connectionTimeoutMillis,\n query_timeout: opts.queryTimeout,\n statement_timeout: opts.statementTimeout,\n keepAlive: opts.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n\n const pool = new Pool(pgPoolConfig);\n\n // ── Pool event logging ────────────────────────────────────────────────\n // Uses console.* because the structured logger lives in server\n // (a separate package). The caller can replace these with the structured\n // logger if desired via pool.on() after creation.\n pool.on(\"error\", (err) => {\n logger.error(\"[pg-pool] Unexpected pool error\", { detail: err.message });\n if (err.message.includes(\"ETIMEDOUT\")) {\n logger.warn(\"[pg-pool] Connection timeout detected — pool will auto-retry\");\n }\n });\n guardPoolAgainstDirtyRelease(pool, \"pg-pool\");\n\n // Create drizzle instance — pass schema when available to enable db.query relational API\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Create a direct (non-pooled) connection for operations that require\n * session-level features incompatible with PgBouncer transaction mode,\n * such as LISTEN/NOTIFY, prepared statements, or advisory locks.\n *\n * Uses a smaller pool since this is only for specific use cases.\n */\nexport function createDirectDatabaseConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = {\n ...DEFAULT_POOL,\n max: 5,\n ...poolConfig\n };\n connectionString = pinSearchPath(connectionString, opts.searchPath);\n\n const pgPoolConfig: PoolConfig = {\n connectionString,\n max: opts.max,\n idleTimeoutMillis: opts.idleTimeoutMillis,\n connectionTimeoutMillis: opts.connectionTimeoutMillis,\n query_timeout: opts.queryTimeout,\n statement_timeout: opts.statementTimeout,\n keepAlive: opts.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n\n const pool = new Pool(pgPoolConfig);\n\n pool.on(\"error\", (err) => {\n logger.error(\"[pg-direct-pool] Unexpected pool error\", { detail: err.message });\n });\n guardPoolAgainstDirtyRelease(pool, \"pg-direct-pool\");\n\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Create a read-only connection for routing read queries to replicas.\n * Uses a moderate pool size since reads are distributed across replicas.\n */\nexport function createReadReplicaConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = {\n ...DEFAULT_POOL,\n max: 10,\n ...poolConfig\n };\n connectionString = pinSearchPath(connectionString, opts.searchPath);\n\n const pgPoolConfig: PoolConfig = {\n connectionString,\n max: opts.max,\n idleTimeoutMillis: opts.idleTimeoutMillis,\n connectionTimeoutMillis: opts.connectionTimeoutMillis,\n query_timeout: opts.queryTimeout,\n statement_timeout: opts.statementTimeout,\n keepAlive: opts.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n\n const pool = new Pool(pgPoolConfig);\n\n pool.on(\"error\", (err) => {\n logger.error(\"[pg-replica-pool] Unexpected pool error\", { detail: err.message });\n });\n guardPoolAgainstDirtyRelease(pool, \"pg-replica-pool\");\n\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAM,eAA6C;CAC/C,KAAK;CACL,YAAY;CACZ,mBAAmB;CACnB,yBAAyB;CASzB,cAAc;CACd,kBAAkB;CAClB,WAAW;AACf;;AAGA,IAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmChB,SAAgB,cAAc,kBAA0B,aAA6B,UAAkB;CACnG,IAAI,eAAe,OAAO,OAAO;CAEjC,IAAI;CACJ,IAAI;EACA,MAAM,IAAI,IAAI,gBAAgB;CAClC,QAAQ;EAGJ,OAAO;CACX;CACA,IAAI,IAAI,aAAa,eAAe,IAAI,aAAa,eAAe,OAAO;CAE3E,MAAM,WAAW,IAAI,aAAa,IAAI,SAAS;CAC/C,IAAI,YAAY,6BAA6B,KAAK,QAAQ,GAAG,OAAO;CAEpE,MAAM,OAAO,kBAAkB;CAC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Require as __createRequire } from "module";
2
- import "process";
3
- __createRequire(import.meta.url);
4
- //#region ../types/src/errors.ts
5
- /**
6
- * The single error type thrown across the entire Rebase client surface —
7
- * HTTP data/control-plane calls, realtime/WebSocket operations, and
8
- * client-side logic errors (e.g. an unknown collection accessor). A `catch`
9
- * block only ever needs to check for this one class:
10
- *
11
- * ```ts
12
- * import { RebaseApiError } from "@rebasepro/client"; // re-exported
13
- *
14
- * try {
15
- * await client.data.products.update(id, { price: 9 });
16
- * } catch (e) {
17
- * if (e instanceof RebaseApiError) {
18
- * if (e.status === 404) { ... } // HTTP failures carry a status
19
- * console.error(e.code, e.details);
20
- * }
21
- * }
22
- * ```
23
- *
24
- * `status` is present for HTTP failures and `undefined` otherwise, so its
25
- * presence distinguishes transport-level errors from realtime/logic errors.
26
- *
27
- * @group Errors
28
- */
29
- var RebaseApiError = class extends Error {
30
- /** HTTP status code, or `undefined` for non-HTTP errors. */
31
- status;
32
- /** Stable machine-readable error code, when the server supplied one. See {@link RebaseErrorCode}. */
33
- code;
34
- /** Structured error payload from the server, when present. */
35
- details;
36
- constructor(message, init = {}) {
37
- super(message);
38
- this.name = "RebaseApiError";
39
- this.status = init.status;
40
- this.code = init.code;
41
- this.details = init.details;
42
- if (init.cause !== void 0) this.cause = init.cause;
43
- }
44
- };
45
- //#endregion
46
- //#region ../types/src/types/policy.ts
47
- /**
48
- * The id a request without a logged-in user reports as `rebase.uid()`.
49
- *
50
- * A user-context request always sets `app.uid`: blank would read back as
51
- * `NULL`, and `NULL` is how the trusted server context is recognised, so an
52
- * anonymous visitor would be promoted to server privileges. The driver
53
- * therefore substitutes this sentinel at the single chokepoint where the GUC
54
- * is set.
55
- *
56
- * The consequence for policy authors is that **`rebase.uid() IS NOT NULL` is a
57
- * tautology on the user path** — it is true for anonymous visitors too. Use
58
- * {@link policy.authenticated} to mean "signed in", and
59
- * {@link policy.serverContext} to mean "the trusted server context". Do not
60
- * hand-write the comparison: see {@link ANONYMOUS_USER_IDS} for why one
61
- * literal is not enough.
62
- *
63
- * @group Models
64
- */
65
- var ANONYMOUS_USER_ID = "anonymous";
66
- /**
67
- * Every uid that has ever meant "nobody is signed in" — newest first.
68
- *
69
- * There are two because there were two. The types, the policy compiler, the
70
- * JavaScript evaluator and the linter were all built on
71
- * {@link ANONYMOUS_USER_ID}, while the request path scoped unauthenticated
72
- * callers as `'anon'` — so `policy.authenticated()`, which compiled to
73
- * `rebase.uid() <> 'anonymous'`, was *true* for an anonymous visitor. The
74
- * sanctioned way to write "signed in" granted to everyone, and the linter
75
- * flagged the spelling that actually worked as a foreign convention.
76
- *
77
- * The request path now reports {@link ANONYMOUS_USER_ID}. `'anon'` stays here
78
- * because policies outlive the server that generated them: a database still
79
- * holding policies from before the fix, or a project whose server has not been
80
- * upgraded yet, must not become a grant in either direction. Compile against
81
- * this list, not against a single literal.
82
- *
83
- * No real user id is ever one of these, so a match is always "not signed in".
84
- *
85
- * @group Models
86
- */
87
- var ANONYMOUS_USER_IDS = [ANONYMOUS_USER_ID, "anon"];
88
- /** @group Models */
89
- var policy = {
90
- true: () => ({ kind: "true" }),
91
- false: () => ({ kind: "false" }),
92
- and: (...operands) => ({
93
- kind: "and",
94
- operands
95
- }),
96
- or: (...operands) => ({
97
- kind: "or",
98
- operands
99
- }),
100
- not: (operand) => ({
101
- kind: "not",
102
- operand
103
- }),
104
- compare: (left, op, right) => ({
105
- kind: "compare",
106
- op,
107
- left,
108
- right
109
- }),
110
- rolesOverlap: (roles) => ({
111
- kind: "rolesOverlap",
112
- roles
113
- }),
114
- rolesContain: (roles) => ({
115
- kind: "rolesContain",
116
- roles
117
- }),
118
- authenticated: () => ({ kind: "authenticated" }),
119
- serverContext: () => ({ kind: "serverContext" }),
120
- existsIn: (args) => ({
121
- kind: "existsIn",
122
- collection: args.collection,
123
- where: args.where
124
- }),
125
- raw: (sql) => ({
126
- kind: "raw",
127
- sql
128
- }),
129
- field: (name) => ({
130
- kind: "field",
131
- name
132
- }),
133
- outerField: (name) => ({
134
- kind: "outerField",
135
- name
136
- }),
137
- literal: (value) => ({
138
- kind: "literal",
139
- value
140
- }),
141
- authUid: () => ({ kind: "authUid" }),
142
- authRoles: () => ({ kind: "authRoles" })
143
- };
144
- /**
145
- * Thrown by {@link resolveClientListLimit} for a `limit` the platform will not
146
- * serve. Carries an HTTP status so an ingress that speaks HTTP can forward it
147
- * verbatim, and `maxLimit` so one can be built without re-deriving the ceiling.
148
- *
149
- * @group Errors
150
- */
151
- var ListLimitError = class ListLimitError extends RebaseApiError {
152
- /** The ceiling that was exceeded — what the caller should page by instead. */
153
- maxLimit;
154
- constructor(message, maxLimit) {
155
- super(message, {
156
- status: 400,
157
- code: "INVALID_LIMIT"
158
- });
159
- this.name = "ListLimitError";
160
- this.maxLimit = maxLimit;
161
- Object.setPrototypeOf(this, ListLimitError.prototype);
162
- }
163
- };
164
- /**
165
- * Resolve a client-supplied list `limit` into a safe, always-defined value.
166
- *
167
- * - An absent / blank limit falls back to the mode default:
168
- * `vectorDefaultLimit` for a vector search, otherwise `defaultLimit`.
169
- * - A limit that is present must be an integer in `[1, maxLimit]`. Anything
170
- * else — `0`, a negative, `1.5`, `abc`, `100000000` — throws
171
- * {@link ListLimitError} rather than being coerced into range, because every
172
- * coercion answers a question the caller did not ask with a page it cannot
173
- * tell apart from the whole collection.
174
- *
175
- * The return is never `undefined` — no ingress that routes its client limit
176
- * through this can produce an unbounded read.
177
- *
178
- * @throws {ListLimitError} when a present `limit` is not an integer in range.
179
- */
180
- function resolveClientListLimit(rawLimit, opts = {}) {
181
- const maxLimit = opts.maxLimit ?? 1e3;
182
- if (rawLimit != null && String(rawLimit).trim() !== "") {
183
- const parsed = typeof rawLimit === "number" ? rawLimit : Number(String(rawLimit).trim());
184
- if (!Number.isInteger(parsed) || parsed < 1) throw new ListLimitError(`Invalid \`limit\`: ${String(rawLimit)}. Expected a whole number between 1 and ${maxLimit}.`, maxLimit);
185
- if (parsed > maxLimit) throw new ListLimitError(`\`limit\` ${parsed} is above the maximum of ${maxLimit}. Ask for at most ${maxLimit} rows per read and page through the rest with \`offset\` — answering with a smaller page would be indistinguishable from there being no more rows.`, maxLimit);
186
- return parsed;
187
- }
188
- return opts.vectorSearch ? opts.vectorDefaultLimit ?? 10 : opts.defaultLimit ?? 50;
189
- }
190
- //#endregion
191
- export { policy as a, ANONYMOUS_USER_IDS as i, resolveClientListLimit as n, ANONYMOUS_USER_ID as r, ListLimitError as t };
192
-
193
- //# sourceMappingURL=data_driver-ULAyJEi9.js.map