@broberg/db-sdk 0.2.0 → 0.4.0
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.
- package/README.md +175 -5
- package/dist/chunk-ONXYOFVT.js +124 -0
- package/dist/chunk-ONXYOFVT.js.map +1 -0
- package/dist/index.d.ts +7 -104
- package/dist/index.js +12 -51
- package/dist/index.js.map +1 -1
- package/dist/switchable/index.d.ts +561 -0
- package/dist/switchable/index.js +1165 -0
- package/dist/switchable/index.js.map +1 -0
- package/dist/types-9Y21zZWt.d.ts +114 -0
- package/package.json +17 -3
package/README.md
CHANGED
|
@@ -88,10 +88,19 @@ Supabase project (eu-north-1), 40 concurrent queries with prepared statements ON
|
|
|
88
88
|
| session pooler | 40/40 |
|
|
89
89
|
| direct, 5432 | 40/40 |
|
|
90
90
|
|
|
91
|
+
**Reproduced on 24 Sep 2026 on a self-hosted Supabase** (CLI 2.117.0, Supavisor
|
|
92
|
+
2.9.12, transaction mode): prepared statements ON hung 2 runs of 2 (one also
|
|
93
|
+
threw driver-internal errors), OFF answered 40/40, and a direct connection
|
|
94
|
+
answered 40/40 either way. So it is the transaction pooler (Supavisor) itself,
|
|
95
|
+
not a quirk of Supabase's cloud.
|
|
96
|
+
|
|
91
97
|
It does not fail — it **hangs**, and only under concurrency, so a sequential
|
|
92
|
-
test and a local Postgres both stay green. The contract suite
|
|
93
|
-
concurrent queries through
|
|
94
|
-
|
|
98
|
+
test and a local Postgres both stay green. The contract suite has a case for
|
|
99
|
+
it — 60 concurrent queries through a transaction pooler against a 90-second
|
|
100
|
+
deadline, red with `HUNG` when prepared statements are turned back on — but it
|
|
101
|
+
runs only when `DB_SDK_TEST_PG_POOLER_URL` points at a real pooler. **CI does
|
|
102
|
+
not have one today**, so the guard in CI is the configuration test
|
|
103
|
+
(`prepare: false`), not the behavioural one.
|
|
95
104
|
|
|
96
105
|
Keep the service-role connection string on the server. Supabase auth belongs in
|
|
97
106
|
`@broberg/auth`, storage in `@broberg/media`; this package is the SQL connection
|
|
@@ -141,6 +150,164 @@ libSQL read batch against a local file was measured executing an INSERT that
|
|
|
141
150
|
Postgres refused, and a read-only promise that holds on one transport only is not
|
|
142
151
|
one the facade can make.
|
|
143
152
|
|
|
153
|
+
## node-postgres (`pg`)
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
const db = createClient({ backend: 'pg', url: process.env.DATABASE_URL }); // or { backend: 'pg', pool: myPgPool }
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
The same facade over `pg.Pool` — for a stack that needs a pg pool (Better Auth's
|
|
160
|
+
kysely dialect does). `pg` is an optional peer dependency: install it yourself,
|
|
161
|
+
or pass your own `pool` and the package never imports it. The contract suite
|
|
162
|
+
runs against it unchanged (components-F085.6).
|
|
163
|
+
|
|
164
|
+
## Instant switch (`@broberg/db-sdk/switchable`) — Postgres, 0.3.0+
|
|
165
|
+
|
|
166
|
+
For a dual-DB app (primary + reserve replica, D-444126): one client that moves
|
|
167
|
+
to the other database **while the process runs**, a fence that makes the
|
|
168
|
+
database you are NOT on refuse writes, and the way back without loss. Ported
|
|
169
|
+
from broberg-id (F084.149/.153/.154); components-F085.5.
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
import { createClient } from '@broberg/db-sdk';
|
|
173
|
+
import { createSwitchable } from '@broberg/db-sdk/switchable';
|
|
174
|
+
|
|
175
|
+
const primary = createClient({ backend: 'postgres', url: process.env.DATABASE_URL });
|
|
176
|
+
const db = createSwitchable(primary, 'primary'); // use `db` everywhere — execute(), batch() AND db.raw
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
**The switch itself is NOT something to do by hand.** It is an ordered
|
|
180
|
+
sequence with a way back at every step, run across every machine — broberg-id's
|
|
181
|
+
`src/db-switch-cli.ts`, whose port into this package is the next step of
|
|
182
|
+
F085.5. Until then, read the order here, not as a recipe:
|
|
183
|
+
|
|
184
|
+
1. Preconditions: the fence is installed on both sides and covers every table;
|
|
185
|
+
the target is `locked`, the current side `open`. Otherwise stop.
|
|
186
|
+
2. To the reserve: a marker row through the replication stream proves it is alive.
|
|
187
|
+
3. `hold(ms)` on every machine. **Any machine not drained (`ok: false`) → abort.**
|
|
188
|
+
4. To the reserve: a second marker must arrive (everything written before the
|
|
189
|
+
hold is there), then `alter subscription … disable`, then
|
|
190
|
+
`captureBaseline(reserve)` — while everything is held.
|
|
191
|
+
5. `setFence(target, 'open')` — nobody writes yet, everyone holds.
|
|
192
|
+
6. `point(target)` on every machine, then `release()` on every machine.
|
|
193
|
+
7. `setFence(old, 'locked')` — also if a machine did not confirm: a machine
|
|
194
|
+
left on the old side is exactly the one that must fail loudly.
|
|
195
|
+
|
|
196
|
+
**Abort** (any step before 6 fails): `release()` on the old side everywhere
|
|
197
|
+
(the machine-side control does this itself if the orchestrator vanishes),
|
|
198
|
+
re-lock the target if step 5 ran, and re-enable the subscription if step 4 ran.
|
|
199
|
+
The way back to the primary is the same with `reconcile(reserve, primary,
|
|
200
|
+
{ apply: true })` before the hold (most rows) and again under it (the rest).
|
|
201
|
+
|
|
202
|
+
- **Either driver.** `createSwitchable(createClient({ backend: 'pg', … }))` gives a `.raw` that is a stand-in `pg.Pool` — `query` and `connect()` wait out a hold and count as running (a client until its `release()`, once) — so Better Auth and your own pool code follow the switch. Both sides must use the same driver.
|
|
203
|
+
- **`.raw` follows the switch.** `db.raw` is a stand-in `Sql`: `` sql`…` ``,
|
|
204
|
+
`sql.unsafe()`, `sql.begin()` and `sql.reserve()` all reach the side that is
|
|
205
|
+
active when they run, after any hold. Query modifiers and fragments work as
|
|
206
|
+
usual; a cursor or `forEach` counts as running until it ends. `sql.notify()`
|
|
207
|
+
waits out a hold too; `sql.listen()` stays on the side it was called on. If a
|
|
208
|
+
postgres.js upgrade moves the internals this relies on, creating the client
|
|
209
|
+
throws — it never runs quietly on the wrong side (postgres.js is pinned
|
|
210
|
+
`~3.4.9`).
|
|
211
|
+
- **The fence lives in the database** (a per-statement trigger), so it covers
|
|
212
|
+
every path in: `execute()`, `.raw`, migrations, psql. Call `installFence`
|
|
213
|
+
after every migration — it fences new tables and never changes the state.
|
|
214
|
+
Replication passes through a locked subscriber — initial copy, INSERT,
|
|
215
|
+
UPDATE, DELETE (measured in CI).
|
|
216
|
+
- **The way back:** `captureBaseline(reserve)` at the switch;
|
|
217
|
+
`reconcile(reserve, primary, { apply })` before switching back copies what
|
|
218
|
+
changed in the reserve and reports — never overwrites — a row the primary
|
|
219
|
+
changed on its own.
|
|
220
|
+
- Names default to `dbFence` / `db_sdk.fence_bypass` / schema `dbSwitch`; BID
|
|
221
|
+
passes its own (`bidFence`, `bid.fence_bypass`, `bidSwitch`).
|
|
222
|
+
|
|
223
|
+
**Per-machine control (`createSwitchControl`).** The HTTP door an orchestrator
|
|
224
|
+
moves each process by — `POST /db/prepare|hold|point|release|abort`, `GET
|
|
225
|
+
/db/status`, Bearer = `switchToken(sharedSecret, context)`. `point` is refused
|
|
226
|
+
(409) unless the target was prepared AND the machine holds. If the orchestrator
|
|
227
|
+
disappears, a holding machine aborts by itself after 2 × the hold — back to
|
|
228
|
+
the side from before, never alone on the new one. Serve it where only your
|
|
229
|
+
own machines reach it (BID: Fly's private network); which URLs and TLS the
|
|
230
|
+
targets use stays in your app:
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
const handle = createSwitchControl({
|
|
234
|
+
switchable: db,
|
|
235
|
+
secret: process.env.APP_SECRET!,
|
|
236
|
+
targets: {
|
|
237
|
+
primary: { label: 'supabase', open: () => createClient({ backend: 'postgres', url: PRIMARY_URL }) },
|
|
238
|
+
reserve: { label: 'upcloud', open: () => createClient({ backend: 'postgres', url: RESERVE_URL }) },
|
|
239
|
+
},
|
|
240
|
+
});
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
`emergencyGate()` is BID's guard for a switch without the primary: never
|
|
244
|
+
without an explicit accept of data loss, and refused while the primary answers.
|
|
245
|
+
|
|
246
|
+
**Orchestration (`orchestrateSwitch`).** BID's switch order as one call, over
|
|
247
|
+
every machine: fence preconditions → probe through the stream → prepare →
|
|
248
|
+
hold (an undrained machine ABORTS) → marker → subscription off → baseline →
|
|
249
|
+
unfence target → point → release → fence the old side. Any failure before
|
|
250
|
+
release aborts on all machines: back to the old side, target re-fenced,
|
|
251
|
+
subscription re-enabled. The way home (`to: 'primary'`) copies the reserve's
|
|
252
|
+
writes first; conflicts stop it unless `skipConflicts`. Emergency
|
|
253
|
+
(`primaryDown`) needs `acceptDataLoss` and is refused while the primary answers.
|
|
254
|
+
Machines are `{ id, call }` — `httpMachine(id, baseUrl, switchToken(secret))`
|
|
255
|
+
for plain HTTP; finding them and setting secrets afterwards stays in the app.
|
|
256
|
+
Tested with three in-process machines, two servers and real replication,
|
|
257
|
+
including the faults BID injects in production (`fault: 'replication' | 'point'`).
|
|
258
|
+
|
|
259
|
+
**Is the reserve alive? (`reserveHealth`, `watchReserve`).** Read from the
|
|
260
|
+
PRIMARY's replication slot (a dead reserve is exactly what it must report):
|
|
261
|
+
`missing | inactive | lost | stale | lagging | unreadable`, never «ok» when it
|
|
262
|
+
could not look. Serve it on its own route (BID: `/health/reserve`), never your
|
|
263
|
+
readiness check — a dead reserve must not take logins down. `watchReserve` is
|
|
264
|
+
the pure alarm hook: unhealthy ≥ 10 min in a row → one incident per episode
|
|
265
|
+
(the id carries the episode start); a failed reserve migration
|
|
266
|
+
(`noteReserveMigration`) alarms at once. You keep the state and send the alarm.
|
|
267
|
+
|
|
268
|
+
**The reserve reconnects itself (`runGuard`, `liveDeps`).** When the
|
|
269
|
+
reserve's provider gives it a new public address (UpCloud maintenance did, twice),
|
|
270
|
+
the primary's allow-list keeps it out and the slot dies. The guard — run from
|
|
271
|
+
CI, never the app (the primary's token is account-wide) — confirms the slot is
|
|
272
|
+
really unhealthy (a blink is not a state), finds the reserve's current address,
|
|
273
|
+
ADDS it (never removes), reads the list back until it took effect, and waits for
|
|
274
|
+
the slot. Outcomes: `healthy | not-network | already-allowed | fixed |
|
|
275
|
+
still-down | needs-rebuild`. `liveDeps` is UpCloud + Supabase; another pair of
|
|
276
|
+
providers is another `GuardDeps`.
|
|
277
|
+
|
|
278
|
+
The CI workflow for the guard, the replication setup and the runbook are a
|
|
279
|
+
Discovery playbook, not package code.
|
|
280
|
+
|
|
281
|
+
### 0.4.0 — at a real shop's size (components-F085.7, measured by VN Leker)
|
|
282
|
+
|
|
283
|
+
Measured against VN Leker's own off-prod pair (two PG17 servers, logical
|
|
284
|
+
replication, 308,153 rows, two machines writing through the switch):
|
|
285
|
+
|
|
286
|
+
| | 0.3.0 | 0.4.0 |
|
|
287
|
+
|---|---|---|
|
|
288
|
+
| queries held, switch to the reserve | 23,800 ms (aborted by the safety net) | **26 ms** |
|
|
289
|
+
| queries held, the way home | not reached | **612 ms** |
|
|
290
|
+
| acked writes lost / failed | — | 0 / 0 (3,240 writes) |
|
|
291
|
+
|
|
292
|
+
- **The baseline is no longer read under the hold.** `freezeBaseline` fixes the
|
|
293
|
+
reserve's instant with a REPEATABLE READ snapshot on a connection of its own
|
|
294
|
+
(milliseconds) and reads the rows through it after release. Until it is
|
|
295
|
+
written, `baselineAt` is null, so a way home cannot start on an old one.
|
|
296
|
+
- **The second pass home compares only what changed** since the first pass
|
|
297
|
+
began (`reconcile({ since: reserveHorizon(...) })`): rows whose `xmin` is at
|
|
298
|
+
or above the horizon, and deletes found by counting per table. Tables
|
|
299
|
+
without a primary key are still compared in full.
|
|
300
|
+
- **Identity columns.** The way home writes `GENERATED ALWAYS AS IDENTITY`
|
|
301
|
+
columns with `OVERRIDING SYSTEM VALUE` and leaves stored generated columns to
|
|
302
|
+
Postgres. **Sequences** are not replicated, so `syncSequences` moves every
|
|
303
|
+
identity/serial sequence on the side that starts taking writes up to its
|
|
304
|
+
column's max — under the hold, never backwards.
|
|
305
|
+
- **Behaviour change — pool size.** `createClient({ backend: 'postgres' })`
|
|
306
|
+
without `max` now gets the driver's default of **10** connections, as this
|
|
307
|
+
README always said. Until 0.3.0 it silently got ONE (`max: undefined` reached
|
|
308
|
+
postgres.js as «set»). If your database caps connections, pass `max`.
|
|
309
|
+
`freezeBaseline` refuses a pool of one with a reason instead of hanging.
|
|
310
|
+
|
|
144
311
|
## Migrating from 0.1.x
|
|
145
312
|
|
|
146
313
|
`createClient()` used to return `@libsql/client`'s own `Client`. It now returns
|
|
@@ -171,8 +338,11 @@ DB_SDK_TEST_PG_URL=postgres://… bun test
|
|
|
171
338
|
One contract suite runs the **same** cases against libSQL (a local file), a
|
|
172
339
|
**real** Postgres, and — when `DB_SDK_TEST_PG_POOLER_URL` is set — a real
|
|
173
340
|
Supabase transaction pooler. Without `DB_SDK_TEST_PG_URL` the suite fails rather than
|
|
174
|
-
skipping Postgres — a skipped transport reads as a green one.
|
|
175
|
-
|
|
341
|
+
skipping Postgres — a skipped transport reads as a green one. The switch tests
|
|
342
|
+
need a SECOND server at `DB_SDK_TEST_PG_URL_2` (two databases on one server hid
|
|
343
|
+
a cancel going to the wrong server). CI starts two Postgres 17 servers with
|
|
344
|
+
`wal_level=logical` and sets `DB_SDK_TEST_REQUIRE_LOGICAL=1`, so the replication
|
|
345
|
+
tests cannot be skipped there.
|
|
176
346
|
|
|
177
347
|
## License
|
|
178
348
|
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// src/backends/pg.ts
|
|
2
|
+
import { createRequire } from "module";
|
|
3
|
+
function parts(stmt) {
|
|
4
|
+
if (typeof stmt === "string") return [stmt, []];
|
|
5
|
+
return [stmt.sql, [...stmt.args ?? []]];
|
|
6
|
+
}
|
|
7
|
+
function toResult(res) {
|
|
8
|
+
const r = Array.isArray(res) ? res[res.length - 1] : res;
|
|
9
|
+
const columns = (r.fields ?? []).map((f) => f.name);
|
|
10
|
+
const rows = (r.rows ?? []).map((x) => ({ ...x }));
|
|
11
|
+
const isRead = r.command === "SELECT";
|
|
12
|
+
return { rows, columns, rowsAffected: isRead ? 0 : r.rowCount ?? 0 };
|
|
13
|
+
}
|
|
14
|
+
function loadPool(url, max) {
|
|
15
|
+
let pg;
|
|
16
|
+
try {
|
|
17
|
+
pg = createRequire(import.meta.url)("pg");
|
|
18
|
+
} catch {
|
|
19
|
+
throw new Error("@broberg/db-sdk: backend 'pg' needs the 'pg' package \u2014 npm i pg (or pass your own `pool`)");
|
|
20
|
+
}
|
|
21
|
+
return new pg.Pool({ connectionString: url, max });
|
|
22
|
+
}
|
|
23
|
+
function pgClient(cfg) {
|
|
24
|
+
let pool;
|
|
25
|
+
if (cfg.pool) pool = cfg.pool;
|
|
26
|
+
else {
|
|
27
|
+
const url = cfg.url ?? process.env.DATABASE_URL;
|
|
28
|
+
if (!url) throw new Error("@broberg/db-sdk: missing database url \u2014 set DATABASE_URL, pass url, or pass your own pool");
|
|
29
|
+
pool = loadPool(url, cfg.max);
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
transport: "postgres",
|
|
33
|
+
raw: pool,
|
|
34
|
+
async execute(stmt) {
|
|
35
|
+
const [text, args] = parts(stmt);
|
|
36
|
+
return toResult(await pool.query(text, args));
|
|
37
|
+
},
|
|
38
|
+
async batch(stmts) {
|
|
39
|
+
const client = await pool.connect();
|
|
40
|
+
try {
|
|
41
|
+
await client.query("begin");
|
|
42
|
+
const out = [];
|
|
43
|
+
for (const s of stmts) {
|
|
44
|
+
const [text, args] = parts(s);
|
|
45
|
+
out.push(toResult(await client.query(text, args)));
|
|
46
|
+
}
|
|
47
|
+
await client.query("commit");
|
|
48
|
+
return out;
|
|
49
|
+
} catch (e) {
|
|
50
|
+
try {
|
|
51
|
+
await client.query("rollback");
|
|
52
|
+
} catch (rb) {
|
|
53
|
+
e.rollbackError = rb;
|
|
54
|
+
}
|
|
55
|
+
throw e;
|
|
56
|
+
} finally {
|
|
57
|
+
client.release();
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
async close() {
|
|
61
|
+
if (!pool.ended) await pool.end();
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// src/backends/postgres.ts
|
|
67
|
+
import postgres from "postgres";
|
|
68
|
+
var PG_OPTIONS = { prepare: false };
|
|
69
|
+
function toResult2(res) {
|
|
70
|
+
const columns = (res.columns ?? []).map((c) => c.name);
|
|
71
|
+
const rows = Array.from(res, (r) => ({ ...r }));
|
|
72
|
+
const isRead = res.command === "SELECT";
|
|
73
|
+
return { rows, columns, rowsAffected: isRead ? 0 : res.count ?? 0 };
|
|
74
|
+
}
|
|
75
|
+
function parts2(stmt) {
|
|
76
|
+
if (typeof stmt === "string") return [stmt, []];
|
|
77
|
+
return [stmt.sql, [...stmt.args ?? []]];
|
|
78
|
+
}
|
|
79
|
+
function run(sql, stmt) {
|
|
80
|
+
const [text, args] = parts2(stmt);
|
|
81
|
+
return sql.unsafe(text, args, PG_OPTIONS);
|
|
82
|
+
}
|
|
83
|
+
function postgresClient(cfg) {
|
|
84
|
+
const url = cfg.url ?? process.env.DATABASE_URL;
|
|
85
|
+
if (!url) {
|
|
86
|
+
throw new Error("@broberg/db-sdk: missing database url \u2014 set DATABASE_URL or pass it explicitly");
|
|
87
|
+
}
|
|
88
|
+
const raw = postgres(url, { ...PG_OPTIONS, ...cfg.max !== void 0 ? { max: cfg.max } : {}, onnotice: () => {
|
|
89
|
+
} });
|
|
90
|
+
return {
|
|
91
|
+
transport: "postgres",
|
|
92
|
+
raw,
|
|
93
|
+
async execute(stmt) {
|
|
94
|
+
return toResult2(await run(raw, stmt));
|
|
95
|
+
},
|
|
96
|
+
// Postgres has no write-lock-up-front mode, so both BatchModes begin a
|
|
97
|
+
// plain transaction and the mode argument is not read.
|
|
98
|
+
async batch(stmts) {
|
|
99
|
+
const results = await raw.begin(async (tx) => {
|
|
100
|
+
const out = [];
|
|
101
|
+
for (const s of stmts) out.push(toResult2(await run(tx, s)));
|
|
102
|
+
return out;
|
|
103
|
+
});
|
|
104
|
+
return results;
|
|
105
|
+
},
|
|
106
|
+
async close() {
|
|
107
|
+
await raw.end();
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
async function postgresVersion(raw) {
|
|
112
|
+
const [row] = await raw.unsafe("show server_version", [], PG_OPTIONS);
|
|
113
|
+
return String(row?.server_version ?? "unknown");
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export {
|
|
117
|
+
toResult,
|
|
118
|
+
pgClient,
|
|
119
|
+
PG_OPTIONS,
|
|
120
|
+
toResult2,
|
|
121
|
+
postgresClient,
|
|
122
|
+
postgresVersion
|
|
123
|
+
};
|
|
124
|
+
//# sourceMappingURL=chunk-ONXYOFVT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/backends/pg.ts","../src/backends/postgres.ts"],"sourcesContent":["/**\n * node-postgres (`pg`) transport for @broberg/db-sdk (components-F085.6).\n *\n * Why a second Postgres driver: some apps cannot move — BID runs Better Auth,\n * whose kysely dialect takes a `pg.Pool` (it recognises one by `connect`). The\n * facade is the same as the postgres.js transport: same SQL dialect ($1), same\n * DbResult shape, `transport: 'postgres'`. `pg` is an OPTIONAL peer dependency:\n * it is loaded only when `backend: 'pg'` is asked for with a `url` — pass your\n * own `pool` and this file never imports it.\n */\nimport { createRequire } from 'node:module';\nimport type { Pool, PoolClient, QueryResult } from 'pg';\nimport type { DbClient, DbResult, PgConfig, Row, Statement } from '../types';\n\nfunction parts(stmt: Statement): [string, unknown[]] {\n if (typeof stmt === 'string') return [stmt, []];\n return [stmt.sql, [...(stmt.args ?? [])]];\n}\n\nexport function toResult(res: QueryResult | QueryResult[]): DbResult {\n // A multi-statement string answers an array; the facade reports the last, like a single statement.\n const r = Array.isArray(res) ? res[res.length - 1]! : res;\n const columns = (r.fields ?? []).map((f) => f.name);\n const rows = (r.rows ?? []).map((x) => ({ ...(x as Row) }));\n const isRead = r.command === 'SELECT';\n return { rows, columns, rowsAffected: isRead ? 0 : (r.rowCount ?? 0) };\n}\n\nfunction loadPool(url: string, max?: number): Pool {\n let pg: { Pool: new (cfg: { connectionString: string; max?: number }) => Pool };\n try {\n pg = createRequire(import.meta.url)('pg');\n } catch {\n throw new Error(\"@broberg/db-sdk: backend 'pg' needs the 'pg' package — npm i pg (or pass your own `pool`)\");\n }\n return new pg.Pool({ connectionString: url, max });\n}\n\nexport function pgClient(cfg: PgConfig): DbClient<Pool> {\n let pool: Pool;\n if (cfg.pool) pool = cfg.pool;\n else {\n const url = cfg.url ?? process.env.DATABASE_URL;\n if (!url) throw new Error('@broberg/db-sdk: missing database url — set DATABASE_URL, pass url, or pass your own pool');\n pool = loadPool(url, cfg.max);\n }\n return {\n transport: 'postgres',\n raw: pool,\n async execute(stmt) {\n const [text, args] = parts(stmt);\n return toResult(await pool.query(text, args));\n },\n async batch(stmts) {\n const client: PoolClient = await pool.connect();\n try {\n await client.query('begin');\n const out: DbResult[] = [];\n for (const s of stmts) {\n const [text, args] = parts(s);\n out.push(toResult(await client.query(text, args)));\n }\n await client.query('commit');\n return out;\n } catch (e) {\n // The original error is what the caller needs; a failed rollback is\n // reported alongside it rather than replacing it.\n try {\n await client.query('rollback');\n } catch (rb) {\n (e as Error & { rollbackError?: unknown }).rollbackError = rb;\n }\n throw e;\n } finally {\n client.release();\n }\n },\n async close() {\n if (!(pool as Pool & { ended?: boolean }).ended) await pool.end();\n },\n };\n}\n","/** PostgreSQL transport for @broberg/db-sdk — Supabase included. */\nimport postgres from 'postgres';\nimport type { Sql, TransactionSql } from 'postgres';\nimport type { DbClient, DbResult, PostgresConfig, Row, Statement } from '../types';\n\n/**\n * Prepared statements are OFF, deliberately, and a test fails if they come back.\n *\n * Supabase's connection pooler in transaction mode (port 6543) hands each\n * transaction to whichever server connection is free, so a statement prepared\n * on one is missing on the next. postgres.js prepares by default. With it on,\n * everything passes against a local Postgres and fails against Supabase —\n * green until production.\n */\nexport const PG_OPTIONS = { prepare: false } as const;\n\ntype PgResult = Awaited<ReturnType<Sql['unsafe']>>;\n\nexport function toResult(res: PgResult): DbResult {\n const columns = (res.columns ?? []).map((c) => c.name);\n const rows = Array.from(res, (r) => ({ ...(r as Row) }));\n // count is the command's row count; for a SELECT that is rows returned, which\n // the facade does not call \"affected\".\n const isRead = res.command === 'SELECT';\n return { rows, columns, rowsAffected: isRead ? 0 : (res.count ?? 0) };\n}\n\nfunction parts(stmt: Statement): [string, unknown[]] {\n if (typeof stmt === 'string') return [stmt, []];\n return [stmt.sql, [...(stmt.args ?? [])]];\n}\n\nfunction run(sql: Sql | TransactionSql, stmt: Statement): Promise<PgResult> {\n const [text, args] = parts(stmt);\n return sql.unsafe(text, args as never[], PG_OPTIONS);\n}\n\nexport function postgresClient(cfg: PostgresConfig): DbClient<Sql> {\n const url = cfg.url ?? process.env.DATABASE_URL;\n if (!url) {\n throw new Error('@broberg/db-sdk: missing database url — set DATABASE_URL or pass it explicitly');\n }\n // F085.7: `max` only when given. postgres.js reads an option by `k in o`, so\n // `max: undefined` was a pool of ONE connection (Array(undefined) has length\n // 1), not the driver's documented 10 — measured on vn-leker's switch, where\n // a reserved connection then left nothing for any other query.\n const raw = postgres(url, { ...PG_OPTIONS, ...(cfg.max !== undefined ? { max: cfg.max } : {}), onnotice: () => {} });\n return {\n transport: 'postgres',\n raw,\n async execute(stmt) {\n return toResult(await run(raw, stmt));\n },\n // Postgres has no write-lock-up-front mode, so both BatchModes begin a\n // plain transaction and the mode argument is not read.\n async batch(stmts) {\n const results = await raw.begin(async (tx) => {\n const out: DbResult[] = [];\n for (const s of stmts) out.push(toResult(await run(tx, s)));\n return out;\n });\n return results as DbResult[];\n },\n async close() {\n await raw.end();\n },\n };\n}\n\nexport async function postgresVersion(raw: Sql): Promise<string> {\n const [row] = await raw.unsafe('show server_version', [], PG_OPTIONS);\n return String((row as Row | undefined)?.server_version ?? 'unknown');\n}\n"],"mappings":";AAUA,SAAS,qBAAqB;AAI9B,SAAS,MAAM,MAAsC;AACnD,MAAI,OAAO,SAAS,SAAU,QAAO,CAAC,MAAM,CAAC,CAAC;AAC9C,SAAO,CAAC,KAAK,KAAK,CAAC,GAAI,KAAK,Q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S,KAAK,EAAE,GAAG,YAAY,GAAI,IAAI,QAAQ,SAAY,EAAE,KAAK,IAAI,IAAI,IAAI,CAAC,GAAI,UAAU,MAAM;AAAA,EAAC,EAAE,CAAC;AACnH,SAAO;AAAA,IACL,WAAW;AAAA,IACX;AAAA,IACA,MAAM,QAAQ,MAAM;AAClB,aAAOD,UAAS,MAAM,IAAI,KAAK,IAAI,CAAC;AAAA,IACtC;AAAA;AAAA;AAAA,IAGA,MAAM,MAAM,OAAO;AACjB,YAAM,UAAU,MAAM,IAAI,MAAM,OAAO,OAAO;AAC5C,cAAM,MAAkB,CAAC;AACzB,mBAAW,KAAK,MAAO,KAAI,KAAKA,UAAS,MAAM,IAAI,IAAI,CAAC,CAAC,CAAC;AAC1D,eAAO;AAAA,MACT,CAAC;AACD,aAAO;AAAA,IACT;AAAA,IACA,MAAM,QAAQ;AACZ,YAAM,IAAI,IAAI;AAAA,IAChB;AAAA,EACF;AACF;AAEA,eAAsB,gBAAgB,KAA2B;AAC/D,QAAM,CAAC,GAAG,IAAI,MAAM,IAAI,OAAO,uBAAuB,CAAC,GAAG,UAAU;AACpE,SAAO,OAAQ,KAAyB,kBAAkB,SAAS;AACrE;","names":["toResult","parts"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,109 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { L as LibsqlConfig, D as DbClient, P as PostgresConfig, a as PgConfig, R as ReplicaConfig, b as ReplicaClient, H as Health } from './types-9Y21zZWt.js';
|
|
2
|
+
export { B as BatchMode, C as Client, c as DbConfig, d as DbResult, e as Row, S as Statement, T as Transport } from './types-9Y21zZWt.js';
|
|
3
|
+
import { Pool } from 'pg';
|
|
4
|
+
import { Client } from '@libsql/client';
|
|
2
5
|
export { Client as LibsqlClient } from '@libsql/client';
|
|
3
6
|
import { Sql } from 'postgres';
|
|
4
7
|
export { Sql } from 'postgres';
|
|
5
8
|
|
|
6
|
-
/** Shared types for @broberg/db-sdk. */
|
|
7
|
-
|
|
8
|
-
/** Which database transport backs a client. */
|
|
9
|
-
type Transport = 'libsql' | 'postgres';
|
|
10
|
-
/** One row, keyed by column name. Duplicate column names: the last one wins. */
|
|
11
|
-
type Row = Record<string, unknown>;
|
|
12
|
-
/** The result of one statement — the same shape from every transport. */
|
|
13
|
-
interface DbResult {
|
|
14
|
-
rows: Row[];
|
|
15
|
-
columns: string[];
|
|
16
|
-
/** Rows written by INSERT/UPDATE/DELETE. 0 for reads and DDL. */
|
|
17
|
-
rowsAffected: number;
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* A statement: bare SQL, or SQL plus positional args.
|
|
21
|
-
*
|
|
22
|
-
* THE SQL IS PASSED THROUGH UNTOUCHED — the facade unifies the transport, not
|
|
23
|
-
* the dialect. libSQL takes `?` placeholders, Postgres takes `$1`. Rewriting one
|
|
24
|
-
* into the other would also rewrite a `?` inside a string literal or a JSON
|
|
25
|
-
* operator, so we do not.
|
|
26
|
-
*/
|
|
27
|
-
type Statement = string | {
|
|
28
|
-
sql: string;
|
|
29
|
-
args?: readonly unknown[];
|
|
30
|
-
};
|
|
31
|
-
/**
|
|
32
|
-
* How the batch's transaction begins. `write` takes the write lock up front;
|
|
33
|
-
* `deferred` takes it at the first write.
|
|
34
|
-
*
|
|
35
|
-
* There is NO `read` mode, on purpose. Measured 23/9 2026 by the contract suite:
|
|
36
|
-
* a libSQL `read` batch against a local file executed an INSERT, while Postgres
|
|
37
|
-
* refused it. A mode that is read-only on one transport and not the other is a
|
|
38
|
-
* promise the facade cannot keep.
|
|
39
|
-
*/
|
|
40
|
-
type BatchMode = 'write' | 'deferred';
|
|
41
|
-
/**
|
|
42
|
-
* The one client surface every transport answers. `Raw` is the escape hatch:
|
|
43
|
-
* the underlying driver's own client, for what the facade does not cover
|
|
44
|
-
* (`LISTEN/NOTIFY`, libSQL `sync()`, streaming). Without it a consumer who needs
|
|
45
|
-
* one transport-specific call would route around the whole facade.
|
|
46
|
-
*/
|
|
47
|
-
interface DbClient<Raw = unknown> {
|
|
48
|
-
/** The transport that answers — read it here, not from your own config. */
|
|
49
|
-
readonly transport: Transport;
|
|
50
|
-
/** The underlying driver client. */
|
|
51
|
-
readonly raw: Raw;
|
|
52
|
-
execute(stmt: Statement): Promise<DbResult>;
|
|
53
|
-
/** All statements in ONE transaction: all apply or none do. */
|
|
54
|
-
batch(stmts: readonly Statement[], mode?: BatchMode): Promise<DbResult[]>;
|
|
55
|
-
close(): Promise<void>;
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* The 0.1.x name for the client type. It is now the facade, not
|
|
59
|
-
* `@libsql/client`'s own `Client` — use `DbClient`.
|
|
60
|
-
* @deprecated since 0.2.0
|
|
61
|
-
*/
|
|
62
|
-
type Client = DbClient;
|
|
63
|
-
/** Remote libSQL / Turso. */
|
|
64
|
-
interface LibsqlConfig {
|
|
65
|
-
backend?: 'libsql';
|
|
66
|
-
/** `libsql://…` (remote) or `file:…` (local). Default: `$TURSO_DATABASE_URL`. */
|
|
67
|
-
url?: string;
|
|
68
|
-
/** Default: `$TURSO_AUTH_TOKEN`. */
|
|
69
|
-
authToken?: string;
|
|
70
|
-
}
|
|
71
|
-
/** PostgreSQL, including Supabase. */
|
|
72
|
-
interface PostgresConfig {
|
|
73
|
-
backend: 'postgres';
|
|
74
|
-
/** `postgres://…`. Default: `$DATABASE_URL`. */
|
|
75
|
-
url?: string;
|
|
76
|
-
/** Max pooled connections. Default: the driver's (10). */
|
|
77
|
-
max?: number;
|
|
78
|
-
}
|
|
79
|
-
type DbConfig = LibsqlConfig | PostgresConfig;
|
|
80
|
-
/**
|
|
81
|
-
* Embedded-replica config. An embedded replica is a libSQL concept with no
|
|
82
|
-
* Postgres counterpart, so `backend` only accepts `'libsql'` — asking for a
|
|
83
|
-
* Postgres replica is a type error, not a runtime throw.
|
|
84
|
-
*/
|
|
85
|
-
interface ReplicaConfig {
|
|
86
|
-
backend?: 'libsql';
|
|
87
|
-
/** Local file path for the replica DB (e.g. `/data/buddy.db`). */
|
|
88
|
-
path: string;
|
|
89
|
-
/** Remote primary to sync from. Default: `$TURSO_DATABASE_URL`. */
|
|
90
|
-
syncUrl?: string;
|
|
91
|
-
/** Default: `$TURSO_AUTH_TOKEN`. */
|
|
92
|
-
authToken?: string;
|
|
93
|
-
/** Auto-sync interval in seconds. Omit to sync manually via `sync()`. */
|
|
94
|
-
syncIntervalSeconds?: number;
|
|
95
|
-
}
|
|
96
|
-
/** A replica client: the facade plus `sync()`, which pulls from the primary. */
|
|
97
|
-
interface ReplicaClient extends DbClient<Client$1> {
|
|
98
|
-
sync(): Promise<void>;
|
|
99
|
-
}
|
|
100
|
-
/** What `health()` measured. `transport` is who ANSWERED, not who was configured. */
|
|
101
|
-
interface Health {
|
|
102
|
-
ok: true;
|
|
103
|
-
transport: Transport;
|
|
104
|
-
version: string;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
9
|
/**
|
|
108
10
|
* @broberg/db-sdk — the broberg.ai fleet's shared database client.
|
|
109
11
|
*
|
|
@@ -123,8 +25,9 @@ interface Health {
|
|
|
123
25
|
* - libSQL/Turso (default): reads `TURSO_DATABASE_URL` + `TURSO_AUTH_TOKEN`.
|
|
124
26
|
* - `{ backend: 'postgres' }`: reads `DATABASE_URL`.
|
|
125
27
|
*/
|
|
126
|
-
declare function createClient(cfg?: LibsqlConfig): DbClient<Client
|
|
28
|
+
declare function createClient(cfg?: LibsqlConfig): DbClient<Client>;
|
|
127
29
|
declare function createClient(cfg: PostgresConfig): DbClient<Sql>;
|
|
30
|
+
declare function createClient(cfg: PgConfig): DbClient<Pool>;
|
|
128
31
|
/**
|
|
129
32
|
* Create an EMBEDDED REPLICA: a local SQLite file kept in sync with a remote
|
|
130
33
|
* Turso primary. Reads hit the local file; writes forward to the primary;
|
|
@@ -139,4 +42,4 @@ declare function createReplica(cfg: ReplicaConfig): ReplicaClient;
|
|
|
139
42
|
*/
|
|
140
43
|
declare function health(client: DbClient): Promise<Health>;
|
|
141
44
|
|
|
142
|
-
export {
|
|
45
|
+
export { DbClient, Health, LibsqlConfig, PgConfig, PostgresConfig, ReplicaClient, ReplicaConfig, createClient, createReplica, health };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
import {
|
|
2
|
+
pgClient,
|
|
3
|
+
postgresClient,
|
|
4
|
+
postgresVersion
|
|
5
|
+
} from "./chunk-ONXYOFVT.js";
|
|
6
|
+
|
|
1
7
|
// src/backends/libsql.ts
|
|
2
8
|
import { createClient as createLibsqlClient } from "@libsql/client";
|
|
3
9
|
function requireUrl(url, what) {
|
|
@@ -62,62 +68,13 @@ async function libsqlVersion(raw) {
|
|
|
62
68
|
return String(res.rows[0]?.v ?? "unknown");
|
|
63
69
|
}
|
|
64
70
|
|
|
65
|
-
// src/backends/postgres.ts
|
|
66
|
-
import postgres from "postgres";
|
|
67
|
-
var PG_OPTIONS = { prepare: false };
|
|
68
|
-
function toResult2(res) {
|
|
69
|
-
const columns = (res.columns ?? []).map((c) => c.name);
|
|
70
|
-
const rows = Array.from(res, (r) => ({ ...r }));
|
|
71
|
-
const isRead = res.command === "SELECT";
|
|
72
|
-
return { rows, columns, rowsAffected: isRead ? 0 : res.count ?? 0 };
|
|
73
|
-
}
|
|
74
|
-
function parts(stmt) {
|
|
75
|
-
if (typeof stmt === "string") return [stmt, []];
|
|
76
|
-
return [stmt.sql, [...stmt.args ?? []]];
|
|
77
|
-
}
|
|
78
|
-
function run(sql, stmt) {
|
|
79
|
-
const [text, args] = parts(stmt);
|
|
80
|
-
return sql.unsafe(text, args, PG_OPTIONS);
|
|
81
|
-
}
|
|
82
|
-
function postgresClient(cfg) {
|
|
83
|
-
const url = cfg.url ?? process.env.DATABASE_URL;
|
|
84
|
-
if (!url) {
|
|
85
|
-
throw new Error("@broberg/db-sdk: missing database url \u2014 set DATABASE_URL or pass it explicitly");
|
|
86
|
-
}
|
|
87
|
-
const raw = postgres(url, { ...PG_OPTIONS, max: cfg.max, onnotice: () => {
|
|
88
|
-
} });
|
|
89
|
-
return {
|
|
90
|
-
transport: "postgres",
|
|
91
|
-
raw,
|
|
92
|
-
async execute(stmt) {
|
|
93
|
-
return toResult2(await run(raw, stmt));
|
|
94
|
-
},
|
|
95
|
-
// Postgres has no write-lock-up-front mode, so both BatchModes begin a
|
|
96
|
-
// plain transaction and the mode argument is not read.
|
|
97
|
-
async batch(stmts) {
|
|
98
|
-
const results = await raw.begin(async (tx) => {
|
|
99
|
-
const out = [];
|
|
100
|
-
for (const s of stmts) out.push(toResult2(await run(tx, s)));
|
|
101
|
-
return out;
|
|
102
|
-
});
|
|
103
|
-
return results;
|
|
104
|
-
},
|
|
105
|
-
async close() {
|
|
106
|
-
await raw.end();
|
|
107
|
-
}
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
async function postgresVersion(raw) {
|
|
111
|
-
const [row] = await raw.unsafe("show server_version", [], PG_OPTIONS);
|
|
112
|
-
return String(row?.server_version ?? "unknown");
|
|
113
|
-
}
|
|
114
|
-
|
|
115
71
|
// src/index.ts
|
|
116
72
|
function createClient(cfg = {}) {
|
|
117
73
|
const backend = cfg.backend ?? "libsql";
|
|
118
74
|
if (cfg.backend === "postgres") return postgresClient(cfg);
|
|
75
|
+
if (cfg.backend === "pg") return pgClient(cfg);
|
|
119
76
|
if (cfg.backend === void 0 || cfg.backend === "libsql") return libsqlClient(cfg);
|
|
120
|
-
throw new Error(`@broberg/db-sdk: unknown backend '${backend}' \u2014 expected 'libsql' or '
|
|
77
|
+
throw new Error(`@broberg/db-sdk: unknown backend '${backend}' \u2014 expected 'libsql', 'postgres' or 'pg'`);
|
|
121
78
|
}
|
|
122
79
|
function createReplica(cfg) {
|
|
123
80
|
const backend = cfg.backend ?? "libsql";
|
|
@@ -128,6 +85,10 @@ function createReplica(cfg) {
|
|
|
128
85
|
}
|
|
129
86
|
async function health(client) {
|
|
130
87
|
if (client.transport === "postgres") {
|
|
88
|
+
if (typeof client.raw !== "function") {
|
|
89
|
+
const r = await client.execute("show server_version");
|
|
90
|
+
return { ok: true, transport: "postgres", version: String(r.rows[0]?.server_version ?? "unknown") };
|
|
91
|
+
}
|
|
131
92
|
return { ok: true, transport: "postgres", version: await postgresVersion(client.raw) };
|
|
132
93
|
}
|
|
133
94
|
return { ok: true, transport: "libsql", version: await libsqlVersion(client.raw) };
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/backends/libsql.ts","../src/backends/postgres.ts","../src/index.ts"],"sourcesContent":["/** libSQL / Turso transport for @broberg/db-sdk. */\nimport { createClient as createLibsqlClient } from '@libsql/client';\nimport type { Client as LibsqlClient, InStatement, InValue, ResultSet } from '@libsql/client';\nimport type { BatchMode, DbClient, DbResult, LibsqlConfig, ReplicaClient, ReplicaConfig, Row, Statement } from '../types';\n\nfunction requireUrl(url: string | undefined, what: string): string {\n if (!url) {\n throw new Error(`@broberg/db-sdk: missing ${what} — set TURSO_DATABASE_URL or pass it explicitly`);\n }\n return url;\n}\n\nfunction toLibsql(stmt: Statement): InStatement {\n if (typeof stmt === 'string') return stmt;\n return { sql: stmt.sql, args: (stmt.args ?? []) as InValue[] };\n}\n\n/** libSQL rows are array-like objects; the facade hands out plain objects. */\nfunction toResult(rs: ResultSet): DbResult {\n const rows: Row[] = rs.rows.map((r) => {\n const row: Row = {};\n rs.columns.forEach((c, i) => {\n row[c] = r[i];\n });\n return row;\n });\n return { rows, columns: [...rs.columns], rowsAffected: rs.rowsAffected };\n}\n\nfunction wrap(raw: LibsqlClient): DbClient<LibsqlClient> {\n return {\n transport: 'libsql',\n raw,\n async execute(stmt) {\n return toResult(await raw.execute(toLibsql(stmt)));\n },\n async batch(stmts, mode: BatchMode = 'deferred') {\n const results = await raw.batch(stmts.map(toLibsql), mode);\n return results.map(toResult);\n },\n async close() {\n raw.close();\n },\n };\n}\n\n/** Remote libSQL/Turso client. */\nexport function libsqlClient(cfg: LibsqlConfig): DbClient<LibsqlClient> {\n const url = requireUrl(cfg.url ?? process.env.TURSO_DATABASE_URL, 'database url');\n const authToken = cfg.authToken ?? process.env.TURSO_AUTH_TOKEN;\n return wrap(createLibsqlClient({ url, authToken }));\n}\n\n/** Embedded replica: a local SQLite file kept in sync with the remote primary. */\nexport function libsqlReplica(cfg: ReplicaConfig): ReplicaClient {\n const syncUrl = requireUrl(cfg.syncUrl ?? process.env.TURSO_DATABASE_URL, 'sync url');\n const authToken = cfg.authToken ?? process.env.TURSO_AUTH_TOKEN;\n const raw = createLibsqlClient({\n url: `file:${cfg.path}`,\n syncUrl,\n authToken,\n syncInterval: cfg.syncIntervalSeconds,\n });\n return {\n ...wrap(raw),\n async sync() {\n await raw.sync();\n },\n };\n}\n\nexport async function libsqlVersion(raw: LibsqlClient): Promise<string> {\n const res = await raw.execute('select sqlite_version() as v');\n return String(res.rows[0]?.v ?? 'unknown');\n}\n","/** PostgreSQL transport for @broberg/db-sdk — Supabase included. */\nimport postgres from 'postgres';\nimport type { Sql, TransactionSql } from 'postgres';\nimport type { DbClient, DbResult, PostgresConfig, Row, Statement } from '../types';\n\n/**\n * Prepared statements are OFF, deliberately, and a test fails if they come back.\n *\n * Supabase's connection pooler in transaction mode (port 6543) hands each\n * transaction to whichever server connection is free, so a statement prepared\n * on one is missing on the next. postgres.js prepares by default. With it on,\n * everything passes against a local Postgres and fails against Supabase —\n * green until production.\n */\nexport const PG_OPTIONS = { prepare: false } as const;\n\ntype PgResult = Awaited<ReturnType<Sql['unsafe']>>;\n\nfunction toResult(res: PgResult): DbResult {\n const columns = (res.columns ?? []).map((c) => c.name);\n const rows = Array.from(res, (r) => ({ ...(r as Row) }));\n // count is the command's row count; for a SELECT that is rows returned, which\n // the facade does not call \"affected\".\n const isRead = res.command === 'SELECT';\n return { rows, columns, rowsAffected: isRead ? 0 : (res.count ?? 0) };\n}\n\nfunction parts(stmt: Statement): [string, unknown[]] {\n if (typeof stmt === 'string') return [stmt, []];\n return [stmt.sql, [...(stmt.args ?? [])]];\n}\n\nfunction run(sql: Sql | TransactionSql, stmt: Statement): Promise<PgResult> {\n const [text, args] = parts(stmt);\n return sql.unsafe(text, args as never[], PG_OPTIONS);\n}\n\nexport function postgresClient(cfg: PostgresConfig): DbClient<Sql> {\n const url = cfg.url ?? process.env.DATABASE_URL;\n if (!url) {\n throw new Error('@broberg/db-sdk: missing database url — set DATABASE_URL or pass it explicitly');\n }\n const raw = postgres(url, { ...PG_OPTIONS, max: cfg.max, onnotice: () => {} });\n return {\n transport: 'postgres',\n raw,\n async execute(stmt) {\n return toResult(await run(raw, stmt));\n },\n // Postgres has no write-lock-up-front mode, so both BatchModes begin a\n // plain transaction and the mode argument is not read.\n async batch(stmts) {\n const results = await raw.begin(async (tx) => {\n const out: DbResult[] = [];\n for (const s of stmts) out.push(toResult(await run(tx, s)));\n return out;\n });\n return results as DbResult[];\n },\n async close() {\n await raw.end();\n },\n };\n}\n\nexport async function postgresVersion(raw: Sql): Promise<string> {\n const [row] = await raw.unsafe('show server_version', [], PG_OPTIONS);\n return String((row as Row | undefined)?.server_version ?? 'unknown');\n}\n","/**\n * @broberg/db-sdk — the broberg.ai fleet's shared database client.\n *\n * One facade over two transports: libSQL/Turso and PostgreSQL (Supabase\n * included). `createClient` returns the same `DbClient` from both, so switching\n * transport is a config change at the call to `createClient` — for the\n * CONNECTION. The SQL itself is passed through untouched: libSQL takes `?`,\n * Postgres takes `$1`, and the facade does not translate between them.\n *\n * Intentionally THIN: a client, an embedded-replica client (libSQL only), and a\n * health probe. ORM, schema and migrations stay in the consumer.\n */\nimport type { LibsqlClient, Sql } from './types';\nimport type { DbClient, Health, LibsqlConfig, PostgresConfig, ReplicaClient, ReplicaConfig } from './types';\nimport { libsqlClient, libsqlReplica, libsqlVersion } from './backends/libsql';\nimport { postgresClient, postgresVersion } from './backends/postgres';\n\nexport type {\n BatchMode,\n Client,\n DbClient,\n DbConfig,\n DbResult,\n Health,\n LibsqlClient,\n LibsqlConfig,\n PostgresConfig,\n ReplicaClient,\n ReplicaConfig,\n Row,\n Sql,\n Statement,\n Transport,\n} from './types';\n\n/**\n * Create a client against a REMOTE database.\n *\n * - libSQL/Turso (default): reads `TURSO_DATABASE_URL` + `TURSO_AUTH_TOKEN`.\n * - `{ backend: 'postgres' }`: reads `DATABASE_URL`.\n */\nexport function createClient(cfg?: LibsqlConfig): DbClient<LibsqlClient>;\nexport function createClient(cfg: PostgresConfig): DbClient<Sql>;\nexport function createClient(cfg: LibsqlConfig | PostgresConfig = {}): DbClient<LibsqlClient> | DbClient<Sql> {\n const backend: string = cfg.backend ?? 'libsql';\n if (cfg.backend === 'postgres') return postgresClient(cfg);\n if (cfg.backend === undefined || cfg.backend === 'libsql') return libsqlClient(cfg);\n throw new Error(`@broberg/db-sdk: unknown backend '${backend}' — expected 'libsql' or 'postgres'`);\n}\n\n/**\n * Create an EMBEDDED REPLICA: a local SQLite file kept in sync with a remote\n * Turso primary. Reads hit the local file; writes forward to the primary;\n * `sync()` (or `syncIntervalSeconds`) pulls the latest. libSQL only — there is\n * no Postgres counterpart, and the config type says so.\n */\nexport function createReplica(cfg: ReplicaConfig): ReplicaClient {\n const backend: string = cfg.backend ?? 'libsql';\n if (backend !== 'libsql') {\n throw new Error(`@broberg/db-sdk: embedded replicas are libSQL-only, got backend '${backend}'`);\n }\n return libsqlReplica(cfg);\n}\n\n/**\n * Liveness + version probe. Asks the transport itself and reports which one\n * answered — read `transport` here rather than inferring it from your config.\n * Throws if the database cannot be reached.\n */\nexport async function health(client: DbClient): Promise<Health> {\n if (client.transport === 'postgres') {\n return { ok: true, transport: 'postgres', version: await postgresVersion(client.raw as Sql) };\n }\n return { ok: true, transport: 'libsql', version: await libsqlVersion(client.raw as LibsqlClient) };\n}\n"],"mappings":";AACA,SAAS,gBAAgB,0BAA0B;AAInD,SAAS,WAAW,KAAyB,MAAsB;AACjE,MAAI,CAAC,KAAK;AACR,UAAM,IAAI,MAAM,4BAA4B,IAAI,sDAAiD;AAAA,EACnG;AACA,SAAO;AACT;AAEA,SAAS,SAAS,MAA8B;AA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","../src/index.ts"],"sourcesContent":["/** libSQL / Turso transport for @broberg/db-sdk. */\nimport { createClient as createLibsqlClient } from '@libsql/client';\nimport type { Client as LibsqlClient, InStatement, InValue, ResultSet } from '@libsql/client';\nimport type { BatchMode, DbClient, DbResult, LibsqlConfig, ReplicaClient, ReplicaConfig, Row, Statement } from '../types';\n\nfunction requireUrl(url: string | undefined, what: string): string {\n if (!url) {\n throw new Error(`@broberg/db-sdk: missing ${what} — set TURSO_DATABASE_URL or pass it explicitly`);\n }\n return url;\n}\n\nfunction toLibsql(stmt: Statement): InStatement {\n if (typeof stmt === 'string') return stmt;\n return { sql: stmt.sql, args: (stmt.args ?? []) as InValue[] };\n}\n\n/** libSQL rows are array-like objects; the facade hands out plain objects. */\nfunction toResult(rs: ResultSet): DbResult {\n const rows: Row[] = rs.rows.map((r) => {\n const row: Row = {};\n rs.columns.forEach((c, i) => {\n row[c] = r[i];\n });\n return row;\n });\n return { rows, columns: [...rs.columns], rowsAffected: rs.rowsAffected };\n}\n\nfunction wrap(raw: LibsqlClient): DbClient<LibsqlClient> {\n return {\n transport: 'libsql',\n raw,\n async execute(stmt) {\n return toResult(await raw.execute(toLibsql(stmt)));\n },\n async batch(stmts, mode: BatchMode = 'deferred') {\n const results = await raw.batch(stmts.map(toLibsql), mode);\n return results.map(toResult);\n },\n async close() {\n raw.close();\n },\n };\n}\n\n/** Remote libSQL/Turso client. */\nexport function libsqlClient(cfg: LibsqlConfig): DbClient<LibsqlClient> {\n const url = requireUrl(cfg.url ?? process.env.TURSO_DATABASE_URL, 'database url');\n const authToken = cfg.authToken ?? process.env.TURSO_AUTH_TOKEN;\n return wrap(createLibsqlClient({ url, authToken }));\n}\n\n/** Embedded replica: a local SQLite file kept in sync with the remote primary. */\nexport function libsqlReplica(cfg: ReplicaConfig): ReplicaClient {\n const syncUrl = requireUrl(cfg.syncUrl ?? process.env.TURSO_DATABASE_URL, 'sync url');\n const authToken = cfg.authToken ?? process.env.TURSO_AUTH_TOKEN;\n const raw = createLibsqlClient({\n url: `file:${cfg.path}`,\n syncUrl,\n authToken,\n syncInterval: cfg.syncIntervalSeconds,\n });\n return {\n ...wrap(raw),\n async sync() {\n await raw.sync();\n },\n };\n}\n\nexport async function libsqlVersion(raw: LibsqlClient): Promise<string> {\n const res = await raw.execute('select sqlite_version() as v');\n return String(res.rows[0]?.v ?? 'unknown');\n}\n","/**\n * @broberg/db-sdk — the broberg.ai fleet's shared database client.\n *\n * One facade over two transports: libSQL/Turso and PostgreSQL (Supabase\n * included). `createClient` returns the same `DbClient` from both, so switching\n * transport is a config change at the call to `createClient` — for the\n * CONNECTION. The SQL itself is passed through untouched: libSQL takes `?`,\n * Postgres takes `$1`, and the facade does not translate between them.\n *\n * Intentionally THIN: a client, an embedded-replica client (libSQL only), and a\n * health probe. ORM, schema and migrations stay in the consumer.\n */\nimport type { LibsqlClient, Sql } from './types';\nimport type { DbClient, Health, LibsqlConfig, PgConfig, PostgresConfig, ReplicaClient, ReplicaConfig } from './types';\nimport type { Pool as PgPool } from 'pg';\nimport { pgClient } from './backends/pg';\nimport { libsqlClient, libsqlReplica, libsqlVersion } from './backends/libsql';\nimport { postgresClient, postgresVersion } from './backends/postgres';\n\nexport type {\n BatchMode,\n Client,\n DbClient,\n DbConfig,\n DbResult,\n Health,\n LibsqlClient,\n LibsqlConfig,\n PgConfig,\n PostgresConfig,\n ReplicaClient,\n ReplicaConfig,\n Row,\n Sql,\n Statement,\n Transport,\n} from './types';\n\n/**\n * Create a client against a REMOTE database.\n *\n * - libSQL/Turso (default): reads `TURSO_DATABASE_URL` + `TURSO_AUTH_TOKEN`.\n * - `{ backend: 'postgres' }`: reads `DATABASE_URL`.\n */\nexport function createClient(cfg?: LibsqlConfig): DbClient<LibsqlClient>;\nexport function createClient(cfg: PostgresConfig): DbClient<Sql>;\nexport function createClient(cfg: PgConfig): DbClient<PgPool>;\nexport function createClient(cfg: LibsqlConfig | PostgresConfig | PgConfig = {}): DbClient<LibsqlClient> | DbClient<Sql> | DbClient<PgPool> {\n const backend: string = cfg.backend ?? 'libsql';\n if (cfg.backend === 'postgres') return postgresClient(cfg);\n if (cfg.backend === 'pg') return pgClient(cfg);\n if (cfg.backend === undefined || cfg.backend === 'libsql') return libsqlClient(cfg);\n throw new Error(`@broberg/db-sdk: unknown backend '${backend}' — expected 'libsql', 'postgres' or 'pg'`);\n}\n\n/**\n * Create an EMBEDDED REPLICA: a local SQLite file kept in sync with a remote\n * Turso primary. Reads hit the local file; writes forward to the primary;\n * `sync()` (or `syncIntervalSeconds`) pulls the latest. libSQL only — there is\n * no Postgres counterpart, and the config type says so.\n */\nexport function createReplica(cfg: ReplicaConfig): ReplicaClient {\n const backend: string = cfg.backend ?? 'libsql';\n if (backend !== 'libsql') {\n throw new Error(`@broberg/db-sdk: embedded replicas are libSQL-only, got backend '${backend}'`);\n }\n return libsqlReplica(cfg);\n}\n\n/**\n * Liveness + version probe. Asks the transport itself and reports which one\n * answered — read `transport` here rather than inferring it from your config.\n * Throws if the database cannot be reached.\n */\nexport async function health(client: DbClient): Promise<Health> {\n if (client.transport === 'postgres') {\n if (typeof client.raw !== 'function') {\n // pg.Pool (an object) rather than postgres.js (a tagged-template function).\n const r = await client.execute('show server_version');\n return { ok: true, transport: 'postgres', version: String(r.rows[0]?.server_version ?? 'unknown') };\n }\n return { ok: true, transport: 'postgres', version: await postgresVersion(client.raw as Sql) };\n }\n return { ok: true, transport: 'libsql', version: await libsqlVersion(client.raw as LibsqlClient) };\n}\n"],"mappings":";;;;;;;AACA,SAAS,gBAAgB,0BAA0B;AAInD,SAAS,WAAW,KAAyB,MAAsB;AACjE,MAAI,CAAC,KAAK;AACR,UAAM,IAAI,MAAM,4BAA4B,IAAI,sDAAiD;AAAA,EACnG;AACA,SAAO;AACT;AAEA,SAAS,SAAS,MAA8B;AAC9C,MAAI,OAAO,SAAS,SAAU,QAAO;AACrC,SAAO,EAAE,KAAK,KAAK,KAAK,MAAO,KAAK,QAAQ,CAAC,EAAgB;AAC/D;AAG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