@rebasepro/server-postgres 0.28.2 → 0.29.0-canary.g0e3a0e7

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 (40) hide show
  1. package/dist/PostgresBackendDriver.d.ts +69 -1
  2. package/dist/PostgresBootstrapper.d.ts +34 -1
  3. package/dist/{cli-console-C0FYkICX.js → cli-console-CJLtH58M.js} +3 -3
  4. package/dist/{cli-console-C0FYkICX.js.map → cli-console-CJLtH58M.js.map} +1 -1
  5. package/dist/cli.js +12 -12
  6. package/dist/{connection-czvI7TZL.js → connection-CcYqncW5.js} +113 -36
  7. package/dist/connection-CcYqncW5.js.map +1 -0
  8. package/dist/connection.d.ts +57 -0
  9. package/dist/database-health.d.ts +23 -0
  10. package/dist/{databasePoolManager-BjoVvuAq.js → databasePoolManager-XmhMczz0.js} +2 -2
  11. package/dist/{databasePoolManager-BjoVvuAq.js.map → databasePoolManager-XmhMczz0.js.map} +1 -1
  12. package/dist/{deferred-index-build-BcJ_oulu.js → deferred-index-build-BwH6k1Og.js} +30 -1
  13. package/dist/{deferred-index-build-BcJ_oulu.js.map → deferred-index-build-BwH6k1Og.js.map} +1 -1
  14. package/dist/{ensure-collection-policies-BNwSQfVx.js → ensure-collection-policies-f0LIwiwp.js} +3 -3
  15. package/dist/{ensure-collection-policies-BNwSQfVx.js.map → ensure-collection-policies-f0LIwiwp.js.map} +1 -1
  16. package/dist/{ensure-collection-tables-CSbgkTBx.js → ensure-collection-tables-DvaCEy6X.js} +4 -4
  17. package/dist/{ensure-collection-tables-CSbgkTBx.js.map → ensure-collection-tables-DvaCEy6X.js.map} +1 -1
  18. package/dist/{enum-labels-kept-BCgFGAbJ.js → enum-labels-kept-DAbJ_IIl.js} +2 -2
  19. package/dist/{enum-labels-kept-BCgFGAbJ.js.map → enum-labels-kept-DAbJ_IIl.js.map} +1 -1
  20. package/dist/index.d.ts +5 -2
  21. package/dist/index.es.js +4 -4
  22. package/dist/{migrate-policy-stamps-B-8vTSIm.js → migrate-policy-stamps-CdljD_y1.js} +4 -4
  23. package/dist/{migrate-policy-stamps-B-8vTSIm.js.map → migrate-policy-stamps-CdljD_y1.js.map} +1 -1
  24. package/dist/{open-rebase-D9n8idex.js → open-rebase-DvmKIu7q.js} +591 -37
  25. package/dist/open-rebase-DvmKIu7q.js.map +1 -0
  26. package/dist/pooled-database.d.ts +38 -0
  27. package/dist/{push-index-prebuild-DR3P4yOw.js → push-index-prebuild-C6wKdjYV.js} +3 -3
  28. package/dist/{push-index-prebuild-DR3P4yOw.js.map → push-index-prebuild-C6wKdjYV.js.map} +1 -1
  29. package/dist/{push-legacy-renames-BIxBmVLl.js → push-legacy-renames-BFF72tHG.js} +3 -3
  30. package/dist/{push-legacy-renames-BIxBmVLl.js.map → push-legacy-renames-BFF72tHG.js.map} +1 -1
  31. package/dist/{push-policy-plan-BHsasXa7.js → push-policy-plan-lOTPeQ1u.js} +2 -2
  32. package/dist/{push-policy-plan-BHsasXa7.js.map → push-policy-plan-lOTPeQ1u.js.map} +1 -1
  33. package/dist/read-routing.d.ts +139 -0
  34. package/dist/schema/deferred-index-build.d.ts +9 -0
  35. package/dist/schema/introspect-db.js +1 -1
  36. package/dist/{websocket-D4wrzF3b.js → websocket-CCJnghvG.js} +2 -2
  37. package/dist/{websocket-D4wrzF3b.js.map → websocket-CCJnghvG.js.map} +1 -1
  38. package/package.json +7 -7
  39. package/dist/connection-czvI7TZL.js.map +0 -1
  40. package/dist/open-rebase-D9n8idex.js.map +0 -1
@@ -3,9 +3,10 @@ import { BranchService } from "./services/BranchService.js";
3
3
  import { RealtimeService, type SubscriptionAuthContext } from "./services/realtimeService.js";
4
4
  import { DatabasePoolManager } from "./databasePoolManager.js";
5
5
  import { DrizzleClient } from "./interfaces.js";
6
- import { DatabaseAdmin, SQLAdmin, DataDriver, DeleteProps, CollectionConfig, FetchCollectionProps, FetchOneProps, ListenCollectionProps, ListenOneProps, RebaseCallContext, RebaseServerClient, RebaseSdkData, RestFetchService, BatchWriteProps, SaveManyProps, SaveProps, SqlCursor, SqlScriptResult, UpdateManyProps, UpdateRelationPivotProps, DeleteManyProps, TableMetadata, User } from "@rebasepro/types";
6
+ import { DatabaseAdmin, DatabaseHealthSample, DatabasePoolStats, SQLAdmin, DataDriver, DeleteProps, CollectionConfig, FetchCollectionProps, FetchOneProps, ListenCollectionProps, ListenOneProps, RebaseCallContext, RebaseServerClient, RebaseSdkData, RestFetchService, BatchWriteProps, SaveManyProps, SaveProps, SqlCursor, SqlScriptResult, UpdateManyProps, UpdateRelationPivotProps, DeleteManyProps, TableMetadata, User } from "@rebasepro/types";
7
7
  import { PostgresCollectionRegistry } from "./collections/PostgresCollectionRegistry.js";
8
8
  import { HistoryService } from "./history/HistoryService.js";
9
+ import { type ReadRouter } from "./read-routing.js";
9
10
  /**
10
11
  * Has an operator opted out of database role switching entirely?
11
12
  *
@@ -117,6 +118,24 @@ export declare class PostgresBackendDriver implements DataDriver {
117
118
  * listening on it hears none of its own notifications.
118
119
  */
119
120
  listenConnectionString?: string;
121
+ /**
122
+ * A handle on this source's direct URL for the work that needs a session
123
+ * of its own — the Studio SQL console's runs, cursors and cancels — set by
124
+ * the bootstrapper when the pool reaches the database through a
125
+ * transaction-mode pooler (`DATABASE_POOLED=true`). There, `SET ROLE` for a
126
+ * session, a cursor held across reads and `pg_cancel_backend` of "this
127
+ * run's backend" mean nothing: each transaction may land on another server
128
+ * connection. Unset, the pool itself is direct and serves them.
129
+ */
130
+ sessionDb?: DrizzleClient;
131
+ /**
132
+ * Where authenticated reads may go instead of the primary: this source's
133
+ * read replica, with its lag guard and read-your-writes pins. Set by the
134
+ * bootstrapper when `DATABASE_READ_URL` names another server. Read by
135
+ * {@link AuthenticatedPostgresBackendDriver}; this driver's own reads stay
136
+ * on the primary.
137
+ */
138
+ readRouter?: ReadRouter<DrizzleClient>;
120
139
  /**
121
140
  * When true, realtime notifications are deferred until after the
122
141
  * wrapping transaction commits. Set by `withAuth` → `withTransaction`.
@@ -202,6 +221,19 @@ export declare class PostgresBackendDriver implements DataDriver {
202
221
  */
203
222
  private applyAfterReadToRow;
204
223
  private static hasAfterRead;
224
+ /**
225
+ * Refuse an aggregate that would read what `afterRead` hides.
226
+ *
227
+ * An aggregate reads the stored columns and never passes through the
228
+ * callbacks, so on a collection whose rows one rewrites, `max(email)` or
229
+ * `groupBy=salary` hands back the value the mask exists to withhold, one
230
+ * bucket at a time. What a callback does to a row cannot be known from
231
+ * here, so the rule is closed: on such a collection only `count()` with no
232
+ * `groupBy` is served — the number `GET /count` already gives — and any
233
+ * other aggregate is refused, whichever tier (global, collection or
234
+ * property) the callback sits on.
235
+ */
236
+ private assertAggregateUnmasked;
205
237
  /**
206
238
  * Apply afterRead to REST/SDK read results.
207
239
  *
@@ -457,6 +489,20 @@ export declare class PostgresBackendDriver implements DataDriver {
457
489
  */
458
490
  appDatabaseName(): Promise<string>;
459
491
  private getTargetDb;
492
+ /**
493
+ * {@link getTargetDb} for work that needs one session from start to end:
494
+ * the app database is reached through {@link sessionDb} when there is one.
495
+ * Other databases come from the pool manager, whose URL is already the
496
+ * direct one (`DATABASE_DIRECT_URL` before `DATABASE_URL`).
497
+ */
498
+ private getSessionTargetDb;
499
+ /** `SQLAdmin.poolStats`: the pools this driver opened beside the server's. */
500
+ poolStats(): DatabasePoolStats[];
501
+ /**
502
+ * `SQLAdmin.sampleHealth`: the server behind the pool, and the replica's
503
+ * lag. Without a pg pool (PGlite) there is no server to sample.
504
+ */
505
+ sampleHealth(): Promise<DatabaseHealthSample>;
460
506
  /**
461
507
  * Build one statement, binding `$n` placeholders as real parameters.
462
508
  *
@@ -602,7 +648,29 @@ export declare class AuthenticatedPostgresBackendDriver implements DataDriver {
602
648
  * level, so it costs nothing.
603
649
  */
604
650
  readTogether<T>(work: (driver: DataDriver) => Promise<T>): Promise<T>;
651
+ /**
652
+ * Run `operation` in a transaction as this caller — on the read replica
653
+ * when this is a read the replica may serve (see {@link replicaFor}), else
654
+ * on the primary.
655
+ *
656
+ * A read the replica fails for the replica's own reasons (it is down,
657
+ * full, or cancelled the read to replay WAL — see
658
+ * `isReplicaFallbackError`) runs again on the primary; anything else it
659
+ * answered is the answer. A write pins this caller to the primary for
660
+ * `REBASE_READ_STICKY_MS`, from when it starts until that long after it
661
+ * ends, so the caller's next list shows what it just saved.
662
+ */
605
663
  private withTransaction;
664
+ /**
665
+ * The replica's handle for a read by this caller, or `undefined` for the
666
+ * primary: there is no replica, the read is inside a write's transaction
667
+ * (it must see what that write has not committed), the caller is the
668
+ * service identity (crons, jobs, `dataAsAdmin` — server work that reads
669
+ * what it acts on), or the router says the replica is behind, failing, or
670
+ * this caller just wrote.
671
+ */
672
+ private replicaFor;
673
+ private runTransaction;
606
674
  fetchCollection<M extends Record<string, unknown>>(props: FetchCollectionProps<M>): Promise<Record<string, unknown>[]>;
607
675
  /**
608
676
  * The delegate is the base driver, on the owner connection. The user's
@@ -11,6 +11,7 @@ import { DatabasePoolManager } from "./databasePoolManager.js";
11
11
  import { PostgresCollectionRegistry } from "./collections/PostgresCollectionRegistry.js";
12
12
  import { type CdcTableRef } from "./services/cdc/trigger-cdc.js";
13
13
  import { type UnknownFilterFieldsMode } from "./utils/drizzle-conditions.js";
14
+ import { type ReadRoutingOptions } from "./read-routing.js";
14
15
  export interface PostgresDriverConfig {
15
16
  connectionString?: string;
16
17
  adminConnectionString?: string;
@@ -35,6 +36,33 @@ export interface PostgresDriverConfig {
35
36
  * resolves `DATABASE_DIRECT_URL__<KEY>` into this for each source.
36
37
  */
37
38
  directConnectionString?: string;
39
+ /**
40
+ * `connectionString` reaches the database through a transaction-mode
41
+ * pooler (PgBouncer), as `DATABASE_POOLED=true` says for the default
42
+ * source. Then nothing that needs a session runs on the pool: `LISTEN`s,
43
+ * index builds and the SQL console go to {@link directConnectionString},
44
+ * which becomes required — the boot refuses rather than holding a
45
+ * `LISTEN` on the pooler, where it would go silent. The pool itself sends
46
+ * no session settings at connect and sets them per transaction (see
47
+ * `PostgresPoolConfig.pooled`). The read replica's URL is taken to be
48
+ * pooled the same way.
49
+ */
50
+ pooled?: boolean;
51
+ /**
52
+ * The `DB_POOL_*` settings of this source, for the pools the driver opens
53
+ * itself — the read replica's. The server's own pool already has them.
54
+ */
55
+ poolConfig?: {
56
+ max?: number;
57
+ idleTimeoutMillis?: number;
58
+ connectionTimeoutMillis?: number;
59
+ };
60
+ /**
61
+ * How authenticated reads use the read replica: read-your-writes and the
62
+ * lag guard. From `REBASE_READ_STICKY_MS` and `REBASE_READ_MAX_LAG_MS` at
63
+ * boot; defaults 5000 and 1000. Ignored without a replica.
64
+ */
65
+ readRouting?: ReadRoutingOptions;
38
66
  connection?: unknown;
39
67
  /**
40
68
  * The project's generated Drizzle module, for **diagnostics only**.
@@ -183,10 +211,15 @@ export declare function describeSchemaDriftCause(provisioning: {
183
211
  *
184
212
  * Exported for its own test; the caller needs a live database.
185
213
  */
186
- export declare function resolveSourceUrls(pgConfig: Pick<PostgresDriverConfig, "connectionString" | "readConnectionString" | "directConnectionString">, sourceKey: string, env?: Record<string, string | undefined>): {
214
+ export declare function resolveSourceUrls(pgConfig: Pick<PostgresDriverConfig, "connectionString" | "readConnectionString" | "directConnectionString" | "pooled">, sourceKey: string, env?: Record<string, string | undefined>): {
187
215
  readUrl?: string;
188
216
  directUrl?: string;
189
217
  };
218
+ /**
219
+ * The refusal for a pooled source with no direct URL — named so the
220
+ * control plane's log line and the self-hoster's both say what to set.
221
+ */
222
+ export declare function pooledWithoutDirectUrlError(sourceKey: string): Error;
190
223
  /**
191
224
  * Is this the local database `rebase init` scaffolds — i.e. the one case where
192
225
  * "you are connected as a superuser" is not news?
@@ -1,8 +1,8 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { n as require_arg, o as __toESM } from "./cli-prompt-DXG0yk-h.js";
4
- import { l as poolMaxCeiling } from "./connection-czvI7TZL.js";
5
- import { t as openRebase } from "./open-rebase-D9n8idex.js";
4
+ import { d as poolMaxCeiling } from "./connection-CcYqncW5.js";
5
+ import { t as openRebase } from "./open-rebase-DvmKIu7q.js";
6
6
  import { a as diagnoseDbError } from "./cli-errors-DYets7cp.js";
7
7
  import { i as outError, n as describeFailure, r as out } from "./source-fZb92pN8.js";
8
8
  import { h as RELAYED_FLAGS } from "./migrate-baseline-DPawvckr.js";
@@ -291,4 +291,4 @@ async function feedLineByLine(source, server, feed, exited) {
291
291
  //#endregion
292
292
  export { consoleCommand };
293
293
 
294
- //# sourceMappingURL=cli-console-C0FYkICX.js.map
294
+ //# sourceMappingURL=cli-console-CJLtH58M.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cli-console-C0FYkICX.js","names":[],"sources":["../src/cli-console.ts"],"sourcesContent":["/**\n * `rebase console` — the driver's half.\n *\n * Loads the project's collections the way `rebase db push` does, and the\n * global callbacks its `config/index.ts` exports, opens the database with\n * {@link openRebase}, and either evaluates one piece of code\n * (`--eval`) or starts a Node REPL with `rebase` and `collections` in scope.\n * The `rebase` CLI resolves the database first (the managed one included) and\n * hands this process `DATABASE_URL`, exactly as it does for `db` commands.\n *\n * This is the boot side of `openRebase`: it is where the environment is read\n * — `DATABASE_URL`, and the `REBASE_DB_POOL_MAX` ceiling the managed\n * development database needs — and turned into explicit options.\n */\nimport arg from \"arg\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport readline from \"node:readline\";\nimport repl from \"node:repl\";\nimport { PassThrough } from \"node:stream\";\nimport tty from \"node:tty\";\nimport { pathToFileURL } from \"node:url\";\nimport { inspect } from \"node:util\";\nimport { setLogOutput } from \"@rebasepro/server\";\nimport type { CollectionCallbacks, CollectionConfig } from \"@rebasepro/types\";\nimport { RELAYED_FLAGS } from \"./cli-flags\";\nimport { diagnoseDbError } from \"./cli-errors\";\nimport { out, outError, describeFailure } from \"./cli-output\";\nimport { poolMaxCeiling } from \"./connection\";\nimport { openRebase, type OpenedRebase } from \"./open-rebase\";\n\n/**\n * The flags `rebase console` takes. `--history` is the CLI's own: where it\n * keeps the REPL's history (`.rebase/console_history` in the project).\n */\nexport const CONSOLE_FLAGS = {\n \"--collections\": String,\n \"-c\": \"--collections\",\n \"--eval\": String,\n \"-e\": \"--eval\",\n \"--history\": String\n} satisfies arg.Spec;\n\n/** What the code the console runs can name. */\nexport interface ConsoleScope {\n rebase: OpenedRebase;\n collections: CollectionConfig[];\n}\n\ntype ScopedFunction = (rebase: OpenedRebase, collections: CollectionConfig[]) => Promise<unknown>;\ntype AsyncFunctionConstructor = new (...parameters: string[]) => ScopedFunction;\n\n/** The constructor of `async function` — what `new Function` is for a body that awaits. */\nconst AsyncFunction: AsyncFunctionConstructor = Object.getPrototypeOf(async () => undefined).constructor;\n\n/**\n * Run `code` with `rebase` and `collections` in scope and resolve with its\n * value.\n *\n * Read as an expression first, so `rebase.dataAsAdmin.posts.find()` is its own\n * result; code that is not one expression runs as a function body, where\n * `await` works everywhere and `return` gives the result.\n */\nexport async function evaluateInConsole(code: string, scope: ConsoleScope): Promise<unknown> {\n let run: ScopedFunction;\n try {\n run = new AsyncFunction(\"rebase\", \"collections\", `return (${code}\\n);`);\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error;\n run = new AsyncFunction(\"rebase\", \"collections\", code);\n }\n return run(scope.rebase, scope.collections);\n}\n\n/** A result as JSON, the way `--eval` prints it: dates as ISO strings, bigints as strings. */\nexport function consoleJson(value: unknown): string {\n return JSON.stringify(value, (_key, item: unknown) => typeof item === \"bigint\" ? item.toString() : item, 2) ?? \"undefined\";\n}\n\n/** The host and database a URL names, for the banner — never its credentials. */\nfunction describeDatabase(databaseUrl: string): string {\n try {\n const url = new URL(databaseUrl);\n return `${url.hostname}${url.port ? `:${url.port}` : \"\"}${url.pathname}`;\n } catch {\n return \"the configured database\";\n }\n}\n\n/** Where the REPL reads and writes; the terminal unless a caller hands it streams. */\nexport interface ConsoleStreams {\n input?: NodeJS.ReadableStream;\n output?: NodeJS.WritableStream;\n}\n\n/**\n * `rebase console [--eval <code>] [--collections <dir>]`, from the driver\n * line `[\"console\", …flags]`. Resolves with the exit code.\n */\nexport async function consoleCommand(args: string[], streams: ConsoleStreams = {}): Promise<number> {\n const flags = arg({ ...RELAYED_FLAGS, ...CONSOLE_FLAGS }, { argv: args.slice(1) });\n if (flags[\"--help\"]) {\n out(\"Run `rebase console --help` for the options — this is the driver's own entry point.\");\n return 0;\n }\n\n const databaseUrl = flags[\"--database-url\"] || process.env.DATABASE_URL;\n if (!databaseUrl) {\n outError(\"✗ No database to open: DATABASE_URL is not set. Set it in .env, or pass --database-url.\");\n return 1;\n }\n\n // The console's own lines are what the reader is here for; the driver's\n // info-level boot notes are not, unless they asked for them.\n if (process.env.LOG_LEVEL === undefined) process.env.LOG_LEVEL = \"warn\";\n\n // And whatever level they asked for, a log line is never part of the\n // answer: stdout holds the `--eval` result a pipe reads (`| jq .`) and the\n // REPL's values. The scaffold's `.env` sets LOG_LEVEL=info, and under\n // NODE_ENV=production warnings go to stdout too.\n setLogOutput(\"stderr\");\n try {\n return await openAndRun({\n databaseUrl,\n collections: flags[\"--collections\"],\n eval: flags[\"--eval\"],\n history: flags[\"--history\"]\n }, streams);\n } finally {\n setLogOutput();\n }\n}\n\n/** Whether a connection was reset or cut off before it answered, anywhere in the error's chain. */\nfunction connectionCutOff(error: unknown, depth = 0): boolean {\n if (!error || typeof error !== \"object\" || depth > 4) return false;\n if (\"code\" in error && error.code === \"ECONNRESET\") return true;\n if (error instanceof Error && /Connection terminated unexpectedly/.test(error.message)) return true;\n if (\"errors\" in error && Array.isArray(error.errors) && error.errors.some(inner => connectionCutOff(inner, depth + 1))) return true;\n return \"cause\" in error && connectionCutOff(error.cause, depth + 1);\n}\n\n/** Whether Postgres refused the connection for want of one: SQLSTATE 53300, anywhere in the error's chain. */\nfunction noFreeConnection(error: unknown, depth = 0): boolean {\n if (!error || typeof error !== \"object\" || depth > 4) return false;\n if (\"code\" in error && error.code === \"53300\") return true;\n return \"cause\" in error && noFreeConnection(error.cause, depth + 1);\n}\n\n/**\n * What the console says when the project's database will not open: the banner\n * every db command prints for a database it cannot reach, or one sentence —\n * never the driver's error serialised onto one line, stack and all.\n *\n * The managed development database accepts only a few connections at a time,\n * and a running `rebase dev` holds some of them. Its proxy refuses one over the\n * limit with SQLSTATE 53300; a database an earlier CLI started resets it\n * instead, and `read ECONNRESET` says nothing about why.\n */\nexport function describeOpenFailure(error: unknown, databaseUrl: string, managed: boolean): string {\n if (managed && (connectionCutOff(error) || noFreeConnection(error))) {\n return \"✗ The managed development database has no free connection: it accepts only a few at a time, \" +\n \"and other clients hold them — a running `rebase dev` holds some.\\n\" +\n \" Close another `rebase console`, psql or database GUI and run this again, \" +\n \"or stop `rebase dev` while you use the console.\";\n }\n return diagnoseDbError(error, databaseUrl) ?? describeFailure(error);\n}\n\n/**\n * The project's global callbacks: the `callbacks` its `config/index.ts`\n * exports, which the server runs ahead of every collection's own hooks.\n *\n * The config package is the directory the collections live in\n * (`<config>/collections`), or `../config` beside the backend for a\n * collections directory named otherwise. No `index` there means no global\n * callbacks, as it does for the server.\n *\n * One that is there and cannot be imported — an import that needs an\n * environment variable the console was not given, say — does not stop the\n * console, which can still read and write. It says so, once, and runs without\n * them: writes from this session then skip the global tier, and the reader\n * knows it.\n */\nexport async function loadProjectCallbacks(collectionsPath: string): Promise<CollectionCallbacks | undefined> {\n const configDir = path.basename(collectionsPath) === \"collections\"\n ? path.dirname(collectionsPath)\n : path.resolve(\"..\", \"config\");\n // `.js` first, as the server's own loader reads it.\n const indexPath = [\".js\", \".ts\"]\n .map(ext => path.join(configDir, `index${ext}`))\n .find(candidate => fs.existsSync(candidate));\n if (!indexPath) return undefined;\n\n let mod: Record<string, unknown>;\n try {\n mod = await import(pathToFileURL(indexPath).href) as Record<string, unknown>;\n } catch (error) {\n const reason = (error instanceof Error ? error.message : String(error)).split(\"\\n\")[0];\n outError(`⚠ Global callbacks are off in this session: ${indexPath} could not be loaded (${reason}). Collection callbacks still run.`);\n return undefined;\n }\n const callbacks = mod.callbacks;\n return callbacks && typeof callbacks === \"object\" ? callbacks as CollectionCallbacks : undefined;\n}\n\n/** Open the project, run `--eval` or the REPL, and close it again. Resolves with the exit code. */\nasync function openAndRun(\n options: { databaseUrl: string; collections?: string; eval?: string; history?: string },\n streams: ConsoleStreams\n): Promise<number> {\n const { databaseUrl } = options;\n const collectionsPath = path.resolve(options.collections || path.join(\"..\", \"config\", \"collections\"));\n const { loadCollections } = await import(\"./schema/doctor\");\n const collections = fs.existsSync(collectionsPath) ? await loadCollections(collectionsPath) : [];\n // Writes from the console run the same hook tiers as a server write.\n const callbacks = await loadProjectCallbacks(collectionsPath);\n\n const ceiling = poolMaxCeiling();\n let rebase: OpenedRebase;\n try {\n rebase = await openRebase({\n databaseUrl,\n collections,\n ...(callbacks ? { callbacks } : {}),\n ...(ceiling !== null ? { pool: { max: ceiling } } : {})\n });\n } catch (error) {\n outError(describeOpenFailure(error, databaseUrl, process.env.REBASE_DEV_DATABASE_KIND === \"managed\"));\n return 1;\n }\n\n try {\n const code = options.eval;\n if (code !== undefined) {\n try {\n const result = await evaluateInConsole(code, { rebase, collections: rebase.collections });\n if (result !== undefined) out(consoleJson(result));\n return 0;\n } catch (error) {\n outError(describeFailure(error));\n return 1;\n }\n }\n\n await startRepl({ rebase, collections: rebase.collections }, {\n history: options.history,\n database: describeDatabase(databaseUrl),\n ...streams\n });\n return 0;\n } finally {\n await rebase.close();\n }\n}\n\n/** The interactive half: a Node REPL until `.exit`, Ctrl-D or the end of piped input. */\nasync function startRepl(scope: ConsoleScope, options: { history?: string; database: string } & ConsoleStreams): Promise<void> {\n const input = options.input ?? process.stdin;\n const output = options.output ?? process.stdout;\n const typed = input instanceof tty.ReadStream && input.isTTY;\n\n // For a person at a terminal. Piped, stdout is the REPL's answers, which\n // whatever reads the pipe is after, so the banner goes to stderr with the\n // rest of what the console says about itself.\n const say = typed ? out : outError;\n say(\"\");\n say(` rebase console — ${options.database}, ${scope.collections.length} collection(s)`);\n say(\" In scope: rebase (dataAsAdmin, sql, withAuth, close) and collections. Top-level await works.\");\n say(\" Try: await rebase.dataAsAdmin.<collection>.find({ limit: 5 })\");\n say(\"\");\n\n // Typed at a terminal, the REPL reads it as one. Anything else — a pipe, a\n // file, a stream handed in — reaches it a line at a time through `feed`\n // (see `feedLineByLine`).\n const feed = typed ? undefined : new PassThrough();\n // Colours for a terminal only: piped to a file or another program, the\n // escape codes are noise in the text.\n const colors = output instanceof tty.WriteStream && output.isTTY;\n // Started without a prompt, and given one once the scope is in place: a\n // line that arrives with the first prompt must already see `rebase`.\n const server = repl.start({\n prompt: \"\",\n useGlobal: false,\n ...(feed ? { input: feed, output, terminal: false } : { input, output }),\n writer: (value: unknown) => inspect(value, { colors, depth: 6 })\n });\n server.context.rebase = scope.rebase;\n server.context.collections = scope.collections;\n server.setPrompt(\"rebase> \");\n\n const history = options.history;\n if (history) {\n fs.mkdirSync(path.dirname(history), { recursive: true });\n await new Promise<void>((resolve) => {\n server.setupHistory(history, (error) => {\n if (error) outError(` (history is off: ${error.message})`);\n resolve();\n });\n });\n }\n\n const exited = new Promise<void>((resolve) => server.once(\"exit\", () => resolve()));\n server.displayPrompt();\n if (feed) await feedLineByLine(input, server, feed, exited);\n await exited;\n}\n\n/**\n * Hand input that is not typed at a terminal to the REPL a line at a time,\n * each once the REPL has finished the one before.\n *\n * Typed, the REPL holds keystrokes back while a top-level `await` is pending.\n * Piped, every line arrives at once and each is evaluated as it arrives, so in\n * `const { data } = await …` followed by `data.map(…)` the second line read\n * `data` before the first had assigned it.\n *\n * The REPL is paused as each line reaches it, and it resumes its input when it\n * displays its prompt again: once the line's value has settled, its error has\n * been printed, or it needs the next line to complete it. That resumption is\n * when the next line goes in. Lines are written one per chunk, because a\n * chunk holding several is split and every line of it handed over at once.\n */\nasync function feedLineByLine(\n source: NodeJS.ReadableStream,\n server: repl.REPLServer,\n feed: PassThrough,\n exited: Promise<void>\n): Promise<void> {\n let evaluated: (() => void) | undefined;\n const ready = () => {\n const resolve = evaluated;\n evaluated = undefined;\n resolve?.();\n };\n // Before the REPL's own handler, so a line it evaluates at once resumes\n // after this pause rather than before it.\n server.prependListener(\"line\", () => {\n if (!server.editorMode) server.pause();\n });\n // `.editor` collects lines with no prompt until Ctrl-D: they go straight in.\n server.on(\"line\", () => {\n if (!server.editorMode) return;\n server.resume();\n ready();\n });\n server.on(\"resume\", ready);\n\n const closed = exited.then(() => \"closed\" as const);\n const lines = readline.createInterface({ input: source, crlfDelay: Infinity });\n for await (const line of lines) {\n const done = new Promise<\"done\">((resolve) => { evaluated = () => resolve(\"done\"); });\n feed.write(`${line}\\n`);\n // `.exit`: the rest of the input is not for this REPL.\n if (await Promise.race([done, closed]) === \"closed\") break;\n }\n feed.end();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmCA,IAAa,gBAAgB;CACzB,iBAAiB;CACjB,MAAM;CACN,UAAU;CACV,MAAM;CACN,aAAa;AACjB;;AAYA,IAAM,gBAA0C,OAAO,eAAe,YAAY,KAAA,CAAS,CAAC,CAAC;;;;;;;;;AAU7F,eAAsB,kBAAkB,MAAc,OAAuC;CACzF,IAAI;CACJ,IAAI;EACA,MAAM,IAAI,cAAc,UAAU,eAAe,WAAW,KAAK,KAAK;CAC1E,SAAS,OAAO;EACZ,IAAI,EAAE,iBAAiB,cAAc,MAAM;EAC3C,MAAM,IAAI,cAAc,UAAU,eAAe,IAAI;CACzD;CACA,OAAO,IAAI,MAAM,QAAQ,MAAM,WAAW;AAC9C;;AAGA,SAAgB,YAAY,OAAwB;CAChD,OAAO,KAAK,UAAU,QAAQ,MAAM,SAAkB,OAAO,SAAS,WAAW,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK;AACnH;;AAGA,SAAS,iBAAiB,aAA6B;CACnD,IAAI;EACA,MAAM,MAAM,IAAI,IAAI,WAAW;EAC/B,OAAO,GAAG,IAAI,WAAW,IAAI,OAAO,IAAI,IAAI,SAAS,KAAK,IAAI;CAClE,QAAQ;EACJ,OAAO;CACX;AACJ;;;;;A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,MAAM,CAAC,MAAM,UAAU;CACzD;CACA,KAAK,IAAI;AACb"}
1
+ {"version":3,"file":"cli-console-CJLtH58M.js","names":[],"sources":["../src/cli-console.ts"],"sourcesContent":["/**\n * `rebase console` — the driver's half.\n *\n * Loads the project's collections the way `rebase db push` does, and the\n * global callbacks its `config/index.ts` exports, opens the database with\n * {@link openRebase}, and either evaluates one piece of code\n * (`--eval`) or starts a Node REPL with `rebase` and `collections` in scope.\n * The `rebase` CLI resolves the database first (the managed one included) and\n * hands this process `DATABASE_URL`, exactly as it does for `db` commands.\n *\n * This is the boot side of `openRebase`: it is where the environment is read\n * — `DATABASE_URL`, and the `REBASE_DB_POOL_MAX` ceiling the managed\n * development database needs — and turned into explicit options.\n */\nimport arg from \"arg\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport readline from \"node:readline\";\nimport repl from \"node:repl\";\nimport { PassThrough } from \"node:stream\";\nimport tty from \"node:tty\";\nimport { pathToFileURL } from \"node:url\";\nimport { inspect } from \"node:util\";\nimport { setLogOutput } from \"@rebasepro/server\";\nimport type { CollectionCallbacks, CollectionConfig } from \"@rebasepro/types\";\nimport { RELAYED_FLAGS } from \"./cli-flags\";\nimport { diagnoseDbError } from \"./cli-errors\";\nimport { out, outError, describeFailure } from \"./cli-output\";\nimport { poolMaxCeiling } from \"./connection\";\nimport { openRebase, type OpenedRebase } from \"./open-rebase\";\n\n/**\n * The flags `rebase console` takes. `--history` is the CLI's own: where it\n * keeps the REPL's history (`.rebase/console_history` in the project).\n */\nexport const CONSOLE_FLAGS = {\n \"--collections\": String,\n \"-c\": \"--collections\",\n \"--eval\": String,\n \"-e\": \"--eval\",\n \"--history\": String\n} satisfies arg.Spec;\n\n/** What the code the console runs can name. */\nexport interface ConsoleScope {\n rebase: OpenedRebase;\n collections: CollectionConfig[];\n}\n\ntype ScopedFunction = (rebase: OpenedRebase, collections: CollectionConfig[]) => Promise<unknown>;\ntype AsyncFunctionConstructor = new (...parameters: string[]) => ScopedFunction;\n\n/** The constructor of `async function` — what `new Function` is for a body that awaits. */\nconst AsyncFunction: AsyncFunctionConstructor = Object.getPrototypeOf(async () => undefined).constructor;\n\n/**\n * Run `code` with `rebase` and `collections` in scope and resolve with its\n * value.\n *\n * Read as an expression first, so `rebase.dataAsAdmin.posts.find()` is its own\n * result; code that is not one expression runs as a function body, where\n * `await` works everywhere and `return` gives the result.\n */\nexport async function evaluateInConsole(code: string, scope: ConsoleScope): Promise<unknown> {\n let run: ScopedFunction;\n try {\n run = new AsyncFunction(\"rebase\", \"collections\", `return (${code}\\n);`);\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error;\n run = new AsyncFunction(\"rebase\", \"collections\", code);\n }\n return run(scope.rebase, scope.collections);\n}\n\n/** A result as JSON, the way `--eval` prints it: dates as ISO strings, bigints as strings. */\nexport function consoleJson(value: unknown): string {\n return JSON.stringify(value, (_key, item: unknown) => typeof item === \"bigint\" ? item.toString() : item, 2) ?? \"undefined\";\n}\n\n/** The host and database a URL names, for the banner — never its credentials. */\nfunction describeDatabase(databaseUrl: string): string {\n try {\n const url = new URL(databaseUrl);\n return `${url.hostname}${url.port ? `:${url.port}` : \"\"}${url.pathname}`;\n } catch {\n return \"the configured database\";\n }\n}\n\n/** Where the REPL reads and writes; the terminal unless a caller hands it streams. */\nexport interface ConsoleStreams {\n input?: NodeJS.ReadableStream;\n output?: NodeJS.WritableStream;\n}\n\n/**\n * `rebase console [--eval <code>] [--collections <dir>]`, from the driver\n * line `[\"console\", …flags]`. Resolves with the exit code.\n */\nexport async function consoleCommand(args: string[], streams: ConsoleStreams = {}): Promise<number> {\n const flags = arg({ ...RELAYED_FLAGS, ...CONSOLE_FLAGS }, { argv: args.slice(1) });\n if (flags[\"--help\"]) {\n out(\"Run `rebase console --help` for the options — this is the driver's own entry point.\");\n return 0;\n }\n\n const databaseUrl = flags[\"--database-url\"] || process.env.DATABASE_URL;\n if (!databaseUrl) {\n outError(\"✗ No database to open: DATABASE_URL is not set. Set it in .env, or pass --database-url.\");\n return 1;\n }\n\n // The console's own lines are what the reader is here for; the driver's\n // info-level boot notes are not, unless they asked for them.\n if (process.env.LOG_LEVEL === undefined) process.env.LOG_LEVEL = \"warn\";\n\n // And whatever level they asked for, a log line is never part of the\n // answer: stdout holds the `--eval` result a pipe reads (`| jq .`) and the\n // REPL's values. The scaffold's `.env` sets LOG_LEVEL=info, and under\n // NODE_ENV=production warnings go to stdout too.\n setLogOutput(\"stderr\");\n try {\n return await openAndRun({\n databaseUrl,\n collections: flags[\"--collections\"],\n eval: flags[\"--eval\"],\n history: flags[\"--history\"]\n }, streams);\n } finally {\n setLogOutput();\n }\n}\n\n/** Whether a connection was reset or cut off before it answered, anywhere in the error's chain. */\nfunction connectionCutOff(error: unknown, depth = 0): boolean {\n if (!error || typeof error !== \"object\" || depth > 4) return false;\n if (\"code\" in error && error.code === \"ECONNRESET\") return true;\n if (error instanceof Error && /Connection terminated unexpectedly/.test(error.message)) return true;\n if (\"errors\" in error && Array.isArray(error.errors) && error.errors.some(inner => connectionCutOff(inner, depth + 1))) return true;\n return \"cause\" in error && connectionCutOff(error.cause, depth + 1);\n}\n\n/** Whether Postgres refused the connection for want of one: SQLSTATE 53300, anywhere in the error's chain. */\nfunction noFreeConnection(error: unknown, depth = 0): boolean {\n if (!error || typeof error !== \"object\" || depth > 4) return false;\n if (\"code\" in error && error.code === \"53300\") return true;\n return \"cause\" in error && noFreeConnection(error.cause, depth + 1);\n}\n\n/**\n * What the console says when the project's database will not open: the banner\n * every db command prints for a database it cannot reach, or one sentence —\n * never the driver's error serialised onto one line, stack and all.\n *\n * The managed development database accepts only a few connections at a time,\n * and a running `rebase dev` holds some of them. Its proxy refuses one over the\n * limit with SQLSTATE 53300; a database an earlier CLI started resets it\n * instead, and `read ECONNRESET` says nothing about why.\n */\nexport function describeOpenFailure(error: unknown, databaseUrl: string, managed: boolean): string {\n if (managed && (connectionCutOff(error) || noFreeConnection(error))) {\n return \"✗ The managed development database has no free connection: it accepts only a few at a time, \" +\n \"and other clients hold them — a running `rebase dev` holds some.\\n\" +\n \" Close another `rebase console`, psql or database GUI and run this again, \" +\n \"or stop `rebase dev` while you use the console.\";\n }\n return diagnoseDbError(error, databaseUrl) ?? describeFailure(error);\n}\n\n/**\n * The project's global callbacks: the `callbacks` its `config/index.ts`\n * exports, which the server runs ahead of every collection's own hooks.\n *\n * The config package is the directory the collections live in\n * (`<config>/collections`), or `../config` beside the backend for a\n * collections directory named otherwise. No `index` there means no global\n * callbacks, as it does for the server.\n *\n * One that is there and cannot be imported — an import that needs an\n * environment variable the console was not given, say — does not stop the\n * console, which can still read and write. It says so, once, and runs without\n * them: writes from this session then skip the global tier, and the reader\n * knows it.\n */\nexport async function loadProjectCallbacks(collectionsPath: string): Promise<CollectionCallbacks | undefined> {\n const configDir = path.basename(collectionsPath) === \"collections\"\n ? path.dirname(collectionsPath)\n : path.resolve(\"..\", \"config\");\n // `.js` first, as the server's own loader reads it.\n const indexPath = [\".js\", \".ts\"]\n .map(ext => path.join(configDir, `index${ext}`))\n .find(candidate => fs.existsSync(candidate));\n if (!indexPath) return undefined;\n\n let mod: Record<string, unknown>;\n try {\n mod = await import(pathToFileURL(indexPath).href) as Record<string, unknown>;\n } catch (error) {\n const reason = (error instanceof Error ? error.message : String(error)).split(\"\\n\")[0];\n outError(`⚠ Global callbacks are off in this session: ${indexPath} could not be loaded (${reason}). Collection callbacks still run.`);\n return undefined;\n }\n const callbacks = mod.callbacks;\n return callbacks && typeof callbacks === \"object\" ? callbacks as CollectionCallbacks : undefined;\n}\n\n/** Open the project, run `--eval` or the REPL, and close it again. Resolves with the exit code. */\nasync function openAndRun(\n options: { databaseUrl: string; collections?: string; eval?: string; history?: string },\n streams: ConsoleStreams\n): Promise<number> {\n const { databaseUrl } = options;\n const collectionsPath = path.resolve(options.collections || path.join(\"..\", \"config\", \"collections\"));\n const { loadCollections } = await import(\"./schema/doctor\");\n const collections = fs.existsSync(collectionsPath) ? await loadCollections(collectionsPath) : [];\n // Writes from the console run the same hook tiers as a server write.\n const callbacks = await loadProjectCallbacks(collectionsPath);\n\n const ceiling = poolMaxCeiling();\n let rebase: OpenedRebase;\n try {\n rebase = await openRebase({\n databaseUrl,\n collections,\n ...(callbacks ? { callbacks } : {}),\n ...(ceiling !== null ? { pool: { max: ceiling } } : {})\n });\n } catch (error) {\n outError(describeOpenFailure(error, databaseUrl, process.env.REBASE_DEV_DATABASE_KIND === \"managed\"));\n return 1;\n }\n\n try {\n const code = options.eval;\n if (code !== undefined) {\n try {\n const result = await evaluateInConsole(code, { rebase, collections: rebase.collections });\n if (result !== undefined) out(consoleJson(result));\n return 0;\n } catch (error) {\n outError(describeFailure(error));\n return 1;\n }\n }\n\n await startRepl({ rebase, collections: rebase.collections }, {\n history: options.history,\n database: describeDatabase(databaseUrl),\n ...streams\n });\n return 0;\n } finally {\n await rebase.close();\n }\n}\n\n/** The interactive half: a Node REPL until `.exit`, Ctrl-D or the end of piped input. */\nasync function startRepl(scope: ConsoleScope, options: { history?: string; database: string } & ConsoleStreams): Promise<void> {\n const input = options.input ?? process.stdin;\n const output = options.output ?? process.stdout;\n const typed = input instanceof tty.ReadStream && input.isTTY;\n\n // For a person at a terminal. Piped, stdout is the REPL's answers, which\n // whatever reads the pipe is after, so the banner goes to stderr with the\n // rest of what the console says about itself.\n const say = typed ? out : outError;\n say(\"\");\n say(` rebase console — ${options.database}, ${scope.collections.length} collection(s)`);\n say(\" In scope: rebase (dataAsAdmin, sql, withAuth, close) and collections. Top-level await works.\");\n say(\" Try: await rebase.dataAsAdmin.<collection>.find({ limit: 5 })\");\n say(\"\");\n\n // Typed at a terminal, the REPL reads it as one. Anything else — a pipe, a\n // file, a stream handed in — reaches it a line at a time through `feed`\n // (see `feedLineByLine`).\n const feed = typed ? undefined : new PassThrough();\n // Colours for a terminal only: piped to a file or another program, the\n // escape codes are noise in the text.\n const colors = output instanceof tty.WriteStream && output.isTTY;\n // Started without a prompt, and given one once the scope is in place: a\n // line that arrives with the first prompt must already see `rebase`.\n const server = repl.start({\n prompt: \"\",\n useGlobal: false,\n ...(feed ? { input: feed, output, terminal: false } : { input, output }),\n writer: (value: unknown) => inspect(value, { colors, depth: 6 })\n });\n server.context.rebase = scope.rebase;\n server.context.collections = scope.collections;\n server.setPrompt(\"rebase> \");\n\n const history = options.history;\n if (history) {\n fs.mkdirSync(path.dirname(history), { recursive: true });\n await new Promise<void>((resolve) => {\n server.setupHistory(history, (error) => {\n if (error) outError(` (history is off: ${error.message})`);\n resolve();\n });\n });\n }\n\n const exited = new Promise<void>((resolve) => server.once(\"exit\", () => resolve()));\n server.displayPrompt();\n if (feed) await feedLineByLine(input, server, feed, exited);\n await exited;\n}\n\n/**\n * Hand input that is not typed at a terminal to the REPL a line at a time,\n * each once the REPL has finished the one before.\n *\n * Typed, the REPL holds keystrokes back while a top-level `await` is pending.\n * Piped, every line arrives at once and each is evaluated as it arrives, so in\n * `const { data } = await …` followed by `data.map(…)` the second line read\n * `data` before the first had assigned it.\n *\n * The REPL is paused as each line reaches it, and it resumes its input when it\n * displays its prompt again: once the line's value has settled, its error has\n * been printed, or it needs the next line to complete it. That resumption is\n * when the next line goes in. Lines are written one per chunk, because a\n * chunk holding several is split and every line of it handed over at once.\n */\nasync function feedLineByLine(\n source: NodeJS.ReadableStream,\n server: repl.REPLServer,\n feed: PassThrough,\n exited: Promise<void>\n): Promise<void> {\n let evaluated: (() => void) | undefined;\n const ready = () => {\n const resolve = evaluated;\n evaluated = undefined;\n resolve?.();\n };\n // Before the REPL's own handler, so a line it evaluates at once resumes\n // after this pause rather than before it.\n server.prependListener(\"line\", () => {\n if (!server.editorMode) server.pause();\n });\n // `.editor` collects lines with no prompt until Ctrl-D: they go straight in.\n server.on(\"line\", () => {\n if (!server.editorMode) return;\n server.resume();\n ready();\n });\n server.on(\"resume\", ready);\n\n const closed = exited.then(() => \"closed\" as const);\n const lines = readline.createInterface({ input: source, crlfDelay: Infinity });\n for await (const line of lines) {\n const done = new Promise<\"done\">((resolve) => { evaluated = () => resolve(\"done\"); });\n feed.write(`${line}\\n`);\n // `.exit`: the rest of the input is not for this REPL.\n if (await Promise.race([done, closed]) === \"closed\") break;\n }\n feed.end();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmCA,IAAa,gBAAgB;CACzB,iBAAiB;CACjB,MAAM;CACN,UAAU;CACV,MAAM;CACN,aAAa;AACjB;;AAYA,IAAM,gBAA0C,OAAO,eAAe,YAAY,KAAA,CAAS,CAAC,CAAC;;;;;;;;;AAU7F,eAAsB,kBAAkB,MAAc,OAAuC;CACzF,IAAI;CACJ,IAAI;EACA,MAAM,IAAI,cAAc,UAAU,eAAe,WAAW,KAAK,KAAK;CAC1E,SAAS,OAAO;EACZ,IAAI,EAAE,iBAAiB,cAAc,MAAM;EAC3C,MAAM,IAAI,cAAc,UAAU,eAAe,IAAI;CACzD;CACA,OAAO,IAAI,MAAM,QAAQ,MAAM,WAAW;AAC9C;;AAGA,SAAgB,YAAY,OAAwB;CAChD,OAAO,KAAK,UAAU,QAAQ,MAAM,SAAkB,OAAO,SAAS,WAAW,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK;AACnH;;AAGA,SAAS,iBAAiB,aAA6B;CACnD,IAAI;EACA,MAAM,MAAM,IAAI,IAAI,WAAW;EAC/B,OAAO,GAAG,IAAI,WAAW,IAAI,OAAO,IAAI,IAAI,SAAS,KAAK,IAAI;CAClE,QAAQ;EACJ,OAAO;CACX;AACJ;;;;;AAYA,eAAsB,eAAe,MAAgB,UAA0B,CAAC,GAAoB;CAChG,MAAM,SAAA,GAAA,WAAA,QAAA,CAAY;EAAE,GAAG;EAAe,GAAG;CAAc,GAAG,EAAE,MAAM,KAAK,MAAM,CAAC,EAAE,CAAC;CACjF,IAAI,MAAM,WAAW;EACjB,IAAI,qFAAqF;EACzF,OAAO;CACX;CAEA,MAAM,cAAc,MAAM,qBAAqB,QAAQ,IAAI;CAC3D,IAAI,CAAC,aAAa;EACd,SAAS,yFAAyF;EAClG,OAAO;CACX;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IACpC,IAAI,OAAO,SAAS,sBAAsB,MAAM,QAAQ,EAAE;IAC1D,QAAQ;GACZ,CAAC;EACL,CAAC;CACL;CAEA,MAAM,SAAS,IAAI,SAAe,YAAY,OAAO,KAAK,cAAc,QAAQ,CAAC,CAAC;CAClF,OAAO,cAAc;CACrB,IAAI,MAAM,MAAM,eAAe,OAAO,QAAQ,MAAM,MAAM;CAC1D,MAAM;AACV;;;;;;;;;;;;;;;;AAiBA,eAAe,eACX,QACA,QACA,MACA,QACa;CACb,IAAI;CACJ,MAAM,cAAc;EAChB,MAAM,UAAU;EAChB,YAAY,KAAA;EACZ,UAAU;CACd;CAGA,OAAO,gBAAgB,cAAc;EACjC,IAAI,CAAC,OAAO,YAAY,OAAO,MAAM;CACzC,CAAC;CAED,OAAO,GAAG,cAAc;EACpB,IAAI,CAAC,OAAO,YAAY;EACxB,OAAO,OAAO;EACd,MAAM;CACV,CAAC;CACD,OAAO,GAAG,UAAU,KAAK;CAEzB,MAAM,SAAS,OAAO,WAAW,QAAiB;CAClD,MAAM,QAAQ,SAAS,gBAAgB;EAAE,OAAO;EAAQ,WAAW;CAAS,CAAC;CAC7E,WAAW,MAAM,QAAQ,OAAO;EAC5B,MAAM,OAAO,IAAI,SAAiB,YAAY;GAAE,kBAAkB,QAAQ,MAAM;EAAG,CAAC;EACpF,KAAK,MAAM,GAAG,KAAK,GAAG;EAEtB,IAAI,MAAM,QAAQ,KAAK,CAAC,MAAM,MAAM,CAAC,MAAM,UAAU;CACzD;CACA,KAAK,IAAI;AACb"}
package/dist/cli.js CHANGED
@@ -1254,7 +1254,7 @@ async function runPluginCommand(args) {
1254
1254
  else if (domain === "schema") await schemaCommand(subcommand, args);
1255
1255
  else if (domain === "doctor") await doctorPluginCommand(args);
1256
1256
  else if (domain === "console") {
1257
- const { consoleCommand } = await import("./cli-console-C0FYkICX.js");
1257
+ const { consoleCommand } = await import("./cli-console-CJLtH58M.js");
1258
1258
  process.exitCode = await consoleCommand(args);
1259
1259
  } else {
1260
1260
  outError(chalk.red(`Unknown domain command: ${domain}`));
@@ -1736,7 +1736,7 @@ async function dbCommand(subcommand, rawArgs) {
1736
1736
  if (databaseUrl) {
1737
1737
  await ensureRlsUserRole(databaseUrl);
1738
1738
  await retireLegacyAuthSchema(databaseUrl);
1739
- const { stampMigratedPolicies } = await import("./migrate-policy-stamps-B-8vTSIm.js");
1739
+ const { stampMigratedPolicies } = await import("./migrate-policy-stamps-CdljD_y1.js");
1740
1740
  await stampMigratedPolicies(databaseUrl, collectionsPath);
1741
1741
  }
1742
1742
  }
@@ -1791,7 +1791,7 @@ async function renameLegacyForeignKeys(databaseUrl, collectionsPath, dryRun) {
1791
1791
  let renames;
1792
1792
  try {
1793
1793
  const { loadCollections } = await import("./doctor-TJApVglQ.js").then((n) => n.t);
1794
- const { legacyForeignKeyRenames } = await import("./push-legacy-renames-BIxBmVLl.js");
1794
+ const { legacyForeignKeyRenames } = await import("./push-legacy-renames-BFF72tHG.js");
1795
1795
  const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
1796
1796
  renames = await withAppClient(databaseUrl, (client) => legacyForeignKeyRenames({ query: async (text) => ({ rows: (await client.query(text)).rows }) }, collections));
1797
1797
  } catch {
@@ -1811,7 +1811,7 @@ async function renameLegacyForeignKeys(databaseUrl, collectionsPath, dryRun) {
1811
1811
  async function reportKeptEnumLabels(databaseUrl, collectionsPath) {
1812
1812
  try {
1813
1813
  const { loadCollections } = await import("./doctor-TJApVglQ.js").then((n) => n.t);
1814
- const { keptEnumLabels, formatKeptEnumLabelsNotice } = await import("./enum-labels-kept-BCgFGAbJ.js");
1814
+ const { keptEnumLabels, formatKeptEnumLabelsNotice } = await import("./enum-labels-kept-DAbJ_IIl.js");
1815
1815
  const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
1816
1816
  const kept = await withAppClient(databaseUrl, (client) => keptEnumLabels({ query: async (text) => ({ rows: (await client.query(text)).rows }) }, collections));
1817
1817
  if (kept.length > 0) outWarn(chalk.yellow(formatKeptEnumLabelsNotice(kept)));
@@ -1821,7 +1821,7 @@ async function prebuildForeignKeyIndexes(databaseUrl, collectionsPath, dryRun) {
1821
1821
  let missing;
1822
1822
  try {
1823
1823
  const { loadCollections } = await import("./doctor-TJApVglQ.js").then((n) => n.t);
1824
- const { missingForeignKeyIndexes } = await import("./push-index-prebuild-DR3P4yOw.js");
1824
+ const { missingForeignKeyIndexes } = await import("./push-index-prebuild-C6wKdjYV.js");
1825
1825
  const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
1826
1826
  missing = await withAppClient(databaseUrl, (client) => missingForeignKeyIndexes({ query: async (text) => ({ rows: (await client.query(text)).rows }) }, collections));
1827
1827
  } catch {
@@ -1831,7 +1831,7 @@ async function prebuildForeignKeyIndexes(databaseUrl, collectionsPath, dryRun) {
1831
1831
  if (missing.length === 0 || dryRun) return names;
1832
1832
  out(chalk.gray(` Building ${missing.length} foreign-key index(es) on existing tables first — CONCURRENTLY, so writes go on:`));
1833
1833
  try {
1834
- const { buildDeferredIndexes } = await import("./deferred-index-build-BcJ_oulu.js").then((n) => n.r);
1834
+ const { buildDeferredIndexes } = await import("./deferred-index-build-BwH6k1Og.js").then((n) => n.r);
1835
1835
  const outcome = await withAppClient(databaseUrl, (client) => buildDeferredIndexes(async () => ({
1836
1836
  dedicated: true,
1837
1837
  query: async (text) => ({ rows: (await client.query(text)).rows }),
@@ -1879,7 +1879,7 @@ async function lockManagedTables(databaseUrl, collectionsPath) {
1879
1879
  let unsecured;
1880
1880
  let userRole;
1881
1881
  try {
1882
- const { lockCollectionTables } = await import("./ensure-collection-policies-BNwSQfVx.js");
1882
+ const { lockCollectionTables } = await import("./ensure-collection-policies-f0LIwiwp.js");
1883
1883
  const { loadCollections } = await import("./doctor-TJApVglQ.js").then((n) => n.t);
1884
1884
  userRole = (await import("./rls-enforcement-BOHuHVlc.js").then((n) => n.l)).REBASE_USER_ROLE;
1885
1885
  const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
@@ -1999,8 +1999,8 @@ async function policyStamping(databaseUrl, collectionsPath, policiesSql) {
1999
1999
  try {
2000
2000
  const { loadCollections } = await import("./doctor-TJApVglQ.js").then((n) => n.t);
2001
2001
  const { planCollectionPolicies } = await import("./generate-postgres-ddl-logic-0rbAqwYT.js").then((n) => n.o);
2002
- const { policyStampSql } = await import("./ensure-collection-policies-BNwSQfVx.js");
2003
- const { pinSearchPath } = await import("./connection-czvI7TZL.js").then((n) => n.n);
2002
+ const { policyStampSql } = await import("./ensure-collection-policies-f0LIwiwp.js");
2003
+ const { pinSearchPath } = await import("./connection-CcYqncW5.js").then((n) => n.r);
2004
2004
  return {
2005
2005
  statements: stampableTables(planCollectionPolicies(await loadCollections(path.resolve(process.cwd(), collectionsPath))), policiesSql).map((plan) => policyStampSql(plan)).filter((statement) => statement !== void 0),
2006
2006
  searchPath: pinSearchPath(databaseUrl) === databaseUrl ? void 0 : "public"
@@ -2017,9 +2017,9 @@ async function policyStamping(databaseUrl, collectionsPath, policiesSql) {
2017
2017
  */
2018
2018
  async function readPolicyPushPlan(databaseUrl, collectionsPath) {
2019
2019
  try {
2020
- const { formatPolicyPushPlan, planPolicyPush, summarizePolicyPushPlan } = await import("./push-policy-plan-BHsasXa7.js");
2020
+ const { formatPolicyPushPlan, planPolicyPush, summarizePolicyPushPlan } = await import("./push-policy-plan-lOTPeQ1u.js");
2021
2021
  const { loadCollections } = await import("./doctor-TJApVglQ.js").then((n) => n.t);
2022
- const { pinSearchPath } = await import("./connection-czvI7TZL.js").then((n) => n.n);
2022
+ const { pinSearchPath } = await import("./connection-CcYqncW5.js").then((n) => n.r);
2023
2023
  const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
2024
2024
  const plan = await withAppClient(databaseUrl, (client) => planPolicyPush({ query: async (text, values) => ({ rows: (await client.query(text, values)).rows }) }, collections, { searchPath: pinSearchPath(databaseUrl) === databaseUrl ? void 0 : "public" }));
2025
2025
  return {
@@ -2132,7 +2132,7 @@ async function branchCommand(rawArgs) {
2132
2132
  outError(chalk.red("✗ DATABASE_URL is not set. Make sure your .env file is configured."));
2133
2133
  process.exit(1);
2134
2134
  }
2135
- const { DatabasePoolManager } = await import("./databasePoolManager-BjoVvuAq.js").then((n) => n.n);
2135
+ const { DatabasePoolManager } = await import("./databasePoolManager-XmhMczz0.js").then((n) => n.n);
2136
2136
  const { BranchService, reopenClosedDatabases, reopenedDatabasesNotice } = await import("./BranchService-BPssiD8_.js").then((n) => n.n);
2137
2137
  const { drizzle } = await import("drizzle-orm/node-postgres");
2138
2138
  const { Pool } = await import("pg");
@@ -58,13 +58,18 @@ function reportPoolError(label, err, log = logger, now = Date.now) {
58
58
  //#region src/connection.ts
59
59
  var connection_exports = /* @__PURE__ */ __exportAll({
60
60
  cappedPoolMax: () => cappedPoolMax,
61
+ closeWithPool: () => closeWithPool,
61
62
  createDirectDatabaseConnection: () => createDirectDatabaseConnection,
62
63
  createPostgresDatabaseConnection: () => createPostgresDatabaseConnection,
63
64
  createReadReplicaConnection: () => createReadReplicaConnection,
64
65
  defaultPoolTimeouts: () => defaultPoolTimeouts,
65
66
  guardPoolAgainstDirtyRelease: () => guardPoolAgainstDirtyRelease,
67
+ isPooledPool: () => isPooledPool,
66
68
  pinSearchPath: () => pinSearchPath,
67
- poolMaxCeiling: () => poolMaxCeiling
69
+ poolMaxCeiling: () => poolMaxCeiling,
70
+ pooledTransactionSettings: () => pooledTransactionSettings,
71
+ searchPathList: () => searchPathList,
72
+ transactionSettingsStatements: () => transactionSettingsStatements
68
73
  });
69
74
  /**
70
75
  * Ceiling on pool size, from the environment.
@@ -94,6 +99,7 @@ function cappedPoolMax(requested, env = process.env) {
94
99
  var DEFAULT_POOL = {
95
100
  max: 20,
96
101
  searchPath: "public",
102
+ pooled: false,
97
103
  idleTimeoutMillis: 3e4,
98
104
  connectionTimeoutMillis: 1e4,
99
105
  queryTimeout: 6e4,
@@ -118,6 +124,64 @@ function defaultPoolTimeouts() {
118
124
  }
119
125
  /** ReadyForQuery status byte: `I` idle, `T` in transaction, `E` failed transaction. */
120
126
  var TX_IDLE = "I";
127
+ var pooledPools = /* @__PURE__ */ new WeakMap();
128
+ /**
129
+ * The settings a transaction on `pool` must `SET LOCAL` for itself, or
130
+ * `undefined` when the pool talks to the database directly and sent them at
131
+ * connect.
132
+ */
133
+ function pooledTransactionSettings(pool) {
134
+ return pool !== null && typeof pool === "object" ? pooledPools.get(pool) : void 0;
135
+ }
136
+ /** Whether `pool` reaches its database through a transaction-mode pooler. */
137
+ function isPooledPool(pool) {
138
+ return pooledTransactionSettings(pool) !== void 0;
139
+ }
140
+ /**
141
+ * The `SET LOCAL` statements that give a transaction on a pooled connection
142
+ * what a direct connection got from its startup packet. Empty for a direct
143
+ * pool. `SET LOCAL` ends with the transaction, so nothing reaches the next
144
+ * client the pooler hands that server connection to.
145
+ */
146
+ function transactionSettingsStatements(settings) {
147
+ if (!settings) return [];
148
+ const statements = [];
149
+ if (settings.searchPath !== false) statements.push(`SET LOCAL search_path TO ${searchPathList(settings.searchPath)}`);
150
+ if (settings.statementTimeoutMs > 0) statements.push(`SET LOCAL statement_timeout = ${Math.floor(settings.statementTimeoutMs)}`);
151
+ return statements;
152
+ }
153
+ /**
154
+ * A `search_path` value as a list of quoted identifiers, so a schema name can
155
+ * never be read as SQL. `"$user"` keeps its meaning quoted.
156
+ */
157
+ function searchPathList(searchPath) {
158
+ return searchPath.split(",").map((part) => part.trim().replace(/^"(.*)"$/, "$1")).filter((part) => part.length > 0).map((part) => `"${part.replace(/"/g, "\"\"")}"`).join(", ");
159
+ }
160
+ /**
161
+ * The `pg.Pool` settings shared by every pool this module opens, with the
162
+ * startup parameters a transaction-mode pooler cannot carry left out when
163
+ * `pooled`. The pool is registered so {@link pooledTransactionSettings} can
164
+ * answer for it.
165
+ */
166
+ function poolOptions(connectionString, opts, max) {
167
+ return {
168
+ connectionString: opts.pooled ? connectionString : pinSearchPath(connectionString, opts.searchPath),
169
+ max,
170
+ idleTimeoutMillis: opts.idleTimeoutMillis,
171
+ connectionTimeoutMillis: opts.connectionTimeoutMillis,
172
+ query_timeout: opts.queryTimeout,
173
+ ...opts.pooled ? {} : { statement_timeout: opts.statementTimeout },
174
+ keepAlive: opts.keepAlive,
175
+ keepAliveInitialDelayMillis: 0
176
+ };
177
+ }
178
+ function registerPooled(pool, opts) {
179
+ if (!opts.pooled) return;
180
+ pooledPools.set(pool, {
181
+ searchPath: opts.searchPath,
182
+ statementTimeoutMs: opts.statementTimeout
183
+ });
184
+ }
121
185
  /**
122
186
  * Pin `search_path` into a connection string, so unqualified SQL resolves to a
123
187
  * schema this framework chose rather than to one Postgres inferred.
@@ -219,17 +283,10 @@ function createPostgresDatabaseConnection(connectionString, schema, poolConfig,
219
283
  ...DEFAULT_POOL,
220
284
  ...poolConfig
221
285
  };
222
- connectionString = pinSearchPath(connectionString, opts.searchPath);
223
- const pool = new Pool({
224
- connectionString,
225
- max: cappedPoolMax(opts.max, env),
226
- idleTimeoutMillis: opts.idleTimeoutMillis,
227
- connectionTimeoutMillis: opts.connectionTimeoutMillis,
228
- query_timeout: opts.queryTimeout,
229
- statement_timeout: opts.statementTimeout,
230
- keepAlive: opts.keepAlive,
231
- keepAliveInitialDelayMillis: 0
232
- });
286
+ const pgPoolConfig = poolOptions(connectionString, opts, cappedPoolMax(opts.max, env));
287
+ connectionString = pgPoolConfig.connectionString ?? connectionString;
288
+ const pool = new Pool(pgPoolConfig);
289
+ registerPooled(pool, opts);
233
290
  pool.on("error", (err) => {
234
291
  reportPoolError("pg-pool", err);
235
292
  if (err.message.includes("ETIMEDOUT")) logger.warn("[pg-pool] Connection timeout detected — pool will auto-retry");
@@ -254,17 +311,10 @@ function createDirectDatabaseConnection(connectionString, schema, poolConfig) {
254
311
  max: 5,
255
312
  ...poolConfig
256
313
  };
257
- connectionString = pinSearchPath(connectionString, opts.searchPath);
258
- const pool = new Pool({
259
- connectionString,
260
- max: cappedPoolMax(opts.max),
261
- idleTimeoutMillis: opts.idleTimeoutMillis,
262
- connectionTimeoutMillis: opts.connectionTimeoutMillis,
263
- query_timeout: opts.queryTimeout,
264
- statement_timeout: opts.statementTimeout,
265
- keepAlive: opts.keepAlive,
266
- keepAliveInitialDelayMillis: 0
267
- });
314
+ const pgPoolConfig = poolOptions(connectionString, opts, cappedPoolMax(opts.max));
315
+ connectionString = pgPoolConfig.connectionString ?? connectionString;
316
+ const pool = new Pool(pgPoolConfig);
317
+ registerPooled(pool, opts);
268
318
  pool.on("error", (err) => reportPoolError("pg-direct-pool", err));
269
319
  guardPoolAgainstDirtyRelease(pool, "pg-direct-pool");
270
320
  return {
@@ -283,17 +333,10 @@ function createReadReplicaConnection(connectionString, schema, poolConfig) {
283
333
  max: 10,
284
334
  ...poolConfig
285
335
  };
286
- connectionString = pinSearchPath(connectionString, opts.searchPath);
287
- const pool = new Pool({
288
- connectionString,
289
- max: cappedPoolMax(opts.max),
290
- idleTimeoutMillis: opts.idleTimeoutMillis,
291
- connectionTimeoutMillis: opts.connectionTimeoutMillis,
292
- query_timeout: opts.queryTimeout,
293
- statement_timeout: opts.statementTimeout,
294
- keepAlive: opts.keepAlive,
295
- keepAliveInitialDelayMillis: 0
296
- });
336
+ const pgPoolConfig = poolOptions(connectionString, opts, cappedPoolMax(opts.max));
337
+ connectionString = pgPoolConfig.connectionString ?? connectionString;
338
+ const pool = new Pool(pgPoolConfig);
339
+ registerPooled(pool, opts);
297
340
  pool.on("error", (err) => reportPoolError("pg-replica-pool", err));
298
341
  guardPoolAgainstDirtyRelease(pool, "pg-replica-pool");
299
342
  return {
@@ -302,7 +345,41 @@ function createReadReplicaConnection(connectionString, schema, poolConfig) {
302
345
  connectionString
303
346
  };
304
347
  }
348
+ /**
349
+ * Close `companions` whenever `pool` is closed, before it.
350
+ *
351
+ * The pools a driver opens for itself — a read replica's, a direct session
352
+ * pool, the per-database pools — are invisible to whoever opened the main
353
+ * pool, and closing the main pool is the one shutdown signal every server
354
+ * version sends a driver. So the main pool's `end` is wrapped: companions
355
+ * first, then the pool, once however many times it is called (`pg.Pool`
356
+ * throws on a second `end`). A pool without `end`, or no pool, is left alone.
357
+ */
358
+ function closeWithPool(pool, companions) {
359
+ if (pool === null || typeof pool !== "object" || !("end" in pool) || typeof pool.end !== "function") return;
360
+ const end = pool.end.bind(pool);
361
+ let closing;
362
+ const wrapped = (callback) => {
363
+ closing ??= (async () => {
364
+ try {
365
+ await companions();
366
+ } finally {
367
+ await end();
368
+ }
369
+ })();
370
+ if (typeof callback === "function") {
371
+ closing.then(() => callback(), (err) => callback(err instanceof Error ? err : new Error(String(err))));
372
+ return;
373
+ }
374
+ return closing;
375
+ };
376
+ Object.defineProperty(pool, "end", {
377
+ value: wrapped,
378
+ configurable: true,
379
+ writable: true
380
+ });
381
+ }
305
382
  //#endregion
306
- export { createReadReplicaConnection as a, pinSearchPath as c, createPostgresDatabaseConnection as i, poolMaxCeiling as l, connection_exports as n, defaultPoolTimeouts as o, createDirectDatabaseConnection as r, guardPoolAgainstDirtyRelease as s, cappedPoolMax as t, reportPoolError as u };
383
+ export { createPostgresDatabaseConnection as a, guardPoolAgainstDirtyRelease as c, poolMaxCeiling as d, pooledTransactionSettings as f, reportPoolError as h, createDirectDatabaseConnection as i, isPooledPool as l, transactionSettingsStatements as m, closeWithPool as n, createReadReplicaConnection as o, searchPathList as p, connection_exports as r, defaultPoolTimeouts as s, cappedPoolMax as t, pinSearchPath as u };
307
384
 
308
- //# sourceMappingURL=connection-czvI7TZL.js.map
385
+ //# sourceMappingURL=connection-CcYqncW5.js.map