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