@voltro/database 0.64.0 → 0.65.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/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { $ as e, $t as t, A as n, At as r, B as i, Bt as a, C as o, Ct as s, D as c, Dt as l, E as u, Et as d, F as f, Ft as p, G as m, Gt as h, H as g, Ht as ee, I as te, It as ne, J as re, Jt as _, K as ie, Kt as ae, L as v, Lt as oe, M as y, Mt as se, N as b, Nt as ce, O as le, Ot as ue, P as de, Pt as fe, Q as pe, Qt as me, R as he, Rt as ge, S as _e, St as ve, T as ye, Tt as be, U as xe, Ut as Se, V as Ce, Vt as we, W as Te, Wt as Ee, X as De, Xt as x, Y as Oe, Yt as ke, Z as S, Zt as Ae, _ as je, _t as Me, a as Ne, an as C, at as Pe, b as Fe, bt as Ie, c as Le, ct as w, d as Re, dt as ze, en as Be, et as Ve, f as He, ft as Ue, g as We, gt as Ge, h as Ke, ht as qe, i as Je, in as Ye, it as Xe, j as Ze, jt as Qe, k as $e, kt as et, l as tt, lt as nt, m as rt, mt as it, n as at, nn as ot, nt as st, o as ct, on as T, ot as lt, p as ut, pt as dt, q as ft, qt as E, r as pt, rn as mt, rt as ht, s as gt, sn as _t, st as vt, t as yt, tn as bt, tt as xt, u as St, ut as Ct, v as wt, vt as Tt, w as Et, wt as Dt, x as Ot, xt as kt, y as D, yt as At, z as jt, zt as Mt } from "./frameworkLiveTables-BURogL9N.js";
2
2
  import { a as Nt, i as Pt, n as Ft, o as It, r as Lt, s as Rt, t as zt } from "./wire-B28cPjEp.js";
3
- import { Cause as Bt, Chunk as Vt, Data as Ht, Effect as O, Exit as Ut, Metric as k, MetricBoundaries as Wt, Option as A, Runtime as Gt, Schedule as Kt, Schema as j, Stream as qt } from "effect";
4
- import { createHash as Jt } from "node:crypto";
5
- import { AsyncLocalStorage as Yt } from "node:async_hooks";
6
- import { TransactionConnection as Xt } from "@effect/sql/SqlClient";
7
- import { ansi as M } from "@voltro/logger";
8
- import { SqlClient as Zt } from "@effect/sql";
3
+ import { Cause as O, Chunk as Bt, Data as Vt, Effect as k, Exit as Ht, Metric as A, MetricBoundaries as Ut, Option as j, Runtime as Wt, Schedule as Gt, Schema as M, Stream as Kt } from "effect";
4
+ import { createHash as qt } from "node:crypto";
5
+ import { AsyncLocalStorage as Jt } from "node:async_hooks";
6
+ import { TransactionConnection as Yt } from "@effect/sql/SqlClient";
7
+ import { ansi as N } from "@voltro/logger";
8
+ import { SqlClient as Xt } from "@effect/sql";
9
9
  //#region src/actorSnapshot.ts
10
- var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n) => {
10
+ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n) => {
11
11
  if (t != null && t !== "") try {
12
12
  let r = (await e.query({
13
13
  table: "actors",
@@ -23,20 +23,20 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
23
23
  }))[0];
24
24
  return r === void 0 ? void 0 : {
25
25
  id: t,
26
- type: Qt(r.kind) ?? n,
27
- displayName: Qt(r.displayName),
28
- email: Qt(r.email)
26
+ type: Zt(r.kind) ?? n,
27
+ displayName: Zt(r.displayName),
28
+ email: Zt(r.email)
29
29
  };
30
30
  } catch {
31
31
  return;
32
32
  }
33
- }, en = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", tn = (e) => {
33
+ }, $t = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", en = (e) => {
34
34
  let t = [];
35
35
  for (let [n, r] of Object.entries(e.fields)) r.type === "array" && t.push(n);
36
36
  return t;
37
- }, nn = (e, t, n) => {
38
- if (!en(n) || !t) return e;
39
- let r = tn(t);
37
+ }, tn = (e, t, n) => {
38
+ if (!$t(n) || !t) return e;
39
+ let r = en(t);
40
40
  if (r.length === 0) return e;
41
41
  let i = { ...e };
42
42
  for (let e of r) {
@@ -44,9 +44,9 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
44
44
  Array.isArray(t) && (i[e] = JSON.stringify(t));
45
45
  }
46
46
  return i;
47
- }, rn = (e, t, n) => {
48
- if (!en(n) || !t) return e;
49
- let r = tn(t);
47
+ }, nn = (e, t, n) => {
48
+ if (!$t(n) || !t) return e;
49
+ let r = en(t);
50
50
  return r.length === 0 ? e : e.map((e) => {
51
51
  let t;
52
52
  for (let n of r) {
@@ -58,13 +58,13 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
58
58
  }
59
59
  return t ?? e;
60
60
  });
61
- }, an = "enc:v1:", on = "enc:v2:", sn = (e, t, n) => {
61
+ }, rn = "enc:v1:", an = "enc:v2:", on = (e, t, n) => {
62
62
  let r = `${e}:${t}`, i = n == null || n === "" ? void 0 : String(n);
63
63
  return i === void 0 ? { column: r } : {
64
64
  column: r,
65
65
  row: `${r}:${i}`
66
66
  };
67
- }, cn = (e) => typeof e == "string" && e.startsWith("enc:v2:"), ln = class extends Error {
67
+ }, sn = (e) => typeof e == "string" && e.startsWith("enc:v2:"), cn = class extends Error {
68
68
  _tag = "FieldDecryptionError";
69
69
  table;
70
70
  column;
@@ -72,7 +72,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
72
72
  constructor(e) {
73
73
  super(`column "${e.table}.${e.column}" is .encrypted() but could not be decrypted (${e.reason}) — the stored value was most likely encrypted under a different key`), this.name = "FieldDecryptionError", this.table = e.table, this.column = e.column, this.reason = e.reason;
74
74
  }
75
- }, un = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", dn = (e) => typeof e == "string" && (e.startsWith("enc:v1:") || e.startsWith("enc:v2:")), fn = (e, t, n) => e.encrypt(JSON.stringify(t), n), pn = /* @__PURE__ */ new Set([
75
+ }, ln = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", un = (e) => typeof e == "string" && (e.startsWith("enc:v1:") || e.startsWith("enc:v2:")), dn = (e, t, n) => e.encrypt(JSON.stringify(t), n), fn = /* @__PURE__ */ new Set([
76
76
  "text",
77
77
  "id",
78
78
  "reference",
@@ -80,51 +80,51 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
80
80
  "uuid",
81
81
  "email",
82
82
  "url"
83
- ]), mn = (e, t, n, r) => {
83
+ ]), pn = (e, t, n, r) => {
84
84
  let i = e.decrypt(t, r), a;
85
85
  try {
86
86
  a = JSON.parse(i);
87
87
  } catch {
88
88
  return i;
89
89
  }
90
- return typeof a == "string" ? a : n === void 0 || pn.has(n) ? i : a;
91
- }, hn = (e, t, n, r) => {
90
+ return typeof a == "string" ? a : n === void 0 || fn.has(n) ? i : a;
91
+ }, mn = (e, t, n, r) => {
92
92
  let i = e.decrypt(t, r);
93
93
  try {
94
- return typeof JSON.parse(i) == "string" ? !1 : n === void 0 || pn.has(n) ? !0 : void 0;
94
+ return typeof JSON.parse(i) == "string" ? !1 : n === void 0 || fn.has(n) ? !0 : void 0;
95
95
  } catch {
96
96
  return !0;
97
97
  }
98
- }, gn = (e, t) => e.fields[t]?.type, _n = (e) => {
98
+ }, hn = (e, t) => e.fields[t]?.type, gn = (e) => {
99
99
  let t = [];
100
100
  for (let [n, r] of Object.entries(e.fields)) r.encrypted === !0 && t.push(n);
101
101
  return t;
102
- }, vn = "id", yn = (e, t, n, r) => {
102
+ }, _n = "id", vn = (e, t, n, r) => {
103
103
  if (!t) return e;
104
- let i = _n(t);
104
+ let i = gn(t);
105
105
  if (i.length === 0) return e;
106
- let a = t.tableName ?? "?", o = r ?? e[vn], s = { ...e };
106
+ let a = t.tableName ?? "?", o = r ?? e[_n], s = { ...e };
107
107
  for (let e of i) {
108
108
  let t = s[e];
109
- if (!(t == null || dn(t))) {
109
+ if (!(t == null || un(t))) {
110
110
  if (!n) throw Error(`column "${a}.${e}" is .encrypted() but no field cipher is registered — set VOLTRO_FIELD_ENCRYPTION_KEY (\`voltro dev\` mints one; \`voltro serve\` refuses to boot without it)`);
111
- s[e] = fn(n, t, sn(a, e, o));
111
+ s[e] = dn(n, t, on(a, e, o));
112
112
  }
113
113
  }
114
114
  return s;
115
- }, bn = (e, t, n, r) => {
115
+ }, yn = (e, t, n, r) => {
116
116
  if (!t) return e;
117
- let i = _n(t);
117
+ let i = gn(t);
118
118
  if (i.length === 0 || !n) return e;
119
119
  let a = r?.onError ?? "throw", o = t.tableName ?? "?";
120
120
  return e.map((e) => {
121
121
  let s;
122
122
  for (let c of i) {
123
123
  let i = e[c];
124
- if (dn(i)) {
124
+ if (un(i)) {
125
125
  s ??= { ...e };
126
126
  try {
127
- s[c] = mn(n, i, gn(t, c), sn(o, c, r?.rowId ?? e[vn]));
127
+ s[c] = pn(n, i, hn(t, c), on(o, c, r?.rowId ?? e[_n]));
128
128
  } catch (e) {
129
129
  let t = String(e?.message ?? e);
130
130
  if (a === "null") {
@@ -135,7 +135,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
135
135
  });
136
136
  continue;
137
137
  }
138
- throw new ln({
138
+ throw new cn({
139
139
  table: o,
140
140
  column: c,
141
141
  reason: t
@@ -145,30 +145,30 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
145
145
  }
146
146
  return s ?? e;
147
147
  });
148
- }, xn = (e) => {
148
+ }, bn = (e) => {
149
149
  let t = e;
150
- for (let e = 0; e < 4 && Gt.isFiberFailure(t); e++) t = Bt.squash(t[Gt.FiberFailureCauseId]);
150
+ for (let e = 0; e < 4 && Wt.isFiberFailure(t); e++) t = O.squash(t[Wt.FiberFailureCauseId]);
151
151
  return t;
152
- }, N = (e, t = 0) => {
153
- if (t >= 4 || !Gt.isFiberFailure(e)) return [e];
154
- let n = e[Gt.FiberFailureCauseId], r = [...Bt.failures(n), ...Bt.defects(n)];
155
- if (r.length === 0) return [Bt.squash(n)];
152
+ }, xn = (e, t = 0) => {
153
+ if (t >= 4 || !Wt.isFiberFailure(e)) return [e];
154
+ let n = e[Wt.FiberFailureCauseId], r = [...O.failures(n), ...O.defects(n)];
155
+ if (r.length === 0) return [O.squash(n)];
156
156
  let i = [];
157
- for (let e of r.slice(0, 8)) i.push(...N(e, t + 1));
157
+ for (let e of r.slice(0, 8)) i.push(...xn(e, t + 1));
158
158
  return i;
159
159
  }, Sn = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, Cn = (e) => {
160
- let t = {}, n = [], r = xn(e);
160
+ let t = {}, n = [], r = bn(e);
161
161
  for (let e = 0; e < 8 && typeof r == "object" && r; e++) {
162
162
  let e = r;
163
163
  t.dbCode === void 0 && (typeof e.code == "string" || typeof e.code == "number") && (t.dbCode = e.code), t.dbErrno === void 0 && typeof e.errno == "number" && (t.dbErrno = e.errno), t.dbNumber === void 0 && typeof e.number == "number" && (t.dbNumber = e.number), t.dbSqlState === void 0 && typeof e.sqlState == "string" && (t.dbSqlState = e.sqlState), t.dbBindings === void 0 && typeof e.voltroBindings == "string" && (t.dbBindings = e.voltroBindings), t.dbStatement === void 0 && typeof e.sql == "string" && e.sql.includes("?") && (t.dbStatement = e.sql, t.dbPlaceholders = (e.sql.match(/\?/g) ?? []).length), t.dbFatal === void 0 && typeof e.fatal == "boolean" && (t.dbFatal = e.fatal), t.dbConstraint === void 0 && typeof e.constraint == "string" && (t.dbConstraint = e.constraint), t.dbTable === void 0 && typeof e.table == "string" && (t.dbTable = e.table), t.dbColumn === void 0 && typeof e.column == "string" && (t.dbColumn = e.column), t.dbSchema === void 0 && typeof e.schema == "string" && (t.dbSchema = e.schema);
164
164
  let i = e.sqlMessage ?? e.detail;
165
165
  t.dbMessage === void 0 && typeof i == "string" && (t.dbMessage = i);
166
166
  let a = typeof e.constructor == "function" ? e.constructor.name : void 0, o = typeof e._tag == "string" && e._tag || typeof e.name == "string" && e.name || (typeof a == "string" && a !== "Object" ? a : void 0), s = typeof e.message == "string" ? e.message : void 0;
167
- (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = xn(e.cause);
167
+ (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = bn(e.cause);
168
168
  }
169
169
  return n.length > 0 && (t.dbCauseChain = n.join(" ← "), t.dbMessage === void 0 && (t.dbMessage = n[n.length - 1])), t;
170
170
  }, wn = (e) => {
171
- let t = N(e).map(Cn);
171
+ let t = xn(e).map(Cn);
172
172
  if (t.length <= 1) return t[0] ?? {};
173
173
  let n = t.find(Sn) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
174
174
  if (r.length === 0) return n;
@@ -177,12 +177,23 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
177
177
  ...n,
178
178
  dbCauseChain: [i, ...r].filter(Boolean).join(" ‖ ")
179
179
  };
180
- }, Tn = /^[A-Za-z_][A-Za-z0-9_$]*$/, P = (e) => e !== void 0 && e.length <= 128 && Tn.test(e) ? e : void 0, En = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, F = (e, ...t) => {
180
+ }, Tn = (e, t) => {
181
+ let n = wn(e), r = jn(n, t);
182
+ if (r !== void 0) {
183
+ let e = r.constraint ?? r.column;
184
+ return e === void 0 ? r.kind : `${r.kind}: ${e}`;
185
+ }
186
+ let i = n.dbCode ?? n.dbSqlState ?? n.dbErrno ?? n.dbNumber, a = On(e);
187
+ return i !== void 0 && En.test(String(i)) ? `${a} (${String(i)})` : a;
188
+ }, En = /^[A-Za-z0-9_]{1,32}$/, Dn = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/, On = (e) => {
189
+ let t = e?._tag, n = e?.name, r = (typeof t == "string" ? t : typeof n == "string" ? n : "").split(/[^A-Za-z0-9_]+/).filter(Boolean).pop();
190
+ return r !== void 0 && Dn.test(r) ? r : "unknown";
191
+ }, kn = /^[A-Za-z_][A-Za-z0-9_$]*$/, P = (e) => e !== void 0 && e.length <= 128 && kn.test(e) ? e : void 0, An = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, F = (e, ...t) => {
181
192
  for (let n of t) {
182
193
  let t = n.exec(e);
183
194
  if (t?.[1] !== void 0) return t[1];
184
195
  }
185
- }, Dn = (e, t) => {
196
+ }, jn = (e, t) => {
186
197
  let n = e.dbCode, r = e.dbErrno, i = e.dbNumber, a = typeof e.dbMessage == "string" ? e.dbMessage : "", o = `${typeof e.dbCauseChain == "string" ? e.dbCauseChain : ""} ${a}`;
187
198
  if (n === "23503") {
188
199
  let t = P(e.dbConstraint);
@@ -220,7 +231,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
220
231
  };
221
232
  }
222
233
  if (r === 1062) {
223
- let e = P(En(F(o, /for key '([^']+)'/)));
234
+ let e = P(An(F(o, /for key '([^']+)'/)));
224
235
  return {
225
236
  kind: "unique",
226
237
  ...e === void 0 ? {} : { constraint: e }
@@ -271,14 +282,14 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
271
282
  }
272
283
  if (n === "SQLITE_CONSTRAINT_FOREIGNKEY") return { kind: t === "delete" || t === "deleteMany" || t === "hardDelete" ? "foreignKeyInUse" : "foreignKey" };
273
284
  if (n === "SQLITE_CONSTRAINT_UNIQUE" || n === "SQLITE_CONSTRAINT_PRIMARYKEY") {
274
- let e = P(En(F(o, /UNIQUE constraint failed: ([^,\s]+)/)));
285
+ let e = P(An(F(o, /UNIQUE constraint failed: ([^,\s]+)/)));
275
286
  return {
276
287
  kind: "unique",
277
288
  ...e === void 0 ? {} : { column: e }
278
289
  };
279
290
  }
280
291
  if (n === "SQLITE_CONSTRAINT_NOTNULL") {
281
- let e = P(En(F(o, /NOT NULL constraint failed: ([^,\s]+)/)));
292
+ let e = P(An(F(o, /NOT NULL constraint failed: ([^,\s]+)/)));
282
293
  return {
283
294
  kind: "notNull",
284
295
  ...e === void 0 ? {} : { column: e }
@@ -291,13 +302,13 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
291
302
  ...e === void 0 ? {} : { constraint: e }
292
303
  };
293
304
  }
294
- }, On = (e) => {
295
- let t = Dn(e)?.kind;
305
+ }, Mn = (e) => {
306
+ let t = jn(e)?.kind;
296
307
  return t === "foreignKey" || t === "foreignKeyInUse";
297
- }, kn = (e) => {
308
+ }, Nn = (e) => {
298
309
  let t = e.dbCode, n = e.dbErrno;
299
310
  return t === "57014" || n === 3024 || n === 1969 || t === "ETIMEOUT" || t === "SQLITE_INTERRUPT";
300
- }, An = (e) => {
311
+ }, Pn = (e) => {
301
312
  let t = wn(e), n = [
302
313
  t.dbCode === void 0 ? void 0 : `code=${String(t.dbCode)}`,
303
314
  t.dbErrno === void 0 ? void 0 : `errno=${String(t.dbErrno)}`,
@@ -307,7 +318,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
307
318
  t.dbPlaceholders === void 0 ? void 0 : `placeholders=${String(t.dbPlaceholders)}`
308
319
  ].filter((e) => e !== void 0), r = typeof e?.message == "string" ? e.message : void 0, i = typeof t.dbMessage == "string" ? t.dbMessage : void 0, a = i === void 0 ? void 0 : n.length > 0 || i !== r && i !== `Error: ${String(r)}` ? i : void 0, o = typeof t.dbBindings == "string" ? `\n bindings: ${t.dbBindings}` : "", s = typeof t.dbStatement == "string" ? `\n statement: ${t.dbStatement.length <= 400 ? t.dbStatement : `${t.dbStatement.slice(0, 400)}…`}` : "";
309
320
  if (a !== void 0 || n.length !== 0) return [a, n.length > 0 ? `[${n.join(" ")}]` : void 0].filter((e) => e !== void 0 && e !== "").join(" ") + s + o;
310
- }, jn = (e) => Object.entries(e).map(([e, t]) => `${e}:${Mn(t)}`).join(" "), Mn = (e) => {
321
+ }, Fn = (e) => Object.entries(e).map(([e, t]) => `${e}:${In(t)}`).join(" "), In = (e) => {
311
322
  if (e === null) return "null";
312
323
  if (e === void 0) return "undefined";
313
324
  if (typeof e == "bigint") return "bigint";
@@ -317,77 +328,77 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
317
328
  if (globalThis.Buffer !== void 0 && globalThis.Buffer.isBuffer(e)) return "Buffer";
318
329
  let t = e.constructor?.name;
319
330
  return typeof t == "string" && t !== "" ? t : "Object";
320
- }, Nn = Symbol.for("@voltro/database/storeRefusal"), Pn = (e) => {
331
+ }, Ln = Symbol.for("@voltro/database/storeRefusal"), Rn = (e) => {
321
332
  let t = Error(e.detail);
322
- return Object.defineProperty(t, Nn, {
333
+ return Object.defineProperty(t, Ln, {
323
334
  value: e,
324
335
  enumerable: !1
325
336
  }), t;
326
- }, Fn = (e) => {
327
- for (let t of N(e)) {
337
+ }, zn = (e) => {
338
+ for (let t of xn(e)) {
328
339
  let e = t;
329
340
  for (let t = 0; e != null && t < 8; t += 1) {
330
- let t = e[Nn];
341
+ let t = e[Ln];
331
342
  if (t !== void 0) return t;
332
343
  e = e.cause;
333
344
  }
334
345
  }
335
- }, In = (e) => {
346
+ }, Bn = (e) => {
336
347
  let t = (() => {
337
348
  switch (e.type) {
338
349
  case "id":
339
350
  case "reference":
340
351
  case "text":
341
- case "enum": return j.String;
352
+ case "enum": return M.String;
342
353
  case "integer":
343
354
  case "real":
344
- case "decimal": return j.Number;
345
- case "boolean": return j.Boolean;
355
+ case "decimal": return M.Number;
356
+ case "boolean": return M.Boolean;
346
357
  case "timestamp":
347
358
  case "date": return zt;
348
- case "bigint": return j.BigInt;
349
- case "bytes": return j.Uint8ArrayFromBase64;
350
- case "array": return j.Array(j.Unknown);
351
- case "interval": return j.String;
352
- default: return j.Unknown;
359
+ case "bigint": return M.BigInt;
360
+ case "bytes": return M.Uint8ArrayFromBase64;
361
+ case "array": return M.Array(M.Unknown);
362
+ case "interval": return M.String;
363
+ default: return M.Unknown;
353
364
  }
354
365
  })();
355
- return e.nullable === !0 ? j.NullOr(t) : t;
356
- }, Ln = (e, t) => {
366
+ return e.nullable === !0 ? M.NullOr(t) : t;
367
+ }, Vn = (e, t) => {
357
368
  let n = new Set(t?.omit ?? []), r = {};
358
- for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = In(i));
359
- return j.Struct(r);
360
- }, Rn = (e) => typeof e == "function" ? e : () => e, zn = (e, t) => ({
369
+ for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = Bn(i));
370
+ return M.Struct(r);
371
+ }, Hn = (e) => typeof e == "function" ? e : () => e, Un = (e, t) => ({
361
372
  kind: "one",
362
- target: Rn(e),
373
+ target: Hn(e),
363
374
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
364
375
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
365
- }), Bn = (e, t) => ({
376
+ }), Wn = (e, t) => ({
366
377
  kind: "many",
367
- target: Rn(e),
378
+ target: Hn(e),
368
379
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
369
380
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
370
- }), Vn = (e, t) => ({
381
+ }), Gn = (e, t) => ({
371
382
  kind: "manyToMany",
372
- target: Rn(e),
373
- through: Rn(t.through),
383
+ target: Hn(e),
384
+ through: Hn(t.through),
374
385
  sourceKey: t.sourceKey,
375
386
  targetKey: t.targetKey
376
- }), Hn = {
377
- one: zn,
378
- many: Bn,
379
- manyToMany: Vn
380
- }, Un = (e, t) => {
387
+ }), Kn = {
388
+ one: Un,
389
+ many: Wn,
390
+ manyToMany: Gn
391
+ }, qn = (e, t) => {
381
392
  let n = typeof e == "function" ? e : () => e;
382
393
  return {
383
394
  source: n,
384
- relations: t(Hn, n())
395
+ relations: t(Kn, n())
385
396
  };
386
- }, Wn = (e) => {
397
+ }, Jn = (e) => {
387
398
  if (typeof e != "object" || !e) return !1;
388
399
  let t = e;
389
400
  return typeof t.source != "function" || typeof t.relations != "object" || t.relations === null ? !1 : Object.keys(t.relations).length === 0;
390
- }, Gn = (e) => {
401
+ }, Yn = (e) => {
391
402
  if (typeof e != "object" || !e) return !1;
392
403
  let t = e;
393
404
  if (typeof t.source != "function" || typeof t.relations != "object" || t.relations === null) return !1;
@@ -396,32 +407,32 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
396
407
  let t = e?.kind;
397
408
  return t === "one" || t === "many" || t === "manyToMany";
398
409
  });
399
- }, Kn = zn, qn = Bn, Jn = Vn, Yn = (e, t, n) => {
410
+ }, Xn = Un, Zn = Wn, Qn = Gn, $n = (e, t, n) => {
400
411
  let r = [];
401
412
  for (let [n, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && r.push(n);
402
413
  if (r.length === 0) throw Error(`relation '${n}': no reference() column on '${e.tableName}' points at '${t}'. Either add one or pass an explicit { foreignKey: '<column>' }.`);
403
414
  if (r.length > 1) throw Error(`relation '${n}': multiple reference() columns on '${e.tableName}' point at '${t}' (${r.join(", ")}). Pass an explicit { foreignKey: '<column>' } to disambiguate.`);
404
415
  return r[0];
405
- }, Xn = (e) => Object.keys(e.fields), Zn = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Qn = (e) => {
406
- let t = Xn(e);
416
+ }, er = (e) => Object.keys(e.fields), tr = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), nr = (e) => {
417
+ let t = er(e);
407
418
  return t.length === 0 ? "<none>" : t.join(", ");
408
- }, $n = (e, t, n) => {
419
+ }, rr = (e, t, n) => {
409
420
  let r = `relation '${t}' on '${e.tableName}'`, i = n.target();
410
421
  if (n.kind === "manyToMany") {
411
422
  let t = n.through();
412
- for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!Zn(t, o)) throw Error(`${r}: manyToMany ${a} '${o}' is not a column on the junction table '${t.tableName}'. Both keys name columns on the JUNCTION — ${a === "sourceKey" ? `sourceKey points at '${e.tableName}'` : `targetKey points at '${i.tableName}'`}. Columns on '${t.tableName}': ${Qn(t)}.`);
423
+ for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!tr(t, o)) throw Error(`${r}: manyToMany ${a} '${o}' is not a column on the junction table '${t.tableName}'. Both keys name columns on the JUNCTION — ${a === "sourceKey" ? `sourceKey points at '${e.tableName}'` : `targetKey points at '${i.tableName}'`}. Columns on '${t.tableName}': ${nr(t)}.`);
413
424
  return;
414
425
  }
415
426
  if (n.sourceKey !== void 0 && n.foreignKey !== void 0) throw Error(`${r}: pass EITHER sourceKey OR foreignKey, not both. sourceKey '${n.sourceKey}' names a column on the source ('${e.tableName}') holding the target's id; foreignKey '${n.foreignKey}' names a column on the target ('${i.tableName}') holding the source's id. With both, foreignKey is ignored.`);
416
- if (n.sourceKey !== void 0 && !Zn(e, n.sourceKey)) {
417
- let t = Zn(i, n.sourceKey);
418
- throw Error(`${r}: sourceKey '${n.sourceKey}' is not a column on the source table '${e.tableName}'.` + (t ? ` It IS a column on the target '${i.tableName}' — you probably want { foreignKey: '${n.sourceKey}' }, which names the column on the TARGET that holds this table's id.` : ` Columns on '${e.tableName}': ${Qn(e)}.`));
427
+ if (n.sourceKey !== void 0 && !tr(e, n.sourceKey)) {
428
+ let t = tr(i, n.sourceKey);
429
+ throw Error(`${r}: sourceKey '${n.sourceKey}' is not a column on the source table '${e.tableName}'.` + (t ? ` It IS a column on the target '${i.tableName}' — you probably want { foreignKey: '${n.sourceKey}' }, which names the column on the TARGET that holds this table's id.` : ` Columns on '${e.tableName}': ${nr(e)}.`));
419
430
  }
420
- if (n.foreignKey !== void 0 && !Zn(i, n.foreignKey)) {
421
- let t = Zn(e, n.foreignKey);
422
- throw Error(`${r}: foreignKey '${n.foreignKey}' is not a column on the target table '${i.tableName}'.` + (t ? ` It IS a column on the source '${e.tableName}' — you want { sourceKey: '${n.foreignKey}' }. foreignKey names the column on the TARGET that points back at this table; sourceKey names the column on THIS table that holds the target's id.` : ` Columns on '${i.tableName}': ${Qn(i)}.`));
431
+ if (n.foreignKey !== void 0 && !tr(i, n.foreignKey)) {
432
+ let t = tr(e, n.foreignKey);
433
+ throw Error(`${r}: foreignKey '${n.foreignKey}' is not a column on the target table '${i.tableName}'.` + (t ? ` It IS a column on the source '${e.tableName}' — you want { sourceKey: '${n.foreignKey}' }. foreignKey names the column on the TARGET that points back at this table; sourceKey names the column on THIS table that holds the target's id.` : ` Columns on '${i.tableName}': ${nr(i)}.`));
423
434
  }
424
- }, er = Symbol.for("@voltro/database/relationsRegistry"), tr = globalThis, I = tr[er] ?? (tr[er] = /* @__PURE__ */ new Map()), nr = (e) => {
435
+ }, ir = Symbol.for("@voltro/database/relationsRegistry"), ar = globalThis, I = ar[ir] ?? (ar[ir] = /* @__PURE__ */ new Map()), or = (e) => {
425
436
  let t = e.source(), n = I.get(t.tableName);
426
437
  if (n === void 0) {
427
438
  I.set(t.tableName, new Map(Object.entries(e.relations)));
@@ -434,14 +445,14 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
434
445
  n.set(r, i);
435
446
  }
436
447
  }
437
- }, rr = (e) => {
448
+ }, sr = (e) => {
438
449
  let t = 0;
439
- for (let n of Object.values(e)) Gn(n) && (nr(n), t += 1);
450
+ for (let n of Object.values(e)) Yn(n) && (or(n), t += 1);
440
451
  return t;
441
- }, ir = (e) => {
452
+ }, cr = (e) => {
442
453
  let t = I.get(e);
443
454
  if (t !== void 0) return Object.fromEntries(t);
444
- }, ar = (e, t) => I.get(e)?.get(t), or = () => {
455
+ }, lr = (e, t) => I.get(e)?.get(t), ur = () => {
445
456
  let e = [];
446
457
  for (let [t, n] of I) for (let [r, i] of n) e.push({
447
458
  source: t,
@@ -449,18 +460,18 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
449
460
  relation: i
450
461
  });
451
462
  return e;
452
- }, sr = () => {
463
+ }, dr = () => {
453
464
  for (let [e, t] of I) {
454
465
  let n = S(e);
455
- if (n !== void 0) for (let [e, r] of t) $n(n, e, r);
466
+ if (n !== void 0) for (let [e, r] of t) rr(n, e, r);
456
467
  }
457
- }, cr = () => {
468
+ }, fr = () => {
458
469
  I.clear();
459
- }, lr = 4, ur = (e) => Object.keys(e.fields), dr = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), fr = (e, t) => {
470
+ }, pr = 4, mr = (e) => Object.keys(e.fields), hr = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), gr = (e, t) => {
460
471
  let n = [];
461
472
  for (let [r, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && n.push(r);
462
473
  return n;
463
- }, pr = (e, t) => {
474
+ }, _r = (e, t) => {
464
475
  let n = [];
465
476
  for (let r of t) {
466
477
  if (r.source !== e) continue;
@@ -477,7 +488,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
477
488
  } catch {
478
489
  continue;
479
490
  }
480
- if (!dr(e, t.sourceKey)) continue;
491
+ if (!hr(e, t.sourceKey)) continue;
481
492
  n.push({
482
493
  table: e.tableName,
483
494
  foreignKey: t.sourceKey,
@@ -486,24 +497,24 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
486
497
  continue;
487
498
  }
488
499
  if (t.sourceKey !== void 0) continue;
489
- let a = fr(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
490
- o === void 0 || !dr(i, o) || n.push({
500
+ let a = gr(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
501
+ o === void 0 || !hr(i, o) || n.push({
491
502
  table: i.tableName,
492
503
  foreignKey: o,
493
504
  parentKey: "id"
494
505
  });
495
506
  }
496
507
  return n;
497
- }, mr = (e, t) => {
508
+ }, vr = (e, t) => {
498
509
  let n = [];
499
- for (let r of t) if (r.tableName !== e) for (let t of fr(r, e)) n.push({
510
+ for (let r of t) if (r.tableName !== e) for (let t of gr(r, e)) n.push({
500
511
  table: r.tableName,
501
512
  foreignKey: t,
502
513
  parentKey: "id"
503
514
  });
504
515
  return n;
505
- }, hr = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, gr = (e) => {
506
- let t = e.tables ?? re(), n = e.relations ?? or(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
516
+ }, yr = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, br = (e) => {
517
+ let t = e.tables ?? re(), n = e.relations ?? ur(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
507
518
  if (!a.has(e.subjectTable)) return {
508
519
  subjectTable: e.subjectTable,
509
520
  paths: [],
@@ -518,11 +529,11 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
518
529
  hops: [],
519
530
  depth: 0,
520
531
  via: "relation"
521
- }, c = [s], l = /* @__PURE__ */ new Set([hr(s)]), u = /* @__PURE__ */ new Set(), d = [s];
532
+ }, c = [s], l = /* @__PURE__ */ new Set([yr(s)]), u = /* @__PURE__ */ new Set(), d = [s];
522
533
  for (let e = 1; e <= r; e++) {
523
534
  let r = [];
524
535
  for (let a of d) {
525
- let s = pr(a.table, n), d = mr(a.table, t), f = [...s.map((e) => [e, "relation"]), ...d.map((e) => [e, "reference"])];
536
+ let s = _r(a.table, n), d = vr(a.table, t), f = [...s.map((e) => [e, "relation"]), ...d.map((e) => [e, "reference"])];
526
537
  for (let [t, n] of f) {
527
538
  if (i.has(t.table)) {
528
539
  o.push({
@@ -540,7 +551,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
540
551
  hops: [...a.hops, t],
541
552
  depth: e,
542
553
  via: n
543
- }, f = hr(d);
554
+ }, f = yr(d);
544
555
  l.has(f) || (l.add(f), c.push(d), r.push(d));
545
556
  }
546
557
  }
@@ -550,7 +561,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
550
561
  }
551
562
  d = r;
552
563
  }
553
- for (let e of d) (pr(e.table, n).length > 0 || mr(e.table, t).length > 0) && o.push({
564
+ for (let e of d) (_r(e.table, n).length > 0 || vr(e.table, t).length > 0) && o.push({
554
565
  kind: "depth-truncated",
555
566
  table: e.table,
556
567
  detail: `stopped at maxDepth ${r}; tables linked FROM '${e.table}' were not explored`
@@ -559,14 +570,14 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
559
570
  for (let n of t) f.has(n.tableName) || i.has(n.tableName) || o.push({
560
571
  kind: "unreachable",
561
572
  table: n.tableName,
562
- detail: `no relation() and no reference() column links '${n.tableName}' to '${e.subjectTable}'. If it holds subject data through a plain column, a polymorphic (type,id) pair, JSON or free text, add an explicit subjectScopes entry — this derivation cannot see it. Columns: ${ur(n).join(", ")}`
573
+ detail: `no relation() and no reference() column links '${n.tableName}' to '${e.subjectTable}'. If it holds subject data through a plain column, a polymorphic (type,id) pair, JSON or free text, add an explicit subjectScopes entry — this derivation cannot see it. Columns: ${mr(n).join(", ")}`
563
574
  });
564
575
  return {
565
576
  subjectTable: e.subjectTable,
566
577
  paths: c,
567
578
  limitations: o
568
579
  };
569
- }, _r = (e) => {
580
+ }, xr = (e) => {
570
581
  let t = [`subject graph · ${e.subjectTable} · ${e.paths.length} table(s) reachable`];
571
582
  for (let n of e.paths) {
572
583
  let r = n.hops.length === 0 ? `${e.subjectTable} (the subject row itself)` : [e.subjectTable, ...n.hops.map((e) => `${e.table}.${e.foreignKey}`)].join(" → ");
@@ -574,7 +585,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
574
585
  }
575
586
  let n = e.limitations.filter((e) => e.kind === "depth-truncated"), r = e.limitations.filter((e) => e.kind === "unreachable"), i = e.limitations.filter((e) => e.kind === "excluded");
576
587
  return t.push(""), t.push(" WHAT THIS CANNOT SEE — a DSAR is only as complete as this list is short:"), n.length > 0 && t.push(` depth-truncated (${n.length}): ${n.map((e) => e.table).join(", ")}`), i.length > 0 && t.push(` excluded (${i.length}): ${[...new Set(i.map((e) => e.table))].join(", ")}`), t.push(r.length === 0 ? " unreachable: none — every registered table is linked to the subject." : ` unreachable (${r.length}): ${r.map((e) => e.table).join(", ")}`), t.push(" Always outside this graph: object storage / uploaded files, external processors,"), t.push(" log and metric sinks, backups, and any subject id embedded in JSON or free text."), t.join("\n");
577
- }, vr = (e) => e == null || typeof e == "boolean" ? e : typeof e == "number" ? e !== 0 : typeof e == "bigint" ? e !== 0n : typeof e == "string" ? e === "1" || e.toLowerCase() === "true" : e, yr = (e) => {
588
+ }, Sr = (e) => e == null || typeof e == "boolean" ? e : typeof e == "number" ? e !== 0 : typeof e == "bigint" ? e !== 0n : typeof e == "string" ? e === "1" || e.toLowerCase() === "true" : e, Cr = (e) => {
578
589
  if (e == null || typeof e != "string") return e;
579
590
  let t = e.trim();
580
591
  if (t.length === 0) return e;
@@ -585,7 +596,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
585
596
  } catch {
586
597
  return e;
587
598
  }
588
- }, br = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, xr = (e) => {
599
+ }, wr = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, Tr = (e) => {
589
600
  if (e == null || e instanceof Date) return e;
590
601
  if (typeof e == "string") {
591
602
  let t = new Date(e);
@@ -596,19 +607,19 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
596
607
  return isNaN(t.getTime()) ? e : t;
597
608
  }
598
609
  return e;
599
- }, Sr = (e, t, n) => {
610
+ }, Er = (e, t, n) => {
600
611
  if (e == null) return e;
601
612
  switch (t) {
602
- case "boolean": return n === "postgres" ? e : vr(e);
613
+ case "boolean": return n === "postgres" ? e : Sr(e);
603
614
  case "json":
604
- case "array": return n === "postgres" ? e : yr(e);
615
+ case "array": return n === "postgres" ? e : Cr(e);
605
616
  case "timestamp":
606
- case "date": return n === "sqlite" || n === "turso" ? xr(e) : e;
617
+ case "date": return n === "sqlite" || n === "turso" ? Tr(e) : e;
607
618
  case "decimal":
608
- case "bigint": return br(e);
619
+ case "bigint": return wr(e);
609
620
  default: return e;
610
621
  }
611
- }, Cr = (e, t, n) => {
622
+ }, Dr = (e, t, n) => {
612
623
  if (e.length === 0) return e;
613
624
  let r = S(t);
614
625
  if (r === void 0) return e;
@@ -619,36 +630,36 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
619
630
  });
620
631
  return e.map((e) => {
621
632
  let t = { ...e };
622
- for (let { key: e, type: r } of a) e in t && (t[e] = Sr(t[e], r, n));
633
+ for (let { key: e, type: r } of a) e in t && (t[e] = Er(t[e], r, n));
623
634
  return t;
624
635
  });
625
- }, wr = (e, t) => {
636
+ }, Or = (e, t) => {
626
637
  if (e == null) return e;
627
638
  switch (t) {
628
639
  case "json":
629
640
  case "array": return typeof e == "string" ? e : JSON.stringify(e);
630
641
  default: return e;
631
642
  }
632
- }, Tr = (e, t, n = ["json", "array"]) => {
643
+ }, kr = (e, t, n = ["json", "array"]) => {
633
644
  let r = S(t);
634
645
  if (r === void 0) return e;
635
646
  let i = r.fields, a = null;
636
647
  for (let [t, r] of Object.entries(i)) if (n.includes(r.type) && t in e) {
637
- let n = wr(e[t], r.type);
648
+ let n = Or(e[t], r.type);
638
649
  n !== e[t] && (a === null && (a = { ...e }), a[t] = n);
639
650
  }
640
651
  return a ?? e;
641
- }, Er = class extends Error {
652
+ }, Ar = class extends Error {
642
653
  _tag = "EagerCardinalityError";
643
654
  constructor(e) {
644
655
  super(e), this.name = "EagerCardinalityError";
645
656
  }
646
- }, Dr = (e) => {
657
+ }, jr = (e) => {
647
658
  let { relationName: t, sourceTableName: n, targetTableName: r, foreignKey: i, sourceKey: a } = e, o = r === n;
648
659
  return `relation '${t}' on '${n}' is declared \`one\`, but ${r}.${i} matches MORE than one row for the same ${n}.${a} — so there is no single related row to return.` + (o ? ` Because this relation is self-referential, check which side the key is on: \`foreignKey: '${i}'\` means "rows whose ${i} points AT me" (my children — there can be many). If you meant "the row my ${i} points to" (my parent), that is \`sourceKey: '${i}'\`.` : " Use `many(...)` if several are expected, or narrow the key.");
649
- }, Or = async (e, t, n, r) => {
660
+ }, Mr = async (e, t, n, r) => {
650
661
  if (e.length === 0) return e;
651
- let i = ir(n.tableName);
662
+ let i = cr(n.tableName);
652
663
  if (i === void 0) throw Error(`cannot eager-load on '${n.tableName}': no relations registered. Did you forget to declare \`relations(${n.tableName}, ...)\` or import the file that does?`);
653
664
  let a = e.map((e) => ({ ...e }));
654
665
  for (let [e, o] of Object.entries(t)) {
@@ -657,36 +668,36 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
657
668
  let t = Object.keys(i).join(", ") || "<none>";
658
669
  throw Error(`unknown relation '${e}' on '${n.tableName}'. Registered relations: ${t}.`);
659
670
  }
660
- $n(n, e, t), await kr(a, e, t, o === !0 ? {} : o, n, r);
671
+ rr(n, e, t), await Nr(a, e, t, o === !0 ? {} : o, n, r);
661
672
  }
662
673
  return a;
663
- }, kr = async (e, t, n, r, i, a) => {
674
+ }, Nr = async (e, t, n, r, i, a) => {
664
675
  switch (n.kind) {
665
676
  case "one":
666
- await Ar(e, t, n, r, i, a);
677
+ await Pr(e, t, n, r, i, a);
667
678
  return;
668
679
  case "many":
669
- await jr(e, t, n, r, i, a);
680
+ await Fr(e, t, n, r, i, a);
670
681
  return;
671
682
  case "manyToMany":
672
- await Nr(e, t, n, r, i, a);
683
+ await Lr(e, t, n, r, i, a);
673
684
  return;
674
685
  }
675
- }, Ar = async (e, t, n, r, i, a) => {
676
- let o = n.target(), s = n.sourceKey ?? Pr(i, o.tableName);
686
+ }, Pr = async (e, t, n, r, i, a) => {
687
+ let o = n.target(), s = n.sourceKey ?? Rr(i, o.tableName);
677
688
  if (s !== void 0) {
678
- let n = Fr(e, s), i = n.length === 0 ? [] : await Ir(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
689
+ let n = zr(e, s), i = n.length === 0 ? [] : await Br(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
679
690
  for (let n of e) {
680
691
  let e = n[s];
681
692
  n[t] = e == null ? null : c.get(e) ?? null;
682
693
  }
683
- await Lr(i, r.with, o, a);
694
+ await Vr(i, r.with, o, a);
684
695
  return;
685
696
  }
686
- let c = n.foreignKey ?? Yn(o, i.tableName, t), l = n.sourceKey ?? "id", u = Fr(e, l), d = u.length === 0 ? [] : await Ir(o, c, u, r, a), f = /* @__PURE__ */ new Map();
697
+ let c = n.foreignKey ?? $n(o, i.tableName, t), l = n.sourceKey ?? "id", u = zr(e, l), d = u.length === 0 ? [] : await Br(o, c, u, r, a), f = /* @__PURE__ */ new Map();
687
698
  for (let e of d) {
688
699
  let n = e[c];
689
- if (f.has(n)) throw new Er(Dr({
700
+ if (f.has(n)) throw new Ar(jr({
690
701
  relationName: t,
691
702
  sourceTableName: i.tableName,
692
703
  targetTableName: o.tableName,
@@ -699,9 +710,9 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
699
710
  let e = n[l];
700
711
  n[t] = e == null ? null : f.get(e) ?? null;
701
712
  }
702
- await Lr(d, r.with, o, a);
703
- }, jr = async (e, t, n, r, i, a) => {
704
- let o = n.target(), s = n.foreignKey ?? Yn(o, i.tableName, t), c = n.sourceKey ?? "id", l = Fr(e, c), u = Mr(r), d = l.length === 0 ? [] : await Ir(o, s, l, u, a), f = /* @__PURE__ */ new Map();
713
+ await Vr(d, r.with, o, a);
714
+ }, Fr = async (e, t, n, r, i, a) => {
715
+ let o = n.target(), s = n.foreignKey ?? $n(o, i.tableName, t), c = n.sourceKey ?? "id", l = zr(e, c), u = Ir(r), d = l.length === 0 ? [] : await Br(o, s, l, u, a), f = /* @__PURE__ */ new Map();
705
716
  for (let e of d) {
706
717
  let t = e[s], n = f.get(t);
707
718
  n ? n.push(e) : f.set(t, [e]);
@@ -717,12 +728,12 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
717
728
  let e = n[c];
718
729
  n[t] = f.get(e) ?? [];
719
730
  }
720
- await Lr(d, r.with, o, a);
721
- }, Mr = (e) => {
731
+ await Vr(d, r.with, o, a);
732
+ }, Ir = (e) => {
722
733
  let { limit: t, offset: n, ...r } = e;
723
734
  return r;
724
- }, Nr = async (e, t, n, r, i, a) => {
725
- let o = n.target(), s = n.through(), c = Fr(e, "id");
735
+ }, Lr = async (e, t, n, r, i, a) => {
736
+ let o = n.target(), s = n.through(), c = zr(e, "id");
726
737
  if (c.length === 0) {
727
738
  for (let n of e) n[t] = [];
728
739
  return;
@@ -743,8 +754,8 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
743
754
  for (let n of e) n[t] = [];
744
755
  return;
745
756
  }
746
- let f = await Ir(o, "id", Fr(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
747
- await Lr(f, r.with, o, a);
757
+ let f = await Br(o, "id", zr(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
758
+ await Vr(f, r.with, o, a);
748
759
  let m = r.junction === void 0 ? void 0 : r.junction === !0 ? Object.keys(s.fields) : r.junction, h = /* @__PURE__ */ new Map();
749
760
  for (let e of d) {
750
761
  let t = e[n.sourceKey], r = e[n.targetKey], i = p.get(r);
@@ -756,16 +767,16 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
756
767
  o ? o.push(a) : h.set(t, [a]);
757
768
  }
758
769
  for (let n of e) n[t] = h.get(n.id) ?? [];
759
- }, Pr = (e, t) => {
770
+ }, Rr = (e, t) => {
760
771
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
761
- }, Fr = (e, t) => {
772
+ }, zr = (e, t) => {
762
773
  let n = /* @__PURE__ */ new Set();
763
774
  for (let r of e) {
764
775
  let e = r[t];
765
776
  e != null && n.add(e);
766
777
  }
767
778
  return [...n];
768
- }, Ir = (e, t, n, r, i) => {
779
+ }, Br = (e, t, n, r, i) => {
769
780
  let a = {
770
781
  column: t,
771
782
  op: "in",
@@ -779,50 +790,50 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
779
790
  skip: r.offset,
780
791
  projection: void 0
781
792
  });
782
- }, Lr = async (e, t, n, r) => {
783
- t !== void 0 && e.length !== 0 && (await Or(e, t, n, r)).forEach((t, n) => {
793
+ }, Vr = async (e, t, n, r) => {
794
+ t !== void 0 && e.length !== 0 && (await Mr(e, t, n, r)).forEach((t, n) => {
784
795
  let r = e[n];
785
796
  for (let [e, n] of Object.entries(t)) e in r || (r[e] = n);
786
797
  });
787
- }, Rr = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, zr = class extends Error {
798
+ }, Hr = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, Ur = class extends Error {
788
799
  _tag = "TenantNamespaceUnresolved";
789
800
  constructor(e) {
790
801
  super(e), this.name = "TenantNamespaceUnresolved";
791
802
  }
792
- }, Br = class extends Error {
803
+ }, Wr = class extends Error {
793
804
  _tag = "TenantNamespaceInvalid";
794
805
  constructor(e) {
795
806
  super(e), this.name = "TenantNamespaceInvalid";
796
807
  }
797
- }, Vr = 63, Hr = "tenant_", Ur = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), Wr = (e) => {
798
- if (e == null || e === "") throw new zr("namespace isolation is on but the request has no resolvable tenant (subject.tenantId is null/empty). Refusing to run against a shared/default namespace — this would be a cross-tenant read. Authenticate with a tenant-scoped subject, or disable namespace isolation for this surface.");
799
- let t = Ur(e);
800
- if (t.replace(/_/g, "") === "") throw new Br(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
801
- let n = `${Hr}${t}`;
802
- if (n.length > Vr) throw new Br(`namespace '${n}' for tenant '${e}' exceeds the ${Vr}-byte identifier limit. Use a shorter tenant id.`);
808
+ }, Gr = 63, Kr = "tenant_", qr = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), Jr = (e) => {
809
+ if (e == null || e === "") throw new Ur("namespace isolation is on but the request has no resolvable tenant (subject.tenantId is null/empty). Refusing to run against a shared/default namespace — this would be a cross-tenant read. Authenticate with a tenant-scoped subject, or disable namespace isolation for this surface.");
810
+ let t = qr(e);
811
+ if (t.replace(/_/g, "") === "") throw new Wr(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
812
+ let n = `${Kr}${t}`;
813
+ if (n.length > Gr) throw new Wr(`namespace '${n}' for tenant '${e}' exceeds the ${Gr}-byte identifier limit. Use a shorter tenant id.`);
803
814
  return n;
804
- }, Gr = (e, t) => e === null ? t : `${e}.${t}`, Kr = /* @__PURE__ */ new Set(["timestamp", "date"]), qr = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, Jr = (e, t) => {
805
- if (e === void 0 || t == null || !Kr.has(e) || t instanceof Date) return t;
815
+ }, Yr = (e, t) => e === null ? t : `${e}.${t}`, Xr = /* @__PURE__ */ new Set(["timestamp", "date"]), Zr = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, Qr = (e, t) => {
816
+ if (e === void 0 || t == null || !Xr.has(e) || t instanceof Date) return t;
806
817
  if (typeof t == "number" && Number.isFinite(t)) return new Date(t);
807
- if (typeof t == "string" && qr.test(t)) {
818
+ if (typeof t == "string" && Zr.test(t)) {
808
819
  let e = new Date(t);
809
820
  return Number.isNaN(e.getTime()) ? t : e;
810
821
  }
811
822
  return t;
812
- }, Yr = (e, t) => e === void 0 || !Kr.has(e) ? t : t.map((t) => Jr(e, t)), Xr = (e, t) => {
823
+ }, $r = (e, t) => e === void 0 || !Xr.has(e) ? t : t.map((t) => Qr(e, t)), ei = (e, t) => {
813
824
  let { strings: n, values: r } = e, i = t.unsafe(n[0] ?? "");
814
825
  for (let e = 0; e < r.length; e++) i = t`${i}${r[e]}${t.unsafe(n[e + 1] ?? "")}`;
815
826
  return t`${i}`;
816
- }, Zr = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), L = (e, t, n = null, r) => {
827
+ }, ti = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), L = (e, t, n = null, r) => {
817
828
  if ("not" in e) return t`NOT (${L(e.not, t, n, r)})`;
818
829
  if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => L(e, t, n, r)));
819
830
  if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => L(e, t, n, r)));
820
831
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
821
- let r = e, i = ci(r.subquery, t, n);
832
+ let r = e, i = fi(r.subquery, t, n);
822
833
  return r.op === "subquery-in" ? t`${t(r.column)} IN (${i})` : t`${t(r.column)} NOT IN (${i})`;
823
834
  }
824
835
  if (e.op === "exists" || e.op === "not-exists") {
825
- let r = e, i = ci(r.subquery, t, n);
836
+ let r = e, i = fi(r.subquery, t, n);
826
837
  return r.op === "exists" ? t`EXISTS (${i})` : t`NOT EXISTS (${i})`;
827
838
  }
828
839
  let i = e, a = t(i.column), o = i.path, s = o !== void 0 && o.length > 0, c = () => t.onDialectOrElse({
@@ -835,7 +846,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
835
846
  mssql: () => t.unsafe(D(i.column, o, "mssql", { numeric: !0 })),
836
847
  sqlite: () => t.unsafe(D(i.column, o, "sqlite", { numeric: !0 })),
837
848
  orElse: () => t.unsafe(D(i.column, o, "postgres", { numeric: !0 }))
838
- }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, p = (e) => s ? Number(e) : e, m = s || r === void 0 ? void 0 : S(r)?.fields?.[i.column]?.type, h = (e) => Jr(m, e);
849
+ }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, p = (e) => s ? Number(e) : e, m = s || r === void 0 ? void 0 : S(r)?.fields?.[i.column]?.type, h = (e) => Qr(m, e);
839
850
  switch (i.op) {
840
851
  case "eq": return t`${u} = ${f(h(i.value))}`;
841
852
  case "neq": return t`${u} <> ${f(h(i.value))}`;
@@ -852,7 +863,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
852
863
  return e.length === 0 ? t`TRUE` : t`${u} NOT IN ${t.in(s ? e.map((e) => f(e)) : e)}`;
853
864
  }
854
865
  case "contains": {
855
- let e = `%${Zr(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
866
+ let e = `%${ti(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
856
867
  return t.onDialectOrElse({
857
868
  mysql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
858
869
  mssql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
@@ -861,7 +872,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
861
872
  });
862
873
  }
863
874
  case "startsWith": {
864
- let e = `${Zr(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
875
+ let e = `${ti(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
865
876
  return t.onDialectOrElse({
866
877
  mysql: () => t`${u} LIKE ${e}`,
867
878
  orElse: () => t`${u} LIKE ${e} ESCAPE '\\'`
@@ -909,13 +920,13 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
909
920
  });
910
921
  }
911
922
  }
912
- }, Qr = (e, t) => {
923
+ }, ni = (e, t) => {
913
924
  let n = [];
914
925
  return e.partitionBy && e.partitionBy.length > 0 && n.push(t`PARTITION BY ${t.csv(e.partitionBy.map((e) => t`${t(e)}`))}`), e.orderBy && e.orderBy.length > 0 && n.push(t`ORDER BY ${t.csv(e.orderBy.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), n.length === 0 ? t`` : n.length === 1 ? n[0] : n.reduce((e, n, r) => r === 0 ? n : t`${e} ${n}`);
915
- }, $r = (e, t) => t.csv(e.map((e) => {
926
+ }, ri = (e, t) => t.csv(e.map((e) => {
916
927
  let n = e.column === void 0 ? t.unsafe("*") : t`${t(e.column)}`;
917
928
  if (e.op.startsWith("window-")) {
918
- let r = Qr(e.window ?? {}, t);
929
+ let r = ni(e.window ?? {}, t);
919
930
  switch (e.op) {
920
931
  case "window-row-number": return t`ROW_NUMBER() OVER (${r}) AS ${t(e.alias)}`;
921
932
  case "window-rank": return t`RANK() OVER (${r}) AS ${t(e.alias)}`;
@@ -939,43 +950,43 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
939
950
  return t`${t(e.column)} AS ${t(e.alias)}`;
940
951
  default: throw Error(`compileAggregateProjection: unknown op '${e.op}'`);
941
952
  }
942
- })), ei = (e) => `[${e.join(",")}]`, ti = (e, t) => {
953
+ })), ii = (e) => `[${e.join(",")}]`, ai = (e, t) => {
943
954
  if (e.queryVector === void 0) return null;
944
- let n = t(e.column), r = ei(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
955
+ let n = t(e.column), r = ii(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
945
956
  return t.onDialectOrElse({
946
957
  mysql: () => t`${t.unsafe(a)}(${n}, ${r})`,
947
958
  mssql: () => t`NULL`,
948
959
  sqlite: () => t`NULL`,
949
960
  orElse: () => t`${n} ${t.unsafe(i)} ${r}::vector`
950
961
  });
951
- }, ni = (e, t) => {
962
+ }, oi = (e, t) => {
952
963
  let n = t.unsafe(e.useGeography ? "::geography" : "::geometry");
953
964
  return t`ST_Distance(${t(e.column)}${n}, ${e.geom}${n})`;
954
- }, ri = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, ii = (e, t) => t`${t(`${e.indexName}_tsv`)}`, ai = (e, t) => `${t}_${e.indexName}_fts`, oi = (e, t, n) => {
955
- let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${Zr(e.query)}%`;
965
+ }, si = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, ci = (e, t) => t`${t(`${e.indexName}_tsv`)}`, li = (e, t) => `${t}_${e.indexName}_fts`, ui = (e, t, n) => {
966
+ let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${ti(e.query)}%`;
956
967
  return n.onDialectOrElse({
957
968
  mysql: () => n`MATCH(${r}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
958
969
  sqlite: () => {
959
- let r = n(ai(e, t));
970
+ let r = n(li(e, t));
960
971
  return n`${n("id")} IN (SELECT ${n("row_id")} FROM ${r} WHERE ${r} MATCH ${e.query})`;
961
972
  },
962
973
  mssql: () => n.or(e.columns.map((e) => n`LOWER(${n(e)}) LIKE LOWER(${i}) ESCAPE '\\'`)),
963
- orElse: () => n`${ii(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
974
+ orElse: () => n`${ci(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
964
975
  });
965
- }, si = (e, t, n) => {
966
- let r = `%${Zr(e.query)}%`;
976
+ }, di = (e, t, n) => {
977
+ let r = `%${ti(e.query)}%`;
967
978
  return n.onDialectOrElse({
968
979
  mysql: () => n`MATCH(${n.csv(e.columns.map((e) => n`${n(e)}`))}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
969
980
  sqlite: () => {
970
- let r = n(ai(e, t));
981
+ let r = n(li(e, t));
971
982
  return n`COALESCE((SELECT -bm25(${r}) FROM ${r} WHERE ${r} MATCH ${e.query} AND ${r}.${n("row_id")} = ${n("id")}), 0)`;
972
983
  },
973
984
  mssql: () => e.columns.map((e) => n`(CASE WHEN LOWER(${n(e)}) LIKE LOWER(${r}) ESCAPE '\\' THEN 1 ELSE 0 END)`).reduce((e, t, r) => r === 0 ? t : n`${e} + ${t}`),
974
- orElse: () => n`ts_rank(${ii(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
985
+ orElse: () => n`ts_rank(${ci(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
975
986
  });
976
- }, ci = (e, t, n = null) => {
987
+ }, fi = (e, t, n = null) => {
977
988
  if (e.setOp && e.setOp.queries.length >= 2) {
978
- let r = e.setOp.kind === "union" ? "UNION" : e.setOp.kind === "union-all" ? "UNION ALL" : e.setOp.kind === "intersect" ? "INTERSECT" : "EXCEPT", i = e.setOp.queries.map((e) => t`(${ci(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
989
+ let r = e.setOp.kind === "union" ? "UNION" : e.setOp.kind === "union-all" ? "UNION ALL" : e.setOp.kind === "intersect" ? "INTERSECT" : "EXCEPT", i = e.setOp.queries.map((e) => t`(${fi(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
979
990
  if (v(e).length > 0 && a.push(t` ORDER BY ${t.csv(v(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
980
991
  if (!Number.isInteger(e.take) || e.take < 0) throw Error(`compileSelect: invalid take ${e.take}`);
981
992
  a.push(t` LIMIT ${t.unsafe(String(e.take))}`);
@@ -986,7 +997,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
986
997
  }
987
998
  return t`${i}${a.reduce((e, n) => t`${e}${n}`, t``)}`;
988
999
  }
989
- let r = e.annClause === void 0 ? null : ti(e.annClause, t);
1000
+ let r = e.annClause === void 0 ? null : ai(e.annClause, t);
990
1001
  e.spatialClause !== void 0 && t.onDialectOrElse({
991
1002
  mysql: () => {
992
1003
  throw Error("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
@@ -999,7 +1010,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
999
1010
  },
1000
1011
  orElse: () => t``
1001
1012
  });
1002
- let i = e.spatialClause?.projectAs === void 0 ? null : ni(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? $r(e.aggregations, t) : e.joinedProjection && e.joinedProjection.length > 0 ? t.csv(e.joinedProjection.map((e) => t`${t(e.source)} AS ${t(e.outputKey)}`)) : e.projection && e.projection.length > 0 ? t.csv(e.projection.map((e) => t`${t(e)}`)) : t`*`, o = (e.aggregations && e.aggregations.length > 0) === !0, s = r !== null && !o ? t`${a}, ${r} AS ${t("distance")}` : a, c = e.fullTextSearch, l = c?.rank !== void 0 && !o ? si(c, e.table, t) : null, u = l !== null && c?.rank !== void 0 ? t`${s}, ${l} AS ${t(c.rank.alias)}` : s, d = i !== null && !o && e.spatialClause?.projectAs !== void 0 ? t`${u}, ${i} AS ${t(e.spatialClause.projectAs)}` : u, f = e.distinctOn && e.distinctOn.length > 0 ? t.onDialectOrElse({
1013
+ let i = e.spatialClause?.projectAs === void 0 ? null : oi(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? ri(e.aggregations, t) : e.joinedProjection && e.joinedProjection.length > 0 ? t.csv(e.joinedProjection.map((e) => t`${t(e.source)} AS ${t(e.outputKey)}`)) : e.projection && e.projection.length > 0 ? t.csv(e.projection.map((e) => t`${t(e)}`)) : t`*`, o = (e.aggregations && e.aggregations.length > 0) === !0, s = r !== null && !o ? t`${a}, ${r} AS ${t("distance")}` : a, c = e.fullTextSearch, l = c?.rank !== void 0 && !o ? di(c, e.table, t) : null, u = l !== null && c?.rank !== void 0 ? t`${s}, ${l} AS ${t(c.rank.alias)}` : s, d = i !== null && !o && e.spatialClause?.projectAs !== void 0 ? t`${u}, ${i} AS ${t(e.spatialClause.projectAs)}` : u, f = e.distinctOn && e.distinctOn.length > 0 ? t.onDialectOrElse({
1003
1014
  orElse: () => t`DISTINCT ON (${t.csv(e.distinctOn.map((e) => t`${t(e)}`))}) `,
1004
1015
  mysql: () => t`DISTINCT `,
1005
1016
  mssql: () => t`DISTINCT `,
@@ -1011,11 +1022,11 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1011
1022
  mssql: () => t``,
1012
1023
  sqlite: () => t``,
1013
1024
  orElse: () => t` FOR UPDATE`
1014
- }) : t``, g = e.alias === void 0 ? t`${t(Gr(n, e.table))}${m}` : t`${t(Gr(n, e.table))} AS ${t(e.alias)}${m}`, ee = (e.joins ?? []).map((e) => {
1025
+ }) : t``, g = e.alias === void 0 ? t`${t(Yr(n, e.table))}${m}` : t`${t(Yr(n, e.table))} AS ${t(e.alias)}${m}`, ee = (e.joins ?? []).map((e) => {
1015
1026
  let r = e.kind === "inner" ? "INNER" : "LEFT";
1016
- return t` ${t.unsafe(r)} JOIN ${t(Gr(n, e.table))} AS ${t(e.alias)} ON ${L(e.on, t, n)}`;
1017
- }), te = ee.length > 0 ? ee.reduce((e, n) => t`${e}${n}`, g) : g, ne = c === void 0 ? null : oi(c, e.table, t), re = [e.predicate ? L(e.predicate, t, n, e.table) : null, ne].filter((e) => e !== null), _ = re.length > 0 ? t` WHERE ${t.and(re)}` : t``, ie = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, ae = e.having ? t` HAVING ${L(e.having, t, n, e.table)}` : t``, oe = e.skip !== void 0, y = [];
1018
- r !== null && y.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && y.push(e.spatialClause.order === "desc" ? t`${ri(e.spatialClause, t)} DESC` : t`${ri(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && y.push(t`${l} DESC`);
1027
+ return t` ${t.unsafe(r)} JOIN ${t(Yr(n, e.table))} AS ${t(e.alias)} ON ${L(e.on, t, n)}`;
1028
+ }), te = ee.length > 0 ? ee.reduce((e, n) => t`${e}${n}`, g) : g, ne = c === void 0 ? null : ui(c, e.table, t), re = [e.predicate ? L(e.predicate, t, n, e.table) : null, ne].filter((e) => e !== null), _ = re.length > 0 ? t` WHERE ${t.and(re)}` : t``, ie = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, ae = e.having ? t` HAVING ${L(e.having, t, n, e.table)}` : t``, oe = e.skip !== void 0, y = [];
1029
+ r !== null && y.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && y.push(e.spatialClause.order === "desc" ? t`${si(e.spatialClause, t)} DESC` : t`${si(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && y.push(t`${l} DESC`);
1019
1030
  for (let n of v(e)) y.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
1020
1031
  let se = y.length > 0 ? t` ORDER BY ${t.csv(y)}` : oe ? t.onDialectOrElse({
1021
1032
  mssql: () => t` ORDER BY (SELECT NULL)`,
@@ -1023,7 +1034,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1023
1034
  }) : t``, b = (e) => {
1024
1035
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`compileSelect: expected non-negative integer take/skip, got ${e}`);
1025
1036
  return t.unsafe(String(e));
1026
- }, ce = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${ci(e.descriptor, t, n)})`), le = (e.ctes ?? []).some((e) => e.recursive === !0), ue = ce.length > 0 ? t`WITH ${t.unsafe(le ? "RECURSIVE " : "")}${t.csv(ce)} ` : t``;
1037
+ }, ce = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${fi(e.descriptor, t, n)})`), le = (e.ctes ?? []).some((e) => e.recursive === !0), ue = ce.length > 0 ? t`WITH ${t.unsafe(le ? "RECURSIVE " : "")}${t.csv(ce)} ` : t``;
1027
1038
  return t.onDialectOrElse({
1028
1039
  mssql: () => {
1029
1040
  let n = e.take !== void 0 && !oe ? t`TOP ${b(e.take)} ` : t``, r = oe ? t` OFFSET ${b(e.skip)} ROWS FETCH NEXT ${b(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
@@ -1034,29 +1045,29 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1034
1045
  return t`${ue}SELECT ${f}${d} FROM ${te}${_}${ie}${ae}${se}${n}${r}${h}`;
1035
1046
  }
1036
1047
  });
1037
- }, li = (e, t, n) => {
1048
+ }, pi = (e, t, n) => {
1038
1049
  if (e.eager === void 0) return null;
1039
- let r = fi(e.table, e.eager, e.sourceTable);
1050
+ let r = gi(e.table, e.eager, e.sourceTable);
1040
1051
  if (r === null) return null;
1041
- let i = yi(n, e, r, vi(t, n));
1052
+ let i = Ci(n, e, r, Si(t, n));
1042
1053
  return i === null ? null : {
1043
1054
  fragment: i,
1044
- decode: Si(r, n)
1055
+ decode: Ei(r, n)
1045
1056
  };
1046
- }, ui = (e) => e.relation.kind === "one" && e.fkSide === "target", di = (e) => ({
1057
+ }, mi = (e) => e.relation.kind === "one" && e.fkSide === "target", hi = (e) => ({
1047
1058
  ...e,
1048
1059
  branch: {
1049
1060
  ...e.branch,
1050
1061
  limit: 2
1051
1062
  }
1052
- }), fi = (e, t, n) => {
1053
- let r = n ?? Ve(e), i = ir(e);
1063
+ }), gi = (e, t, n) => {
1064
+ let r = n ?? Ve(e), i = cr(e);
1054
1065
  if (i === void 0) return null;
1055
1066
  let a = [];
1056
1067
  for (let [e, n] of Object.entries(t)) {
1057
1068
  let t = i[e];
1058
1069
  if (t === void 0) return null;
1059
- let o = pi(e, t, r, n === !0 ? {} : n);
1070
+ let o = _i(e, t, r, n === !0 ? {} : n);
1060
1071
  if (o === null) return null;
1061
1072
  a.push(o);
1062
1073
  }
@@ -1064,30 +1075,30 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1064
1075
  table: r,
1065
1076
  children: a
1066
1077
  };
1067
- }, pi = (e, t, n, r) => {
1078
+ }, _i = (e, t, n, r) => {
1068
1079
  let i = t.target(), a = (t.kind === "manyToMany" ? void 0 : t.sourceKey) ?? "id", o, s;
1069
1080
  if (t.kind === "manyToMany") o = t.targetKey, s = "target";
1070
1081
  else if (t.kind === "one") {
1071
- let r = t.sourceKey ?? _i(n, i.tableName);
1082
+ let r = t.sourceKey ?? xi(n, i.tableName);
1072
1083
  if (r !== void 0) o = r, s = "source";
1073
1084
  else try {
1074
- o = t.foreignKey ?? Yn(i, n.tableName, e), s = "target";
1085
+ o = t.foreignKey ?? $n(i, n.tableName, e), s = "target";
1075
1086
  } catch {
1076
1087
  return null;
1077
1088
  }
1078
1089
  } else try {
1079
- o = t.foreignKey ?? Yn(i, n.tableName, e), s = "target";
1090
+ o = t.foreignKey ?? $n(i, n.tableName, e), s = "target";
1080
1091
  } catch {
1081
1092
  return null;
1082
1093
  }
1083
1094
  let c = r.with === void 0 ? [] : (() => {
1084
- let e = ir(i.tableName);
1095
+ let e = cr(i.tableName);
1085
1096
  if (e === void 0 && Object.keys(r.with).length > 0) return null;
1086
1097
  let t = [];
1087
1098
  for (let [n, a] of Object.entries(r.with)) {
1088
1099
  let r = e?.[n];
1089
1100
  if (r === void 0) return null;
1090
- let o = pi(n, r, i, a === !0 ? {} : a);
1101
+ let o = _i(n, r, i, a === !0 ? {} : a);
1091
1102
  if (o === null) return null;
1092
1103
  t.push(o);
1093
1104
  }
@@ -1103,9 +1114,9 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1103
1114
  fkSide: s,
1104
1115
  branch: r,
1105
1116
  children: c,
1106
- junction: mi(t, r)
1117
+ junction: vi(t, r)
1107
1118
  };
1108
- }, mi = (e, t) => {
1119
+ }, vi = (e, t) => {
1109
1120
  if (e.kind !== "manyToMany" || t.junction === void 0) return;
1110
1121
  let n = e.through(), r = t.junction === !0 ? Object.keys(n.fields) : t.junction, i = r.filter((e) => e in n.fields);
1111
1122
  return {
@@ -1117,35 +1128,35 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1117
1128
  return t !== void 0 && (t.type === "timestamp" || t.type === "date");
1118
1129
  })
1119
1130
  };
1120
- }, hi = (e) => `__j_${e}`, gi = "__j", _i = (e, t) => {
1131
+ }, yi = (e) => `__j_${e}`, bi = "__j", xi = (e, t) => {
1121
1132
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
1122
- }, vi = (e, t) => {
1133
+ }, Si = (e, t) => {
1123
1134
  let n = 0;
1124
1135
  return {
1125
1136
  sql: e,
1126
1137
  dialect: t,
1127
1138
  nextAlias: () => `__a${n++}`
1128
1139
  };
1129
- }, yi = (e, t, n, r) => {
1140
+ }, Ci = (e, t, n, r) => {
1130
1141
  switch (e) {
1131
- case "postgres": return Ti(t, n, r);
1142
+ case "postgres": return ki(t, n, r);
1132
1143
  case "sqlite":
1133
- case "turso": return Ni(t, n, r);
1144
+ case "turso": return Li(t, n, r);
1134
1145
  case "mysql":
1135
- case "mariadb": return Ui(t, n, r);
1136
- case "mssql": return Xi(t, n, r);
1146
+ case "mariadb": return qi(t, n, r);
1147
+ case "mssql": return ea(t, n, r);
1137
1148
  }
1138
- }, bi = (e, t) => t === "mssql" && !xi.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), xi = /(?:Z|[+-]\d{2}:?\d{2})$/, Si = (e, t) => {
1139
- let n = Ci(e.table, e.children, t);
1149
+ }, wi = (e, t) => t === "mssql" && !Ti.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), Ti = /(?:Z|[+-]\d{2}:?\d{2})$/, Ei = (e, t) => {
1150
+ let n = Di(e.table, e.children, t);
1140
1151
  return (e) => e.map((e) => {
1141
1152
  let t = e.__row, r = typeof t == "string" ? JSON.parse(t) : t;
1142
1153
  return n(r);
1143
1154
  });
1144
- }, Ci = (e, t, n) => {
1155
+ }, Di = (e, t, n) => {
1145
1156
  let r = [];
1146
1157
  for (let [t, n] of Object.entries(e.fields)) (n.type === "timestamp" || n.type === "date") && r.push(t);
1147
1158
  let i = t.map((e) => {
1148
- let t = Ci(e.target, e.children, n), r = e.relation.kind === "one", i = ui(e), a = i ? Dr({
1159
+ let t = Di(e.target, e.children, n), r = e.relation.kind === "one", i = mi(e), a = i ? jr({
1149
1160
  relationName: e.relationName,
1150
1161
  sourceTableName: e.source.tableName,
1151
1162
  targetTableName: e.target.tableName,
@@ -1158,14 +1169,14 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1158
1169
  isSingle: r,
1159
1170
  fromOverFetch: i,
1160
1171
  cardinalityMessage: a,
1161
- junction: wi(e.junction, n)
1172
+ junction: Oi(e.junction, n)
1162
1173
  };
1163
1174
  });
1164
1175
  return (e) => {
1165
1176
  let t = { ...e };
1166
1177
  for (let e of r) {
1167
1178
  let r = t[e];
1168
- typeof r == "string" && (t[e] = bi(r, n));
1179
+ typeof r == "string" && (t[e] = wi(r, n));
1169
1180
  }
1170
1181
  for (let e of i) {
1171
1182
  let n = t[e.name];
@@ -1175,7 +1186,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1175
1186
  }
1176
1187
  if (e.fromOverFetch) {
1177
1188
  let r = n;
1178
- if (r.length > 1) throw new Er(e.cardinalityMessage);
1189
+ if (r.length > 1) throw new Ar(e.cardinalityMessage);
1179
1190
  t[e.name] = r.length === 0 ? null : e.decode(r[0]);
1180
1191
  continue;
1181
1192
  }
@@ -1187,104 +1198,104 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1187
1198
  }
1188
1199
  return t;
1189
1200
  };
1190
- }, wi = (e, t) => {
1201
+ }, Oi = (e, t) => {
1191
1202
  if (e === void 0) return;
1192
1203
  let n = new Set(e.dateColumns), r = e.requested;
1193
1204
  return (e) => {
1194
1205
  let i = e._junction ?? {}, a = {};
1195
1206
  for (let e of r) {
1196
1207
  let r = i[e];
1197
- a[e] = n.has(e) && typeof r == "string" ? bi(r, t) : r;
1208
+ a[e] = n.has(e) && typeof r == "string" ? wi(r, t) : r;
1198
1209
  }
1199
1210
  return {
1200
1211
  ...e,
1201
1212
  _junction: a
1202
1213
  };
1203
1214
  };
1204
- }, Ti = (e, t, n) => {
1205
- let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = Ei(i, t.children, n);
1215
+ }, ki = (e, t, n) => {
1216
+ let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = Ai(i, t.children, n);
1206
1217
  return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``}${v(e).length > 0 ? r` ORDER BY ${r.csv(v(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`}`;
1207
- }, Ei = (e, t, n, r) => {
1208
- let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${V(gi, i)}::text)`;
1218
+ }, Ai = (e, t, n, r) => {
1219
+ let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${V(bi, i)}::text)`;
1209
1220
  if (t.length === 0 && r === void 0) return a;
1210
1221
  let o = [];
1211
- r !== void 0 && o.push(i`${V("_junction", i)}, ${B(e, gi, i)}`);
1222
+ r !== void 0 && o.push(i`${V("_junction", i)}, ${B(e, bi, i)}`);
1212
1223
  for (let r of t) {
1213
- let t = Di(r, e, n);
1224
+ let t = ji(r, e, n);
1214
1225
  if (t === null) return null;
1215
1226
  o.push(i`${V(r.relationName, i)}, ${t}`);
1216
1227
  }
1217
1228
  return i`${a} || jsonb_build_object(${i.csv(o)})`;
1218
- }, Di = (e, t, n) => {
1229
+ }, ji = (e, t, n) => {
1219
1230
  switch (e.relation.kind) {
1220
- case "one": return ui(e) ? ki(di(e), t, n) : Oi(e, t, n);
1221
- case "many": return ki(e, t, n);
1222
- case "manyToMany": return Ai(e, t, n);
1231
+ case "one": return mi(e) ? Ni(hi(e), t, n) : Mi(e, t, n);
1232
+ case "many": return Ni(e, t, n);
1233
+ case "manyToMany": return Pi(e, t, n);
1223
1234
  }
1224
- }, Oi = (e, t, n) => {
1225
- let r = n.sql, i = n.nextAlias(), a = Ei(i, e.children, n);
1235
+ }, Mi = (e, t, n) => {
1236
+ let r = n.sql, i = n.nextAlias(), a = Ai(i, e.children, n);
1226
1237
  if (a === null) return null;
1227
1238
  let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, i, r)}`, c = R(i, e.branch.orderBy, r);
1228
1239
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}${c} LIMIT 1)`;
1229
- }, ki = (e, t, n) => {
1230
- let r = n.sql, i = n.nextAlias(), a = Ei(i, e.children, n);
1240
+ }, Ni = (e, t, n) => {
1241
+ let r = n.sql, i = n.nextAlias(), a = Ai(i, e.children, n);
1231
1242
  if (a === null) return null;
1232
- let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, c = Mi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1243
+ let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, c = Ii(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1233
1244
  return r`COALESCE((SELECT jsonb_agg(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), '[]'::jsonb)`;
1234
- }, Ai = (e, t, n) => {
1235
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ei(o, e.children, n, e.junction);
1245
+ }, Pi = (e, t, n) => {
1246
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ai(o, e.children, n, e.junction);
1236
1247
  if (c === null) return null;
1237
- let l = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, u = ia(e, s, r), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${ji(e.junction, s, r)} AS ${r(gi)}`;
1248
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, u = ca(e, s, r), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${Fi(e.junction, s, r)} AS ${r(bi)}`;
1238
1249
  return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
1239
- }, ji = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t, e, n)}`))})`, R = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${B(e, t.column, n)} DESC` : n`${B(e, t.column, n)} ASC`))}`, Mi = (e, t) => e === void 0 || e.length === 0 ? t`` : t` ORDER BY ${t.csv(e.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`, Ni = (e, t, n) => {
1240
- let r = n.sql, i = n.nextAlias(), a = Pi(i, t.table, t.children, n);
1250
+ }, Fi = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t, e, n)}`))})`, R = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${B(e, t.column, n)} DESC` : n`${B(e, t.column, n)} ASC`))}`, Ii = (e, t) => e === void 0 || e.length === 0 ? t`` : t` ORDER BY ${t.csv(e.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`, Li = (e, t, n) => {
1251
+ let r = n.sql, i = n.nextAlias(), a = Ri(i, t.table, t.children, n);
1241
1252
  if (a === null) return null;
1242
1253
  let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = v(e).length > 0 ? r` ORDER BY ${r.csv(v(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
1243
1254
  return r`SELECT ${a} AS "__row" FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1244
- }, Pi = (e, t, n, r, i) => {
1255
+ }, Ri = (e, t, n, r, i) => {
1245
1256
  let a = r.sql, o = [];
1246
1257
  for (let n of Object.keys(t.fields)) o.push(a`${V(n, a)}, ${B(e, n, a)}`);
1247
1258
  if (i !== void 0) {
1248
- let e = Fi(i.projection, i.source, a);
1259
+ let e = zi(i.projection, i.source, a);
1249
1260
  o.push(a`${V("_junction", a)}, json_object(${e})`);
1250
1261
  }
1251
1262
  for (let t of n) {
1252
- let n = zi(t, e, r);
1263
+ let n = Ui(t, e, r);
1253
1264
  if (n === null) return null;
1254
1265
  o.push(a`${V(t.relationName, a)}, ${n}`);
1255
1266
  }
1256
1267
  return a`json_object(${a.csv(o)})`;
1257
- }, Fi = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t.alias, t.physical(e), n)}`)), Ii = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${B(t, e, n)} AS ${n(hi(e))}`))}`, Li = (e) => ({
1268
+ }, zi = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t.alias, t.physical(e), n)}`)), Bi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${B(t, e, n)} AS ${n(yi(e))}`))}`, Vi = (e) => ({
1258
1269
  alias: e,
1259
- physical: hi
1260
- }), Ri = (e) => ({
1270
+ physical: yi
1271
+ }), Hi = (e) => ({
1261
1272
  alias: e,
1262
1273
  physical: (e) => e
1263
- }), zi = (e, t, n) => {
1274
+ }), Ui = (e, t, n) => {
1264
1275
  switch (e.relation.kind) {
1265
- case "one": return ui(e) ? Vi(di(e), t, n) : Bi(e, t, n);
1266
- case "many": return Vi(e, t, n);
1267
- case "manyToMany": return Hi(e, t, n);
1276
+ case "one": return mi(e) ? Gi(hi(e), t, n) : Wi(e, t, n);
1277
+ case "many": return Gi(e, t, n);
1278
+ case "manyToMany": return Ki(e, t, n);
1268
1279
  }
1269
- }, Bi = (e, t, n) => {
1270
- let r = n.sql, i = n.nextAlias(), a = Pi(i, e.target, e.children, n);
1280
+ }, Wi = (e, t, n) => {
1281
+ let r = n.sql, i = n.nextAlias(), a = Ri(i, e.target, e.children, n);
1271
1282
  if (a === null) return null;
1272
1283
  let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1273
1284
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1274
- }, Vi = (e, t, n) => {
1275
- let r = n.sql, i = n.nextAlias(), a = Pi(i, e.target, e.children, n);
1285
+ }, Gi = (e, t, n) => {
1286
+ let r = n.sql, i = n.nextAlias(), a = Ri(i, e.target, e.children, n);
1276
1287
  if (a === null) return null;
1277
- let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = Mi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1288
+ let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = Ii(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1278
1289
  return r`COALESCE((SELECT json_group_array(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), json('[]'))`;
1279
- }, Hi = (e, t, n) => {
1280
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Pi(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1290
+ }, Ki = (e, t, n) => {
1291
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ri(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1281
1292
  projection: e.junction,
1282
- source: Li(o)
1293
+ source: Vi(o)
1283
1294
  });
1284
1295
  if (c === null) return null;
1285
- let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = ia(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Ii(e.junction, s, r);
1296
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = ca(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Bi(e.junction, s, r);
1286
1297
  return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
1287
- }, Ui = (e, t, n) => {
1298
+ }, qi = (e, t, n) => {
1288
1299
  let r = n.sql, i = n.nextAlias(), a = z(i, t.table, t.children, n);
1289
1300
  if (a === null) return null;
1290
1301
  let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = v(e).length > 0 ? r` ORDER BY ${r.csv(v(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
@@ -1293,66 +1304,66 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1293
1304
  let a = r.sql, o = [];
1294
1305
  for (let n of Object.keys(t.fields)) o.push(a`${V(n, a)}, ${B(e, n, a)}`);
1295
1306
  if (i !== void 0) {
1296
- let e = Fi(i.projection, i.source, a);
1307
+ let e = zi(i.projection, i.source, a);
1297
1308
  o.push(a`${V("_junction", a)}, JSON_OBJECT(${e})`);
1298
1309
  }
1299
1310
  for (let t of n) {
1300
- let n = Wi(t, e, r);
1311
+ let n = Ji(t, e, r);
1301
1312
  if (n === null) return null;
1302
1313
  o.push(a`${V(t.relationName, a)}, ${n}`);
1303
1314
  }
1304
1315
  return a`JSON_OBJECT(${a.csv(o)})`;
1305
- }, Wi = (e, t, n) => {
1316
+ }, Ji = (e, t, n) => {
1306
1317
  switch (e.relation.kind) {
1307
1318
  case "one":
1308
- if (ui(e)) {
1309
- let r = di(e);
1310
- return n.dialect === "mariadb" ? Ji(r, t, n) : Ki(r, t, n);
1319
+ if (mi(e)) {
1320
+ let r = hi(e);
1321
+ return n.dialect === "mariadb" ? Qi(r, t, n) : Xi(r, t, n);
1311
1322
  }
1312
- return Gi(e, t, n);
1313
- case "many": return n.dialect === "mariadb" ? Ji(e, t, n) : Ki(e, t, n);
1314
- case "manyToMany": return n.dialect === "mariadb" ? Yi(e, t, n) : qi(e, t, n);
1323
+ return Yi(e, t, n);
1324
+ case "many": return n.dialect === "mariadb" ? Qi(e, t, n) : Xi(e, t, n);
1325
+ case "manyToMany": return n.dialect === "mariadb" ? $i(e, t, n) : Zi(e, t, n);
1315
1326
  }
1316
- }, Gi = (e, t, n) => {
1327
+ }, Yi = (e, t, n) => {
1317
1328
  let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1318
1329
  if (a === null) return null;
1319
1330
  let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1320
1331
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1321
- }, Ki = (e, t, n) => {
1332
+ }, Xi = (e, t, n) => {
1322
1333
  let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1323
1334
  if (a === null) return null;
1324
- let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = Mi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1335
+ let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = Ii(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1325
1336
  return r`COALESCE((SELECT JSON_ARRAYAGG(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), JSON_ARRAY())`;
1326
- }, qi = (e, t, n) => {
1337
+ }, Zi = (e, t, n) => {
1327
1338
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = z(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1328
1339
  projection: e.junction,
1329
- source: Li(o)
1340
+ source: Vi(o)
1330
1341
  });
1331
1342
  if (c === null) return null;
1332
- let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = ia(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Ii(e.junction, s, r);
1343
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = ca(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Bi(e.junction, s, r);
1333
1344
  return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
1334
- }, Ji = (e, t, n) => {
1345
+ }, Qi = (e, t, n) => {
1335
1346
  let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1336
1347
  if (a === null) return null;
1337
1348
  let o = r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1338
1349
  if (e.branch.limit === void 0 && e.branch.offset === void 0) return r`COALESCE((SELECT JSON_ARRAYAGG(${a}${c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
1339
1350
  let l = c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${r(e.column)} DESC` : r`${r(e.column)} ASC`))}` : r` ORDER BY ${r("id")}`, u = e.branch.limit, d = e.branch.offset, f = u !== void 0 && d !== void 0 ? r` AND ${B(i, "rn", r)} > ${H(d, r)} AND ${B(i, "rn", r)} <= ${H(d + u, r)}` : u === void 0 ? r` AND ${B(i, "rn", r)} > ${H(d, r)}` : r` AND ${B(i, "rn", r)} <= ${H(u, r)}`;
1340
1351
  return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${B(i, "rn", r)}) FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${r(e.foreignKey)}${l}) AS rn FROM ${r(e.target.tableName)}) AS ${r(i)} WHERE ${o}${s}${f}), JSON_ARRAY())`;
1341
- }, Yi = (e, t, n) => {
1352
+ }, $i = (e, t, n) => {
1342
1353
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = (t) => e.junction === void 0 ? void 0 : {
1343
1354
  projection: e.junction,
1344
1355
  source: t
1345
- }, l = r`${B(s, i.sourceKey, r)} = ${B(t, "id", r)}`, u = r`${B(o, "id", r)} = ${B(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, f = ia(e, s, r, !0), p = e.branch.orderBy ?? [];
1356
+ }, l = r`${B(s, i.sourceKey, r)} = ${B(t, "id", r)}`, u = r`${B(o, "id", r)} = ${B(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, f = ca(e, s, r, !0), p = e.branch.orderBy ?? [];
1346
1357
  if (e.branch.limit === void 0 && e.branch.offset === void 0) {
1347
- let t = z(o, e.target, e.children, n, c(Ri(s)));
1358
+ let t = z(o, e.target, e.children, n, c(Hi(s)));
1348
1359
  return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r``}) FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u} WHERE ${l}${f}${d}), JSON_ARRAY())`;
1349
1360
  }
1350
- let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r` ORDER BY ${B(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, ee = h !== void 0 && g !== void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)} AND ${B(o, "rn", r)} <= ${H(g + h, r)}` : h === void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)}` : r` AND ${B(o, "rn", r)} <= ${H(h, r)}`, te = e.branch.onJunction === void 0 ? r`` : r` WHERE ${U(W(e.branch.onJunction), s, r)}`, ne = z(o, e.target, e.children, n, c(Li(o)));
1361
+ let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r` ORDER BY ${B(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, ee = h !== void 0 && g !== void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)} AND ${B(o, "rn", r)} <= ${H(g + h, r)}` : h === void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)}` : r` AND ${B(o, "rn", r)} <= ${H(h, r)}`, te = e.branch.onJunction === void 0 ? r`` : r` WHERE ${U(W(e.branch.onJunction), s, r)}`, ne = z(o, e.target, e.children, n, c(Vi(o)));
1351
1362
  if (ne === null) return null;
1352
- let re = e.junction === void 0 ? r`` : Ii(e.junction, s, r);
1363
+ let re = e.junction === void 0 ? r`` : Bi(e.junction, s, r);
1353
1364
  return r`COALESCE((SELECT JSON_ARRAYAGG(${ne} ORDER BY ${B(o, "rn", r)}) FROM (SELECT ${r(o)}.*${re}, ${B(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${B(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${te}) AS ${r(o)} WHERE ${B(o, `__src_${i.sourceKey}`, r)} = ${B(t, "id", r)}${d}${ee}), JSON_ARRAY())`;
1354
- }, Xi = (e, t, n) => {
1355
- let r = n.sql, i = n.nextAlias(), a = Zi(i, t.table, t.children, n);
1365
+ }, ea = (e, t, n) => {
1366
+ let r = n.sql, i = n.nextAlias(), a = ta(i, t.table, t.children, n);
1356
1367
  if (a === null) return null;
1357
1368
  let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = v(e).length > 0 ? r` ORDER BY ${r.csv(v(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1358
1369
  if (e.skip !== void 0) {
@@ -1361,28 +1372,28 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1361
1372
  } else e.take !== void 0 && (c = r`TOP ${H(e.take, r)} `);
1362
1373
  let u = e.skip === void 0 ? s : r``;
1363
1374
  return r`SELECT ${c}(SELECT ${a} FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER) AS ${r("__row")} FROM ${r(t.table.tableName)} AS ${r(i)}${o}${u}${l}`;
1364
- }, Zi = (e, t, n, r, i) => {
1375
+ }, ta = (e, t, n, r, i) => {
1365
1376
  let a = r.sql, o = [];
1366
1377
  for (let n of Object.keys(t.fields)) o.push(a`${B(e, n, a)} AS ${a(n)}`);
1367
- if (i !== void 0) for (let e of i.projection.present) o.push(a`${B(i.source.alias, i.source.physical(e), a)} AS ${Qi(`_junction.${e}`, a)}`);
1378
+ if (i !== void 0) for (let e of i.projection.present) o.push(a`${B(i.source.alias, i.source.physical(e), a)} AS ${na(`_junction.${e}`, a)}`);
1368
1379
  for (let t of n) {
1369
- let n = $i(t, e, r);
1380
+ let n = ra(t, e, r);
1370
1381
  if (n === null) return null;
1371
1382
  o.push(n);
1372
1383
  }
1373
1384
  return a.csv(o);
1374
- }, Qi = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), $i = (e, t, n) => {
1385
+ }, na = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), ra = (e, t, n) => {
1375
1386
  switch (e.relation.kind) {
1376
- case "one": return ui(e) ? na(di(e), t, n) : ea(e, t, n);
1377
- case "many": return na(e, t, n);
1378
- case "manyToMany": return ra(e, t, n);
1387
+ case "one": return mi(e) ? oa(hi(e), t, n) : ia(e, t, n);
1388
+ case "many": return oa(e, t, n);
1389
+ case "manyToMany": return sa(e, t, n);
1379
1390
  }
1380
- }, ea = (e, t, n) => {
1381
- let r = n.sql, i = n.nextAlias(), a = Zi(i, e.target, e.children, n);
1391
+ }, ia = (e, t, n) => {
1392
+ let r = n.sql, i = n.nextAlias(), a = ta(i, e.target, e.children, n);
1382
1393
  if (a === null) return null;
1383
1394
  let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1384
1395
  return r`JSON_QUERY((SELECT TOP 1 ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)) AS ${r(e.relationName)}`;
1385
- }, ta = (e, t, n) => {
1396
+ }, aa = (e, t, n) => {
1386
1397
  if (e.offset !== void 0) {
1387
1398
  let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${H(e.offset, n)} ROWS` : n`${r} OFFSET ${H(e.offset, n)} ROWS FETCH NEXT ${H(e.limit, n)} ROWS ONLY`;
1388
1399
  return {
@@ -1396,29 +1407,29 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1396
1407
  pagination: n``,
1397
1408
  finalOrder: t
1398
1409
  };
1399
- }, na = (e, t, n) => {
1400
- let r = n.sql, i = n.nextAlias(), a = Zi(i, e.target, e.children, n);
1410
+ }, oa = (e, t, n) => {
1411
+ let r = n.sql, i = n.nextAlias(), a = ta(i, e.target, e.children, n);
1401
1412
  if (a === null) return null;
1402
- let o = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, i, r)}`, s = R(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = ta(e.branch, s, r);
1413
+ let o = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, i, r)}`, s = R(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = aa(e.branch, s, r);
1403
1414
  return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1404
- }, ra = (e, t, n) => {
1405
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Zi(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1415
+ }, sa = (e, t, n) => {
1416
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ta(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1406
1417
  projection: e.junction,
1407
- source: Ri(s)
1418
+ source: Hi(s)
1408
1419
  });
1409
1420
  if (c === null) return null;
1410
- let l = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, o, r)}`, u = ia(e, s, r), d = R(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = ta(e.branch, d, r);
1421
+ let l = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, o, r)}`, u = ca(e, s, r), d = R(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = aa(e.branch, d, r);
1411
1422
  return r`ISNULL(JSON_QUERY((SELECT ${f}${c} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1412
1423
  }, B = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, V = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), H = (e, t) => {
1413
1424
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`literalInt: expected non-negative integer, got ${e}`);
1414
1425
  return t.unsafe(String(e));
1415
- }, U = (e, t, n) => L(aa(e, t), n), ia = (e, t, n, r = !1) => {
1426
+ }, U = (e, t, n) => L(la(e, t), n), ca = (e, t, n, r = !1) => {
1416
1427
  let i = e.branch.onJunction;
1417
1428
  return i === void 0 ? n`` : n` AND ${U(r ? W(i) : i, t, n)}`;
1418
- }, aa = (e, t) => {
1419
- if ("not" in e) return { not: aa(e.not, t) };
1420
- if ("and" in e) return { and: e.and.map((e) => aa(e, t)) };
1421
- if ("or" in e) return { or: e.or.map((e) => aa(e, t)) };
1429
+ }, la = (e, t) => {
1430
+ if ("not" in e) return { not: la(e.not, t) };
1431
+ if ("and" in e) return { and: e.and.map((e) => la(e, t)) };
1432
+ if ("or" in e) return { or: e.or.map((e) => la(e, t)) };
1422
1433
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
1423
1434
  let n = e;
1424
1435
  return {
@@ -1440,15 +1451,15 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1440
1451
  let t = e;
1441
1452
  return {
1442
1453
  ...t,
1443
- value: oa(t.value)
1454
+ value: ua(t.value)
1444
1455
  };
1445
- }, oa = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => oa(e)) : e, sa = Symbol.for("@voltro/database/coreTablesRegistry"), ca = globalThis, la = ca[sa] ?? (ca[sa] = {}), ua = (e) => {
1446
- e.actors !== void 0 && (la.actors = e.actors), e.tenants !== void 0 && (la.tenants = e.tenants);
1447
- }, da = (e, t) => () => {
1456
+ }, ua = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => ua(e)) : e, da = Symbol.for("@voltro/database/coreTablesRegistry"), fa = globalThis, pa = fa[da] ?? (fa[da] = {}), ma = (e) => {
1457
+ e.actors !== void 0 && (pa.actors = e.actors), e.tenants !== void 0 && (pa.tenants = e.tenants);
1458
+ }, ha = (e, t) => () => {
1448
1459
  let n = e();
1449
1460
  if (n === void 0) throw Error(`core '${t}' table not registered; expected the framework CLI or your migrate step to call registerCoreTables({ ${t}: () => ${t}Table }) before the database handle is constructed`);
1450
1461
  return n();
1451
- }, fa = () => da(() => la.actors, "actors"), pa = () => da(() => la.tenants, "tenants"), ma = w("actors", {
1462
+ }, ga = () => ha(() => pa.actors, "actors"), _a = () => ha(() => pa.tenants, "tenants"), va = w("actors", {
1452
1463
  id: E(),
1453
1464
  kind: C().oneOf([
1454
1465
  "user",
@@ -1458,73 +1469,73 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1458
1469
  ]),
1459
1470
  displayName: C().nullable(),
1460
1471
  createdAt: T().default("now")
1461
- }), ha = (e, t) => ({
1472
+ }), ya = (e, t) => ({
1462
1473
  column: e,
1463
1474
  op: "eq",
1464
1475
  value: t
1465
- }), ga = (e, t) => ({
1476
+ }), ba = (e, t) => ({
1466
1477
  column: e,
1467
1478
  op: "neq",
1468
1479
  value: t
1469
- }), _a = (e, t) => ({
1480
+ }), xa = (e, t) => ({
1470
1481
  column: e,
1471
1482
  op: "gt",
1472
1483
  value: t
1473
- }), va = (e, t) => ({
1484
+ }), Sa = (e, t) => ({
1474
1485
  column: e,
1475
1486
  op: "gte",
1476
1487
  value: t
1477
- }), ya = (e, t) => ({
1488
+ }), Ca = (e, t) => ({
1478
1489
  column: e,
1479
1490
  op: "lt",
1480
1491
  value: t
1481
- }), ba = (e, t) => ({
1492
+ }), wa = (e, t) => ({
1482
1493
  column: e,
1483
1494
  op: "lte",
1484
1495
  value: t
1485
- }), xa = (e, t) => ({
1496
+ }), Ta = (e, t) => ({
1486
1497
  column: e,
1487
1498
  op: "in",
1488
1499
  value: t
1489
- }), Sa = (e, t) => ({
1500
+ }), Ea = (e, t) => ({
1490
1501
  column: e,
1491
1502
  op: "notIn",
1492
1503
  value: t
1493
- }), Ca = (e, t) => ({
1504
+ }), Da = (e, t) => ({
1494
1505
  column: e,
1495
1506
  op: "contains",
1496
1507
  value: t
1497
- }), wa = (e, t) => ({
1508
+ }), Oa = (e, t) => ({
1498
1509
  column: e,
1499
1510
  op: "startsWith",
1500
1511
  value: t
1501
- }), Ta = (e, t) => ({
1512
+ }), ka = (e, t) => ({
1502
1513
  column: e,
1503
1514
  op: "arrayContains",
1504
1515
  value: t
1505
- }), Ea = (e, t) => ({
1516
+ }), Aa = (e, t) => ({
1506
1517
  column: e,
1507
1518
  op: "arrayOverlaps",
1508
1519
  value: t
1509
- }), Da = (e, t) => ({
1520
+ }), ja = (e, t) => ({
1510
1521
  column: e,
1511
1522
  op: "arrayHas",
1512
1523
  value: t
1513
- }), Oa = {
1524
+ }), Ma = {
1514
1525
  column: "id",
1515
1526
  op: "in",
1516
1527
  value: []
1517
- }, ka = (e) => ({
1528
+ }, Na = (e) => ({
1518
1529
  column: e,
1519
1530
  op: "isNull"
1520
- }), Aa = (e) => ({
1531
+ }), Pa = (e) => ({
1521
1532
  column: e,
1522
1533
  op: "isNotNull"
1523
- }), ja = (e, t) => ({
1534
+ }), Fa = (e, t) => ({
1524
1535
  column: e,
1525
1536
  op: "spatial",
1526
1537
  value: t
1527
- }), Ma = (...e) => ({ and: e }), Na = (...e) => ({ or: e }), Pa = (e) => ({ not: e }), Fa = (e, ...t) => {
1538
+ }), Ia = (...e) => ({ and: e }), La = (...e) => ({ or: e }), Ra = (e) => ({ not: e }), za = (e, ...t) => {
1528
1539
  if (t.length === 0) throw Error(`jsonField("${e}"): at least one path segment is required`);
1529
1540
  let n = (n, r) => ({
1530
1541
  column: e,
@@ -1546,33 +1557,33 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1546
1557
  isNull: () => n("isNull"),
1547
1558
  isNotNull: () => n("isNotNull")
1548
1559
  };
1549
- }, Ia = (e) => "descriptor" in e ? e.descriptor : e, La = (e, t) => ({
1560
+ }, Ba = (e) => "descriptor" in e ? e.descriptor : e, Va = (e, t) => ({
1550
1561
  column: e,
1551
1562
  op: "subquery-in",
1552
- subquery: Ia(t)
1553
- }), Ra = (e, t) => ({
1563
+ subquery: Ba(t)
1564
+ }), Ha = (e, t) => ({
1554
1565
  column: e,
1555
1566
  op: "subquery-not-in",
1556
- subquery: Ia(t)
1557
- }), za = (e) => ({
1567
+ subquery: Ba(t)
1568
+ }), Ua = (e) => ({
1558
1569
  op: "exists",
1559
- subquery: Ia(e)
1560
- }), Ba = (e) => ({
1570
+ subquery: Ba(e)
1571
+ }), Wa = (e) => ({
1561
1572
  op: "not-exists",
1562
- subquery: Ia(e)
1563
- }), Va = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), Ha = (e, t) => {
1573
+ subquery: Ba(e)
1574
+ }), Ga = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), Ka = (e, t) => {
1564
1575
  if (e == null || t == null) return null;
1565
1576
  let n = e instanceof Date ? e.getTime() : e, r = t instanceof Date ? t.getTime() : t;
1566
1577
  return typeof n == typeof r ? n === r ? 0 : n > r ? 1 : -1 : null;
1567
- }, Ua = (e, t, n = null) => {
1578
+ }, qa = (e, t, n = null) => {
1568
1579
  if (!t) return !1;
1569
- if ("not" in e) return !Ua(e.not, t, n);
1580
+ if ("not" in e) return !qa(e.not, t, n);
1570
1581
  if ("and" in e) {
1571
- for (let r of e.and) if (!Ua(r, t, n)) return !1;
1582
+ for (let r of e.and) if (!qa(r, t, n)) return !1;
1572
1583
  return !0;
1573
1584
  }
1574
1585
  if ("or" in e) {
1575
- for (let r of e.or) if (Ua(r, t, n)) return !0;
1586
+ for (let r of e.or) if (qa(r, t, n)) return !0;
1576
1587
  return !1;
1577
1588
  }
1578
1589
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
@@ -1589,14 +1600,14 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1589
1600
  }
1590
1601
  let r = e, i = t[r.column];
1591
1602
  switch (r.op) {
1592
- case "eq": return Va(i, r.value);
1593
- case "neq": return !Va(i, r.value);
1594
- case "gt": return (Ha(i, r.value) ?? -1) > 0;
1595
- case "gte": return (Ha(i, r.value) ?? -1) >= 0;
1596
- case "lt": return (Ha(i, r.value) ?? 1) < 0;
1597
- case "lte": return (Ha(i, r.value) ?? 1) <= 0;
1598
- case "in": return Array.isArray(r.value) && r.value.some((e) => Va(i, e));
1599
- case "notIn": return Array.isArray(r.value) && !r.value.some((e) => Va(i, e));
1603
+ case "eq": return Ga(i, r.value);
1604
+ case "neq": return !Ga(i, r.value);
1605
+ case "gt": return (Ka(i, r.value) ?? -1) > 0;
1606
+ case "gte": return (Ka(i, r.value) ?? -1) >= 0;
1607
+ case "lt": return (Ka(i, r.value) ?? 1) < 0;
1608
+ case "lte": return (Ka(i, r.value) ?? 1) <= 0;
1609
+ case "in": return Array.isArray(r.value) && r.value.some((e) => Ga(i, e));
1610
+ case "notIn": return Array.isArray(r.value) && !r.value.some((e) => Ga(i, e));
1600
1611
  case "contains": return typeof i == "string" && typeof r.value == "string" && i.toLowerCase().includes(r.value.toLowerCase());
1601
1612
  case "startsWith": return typeof i == "string" && typeof r.value == "string" && i.startsWith(r.value);
1602
1613
  case "arrayContains": {
@@ -1612,17 +1623,17 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1612
1623
  case "isNotNull": return i != null;
1613
1624
  case "spatial": throw Error("@voltro/plugin-postgis: spatial predicates (ST_DWithin / ST_Contains / ST_Within / ST_Intersects / bbox &&) are not evaluable in-memory — use them in one-shot ctx.store.query reads, not reactive subscriptions.");
1614
1625
  }
1615
- }, Wa = function* (e) {
1626
+ }, Ja = function* (e) {
1616
1627
  if ("not" in e) {
1617
- yield* Wa(e.not);
1628
+ yield* Ja(e.not);
1618
1629
  return;
1619
1630
  }
1620
1631
  if ("and" in e) {
1621
- for (let t of e.and) yield* Wa(t);
1632
+ for (let t of e.and) yield* Ja(t);
1622
1633
  return;
1623
1634
  }
1624
1635
  if ("or" in e) {
1625
- for (let t of e.or) yield* Wa(t);
1636
+ for (let t of e.or) yield* Ja(t);
1626
1637
  return;
1627
1638
  }
1628
1639
  e.op === "subquery-in" || e.op === "subquery-not-in" ? yield {
@@ -1632,46 +1643,46 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1632
1643
  kind: "exists",
1633
1644
  descriptor: e.subquery
1634
1645
  });
1635
- }, Ga = function* (e, t = !0) {
1646
+ }, Ya = function* (e, t = !0) {
1636
1647
  if ("not" in e) {
1637
- yield* Ga(e.not, !1);
1648
+ yield* Ya(e.not, !1);
1638
1649
  return;
1639
1650
  }
1640
1651
  if ("and" in e) {
1641
- for (let n of e.and) yield* Ga(n, t);
1652
+ for (let n of e.and) yield* Ya(n, t);
1642
1653
  return;
1643
1654
  }
1644
1655
  if ("or" in e) {
1645
- for (let t of e.or) yield* Ga(t, !1);
1656
+ for (let t of e.or) yield* Ya(t, !1);
1646
1657
  return;
1647
1658
  }
1648
1659
  e.op !== "subquery-in" && e.op !== "subquery-not-in" && e.op !== "exists" && e.op !== "not-exists" && (yield {
1649
1660
  ...e,
1650
1661
  conjunctive: t
1651
1662
  });
1652
- }, Ka = (e, t) => ({
1663
+ }, Xa = (e, t) => ({
1653
1664
  ...t,
1654
1665
  ...e,
1655
1666
  origin: e.origin ?? "injected"
1656
- }), qa = (e, t, n = {}) => ({
1667
+ }), Za = (e, t, n = {}) => ({
1657
1668
  table: e,
1658
1669
  op: "insert",
1659
1670
  old: null,
1660
1671
  new: t,
1661
1672
  ...n
1662
- }), Ja = (e, t, n, r = {}) => ({
1673
+ }), Qa = (e, t, n, r = {}) => ({
1663
1674
  table: e,
1664
1675
  op: "update",
1665
1676
  old: t,
1666
1677
  new: n,
1667
1678
  ...r
1668
- }), Ya = (e, t, n = {}) => ({
1679
+ }), $a = (e, t, n = {}) => ({
1669
1680
  table: e,
1670
1681
  op: "delete",
1671
1682
  old: t,
1672
1683
  new: null,
1673
1684
  ...n
1674
- }), Xa = (e, t, n = {}) => {
1685
+ }), eo = (e, t, n = {}) => {
1675
1686
  let { at: r = "2026-01-01T00:00:00.000Z", column: i = "deletedAt", ...a } = n;
1676
1687
  return {
1677
1688
  table: e,
@@ -1686,13 +1697,13 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1686
1697
  },
1687
1698
  ...a
1688
1699
  };
1689
- }, Za = (e) => e == null ? "null" : e instanceof Date ? JSON.stringify(e.toISOString()) : typeof e == "bigint" ? JSON.stringify(e.toString()) : Array.isArray(e) ? `[${e.map(Za).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${Za(t)}`).join(",")}}` : JSON.stringify(e) ?? "null", Qa = (e) => Jt("sha256").update([
1700
+ }, to = (e) => e == null ? "null" : e instanceof Date ? JSON.stringify(e.toISOString()) : typeof e == "bigint" ? JSON.stringify(e.toString()) : Array.isArray(e) ? `[${e.map(to).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${to(t)}`).join(",")}}` : JSON.stringify(e) ?? "null", no = (e) => qt("sha256").update([
1690
1701
  e.pipe,
1691
1702
  e.op,
1692
1703
  e.key,
1693
- Za(e.next),
1694
- Za(e.prev)
1695
- ].join("\0")).digest("hex").slice(0, 32), $a = (e, t) => `${e}:${t}`, eo = (e) => {
1704
+ to(e.next),
1705
+ to(e.prev)
1706
+ ].join("\0")).digest("hex").slice(0, 32), ro = (e, t) => `${e}:${t}`, io = (e) => {
1696
1707
  let t = e.lastIndexOf(":");
1697
1708
  if (t <= 0) return null;
1698
1709
  let n = Number(e.slice(t + 1));
@@ -1700,7 +1711,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1700
1711
  digest: e.slice(0, t),
1701
1712
  occurrence: n
1702
1713
  };
1703
- }, to = class {
1714
+ }, ao = class {
1704
1715
  #e = /* @__PURE__ */ new Map();
1705
1716
  #t;
1706
1717
  #n;
@@ -1722,7 +1733,7 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1722
1733
  }
1723
1734
  seedFromChangeKeys(e, t) {
1724
1735
  for (let n of e) {
1725
- let e = eo(n);
1736
+ let e = io(n);
1726
1737
  if (e === null) continue;
1727
1738
  let r = this.#e.get(e.digest), i = Math.max(r?.count ?? 0, e.occurrence + 1);
1728
1739
  this.#e.set(e.digest, {
@@ -1743,29 +1754,29 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1743
1754
  this.#e.delete(e.value);
1744
1755
  }
1745
1756
  }
1746
- }, no = "VOLTRO_CHANGE_CLAIMS_TTL_HOURS", ro = 1, io = (e = process.env) => {
1747
- let t = Number(e[no]);
1757
+ }, oo = "VOLTRO_CHANGE_CLAIMS_TTL_HOURS", so = 1, co = (e = process.env) => {
1758
+ let t = Number(e[oo]);
1748
1759
  return (Number.isFinite(t) && t > 0 ? t : 1) * 2 * 36e5;
1749
- }, ao = new Yt(), oo = (e, t) => ao.run(e, t), so = () => ao.getStore(), co = (e) => {
1750
- let t = e ?? ao.getStore();
1760
+ }, lo = new Jt(), uo = (e, t) => lo.run(e, t), fo = () => lo.getStore(), po = (e) => {
1761
+ let t = e ?? lo.getStore();
1751
1762
  return t === void 0 ? {} : {
1752
1763
  ...t.traceId === void 0 ? {} : { traceId: t.traceId },
1753
1764
  ...t.subjectId === void 0 ? {} : { subjectId: t.subjectId },
1754
1765
  ...t.procedure === void 0 ? {} : { procedure: t.procedure },
1755
1766
  ...t.via === void 0 ? {} : { via: t.via }
1756
1767
  };
1757
- }, lo = (e) => {
1758
- let t = ao.getStore();
1759
- return t === void 0 ? e(void 0) : ao.run(t, () => e(t));
1760
- }, uo = 3e4, fo = 1e4, G = /* @__PURE__ */ new Map(), K = 0, po = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, mo = (e) => {
1768
+ }, mo = (e) => {
1769
+ let t = lo.getStore();
1770
+ return t === void 0 ? e(void 0) : lo.run(t, () => e(t));
1771
+ }, ho = 3e4, go = 1e4, G = /* @__PURE__ */ new Map(), K = 0, _o = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, vo = (e) => {
1761
1772
  for (let [t, n] of G) {
1762
- let r = n.filter((t) => e - t.at < uo);
1773
+ let r = n.filter((t) => e - t.at < ho);
1763
1774
  K -= n.length - r.length, r.length === 0 ? G.delete(t) : r.length !== n.length && G.set(t, r);
1764
1775
  }
1765
- }, ho = (e, t) => {
1776
+ }, yo = (e, t) => {
1766
1777
  if (t.traceId === void 0 && t.subjectId === void 0 && t.procedure === void 0) return;
1767
1778
  let n = Date.now();
1768
- if (K >= fo && mo(n), K >= fo) return;
1779
+ if (K >= go && vo(n), K >= go) return;
1769
1780
  let r = G.get(e);
1770
1781
  r === void 0 ? G.set(e, [{
1771
1782
  attribution: t,
@@ -1774,38 +1785,38 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1774
1785
  attribution: t,
1775
1786
  at: n
1776
1787
  }), K += 1;
1777
- }, go = (e) => {
1788
+ }, bo = (e) => {
1778
1789
  let t = G.get(e);
1779
1790
  if (t === void 0 || t.length === 0) return;
1780
1791
  let n = t.shift();
1781
- if (--K, t.length === 0 && G.delete(e), !(Date.now() - n.at >= uo)) return n.attribution;
1782
- }, _o = (e) => (G.get(e)?.length ?? 0) > 0, q = /* @__PURE__ */ new Map(), vo = /* @__PURE__ */ new Map(), yo = /* @__PURE__ */ new Map(), bo = 250, xo = (e) => {
1783
- let t = vo.get(e);
1792
+ if (--K, t.length === 0 && G.delete(e), !(Date.now() - n.at >= ho)) return n.attribution;
1793
+ }, xo = (e) => (G.get(e)?.length ?? 0) > 0, q = /* @__PURE__ */ new Map(), So = /* @__PURE__ */ new Map(), Co = /* @__PURE__ */ new Map(), wo = 250, To = (e) => {
1794
+ let t = So.get(e);
1784
1795
  if (t === void 0) return;
1785
- vo.delete(e);
1786
- let n = yo.get(e);
1787
- n !== void 0 && (clearTimeout(n), yo.delete(e));
1796
+ So.delete(e);
1797
+ let n = Co.get(e);
1798
+ n !== void 0 && (clearTimeout(n), Co.delete(e));
1788
1799
  for (let e of t) e();
1789
- }, So = (e) => {
1800
+ }, Eo = (e) => {
1790
1801
  q.set(e, (q.get(e) ?? 0) + 1);
1791
- }, Co = (e) => {
1802
+ }, Do = (e) => {
1792
1803
  let t = (q.get(e) ?? 0) - 1;
1793
1804
  if (t > 0) {
1794
1805
  q.set(e, t);
1795
1806
  return;
1796
1807
  }
1797
- q.delete(e), xo(e);
1798
- }, wo = (e, t, n, r) => {
1799
- let i = n == null ? void 0 : po(e, t, n), a = () => r(i === void 0 ? void 0 : go(i));
1808
+ q.delete(e), To(e);
1809
+ }, Oo = (e, t, n, r) => {
1810
+ let i = n == null ? void 0 : _o(e, t, n), a = () => r(i === void 0 ? void 0 : bo(i));
1800
1811
  if (i === void 0) {
1801
1812
  a();
1802
1813
  return;
1803
1814
  }
1804
- if (_o(i)) {
1815
+ if (xo(i)) {
1805
1816
  a();
1806
1817
  return;
1807
1818
  }
1808
- let o = vo.get(e);
1819
+ let o = So.get(e);
1809
1820
  if (o === void 0 && (q.get(e) ?? 0) === 0) {
1810
1821
  a();
1811
1822
  return;
@@ -1814,91 +1825,91 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1814
1825
  o.push(a);
1815
1826
  return;
1816
1827
  }
1817
- vo.set(e, [a]);
1818
- let s = setTimeout(() => xo(e), bo);
1819
- typeof s == "object" && typeof s.unref == "function" && s.unref(), yo.set(e, s);
1820
- }, To = () => {
1828
+ So.set(e, [a]);
1829
+ let s = setTimeout(() => To(e), wo);
1830
+ typeof s == "object" && typeof s.unref == "function" && s.unref(), Co.set(e, s);
1831
+ }, ko = () => {
1821
1832
  G.clear(), K = 0, q.clear();
1822
- for (let e of yo.values()) clearTimeout(e);
1823
- yo.clear(), vo.clear();
1824
- }, Eo = () => K, Do = 64, Oo = "\0", ko = 32, Ao = (e, ...t) => `${e}_${Jt("sha256").update(t.map(String).join(Oo)).digest("hex").slice(0, ko)}`, jo = (e) => e.length + 1 + ko, J = /* @__PURE__ */ new Map(), Mo = (e, t) => {
1833
+ for (let e of Co.values()) clearTimeout(e);
1834
+ Co.clear(), So.clear();
1835
+ }, Ao = () => K, jo = 64, Mo = "\0", No = 32, Po = (e, ...t) => `${e}_${qt("sha256").update(t.map(String).join(Mo)).digest("hex").slice(0, No)}`, Fo = (e) => e.length + 1 + No, J = /* @__PURE__ */ new Map(), Io = (e, t) => {
1825
1836
  J.set(e, {
1826
1837
  recorder: t.recorder,
1827
1838
  tables: new Set(t.tables),
1828
1839
  ownTables: new Set(t.ownTables)
1829
1840
  });
1830
- }, No = (e) => {
1841
+ }, Lo = (e) => {
1831
1842
  J.delete(e);
1832
- }, Po = () => J.clear(), Fo = new Yt(), Io = (e) => Fo.run({ n: 1 }, e), Lo = (e) => O.suspend(() => {
1833
- let t = Fo.getStore();
1834
- if (t !== void 0) return t.n += 1, O.ensuring(e, O.sync(() => {
1843
+ }, Ro = () => J.clear(), zo = new Jt(), Bo = (e) => zo.run({ n: 1 }, e), Vo = (e) => k.suspend(() => {
1844
+ let t = zo.getStore();
1845
+ if (t !== void 0) return t.n += 1, k.ensuring(e, k.sync(() => {
1835
1846
  --t.n;
1836
1847
  }));
1837
1848
  let n = { n: 1 };
1838
- return Fo.enterWith(n), O.ensuring(e, O.sync(() => {
1849
+ return zo.enterWith(n), k.ensuring(e, k.sync(() => {
1839
1850
  --n.n;
1840
1851
  }));
1841
- }), Ro = () => (Fo.getStore()?.n ?? 0) > 0, zo = (e) => {
1842
- if (J.size === 0 || (Fo.getStore()?.n ?? 0) > 0) return !1;
1852
+ }), Ho = () => (zo.getStore()?.n ?? 0) > 0, Uo = (e) => {
1853
+ if (J.size === 0 || (zo.getStore()?.n ?? 0) > 0) return !1;
1843
1854
  for (let t of J.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1844
1855
  return !1;
1845
- }, Bo = async (e, t) => {
1856
+ }, Wo = async (e, t) => {
1846
1857
  if (J.size !== 0) {
1847
1858
  for (let [n, r] of J.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1848
1859
  await r.recorder(e, t);
1849
1860
  } catch (e) {
1850
- let r = An(e);
1861
+ let r = Pn(e);
1851
1862
  throw r === void 0 ? e : Error(`write recorder '${n}' failed while recording a ${t.op} on '${t.table}': ${r}`, { cause: e });
1852
1863
  }
1853
1864
  }
1854
- }, Vo = Wt.exponential({
1865
+ }, Go = Ut.exponential({
1855
1866
  start: 5e-4,
1856
1867
  factor: 2,
1857
1868
  count: 16
1858
- }), Ho = k.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), Uo = k.histogram("voltro_db_query_duration_seconds", Vo, "Database operation duration in seconds, by dialect and operation kind."), Wo = k.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), Go = k.gauge("voltro_db_operations_in_flight", { description: "Database operations currently executing, by dialect. An upper bound on connections the framework holds; NOT the driver pool's waiting count." }), Ko = k.counter("voltro_db_eager_fallback_total", { description: "Eager-load queries that degraded from the single-roundtrip JSON-agg path to the multi-query walker, by dialect and reason." }), qo = [], Jo = /* @__PURE__ */ new Map(), Yo = /* @__PURE__ */ new Map(), Xo = /* @__PURE__ */ new Map(), Zo = (e, t) => {
1859
- let n = `${e}\u0000${t}`, r = Jo.get(n);
1869
+ }), Ko = A.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), qo = A.histogram("voltro_db_query_duration_seconds", Go, "Database operation duration in seconds, by dialect and operation kind."), Jo = A.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), Yo = A.gauge("voltro_db_operations_in_flight", { description: "Database operations currently executing, by dialect. An upper bound on connections the framework holds; NOT the driver pool's waiting count." }), Xo = A.counter("voltro_db_eager_fallback_total", { description: "Eager-load queries that degraded from the single-roundtrip JSON-agg path to the multi-query walker, by dialect and reason." }), Zo = [], Qo = /* @__PURE__ */ new Map(), $o = /* @__PURE__ */ new Map(), es = /* @__PURE__ */ new Map(), ts = (e, t) => {
1870
+ let n = `${e}\u0000${t}`, r = Qo.get(n);
1860
1871
  if (r !== void 0) return r;
1861
- let i = (n) => k.tagged(k.tagged(n, "dialect", e), "op", t), a = {
1862
- count: i(Ho),
1863
- duration: i(Uo),
1864
- errors: i(Wo)
1872
+ let i = (n) => A.tagged(A.tagged(n, "dialect", e), "op", t), a = {
1873
+ count: i(Ko),
1874
+ duration: i(qo),
1875
+ errors: i(Jo)
1865
1876
  };
1866
- return Jo.set(n, a), a;
1867
- }, Qo = () => {
1868
- Jo.clear(), Yo.clear(), Xo.clear();
1869
- }, $o = () => Jo.size + Yo.size + Xo.size, es = /* @__PURE__ */ new Map(), ts = (e, t) => {
1870
- let n = Math.max(0, (es.get(e) ?? 0) + t);
1871
- n === 0 ? es.delete(e) : es.set(e, n);
1872
- let r = Yo.get(e);
1873
- r === void 0 && (r = k.tagged(Go, "dialect", e), Yo.set(e, r)), r.unsafeUpdate(n, qo);
1874
- }, ns = (e) => es.get(e) ?? 0, rs = (e) => {
1875
- let t = Zo(String(e.dialect), e.op);
1876
- t.count.unsafeUpdate(1, qo), t.duration.unsafeUpdate(e.durationMs / 1e3, qo), e.status === "error" && t.errors.unsafeUpdate(1, qo);
1877
- }, is = async (e, t, n) => {
1877
+ return Qo.set(n, a), a;
1878
+ }, ns = () => {
1879
+ Qo.clear(), $o.clear(), es.clear();
1880
+ }, rs = () => Qo.size + $o.size + es.size, is = /* @__PURE__ */ new Map(), as = (e, t) => {
1881
+ let n = Math.max(0, (is.get(e) ?? 0) + t);
1882
+ n === 0 ? is.delete(e) : is.set(e, n);
1883
+ let r = $o.get(e);
1884
+ r === void 0 && (r = A.tagged(Yo, "dialect", e), $o.set(e, r)), r.unsafeUpdate(n, Zo);
1885
+ }, os = (e) => is.get(e) ?? 0, ss = (e) => {
1886
+ let t = ts(String(e.dialect), e.op);
1887
+ t.count.unsafeUpdate(1, Zo), t.duration.unsafeUpdate(e.durationMs / 1e3, Zo), e.status === "error" && t.errors.unsafeUpdate(1, Zo);
1888
+ }, cs = async (e, t, n) => {
1878
1889
  let r = performance.now(), i = String(e);
1879
- ts(i, 1);
1890
+ as(i, 1);
1880
1891
  let a = "ok";
1881
1892
  try {
1882
1893
  return await n();
1883
1894
  } catch (e) {
1884
1895
  throw a = "error", e;
1885
1896
  } finally {
1886
- ts(i, -1), rs({
1897
+ as(i, -1), ss({
1887
1898
  dialect: e,
1888
1899
  op: t,
1889
1900
  durationMs: performance.now() - r,
1890
1901
  status: a
1891
1902
  });
1892
1903
  }
1893
- }, as = 3e5, os = (e) => {
1904
+ }, ls = 3e5, us = (e) => {
1894
1905
  if (e == null || e === "") return;
1895
1906
  let t = Number(e);
1896
1907
  return Number.isFinite(t) && t >= 0 ? Math.floor(t) : void 0;
1897
- }, ss = (e, t = process.env) => os(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? os(e) ?? 3e5, cs = (e, t = {}) => {
1898
- let n = ss(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1908
+ }, ds = (e, t = process.env) => us(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? us(e) ?? 3e5, fs = (e, t = {}) => {
1909
+ let n = ds(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1899
1910
  return (t) => {
1900
- let a = `${t.dialect} ${t.reason}`, o = Xo.get(a);
1901
- o === void 0 && (o = k.tagged(k.tagged(Ko, "dialect", String(t.dialect)), "reason", t.reason), Xo.set(a, o)), o.unsafeUpdate(1, qo);
1911
+ let a = `${t.dialect} ${t.reason}`, o = es.get(a);
1912
+ o === void 0 && (o = A.tagged(A.tagged(Xo, "dialect", String(t.dialect)), "reason", t.reason), es.set(a, o)), o.unsafeUpdate(1, Zo);
1902
1913
  let s = `${t.table}\u0000${t.reason}`, c = i.get(s), l = c === void 0 || n > 0 && r() - c >= n, u = {
1903
1914
  table: t.table,
1904
1915
  dialect: String(t.dialect),
@@ -1912,24 +1923,24 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1912
1923
  }
1913
1924
  i.set(s, r()), e.warn(t.reason === "execute-failed" ? "eager-load JSON-agg statement FAILED and was re-run on the multi-query walker — this query pays both paths on every call. Counted as voltro_db_eager_fallback_total{reason=\"execute-failed\"}." : "eager-load could not be compiled to a single JSON-agg roundtrip and is running on the multi-query walker — one round trip per relation level, on every call. Counted as voltro_db_eager_fallback_total{reason=\"not-compilable\"}.", u);
1914
1925
  };
1915
- }, ls = (e) => {
1916
- if (Ut.isSuccess(e)) return e.value;
1917
- throw Bt.squash(e.cause);
1918
- }, us = "10 millis", ds = 3, fs = async (e) => {
1919
- let t = 0, n = O.suspend(() => {
1926
+ }, ps = (e) => {
1927
+ if (Ht.isSuccess(e)) return e.value;
1928
+ throw O.squash(e.cause);
1929
+ }, ms = "10 millis", hs = 3, gs = async (e) => {
1930
+ let t = 0, n = k.suspend(() => {
1920
1931
  let n = ++t;
1921
- return e.withTransaction(O.flatMap(O.serviceOption(Xt), (t) => {
1922
- if (A.isNone(t)) return O.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1923
- let r = t.value, i = O.tryPromise({
1932
+ return e.withTransaction(k.flatMap(k.serviceOption(Yt), (t) => {
1933
+ if (j.isNone(t)) return k.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1934
+ let r = t.value, i = k.tryPromise({
1924
1935
  try: () => e.body(r, n),
1925
1936
  catch: (e) => e
1926
1937
  });
1927
- return e.prepare === void 0 ? i : O.flatMap(e.prepare(r), () => i);
1928
- })).pipe(O.catchAllDefect((t) => e.isRetryable(t) ? O.fail(t) : O.die(t)));
1929
- }), r = Kt.exponential(us).pipe(Kt.compose(Kt.recurs(ds)), Kt.whileInput(e.isRetryable)), i = n.pipe(O.retry(r), O.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1930
- return is(e.dialect, "transaction", async () => ls(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1931
- }, ps = async (e) => {
1932
- let t = so(), n = t === void 0 ? (e) => e() : (e) => oo(t, e), r = await fs({
1938
+ return e.prepare === void 0 ? i : k.flatMap(e.prepare(r), () => i);
1939
+ })).pipe(k.catchAllDefect((t) => e.isRetryable(t) ? k.fail(t) : k.die(t)));
1940
+ }), r = Gt.exponential(ms).pipe(Gt.compose(Gt.recurs(hs)), Gt.whileInput(e.isRetryable)), i = n.pipe(k.retry(r), k.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1941
+ return cs(e.dialect, "transaction", async () => ps(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1942
+ }, _s = async (e) => {
1943
+ let t = fo(), n = t === void 0 ? (e) => e() : (e) => uo(t, e), r = await gs({
1933
1944
  ...e,
1934
1945
  body: (r) => {
1935
1946
  let i = e.makeView(r, t);
@@ -1940,50 +1951,50 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1940
1951
  }
1941
1952
  });
1942
1953
  return r.view.commitEvents(), r.result;
1943
- }, ms = /* @__PURE__ */ new Set([
1954
+ }, vs = /* @__PURE__ */ new Set([
1944
1955
  "1213",
1945
1956
  "ER_LOCK_DEADLOCK",
1946
1957
  "1205",
1947
1958
  "ER_LOCK_WAIT_TIMEOUT",
1948
1959
  "1020",
1949
1960
  "ER_CHECKREAD"
1950
- ]), hs = /* @__PURE__ */ new Set(["40001", "40P01"]), gs = /* @__PURE__ */ new Set(["1205"]), _s = /* @__PURE__ */ new Set([
1961
+ ]), ys = /* @__PURE__ */ new Set(["40001", "40P01"]), bs = /* @__PURE__ */ new Set(["1205"]), xs = /* @__PURE__ */ new Set([
1951
1962
  "SQLITE_BUSY",
1952
1963
  "5",
1953
1964
  "SQLITE_LOCKED",
1954
1965
  "6"
1955
- ]), vs = /write-write conflict|write-read conflict|database is locked|table is locked|database is busy/i, ys = /* @__PURE__ */ new Set([
1966
+ ]), Ss = /write-write conflict|write-read conflict|database is locked|table is locked|database is busy/i, Cs = /* @__PURE__ */ new Set([
1956
1967
  1213,
1957
1968
  1205,
1958
1969
  1020
1959
- ]), bs = /* @__PURE__ */ new Set([
1960
- ...ms,
1961
- ...hs,
1962
- ...gs,
1963
- ..._s
1964
- ]), xs = (e) => N(e).some(Ss), Ss = (e) => {
1970
+ ]), ws = /* @__PURE__ */ new Set([
1971
+ ...vs,
1972
+ ...ys,
1973
+ ...bs,
1974
+ ...xs
1975
+ ]), Ts = (e) => xn(e).some(Es), Es = (e) => {
1965
1976
  let t = e;
1966
1977
  for (let e = 0; e < 6 && typeof t == "object" && t; e++) {
1967
1978
  let e = t;
1968
- if (typeof e.errno == "number" && ys.has(e.errno) || typeof e.number == "number" && gs.has(String(e.number)) || typeof e.code == "string" && bs.has(e.code) || typeof e.sqlState == "string" && hs.has(e.sqlState) || typeof e.message == "string" && vs.test(e.message)) return !0;
1979
+ if (typeof e.errno == "number" && Cs.has(e.errno) || typeof e.number == "number" && bs.has(String(e.number)) || typeof e.code == "string" && ws.has(e.code) || typeof e.sqlState == "string" && ys.has(e.sqlState) || typeof e.message == "string" && Ss.test(e.message)) return !0;
1969
1980
  t = e.cause;
1970
1981
  }
1971
1982
  return !1;
1972
- }, Cs = "voltro/expires", ws = () => Ct({
1973
- id: Cs,
1983
+ }, Ds = "voltro/expires", Os = () => Ct({
1984
+ id: Ds,
1974
1985
  fields: { expiresAt: T().nullable() },
1975
1986
  behaviors: { defaultWhere: () => "expiresAt IS NULL OR expiresAt > now()" }
1976
- }), Ts = "voltro/localFirst", Es = () => Ct({
1977
- id: Ts,
1987
+ }), ks = "voltro/localFirst", As = () => Ct({
1988
+ id: ks,
1978
1989
  fields: {}
1979
- }), Ds = (e) => e.appliedMixins.some((e) => e.id === Ts), Os = (e) => {
1990
+ }), js = (e) => e.appliedMixins.some((e) => e.id === ks), Ms = (e) => {
1980
1991
  let t = [];
1981
- for (let n of Object.values(e)) Ds(n) && t.push(n.tableName);
1992
+ for (let n of Object.values(e)) js(n) && t.push(n.tableName);
1982
1993
  return t;
1983
- }, ks = class extends Ht.TaggedError("TableStreamError") {}, As = 1e3, js = (e, t, n, r) => {
1984
- let i = A.match(r, {
1994
+ }, Ns = class extends Vt.TaggedError("TableStreamError") {}, Ps = 1e3, Fs = (e, t, n, r) => {
1995
+ let i = j.match(r, {
1985
1996
  onNone: () => e.where,
1986
- onSome: (n) => e.where ? Ma(e.where, _a(t, n)) : _a(t, n)
1997
+ onSome: (n) => e.where ? Ia(e.where, xa(t, n)) : xa(t, n)
1987
1998
  });
1988
1999
  return {
1989
2000
  table: e.table,
@@ -1998,19 +2009,19 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
1998
2009
  ...e.includeDeleted === void 0 ? {} : { includeDeleted: e.includeDeleted },
1999
2010
  ...e.crossTenant === void 0 ? {} : { crossTenant: e.crossTenant }
2000
2011
  };
2001
- }, Ms = (e, t) => {
2002
- let n = t.pk ?? "id", r = t.chunkSize ?? As;
2003
- return qt.paginateChunkEffect(A.none(), (i) => {
2004
- let a = O.tryPromise({
2005
- try: () => e.query(js(t, n, r, i)),
2006
- catch: (e) => new ks({
2012
+ }, Is = (e, t) => {
2013
+ let n = t.pk ?? "id", r = t.chunkSize ?? Ps;
2014
+ return Kt.paginateChunkEffect(j.none(), (i) => {
2015
+ let a = k.tryPromise({
2016
+ try: () => e.query(Fs(t, n, r, i)),
2017
+ catch: (e) => new Ns({
2007
2018
  table: t.table,
2008
2019
  cause: e
2009
2020
  })
2010
2021
  });
2011
- return (t.retry ? a.pipe(O.retry(t.retry)) : a).pipe(O.map((e) => [Vt.fromIterable(e), e.length === r && e.length > 0 ? A.some(A.some(e[e.length - 1][n])) : A.none()]));
2022
+ return (t.retry ? a.pipe(k.retry(t.retry)) : a).pipe(k.map((e) => [Bt.fromIterable(e), e.length === r && e.length > 0 ? j.some(j.some(e[e.length - 1][n])) : j.none()]));
2012
2023
  });
2013
- }, Ns = (e) => {
2024
+ }, Ls = (e) => {
2014
2025
  let t = e.alpha ?? .5;
2015
2026
  if (t < 0 || t > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${t}`);
2016
2027
  return (n) => {
@@ -2037,14 +2048,14 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
2037
2048
  }
2038
2049
  };
2039
2050
  };
2040
- }, Ps = async (e, t) => {
2051
+ }, Rs = async (e, t) => {
2041
2052
  let n = e.as ?? "embedding", r = t.row[e.from];
2042
2053
  if (typeof r != "string" || r.length === 0) return {};
2043
2054
  let i = await t.embed(r);
2044
2055
  return { [n]: i };
2045
- }, Fs = (e) => {
2056
+ }, zs = (e) => {
2046
2057
  if (!Number.isInteger(e.dimensions) || e.dimensions <= 0) throw Error(`vectorEmbedding: dimensions must be a positive integer, got ${String(e.dimensions)}.`);
2047
- let t = e.as ?? "embedding", n = (t) => Ps(e, t);
2058
+ let t = e.as ?? "embedding", n = (t) => Rs(e, t);
2048
2059
  return Ct({
2049
2060
  id: "voltro/vectorEmbedding",
2050
2061
  fields: { [t]: _t(e.dimensions) },
@@ -2062,19 +2073,19 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
2062
2073
  beforeUpdate: n
2063
2074
  }
2064
2075
  });
2065
- }, Is = 63, Ls = "br_pr", Y = class extends Error {
2076
+ }, Bs = 63, Vs = "br_pr", Y = class extends Error {
2066
2077
  _tag = "BranchNameInvalid";
2067
2078
  constructor(e) {
2068
2079
  super(e), this.name = "BranchNameInvalid";
2069
2080
  }
2070
- }, Rs = (e, t) => {
2081
+ }, Hs = (e, t) => {
2071
2082
  if (!Number.isInteger(t) || t < 0) throw new Y(`prNumber must be a non-negative integer, got ${String(t)}`);
2072
- let n = Ur(e);
2083
+ let n = qr(e);
2073
2084
  if (n.replace(/_/g, "") === "") throw new Y(`app slug '${e}' has no usable identifier characters`);
2074
- let r = `${Ls}${t}_${n}`;
2075
- if (r.length > Is) throw new Y(`branch namespace '${r}' exceeds the ${Is}-byte identifier limit — use a shorter app slug`);
2085
+ let r = `${Vs}${t}_${n}`;
2086
+ if (r.length > Bs) throw new Y(`branch namespace '${r}' exceeds the ${Bs}-byte identifier limit — use a shorter app slug`);
2076
2087
  return r;
2077
- }, zs = (e) => e.startsWith(Ls), Bs = {
2088
+ }, Us = (e) => e.startsWith(Vs), Ws = {
2078
2089
  requested: {
2079
2090
  provision: "provisioning",
2080
2091
  destroy: "destroying"
@@ -2093,18 +2104,18 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
2093
2104
  fail: "failed"
2094
2105
  },
2095
2106
  destroyed: {}
2096
- }, Vs = class extends Error {
2107
+ }, Gs = class extends Error {
2097
2108
  from;
2098
2109
  event;
2099
2110
  _tag = "BranchTransitionInvalid";
2100
2111
  constructor(e, t) {
2101
2112
  super(`invalid branch transition: ${e} --${t}-->`), this.from = e, this.event = t, this.name = "BranchTransitionInvalid";
2102
2113
  }
2103
- }, Hs = (e, t) => {
2104
- let n = Bs[e][t];
2105
- if (n === void 0) throw new Vs(e, t);
2114
+ }, Ks = (e, t) => {
2115
+ let n = Ws[e][t];
2116
+ if (n === void 0) throw new Gs(e, t);
2106
2117
  return n;
2107
- }, Us = (e, t, n, r, i = [], a = []) => {
2118
+ }, qs = (e, t, n, r, i = [], a = []) => {
2108
2119
  if (n === "copy" && (r === void 0 || r === "")) throw new Y("seed 'copy' requires a parentNamespace to snapshot from");
2109
2120
  let o = [{
2110
2121
  kind: "create-namespace",
@@ -2134,13 +2145,13 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
2134
2145
  kind: "seed",
2135
2146
  detail: `run boot seeds into ${e}`
2136
2147
  }), o;
2137
- }, Ws = (e) => {
2138
- if (!zs(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2148
+ }, Js = (e) => {
2149
+ if (!Us(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2139
2150
  return [{
2140
2151
  kind: "drop-namespace",
2141
2152
  detail: e
2142
2153
  }];
2143
- }, Gs = (e) => {
2154
+ }, Ys = (e) => {
2144
2155
  if (e === void 0 || e === "") return !1;
2145
2156
  try {
2146
2157
  let t = new URL(e).hostname.toLowerCase();
@@ -2148,27 +2159,27 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
2148
2159
  } catch {
2149
2160
  return /\bneon\.(tech|build)\b/i.test(e);
2150
2161
  }
2151
- }, Ks = (e) => e.prefer === void 0 ? e.seed === "copy" && Gs(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, qs = (e, t = {}) => [{
2162
+ }, Xs = (e) => e.prefer === void 0 ? e.seed === "copy" && Ys(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, Zs = (e, t = {}) => [{
2152
2163
  kind: "neon-branch-create",
2153
2164
  detail: `${t.parentBranch ?? "main"} → ${e} (copy-on-write)`
2154
- }], Js = (e) => {
2155
- if (!zs(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2165
+ }], Qs = (e) => {
2166
+ if (!Us(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2156
2167
  return [{
2157
2168
  kind: "neon-branch-delete",
2158
2169
  detail: e
2159
2170
  }];
2160
- }, Ys = (e) => e.mechanism === "neon-cow" ? qs(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : Us(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), Xs = (e, t) => e === "neon-cow" ? Js(t) : Ws(t), Zs = (e, t, n) => {
2171
+ }, $s = (e) => e.mechanism === "neon-cow" ? Zs(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : qs(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), ec = (e, t) => e === "neon-cow" ? Qs(t) : Js(t), tc = (e, t, n) => {
2161
2172
  let r = e.filter((e) => e.state !== "destroyed" && e.state !== "destroying"), i = r.filter((e) => n - e.createdAtMs > t.ttlMs).map((e) => e.namespace), a = new Set(i);
2162
2173
  return {
2163
2174
  evict: i,
2164
2175
  rejectNew: r.filter((e) => !a.has(e.namespace)).length >= t.maxBranches
2165
2176
  };
2166
- }, Qs = async (e, t) => {
2167
- let n = Rs(e.appSlug, e.prNumber), r = Ks({
2177
+ }, nc = async (e, t) => {
2178
+ let n = Hs(e.appSlug, e.prNumber), r = Xs({
2168
2179
  seed: e.seed,
2169
2180
  ...e.dbUrl === void 0 ? {} : { dbUrl: e.dbUrl },
2170
2181
  ...e.prefer === void 0 ? {} : { prefer: e.prefer }
2171
- }), i = Ys({
2182
+ }), i = $s({
2172
2183
  mechanism: r,
2173
2184
  branchId: n,
2174
2185
  tableNames: e.tableNames,
@@ -2197,15 +2208,15 @@ var Qt = (e) => typeof e == "string" && e !== "" ? e : null, $t = async (e, t, n
2197
2208
  mechanism: r,
2198
2209
  steps: i
2199
2210
  };
2200
- }, $s = async (e, t, n) => {
2201
- let r = Xs(t, e);
2211
+ }, rc = async (e, t, n) => {
2212
+ let r = ec(t, e);
2202
2213
  return t === "neon-cow" ? await n.neonBranchDelete(e) : await n.dropNamespace(e), r;
2203
- }, ec = (e, t, n) => Zs(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, tc = {
2214
+ }, ic = (e, t, n) => tc(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, ac = {
2204
2215
  cascade: "CASCADE",
2205
2216
  restrict: "RESTRICT",
2206
2217
  setNull: "SET NULL",
2207
2218
  noAction: "NO ACTION"
2208
- }, Z = (e) => `'${e.replace(/'/g, "''")}'`, nc = (e, t) => {
2219
+ }, Z = (e) => `'${e.replace(/'/g, "''")}'`, oc = (e, t) => {
2209
2220
  let n = t.columns.map(Z).join(", ");
2210
2221
  return `DO $voltro_branch$
2211
2222
  DECLARE derived name;
@@ -2232,10 +2243,10 @@ BEGIN
2232
2243
  END IF;
2233
2244
  END
2234
2245
  $voltro_branch$`;
2235
- }, rc = (e, t) => {
2236
- let n = t.onDelete === void 0 ? "" : ` ON DELETE ${tc[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${tc[t.onUpdate]}`;
2246
+ }, sc = (e, t) => {
2247
+ let n = t.onDelete === void 0 ? "" : ` ON DELETE ${ac[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${ac[t.onUpdate]}`;
2237
2248
  return `ALTER TABLE ${X(e)}.${X(t.table)} ADD FOREIGN KEY (${X(t.column)}) REFERENCES ${X(e)}.${X(t.targetTable)} (${X(t.targetColumn)})${n}${r}`;
2238
- }, ic = (e) => {
2249
+ }, cc = (e) => {
2239
2250
  let t = () => {
2240
2251
  throw Error("namespace branch executor: Neon ops require a neon-cow executor (use a Neon connection for copy-on-write branches)");
2241
2252
  };
@@ -2243,24 +2254,24 @@ $voltro_branch$`;
2243
2254
  createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${X(t)}`),
2244
2255
  createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${X(t)}.${X(n)} (LIKE ${X(n)} INCLUDING ALL)`),
2245
2256
  copyTable: (t, n, r) => e.run(`INSERT INTO ${X(n)}.${X(r)} SELECT * FROM ${X(t)}.${X(r)}`),
2246
- addForeignKey: (t, n) => e.run(rc(t, n)),
2247
- restoreIndexName: (t, n) => e.run(nc(t, n)),
2257
+ addForeignKey: (t, n) => e.run(sc(t, n)),
2258
+ restoreIndexName: (t, n) => e.run(oc(t, n)),
2248
2259
  dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${X(t)} CASCADE`),
2249
2260
  neonBranchCreate: t,
2250
2261
  neonBranchDelete: t
2251
2262
  };
2252
- }, ac = class extends Error {
2263
+ }, lc = class extends Error {
2253
2264
  _tag = "TenantResidencyUnresolved";
2254
2265
  constructor(e) {
2255
2266
  super(e), this.name = "TenantResidencyUnresolved";
2256
2267
  }
2257
- }, oc = class extends Error {
2268
+ }, uc = class extends Error {
2258
2269
  region;
2259
2270
  _tag = "TenantRegionUnavailable";
2260
2271
  constructor(e, t) {
2261
2272
  super(t), this.region = e, this.name = "TenantRegionUnavailable";
2262
2273
  }
2263
- }, sc, cc = (e) => {
2274
+ }, dc, fc = (e) => {
2264
2275
  if (e.homes === void 0) throw Error("setResidencyConfig: `homes` is required");
2265
2276
  if (e.servableRegions === void 0 || e.servableRegions.length === 0) throw Error("setResidencyConfig: `servableRegions` must be non-empty (which regions this deployment serves)");
2266
2277
  let t = /* @__PURE__ */ new Map();
@@ -2269,55 +2280,55 @@ $voltro_branch$`;
2269
2280
  if (e !== void 0 && e !== n.region) throw Error(`residency: tenant '${n.tenantId}' is mapped to two regions ('${e}' and '${n.region}')`);
2270
2281
  t.set(n.tenantId, n.region);
2271
2282
  }
2272
- return sc = e, e;
2273
- }, lc = () => sc, uc = () => {
2274
- sc = void 0;
2275
- }, dc = (e, t) => {
2276
- if (e == null || e === "") throw new ac("residency is on but the request has no resolvable tenant — refusing to bind a store");
2283
+ return dc = e, e;
2284
+ }, pc = () => dc, mc = () => {
2285
+ dc = void 0;
2286
+ }, hc = (e, t) => {
2287
+ if (e == null || e === "") throw new lc("residency is on but the request has no resolvable tenant — refusing to bind a store");
2277
2288
  let n = t.homes.find((t) => t.tenantId === e);
2278
- if (n === void 0) throw new ac(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2289
+ if (n === void 0) throw new lc(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2279
2290
  return n;
2280
- }, fc = (e, t) => t.servableRegions.includes(e), pc = (e, t) => {
2281
- let n = dc(e.tenantId, t), r = Wr(n.tenantId);
2291
+ }, gc = (e, t) => t.servableRegions.includes(e), _c = (e, t) => {
2292
+ let n = hc(e.tenantId, t), r = Jr(n.tenantId);
2282
2293
  return {
2283
2294
  region: n.region,
2284
2295
  namespace: r,
2285
2296
  ...n.connectionKey === void 0 ? {} : { connectionKey: n.connectionKey }
2286
2297
  };
2287
- }, mc = (e, t, n) => {
2288
- let r = pc(e, t);
2289
- if (!fc(r.region, t)) throw new oc(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
2298
+ }, vc = (e, t, n) => {
2299
+ let r = _c(e, t);
2300
+ if (!gc(r.region, t)) throw new uc(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
2290
2301
  let i = n.get(r.region);
2291
- if (i === void 0) throw new oc(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
2302
+ if (i === void 0) throw new uc(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
2292
2303
  return {
2293
2304
  store: i,
2294
2305
  placement: r
2295
2306
  };
2296
- }, hc = async (e, t, n, r) => {
2297
- let { store: i, placement: a } = mc(e, t, n);
2307
+ }, yc = async (e, t, n, r) => {
2308
+ let { store: i, placement: a } = vc(e, t, n);
2298
2309
  return await r(i, a), a;
2299
- }, gc = (e) => {
2310
+ }, bc = (e) => {
2300
2311
  if (typeof e == "string") return e;
2301
2312
  if ("jsonPath" in e) {
2302
2313
  let { column: t, path: n, numeric: r } = e.jsonPath;
2303
2314
  return `(json:${t}->${n.join(".")}${r ? "::num" : ""})`;
2304
2315
  }
2305
2316
  return `(${e.expr})`;
2306
- }, Q = (e) => e.map(gc), _c = (e, t) => {
2317
+ }, Q = (e) => e.map(bc), xc = (e, t) => {
2307
2318
  if (e.length !== t.length) return !1;
2308
- for (let n = 0; n < e.length; n++) if (gc(e[n]) !== gc(t[n])) return !1;
2319
+ for (let n = 0; n < e.length; n++) if (bc(e[n]) !== bc(t[n])) return !1;
2309
2320
  return !0;
2310
- }, vc = (e, t) => {
2321
+ }, Sc = (e, t) => {
2311
2322
  if (e.length >= t.length) return !1;
2312
- for (let n = 0; n < e.length; n++) if (gc(e[n]) !== gc(t[n])) return !1;
2323
+ for (let n = 0; n < e.length; n++) if (bc(e[n]) !== bc(t[n])) return !1;
2313
2324
  return !0;
2314
- }, yc = (e) => {
2325
+ }, Cc = (e) => {
2315
2326
  let t = [], n = e.appliedIndexes, r = e.tableName;
2316
2327
  for (let e = 0; e < n.length; e++) {
2317
2328
  let i = n[e];
2318
2329
  for (let a = e + 1; a < n.length; a++) {
2319
2330
  let e = n[a];
2320
- if (_c(i.fields, e.fields)) {
2331
+ if (xc(i.fields, e.fields)) {
2321
2332
  let [n, a] = i.name < e.name ? [i, e] : [e, i];
2322
2333
  t.push({
2323
2334
  kind: "duplicate-fields",
@@ -2328,13 +2339,13 @@ $voltro_branch$`;
2328
2339
  });
2329
2340
  continue;
2330
2341
  }
2331
- vc(i.fields, e.fields) ? t.push({
2342
+ Sc(i.fields, e.fields) ? t.push({
2332
2343
  kind: "redundant-prefix",
2333
2344
  table: r,
2334
2345
  redundant: i,
2335
2346
  coveredBy: e,
2336
2347
  message: `'${r}' index '${i.name}' on [${Q(i.fields).join(", ")}] is a leading prefix of '${e.name}' on [${Q(e.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Q(i.fields).join(", ")}] query from '${e.name}' too via the leading-prefix rule, so '${i.name}' adds write cost without read benefit. Drop '${i.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
2337
- }) : vc(e.fields, i.fields) && t.push({
2348
+ }) : Sc(e.fields, i.fields) && t.push({
2338
2349
  kind: "redundant-prefix",
2339
2350
  table: r,
2340
2351
  redundant: e,
@@ -2344,23 +2355,23 @@ $voltro_branch$`;
2344
2355
  }
2345
2356
  }
2346
2357
  return t;
2347
- }, bc = (e) => {
2358
+ }, wc = (e) => {
2348
2359
  let t = [];
2349
- for (let n of e) t.push(...yc(n));
2360
+ for (let n of e) t.push(...Cc(n));
2350
2361
  return t;
2351
- }, xc = "\x1B[", Sc = `${xc}38;2;245;158;11m`, Cc = `${xc}38;2;16;185;129m`, wc = (e, t) => `${e}${t}${M.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : wc(t, n) : n, Tc = (e, t = {}) => {
2352
- let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, M.dim, e.padEnd(11)), a = (e) => $(n, (e) => M.bold(M.brand(e)), e), o = (e) => $(n, M.brightRed24, e), s = (e) => $(n, Cc, e), c = (e) => $(n, Sc, e), l = (e) => $(n, M.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, M.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
2362
+ }, Tc = "\x1B[", Ec = `${Tc}38;2;245;158;11m`, Dc = `${Tc}38;2;16;185;129m`, Oc = (e, t) => `${e}${t}${N.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : Oc(t, n) : n, kc = (e, t = {}) => {
2363
+ let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, N.dim, e.padEnd(11)), a = (e) => $(n, (e) => N.bold(N.brand(e)), e), o = (e) => $(n, N.brightRed24, e), s = (e) => $(n, Dc, e), c = (e) => $(n, Ec, e), l = (e) => $(n, N.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, N.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
2353
2364
  let n = e.slice(0, t), r = e.slice(t), i = [];
2354
2365
  return n.length > 0 && i.push(s(`[${n.join(", ")}]`)), r.length > 0 && i.push(c(`+ [${r.join(", ")}]`)), i.join(" ");
2355
2366
  }, m = [];
2356
- return m.push(u), m.push(""), m.push(`${i("table")}${a(e.table)}`), m.push(""), m.push(`${i("redundant")}${o(e.redundant.name)}`), m.push(`${i("")}${p(Q(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Q(e.coveredBy.fields), d)}`), f.length > 0 && m.push(`${i("")}${l(`└ extra columns: ${f.join(", ")}`)}`), m.push(""), e.kind === "redundant-prefix" ? (m.push(`${i("why")}B-tree indexes serve queries that filter on a LEADING PREFIX of`), m.push(`${i("")}their column list. The wider index already covers every`), m.push(`${i("")}query the narrower one can serve.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)) : (m.push(`${i("why")}Two indexes on the same columns under different names.`), m.push(`${i("")}The B-tree engine builds both — same coverage, double cost.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)), m.push(""), m.push(`${i("cost")}Every ${a("INSERT")} / ${a("UPDATE")} / ${a("DELETE")} on this table writes`), m.push(`${i("")}to ${$(n, M.bold, "both")} B-trees. Pure write overhead, zero read benefit.`), m.push(""), m.push(`${i("fix")}Drop ${o(e.redundant.name)}`), m.push(`${i("")}${l("Keep only if profiling shows the smaller index gives a")}`), m.push(`${i("")}${l("measurable cache-locality boost on a write-heavy hot path.")}`), m.push(`${i("")}${l("Silence with VOLTRO_INDEX_AUDIT=off if intentional.")}`), m.map((e) => `${r}${e}`).join("\n");
2357
- }, Ec = (e, { apply: t, undo: n }) => ({
2367
+ return m.push(u), m.push(""), m.push(`${i("table")}${a(e.table)}`), m.push(""), m.push(`${i("redundant")}${o(e.redundant.name)}`), m.push(`${i("")}${p(Q(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Q(e.coveredBy.fields), d)}`), f.length > 0 && m.push(`${i("")}${l(`└ extra columns: ${f.join(", ")}`)}`), m.push(""), e.kind === "redundant-prefix" ? (m.push(`${i("why")}B-tree indexes serve queries that filter on a LEADING PREFIX of`), m.push(`${i("")}their column list. The wider index already covers every`), m.push(`${i("")}query the narrower one can serve.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)) : (m.push(`${i("why")}Two indexes on the same columns under different names.`), m.push(`${i("")}The B-tree engine builds both — same coverage, double cost.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)), m.push(""), m.push(`${i("cost")}Every ${a("INSERT")} / ${a("UPDATE")} / ${a("DELETE")} on this table writes`), m.push(`${i("")}to ${$(n, N.bold, "both")} B-trees. Pure write overhead, zero read benefit.`), m.push(""), m.push(`${i("fix")}Drop ${o(e.redundant.name)}`), m.push(`${i("")}${l("Keep only if profiling shows the smaller index gives a")}`), m.push(`${i("")}${l("measurable cache-locality boost on a write-heavy hot path.")}`), m.push(`${i("")}${l("Silence with VOLTRO_INDEX_AUDIT=off if intentional.")}`), m.map((e) => `${r}${e}`).join("\n");
2368
+ }, Ac = (e, { apply: t, undo: n }) => ({
2358
2369
  name: e,
2359
2370
  apply: t,
2360
2371
  undo: n
2361
- }), Dc = (e) => {
2372
+ }), jc = (e) => {
2362
2373
  if (!/^\d{14}_/.test(e.id)) throw Error(`migration "${e.id}": id must start with a 14-digit timestamp followed by "_" (convention: <YYYYMMDDHHMMSS>_<slug>)`);
2363
- let t = e.steps({ step: Ec });
2374
+ let t = e.steps({ step: Ac });
2364
2375
  if (t.length === 0) throw Error(`migration "${e.id}": at least one step is required`);
2365
2376
  return {
2366
2377
  __migration: !0,
@@ -2368,7 +2379,7 @@ $voltro_branch$`;
2368
2379
  name: e.name,
2369
2380
  steps: t
2370
2381
  };
2371
- }, Oc = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, kc = w("_voltro_migrations", {
2382
+ }, Mc = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Nc = w("_voltro_migrations", {
2372
2383
  id: E({ prefix: "mig" }),
2373
2384
  name: C(),
2374
2385
  hash: C(),
@@ -2380,7 +2391,7 @@ $voltro_branch$`;
2380
2391
  workflowRunId: C().nullable(),
2381
2392
  createdAt: T().default("now"),
2382
2393
  updatedAt: T().default("now").onUpdate("now")
2383
- }).index(["status"]), Ac = w("_voltro_seeds", {
2394
+ }).index(["status"]), Pc = w("_voltro_seeds", {
2384
2395
  id: E({ prefix: "seed" }),
2385
2396
  name: C(),
2386
2397
  lifecycle: C(),
@@ -2396,7 +2407,7 @@ $voltro_branch$`;
2396
2407
  workflowRunId: C().nullable(),
2397
2408
  createdAt: T().default("now"),
2398
2409
  updatedAt: T().default("now").onUpdate("now")
2399
- }).index(["lifecycle"]).index(["nextRunAt"]), jc = w("_voltro_migration_plans", {
2410
+ }).index(["lifecycle"]).index(["nextRunAt"]), Fc = w("_voltro_migration_plans", {
2400
2411
  id: E({ prefix: "plan" }),
2401
2412
  fingerprint: C(),
2402
2413
  liveFingerprint: C().nullable(),
@@ -2412,21 +2423,21 @@ $voltro_branch$`;
2412
2423
  appliedAt: T().default("now"),
2413
2424
  createdAt: T().default("now"),
2414
2425
  updatedAt: T().default("now").onUpdate("now")
2415
- }).index(["fingerprint"]).index(["environment"]), Mc = w("_voltro_idempotency", {
2426
+ }).index(["fingerprint"]).index(["environment"]), Ic = w("_voltro_idempotency", {
2416
2427
  id: E({ prefix: "idem" }),
2417
2428
  scope: C(),
2418
2429
  key: C(),
2419
2430
  status: C(),
2420
2431
  response: x().nullable(),
2421
2432
  createdAt: T().default("now")
2422
- }).unique(["scope", "key"]).index(["createdAt"]), Nc = w("_voltro_kv", {
2433
+ }).unique(["scope", "key"]).index(["createdAt"]), Lc = w("_voltro_kv", {
2423
2434
  id: E({ prefix: "kv" }),
2424
2435
  key: C().unique(),
2425
2436
  value: C().nullable(),
2426
2437
  expiresAt: T().nullable(),
2427
2438
  createdAt: T().default("now"),
2428
2439
  updatedAt: T().default("now").onUpdate("now")
2429
- }).index(["expiresAt"]), Pc = w("_voltro_api_keys", {
2440
+ }).index(["expiresAt"]), Rc = w("_voltro_api_keys", {
2430
2441
  id: E({ prefix: "apikey" }),
2431
2442
  tenantId: C().nullable(),
2432
2443
  name: C(),
@@ -2441,7 +2452,7 @@ $voltro_branch$`;
2441
2452
  onBehalfOf: C().nullable(),
2442
2453
  metadata: x().nullable(),
2443
2454
  createdAt: T().default("now")
2444
- }).index("byApiKeyTenant", ["tenantId"]), Fc = w("_voltro_replica_observations", {
2455
+ }).index("byApiKeyTenant", ["tenantId"]), zc = w("_voltro_replica_observations", {
2445
2456
  id: E({ prefix: "robs" }),
2446
2457
  replicaId: C().maxLength(191),
2447
2458
  startedAt: T(),
@@ -2450,11 +2461,11 @@ $voltro_branch$`;
2450
2461
  payload: C().nullable(),
2451
2462
  reachableAt: C().maxLength(255).nullable(),
2452
2463
  writtenAt: T().default("now").onUpdate("now")
2453
- }).unique(["replicaId", "kind"]).index(["kind"]), Ic = [
2454
- kc,
2455
- Ac,
2456
- jc
2457
- ], Lc = "_voltro_replace_in_progress", Rc = w(Lc, {
2464
+ }).unique(["replicaId", "kind"]).index(["kind"]), Bc = [
2465
+ Nc,
2466
+ Pc,
2467
+ Fc
2468
+ ], Vc = "_voltro_replace_in_progress", Hc = w(Vc, {
2458
2469
  id: E({ prefix: "repl" }),
2459
2470
  startedAt: T().default("now"),
2460
2471
  kind: C().default("replace"),
@@ -2464,10 +2475,10 @@ $voltro_branch$`;
2464
2475
  staging: C().nullable(),
2465
2476
  heartbeatAt: T().nullable(),
2466
2477
  resumable: p().nullable()
2467
- }), zc = 30, Bc = (e, t) => {
2478
+ }), Uc = 30, Wc = (e, t) => {
2468
2479
  let n = typeof t == "number" && Number.isFinite(t) && t > 0 ? t : 30, r = Number(e.VOLTRO_STAGING_STALE_MINUTES);
2469
2480
  return (Number.isFinite(r) && r > 0 ? r : n) * 6e4;
2470
- }, Vc = (e) => e == null || String(e).length === 0 ? [] : String(e).split(",").map((e) => e.trim()).filter((e) => e.length > 0), Hc = (e) => {
2481
+ }, Gc = (e) => e == null || String(e).length === 0 ? [] : String(e).split(",").map((e) => e.trim()).filter((e) => e.length > 0), Kc = (e) => {
2471
2482
  let t = e.filter((e) => e.kind !== "staging");
2472
2483
  if (t.length !== 0) return `refusing to start: a destructive data operation did not finish.
2473
2484
  ${t.map((e) => {
@@ -2482,7 +2493,7 @@ ${t.map((e) => {
2482
2493
 
2483
2494
  When the data is back, or you have decided the current state is correct, clear the marker:
2484
2495
  voltro data clear-replace-marker --yes`;
2485
- }, Uc = (e, t, n) => {
2496
+ }, qc = (e, t, n) => {
2486
2497
  let r = e.filter((e) => e.kind === "staging");
2487
2498
  return {
2488
2499
  all: r,
@@ -2492,7 +2503,7 @@ ${t.map((e) => {
2492
2503
  return Number.isFinite(r) ? t - r >= n : !1;
2493
2504
  })
2494
2505
  };
2495
- }, Wc = (e, t) => {
2506
+ }, Jc = (e, t) => {
2496
2507
  if (e.all.length === 0) return;
2497
2508
  let n = new Set(e.droppable.map((e) => e.id));
2498
2509
  return `staged data-import leftovers:
@@ -2501,22 +2512,22 @@ ${e.all.map((e) => {
2501
2512
  return n.has(e.id) ? ` - ${a} — DROPPED: the run is not resumable and has been silent long enough that nothing is loading into them.` : e.resumable ? ` - ${a} — KEPT: the run was started \`--no-atomic\`, so these ARE its resume point. Re-run the same\n bundle to continue from them, or drop them with: voltro data clear-staging --yes` : ` - ${a} — KEPT: still beating, so an import is loading into them right now.`;
2502
2513
  }).join("\n")}\n The target of a staged \`replace\` is untouched until one short swap at the end, so none of this is
2503
2514
  a reason to refuse the boot — it is a reason to know the disk is holding a copy of a bundle.`;
2504
- }, Gc = "id", Kc = (e, t) => {
2515
+ }, Yc = "id", Xc = (e, t) => {
2505
2516
  let n = S(e);
2506
2517
  if (n === void 0) return t;
2507
- let r = n.fields[Gc]?.idScheme;
2508
- if (r === void 0 || t[Gc] != null) return t;
2518
+ let r = n.fields[Yc]?.idScheme;
2519
+ if (r === void 0 || t[Yc] != null) return t;
2509
2520
  if (r.kind === "numeric") {
2510
- if (!(Gc in t)) return t;
2521
+ if (!(Yc in t)) return t;
2511
2522
  let e = { ...t };
2512
- return delete e[Gc], e;
2523
+ return delete e[Yc], e;
2513
2524
  }
2514
2525
  let i = it(r, e);
2515
2526
  return i === null ? t : {
2516
2527
  ...t,
2517
- [Gc]: i
2528
+ [Yc]: i
2518
2529
  };
2519
- }, qc = (e, t) => t.map((t) => Kc(e, t)), Jc = {
2530
+ }, Zc = (e, t) => t.map((t) => Xc(e, t)), Qc = {
2520
2531
  postgres: { maxBindParameters: 65535 },
2521
2532
  mysql: { maxBindParameters: 65535 },
2522
2533
  mariadb: { maxBindParameters: 65535 },
@@ -2526,25 +2537,25 @@ ${e.all.map((e) => {
2526
2537
  },
2527
2538
  sqlite: { maxBindParameters: 32766 },
2528
2539
  turso: { maxBindParameters: 32766 }
2529
- }, Yc = (e) => Jc[e], Xc = (e) => {
2540
+ }, $c = (e) => Qc[e], el = (e) => {
2530
2541
  let t = /* @__PURE__ */ new Set();
2531
2542
  for (let n of e) for (let e of Object.keys(n)) t.add(e);
2532
2543
  return t.size;
2533
- }, Zc = (e, t) => {
2544
+ }, tl = (e, t) => {
2534
2545
  if (t === void 0 || e.length === 0) return [e];
2535
- let n = Math.max(1, Xc(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2546
+ let n = Math.max(1, el(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2536
2547
  if (e.length <= a) return [e];
2537
2548
  let o = [];
2538
2549
  for (let t = 0; t < e.length; t += a) o.push(e.slice(t, t + a));
2539
2550
  return o;
2540
- }, Qc = (e, t) => {
2551
+ }, nl = (e, t) => {
2541
2552
  let n = [], r = t;
2542
2553
  for (let [t, i] of Object.entries(e.fields)) {
2543
2554
  let e = i;
2544
2555
  e.nullable || e.hasDefault || e.idScheme !== void 0 || e.generatedAs !== void 0 || (r[t] === void 0 || r[t] === null) && n.push(t);
2545
2556
  }
2546
2557
  return n;
2547
- }, $c = (e, t, n) => {
2558
+ }, rl = (e, t, n) => {
2548
2559
  let r = n, i = new Set(e === void 0 ? [] : Object.entries(e.fields).filter(([, e]) => e.generatedAs !== void 0).map(([e]) => e)), a = [];
2549
2560
  for (let e of t) i.has(e) || (r[e] === void 0 ? a.push({
2550
2561
  column: e,
@@ -2554,28 +2565,28 @@ ${e.all.map((e) => {
2554
2565
  reason: "null"
2555
2566
  }));
2556
2567
  return a;
2557
- }, el = (e, t, n) => e.insert(t.tableName, n), tl = (e, t, n, r) => e.upsert(t.tableName, n, {
2568
+ }, il = (e, t, n) => e.insert(t.tableName, n), al = (e, t, n, r) => e.upsert(t.tableName, n, {
2558
2569
  conflictColumns: r.conflictColumns,
2559
2570
  ...r.update === void 0 ? {} : { update: r.update }
2560
- }), nl = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), rl = 512, il = (e) => {
2571
+ }), ol = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), sl = 512, cl = (e) => {
2561
2572
  e.setMaxListeners(512);
2562
- }, al = (e, t, n) => ({
2573
+ }, ll = (e, t, n) => ({
2563
2574
  _tag: "PrimaryKeyConflictError",
2564
2575
  table: e,
2565
2576
  key: t,
2566
2577
  cause: n
2567
- }), ol = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", sl = {
2578
+ }), ul = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", dl = {
2568
2579
  postgres: 5432,
2569
2580
  mysql: 3306,
2570
2581
  mariadb: 3306,
2571
2582
  mssql: 1433
2572
- }, cl = /* @__PURE__ */ new Set([
2583
+ }, fl = /* @__PURE__ */ new Set([
2573
2584
  "localhost",
2574
2585
  "127.0.0.1",
2575
2586
  "::1",
2576
2587
  "[::1]",
2577
2588
  "0.0.0.0"
2578
- ]), ll = (e) => {
2589
+ ]), pl = (e) => {
2579
2590
  let t = e.host, n = e.port, r = e.database;
2580
2591
  if (e.url !== void 0 && e.url !== "") try {
2581
2592
  let i = new URL(e.url);
@@ -2584,29 +2595,29 @@ ${e.all.map((e) => {
2584
2595
  return;
2585
2596
  }
2586
2597
  if (t === void 0 || t === "" || r === void 0 || r === "") return;
2587
- let i = n ?? sl[(e.dialect ?? "").toLowerCase()];
2598
+ let i = n ?? dl[(e.dialect ?? "").toLowerCase()];
2588
2599
  if (i === void 0 || !Number.isFinite(i)) return;
2589
2600
  let a = t.toLowerCase();
2590
2601
  return {
2591
- host: cl.has(a) ? "localhost" : a,
2602
+ host: fl.has(a) ? "localhost" : a,
2592
2603
  port: i,
2593
2604
  database: r.toLowerCase()
2594
2605
  };
2595
- }, ul = (e) => {
2596
- let t = ll(e);
2597
- if (t !== void 0) return Jt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2598
- }, dl = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", fl = {
2606
+ }, ml = (e) => {
2607
+ let t = pl(e);
2608
+ if (t !== void 0) return qt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2609
+ }, hl = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", gl = {
2599
2610
  app: 3,
2600
2611
  plugin: 2,
2601
2612
  framework: 1
2602
- }, pl = /* @__PURE__ */ new Map(), ml = [], hl = () => [...ml], gl = (e) => {
2613
+ }, _l = /* @__PURE__ */ new Map(), vl = [], yl = () => [...vl], bl = (e) => {
2603
2614
  if (!e.table || !e.timeColumn) throw Error("registerRetention: table + timeColumn are required");
2604
2615
  if (!Number.isFinite(e.ttlMs) || e.ttlMs <= 0) throw Error(`registerRetention(${e.table}): ttlMs must be a positive number`);
2605
- let t = e.source ?? "app", n = pl.get(e.table);
2616
+ let t = e.source ?? "app", n = _l.get(e.table);
2606
2617
  if (n !== void 0) {
2607
2618
  let r = n.source ?? "app", i = n.ttlMs !== e.ttlMs || n.where !== void 0 != (e.where !== void 0);
2608
- if (fl[t] < fl[r]) {
2609
- i && ml.push({
2619
+ if (gl[t] < gl[r]) {
2620
+ i && vl.push({
2610
2621
  table: e.table,
2611
2622
  kept: {
2612
2623
  source: r,
@@ -2619,7 +2630,7 @@ ${e.all.map((e) => {
2619
2630
  });
2620
2631
  return;
2621
2632
  }
2622
- i && r !== t && ml.push({
2633
+ i && r !== t && vl.push({
2623
2634
  table: e.table,
2624
2635
  kept: {
2625
2636
  source: t,
@@ -2631,13 +2642,13 @@ ${e.all.map((e) => {
2631
2642
  }
2632
2643
  });
2633
2644
  }
2634
- pl.set(e.table, {
2645
+ _l.set(e.table, {
2635
2646
  ...e,
2636
2647
  source: t
2637
2648
  });
2638
- }, _l = () => [...pl.values()], vl = () => {
2639
- pl.clear(), ml.length = 0;
2640
- }, yl = async (e, t, n, r = 2e4) => {
2649
+ }, xl = () => [..._l.values()], Sl = () => {
2650
+ _l.clear(), vl.length = 0;
2651
+ }, Cl = async (e, t, n, r = 2e4) => {
2641
2652
  let i = new Date(t - e.ttlMs), a = 0;
2642
2653
  try {
2643
2654
  for (;;) {
@@ -2645,26 +2656,26 @@ ${e.all.map((e) => {
2645
2656
  if (a += t, t < r) break;
2646
2657
  }
2647
2658
  } catch (t) {
2648
- throw O.runSync(k.increment(k.tagged(xl, "table", e.table))), t;
2659
+ throw k.runSync(A.increment(A.tagged(Tl, "table", e.table))), t;
2649
2660
  }
2650
- return a > 0 && O.runSync(k.incrementBy(k.tagged(bl, "table", e.table), a)), a;
2651
- }, bl = k.counter("voltro_retention_swept_rows_total"), xl = k.counter("voltro_retention_sweep_errors_total"), Sl = (e, t) => {
2661
+ return a > 0 && k.runSync(A.incrementBy(A.tagged(wl, "table", e.table), a)), a;
2662
+ }, wl = A.counter("voltro_retention_swept_rows_total"), Tl = A.counter("voltro_retention_sweep_errors_total"), El = (e, t) => {
2652
2663
  let n = Number(e ?? String(t));
2653
2664
  return (Number.isFinite(n) && n > 0 ? n : t) * 36e5;
2654
- }, Cl = "_voltro_cdc_offsets", wl = w(Cl, {
2665
+ }, Dl = "_voltro_cdc_offsets", Ol = w(Dl, {
2655
2666
  id: E({ prefix: "cdcoff" }),
2656
2667
  replicaId: C(),
2657
2668
  streamName: C(),
2658
2669
  binlogFile: C(),
2659
2670
  binlogPosition: C(),
2660
2671
  updatedAt: T()
2661
- }).index(["replicaId"]), Tl = w(Cl, {
2672
+ }).index(["replicaId"]), kl = w(Dl, {
2662
2673
  id: E({ prefix: "cdcoff" }),
2663
2674
  replicaId: C(),
2664
2675
  streamName: C(),
2665
2676
  ctVersion: C(),
2666
2677
  updatedAt: T()
2667
- }).index(["replicaId"]), El = "_voltro_data_transfers", Dl = w(El, {
2678
+ }).index(["replicaId"]), Al = "_voltro_data_transfers", jl = w(Al, {
2668
2679
  id: E({ prefix: "dimp" }),
2669
2680
  startedAt: T().default("now"),
2670
2681
  finishedAt: T().nullable(),
@@ -2677,13 +2688,13 @@ ${e.all.map((e) => {
2677
2688
  rowsWritten: _().default(0),
2678
2689
  failure: C().nullable(),
2679
2690
  staged: p().nullable()
2680
- }).renamedFrom("_voltro_data_imports").nonReactive(), Ol = (e) => {
2691
+ }).renamedFrom("_voltro_data_imports").nonReactive(), Ml = (e) => {
2681
2692
  let t = Number.isFinite(e.startedAt.getTime()) ? e.startedAt.toISOString() : "an unknown time", n = e.direction === "import" ? e.mode : `${e.direction} ${e.mode}`, r = e.failure === null ? e.finishedAt === null ? `${n} — started and never reported finishing` : e.direction === "backup" || e.direction === "restore" ? `${n} — finished${e.rowsWritten > 0 ? ` (${e.rowsWritten} blob(s))` : ""}` : `${n} — ${e.rowsWritten} row(s) across ${e.tablesWritten} table(s)` : `FAILED ${n} — ${e.failure}`, i = e.staged === null ? "" : e.staged ? " · staged (target untouched until the swap)" : " · NOT staged (target emptied first)";
2682
2693
  return `${t} · ${r} · via ${e.via}${i}` + (e.bundle === null ? "" : ` · from ${e.bundle}`) + (e.sourceFingerprint === null ? "" : ` · source schema ${e.sourceFingerprint}`);
2683
- }, kl = 255, Al = (e) => e == null ? "null" : typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? JSON.stringify(e) : Array.isArray(e) ? `[${e.map(Al).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${Al(t)}`).join(",")}}` : JSON.stringify(String(e)), jl = (e) => {
2694
+ }, Nl = 255, Pl = (e) => e == null ? "null" : typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? JSON.stringify(e) : Array.isArray(e) ? `[${e.map(Pl).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${Pl(t)}`).join(",")}}` : JSON.stringify(String(e)), Fl = (e) => {
2684
2695
  if (e == null) return null;
2685
- let t = typeof e == "string" ? e : Al(e);
2696
+ let t = typeof e == "string" ? e : Pl(e);
2686
2697
  return t.length > 255 ? t.slice(0, 255) : t;
2687
- }, Ml = "postgres";
2698
+ }, Il = "postgres";
2688
2699
  //#endregion
2689
- export { lt as AUTO_FILLED_COLUMNS, on as BOUND_ENCRYPTED_PREFIX, Jc as BULK_INSERT_LIMITS, Y as BranchNameInvalid, Vs as BranchTransitionInvalid, Cl as CDC_OFFSETS_TABLE, no as CHANGE_CLAIM_TTL_ENV, rl as CHANGE_LISTENER_CEILING, Qe as ColumnBuilder, El as DATA_TRANSFERS_TABLE, st as DEFAULT_ACQUIRE_TIMEOUT_MS, ro as DEFAULT_CHANGE_CLAIM_TTL_HOURS, as as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, yt as DEFAULT_SOFT_DROP_RETENTION_DAYS, lr as DEFAULT_SUBJECT_GRAPH_DEPTH, an as ENCRYPTED_PREFIX, Ml as ENGINE, Er as EagerCardinalityError, St as FILE_MIGRATION_PATTERN, at as FRAMEWORK_LIVE_TABLES, ln as FieldDecryptionError, Do as ID_COLUMN_MAX_LENGTH, Lt as INITIAL_VERSION, Oa as MATCHES_NO_ROWS, Tt as MAX_IDENTIFIER_LENGTH, gs as MSSQL_TRANSIENT_NUMBERS, ms as MYSQL_TRANSIENT_CODES, to as OccurrenceCounter, hs as POSTGRES_TRANSIENT_STATES, Lc as REPLACE_IN_PROGRESS_TABLE, kl as SCOPE_KEY_MAX_LENGTH, se as SELF_REFERENCE_TARGET, _s as SQLITE_TRANSIENT_CODES, zc as STAGING_STALE_MINUTES, pt as STAGING_TABLE_PREFIX, Zt as SqlClient, vs as TURSO_TRANSIENT_MESSAGE, ks as TableStreamError, Br as TenantNamespaceInvalid, zr as TenantNamespaceUnresolved, oc as TenantRegionUnavailable, ac as TenantResidencyUnresolved, Cs as VOLTRO_EXPIRES_MIXIN_ID, Ts as VOLTRO_LOCAL_FIRST_MIXIN_ID, Pt as VersionConflict, At as WARN_IDENTIFIER_LENGTH, Pc as _voltroApiKeysTable, wl as _voltroCdcOffsetsTable, Dl as _voltroDataTransfersTable, Mc as _voltroIdempotencyTable, Nc as _voltroKvTable, jc as _voltroMigrationPlansTable, kc as _voltroMigrationsTable, Tl as _voltroMssqlCdcOffsetsTable, Rc as _voltroReplaceInProgressTable, Fc as _voltroReplicaObservationsTable, Ac as _voltroSeedsTable, ma as actorsTable, ec as admitBranch, Je as agedSoftDropSnapshots, be as allEnumRenames, or as allRegisteredRelations, re as allRegisteredTables, Ma as and, ce as array, Ta as arrayContains, Da as arrayHas, Ea as arrayOverlaps, Or as attachEagerLoads, co as attributionFields, po as attributionKey, bc as auditAllTableIndexes, yc as auditTableIndexes, Et as avg, ye as avgOver, So as beginLocalWrite, fe as bigint, mc as bindResidentStore, p as boolean, Rs as branchNamespaceName, Yc as bulkInsertLimitsFor, ne as bytes, N as causeBranches, Ya as changeDelete, Qa as changeDigest, qa as changeInsert, Xa as changeSoftDelete, Ja as changeUpdate, Zc as chunkRowsForInsert, go as claimPendingAttribution, Dn as classifyConstraintViolation, d as clearEnumRenames, To as clearPendingAttribution, cr as clearRelationsRegistry, uc as clearResidencyConfig, vl as clearRetentions, Oe as clearTableRegistry, Po as clearWriteRecorders, W as coercePredicateForSqlite, Jr as coercePredicateValue, Yr as coercePredicateValues, oa as coerceValueForSqlite, Wa as collectSubqueries, u as column, In as columnSchema, Xc as columnsPerRow, li as compileEagerJson, L as compilePredicate, Xr as compileRawFragment, ci as compileSelect, $a as composeChangeKey, Ps as computeEmbedding, ul as connectionIdentity, Ca as contains, c as count, le as countDistinct, oe as crdtDoc, ge as crdtManagedColumns, Mt as crdtManagedColumnsOf, a as crdtText, so as currentWriteAttribution, $e as databaseHandle, we as date, ee as dbEnum, $o as dbMetricTagCacheSizeForTests, ns as dbOperationsInFlight, Se as decimal, l as declareEnumRename, mn as decodeFieldValue, Cr as decodeRowsFromSchema, bn as decryptFieldsOnRead, Dc as defineMigration, Ct as defineMixin, ut as defineSeed, n as denseRank, gr as deriveSubjectGraph, dt as deriveTypeIdPrefix, Ao as derivedRowId, jo as derivedRowIdLength, Ne as describeAgedSoftDropSnapshots, An as describeDriverError, jn as describeRowBindings, Ol as describeTransferRun, rn as deserializeArraysOnRead, Ie as drainIdentifierWarnings, Ee as dropped, fn as encodeFieldValue, Tr as encodeRowForSchema, yn as encryptFieldsForWrite, _n as encryptedColumnsOf, Co as endLocalWrite, Zs as enforceBranchLimits, De as ensureTableRegistered, ha as eq, Zr as escapeLike, Ua as evaluatePredicate, Ze as except, za as exists, ws as expires, Ka as externalChangeEvent, wn as extractDbCause, sn as fieldBinding, rt as fireSchemaChangeSeeds, Ke as fireTenantCreateSeeds, Tc as formatIndexAuditIssue, _r as formatSubjectGraph, Ic as frameworkTables, it as generateId, Ge as generateSnowflake, h as geography, ae as geometry, ue as getEnumRenames, ar as getRelation, ir as getRelations, lc as getResidencyConfig, S as getTable, _a as gt, va as gte, Rr as hasEagerLoads, Ns as hybridSearch, E as id, xa as inSet, La as inSubquery, Yn as inferForeignKey, el as insertRow, _ as integer, Hc as interruptedReplaceRefusal, y as intersect, ke as interval, cn as isBoundCiphertext, zs as isBranchNamespace, Wn as isEmptyRelationsSpec, dn as isEncrypted, un as isFieldDecryptionError, Re as isFileMigration, On as isForeignKeyViolation, ct as isFrameworkOwnedLiveTable, Ds as isLocalFirst, Oc as isMigrationDefinition, ht as isMysqlFamily, Gs as isNeonConnection, Aa as isNotNull, ka as isNull, ol as isPrimaryKeyConflictError, kn as isQueryTimeout, hn as isRawEncoding, fc as isRegionServable, Gn as isRelationsSpec, We as isSeedDefinition, gt as isSoftDropSnapshotName, Xe as isSqliteFamily, Le as isStagingTableName, pe as isTableReactive, xs as isTransientContention, Fe as isView, x as json, Fa as jsonField, vt as jsonIndex, b as lag, de as lead, hl as listRetentionConflicts, _l as listRetentions, Es as localFirst, Os as localFirstTables, ya as lt, ba as lte, cs as makeEagerFallbackReporter, ic as makeNamespaceBranchExecutor, qn as many, Jn as manyToMany, Ae as materializeFields, f as max, He as migration, te as min, $c as missingConflictColumns, Qc as missingRequiredColumns, ze as mixin, ga as neq, Hs as nextBranchState, ll as normaliseTarget, Pa as not, Ba as notExists, Sa as notInSet, Ra as notInSubquery, me as numeric, is as observeDbOp, io as occurrenceWindowMs, Kn as one, Dr as oneCardinalityMessage, Na as or, v as orderClausesOf, he as paginateBy, jt as paginateById, eo as parseChangeKey, Eo as pendingAttributionCount, Ys as planBranch, Us as planBranchProvision, Ws as planBranchTeardown, Xs as planBranchTeardownFor, qs as planNeonBranchProvision, Js as planNeonBranchTeardown, Nt as planVersionedUpdate, et as pluginRef, r as pluginRefSpecOf, al as primaryKeyConflictError, Qs as provisionBranch, hc as provisionResidentTenant, Gr as qualifyTable, i as queryFor, Ot as queryForView, Pe as quoteIdent, il as raiseChangeListenerCeiling, Ce as rank, t as raw, Be as readableByColumns, bt as real, rs as recordDbOp, zo as recordsTable, ot as reference, Pn as refuseWrite, ua as registerCoreTables, rr as registerDiscoveredRelations, ho as registerPendingAttribution, nr as registerRelations, gl as registerRetention, e as registerTable, Mo as registerWriteRecorder, Un as relations, fa as requireActors, Ve as requireTable, pa as requireTenants, Qo as resetDbMetricTagCacheForTests, Me as resetSnowflake, pc as residentPlacement, $t as resolveActorSnapshot, Ks as resolveBranchMechanism, ss as resolveEagerFallbackWarnIntervalMs, wo as resolveEchoAttribution, g as resolveFullTextIndex, qe as resolveIdScheme, Ue as resolveMixinGraph, dc as resolveTenantHome, Wr as resolveTenantNamespace, Sl as retentionTtlMsFromEnv, xe as rowNumber, Ln as rowSchema, fs as runRetryingTransaction, ps as runStoreTransaction, oo as runWithWriteAttribution, Bo as runWriteRecorders, dl as sameDatabase, Ur as sanitizeIdentifierFragment, jl as scopeKeyOf, mt as selfReference, nn as serializeArraysForWrite, Ye as serverOnlyColumns, cc as setResidencyConfig, je as setSchemaChangeSeedHook, wt as setTenantCreateSeedHook, ls as settleTransactionExit, It as settleVersionedUpdate, tt as softDropSnapshotStamp, ja as spatialPredicate, Wc as stagingLeftoverReport, Uc as stagingLeftovers, Vc as stagingNamesOf, Bc as stagingStaleAfterMs, Kc as stampGeneratedId, qc as stampGeneratedIds, wa as startsWith, Fn as storeRefusalOf, Ms as streamTable, Te as sum, m as sumOver, Io as suspendWriteRecorders, Lo as suspendWriteRecordersEffect, yl as sweepRetention, w as table, $s as teardownBranch, C as text, T as timestamp, zt as timestampMs, Ft as timestampMsOrNull, ie as union, ft as unionAll, xt as unregisterTable, No as unregisterWriteRecorder, nl as updateManyRow, tl as upsertRow, kt as validateColumnName, ve as validateIndexName, sr as validateRegisteredRelations, $n as validateRelationConfig, s as validateTableName, Dt as validateTypeIdPrefix, _t as vector, nt as vectorDistanceToOpclass, Fs as vectorEmbedding, Rt as versionColumnOf, _e as view, o as viewSql, Ga as walkLeaves, lo as withCapturedAttribution, Ro as writeRecordersSuspended };
2700
+ export { lt as AUTO_FILLED_COLUMNS, an as BOUND_ENCRYPTED_PREFIX, Qc as BULK_INSERT_LIMITS, Y as BranchNameInvalid, Gs as BranchTransitionInvalid, Dl as CDC_OFFSETS_TABLE, oo as CHANGE_CLAIM_TTL_ENV, sl as CHANGE_LISTENER_CEILING, Qe as ColumnBuilder, Al as DATA_TRANSFERS_TABLE, st as DEFAULT_ACQUIRE_TIMEOUT_MS, so as DEFAULT_CHANGE_CLAIM_TTL_HOURS, ls as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, yt as DEFAULT_SOFT_DROP_RETENTION_DAYS, pr as DEFAULT_SUBJECT_GRAPH_DEPTH, rn as ENCRYPTED_PREFIX, Il as ENGINE, Ar as EagerCardinalityError, St as FILE_MIGRATION_PATTERN, at as FRAMEWORK_LIVE_TABLES, cn as FieldDecryptionError, jo as ID_COLUMN_MAX_LENGTH, Lt as INITIAL_VERSION, Ma as MATCHES_NO_ROWS, Tt as MAX_IDENTIFIER_LENGTH, bs as MSSQL_TRANSIENT_NUMBERS, vs as MYSQL_TRANSIENT_CODES, ao as OccurrenceCounter, ys as POSTGRES_TRANSIENT_STATES, Vc as REPLACE_IN_PROGRESS_TABLE, Nl as SCOPE_KEY_MAX_LENGTH, se as SELF_REFERENCE_TARGET, xs as SQLITE_TRANSIENT_CODES, Uc as STAGING_STALE_MINUTES, pt as STAGING_TABLE_PREFIX, Xt as SqlClient, Ss as TURSO_TRANSIENT_MESSAGE, Ns as TableStreamError, Wr as TenantNamespaceInvalid, Ur as TenantNamespaceUnresolved, uc as TenantRegionUnavailable, lc as TenantResidencyUnresolved, Ds as VOLTRO_EXPIRES_MIXIN_ID, ks as VOLTRO_LOCAL_FIRST_MIXIN_ID, Pt as VersionConflict, At as WARN_IDENTIFIER_LENGTH, Rc as _voltroApiKeysTable, Ol as _voltroCdcOffsetsTable, jl as _voltroDataTransfersTable, Ic as _voltroIdempotencyTable, Lc as _voltroKvTable, Fc as _voltroMigrationPlansTable, Nc as _voltroMigrationsTable, kl as _voltroMssqlCdcOffsetsTable, Hc as _voltroReplaceInProgressTable, zc as _voltroReplicaObservationsTable, Pc as _voltroSeedsTable, va as actorsTable, ic as admitBranch, Je as agedSoftDropSnapshots, be as allEnumRenames, ur as allRegisteredRelations, re as allRegisteredTables, Ia as and, ce as array, ka as arrayContains, ja as arrayHas, Aa as arrayOverlaps, Mr as attachEagerLoads, po as attributionFields, _o as attributionKey, wc as auditAllTableIndexes, Cc as auditTableIndexes, Et as avg, ye as avgOver, Eo as beginLocalWrite, fe as bigint, vc as bindResidentStore, p as boolean, Hs as branchNamespaceName, $c as bulkInsertLimitsFor, ne as bytes, xn as causeBranches, $a as changeDelete, no as changeDigest, Za as changeInsert, eo as changeSoftDelete, Qa as changeUpdate, tl as chunkRowsForInsert, bo as claimPendingAttribution, jn as classifyConstraintViolation, d as clearEnumRenames, ko as clearPendingAttribution, fr as clearRelationsRegistry, mc as clearResidencyConfig, Sl as clearRetentions, Oe as clearTableRegistry, Ro as clearWriteRecorders, W as coercePredicateForSqlite, Qr as coercePredicateValue, $r as coercePredicateValues, ua as coerceValueForSqlite, Ja as collectSubqueries, u as column, Bn as columnSchema, el as columnsPerRow, pi as compileEagerJson, L as compilePredicate, ei as compileRawFragment, fi as compileSelect, ro as composeChangeKey, Rs as computeEmbedding, ml as connectionIdentity, Da as contains, c as count, le as countDistinct, oe as crdtDoc, ge as crdtManagedColumns, Mt as crdtManagedColumnsOf, a as crdtText, fo as currentWriteAttribution, $e as databaseHandle, we as date, ee as dbEnum, rs as dbMetricTagCacheSizeForTests, os as dbOperationsInFlight, Se as decimal, l as declareEnumRename, pn as decodeFieldValue, Dr as decodeRowsFromSchema, yn as decryptFieldsOnRead, jc as defineMigration, Ct as defineMixin, ut as defineSeed, n as denseRank, br as deriveSubjectGraph, dt as deriveTypeIdPrefix, Po as derivedRowId, Fo as derivedRowIdLength, Ne as describeAgedSoftDropSnapshots, Pn as describeDriverError, Fn as describeRowBindings, Ml as describeTransferRun, nn as deserializeArraysOnRead, Ie as drainIdentifierWarnings, Ee as dropped, dn as encodeFieldValue, kr as encodeRowForSchema, vn as encryptFieldsForWrite, gn as encryptedColumnsOf, Do as endLocalWrite, tc as enforceBranchLimits, De as ensureTableRegistered, ya as eq, ti as escapeLike, qa as evaluatePredicate, Ze as except, Ua as exists, Os as expires, Xa as externalChangeEvent, wn as extractDbCause, on as fieldBinding, rt as fireSchemaChangeSeeds, Ke as fireTenantCreateSeeds, kc as formatIndexAuditIssue, xr as formatSubjectGraph, Bc as frameworkTables, it as generateId, Ge as generateSnowflake, h as geography, ae as geometry, ue as getEnumRenames, lr as getRelation, cr as getRelations, pc as getResidencyConfig, S as getTable, xa as gt, Sa as gte, Hr as hasEagerLoads, Ls as hybridSearch, E as id, Ta as inSet, Va as inSubquery, $n as inferForeignKey, il as insertRow, _ as integer, Kc as interruptedReplaceRefusal, y as intersect, ke as interval, sn as isBoundCiphertext, Us as isBranchNamespace, Jn as isEmptyRelationsSpec, un as isEncrypted, ln as isFieldDecryptionError, Re as isFileMigration, Mn as isForeignKeyViolation, ct as isFrameworkOwnedLiveTable, js as isLocalFirst, Mc as isMigrationDefinition, ht as isMysqlFamily, Ys as isNeonConnection, Pa as isNotNull, Na as isNull, ul as isPrimaryKeyConflictError, Nn as isQueryTimeout, mn as isRawEncoding, gc as isRegionServable, Yn as isRelationsSpec, We as isSeedDefinition, gt as isSoftDropSnapshotName, Xe as isSqliteFamily, Le as isStagingTableName, pe as isTableReactive, Ts as isTransientContention, Fe as isView, x as json, za as jsonField, vt as jsonIndex, b as lag, de as lead, yl as listRetentionConflicts, xl as listRetentions, As as localFirst, Ms as localFirstTables, Ca as lt, wa as lte, fs as makeEagerFallbackReporter, cc as makeNamespaceBranchExecutor, Zn as many, Qn as manyToMany, Ae as materializeFields, f as max, He as migration, te as min, rl as missingConflictColumns, nl as missingRequiredColumns, ze as mixin, ba as neq, Ks as nextBranchState, pl as normaliseTarget, Ra as not, Wa as notExists, Ea as notInSet, Ha as notInSubquery, me as numeric, cs as observeDbOp, co as occurrenceWindowMs, Xn as one, jr as oneCardinalityMessage, La as or, v as orderClausesOf, he as paginateBy, jt as paginateById, io as parseChangeKey, Ao as pendingAttributionCount, $s as planBranch, qs as planBranchProvision, Js as planBranchTeardown, ec as planBranchTeardownFor, Zs as planNeonBranchProvision, Qs as planNeonBranchTeardown, Nt as planVersionedUpdate, et as pluginRef, r as pluginRefSpecOf, ll as primaryKeyConflictError, nc as provisionBranch, yc as provisionResidentTenant, Yr as qualifyTable, i as queryFor, Ot as queryForView, Pe as quoteIdent, cl as raiseChangeListenerCeiling, Ce as rank, t as raw, Be as readableByColumns, bt as real, ss as recordDbOp, Uo as recordsTable, ot as reference, Rn as refuseWrite, ma as registerCoreTables, sr as registerDiscoveredRelations, yo as registerPendingAttribution, or as registerRelations, bl as registerRetention, e as registerTable, Io as registerWriteRecorder, qn as relations, ga as requireActors, Ve as requireTable, _a as requireTenants, ns as resetDbMetricTagCacheForTests, Me as resetSnowflake, _c as residentPlacement, Qt as resolveActorSnapshot, Xs as resolveBranchMechanism, ds as resolveEagerFallbackWarnIntervalMs, Oo as resolveEchoAttribution, g as resolveFullTextIndex, qe as resolveIdScheme, Ue as resolveMixinGraph, hc as resolveTenantHome, Jr as resolveTenantNamespace, El as retentionTtlMsFromEnv, xe as rowNumber, Vn as rowSchema, gs as runRetryingTransaction, _s as runStoreTransaction, uo as runWithWriteAttribution, Wo as runWriteRecorders, hl as sameDatabase, qr as sanitizeIdentifierFragment, Fl as scopeKeyOf, mt as selfReference, tn as serializeArraysForWrite, Ye as serverOnlyColumns, fc as setResidencyConfig, je as setSchemaChangeSeedHook, wt as setTenantCreateSeedHook, ps as settleTransactionExit, It as settleVersionedUpdate, tt as softDropSnapshotStamp, Fa as spatialPredicate, Jc as stagingLeftoverReport, qc as stagingLeftovers, Gc as stagingNamesOf, Wc as stagingStaleAfterMs, Xc as stampGeneratedId, Zc as stampGeneratedIds, Oa as startsWith, zn as storeRefusalOf, Is as streamTable, Te as sum, m as sumOver, Bo as suspendWriteRecorders, Vo as suspendWriteRecordersEffect, Cl as sweepRetention, w as table, rc as teardownBranch, C as text, T as timestamp, zt as timestampMs, Ft as timestampMsOrNull, ie as union, ft as unionAll, xt as unregisterTable, Lo as unregisterWriteRecorder, ol as updateManyRow, al as upsertRow, kt as validateColumnName, ve as validateIndexName, dr as validateRegisteredRelations, rr as validateRelationConfig, s as validateTableName, Dt as validateTypeIdPrefix, _t as vector, nt as vectorDistanceToOpclass, zs as vectorEmbedding, Rt as versionColumnOf, _e as view, o as viewSql, Ya as walkLeaves, Tn as wireSafeCause, mo as withCapturedAttribution, Ho as writeRecordersSuspended };