@voltro/database 0.84.0 → 0.85.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,11 +1,11 @@
1
- import { $ as e, $n as t, $r as n, $t as r, A as i, An as a, Ar as o, At as s, B as c, Bn as l, Br as u, Bt as d, C as f, Cn as p, Cr as m, Ct as h, D as g, Dn as _, Dr as v, Dt as ee, E as te, En as ne, Er as re, Et as ie, F as ae, Fn as oe, Fr as se, G as ce, Gn as le, Gr as y, H as ue, Hn as de, Hr as fe, Ht as pe, I as me, In as he, Ir as ge, It as _e, J as ve, Jn as ye, Jr as be, K as xe, Kn as Se, Kr as Ce, Kt as we, L as Te, Ln as Ee, Lr as De, Lt as Oe, M as ke, Mn as Ae, Mr as je, Mt as Me, N as Ne, Nn as Pe, Nr as Fe, Nt as Ie, O as Le, On as Re, Or as ze, Ot as Be, P as Ve, Pn as He, Pr as Ue, Pt as We, Q as Ge, Qn as Ke, Qr as b, R as qe, Rn as Je, Rr as Ye, Rt as Xe, S as Ze, Sn as Qe, Sr as $e, St as et, T as tt, Tn as nt, Tr as rt, Tt as it, U as at, Un as ot, Ur as st, Ut as ct, V as lt, Vn as x, Vr as ut, Vt as dt, W as ft, Wn as pt, Wr as mt, Wt as ht, X as gt, Xn as _t, Xr as vt, Y as yt, Yn as bt, Yr as xt, Z as St, Zn as Ct, Zr as wt, _ as Tt, _n as Et, _r as Dt, _t as Ot, a as kt, an as At, ar as jt, at as Mt, b as Nt, bn as Pt, br as Ft, bt as It, c as Lt, cn as Rt, cr as zt, ct as Bt, d as Vt, dn as Ht, dr as Ut, dt as Wt, ei as Gt, en as Kt, er as qt, et as Jt, f as Yt, fn as Xt, fr as Zt, ft as Qt, g as $t, gn as S, gr as en, gt as tn, h as nn, hn as rn, hr as an, ht as on, i as sn, in as cn, ir as C, it as ln, j as un, jn as dn, jr as fn, jt as pn, kn as mn, kr as hn, kt as gn, l as _n, ln as vn, lr as yn, lt as bn, m as xn, mn as Sn, mr as Cn, mt as wn, n as Tn, nn as En, nr as Dn, nt as On, o as kn, on as An, or as jn, ot as Mn, p as Nn, pn as Pn, pr as Fn, pt as In, q as Ln, qn as Rn, qr as zn, r as Bn, rn as Vn, rr as Hn, rt as Un, s as Wn, sn as Gn, sr as Kn, st as qn, t as Jn, tn as Yn, tr as Xn, tt as Zn, u as Qn, un as $n, ur as er, ut as tr, v as nr, vn as rr, vr as ir, vt as ar, w as or, wn as sr, wr as cr, wt as lr, x as ur, xn as dr, xr as fr, xt as pr, y as mr, yn as hr, yr as gr, yt as _r, z as vr, zn as yr, zr as br, zt as xr } from "./replaceInProgress-DUHl5JEz.js";
2
- import { a as Sr, i as Cr, n as wr, o as Tr, r as Er, s as Dr, t as Or } from "./wire-B28cPjEp.js";
3
- import { Cause as kr, Chunk as Ar, Data as jr, Effect as w, Exit as Mr, Metric as T, MetricBoundaries as Nr, Option as E, Schedule as Pr, Schema as D, Stream as Fr } from "effect";
1
+ import { $ as e, $n as t, $r as n, An as r, Ar as i, At as a, B as o, Bn as s, Br as c, Bt as l, C as u, Cn as d, Cr as f, Ct as p, D as m, Dn as h, Dr as g, Dt as _, E as v, En as ee, Er as te, Et as ne, F as re, Fn as ie, Fr as ae, Ft as oe, G as se, Gn as ce, Gr as le, Gt as ue, H as de, Hn as fe, Hr as pe, Ht as me, I as he, In as ge, Ir as _e, It as ve, J as ye, Jn as be, Jr as xe, Jt as Se, K as Ce, Kn as we, Kr as Te, Kt as Ee, L as De, Ln as Oe, Lr as ke, M as Ae, Mn as je, Mr as Me, Mt as Ne, N as Pe, Nn as Fe, Nr as Ie, Nt as Le, O as Re, On as ze, Or as Be, Ot as Ve, P as He, Pn as Ue, Pr as We, Pt as Ge, Q as Ke, Qn as qe, Qr as Je, R as Ye, Rn as Xe, Rr as Ze, Rt as Qe, S as $e, Sn as et, Sr as tt, St as nt, T as rt, Tn as it, Tr as at, Tt as y, U as ot, Un as b, Ur as st, Ut as ct, V as lt, Vn as ut, Vr as dt, Vt as ft, W as pt, Wn as mt, Wr as ht, Wt as gt, X as _t, Xn as vt, Xr as yt, Y as bt, Yn as xt, Yr as St, Z as Ct, Zn as wt, Zr as Tt, _ as Et, _n as Dt, _r as Ot, _t as kt, a as At, an as jt, ar as Mt, at as Nt, b as Pt, bn as Ft, br as It, bt as Lt, c as Rt, cn as zt, cr as Bt, ct as Vt, d as Ht, dn as Ut, dr as Wt, dt as Gt, ei as x, er as Kt, et as qt, f as Jt, fn as Yt, fr as Xt, ft as Zt, g as Qt, gn as $t, gr as en, gt as tn, h as nn, hn as rn, hr as an, ht as on, i as sn, in as cn, ir as ln, it as un, j as dn, jn as fn, jr as pn, jt as mn, k as hn, kn as gn, kr as _n, kt as vn, l as yn, ln as bn, lr as xn, lt as Sn, m as Cn, mn as wn, mr as Tn, mt as En, n as Dn, ni as On, nn as kn, nr as An, nt as jn, o as Mn, on as Nn, or as S, ot as Pn, p as Fn, pn as In, pr as Ln, pt as Rn, q as zn, qn as Bn, qr as C, r as Vn, rn as Hn, rr as Un, rt as Wn, s as Gn, sn as Kn, sr as qn, st as Jn, t as Yn, ti as w, tn as Xn, tr as Zn, tt as Qn, u as $n, un as er, ur as tr, ut as nr, v as rr, vn as T, vr as ir, vt as ar, w as or, wn as sr, wr as cr, wt as lr, x as ur, xn as dr, xr as fr, xt as pr, y as mr, yn as hr, yr as gr, yt as _r, z as vr, zn as yr, zr as br, zt as xr } from "./replaceInProgress-DC88Pdiy.js";
2
+ import { a as Sr, i as Cr, n as wr, o as Tr, r as Er, s as Dr, t as Or } from "./wire-CG2j7J3f.js";
3
+ import { Cause as kr, Context as Ar, Data as jr, Effect as E, Exit as Mr, Metric as D, Option as O, Schedule as Nr, Schema as k, Stream as Pr } from "effect";
4
+ import { types as Fr } from "node:util";
4
5
  import { createHash as Ir } from "node:crypto";
5
6
  import { AsyncLocalStorage as Lr } from "node:async_hooks";
6
- import { TransactionConnection as Rr } from "@effect/sql/SqlClient";
7
- import { ansi as O } from "@voltro/logger";
8
- import { SqlClient as zr } from "@effect/sql";
7
+ import { SqlClient as Rr, SqlClient as zr } from "effect/sql";
8
+ import { ansi as A } from "@voltro/logger";
9
9
  //#region src/actorSnapshot.ts
10
10
  var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n) => {
11
11
  if (t != null && t !== "") try {
@@ -102,17 +102,24 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
102
102
  }, ai = "id", oi = (e, t, n, r) => {
103
103
  if (!t) return e;
104
104
  let i = ii(t);
105
- if (i.length === 0) return e;
106
- let a = t.tableName ?? "?", o = r ?? e[ai], s = { ...e };
107
- for (let e of i) {
108
- let t = s[e];
105
+ return i.length === 0 ? e : ci(e, i, t.tableName ?? "?", n, r);
106
+ }, si = (e, t, n) => {
107
+ if (t === void 0 || e.length === 0) return e;
108
+ let r = ii(t);
109
+ if (r.length === 0) return e;
110
+ let i = t.tableName ?? "?";
111
+ return e.map((e) => ci(e, r, i, n));
112
+ }, ci = (e, t, n, r, i) => {
113
+ let a = i ?? e[ai], o = { ...e };
114
+ for (let e of t) {
115
+ let t = o[e];
109
116
  if (!(t == null || Qr(t))) {
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] = $r(n, t, Jr(a, e, o));
117
+ if (!r) throw Error(`column "${n}.${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`);
118
+ o[e] = $r(r, t, Jr(n, e, a));
112
119
  }
113
120
  }
114
- return s;
115
- }, si = (e, t, n, r) => {
121
+ return o;
122
+ }, li = (e, t, n, r) => {
116
123
  if (!t) return e;
117
124
  let i = ii(t);
118
125
  if (i.length === 0 || !n) return e;
@@ -145,77 +152,77 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
145
152
  }
146
153
  return s ?? e;
147
154
  });
148
- }, ci = Symbol.for("@voltro/database/storeRefusal"), li = (e) => {
149
- let t = C(e.detail);
150
- return Object.defineProperty(t, ci, {
155
+ }, ui = Symbol.for("@voltro/database/storeRefusal"), di = (e) => {
156
+ let t = S(e.detail);
157
+ return Object.defineProperty(t, ui, {
151
158
  value: e,
152
159
  enumerable: !1
153
160
  }), t;
154
- }, ui = (e) => {
155
- for (let t of jn(e)) {
161
+ }, fi = (e) => {
162
+ for (let t of Bt(e)) {
156
163
  let e = t;
157
164
  for (let t = 0; e != null && t < 8; t += 1) {
158
- let t = e[ci];
165
+ let t = e[ui];
159
166
  if (t !== void 0) return t;
160
167
  e = e.cause;
161
168
  }
162
169
  }
163
- }, di = (e) => {
170
+ }, pi = (e) => {
164
171
  let t = (() => {
165
172
  switch (e.type) {
166
- case "id": return e.idScheme?.kind === "numeric" ? D.Number : D.String;
173
+ case "id": return e.idScheme?.kind === "numeric" ? k.Number : k.String;
167
174
  case "text":
168
- case "enum": return D.String;
169
- case "reference": return e.referenceStorage === "numeric" ? D.Number : D.String;
175
+ case "enum": return k.String;
176
+ case "reference": return e.referenceStorage === "numeric" ? k.Number : k.String;
170
177
  case "integer":
171
178
  case "real":
172
- case "decimal": return D.Number;
173
- case "boolean": return D.Boolean;
179
+ case "decimal": return k.Number;
180
+ case "boolean": return k.Boolean;
174
181
  case "timestamp":
175
182
  case "date": return Or;
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;
183
+ case "bigint": return k.BigIntFromString;
184
+ case "bytes": return k.Uint8ArrayFromBase64;
185
+ case "array": return k.Array(k.Unknown);
186
+ case "interval": return k.String;
187
+ default: return k.Unknown;
181
188
  }
182
189
  })();
183
- return e.nullable === !0 ? D.NullOr(t) : t;
184
- }, fi = (e, t) => {
190
+ return e.nullable === !0 ? k.NullOr(t) : t;
191
+ }, mi = (e, t) => {
185
192
  let n = new Set(t?.omit ?? []), r = {};
186
- for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = di(i));
187
- return D.Struct(r);
188
- }, pi = (e) => typeof e == "function" ? e : () => e, mi = (e, t) => ({
193
+ for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = pi(i));
194
+ return k.Struct(r);
195
+ }, hi = (e) => typeof e == "function" ? e : () => e, gi = (e, t) => ({
189
196
  kind: "one",
190
- target: pi(e),
197
+ target: hi(e),
191
198
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
192
199
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
193
- }), hi = (e, t) => ({
200
+ }), _i = (e, t) => ({
194
201
  kind: "many",
195
- target: pi(e),
202
+ target: hi(e),
196
203
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
197
204
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
198
- }), gi = (e, t) => ({
205
+ }), vi = (e, t) => ({
199
206
  kind: "manyToMany",
200
- target: pi(e),
201
- through: pi(t.through),
207
+ target: hi(e),
208
+ through: hi(t.through),
202
209
  sourceKey: t.sourceKey,
203
210
  targetKey: t.targetKey
204
- }), _i = {
205
- one: mi,
206
- many: hi,
207
- manyToMany: gi
208
- }, vi = (e, t) => {
211
+ }), yi = {
212
+ one: gi,
213
+ many: _i,
214
+ manyToMany: vi
215
+ }, bi = (e, t) => {
209
216
  let n = typeof e == "function" ? e : () => e;
210
217
  return {
211
218
  source: n,
212
- relations: t(_i, n())
219
+ relations: t(yi, n())
213
220
  };
214
- }, yi = (e) => {
221
+ }, xi = (e) => {
215
222
  if (typeof e != "object" || !e) return !1;
216
223
  let t = e;
217
224
  return typeof t.source != "function" || typeof t.relations != "object" || t.relations === null ? !1 : Object.keys(t.relations).length === 0;
218
- }, bi = (e) => {
225
+ }, Si = (e) => {
219
226
  if (typeof e != "object" || !e) return !1;
220
227
  let t = e;
221
228
  if (typeof t.source != "function" || typeof t.relations != "object" || t.relations === null) return !1;
@@ -224,35 +231,35 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
224
231
  let t = e?.kind;
225
232
  return t === "one" || t === "many" || t === "manyToMany";
226
233
  });
227
- }, xi = mi, Si = hi, Ci = gi, k = (e, t, n) => {
234
+ }, Ci = gi, wi = _i, Ti = vi, Ei = (e, t, n) => {
228
235
  let r = [];
229
236
  for (let [n, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && r.push(n);
230
- if (r.length === 0) throw C(`relation '${n}': no reference() column on '${e.tableName}' points at '${t}'. Either add one or pass an explicit { foreignKey: '<column>' }.`);
231
- if (r.length > 1) throw C(`relation '${n}': multiple reference() columns on '${e.tableName}' point at '${t}' (${r.join(", ")}). Pass an explicit { foreignKey: '<column>' } to disambiguate.`);
237
+ if (r.length === 0) throw S(`relation '${n}': no reference() column on '${e.tableName}' points at '${t}'. Either add one or pass an explicit { foreignKey: '<column>' }.`);
238
+ if (r.length > 1) throw S(`relation '${n}': multiple reference() columns on '${e.tableName}' point at '${t}' (${r.join(", ")}). Pass an explicit { foreignKey: '<column>' } to disambiguate.`);
232
239
  return r[0];
233
- }, wi = (e) => Object.keys(e.fields), Ti = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Ei = (e) => {
234
- let t = wi(e);
240
+ }, Di = (e) => Object.keys(e.fields), Oi = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), ki = (e) => {
241
+ let t = Di(e);
235
242
  return t.length === 0 ? "<none>" : t.join(", ");
236
- }, Di = (e, t, n) => {
243
+ }, Ai = (e, t, n) => {
237
244
  let r = `relation '${t}' on '${e.tableName}'`, i = n.target();
238
245
  if (n.kind === "manyToMany") {
239
246
  let t = n.through();
240
- for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!Ti(t, o)) throw C(`${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}': ${Ei(t)}.`);
247
+ for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!Oi(t, o)) throw S(`${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}': ${ki(t)}.`);
241
248
  return;
242
249
  }
243
- if (n.sourceKey !== void 0 && n.foreignKey !== void 0) throw C(`${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.`);
244
- if (n.sourceKey !== void 0 && !Ti(e, n.sourceKey)) {
245
- let t = Ti(i, n.sourceKey);
246
- throw C(`${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}': ${Ei(e)}.`));
250
+ if (n.sourceKey !== void 0 && n.foreignKey !== void 0) throw S(`${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.`);
251
+ if (n.sourceKey !== void 0 && !Oi(e, n.sourceKey)) {
252
+ let t = Oi(i, n.sourceKey);
253
+ throw S(`${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}': ${ki(e)}.`));
247
254
  }
248
- if (n.foreignKey !== void 0 && !Ti(i, n.foreignKey)) {
249
- let t = Ti(e, n.foreignKey);
250
- throw C(`${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}': ${Ei(i)}.`));
255
+ if (n.foreignKey !== void 0 && !Oi(i, n.foreignKey)) {
256
+ let t = Oi(e, n.foreignKey);
257
+ throw S(`${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}': ${ki(i)}.`));
251
258
  }
252
- }, Oi = Symbol.for("@voltro/database/relationsRegistry"), ki = globalThis, A = ki[Oi] ?? (ki[Oi] = /* @__PURE__ */ new Map()), Ai = (e) => {
253
- let t = e.source(), n = A.get(t.tableName);
259
+ }, ji = Symbol.for("@voltro/database/relationsRegistry"), Mi = globalThis, j = Mi[ji] ?? (Mi[ji] = /* @__PURE__ */ new Map()), Ni = (e) => {
260
+ let t = e.source(), n = j.get(t.tableName);
254
261
  if (n === void 0) {
255
- A.set(t.tableName, new Map(Object.entries(e.relations)));
262
+ j.set(t.tableName, new Map(Object.entries(e.relations)));
256
263
  return;
257
264
  }
258
265
  for (let [r, i] of Object.entries(e.relations)) {
@@ -262,33 +269,33 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
262
269
  n.set(r, i);
263
270
  }
264
271
  }
265
- }, ji = (e) => {
272
+ }, Pi = (e) => {
266
273
  let t = 0;
267
- for (let n of Object.values(e)) bi(n) && (Ai(n), t += 1);
274
+ for (let n of Object.values(e)) Si(n) && (Ni(n), t += 1);
268
275
  return t;
269
- }, Mi = (e) => {
270
- let t = A.get(e);
276
+ }, Fi = (e) => {
277
+ let t = j.get(e);
271
278
  if (t !== void 0) return Object.fromEntries(t);
272
- }, Ni = (e, t) => A.get(e)?.get(t), Pi = () => {
279
+ }, Ii = (e, t) => j.get(e)?.get(t), Li = () => {
273
280
  let e = [];
274
- for (let [t, n] of A) for (let [r, i] of n) e.push({
281
+ for (let [t, n] of j) for (let [r, i] of n) e.push({
275
282
  source: t,
276
283
  name: r,
277
284
  relation: i
278
285
  });
279
286
  return e;
280
- }, Fi = () => {
281
- for (let [e, t] of A) {
282
- let n = a(e);
283
- if (n !== void 0) for (let [e, r] of t) Di(n, e, r);
284
- }
285
- }, Ii = () => {
286
- A.clear();
287
- }, Li = 4, Ri = (e) => Object.keys(e.fields), zi = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Bi = (e, t) => {
287
+ }, Ri = () => {
288
+ for (let [e, t] of j) {
289
+ let n = je(e);
290
+ if (n !== void 0) for (let [e, r] of t) Ai(n, e, r);
291
+ }
292
+ }, zi = () => {
293
+ j.clear();
294
+ }, Bi = 4, Vi = (e) => Object.keys(e.fields), Hi = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Ui = (e, t) => {
288
295
  let n = [];
289
296
  for (let [r, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && n.push(r);
290
297
  return n;
291
- }, Vi = (e, t) => {
298
+ }, Wi = (e, t) => {
292
299
  let n = [];
293
300
  for (let r of t) {
294
301
  if (r.source !== e) continue;
@@ -305,7 +312,7 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
305
312
  } catch {
306
313
  continue;
307
314
  }
308
- if (!zi(e, t.sourceKey)) continue;
315
+ if (!Hi(e, t.sourceKey)) continue;
309
316
  n.push({
310
317
  table: e.tableName,
311
318
  foreignKey: t.sourceKey,
@@ -314,8 +321,8 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
314
321
  continue;
315
322
  }
316
323
  if (t.sourceKey !== void 0) continue;
317
- let a = Bi(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
318
- if (o === void 0 || !zi(i, o)) continue;
324
+ let a = Ui(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
325
+ if (o === void 0 || !Hi(i, o)) continue;
319
326
  let s = i.fields[o];
320
327
  n.push({
321
328
  table: i.tableName,
@@ -324,9 +331,9 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
324
331
  });
325
332
  }
326
333
  return n;
327
- }, Hi = (e, t) => {
334
+ }, Gi = (e, t) => {
328
335
  let n = [];
329
- for (let r of t) if (r.tableName !== e) for (let t of Bi(r, e)) {
336
+ for (let r of t) if (r.tableName !== e) for (let t of Ui(r, e)) {
330
337
  let e = r.fields[t];
331
338
  n.push({
332
339
  table: r.tableName,
@@ -335,8 +342,53 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
335
342
  });
336
343
  }
337
344
  return n;
338
- }, Ui = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, Wi = (e) => {
339
- let t = e.tables ?? _(), n = e.relations ?? Pi(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
345
+ }, Ki = (e) => {
346
+ if (Fr.isProxy(e)) return !1;
347
+ let t = Object.getPrototypeOf(e);
348
+ return (t === Object.prototype || t === null) && Reflect.ownKeys(e).every((t) => "value" in Object.getOwnPropertyDescriptor(e, t));
349
+ }, qi = (e) => !Fr.isProxy(e) && Object.getPrototypeOf(e) === Array.prototype && Reflect.ownKeys(e).every((t) => typeof t == "string" && (t === "length" || /^(0|[1-9][0-9]*)$/.test(t)) && "value" in Object.getOwnPropertyDescriptor(e, t)), Ji = (e) => {
350
+ if (e.length < 32 || !qi(e) || !e.every((e) => Ki(e) && Ki(e.fields) && Object.values(e.fields).every(Ki))) return (t) => Gi(t, e);
351
+ let t = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Map();
352
+ e.forEach((e, t) => {
353
+ n.has(e) || n.set(e, t);
354
+ });
355
+ let r, i = !1, a = (e) => {
356
+ for (let r of e) {
357
+ let e = n.get(r);
358
+ for (let [n, i] of Object.entries(r.fields)) {
359
+ if (i.type !== "reference") continue;
360
+ let a = i.references?.()?.tableName;
361
+ if (a === void 0) continue;
362
+ let o = {
363
+ order: e,
364
+ hop: {
365
+ table: r.tableName,
366
+ foreignKey: n,
367
+ parentKey: i.referenceColumn ?? "id"
368
+ }
369
+ }, s = t.get(a);
370
+ s ? s.push(o) : t.set(a, [o]);
371
+ }
372
+ }
373
+ };
374
+ return (n) => {
375
+ if (!i) r = e.filter((e) => e.tableName === n), a(e.filter((e) => e.tableName !== n)), i = !0;
376
+ else if (r?.some((e) => e.tableName !== n)) {
377
+ a(r), r = void 0;
378
+ for (let e of t.values()) e.sort((e, t) => e.order - t.order);
379
+ }
380
+ return (t.get(n) ?? []).filter((e) => e.hop.table !== n).map((e) => e.hop);
381
+ };
382
+ }, Yi = (e) => {
383
+ if (e.length < 32 || !qi(e) || !e.every(Ki)) return (t) => Wi(t, e);
384
+ let t = /* @__PURE__ */ new Map();
385
+ for (let n of e) {
386
+ let e = t.get(n.source);
387
+ e ? e.push(n) : t.set(n.source, [n]);
388
+ }
389
+ return (e) => Wi(e, t.get(e) ?? []);
390
+ }, Xi = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, Zi = (e) => {
391
+ let t = e.tables ?? gn(), n = e.relations ?? Li(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
340
392
  if (!a.has(e.subjectTable)) return {
341
393
  subjectTable: e.subjectTable,
342
394
  paths: [],
@@ -351,55 +403,55 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
351
403
  hops: [],
352
404
  depth: 0,
353
405
  via: "relation"
354
- }, c = [s], l = /* @__PURE__ */ new Set([Ui(s)]), u = /* @__PURE__ */ new Set(), d = [s];
406
+ }, c = Ji(t), l = Yi(n), u = [s], d = /* @__PURE__ */ new Set([Xi(s)]), f = /* @__PURE__ */ new Set(), p = [s];
355
407
  for (let e = 1; e <= r; e++) {
356
- let r = [];
357
- for (let a of d) {
358
- let s = Vi(a.table, n), d = Hi(a.table, t), f = [...s.map((e) => [e, "relation"]), ...d.map((e) => [e, "reference"])];
359
- for (let [t, n] of f) {
360
- if (i.has(t.table)) {
408
+ let t = [];
409
+ for (let n of p) {
410
+ let r = l(n.table), a = c(n.table), s = [...r.map((e) => [e, "relation"]), ...a.map((e) => [e, "reference"])];
411
+ for (let [r, a] of s) {
412
+ if (i.has(r.table)) {
361
413
  o.push({
362
414
  kind: "excluded",
363
- table: t.table,
364
- detail: `excluded by configuration (reached from '${a.table}')`
415
+ table: r.table,
416
+ detail: `excluded by configuration (reached from '${n.table}')`
365
417
  });
366
418
  continue;
367
419
  }
368
- let s = `${t.table}\u0000${t.foreignKey}`;
369
- if (u.has(s)) continue;
370
- u.add(s);
371
- let d = {
372
- table: t.table,
373
- hops: [...a.hops, t],
420
+ let s = `${r.table}\u0000${r.foreignKey}`;
421
+ if (f.has(s)) continue;
422
+ f.add(s);
423
+ let c = {
424
+ table: r.table,
425
+ hops: [...n.hops, r],
374
426
  depth: e,
375
- via: n
376
- }, f = Ui(d);
377
- l.has(f) || (l.add(f), c.push(d), r.push(d));
427
+ via: a
428
+ }, l = Xi(c);
429
+ d.has(l) || (d.add(l), u.push(c), t.push(c));
378
430
  }
379
431
  }
380
- if (r.length === 0) {
381
- d = [];
432
+ if (t.length === 0) {
433
+ p = [];
382
434
  break;
383
435
  }
384
- d = r;
436
+ p = t;
385
437
  }
386
- for (let e of d) (Vi(e.table, n).length > 0 || Hi(e.table, t).length > 0) && o.push({
438
+ for (let e of p) (l(e.table).length > 0 || c(e.table).length > 0) && o.push({
387
439
  kind: "depth-truncated",
388
440
  table: e.table,
389
441
  detail: `stopped at maxDepth ${r}; tables linked FROM '${e.table}' were not explored`
390
442
  });
391
- let f = new Set(c.map((e) => e.table));
392
- for (let n of t) f.has(n.tableName) || i.has(n.tableName) || o.push({
443
+ let m = new Set(u.map((e) => e.table));
444
+ for (let n of t) m.has(n.tableName) || i.has(n.tableName) || o.push({
393
445
  kind: "unreachable",
394
446
  table: n.tableName,
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: ${Ri(n).join(", ")}`
447
+ 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: ${Vi(n).join(", ")}`
396
448
  });
397
449
  return {
398
450
  subjectTable: e.subjectTable,
399
- paths: c,
451
+ paths: u,
400
452
  limitations: o
401
453
  };
402
- }, Gi = (e) => {
454
+ }, Qi = (e) => {
403
455
  let t = [`subject graph · ${e.subjectTable} · ${e.paths.length} table(s) reachable`];
404
456
  for (let n of e.paths) {
405
457
  let r = n.hops.length === 0 ? `${e.subjectTable} (the subject row itself)` : [e.subjectTable, ...n.hops.map((e) => `${e.table}.${e.foreignKey}`)].join(" → ");
@@ -407,12 +459,12 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
407
459
  }
408
460
  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");
409
461
  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");
410
- }, Ki = (e) => Object.fromEntries(Object.entries(e.updateValues ?? {}).filter(([t, n]) => {
462
+ }, $i = (e) => Object.fromEntries(Object.entries(e.updateValues ?? {}).filter(([t, n]) => {
411
463
  if (n === void 0) return !1;
412
- if (t === "id" || e.conflictColumns.includes(t)) throw C(`upsert: updateValues cannot rewrite row identity column '${t}'`);
464
+ if (t === "id" || e.conflictColumns.includes(t)) throw S(`upsert: updateValues cannot rewrite row identity column '${t}'`);
413
465
  return !0;
414
- })), qi = (e, t, n) => {
415
- let r = Ki(n);
466
+ })), ea = (e, t, n) => {
467
+ let r = $i(n);
416
468
  if (typeof n.update == "function") return {
417
469
  ...n.update(t),
418
470
  ...r
@@ -422,21 +474,21 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
422
474
  ...Object.fromEntries(i.filter((t) => t in e).map((t) => [t, e[t]])),
423
475
  ...r
424
476
  };
425
- }, Ji = (e) => typeof e == "string" ? [["id", e]] : Object.entries(e).map(([e, t]) => [e, t]), Yi = (e) => {
477
+ }, ta = (e) => typeof e == "string" ? [["id", e]] : Object.entries(e).map(([e, t]) => [e, t]), na = (e) => {
426
478
  if (typeof e == "string") return e;
427
479
  let t = Object.entries(e);
428
480
  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");
429
- }, Xi = (e) => typeof e != "string", Zi = (e, t, n) => {
430
- let r = new Set(Ji(e).map(([e]) => e)), i = t.split(".")[0];
481
+ }, ra = (e) => typeof e != "string", ia = (e, t, n) => {
482
+ let r = new Set(ta(e).map(([e]) => e)), i = t.split(".")[0];
431
483
  return Object.fromEntries(Object.entries(n ?? {}).filter(([e, t]) => {
432
484
  if (t === void 0) return !1;
433
- if (r.has(e) || e === i) throw C(`patchJson: additionalPatch cannot rewrite the primary key or patched JSON column '${e}'`);
485
+ if (r.has(e) || e === i) throw S(`patchJson: additionalPatch cannot rewrite the primary key or patched JSON column '${e}'`);
434
486
  return !0;
435
487
  }));
436
- }, Qi = (e) => typeof e == "object" && !!e && !Array.isArray(e), $i = (e) => JSON.parse(JSON.stringify(e ?? null)), ea = (e, t, n) => {
437
- let [r, ...i] = t.split("."), a = $i(n), o = e[r], s = (e, t) => {
488
+ }, M = (e) => typeof e == "object" && !!e && !Array.isArray(e), aa = (e) => JSON.parse(JSON.stringify(e ?? null)), oa = (e, t, n) => {
489
+ let [r, ...i] = t.split("."), a = aa(n), o = e[r], s = (e, t) => {
438
490
  if (t === i.length) return a;
439
- let n = Qi(e) ? e : {}, r = i[t], o = Object.hasOwn(n, r) ? n[r] : void 0;
491
+ let n = M(e) ? e : {}, r = i[t], o = Object.hasOwn(n, r) ? n[r] : void 0;
440
492
  return {
441
493
  ...n,
442
494
  [r]: s(o, t + 1)
@@ -444,14 +496,14 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
444
496
  };
445
497
  return {
446
498
  ...e,
447
- [r]: i.length === 0 ? Qi(o) && Qi(a) ? {
499
+ [r]: i.length === 0 ? M(o) && M(a) ? {
448
500
  ...o,
449
501
  ...a
450
502
  } : a : s(o, 0)
451
503
  };
452
- }, ta = (e, t, n, r, i) => {
453
- let [a, ...o] = n.split("."), s = i ?? e`${e(a)}`, c = $i(r), l = (e) => /["\\\u0000-\u001f]/.test(e);
454
- if ((t === "sqlite" || t === "turso") && (o.some(l) || o.length === 0 && Qi(c) && Object.keys(c).some(l))) {
504
+ }, sa = (e, t, n, r, i) => {
505
+ let [a, ...o] = n.split("."), s = i ?? e`${e(a)}`, c = aa(r), l = (e) => /["\\\u0000-\u001f]/.test(e);
506
+ if ((t === "sqlite" || t === "turso") && (o.some(l) || o.length === 0 && M(c) && Object.keys(c).some(l))) {
455
507
  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`}
456
508
  THEN json_extract('"' || replace(${t}.key, '"', ${String.raw`\"`}) || '"', '$')
457
509
  ELSE ${t}.key END`, r = (r) => {
@@ -481,7 +533,7 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
481
533
  }
482
534
  return e`${e(a)} = ${l}`;
483
535
  }
484
- let u = (e) => "$" + e.map((e) => `.${JSON.stringify(e)}`).join(""), d = (t) => e`ARRAY[${e.csv(t.map((t) => e`${t}`))}]::text[]`, f = (n) => n.length === 0 ? s : t === "postgres" ? e`${s} #> ${d(n)}` : t === "mssql" ? e`JSON_QUERY(${s}, ${u(n)})` : t === "mysql" || t === "mariadb" ? e`JSON_EXTRACT(${s}, ${u(n)})` : e`json_extract(${s}, ${u(n)})`, p = (n) => t === "postgres" ? e`jsonb_typeof(${f(n)}) = 'object'` : t === "mssql" ? e`LEFT(LTRIM(${f(n)}), 1) = '{'` : t === "mysql" || t === "mariadb" ? e`JSON_TYPE(${f(n)}) = 'OBJECT'` : e`json_type(${s}, ${u(n)}) = 'object'`, m = t === "postgres" ? e`'{}'::jsonb` : e`'{}'`, h = (t) => {
536
+ let u = (e) => "$" + e.map((e) => `.${JSON.stringify(e)}`).join(""), d = (t) => e`ARRAY[${e.join(", ", !1)(t.map((t) => e`${t}`))}]::text[]`, f = (n) => n.length === 0 ? s : t === "postgres" ? e`${s} #> ${d(n)}` : t === "mssql" ? e`JSON_QUERY(${s}, ${u(n)})` : t === "mysql" || t === "mariadb" ? e`JSON_EXTRACT(${s}, ${u(n)})` : e`json_extract(${s}, ${u(n)})`, p = (n) => t === "postgres" ? e`jsonb_typeof(${f(n)}) = 'object'` : t === "mssql" ? e`LEFT(LTRIM(${f(n)}), 1) = '{'` : t === "mysql" || t === "mariadb" ? e`JSON_TYPE(${f(n)}) = 'OBJECT'` : e`json_type(${s}, ${u(n)}) = 'object'`, m = t === "postgres" ? e`'{}'::jsonb` : e`'{}'`, h = (t) => {
485
537
  let n = Array.from({ length: t.length + 1 }, (e, n) => p(t.slice(0, n)));
486
538
  return e`CASE WHEN ${e.and(n)} THEN ${f(t)} ELSE ${m} END`;
487
539
  }, g = (n) => {
@@ -493,7 +545,7 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
493
545
  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}))`;
494
546
  }, v;
495
547
  if (o.length === 0) {
496
- if (!Qi(c)) v = g(c);
548
+ if (!M(c)) v = g(c);
497
549
  else {
498
550
  v = h([]);
499
551
  for (let [e, t] of Object.entries(c)) v = _(v, [e], g(t), t);
@@ -507,55 +559,55 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
507
559
  v = _(v, o, g(c), c);
508
560
  }
509
561
  return e`${e(a)} = ${v}`;
510
- }, na = class extends Error {
562
+ }, ca = class extends Error {
511
563
  _tag = "EagerCardinalityError";
512
564
  constructor(e) {
513
565
  super(e), this.name = "EagerCardinalityError";
514
566
  }
515
- }, ra = (e) => {
567
+ }, la = (e) => {
516
568
  let { relationName: t, sourceTableName: n, targetTableName: r, foreignKey: i, sourceKey: a } = e, o = r === n;
517
569
  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.");
518
- }, ia = async (e, t, n, r) => {
570
+ }, ua = async (e, t, n, r) => {
519
571
  if (e.length === 0) return e;
520
- let i = Mi(n.tableName);
521
- if (i === void 0) throw C(`cannot eager-load on '${n.tableName}': no relations registered. Did you forget to declare \`relations(${n.tableName}, ...)\` or import the file that does?`);
572
+ let i = Fi(n.tableName);
573
+ if (i === void 0) throw S(`cannot eager-load on '${n.tableName}': no relations registered. Did you forget to declare \`relations(${n.tableName}, ...)\` or import the file that does?`);
522
574
  let a = e.map((e) => ({ ...e }));
523
575
  for (let [e, o] of Object.entries(t)) {
524
576
  let t = i[e];
525
577
  if (t === void 0) {
526
578
  let t = Object.keys(i).join(", ") || "<none>";
527
- throw C(`unknown relation '${e}' on '${n.tableName}'. Registered relations: ${t}.`);
579
+ throw S(`unknown relation '${e}' on '${n.tableName}'. Registered relations: ${t}.`);
528
580
  }
529
- Di(n, e, t), await aa(a, e, t, o === !0 ? {} : o, n, r);
581
+ Ai(n, e, t), await da(a, e, t, o === !0 ? {} : o, n, r);
530
582
  }
531
583
  return a;
532
- }, aa = async (e, t, n, r, i, a) => {
584
+ }, da = async (e, t, n, r, i, a) => {
533
585
  switch (n.kind) {
534
586
  case "one":
535
- await oa(e, t, n, r, i, a);
587
+ await fa(e, t, n, r, i, a);
536
588
  return;
537
589
  case "many":
538
- await sa(e, t, n, r, i, a);
590
+ await pa(e, t, n, r, i, a);
539
591
  return;
540
592
  case "manyToMany":
541
- await la(e, t, n, r, i, a);
593
+ await ha(e, t, n, r, i, a);
542
594
  return;
543
595
  }
544
- }, oa = async (e, t, n, r, i, a) => {
545
- let o = n.target(), s = n.sourceKey ?? ua(i, o.tableName);
596
+ }, fa = async (e, t, n, r, i, a) => {
597
+ let o = n.target(), s = n.sourceKey ?? ga(i, o.tableName);
546
598
  if (s !== void 0) {
547
- let n = M(e, s), c = n.length === 0 ? [] : await da(o, "id", n, r, a), l = new Map(c.map((e) => [j(o, "id", e.id), e]));
599
+ let n = P(e, s), c = n.length === 0 ? [] : await _a(o, "id", n, r, a), l = new Map(c.map((e) => [N(o, "id", e.id), e]));
548
600
  for (let n of e) {
549
- let e = j(i, s, n[s]);
601
+ let e = N(i, s, n[s]);
550
602
  n[t] = e == null ? null : l.get(e) ?? null;
551
603
  }
552
- await fa(c, r.with, o, a);
604
+ await va(c, r.with, o, a);
553
605
  return;
554
606
  }
555
- let c = n.foreignKey ?? k(o, i.tableName, t), l = n.sourceKey ?? "id", u = M(e, l), d = u.length === 0 ? [] : await da(o, c, u, r, a), f = /* @__PURE__ */ new Map();
607
+ let c = n.foreignKey ?? Ei(o, i.tableName, t), l = n.sourceKey ?? "id", u = P(e, l), d = u.length === 0 ? [] : await _a(o, c, u, r, a), f = /* @__PURE__ */ new Map();
556
608
  for (let e of d) {
557
- let n = j(o, c, e[c]);
558
- if (f.has(n)) throw new na(ra({
609
+ let n = N(o, c, e[c]);
610
+ if (f.has(n)) throw new ca(la({
559
611
  relationName: t,
560
612
  sourceTableName: i.tableName,
561
613
  targetTableName: o.tableName,
@@ -565,33 +617,38 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
565
617
  f.set(n, e);
566
618
  }
567
619
  for (let n of e) {
568
- let e = j(i, l, n[l]);
620
+ let e = N(i, l, n[l]);
569
621
  n[t] = e == null ? null : f.get(e) ?? null;
570
622
  }
571
- await fa(d, r.with, o, a);
572
- }, sa = 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 = M(e, c), u = ca(r), d = l.length === 0 ? [] : await da(o, s, l, u, a), f = /* @__PURE__ */ new Map();
623
+ await va(d, r.with, o, a);
624
+ }, pa = async (e, t, n, r, i, a) => {
625
+ let o = n.target(), s = n.foreignKey ?? Ei(o, i.tableName, t), c = n.sourceKey ?? "id", l = P(e, c), u = ma(r), d = l.length === 0 ? [] : await _a(o, s, l, u, a), f = /* @__PURE__ */ new Map(), p = r.offset ?? 0, m = Number.isSafeInteger(p) && p >= 0 && (r.limit === void 0 || Number.isSafeInteger(r.limit) && r.limit >= 0), h = /* @__PURE__ */ new Map();
574
626
  for (let e of d) {
575
- let t = j(o, s, e[s]), n = f.get(t);
627
+ let t = N(o, s, e[s]);
628
+ if (m) {
629
+ let e = h.get(t) ?? 0;
630
+ if (h.set(t, e + 1), e < p || r.limit !== void 0 && e - p >= r.limit) continue;
631
+ }
632
+ let n = f.get(t);
576
633
  n ? n.push(e) : f.set(t, [e]);
577
634
  }
578
- if (r.limit !== void 0 || r.offset !== void 0) {
579
- let e = r.offset ?? 0, t = r.limit;
580
- for (let [n, r] of f) {
581
- let i = t === void 0 ? r.slice(e) : r.slice(e, e + t);
582
- f.set(n, i);
635
+ if (!m && (r.limit !== void 0 || r.offset !== void 0)) {
636
+ let e = r.limit;
637
+ for (let [t, n] of f) {
638
+ let r = e === void 0 ? n.slice(p) : n.slice(p, p + e);
639
+ f.set(t, r);
583
640
  }
584
641
  }
585
642
  for (let n of e) {
586
- let e = j(i, c, n[c]);
643
+ let e = N(i, c, n[c]);
587
644
  n[t] = f.get(e) ?? [];
588
645
  }
589
- await fa(d, r.with, o, a);
590
- }, ca = (e) => {
646
+ r.with !== void 0 && await va([...f.values()].flat(), r.with, o, a);
647
+ }, ma = (e) => {
591
648
  let { limit: t, offset: n, ...r } = e;
592
649
  return r;
593
- }, la = async (e, t, n, r, i, a) => {
594
- let o = n.target(), s = n.through(), c = M(e, "id");
650
+ }, ha = async (e, t, n, r, i, a) => {
651
+ let o = n.target(), s = n.through(), c = P(e, "id");
595
652
  if (c.length === 0) {
596
653
  for (let n of e) n[t] = [];
597
654
  return;
@@ -612,11 +669,11 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
612
669
  for (let n of e) n[t] = [];
613
670
  return;
614
671
  }
615
- let f = await da(o, "id", M(d, n.targetKey), r, a), p = new Map(f.map((e) => [j(o, "id", e.id), e]));
616
- await fa(f, r.with, o, a);
617
- let m = r.junction === void 0 ? void 0 : r.junction === !0 ? y(s) : r.junction, h = /* @__PURE__ */ new Map();
672
+ let f = await _a(o, "id", P(d, n.targetKey), r, a), p = new Map(f.map((e) => [N(o, "id", e.id), e]));
673
+ await va(f, r.with, o, a);
674
+ let m = r.junction === void 0 ? void 0 : r.junction === !0 ? C(s) : r.junction, h = /* @__PURE__ */ new Map();
618
675
  for (let e of d) {
619
- let t = j(s, n.sourceKey, e[n.sourceKey]), r = j(s, n.targetKey, e[n.targetKey]), i = p.get(r);
676
+ let t = N(s, n.sourceKey, e[n.sourceKey]), r = N(s, n.targetKey, e[n.targetKey]), i = p.get(r);
620
677
  if (i === void 0) continue;
621
678
  let a = m === void 0 ? i : {
622
679
  ...i,
@@ -624,17 +681,17 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
624
681
  }, o = h.get(t);
625
682
  o ? o.push(a) : h.set(t, [a]);
626
683
  }
627
- for (let n of e) n[t] = h.get(j(i, "id", n.id)) ?? [];
628
- }, j = (e, t, n) => e.fields[t]?.type === "decimal" ? d(n) ?? n : n, ua = (e, t) => {
684
+ for (let n of e) n[t] = h.get(N(i, "id", n.id)) ?? [];
685
+ }, N = (e, t, n) => e.fields[t]?.type === "decimal" ? me(n) ?? n : n, ga = (e, t) => {
629
686
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
630
- }, M = (e, t) => {
687
+ }, P = (e, t) => {
631
688
  let n = /* @__PURE__ */ new Set();
632
689
  for (let r of e) {
633
690
  let e = r[t];
634
691
  e != null && n.add(e);
635
692
  }
636
693
  return [...n];
637
- }, da = (e, t, n, r, i) => {
694
+ }, _a = (e, t, n, r, i) => {
638
695
  let a = {
639
696
  column: t,
640
697
  op: "in",
@@ -648,37 +705,37 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
648
705
  skip: r.offset,
649
706
  projection: void 0
650
707
  });
651
- }, fa = async (e, t, n, r) => {
652
- t !== void 0 && e.length !== 0 && (await ia(e, t, n, r)).forEach((t, n) => {
708
+ }, va = async (e, t, n, r) => {
709
+ t !== void 0 && e.length !== 0 && (await ua(e, t, n, r)).forEach((t, n) => {
653
710
  let r = e[n];
654
711
  for (let [e, n] of Object.entries(t)) e in r || (r[e] = n);
655
712
  });
656
- }, pa = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, ma = (e, t, n) => {
713
+ }, ya = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, ba = (e, t, n) => {
657
714
  if (e.eager === void 0) return null;
658
- let r = _a(e.table, e.eager, e.sourceTable);
659
- if (r === null || n === "sqlite" && ha(r)) return null;
660
- let i = wa(n, e, r, Ca(t, n));
715
+ let r = Ca(e.table, e.eager, e.sourceTable);
716
+ if (r === null || n === "sqlite" && xa(r)) return null;
717
+ let i = Aa(n, e, r, ka(t, n));
661
718
  return i === null ? null : {
662
719
  fragment: i,
663
- decode: Da(r, n)
720
+ decode: Na(r, n)
664
721
  };
665
- }, ha = (e) => Object.values(e.table.fields).some(we) || e.children.some((e) => ha({
722
+ }, xa = (e) => Object.values(e.table.fields).some(Se) || e.children.some((e) => xa({
666
723
  table: e.target,
667
724
  children: e.children
668
- }) || e.relation.kind === "manyToMany" && Object.values(e.relation.through().fields).some(we)), N = (e) => e.relation.kind === "one" && e.fkSide === "target", ga = (e) => ({
725
+ }) || e.relation.kind === "manyToMany" && Object.values(e.relation.through().fields).some(Se)), F = (e) => e.relation.kind === "one" && e.fkSide === "target", Sa = (e) => ({
669
726
  ...e,
670
727
  branch: {
671
728
  ...e.branch,
672
729
  limit: 2
673
730
  }
674
- }), _a = (e, t, n) => {
675
- let r = n ?? Pe(e), i = Mi(e);
731
+ }), Ca = (e, t, n) => {
732
+ let r = n ?? ie(e), i = Fi(e);
676
733
  if (i === void 0) return null;
677
734
  let a = [];
678
735
  for (let [e, n] of Object.entries(t)) {
679
736
  let t = i[e];
680
737
  if (t === void 0) return null;
681
- let o = va(e, t, r, n === !0 ? {} : n);
738
+ let o = wa(e, t, r, n === !0 ? {} : n);
682
739
  if (o === null) return null;
683
740
  a.push(o);
684
741
  }
@@ -686,30 +743,30 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
686
743
  table: r,
687
744
  children: a
688
745
  };
689
- }, va = (e, t, n, r) => {
746
+ }, wa = (e, t, n, r) => {
690
747
  let i = t.target(), a = (t.kind === "manyToMany" ? void 0 : t.sourceKey) ?? "id", o, s;
691
748
  if (t.kind === "manyToMany") o = t.targetKey, s = "target";
692
749
  else if (t.kind === "one") {
693
- let r = t.sourceKey ?? Sa(n, i.tableName);
750
+ let r = t.sourceKey ?? Oa(n, i.tableName);
694
751
  if (r !== void 0) o = r, s = "source";
695
752
  else try {
696
- o = t.foreignKey ?? k(i, n.tableName, e), s = "target";
753
+ o = t.foreignKey ?? Ei(i, n.tableName, e), s = "target";
697
754
  } catch {
698
755
  return null;
699
756
  }
700
757
  } else try {
701
- o = t.foreignKey ?? k(i, n.tableName, e), s = "target";
758
+ o = t.foreignKey ?? Ei(i, n.tableName, e), s = "target";
702
759
  } catch {
703
760
  return null;
704
761
  }
705
762
  let c = r.with === void 0 ? [] : (() => {
706
- let e = Mi(i.tableName);
763
+ let e = Fi(i.tableName);
707
764
  if (e === void 0 && Object.keys(r.with).length > 0) return null;
708
765
  let t = [];
709
766
  for (let [n, a] of Object.entries(r.with)) {
710
767
  let r = e?.[n];
711
768
  if (r === void 0) return null;
712
- let o = va(n, r, i, a === !0 ? {} : a);
769
+ let o = wa(n, r, i, a === !0 ? {} : a);
713
770
  if (o === null) return null;
714
771
  t.push(o);
715
772
  }
@@ -725,49 +782,49 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
725
782
  fkSide: s,
726
783
  branch: r,
727
784
  children: c,
728
- junction: ya(t, r)
785
+ junction: Ta(t, r)
729
786
  };
730
- }, ya = (e, t) => {
787
+ }, Ta = (e, t) => {
731
788
  if (e.kind !== "manyToMany" || t.junction === void 0) return;
732
- let n = e.through(), r = y(n), i = t.junction === !0 ? r : t.junction, a = i.filter((e) => r.includes(e));
789
+ let n = e.through(), r = C(n), i = t.junction === !0 ? r : t.junction, a = t.junction === !0 ? void 0 : new Set(r), o = a === void 0 ? r : i.filter((e) => a.has(e));
733
790
  return {
734
791
  through: n,
735
792
  requested: i,
736
- present: a,
737
- dateColumns: a.filter((e) => {
793
+ present: o,
794
+ dateColumns: o.filter((e) => {
738
795
  let t = n.fields[e];
739
796
  return t !== void 0 && (t.type === "timestamp" || t.type === "date");
740
797
  })
741
798
  };
742
- }, ba = (e) => `__j_${e}`, xa = "__j", Sa = (e, t) => {
799
+ }, Ea = (e) => `__j_${e}`, Da = "__j", Oa = (e, t) => {
743
800
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
744
- }, Ca = (e, t) => {
801
+ }, ka = (e, t) => {
745
802
  let n = 0;
746
803
  return {
747
804
  sql: e,
748
805
  dialect: t,
749
806
  nextAlias: () => `__a${n++}`
750
807
  };
751
- }, wa = (e, t, n, r) => {
808
+ }, Aa = (e, t, n, r) => {
752
809
  switch (e) {
753
- case "postgres": return Aa(t, n, r);
810
+ case "postgres": return Ia(t, n, r);
754
811
  case "sqlite":
755
- case "turso": return Ra(t, n, r);
812
+ case "turso": return Wa(t, n, r);
756
813
  case "mysql":
757
- case "mariadb": return Ja(t, n, r);
758
- case "mssql": return to(t, n, r);
814
+ case "mariadb": return eo(t, n, r);
815
+ case "mssql": return so(t, n, r);
759
816
  }
760
- }, Ta = (e, t) => t === "mssql" && !Ea.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), Ea = /(?:Z|[+-]\d{2}:?\d{2})$/, Da = (e, t) => {
761
- let n = Oa(e.table, e.children, t);
817
+ }, ja = (e, t) => t === "mssql" && !Ma.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), Ma = /(?:Z|[+-]\d{2}:?\d{2})$/, Na = (e, t) => {
818
+ let n = Pa(e.table, e.children, t);
762
819
  return (e) => e.map((e) => {
763
820
  let t = e.__row, r = typeof t == "string" ? JSON.parse(t) : t;
764
821
  return n(r);
765
822
  });
766
- }, Oa = (e, t, n) => {
823
+ }, Pa = (e, t, n) => {
767
824
  let r = [], i = [];
768
825
  for (let [t, n] of Object.entries(e.fields)) (n.type === "timestamp" || n.type === "date") && r.push(t), n.type === "vector" && i.push(t);
769
826
  let a = t.map((e) => {
770
- let t = Oa(e.target, e.children, n), r = e.relation.kind === "one", i = N(e), a = i ? ra({
827
+ let t = Pa(e.target, e.children, n), r = e.relation.kind === "one", i = F(e), a = i ? la({
771
828
  relationName: e.relationName,
772
829
  sourceTableName: e.source.tableName,
773
830
  targetTableName: e.target.tableName,
@@ -780,15 +837,15 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
780
837
  isSingle: r,
781
838
  fromOverFetch: i,
782
839
  cardinalityMessage: a,
783
- junction: ka(e.junction, n)
840
+ junction: Fa(e.junction, n)
784
841
  };
785
842
  });
786
843
  return (e) => {
787
844
  let t = { ...e };
788
- for (let e of i) e in t && (t[e] = dt(t[e], "vector", n));
845
+ for (let e of i) e in t && (t[e] = ct(t[e], "vector", n));
789
846
  for (let e of r) {
790
847
  let r = t[e];
791
- typeof r == "string" && (t[e] = Ta(r, n));
848
+ typeof r == "string" && (t[e] = ja(r, n));
792
849
  }
793
850
  for (let e of a) {
794
851
  let n = t[e.name];
@@ -798,7 +855,7 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
798
855
  }
799
856
  if (e.fromOverFetch) {
800
857
  let r = n;
801
- if (r.length > 1) throw new na(e.cardinalityMessage);
858
+ if (r.length > 1) throw new ca(e.cardinalityMessage);
802
859
  t[e.name] = r.length === 0 ? null : e.decode(r[0]);
803
860
  continue;
804
861
  }
@@ -810,213 +867,213 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
810
867
  }
811
868
  return t;
812
869
  };
813
- }, ka = (e, t) => {
870
+ }, Fa = (e, t) => {
814
871
  if (e === void 0) return;
815
872
  let n = new Set(e.dateColumns), r = e.requested;
816
873
  return (e) => {
817
874
  let i = e._junction ?? {}, a = {};
818
875
  for (let e of r) {
819
876
  let r = i[e];
820
- a[e] = n.has(e) && typeof r == "string" ? Ta(r, t) : r;
877
+ a[e] = n.has(e) && typeof r == "string" ? ja(r, t) : r;
821
878
  }
822
879
  return {
823
880
  ...e,
824
881
  _junction: a
825
882
  };
826
883
  };
827
- }, Aa = (e, t, n) => {
828
- let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = ja(i, t.children, n);
829
- return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${z(e.predicate, i, r)}` : r``}${S(e).length > 0 ? r` ORDER BY ${r.csv(S(e).map((e) => e.direction === "desc" ? r`${I(i, e.column, r)} DESC` : r`${I(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${R(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${R(e.skip, r)}`}`;
830
- }, ja = (e, t, n, r) => {
831
- let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${L(xa, i)}::text)`;
884
+ }, Ia = (e, t, n) => {
885
+ let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = La(i, t.children, n);
886
+ return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``}${T(e).length > 0 ? r` ORDER BY ${r.join(", ", !1)(T(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${B(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${B(e.skip, r)}`}`;
887
+ }, La = (e, t, n, r) => {
888
+ let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${z(Da, i)}::text)`;
832
889
  if (t.length === 0 && r === void 0) return a;
833
890
  let o = [];
834
- r !== void 0 && o.push(i`${L("_junction", i)}, ${I(e, xa, i)}`);
891
+ r !== void 0 && o.push(i`${z("_junction", i)}, ${R(e, Da, i)}`);
835
892
  for (let r of t) {
836
- let t = Ma(r, e, n);
893
+ let t = Ra(r, e, n);
837
894
  if (t === null) return null;
838
- o.push(i`${L(r.relationName, i)}, ${t}`);
895
+ o.push(i`${z(r.relationName, i)}, ${t}`);
839
896
  }
840
- return i`${a} || jsonb_build_object(${i.csv(o)})`;
841
- }, Ma = (e, t, n) => {
897
+ return i`${a} || jsonb_build_object(${i.join(", ", !1)(o)})`;
898
+ }, Ra = (e, t, n) => {
842
899
  switch (e.relation.kind) {
843
- case "one": return N(e) ? Pa(ga(e), t, n) : Na(e, t, n);
844
- case "many": return Pa(e, t, n);
845
- case "manyToMany": return Fa(e, t, n);
900
+ case "one": return F(e) ? Ba(Sa(e), t, n) : za(e, t, n);
901
+ case "many": return Ba(e, t, n);
902
+ case "manyToMany": return Va(e, t, n);
846
903
  }
847
- }, Na = (e, t, n) => {
848
- let r = n.sql, i = n.nextAlias(), a = ja(i, e.children, n);
904
+ }, za = (e, t, n) => {
905
+ let r = n.sql, i = n.nextAlias(), a = La(i, e.children, n);
849
906
  if (a === null) return null;
850
- let o = e.fkSide === "source" ? r`${I(i, "id", r)} = ${I(t, e.foreignKey, r)}` : r`${I(i, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${z(e.branch.where, i, r)}`, c = P(i, e.branch.orderBy, r);
907
+ let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${V(e.branch.where, i, r)}`, c = I(i, e.branch.orderBy, r);
851
908
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}${c} LIMIT 1)`;
852
- }, Pa = (e, t, n) => {
853
- let r = n.sql, i = n.nextAlias(), a = ja(i, e.children, n);
909
+ }, Ba = (e, t, n) => {
910
+ let r = n.sql, i = n.nextAlias(), a = La(i, e.children, n);
854
911
  if (a === null) return null;
855
- let o = r`${I(void 0, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${h(e.branch.where, r)}`, c = La(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${R(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${R(e.branch.offset, r)}`;
912
+ let o = r`${R(void 0, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${y(e.branch.where, r)}`, c = Ua(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`;
856
913
  return r`COALESCE((SELECT jsonb_agg(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), '[]'::jsonb)`;
857
- }, Fa = (e, t, n) => {
858
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ja(o, e.children, n, e.junction);
914
+ }, Va = (e, t, n) => {
915
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = La(o, e.children, n, e.junction);
859
916
  if (c === null) return null;
860
- let l = e.branch.where === void 0 ? r`` : r` AND ${h(e.branch.where, r)}`, u = lo(e, s, r), d = P(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${R(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${R(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${Ia(e.junction, s, r)} AS ${r(xa)}`;
861
- 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 ${I(o, "id", r)} = ${I(s, i.targetKey, r)} WHERE ${I(s, i.sourceKey, r)} = ${I(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
862
- }, Ia = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${L(e, n)}, ${I(t, e, n)}`))})`, P = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${I(e, t.column, n)} DESC` : n`${I(e, t.column, n)} ASC`))}`, La = (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`))}`, Ra = (e, t, n) => {
863
- let r = n.sql, i = n.nextAlias(), a = za(i, t.table, t.children, n);
917
+ let l = e.branch.where === void 0 ? r`` : r` AND ${y(e.branch.where, r)}`, u = go(e, s, r), d = I(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${Ha(e.junction, s, r)} AS ${r(Da)}`;
918
+ 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 ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
919
+ }, Ha = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.join(", ", !1)(e.present.map((e) => n`${z(e, n)}, ${R(t, e, n)}`))})`, I = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.join(", ", !1)(t.map((t) => t.direction === "desc" ? n`${R(e, t.column, n)} DESC` : n`${R(e, t.column, n)} ASC`))}`, Ua = (e, t) => e === void 0 || e.length === 0 ? t`` : t` ORDER BY ${t.join(", ", !1)(e.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`, Wa = (e, t, n) => {
920
+ let r = n.sql, i = n.nextAlias(), a = Ga(i, t.table, t.children, n);
864
921
  if (a === null) return null;
865
- let o = e.predicate ? r` WHERE ${z(e.predicate, i, r)}` : r``, s = S(e).length > 0 ? r` ORDER BY ${r.csv(S(e).map((e) => e.direction === "desc" ? r`${I(i, e.column, r)} DESC` : r`${I(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${R(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${R(e.skip, r)}`;
922
+ let o = e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``, s = T(e).length > 0 ? r` ORDER BY ${r.join(", ", !1)(T(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${B(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${B(e.skip, r)}`;
866
923
  return r`SELECT ${a} AS "__row" FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
867
- }, za = (e, t, n, r, i) => {
924
+ }, Ga = (e, t, n, r, i) => {
868
925
  let a = r.sql, o = [];
869
- for (let n of y(t)) {
870
- let r = I(e, n, a), i = t.fields[n]?.type === "bigint" ? a`CAST(${r} AS TEXT)` : r;
871
- o.push(a`${L(n, a)}, ${i}`);
926
+ for (let n of C(t)) {
927
+ let r = R(e, n, a), i = t.fields[n]?.type === "bigint" ? a`CAST(${r} AS TEXT)` : r;
928
+ o.push(a`${z(n, a)}, ${i}`);
872
929
  }
873
930
  if (i !== void 0) {
874
- let e = Ba(i.projection, i.source, a);
875
- o.push(a`${L("_junction", a)}, json_object(${e})`);
931
+ let e = Ka(i.projection, i.source, a);
932
+ o.push(a`${z("_junction", a)}, json_object(${e})`);
876
933
  }
877
934
  for (let t of n) {
878
- let n = Wa(t, e, r);
935
+ let n = Xa(t, e, r);
879
936
  if (n === null) return null;
880
- o.push(a`${L(t.relationName, a)}, ${n}`);
937
+ o.push(a`${z(t.relationName, a)}, ${n}`);
881
938
  }
882
- return a`json_object(${a.csv(o)})`;
883
- }, Ba = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((r) => {
884
- let i = I(t.alias, t.physical(r), n), a = e.through.fields[r]?.type === "bigint" ? n.onDialectOrElse({
939
+ return a`json_object(${a.join(", ", !1)(o)})`;
940
+ }, Ka = (e, t, n) => e.present.length === 0 ? n`` : n.join(", ", !1)(e.present.map((r) => {
941
+ let i = R(t.alias, t.physical(r), n), a = e.through.fields[r]?.type === "bigint" ? n.onDialectOrElse({
885
942
  sqlite: () => n`CAST(${i} AS TEXT)`,
886
943
  orElse: () => i
887
944
  }) : i;
888
- return n`${L(r, n)}, ${a}`;
889
- })), Va = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${I(t, e, n)} AS ${n(ba(e))}`))}`, Ha = (e) => ({
945
+ return n`${z(r, n)}, ${a}`;
946
+ })), qa = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.join(", ", !1)(e.present.map((e) => n`${R(t, e, n)} AS ${n(Ea(e))}`))}`, Ja = (e) => ({
890
947
  alias: e,
891
- physical: ba
892
- }), Ua = (e) => ({
948
+ physical: Ea
949
+ }), Ya = (e) => ({
893
950
  alias: e,
894
951
  physical: (e) => e
895
- }), Wa = (e, t, n) => {
952
+ }), Xa = (e, t, n) => {
896
953
  switch (e.relation.kind) {
897
- case "one": return N(e) ? Ka(ga(e), t, n) : Ga(e, t, n);
898
- case "many": return Ka(e, t, n);
899
- case "manyToMany": return qa(e, t, n);
954
+ case "one": return F(e) ? Qa(Sa(e), t, n) : Za(e, t, n);
955
+ case "many": return Qa(e, t, n);
956
+ case "manyToMany": return $a(e, t, n);
900
957
  }
901
- }, Ga = (e, t, n) => {
902
- let r = n.sql, i = n.nextAlias(), a = za(i, e.target, e.children, n);
958
+ }, Za = (e, t, n) => {
959
+ let r = n.sql, i = n.nextAlias(), a = Ga(i, e.target, e.children, n);
903
960
  if (a === null) return null;
904
- let o = e.fkSide === "source" ? r`${I(i, "id", r)} = ${I(t, e.foreignKey, r)}` : r`${I(i, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`;
961
+ let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`;
905
962
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
906
- }, Ka = (e, t, n) => {
907
- let r = n.sql, i = n.nextAlias(), a = za(i, e.target, e.children, n);
963
+ }, Qa = (e, t, n) => {
964
+ let r = n.sql, i = n.nextAlias(), a = Ga(i, e.target, e.children, n);
908
965
  if (a === null) return null;
909
- let o = r`${I(void 0, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${h(B(e.branch.where), r)}`, c = La(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${R(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${R(e.branch.offset, r)}`;
966
+ let o = r`${R(void 0, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${y(H(e.branch.where), r)}`, c = Ua(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`;
910
967
  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('[]'))`;
911
- }, qa = (e, t, n) => {
912
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = za(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
968
+ }, $a = (e, t, n) => {
969
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ga(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
913
970
  projection: e.junction,
914
- source: Ha(o)
971
+ source: Ja(o)
915
972
  });
916
973
  if (c === null) return null;
917
- let l = e.branch.where === void 0 ? r`` : r` AND ${h(B(e.branch.where), r)}`, u = lo(e, s, r, !0), d = P(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${R(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${R(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Va(e.junction, s, r);
918
- 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 ${I(o, "id", r)} = ${I(s, i.targetKey, r)} WHERE ${I(s, i.sourceKey, r)} = ${I(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
919
- }, Ja = (e, t, n) => {
920
- let r = n.sql, i = n.nextAlias(), a = F(i, t.table, t.children, n);
974
+ let l = e.branch.where === void 0 ? r`` : r` AND ${y(H(e.branch.where), r)}`, u = go(e, s, r, !0), d = I(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : qa(e.junction, s, r);
975
+ 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 ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
976
+ }, eo = (e, t, n) => {
977
+ let r = n.sql, i = n.nextAlias(), a = L(i, t.table, t.children, n);
921
978
  if (a === null) return null;
922
- let o = e.predicate ? r` WHERE ${z(e.predicate, i, r)}` : r``, s = S(e).length > 0 ? r` ORDER BY ${r.csv(S(e).map((e) => e.direction === "desc" ? r`${I(i, e.column, r)} DESC` : r`${I(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${R(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${R(e.skip, r)}`;
979
+ let o = e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``, s = T(e).length > 0 ? r` ORDER BY ${r.join(", ", !1)(T(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${B(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${B(e.skip, r)}`;
923
980
  return r`SELECT ${a} AS \`__row\` FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
924
- }, F = (e, t, n, r, i) => {
981
+ }, L = (e, t, n, r, i) => {
925
982
  let a = r.sql, o = [];
926
- for (let n of y(t)) o.push(a`${L(n, a)}, ${I(e, n, a)}`);
983
+ for (let n of C(t)) o.push(a`${z(n, a)}, ${R(e, n, a)}`);
927
984
  if (i !== void 0) {
928
- let e = Ba(i.projection, i.source, a);
929
- o.push(a`${L("_junction", a)}, JSON_OBJECT(${e})`);
985
+ let e = Ka(i.projection, i.source, a);
986
+ o.push(a`${z("_junction", a)}, JSON_OBJECT(${e})`);
930
987
  }
931
988
  for (let t of n) {
932
- let n = Ya(t, e, r);
989
+ let n = to(t, e, r);
933
990
  if (n === null) return null;
934
- o.push(a`${L(t.relationName, a)}, ${n}`);
991
+ o.push(a`${z(t.relationName, a)}, ${n}`);
935
992
  }
936
- return a`JSON_OBJECT(${a.csv(o)})`;
937
- }, Ya = (e, t, n) => {
993
+ return a`JSON_OBJECT(${a.join(", ", !1)(o)})`;
994
+ }, to = (e, t, n) => {
938
995
  switch (e.relation.kind) {
939
996
  case "one":
940
- if (N(e)) {
941
- let r = ga(e);
942
- return n.dialect === "mariadb" ? $a(r, t, n) : Za(r, t, n);
997
+ if (F(e)) {
998
+ let r = Sa(e);
999
+ return n.dialect === "mariadb" ? ao(r, t, n) : ro(r, t, n);
943
1000
  }
944
- return Xa(e, t, n);
945
- case "many": return n.dialect === "mariadb" ? $a(e, t, n) : Za(e, t, n);
946
- case "manyToMany": return n.dialect === "mariadb" ? eo(e, t, n) : Qa(e, t, n);
1001
+ return no(e, t, n);
1002
+ case "many": return n.dialect === "mariadb" ? ao(e, t, n) : ro(e, t, n);
1003
+ case "manyToMany": return n.dialect === "mariadb" ? oo(e, t, n) : io(e, t, n);
947
1004
  }
948
- }, Xa = (e, t, n) => {
949
- let r = n.sql, i = n.nextAlias(), a = F(i, e.target, e.children, n);
1005
+ }, no = (e, t, n) => {
1006
+ let r = n.sql, i = n.nextAlias(), a = L(i, e.target, e.children, n);
950
1007
  if (a === null) return null;
951
- let o = e.fkSide === "source" ? r`${I(i, "id", r)} = ${I(t, e.foreignKey, r)}` : r`${I(i, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`;
1008
+ let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`;
952
1009
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
953
- }, Za = (e, t, n) => {
954
- let r = n.sql, i = n.nextAlias(), a = F(i, e.target, e.children, n);
1010
+ }, ro = (e, t, n) => {
1011
+ let r = n.sql, i = n.nextAlias(), a = L(i, e.target, e.children, n);
955
1012
  if (a === null) return null;
956
- let o = r`${I(void 0, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${h(B(e.branch.where), r)}`, c = La(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${R(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${R(e.branch.offset, r)}`;
1013
+ let o = r`${R(void 0, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${y(H(e.branch.where), r)}`, c = Ua(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`;
957
1014
  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())`;
958
- }, Qa = (e, t, n) => {
959
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = F(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1015
+ }, io = (e, t, n) => {
1016
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = L(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
960
1017
  projection: e.junction,
961
- source: Ha(o)
1018
+ source: Ja(o)
962
1019
  });
963
1020
  if (c === null) return null;
964
- let l = e.branch.where === void 0 ? r`` : r` AND ${h(B(e.branch.where), r)}`, u = lo(e, s, r, !0), d = P(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${R(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${R(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Va(e.junction, s, r);
965
- 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 ${I(o, "id", r)} = ${I(s, i.targetKey, r)} WHERE ${I(s, i.sourceKey, r)} = ${I(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
966
- }, $a = (e, t, n) => {
967
- let r = n.sql, i = n.nextAlias(), a = F(i, e.target, e.children, n);
1021
+ let l = e.branch.where === void 0 ? r`` : r` AND ${y(H(e.branch.where), r)}`, u = go(e, s, r, !0), d = I(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : qa(e.junction, s, r);
1022
+ 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 ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
1023
+ }, ao = (e, t, n) => {
1024
+ let r = n.sql, i = n.nextAlias(), a = L(i, e.target, e.children, n);
968
1025
  if (a === null) return null;
969
- let o = r`${I(i, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${h(B(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
970
- 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`${I(i, e.column, r)} DESC` : r`${I(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
971
- 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 ${I(i, "rn", r)} > ${R(d, r)} AND ${I(i, "rn", r)} <= ${R(d + u, r)}` : u === void 0 ? r` AND ${I(i, "rn", r)} > ${R(d, r)}` : r` AND ${I(i, "rn", r)} <= ${R(u, r)}`;
972
- return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${I(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())`;
973
- }, eo = (e, t, n) => {
1026
+ let o = r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${y(H(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1027
+ 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.join(", ", !1)(c.map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
1028
+ let l = c.length > 0 ? r` ORDER BY ${r.join(", ", !1)(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 ${R(i, "rn", r)} > ${B(d, r)} AND ${R(i, "rn", r)} <= ${B(d + u, r)}` : u === void 0 ? r` AND ${R(i, "rn", r)} > ${B(d, r)}` : r` AND ${R(i, "rn", r)} <= ${B(u, r)}`;
1029
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${R(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())`;
1030
+ }, oo = (e, t, n) => {
974
1031
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = (t) => e.junction === void 0 ? void 0 : {
975
1032
  projection: e.junction,
976
1033
  source: t
977
- }, l = r`${I(s, i.sourceKey, r)} = ${I(t, "id", r)}`, u = r`${I(o, "id", r)} = ${I(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${h(B(e.branch.where), r)}`, f = lo(e, s, r, !0), p = e.branch.orderBy ?? [];
1034
+ }, l = r`${R(s, i.sourceKey, r)} = ${R(t, "id", r)}`, u = r`${R(o, "id", r)} = ${R(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${y(H(e.branch.where), r)}`, f = go(e, s, r, !0), p = e.branch.orderBy ?? [];
978
1035
  if (e.branch.limit === void 0 && e.branch.offset === void 0) {
979
- let t = F(o, e.target, e.children, n, c(Ua(s)));
980
- 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`${I(o, e.column, r)} DESC` : r`${I(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())`;
1036
+ let t = L(o, e.target, e.children, n, c(Ya(s)));
1037
+ return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${p.length > 0 ? r` ORDER BY ${r.join(", ", !1)(p.map((e) => e.direction === "desc" ? r`${R(o, e.column, r)} DESC` : r`${R(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())`;
981
1038
  }
982
- let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${I(o, e.column, r)} DESC` : r`${I(o, e.column, r)} ASC`))}` : r` ORDER BY ${I(o, "id", r)}`, g = e.branch.limit, _ = e.branch.offset, v = g !== void 0 && _ !== void 0 ? r` AND ${I(o, "rn", r)} > ${R(_, r)} AND ${I(o, "rn", r)} <= ${R(_ + g, r)}` : g === void 0 ? r` AND ${I(o, "rn", r)} > ${R(_, r)}` : r` AND ${I(o, "rn", r)} <= ${R(g, r)}`, ee = e.branch.onJunction === void 0 ? r`` : r` WHERE ${z(B(e.branch.onJunction), s, r)}`, te = F(o, e.target, e.children, n, c(Ha(o)));
983
- if (te === null) return null;
984
- let ne = e.junction === void 0 ? r`` : Va(e.junction, s, r);
985
- return r`COALESCE((SELECT JSON_ARRAYAGG(${te} ORDER BY ${I(o, "rn", r)}) FROM (SELECT ${r(o)}.*${ne}, ${I(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${I(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}${ee}) AS ${r(o)} WHERE ${I(o, `__src_${i.sourceKey}`, r)} = ${I(t, "id", r)}${d}${v}), JSON_ARRAY())`;
986
- }, to = (e, t, n) => {
987
- let r = n.sql, i = n.nextAlias(), a = no(i, t.table, t.children, n);
1039
+ let m = p.length > 0 ? r` ORDER BY ${r.join(", ", !1)(p.map((e) => e.direction === "desc" ? r`${R(o, e.column, r)} DESC` : r`${R(o, e.column, r)} ASC`))}` : r` ORDER BY ${R(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, _ = h !== void 0 && g !== void 0 ? r` AND ${R(o, "rn", r)} > ${B(g, r)} AND ${R(o, "rn", r)} <= ${B(g + h, r)}` : h === void 0 ? r` AND ${R(o, "rn", r)} > ${B(g, r)}` : r` AND ${R(o, "rn", r)} <= ${B(h, r)}`, v = e.branch.onJunction === void 0 ? r`` : r` WHERE ${V(H(e.branch.onJunction), s, r)}`, ee = L(o, e.target, e.children, n, c(Ja(o)));
1040
+ if (ee === null) return null;
1041
+ let te = e.junction === void 0 ? r`` : qa(e.junction, s, r);
1042
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${ee} ORDER BY ${R(o, "rn", r)}) FROM (SELECT ${r(o)}.*${te}, ${R(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${R(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 ${R(o, `__src_${i.sourceKey}`, r)} = ${R(t, "id", r)}${d}${_}), JSON_ARRAY())`;
1043
+ }, so = (e, t, n) => {
1044
+ let r = n.sql, i = n.nextAlias(), a = co(i, t.table, t.children, n);
988
1045
  if (a === null) return null;
989
- let o = e.predicate ? r` WHERE ${z(e.predicate, i, r)}` : r``, s = S(e).length > 0 ? r` ORDER BY ${r.csv(S(e).map((e) => e.direction === "desc" ? r`${I(i, e.column, r)} DESC` : r`${I(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1046
+ let o = e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``, s = T(e).length > 0 ? r` ORDER BY ${r.join(", ", !1)(T(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
990
1047
  if (e.skip !== void 0) {
991
- let t = S(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
992
- l = e.take === void 0 ? r`${t} OFFSET ${R(e.skip, r)} ROWS` : r`${t} OFFSET ${R(e.skip, r)} ROWS FETCH NEXT ${R(e.take, r)} ROWS ONLY`;
993
- } else e.take !== void 0 && (c = r`TOP ${R(e.take, r)} `);
1048
+ let t = T(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1049
+ l = e.take === void 0 ? r`${t} OFFSET ${B(e.skip, r)} ROWS` : r`${t} OFFSET ${B(e.skip, r)} ROWS FETCH NEXT ${B(e.take, r)} ROWS ONLY`;
1050
+ } else e.take !== void 0 && (c = r`TOP ${B(e.take, r)} `);
994
1051
  let u = e.skip === void 0 ? s : r``;
995
1052
  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}`;
996
- }, no = (e, t, n, r, i) => {
1053
+ }, co = (e, t, n, r, i) => {
997
1054
  let a = r.sql, o = [];
998
- for (let n of y(t)) o.push(a`${I(e, n, a)} AS ${a(n)}`);
999
- if (i !== void 0) for (let e of i.projection.present) o.push(a`${I(i.source.alias, i.source.physical(e), a)} AS ${ro(`_junction.${e}`, a)}`);
1055
+ for (let n of C(t)) o.push(a`${R(e, n, a)} AS ${a(n)}`);
1056
+ if (i !== void 0) for (let e of i.projection.present) o.push(a`${R(i.source.alias, i.source.physical(e), a)} AS ${lo(`_junction.${e}`, a)}`);
1000
1057
  for (let t of n) {
1001
- let n = io(t, e, r);
1058
+ let n = uo(t, e, r);
1002
1059
  if (n === null) return null;
1003
1060
  o.push(n);
1004
1061
  }
1005
- return a.csv(o);
1006
- }, ro = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), io = (e, t, n) => {
1062
+ return a.join(", ", !1)(o);
1063
+ }, lo = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), uo = (e, t, n) => {
1007
1064
  switch (e.relation.kind) {
1008
- case "one": return N(e) ? so(ga(e), t, n) : ao(e, t, n);
1009
- case "many": return so(e, t, n);
1010
- case "manyToMany": return co(e, t, n);
1065
+ case "one": return F(e) ? mo(Sa(e), t, n) : fo(e, t, n);
1066
+ case "many": return mo(e, t, n);
1067
+ case "manyToMany": return ho(e, t, n);
1011
1068
  }
1012
- }, ao = (e, t, n) => {
1013
- let r = n.sql, i = n.nextAlias(), a = no(i, e.target, e.children, n);
1069
+ }, fo = (e, t, n) => {
1070
+ let r = n.sql, i = n.nextAlias(), a = co(i, e.target, e.children, n);
1014
1071
  if (a === null) return null;
1015
- let o = e.fkSide === "source" ? r`${I(i, "id", r)} = ${I(t, e.foreignKey, r)}` : r`${I(i, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`;
1072
+ let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`;
1016
1073
  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)}`;
1017
- }, oo = (e, t, n) => {
1074
+ }, po = (e, t, n) => {
1018
1075
  if (e.offset !== void 0) {
1019
- let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${R(e.offset, n)} ROWS` : n`${r} OFFSET ${R(e.offset, n)} ROWS FETCH NEXT ${R(e.limit, n)} ROWS ONLY`;
1076
+ let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${B(e.offset, n)} ROWS` : n`${r} OFFSET ${B(e.offset, n)} ROWS FETCH NEXT ${B(e.limit, n)} ROWS ONLY`;
1020
1077
  return {
1021
1078
  top: n``,
1022
1079
  pagination: i,
@@ -1024,36 +1081,36 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1024
1081
  };
1025
1082
  }
1026
1083
  return {
1027
- top: e.limit === void 0 ? n`` : n`TOP ${R(e.limit, n)} `,
1084
+ top: e.limit === void 0 ? n`` : n`TOP ${B(e.limit, n)} `,
1028
1085
  pagination: n``,
1029
1086
  finalOrder: t
1030
1087
  };
1031
- }, so = (e, t, n) => {
1032
- let r = n.sql, i = n.nextAlias(), a = no(i, e.target, e.children, n);
1088
+ }, mo = (e, t, n) => {
1089
+ let r = n.sql, i = n.nextAlias(), a = co(i, e.target, e.children, n);
1033
1090
  if (a === null) return null;
1034
- let o = e.branch.where === void 0 ? r`` : r` AND ${z(e.branch.where, i, r)}`, s = P(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = oo(e.branch, s, r);
1035
- return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${I(i, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1036
- }, co = (e, t, n) => {
1037
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = no(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1091
+ let o = e.branch.where === void 0 ? r`` : r` AND ${V(e.branch.where, i, r)}`, s = I(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = po(e.branch, s, r);
1092
+ return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1093
+ }, ho = (e, t, n) => {
1094
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = co(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1038
1095
  projection: e.junction,
1039
- source: Ua(s)
1096
+ source: Ya(s)
1040
1097
  });
1041
1098
  if (c === null) return null;
1042
- let l = e.branch.where === void 0 ? r`` : r` AND ${z(e.branch.where, o, r)}`, u = lo(e, s, r), d = P(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = oo(e.branch, d, r);
1043
- 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 ${I(o, "id", r)} = ${I(s, i.targetKey, r)} WHERE ${I(s, i.sourceKey, r)} = ${I(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1044
- }, I = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, L = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), R = (e, t) => {
1045
- if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw C(`literalInt: expected non-negative integer, got ${e}`);
1099
+ let l = e.branch.where === void 0 ? r`` : r` AND ${V(e.branch.where, o, r)}`, u = go(e, s, r), d = I(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = po(e.branch, d, r);
1100
+ 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 ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1101
+ }, R = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, z = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), B = (e, t) => {
1102
+ if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw S(`literalInt: expected non-negative integer, got ${e}`);
1046
1103
  return t.unsafe(String(e));
1047
- }, z = (e, t, n) => {
1048
- let r = uo(e, t);
1049
- return h(r, n);
1050
- }, lo = (e, t, n, r = !1) => {
1104
+ }, V = (e, t, n) => {
1105
+ let r = _o(e, t);
1106
+ return y(r, n);
1107
+ }, go = (e, t, n, r = !1) => {
1051
1108
  let i = e.branch.onJunction;
1052
- return i === void 0 ? n`` : n` AND ${z(r ? B(i) : i, t, n)}`;
1053
- }, uo = (e, t) => {
1054
- if ("not" in e) return { not: uo(e.not, t) };
1055
- if ("and" in e) return { and: e.and.map((e) => uo(e, t)) };
1056
- if ("or" in e) return { or: e.or.map((e) => uo(e, t)) };
1109
+ return i === void 0 ? n`` : n` AND ${V(r ? H(i) : i, t, n)}`;
1110
+ }, _o = (e, t) => {
1111
+ if ("not" in e) return { not: _o(e.not, t) };
1112
+ if ("and" in e) return { and: e.and.map((e) => _o(e, t)) };
1113
+ if ("or" in e) return { or: e.or.map((e) => _o(e, t)) };
1057
1114
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
1058
1115
  let n = e;
1059
1116
  return {
@@ -1066,57 +1123,57 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1066
1123
  return {
1067
1124
  ...n,
1068
1125
  column: `${t}.${n.column}`,
1069
- ...Xe(n.value) ? { value: Oe(`${t}.${n.value.column}`) } : {}
1126
+ ...l(n.value) ? { value: xr(`${t}.${n.value.column}`) } : {}
1070
1127
  };
1071
- }, B = (e) => {
1072
- if ("not" in e) return { not: B(e.not) };
1073
- if ("and" in e) return { and: e.and.map((e) => B(e)) };
1074
- if ("or" in e) return { or: e.or.map((e) => B(e)) };
1128
+ }, H = (e) => {
1129
+ if ("not" in e) return { not: H(e.not) };
1130
+ if ("and" in e) return { and: e.and.map((e) => H(e)) };
1131
+ if ("or" in e) return { or: e.or.map((e) => H(e)) };
1075
1132
  if (e.op === "subquery-in" || e.op === "subquery-not-in" || e.op === "exists" || e.op === "not-exists") return e;
1076
1133
  let t = e;
1077
1134
  return {
1078
1135
  ...t,
1079
- value: _e(t.value)
1136
+ value: Qe(t.value)
1080
1137
  };
1081
- }, fo = Symbol.for("@voltro/database/coreTablesRegistry"), po = globalThis, mo = po[fo] ?? (po[fo] = {}), ho = (e) => {
1082
- e.actors !== void 0 && (mo.actors = e.actors), e.tenants !== void 0 && (mo.tenants = e.tenants);
1083
- }, go = (e, t) => () => {
1138
+ }, vo = Symbol.for("@voltro/database/coreTablesRegistry"), yo = globalThis, bo = yo[vo] ?? (yo[vo] = {}), xo = (e) => {
1139
+ e.actors !== void 0 && (bo.actors = e.actors), e.tenants !== void 0 && (bo.tenants = e.tenants);
1140
+ }, So = (e, t) => () => {
1084
1141
  let n = e();
1085
1142
  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`);
1086
1143
  return n();
1087
- }, _o = () => go(() => mo.actors, "actors"), vo = () => go(() => mo.tenants, "tenants"), yo = x("actors", {
1088
- id: br(),
1089
- kind: b().oneOf([
1144
+ }, Co = () => So(() => bo.actors, "actors"), wo = () => So(() => bo.tenants, "tenants"), To = b("actors", {
1145
+ id: dt(),
1146
+ kind: x().oneOf([
1090
1147
  "user",
1091
1148
  "serviceAccount",
1092
1149
  "apiKey",
1093
1150
  "system"
1094
1151
  ]).safe(),
1095
- displayName: b().nullable().sensitive("fullName"),
1096
- createdAt: n().default("now")
1097
- }), bo = (e, t) => ({
1152
+ displayName: x().nullable().sensitive("fullName"),
1153
+ createdAt: w().default("now")
1154
+ }), Eo = (e, t) => ({
1098
1155
  ...t,
1099
1156
  ...e,
1100
1157
  origin: e.origin ?? "injected"
1101
- }), xo = (e, t, n = {}) => ({
1158
+ }), Do = (e, t, n = {}) => ({
1102
1159
  table: e,
1103
1160
  op: "insert",
1104
1161
  old: null,
1105
1162
  new: t,
1106
1163
  ...n
1107
- }), So = (e, t, n, r = {}) => ({
1164
+ }), Oo = (e, t, n, r = {}) => ({
1108
1165
  table: e,
1109
1166
  op: "update",
1110
1167
  old: t,
1111
1168
  new: n,
1112
1169
  ...r
1113
- }), Co = (e, t, n = {}) => ({
1170
+ }), ko = (e, t, n = {}) => ({
1114
1171
  table: e,
1115
1172
  op: "delete",
1116
1173
  old: t,
1117
1174
  new: null,
1118
1175
  ...n
1119
- }), wo = (e, t, n = {}) => {
1176
+ }), Ao = (e, t, n = {}) => {
1120
1177
  let { at: r = "2026-01-01T00:00:00.000Z", column: i = "deletedAt", ...a } = n;
1121
1178
  return {
1122
1179
  table: e,
@@ -1131,13 +1188,21 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1131
1188
  },
1132
1189
  ...a
1133
1190
  };
1134
- }, To = (e) => e == null ? "null" : e instanceof Date ? JSON.stringify(e.toISOString()) : typeof e == "bigint" ? JSON.stringify(e.toString()) : Array.isArray(e) ? `[${e.map(To).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${To(t)}`).join(",")}}` : JSON.stringify(e) ?? "null", Eo = (e) => Ir("sha256").update([
1191
+ }, jo = Symbol.for("voltro.database.committedChanges"), Mo = globalThis, No = Mo[jo] ??= /* @__PURE__ */ new WeakMap(), Po = (e, t) => {
1192
+ let n = {};
1193
+ for (let t of e) No.set(t, n);
1194
+ try {
1195
+ for (let n of e) t(n);
1196
+ } finally {
1197
+ for (let t of e) No.delete(t);
1198
+ }
1199
+ }, Fo = (e) => No.get(e), Io = (e) => e == null ? "null" : e instanceof Date ? JSON.stringify(e.toISOString()) : typeof e == "bigint" ? JSON.stringify(e.toString()) : Array.isArray(e) ? `[${e.map(Io).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)}:${Io(t)}`).join(",")}}` : JSON.stringify(e) ?? "null", Lo = (e) => Ir("sha256").update([
1135
1200
  e.pipe,
1136
1201
  e.op,
1137
1202
  e.key,
1138
- To(e.next),
1139
- To(e.prev)
1140
- ].join("\0")).digest("hex").slice(0, 32), Do = (e, t) => `${e}:${t}`, Oo = (e) => {
1203
+ Io(e.next),
1204
+ Io(e.prev)
1205
+ ].join("\0")).digest("hex").slice(0, 32), Ro = (e, t) => `${e}:${t}`, zo = (e) => {
1141
1206
  let t = e.lastIndexOf(":");
1142
1207
  if (t <= 0) return null;
1143
1208
  let n = Number(e.slice(t + 1));
@@ -1145,7 +1210,7 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1145
1210
  digest: e.slice(0, t),
1146
1211
  occurrence: n
1147
1212
  };
1148
- }, ko = class {
1213
+ }, Bo = class {
1149
1214
  #e = /* @__PURE__ */ new Map();
1150
1215
  #t;
1151
1216
  #n;
@@ -1167,7 +1232,7 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1167
1232
  }
1168
1233
  seedFromChangeKeys(e, t) {
1169
1234
  for (let n of e) {
1170
- let e = Oo(n);
1235
+ let e = zo(n);
1171
1236
  if (e === null) continue;
1172
1237
  let r = this.#e.get(e.digest), i = Math.max(r?.count ?? 0, e.occurrence + 1);
1173
1238
  this.#e.set(e.digest, {
@@ -1188,70 +1253,89 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1188
1253
  this.#e.delete(e.value);
1189
1254
  }
1190
1255
  }
1191
- }, Ao = "VOLTRO_CHANGE_CLAIMS_TTL_HOURS", jo = 1, Mo = (e = process.env) => {
1192
- let t = Number(e[Ao]);
1256
+ }, Vo = "VOLTRO_CHANGE_CLAIMS_TTL_HOURS", Ho = 1, Uo = (e = process.env) => {
1257
+ let t = Number(e[Vo]);
1193
1258
  return (Number.isFinite(t) && t > 0 ? t : 1) * 2 * 36e5;
1194
- }, No = new Lr(), Po = (e, t) => No.run(e, t), Fo = () => No.getStore(), Io = (e) => {
1195
- let t = e ?? No.getStore();
1259
+ }, Wo = new Lr(), Go = (e, t) => Wo.run(e, t), Ko = () => Wo.getStore(), qo = (e) => {
1260
+ let t = e ?? Wo.getStore();
1196
1261
  return t === void 0 ? {} : {
1197
1262
  ...t.traceId === void 0 ? {} : { traceId: t.traceId },
1198
1263
  ...t.subjectId === void 0 ? {} : { subjectId: t.subjectId },
1199
1264
  ...t.procedure === void 0 ? {} : { procedure: t.procedure },
1200
1265
  ...t.via === void 0 ? {} : { via: t.via }
1201
1266
  };
1202
- }, Lo = (e) => {
1203
- let t = No.getStore();
1204
- return t === void 0 ? e(void 0) : No.run(t, () => e(t));
1205
- }, Ro = 3e4, zo = 1e4, V = /* @__PURE__ */ new Map(), H = 0, Bo = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Vo = (e) => {
1206
- for (let [t, n] of V) {
1207
- let r = n.filter((t) => e - t.at < Ro);
1208
- H -= n.length - r.length, r.length === 0 ? V.delete(t) : r.length !== n.length && V.set(t, r);
1209
- }
1210
- }, Ho = (e, t) => {
1211
- if (t.traceId === void 0 && t.subjectId === void 0 && t.procedure === void 0) return;
1267
+ }, Jo = (e) => {
1268
+ let t = Wo.getStore();
1269
+ return t === void 0 ? e(void 0) : Wo.run(t, () => e(t));
1270
+ }, Yo = 3e4, Xo = 1e4, U = /* @__PURE__ */ new Map(), W = [], Zo = (e, t) => {
1271
+ let n = W[e];
1272
+ W[e] = W[t], W[t] = n, W[e].heapIndex = e, n.heapIndex = t;
1273
+ }, Qo = (e) => {
1274
+ for (; e > 0;) {
1275
+ let t = Math.floor((e - 1) / 2);
1276
+ if (W[t].at <= W[e].at) break;
1277
+ Zo(t, e), e = t;
1278
+ }
1279
+ return e;
1280
+ }, $o = (e) => {
1281
+ for (; e * 2 + 1 < W.length;) {
1282
+ let t = e * 2 + 1;
1283
+ if (t + 1 < W.length && W[t + 1].at < W[t].at && t++, W[e].at <= W[t].at) break;
1284
+ Zo(e, t), e = t;
1285
+ }
1286
+ }, es = (e) => {
1287
+ let t = U.get(e.key);
1288
+ e.previous ? e.previous.next = e.next : e.next && (t.head = e.next), e.next ? e.next.previous = e.previous : e.previous && (t.tail = e.previous), !e.previous && !e.next && U.delete(e.key);
1289
+ let n = e.heapIndex, r = W.pop();
1290
+ n < W.length && (W[n] = r, r.heapIndex = n, $o(Qo(n)));
1291
+ }, ts = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, ns = (e) => {
1292
+ for (; W[0] !== void 0 && e - W[0].at >= Yo;) es(W[0]);
1293
+ }, rs = (e, t) => {
1294
+ if (t.traceId === void 0 && t.subjectId === void 0 && t.procedure === void 0 && t.via === void 0) return;
1212
1295
  let n = Date.now();
1213
- if (H >= zo && Vo(n), H >= zo) return;
1214
- let r = V.get(e);
1215
- r === void 0 ? V.set(e, [{
1216
- attribution: t,
1217
- at: n
1218
- }]) : r.push({
1296
+ if (W.length >= Xo && ns(n), W.length >= Xo) return;
1297
+ let r = U.get(e), i = {
1298
+ key: e,
1219
1299
  attribution: t,
1220
- at: n
1221
- }), H += 1;
1222
- }, Uo = (e) => {
1223
- let t = V.get(e);
1224
- if (t === void 0 || t.length === 0) return;
1225
- let n = t.shift();
1226
- if (--H, t.length === 0 && V.delete(e), !(Date.now() - n.at >= Ro)) return n.attribution;
1227
- }, Wo = (e) => (V.get(e)?.length ?? 0) > 0, U = /* @__PURE__ */ new Map(), W = /* @__PURE__ */ new Map(), G = /* @__PURE__ */ new Map(), Go = 250, Ko = (e) => {
1228
- let t = W.get(e);
1300
+ at: n,
1301
+ heapIndex: W.length,
1302
+ previous: r?.tail
1303
+ };
1304
+ r ? (r.tail.next = i, r.tail = i) : U.set(e, {
1305
+ head: i,
1306
+ tail: i
1307
+ }), W.push(i), Qo(i.heapIndex);
1308
+ }, is = (e) => {
1309
+ let t = U.get(e)?.head;
1310
+ if (t !== void 0 && (es(t), !(Date.now() - t.at >= Yo))) return t.attribution;
1311
+ }, as = (e) => U.has(e), G = /* @__PURE__ */ new Map(), os = /* @__PURE__ */ new Map(), ss = /* @__PURE__ */ new Map(), cs = 250, ls = (e) => {
1312
+ let t = os.get(e);
1229
1313
  if (t === void 0) return;
1230
- W.delete(e);
1231
- let n = G.get(e);
1232
- n !== void 0 && (clearTimeout(n), G.delete(e));
1314
+ os.delete(e);
1315
+ let n = ss.get(e);
1316
+ n !== void 0 && (clearTimeout(n), ss.delete(e));
1233
1317
  for (let e of t) e();
1234
- }, qo = (e) => {
1235
- U.set(e, (U.get(e) ?? 0) + 1);
1236
- }, Jo = (e) => {
1237
- let t = (U.get(e) ?? 0) - 1;
1318
+ }, us = (e) => {
1319
+ G.set(e, (G.get(e) ?? 0) + 1);
1320
+ }, ds = (e) => {
1321
+ let t = (G.get(e) ?? 0) - 1;
1238
1322
  if (t > 0) {
1239
- U.set(e, t);
1323
+ G.set(e, t);
1240
1324
  return;
1241
1325
  }
1242
- U.delete(e), Ko(e);
1243
- }, Yo = (e, t, n, r) => {
1244
- let i = n == null ? void 0 : Bo(e, t, n), a = () => r(i === void 0 ? void 0 : Uo(i));
1326
+ G.delete(e), ls(e);
1327
+ }, fs = (e, t, n, r) => {
1328
+ let i = n == null ? void 0 : ts(e, t, n), a = () => r(i === void 0 ? void 0 : is(i));
1245
1329
  if (i === void 0) {
1246
1330
  a();
1247
1331
  return;
1248
1332
  }
1249
- if (Wo(i)) {
1333
+ if (as(i)) {
1250
1334
  a();
1251
1335
  return;
1252
1336
  }
1253
- let o = W.get(e);
1254
- if (o === void 0 && (U.get(e) ?? 0) === 0) {
1337
+ let o = os.get(e);
1338
+ if (o === void 0 && (G.get(e) ?? 0) === 0) {
1255
1339
  a();
1256
1340
  return;
1257
1341
  }
@@ -1259,91 +1343,94 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1259
1343
  o.push(a);
1260
1344
  return;
1261
1345
  }
1262
- W.set(e, [a]);
1263
- let s = setTimeout(() => Ko(e), Go);
1264
- typeof s == "object" && typeof s.unref == "function" && s.unref(), G.set(e, s);
1265
- }, Xo = () => {
1266
- V.clear(), H = 0, U.clear();
1267
- for (let e of G.values()) clearTimeout(e);
1268
- G.clear(), W.clear();
1269
- }, Zo = () => H, Qo = 64, $o = "\0", es = 32, ts = (e, ...t) => `${e}_${Ir("sha256").update(t.map(String).join($o)).digest("hex").slice(0, es)}`, ns = (e) => e.length + 1 + es, K = /* @__PURE__ */ new Map(), rs = (e, t) => {
1346
+ os.set(e, [a]);
1347
+ let s = setTimeout(() => ls(e), cs);
1348
+ typeof s == "object" && typeof s.unref == "function" && s.unref(), ss.set(e, s);
1349
+ }, ps = () => {
1350
+ U.clear(), W.length = 0, G.clear();
1351
+ for (let e of ss.values()) clearTimeout(e);
1352
+ ss.clear(), os.clear();
1353
+ }, ms = () => W.length, hs = 64, gs = "\0", _s = 32, vs = (e, ...t) => `${e}_${Ir("sha256").update(t.map(String).join(gs)).digest("hex").slice(0, _s)}`, ys = (e) => e.length + 1 + _s, K = /* @__PURE__ */ new Map(), bs = (e, t) => {
1270
1354
  K.set(e, {
1271
1355
  recorder: t.recorder,
1272
1356
  tables: new Set(t.tables),
1273
1357
  ownTables: new Set(t.ownTables)
1274
1358
  });
1275
- }, is = (e) => {
1359
+ }, xs = (e) => {
1276
1360
  K.delete(e);
1277
- }, as = () => K.clear(), q = new Lr(), os = (e) => q.run({ n: 1 }, e), ss = (e) => w.suspend(() => {
1278
- let t = q.getStore();
1279
- if (t !== void 0) return t.n += 1, w.ensuring(e, w.sync(() => {
1361
+ }, Ss = () => K.clear(), Cs = new Lr(), ws = (e) => Cs.run({ n: 1 }, e), Ts = (e) => E.suspend(() => {
1362
+ let t = Cs.getStore();
1363
+ if (t !== void 0) return t.n += 1, E.ensuring(e, E.sync(() => {
1280
1364
  --t.n;
1281
1365
  }));
1282
1366
  let n = { n: 1 };
1283
- return q.enterWith(n), w.ensuring(e, w.sync(() => {
1367
+ return Cs.enterWith(n), E.ensuring(e, E.sync(() => {
1284
1368
  --n.n;
1285
1369
  }));
1286
- }), cs = () => (q.getStore()?.n ?? 0) > 0, ls = (e) => {
1287
- if (K.size === 0 || (q.getStore()?.n ?? 0) > 0) return !1;
1370
+ }), Es = () => (Cs.getStore()?.n ?? 0) > 0, Ds = (e) => {
1371
+ if (K.size === 0 || (Cs.getStore()?.n ?? 0) > 0) return !1;
1288
1372
  for (let t of K.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1289
1373
  return !1;
1290
- }, us = async (e, t) => {
1374
+ }, Os = async (e, t) => {
1291
1375
  if (K.size !== 0) {
1292
1376
  for (let [n, r] of K.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1293
1377
  await r.recorder(e, t);
1294
1378
  } catch (e) {
1295
- let r = yn(e);
1379
+ let r = Wt(e);
1296
1380
  throw r === void 0 ? e : Error(`write recorder '${n}' failed while recording a ${t.op} on '${t.table}': ${r}`, { cause: e });
1297
1381
  }
1298
1382
  }
1299
- }, ds = Nr.exponential({
1383
+ }, ks = D.exponentialBoundaries({
1300
1384
  start: 5e-4,
1301
1385
  factor: 2,
1302
1386
  count: 16
1303
- }), fs = T.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), ps = T.histogram("voltro_db_query_duration_seconds", ds, "Database operation duration in seconds, by dialect and operation kind."), ms = T.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), hs = 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." }), gs = 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 = [], _s = /* @__PURE__ */ new Map(), vs = /* @__PURE__ */ new Map(), ys = /* @__PURE__ */ new Map(), bs = (e, t) => {
1304
- let n = `${e}\u0000${t}`, r = _s.get(n);
1387
+ }), As = D.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), js = D.histogram("voltro_db_query_duration_seconds", {
1388
+ boundaries: ks,
1389
+ description: "Database operation duration in seconds, by dialect and operation kind."
1390
+ }), Ms = D.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), Ns = D.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." }), Ps = D.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." }), Fs = Ar.empty(), Is = /* @__PURE__ */ new Map(), Ls = /* @__PURE__ */ new Map(), Rs = /* @__PURE__ */ new Map(), zs = (e, t) => {
1391
+ let n = `${e}\u0000${t}`, r = Is.get(n);
1305
1392
  if (r !== void 0) return r;
1306
- let i = (n) => T.tagged(T.tagged(n, "dialect", e), "op", t), a = {
1307
- count: i(fs),
1308
- duration: i(ps),
1309
- errors: i(ms)
1393
+ let i = (n) => D.withAttributes(D.withAttributes(n, { dialect: e }), { op: t }), a = {
1394
+ count: i(As),
1395
+ duration: i(js),
1396
+ errors: i(Ms)
1310
1397
  };
1311
- return _s.set(n, a), a;
1312
- }, xs = () => {
1313
- _s.clear(), vs.clear(), ys.clear();
1314
- }, Ss = () => _s.size + vs.size + ys.size, Cs = /* @__PURE__ */ new Map(), ws = (e, t) => {
1315
- let n = Math.max(0, (Cs.get(e) ?? 0) + t);
1316
- n === 0 ? Cs.delete(e) : Cs.set(e, n);
1317
- let r = vs.get(e);
1318
- r === void 0 && (r = T.tagged(hs, "dialect", e), vs.set(e, r)), r.unsafeUpdate(n, J);
1319
- }, Ts = (e) => Cs.get(e) ?? 0, Es = (e) => {
1320
- let t = bs(String(e.dialect), e.op);
1321
- t.count.unsafeUpdate(1, J), t.duration.unsafeUpdate(e.durationMs / 1e3, J), e.status === "error" && t.errors.unsafeUpdate(1, J);
1322
- }, Ds = async (e, t, n) => {
1398
+ return Is.set(n, a), a;
1399
+ }, Bs = () => {
1400
+ Is.clear(), Ls.clear(), Rs.clear();
1401
+ }, Vs = () => Is.size + Ls.size + Rs.size, Hs = /* @__PURE__ */ new Map(), Us = (e, t) => {
1402
+ let n = Math.max(0, (Hs.get(e) ?? 0) + t);
1403
+ n === 0 ? Hs.delete(e) : Hs.set(e, n);
1404
+ let r = Ls.get(e);
1405
+ r === void 0 && (r = D.withAttributes(Ns, { dialect: e }), Ls.set(e, r)), r.updateUnsafe(n, Fs);
1406
+ }, Ws = (e) => Hs.get(e) ?? 0, Gs = (e) => {
1407
+ let t = zs(String(e.dialect), e.op);
1408
+ t.count.updateUnsafe(1, Fs), t.duration.updateUnsafe(e.durationMs / 1e3, Fs), e.status === "error" && t.errors.updateUnsafe(1, Fs);
1409
+ }, Ks = async (e, t, n) => {
1323
1410
  let r = performance.now(), i = String(e);
1324
- ws(i, 1);
1411
+ Us(i, 1);
1325
1412
  let a = "ok";
1326
1413
  try {
1327
1414
  return await n();
1328
1415
  } catch (e) {
1329
1416
  throw a = "error", e;
1330
1417
  } finally {
1331
- ws(i, -1), Es({
1418
+ Us(i, -1), Gs({
1332
1419
  dialect: e,
1333
1420
  op: t,
1334
1421
  durationMs: performance.now() - r,
1335
1422
  status: a
1336
1423
  });
1337
1424
  }
1338
- }, Os = 3e5, ks = (e) => {
1425
+ }, qs = 3e5, Js = (e) => {
1339
1426
  if (e == null || e === "") return;
1340
1427
  let t = Number(e);
1341
1428
  return Number.isFinite(t) && t >= 0 ? Math.floor(t) : void 0;
1342
- }, As = (e, t = process.env) => ks(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? ks(e) ?? 3e5, js = (e, t = {}) => {
1343
- let n = As(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1429
+ }, Ys = (e, t = process.env) => Js(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? Js(e) ?? 3e5, Xs = (e, t = {}) => {
1430
+ let n = Ys(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1344
1431
  return (t) => {
1345
- let a = `${t.dialect} ${t.reason}`, o = ys.get(a);
1346
- o === void 0 && (o = T.tagged(T.tagged(gs, "dialect", String(t.dialect)), "reason", t.reason), ys.set(a, o)), o.unsafeUpdate(1, J);
1432
+ let a = `${t.dialect} ${t.reason}`, o = Rs.get(a);
1433
+ o === void 0 && (o = D.withAttributes(D.withAttributes(Ps, { dialect: String(t.dialect) }), { reason: t.reason }), Rs.set(a, o)), o.updateUnsafe(1, Fs);
1347
1434
  let s = `${t.table}\u0000${t.reason}`, c = i.get(s), l = c === void 0 || n > 0 && r() - c >= n, u = {
1348
1435
  table: t.table,
1349
1436
  dialect: String(t.dialect),
@@ -1357,37 +1444,45 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1357
1444
  }
1358
1445
  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);
1359
1446
  };
1360
- }, Ms = (e) => {
1447
+ }, Zs = (e) => {
1361
1448
  if (Mr.isSuccess(e)) return e.value;
1362
- throw kr.squash(e.cause);
1363
- }, Ns = "10 millis", Ps = 3, Fs = (e) => Pr.exponential(Ns).pipe(Pr.compose(Pr.recurs(Ps)), Pr.whileInput(e)), Is = async (e) => {
1364
- let t = 0, n = w.suspend(() => {
1449
+ let t = kr.squash(e.cause);
1450
+ throw e.cause.reasons.length > 1 && typeof t == "object" && t && Object.isExtensible(t) && Object.defineProperty(t, "voltroCause", {
1451
+ value: e.cause,
1452
+ enumerable: !1,
1453
+ configurable: !0
1454
+ }), t;
1455
+ }, Qs = "10 millis", $s = 3, ec = (e) => Nr.max([Nr.exponential(Qs), Nr.recurs($s)]).pipe(Nr.while(({ input: t }) => e(t))), tc = zr.TransactionConnection(0), nc = /* @__PURE__ */ new WeakMap(), rc = (e, t, n) => {
1456
+ let r = nc.get(n);
1457
+ return r === void 0 ? E.provideService(e, t, n) : E.provideContext(e, r);
1458
+ }, ic = async (e) => {
1459
+ let t = 0, n = E.suspend(() => {
1365
1460
  let n = ++t;
1366
- return e.withTransaction(w.flatMap(w.serviceOption(Rr), (t) => {
1367
- if (E.isNone(t)) return w.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1368
- let r = t.value, i = w.tryPromise({
1461
+ return e.withTransaction(E.flatMap(E.serviceOption(e.transactionService), (t) => {
1462
+ if (O.isNone(t)) return E.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1463
+ let r = t.value, i = E.tryPromise({
1369
1464
  try: () => e.body(r, n),
1370
1465
  catch: (e) => e
1371
1466
  });
1372
- return e.prepare === void 0 ? i : w.flatMap(e.prepare(r), () => i);
1373
- })).pipe(w.catchAllDefect((t) => e.isRetryable(t) ? w.fail(t) : w.die(t)));
1374
- }).pipe(w.retry(Fs(e.isRetryable)), w.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1375
- return Ds(e.dialect, "transaction", async () => Ms(await e.runPromiseExit(e.wrapProgram === void 0 ? n : e.wrapProgram(n))));
1376
- }, Ls = class extends Error {
1467
+ return E.flatMap(E.context(), (t) => (nc.set(r, t), e.prepare === void 0 ? i : E.flatMap(e.prepare(r), () => i)));
1468
+ })).pipe(E.catchDefect((t) => e.isRetryable(t) ? E.fail(t) : E.die(t)));
1469
+ }).pipe(E.retry(ec(e.isRetryable)), E.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1470
+ return Ks(e.dialect, "transaction", async () => Zs(await e.runPromiseExit(e.wrapProgram === void 0 ? n : e.wrapProgram(n))));
1471
+ }, ac = class extends Error {
1377
1472
  swallowed;
1378
1473
  _tag = "TransactionAborted";
1379
1474
  constructor(e, t) {
1380
1475
  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.
1381
- the caught failure: ${Vs(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";
1476
+ the caught failure: ${lc(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";
1382
1477
  }
1383
- }, Rs = (e, t = "transactional()") => {
1478
+ }, oc = (e, t = "transactional()") => {
1384
1479
  let n = 0, r, i = (e) => {
1385
1480
  r === void 0 && (r = { error: e });
1386
1481
  };
1387
1482
  return {
1388
1483
  track: (a) => r === void 0 ? n > 0 ? a() : a().catch((t) => {
1389
1484
  throw e(t) && i(t), t;
1390
- }) : Promise.reject(new Ls(t, r.error)),
1485
+ }) : Promise.reject(new ac(t, r.error)),
1391
1486
  inSavepoint: async (e) => {
1392
1487
  n++;
1393
1488
  try {
@@ -1399,7 +1494,7 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1399
1494
  record: i,
1400
1495
  abortedBy: () => r
1401
1496
  };
1402
- }, zs = async (e, t) => {
1497
+ }, sc = async (e, t) => {
1403
1498
  let { tracker: n, name: r, exec: i, spelling: a } = e;
1404
1499
  await n.track(() => i(a === "mssql" ? `SAVE TRANSACTION ${r}` : `SAVEPOINT ${r}`));
1405
1500
  try {
@@ -1408,8 +1503,8 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1408
1503
  } catch (e) {
1409
1504
  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;
1410
1505
  }
1411
- }, Bs = (e) => e instanceof Ls || typeof e == "object" && !!e && e._tag === "TransactionAborted", Vs = (e) => {
1412
- for (let t of jn(e)) {
1506
+ }, cc = (e) => e instanceof ac || typeof e == "object" && !!e && e._tag === "TransactionAborted", lc = (e) => {
1507
+ for (let t of Bt(e)) {
1413
1508
  let e = t;
1414
1509
  for (let t = 0; t < 5 && typeof e == "object" && e; t++) {
1415
1510
  let t = e.code, n = e.message;
@@ -1418,14 +1513,14 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1418
1513
  }
1419
1514
  }
1420
1515
  return e instanceof Error ? e.message : String(e);
1421
- }, Hs = async (e) => {
1422
- let t = Fo(), n = t === void 0 ? (e) => e() : (e) => Po(t, e), r = await Is({
1516
+ }, uc = async (e) => {
1517
+ let t = Ko(), n = t === void 0 ? (e) => e() : (e) => Go(t, e), r = await ic({
1423
1518
  ...e,
1424
1519
  body: (r) => {
1425
1520
  let i = e.makeView(r, t);
1426
1521
  return n(() => e.work(i)).then((t) => {
1427
1522
  let n = i.abortedBy?.();
1428
- if (n !== void 0) throw e.isRetryable(n.error) ? n.error : new Ls(e.label, n.error);
1523
+ if (n !== void 0) throw e.isRetryable(n.error) ? n.error : new ac(e.label, n.error);
1429
1524
  return {
1430
1525
  result: t,
1431
1526
  view: i
@@ -1437,50 +1532,52 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1437
1532
  }
1438
1533
  });
1439
1534
  return r.view.commitEvents(), r.result;
1440
- }, Us = /* @__PURE__ */ new Set([
1535
+ }, dc = /* @__PURE__ */ new Set([
1441
1536
  "1213",
1442
1537
  "ER_LOCK_DEADLOCK",
1443
1538
  "1205",
1444
1539
  "ER_LOCK_WAIT_TIMEOUT",
1445
1540
  "1020",
1446
1541
  "ER_CHECKREAD"
1447
- ]), Ws = /* @__PURE__ */ new Set(["40001", "40P01"]), Gs = /* @__PURE__ */ new Set(["1205"]), Ks = /* @__PURE__ */ new Set([
1542
+ ]), fc = /* @__PURE__ */ new Set(["40001", "40P01"]), pc = /* @__PURE__ */ new Set(["1205"]), mc = /* @__PURE__ */ new Set([
1448
1543
  "SQLITE_BUSY",
1449
1544
  "5",
1545
+ "SQLITE_BUSY_SNAPSHOT",
1546
+ "517",
1450
1547
  "SQLITE_LOCKED",
1451
1548
  "6"
1452
- ]), qs = /write-write conflict|write-read conflict|database is locked|table is locked|database is busy/i, Js = /* @__PURE__ */ new Set([
1549
+ ]), hc = /write-write conflict|write-read conflict|database is locked|table is locked|database is busy/i, gc = /* @__PURE__ */ new Set([
1453
1550
  1213,
1454
1551
  1205,
1455
1552
  1020
1456
- ]), Ys = /* @__PURE__ */ new Set([
1457
- ...Us,
1458
- ...Ws,
1459
- ...Gs,
1460
- ...Ks
1461
- ]), Xs = (e) => jn(e).some(Zs), Zs = (e) => {
1553
+ ]), _c = /* @__PURE__ */ new Set([
1554
+ ...dc,
1555
+ ...fc,
1556
+ ...pc,
1557
+ ...mc
1558
+ ]), vc = (e) => Bt(e).some(yc), yc = (e) => {
1462
1559
  let t = e;
1463
1560
  for (let e = 0; e < 6 && typeof t == "object" && t; e++) {
1464
1561
  let e = t;
1465
- if (typeof e.errno == "number" && Js.has(e.errno) || typeof e.number == "number" && Gs.has(String(e.number)) || typeof e.code == "string" && Ys.has(e.code) || typeof e.sqlState == "string" && Ws.has(e.sqlState) || typeof e.message == "string" && qs.test(e.message)) return !0;
1562
+ if (typeof e.errno == "number" && gc.has(e.errno) || typeof e.number == "number" && pc.has(String(e.number)) || typeof e.code == "string" && _c.has(e.code) || typeof e.sqlState == "string" && fc.has(e.sqlState) || typeof e.message == "string" && hc.test(e.message)) return !0;
1466
1563
  t = e.cause;
1467
1564
  }
1468
1565
  return !1;
1469
- }, Qs = "voltro/expires", $s = () => ot({
1470
- id: Qs,
1471
- fields: { expiresAt: n().nullable() },
1566
+ }, bc = "voltro/expires", xc = () => ce({
1567
+ id: bc,
1568
+ fields: { expiresAt: w().nullable() },
1472
1569
  behaviors: { defaultWhere: () => "expiresAt IS NULL OR expiresAt > now()" }
1473
- }), ec = "voltro/localFirst", tc = () => ot({
1474
- id: ec,
1570
+ }), Sc = "voltro/localFirst", Cc = () => ce({
1571
+ id: Sc,
1475
1572
  fields: {}
1476
- }), nc = (e) => e.appliedMixins.some((e) => e.id === ec), rc = (e) => {
1573
+ }), wc = (e) => e.appliedMixins.some((e) => e.id === Sc), Tc = (e) => {
1477
1574
  let t = [];
1478
- for (let n of Object.values(e)) nc(n) && t.push(n.tableName);
1575
+ for (let n of Object.values(e)) wc(n) && t.push(n.tableName);
1479
1576
  return t;
1480
- }, ic = class extends jr.TaggedError("TableStreamError") {}, ac = 1e3, oc = (e, t, n, r) => {
1481
- let i = E.match(r, {
1577
+ }, Ec = class extends jr.TaggedError("TableStreamError") {}, Dc = 1e3, Oc = (e, t, n, r) => {
1578
+ let i = O.match(r, {
1482
1579
  onNone: () => e.where,
1483
- onSome: (n) => e.where ? gt(e.where, Mt(t, n)) : Mt(t, n)
1580
+ onSome: (n) => e.where ? Ct(e.where, Pn(t, n)) : Pn(t, n)
1484
1581
  });
1485
1582
  return {
1486
1583
  table: e.table,
@@ -1495,19 +1592,19 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1495
1592
  ...e.includeDeleted === void 0 ? {} : { includeDeleted: e.includeDeleted },
1496
1593
  ...e.crossTenant === void 0 ? {} : { crossTenant: e.crossTenant }
1497
1594
  };
1498
- }, sc = (e, t) => {
1499
- let n = t.pk ?? "id", r = t.chunkSize ?? ac;
1500
- return Fr.paginateChunkEffect(E.none(), (i) => {
1501
- let a = w.tryPromise({
1502
- try: () => e.query(oc(t, n, r, i)),
1503
- catch: (e) => new ic({
1595
+ }, kc = (e, t) => {
1596
+ let n = t.pk ?? "id", r = t.chunkSize ?? Dc;
1597
+ return Pr.paginate(O.none(), (i) => {
1598
+ let a = E.tryPromise({
1599
+ try: () => e.query(Oc(t, n, r, i)),
1600
+ catch: (e) => new Ec({
1504
1601
  table: t.table,
1505
1602
  cause: e
1506
1603
  })
1507
1604
  });
1508
- return (t.retry ? a.pipe(w.retry(t.retry)) : a).pipe(w.map((e) => [Ar.fromIterable(e), e.length === r && e.length > 0 ? E.some(E.some(e[e.length - 1][n])) : E.none()]));
1605
+ return (t.retry ? a.pipe(E.retry(t.retry)) : a).pipe(E.map((e) => [e, e.length === r && e.length > 0 ? O.some(O.some(e[e.length - 1][n])) : O.none()]));
1509
1606
  });
1510
- }, cc = (e) => {
1607
+ }, Ac = (e) => {
1511
1608
  let t = e.alpha ?? .5;
1512
1609
  if (t < 0 || t > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${t}`);
1513
1610
  return (n) => {
@@ -1521,7 +1618,7 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1521
1618
  queryText: e.vector.query,
1522
1619
  distance: e.vector.distance ?? "cosine",
1523
1620
  alpha: t
1524
- }, i = dr(n.table, e.fts.indexName, n.fullTextIndexes);
1621
+ }, i = d(n.table, e.fts.indexName, n.fullTextIndexes);
1525
1622
  return {
1526
1623
  ...n,
1527
1624
  annClause: r,
@@ -1534,17 +1631,17 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1534
1631
  }
1535
1632
  };
1536
1633
  };
1537
- }, lc = async (e, t) => {
1634
+ }, jc = async (e, t) => {
1538
1635
  let n = e.as ?? "embedding", r = t.row[e.from];
1539
1636
  if (typeof r != "string" || r.length === 0) return {};
1540
1637
  let i = await t.embed(r);
1541
1638
  return { [n]: i };
1542
- }, uc = (e) => {
1639
+ }, Mc = (e) => {
1543
1640
  if (!Number.isInteger(e.dimensions) || e.dimensions <= 0) throw Error(`vectorEmbedding: dimensions must be a positive integer, got ${String(e.dimensions)}.`);
1544
- let t = e.as ?? "embedding", n = (t) => lc(e, t);
1545
- return ot({
1641
+ let t = e.as ?? "embedding", n = (t) => jc(e, t);
1642
+ return ce({
1546
1643
  id: "voltro/vectorEmbedding",
1547
- fields: { [t]: Gt(e.dimensions) },
1644
+ fields: { [t]: On(e.dimensions) },
1548
1645
  ...e.index === !1 ? {} : { indexes: [{
1549
1646
  fields: [t],
1550
1647
  kind: "hnsw",
@@ -1559,19 +1656,19 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1559
1656
  beforeUpdate: n
1560
1657
  }
1561
1658
  });
1562
- }, dc = 63, fc = "br_pr", Y = class extends Error {
1659
+ }, Nc = 63, Pc = "br_pr", q = class extends Error {
1563
1660
  _tag = "BranchNameInvalid";
1564
1661
  constructor(e) {
1565
1662
  super(e), this.name = "BranchNameInvalid";
1566
1663
  }
1567
- }, pc = (e, t) => {
1568
- if (!Number.isInteger(t) || t < 0) throw new Y(`prNumber must be a non-negative integer, got ${String(t)}`);
1569
- let n = We(e);
1570
- if (n.replace(/_/g, "") === "") throw new Y(`app slug '${e}' has no usable identifier characters`);
1571
- let r = `${fc}${t}_${n}`;
1572
- if (r.length > dc) throw new Y(`branch namespace '${r}' exceeds the ${dc}-byte identifier limit — use a shorter app slug`);
1664
+ }, Fc = (e, t) => {
1665
+ if (!Number.isInteger(t) || t < 0) throw new q(`prNumber must be a non-negative integer, got ${String(t)}`);
1666
+ let n = ve(e);
1667
+ if (n.replace(/_/g, "") === "") throw new q(`app slug '${e}' has no usable identifier characters`);
1668
+ let r = `${Pc}${t}_${n}`;
1669
+ if (r.length > Nc) throw new q(`branch namespace '${r}' exceeds the ${Nc}-byte identifier limit — use a shorter app slug`);
1573
1670
  return r;
1574
- }, mc = (e) => e.startsWith(fc), hc = {
1671
+ }, Ic = (e) => e.startsWith(Pc), Lc = {
1575
1672
  requested: {
1576
1673
  provision: "provisioning",
1577
1674
  destroy: "destroying"
@@ -1590,19 +1687,19 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1590
1687
  fail: "failed"
1591
1688
  },
1592
1689
  destroyed: {}
1593
- }, gc = class extends Error {
1690
+ }, Rc = class extends Error {
1594
1691
  from;
1595
1692
  event;
1596
1693
  _tag = "BranchTransitionInvalid";
1597
1694
  constructor(e, t) {
1598
1695
  super(`invalid branch transition: ${e} --${t}-->`), this.from = e, this.event = t, this.name = "BranchTransitionInvalid";
1599
1696
  }
1600
- }, _c = (e, t) => {
1601
- let n = hc[e][t];
1602
- if (n === void 0) throw new gc(e, t);
1697
+ }, zc = (e, t) => {
1698
+ let n = Lc[e][t];
1699
+ if (n === void 0) throw new Rc(e, t);
1603
1700
  return n;
1604
- }, vc = (e, t, n, r, i = [], a = []) => {
1605
- if (n === "copy" && (r === void 0 || r === "")) throw new Y("seed 'copy' requires a parentNamespace to snapshot from");
1701
+ }, Bc = (e, t, n, r, i = [], a = []) => {
1702
+ if (n === "copy" && (r === void 0 || r === "")) throw new q("seed 'copy' requires a parentNamespace to snapshot from");
1606
1703
  let o = [{
1607
1704
  kind: "create-namespace",
1608
1705
  detail: e
@@ -1631,13 +1728,13 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1631
1728
  kind: "seed",
1632
1729
  detail: `run boot seeds into ${e}`
1633
1730
  }), o;
1634
- }, yc = (e) => {
1635
- if (!mc(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
1731
+ }, Vc = (e) => {
1732
+ if (!Ic(e)) throw new q(`refusing to plan teardown of '${e}' — not a branch namespace`);
1636
1733
  return [{
1637
1734
  kind: "drop-namespace",
1638
1735
  detail: e
1639
1736
  }];
1640
- }, bc = (e) => {
1737
+ }, Hc = (e) => {
1641
1738
  if (e === void 0 || e === "") return !1;
1642
1739
  try {
1643
1740
  let t = new URL(e).hostname.toLowerCase();
@@ -1645,27 +1742,27 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1645
1742
  } catch {
1646
1743
  return /\bneon\.(tech|build)\b/i.test(e);
1647
1744
  }
1648
- }, xc = (e) => e.prefer === void 0 ? e.seed === "copy" && bc(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, Sc = (e, t = {}) => [{
1745
+ }, Uc = (e) => e.prefer === void 0 ? e.seed === "copy" && Hc(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, Wc = (e, t = {}) => [{
1649
1746
  kind: "neon-branch-create",
1650
1747
  detail: `${t.parentBranch ?? "main"} → ${e} (copy-on-write)`
1651
- }], Cc = (e) => {
1652
- if (!mc(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
1748
+ }], Gc = (e) => {
1749
+ if (!Ic(e)) throw new q(`refusing to plan teardown of '${e}' — not a branch namespace`);
1653
1750
  return [{
1654
1751
  kind: "neon-branch-delete",
1655
1752
  detail: e
1656
1753
  }];
1657
- }, wc = (e) => e.mechanism === "neon-cow" ? Sc(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : vc(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), Tc = (e, t) => e === "neon-cow" ? Cc(t) : yc(t), Ec = (e, t, n) => {
1754
+ }, Kc = (e) => e.mechanism === "neon-cow" ? Wc(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : Bc(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), qc = (e, t) => e === "neon-cow" ? Gc(t) : Vc(t), Jc = (e, t, n) => {
1658
1755
  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);
1659
1756
  return {
1660
1757
  evict: i,
1661
1758
  rejectNew: r.filter((e) => !a.has(e.namespace)).length >= t.maxBranches
1662
1759
  };
1663
- }, Dc = async (e, t) => {
1664
- let n = pc(e.appSlug, e.prNumber), r = xc({
1760
+ }, Yc = async (e, t) => {
1761
+ let n = Fc(e.appSlug, e.prNumber), r = Uc({
1665
1762
  seed: e.seed,
1666
1763
  ...e.dbUrl === void 0 ? {} : { dbUrl: e.dbUrl },
1667
1764
  ...e.prefer === void 0 ? {} : { prefer: e.prefer }
1668
- }), i = wc({
1765
+ }), i = Kc({
1669
1766
  mechanism: r,
1670
1767
  branchId: n,
1671
1768
  tableNames: e.tableNames,
@@ -1694,16 +1791,16 @@ var Br = (e) => typeof e == "string" && e !== "" ? e : null, Vr = async (e, t, n
1694
1791
  mechanism: r,
1695
1792
  steps: i
1696
1793
  };
1697
- }, Oc = async (e, t, n) => {
1698
- let r = Tc(t, e);
1794
+ }, Xc = async (e, t, n) => {
1795
+ let r = qc(t, e);
1699
1796
  return t === "neon-cow" ? await n.neonBranchDelete(e) : await n.dropNamespace(e), r;
1700
- }, kc = (e, t, n) => Ec(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, Ac = {
1797
+ }, Zc = (e, t, n) => Jc(e, t, n), J = (e) => `"${e.replace(/"/g, "\"\"")}"`, Qc = {
1701
1798
  cascade: "CASCADE",
1702
1799
  restrict: "RESTRICT",
1703
1800
  setNull: "SET NULL",
1704
1801
  noAction: "NO ACTION"
1705
- }, Z = (e) => `'${e.replace(/'/g, "''")}'`, jc = (e, t) => {
1706
- let n = t.columns.map(Z).join(", ");
1802
+ }, Y = (e) => `'${e.replace(/'/g, "''")}'`, $c = (e, t) => {
1803
+ let n = t.columns.map(Y).join(", ");
1707
1804
  return `DO $voltro_branch$
1708
1805
  DECLARE derived name;
1709
1806
  BEGIN
@@ -1712,11 +1809,12 @@ BEGIN
1712
1809
  JOIN pg_class i ON i.oid = x.indexrelid
1713
1810
  JOIN pg_class c ON c.oid = x.indrelid
1714
1811
  JOIN pg_namespace nsp ON nsp.oid = c.relnamespace
1715
- WHERE nsp.nspname = ${Z(e)}
1716
- AND c.relname = ${Z(t.table)}
1812
+ WHERE nsp.nspname = ${Y(e)}
1813
+ AND c.relname = ${Y(t.table)}
1717
1814
  AND NOT x.indisprimary
1718
1815
  AND x.indisunique = ${t.unique ? "true" : "false"}
1719
- AND i.relname <> ${Z(t.name)}
1816
+ AND i.relname <> ${Y(t.name)}
1817
+ AND pg_get_expr(x.indpred, x.indrelid) IS NOT DISTINCT FROM ${t.where === void 0 ? "NULL" : Y(t.where)}
1720
1818
  AND (
1721
1819
  SELECT array_agg(att.attname::text ORDER BY k.ord)
1722
1820
  FROM unnest(x.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord)
@@ -1725,39 +1823,39 @@ BEGIN
1725
1823
  LIMIT 1;
1726
1824
  IF derived IS NOT NULL THEN
1727
1825
  EXECUTE format('ALTER INDEX %I.%I RENAME TO %I',
1728
- ${Z(e)}, derived, ${Z(t.name)});
1826
+ ${Y(e)}, derived, ${Y(t.name)});
1729
1827
  END IF;
1730
1828
  END
1731
1829
  $voltro_branch$`;
1732
- }, Mc = (e, t) => {
1733
- let n = t.onDelete === void 0 ? "" : ` ON DELETE ${Ac[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${Ac[t.onUpdate]}`;
1734
- 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}`;
1735
- }, Nc = (e) => {
1830
+ }, el = (e, t) => {
1831
+ let n = t.onDelete === void 0 ? "" : ` ON DELETE ${Qc[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${Qc[t.onUpdate]}`;
1832
+ return `ALTER TABLE ${J(e)}.${J(t.table)} ADD FOREIGN KEY (${J(t.column)}) REFERENCES ${J(e)}.${J(t.targetTable)} (${J(t.targetColumn)})${n}${r}`;
1833
+ }, tl = (e) => {
1736
1834
  let t = () => {
1737
1835
  throw Error("namespace branch executor: Neon ops require a neon-cow executor (use a Neon connection for copy-on-write branches)");
1738
1836
  };
1739
1837
  return {
1740
- createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${X(t)}`),
1741
- createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${X(t)}.${X(n)} (LIKE ${X(n)} INCLUDING ALL)`),
1742
- copyTable: (t, n, r) => e.run(`INSERT INTO ${X(n)}.${X(r)} SELECT * FROM ${X(t)}.${X(r)}`),
1743
- addForeignKey: (t, n) => e.run(Mc(t, n)),
1744
- restoreIndexName: (t, n) => e.run(jc(t, n)),
1745
- dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${X(t)} CASCADE`),
1838
+ createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${J(t)}`),
1839
+ createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${J(t)}.${J(n)} (LIKE ${J(n)} INCLUDING ALL)`),
1840
+ copyTable: (t, n, r) => e.run(`INSERT INTO ${J(n)}.${J(r)} SELECT * FROM ${J(t)}.${J(r)}`),
1841
+ addForeignKey: (t, n) => e.run(el(t, n)),
1842
+ restoreIndexName: (t, n) => e.run($c(t, n)),
1843
+ dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${J(t)} CASCADE`),
1746
1844
  neonBranchCreate: t,
1747
1845
  neonBranchDelete: t
1748
1846
  };
1749
- }, Pc = class extends Error {
1847
+ }, nl = class extends Error {
1750
1848
  _tag = "TenantResidencyUnresolved";
1751
1849
  constructor(e) {
1752
1850
  super(e), this.name = "TenantResidencyUnresolved";
1753
1851
  }
1754
- }, Fc = class extends Error {
1852
+ }, rl = class extends Error {
1755
1853
  region;
1756
1854
  _tag = "TenantRegionUnavailable";
1757
1855
  constructor(e, t) {
1758
1856
  super(t), this.region = e, this.name = "TenantRegionUnavailable";
1759
1857
  }
1760
- }, Ic, Lc = (e) => {
1858
+ }, il, al = (e) => {
1761
1859
  if (e.homes === void 0) throw Error("setResidencyConfig: `homes` is required");
1762
1860
  if (e.servableRegions === void 0 || e.servableRegions.length === 0) throw Error("setResidencyConfig: `servableRegions` must be non-empty (which regions this deployment serves)");
1763
1861
  let t = /* @__PURE__ */ new Map();
@@ -1766,98 +1864,98 @@ $voltro_branch$`;
1766
1864
  if (e !== void 0 && e !== n.region) throw Error(`residency: tenant '${n.tenantId}' is mapped to two regions ('${e}' and '${n.region}')`);
1767
1865
  t.set(n.tenantId, n.region);
1768
1866
  }
1769
- return Ic = e, e;
1770
- }, Rc = () => Ic, zc = () => {
1771
- Ic = void 0;
1772
- }, Bc = (e, t) => {
1773
- if (e == null || e === "") throw new Pc("residency is on but the request has no resolvable tenant — refusing to bind a store");
1867
+ return il = e, e;
1868
+ }, ol = () => il, sl = () => {
1869
+ il = void 0;
1870
+ }, cl = (e, t) => {
1871
+ if (e == null || e === "") throw new nl("residency is on but the request has no resolvable tenant — refusing to bind a store");
1774
1872
  let n = t.homes.find((t) => t.tenantId === e);
1775
- if (n === void 0) throw new Pc(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
1873
+ if (n === void 0) throw new nl(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
1776
1874
  return n;
1777
- }, Vc = (e, t) => t.servableRegions.includes(e), Hc = (e, t) => {
1778
- let n = Bc(e.tenantId, t), r = Ie(n.tenantId);
1875
+ }, ll = (e, t) => t.servableRegions.includes(e), ul = (e, t) => {
1876
+ let n = cl(e.tenantId, t), r = oe(n.tenantId);
1779
1877
  return {
1780
1878
  region: n.region,
1781
1879
  namespace: r,
1782
1880
  ...n.connectionKey === void 0 ? {} : { connectionKey: n.connectionKey }
1783
1881
  };
1784
- }, Uc = (e, t, n) => {
1785
- let r = Hc(e, t);
1786
- if (!Vc(r.region, t)) throw new Fc(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
1882
+ }, dl = (e, t, n) => {
1883
+ let r = ul(e, t);
1884
+ if (!ll(r.region, t)) throw new rl(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
1787
1885
  let i = n.get(r.region);
1788
- if (i === void 0) throw new Fc(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
1886
+ if (i === void 0) throw new rl(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
1789
1887
  return {
1790
1888
  store: i,
1791
1889
  placement: r
1792
1890
  };
1793
- }, Wc = async (e, t, n, r) => {
1794
- let { store: i, placement: a } = Uc(e, t, n);
1891
+ }, fl = async (e, t, n, r) => {
1892
+ let { store: i, placement: a } = dl(e, t, n);
1795
1893
  return await r(i, a), a;
1796
- }, Gc = (e) => {
1894
+ }, X = (e) => {
1797
1895
  if (typeof e == "string") return e;
1798
1896
  if ("jsonPath" in e) {
1799
1897
  let { column: t, path: n, numeric: r } = e.jsonPath;
1800
1898
  return `(json:${t}->${n.join(".")}${r ? "::num" : ""})`;
1801
1899
  }
1802
1900
  return `(${e.expr})`;
1803
- }, Q = (e) => e.map(Gc), Kc = (e, t) => {
1901
+ }, Z = (e) => e.map(X), pl = (e, t) => {
1804
1902
  if (e.length !== t.length) return !1;
1805
- for (let n = 0; n < e.length; n++) if (Gc(e[n]) !== Gc(t[n])) return !1;
1903
+ for (let n = 0; n < e.length; n++) if (X(e[n]) !== X(t[n])) return !1;
1806
1904
  return !0;
1807
- }, qc = (e, t) => {
1905
+ }, ml = (e, t) => {
1808
1906
  if (e.length >= t.length) return !1;
1809
- for (let n = 0; n < e.length; n++) if (Gc(e[n]) !== Gc(t[n])) return !1;
1907
+ for (let n = 0; n < e.length; n++) if (X(e[n]) !== X(t[n])) return !1;
1810
1908
  return !0;
1811
- }, Jc = (e) => {
1909
+ }, hl = (e) => {
1812
1910
  let t = [], n = e.appliedIndexes, r = e.tableName;
1813
1911
  for (let e = 0; e < n.length; e++) {
1814
1912
  let i = n[e];
1815
1913
  for (let a = e + 1; a < n.length; a++) {
1816
1914
  let e = n[a];
1817
- if (Kc(i.fields, e.fields)) {
1915
+ if (pl(i.fields, e.fields)) {
1818
1916
  let [n, a] = i.name < e.name ? [i, e] : [e, i];
1819
1917
  t.push({
1820
1918
  kind: "duplicate-fields",
1821
1919
  table: r,
1822
1920
  redundant: n,
1823
1921
  coveredBy: a,
1824
- message: `'${r}' has two indexes on the same fields [${Q(i.fields).join(", ")}]: '${i.name}' and '${e.name}'. The B-tree engine builds both, costing write throughput + disk space for no read benefit. Drop '${n.name}' (or '${a.name}' if you prefer the other name). Applies to every supported dialect (Postgres / MySQL / MariaDB / MSSQL / SQLite).`
1922
+ message: `'${r}' has two indexes on the same fields [${Z(i.fields).join(", ")}]: '${i.name}' and '${e.name}'. The B-tree engine builds both, costing write throughput + disk space for no read benefit. Drop '${n.name}' (or '${a.name}' if you prefer the other name). Applies to every supported dialect (Postgres / MySQL / MariaDB / MSSQL / SQLite).`
1825
1923
  });
1826
1924
  continue;
1827
1925
  }
1828
- qc(i.fields, e.fields) ? t.push({
1926
+ ml(i.fields, e.fields) ? t.push({
1829
1927
  kind: "redundant-prefix",
1830
1928
  table: r,
1831
1929
  redundant: i,
1832
1930
  coveredBy: e,
1833
- 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).`
1834
- }) : qc(e.fields, i.fields) && t.push({
1931
+ message: `'${r}' index '${i.name}' on [${Z(i.fields).join(", ")}] is a leading prefix of '${e.name}' on [${Z(e.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Z(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).`
1932
+ }) : ml(e.fields, i.fields) && t.push({
1835
1933
  kind: "redundant-prefix",
1836
1934
  table: r,
1837
1935
  redundant: e,
1838
1936
  coveredBy: i,
1839
- message: `'${r}' index '${e.name}' on [${Q(e.fields).join(", ")}] is a leading prefix of '${i.name}' on [${Q(i.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Q(e.fields).join(", ")}] query from '${i.name}' too via the leading-prefix rule, so '${e.name}' adds write cost without read benefit. Drop '${e.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
1937
+ message: `'${r}' index '${e.name}' on [${Z(e.fields).join(", ")}] is a leading prefix of '${i.name}' on [${Z(i.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Z(e.fields).join(", ")}] query from '${i.name}' too via the leading-prefix rule, so '${e.name}' adds write cost without read benefit. Drop '${e.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
1840
1938
  });
1841
1939
  }
1842
1940
  }
1843
1941
  return t;
1844
- }, Yc = (e) => {
1942
+ }, gl = (e) => {
1845
1943
  let t = [];
1846
- for (let n of e) t.push(...Jc(n));
1944
+ for (let n of e) t.push(...hl(n));
1847
1945
  return t;
1848
- }, Xc = "\x1B[", Zc = `${Xc}38;2;245;158;11m`, Qc = `${Xc}38;2;16;185;129m`, $c = (e, t) => `${e}${t}${O.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : $c(t, n) : n, el = (e, t = {}) => {
1849
- 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, Qc, e), c = (e) => $(n, Zc, 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) => {
1946
+ }, _l = "\x1B[", vl = `${_l}38;2;245;158;11m`, yl = `${_l}38;2;16;185;129m`, bl = (e, t) => `${e}${t}${A.reset}`, Q = (e, t, n) => e ? typeof t == "function" ? t(n) : bl(t, n) : n, xl = (e, t = {}) => {
1947
+ let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => Q(n, A.dim, e.padEnd(11)), a = (e) => Q(n, (e) => A.bold(A.brand(e)), e), o = (e) => Q(n, A.brightRed24, e), s = (e) => Q(n, yl, e), c = (e) => Q(n, vl, e), l = (e) => Q(n, A.dim, e), u = `${c("index audit")} ${l("·")} ${Q(n, A.bold, e.kind)}`, d = e.redundant.fields.length, f = Z(e.coveredBy.fields.slice(d)), p = (e, t) => {
1850
1948
  let n = e.slice(0, t), r = e.slice(t), i = [];
1851
1949
  return n.length > 0 && i.push(s(`[${n.join(", ")}]`)), r.length > 0 && i.push(c(`+ [${r.join(", ")}]`)), i.join(" ");
1852
1950
  }, m = [];
1853
- 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");
1854
- }, tl = (e, { apply: t, undo: n }) => ({
1951
+ 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(Z(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Z(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 ${Q(n, A.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");
1952
+ }, Sl = (e, { apply: t, undo: n }) => ({
1855
1953
  name: e,
1856
1954
  apply: t,
1857
1955
  undo: n
1858
- }), nl = (e) => {
1956
+ }), Cl = (e) => {
1859
1957
  if (!/^\d{14}_/.test(e.id)) throw Error(`migration "${e.id}": id must start with a 14-digit timestamp followed by "_" (convention: <YYYYMMDDHHMMSS>_<slug>)`);
1860
- let t = e.steps({ step: tl });
1958
+ let t = e.steps({ step: Sl });
1861
1959
  if (t.length === 0) throw Error(`migration "${e.id}": at least one step is required`);
1862
1960
  return {
1863
1961
  __migration: !0,
@@ -1865,43 +1963,43 @@ $voltro_branch$`;
1865
1963
  name: e.name,
1866
1964
  steps: t
1867
1965
  };
1868
- }, rl = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, il = mr.tableName, al = (e) => Ir("sha256").update(`${e.type}\u0000${e.id}`, "utf8").digest("hex"), ol = async (e, t) => {
1966
+ }, wl = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Tl = mr.tableName, El = (e) => Ir("sha256").update(`${e.type}\u0000${e.id}`, "utf8").digest("hex"), Dl = async (e, t) => {
1869
1967
  let [n] = await e.query({
1870
- table: il,
1871
- predicate: On("id", al(t)),
1968
+ table: Tl,
1969
+ predicate: Wn("id", El(t)),
1872
1970
  order: [],
1873
1971
  take: 1,
1874
1972
  skip: void 0,
1875
1973
  projection: void 0
1876
1974
  }), r = n?.tenantId;
1877
1975
  return typeof r == "string" ? r : null;
1878
- }, sl = async (e, t, n) => {
1879
- await e.upsert(il, {
1880
- id: al(t),
1976
+ }, Ol = async (e, t, n) => {
1977
+ await e.upsert(Tl, {
1978
+ id: El(t),
1881
1979
  subjectType: t.type,
1882
1980
  subjectId: t.id,
1883
1981
  tenantId: n,
1884
1982
  selectedAt: /* @__PURE__ */ new Date()
1885
1983
  }, { conflictColumns: ["id"] });
1886
- }, cl = async (e, t) => {
1887
- await e.delete(il, al(t));
1888
- }, ll = "id", ul = (e, t) => {
1889
- let n = a(e);
1984
+ }, kl = async (e, t) => {
1985
+ await e.delete(Tl, El(t));
1986
+ }, $ = "id", Al = (e, t) => {
1987
+ let n = je(e);
1890
1988
  if (n === void 0) return t;
1891
- let r = n.fields[ll]?.idScheme;
1892
- if (r === void 0 || t[ll] != null) return t;
1989
+ let r = n.fields[$]?.idScheme;
1990
+ if (r === void 0 || t[$] != null) return t;
1893
1991
  if (r.kind === "numeric") {
1894
- if (!(ll in t)) return t;
1992
+ if (!($ in t)) return t;
1895
1993
  let e = { ...t };
1896
- return delete e[ll], e;
1994
+ return delete e[$], e;
1897
1995
  }
1898
- let i = Rn(r, e);
1996
+ let i = xt(r, e);
1899
1997
  return i === null ? t : {
1900
1998
  ...t,
1901
- [ll]: i
1999
+ [$]: i
1902
2000
  };
1903
- }, dl = (e, t) => t.map((t) => ul(e, t)), fl = {
1904
- postgres: { maxBindParameters: 65535 },
2001
+ }, jl = (e, t) => t.map((t) => Al(e, t)), Ml = {
2002
+ postgres: { maxBindParameters: 32767 },
1905
2003
  mysql: { maxBindParameters: 65535 },
1906
2004
  mariadb: { maxBindParameters: 65535 },
1907
2005
  mssql: {
@@ -1910,26 +2008,31 @@ $voltro_branch$`;
1910
2008
  },
1911
2009
  sqlite: { maxBindParameters: 32766 },
1912
2010
  turso: { maxBindParameters: 32766 }
1913
- }, pl = (e) => fl[e], ml = (e) => {
2011
+ }, Nl = (e) => Ml[e], Pl = (e) => {
1914
2012
  let t = /* @__PURE__ */ new Set();
1915
2013
  for (let n of e) for (let e of Object.keys(n)) t.add(e);
1916
2014
  return t.size;
1917
- }, hl = (e, t) => {
2015
+ }, Fl = (e, t) => {
1918
2016
  if (t === void 0 || e.length === 0) return [e];
1919
- let n = Math.max(1, ml(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2017
+ let n = Math.max(1, Pl(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
1920
2018
  if (e.length <= a) return [e];
1921
2019
  let o = [];
1922
2020
  for (let t = 0; t < e.length; t += a) o.push(e.slice(t, t + a));
1923
2021
  return o;
1924
- }, gl = (e, t) => {
2022
+ }, Il = (e, t) => {
1925
2023
  let n = [], r = t;
1926
2024
  for (let [t, i] of Object.entries(e.fields)) {
1927
2025
  let e = i;
1928
2026
  e.nullable || e.hasDefault || e.idScheme !== void 0 || e.generatedAs !== void 0 || (r[t] === void 0 || r[t] === null) && n.push(t);
1929
2027
  }
1930
2028
  return n;
1931
- }, _l = (e, t, n) => {
1932
- let r = n, i = new Set(e === void 0 ? [] : Object.entries(e.fields).filter(([, e]) => e.generatedAs !== void 0).map(([e]) => e)), a = [];
2029
+ }, Ll = (e, t, n) => {
2030
+ let r = n, i = /* @__PURE__ */ new Set();
2031
+ if (e !== void 0) {
2032
+ let n = e.fields;
2033
+ for (let e of new Set(t)) Object.getOwnPropertyDescriptor(n, e)?.enumerable && n[e]?.generatedAs !== void 0 && i.add(e);
2034
+ }
2035
+ let a = [];
1933
2036
  for (let e of t) i.has(e) || (r[e] === void 0 ? a.push({
1934
2037
  column: e,
1935
2038
  reason: "absent"
@@ -1938,36 +2041,36 @@ $voltro_branch$`;
1938
2041
  reason: "null"
1939
2042
  }));
1940
2043
  return a;
1941
- }, vl = (e, t, n) => e.insert(t.tableName, n), yl = (e, t, n) => e.insertMany(t.tableName, n), bl = (e, t, n, r) => e.upsert(t.tableName, n, {
2044
+ }, Rl = (e, t, n) => e.insert(t.tableName, n), zl = (e, t, n) => e.insertMany(t.tableName, n), Bl = (e, t, n, r) => e.upsert(t.tableName, n, {
1942
2045
  conflictColumns: r.conflictColumns,
1943
2046
  ...r.update === void 0 ? {} : { update: r.update },
1944
2047
  ...r.updateValues === void 0 ? {} : { updateValues: r.updateValues }
1945
- }), xl = async (e, t, n, r) => {
1946
- if (e.upsertWithOutcome === void 0) throw C("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.");
2048
+ }), Vl = async (e, t, n, r) => {
2049
+ if (e.upsertWithOutcome === void 0) throw S("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.");
1947
2050
  return e.upsertWithOutcome(t.tableName, n, {
1948
2051
  conflictColumns: r.conflictColumns,
1949
2052
  ...r.update === void 0 ? {} : { update: r.update },
1950
2053
  ...r.updateValues === void 0 ? {} : { updateValues: r.updateValues }
1951
2054
  });
1952
- }, Sl = async (e, t, n, r) => e.insertIgnoreWithOutcome(t.tableName, n, { conflictColumns: r.conflictColumns }), Cl = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), wl = 512, Tl = (e) => {
2055
+ }, Hl = async (e, t, n, r) => e.insertIgnoreWithOutcome(t.tableName, n, { conflictColumns: r.conflictColumns }), Ul = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), Wl = 512, Gl = (e) => {
1953
2056
  e.setMaxListeners(512);
1954
- }, El = (e, t, n) => ({
2057
+ }, Kl = (e, t, n) => ({
1955
2058
  _tag: "PrimaryKeyConflictError",
1956
2059
  table: e,
1957
2060
  key: t,
1958
2061
  cause: n
1959
- }), Dl = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", Ol = {
2062
+ }), ql = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", Jl = {
1960
2063
  postgres: 5432,
1961
2064
  mysql: 3306,
1962
2065
  mariadb: 3306,
1963
2066
  mssql: 1433
1964
- }, kl = /* @__PURE__ */ new Set([
2067
+ }, Yl = /* @__PURE__ */ new Set([
1965
2068
  "localhost",
1966
2069
  "127.0.0.1",
1967
2070
  "::1",
1968
2071
  "[::1]",
1969
2072
  "0.0.0.0"
1970
- ]), Al = (e) => {
2073
+ ]), Xl = (e) => {
1971
2074
  let t = e.host, n = e.port, r = e.database;
1972
2075
  if (e.url !== void 0 && e.url !== "") try {
1973
2076
  let i = new URL(e.url);
@@ -1976,29 +2079,29 @@ $voltro_branch$`;
1976
2079
  return;
1977
2080
  }
1978
2081
  if (t === void 0 || t === "" || r === void 0 || r === "") return;
1979
- let i = n ?? Ol[(e.dialect ?? "").toLowerCase()];
2082
+ let i = n ?? Jl[(e.dialect ?? "").toLowerCase()];
1980
2083
  if (i === void 0 || !Number.isFinite(i)) return;
1981
2084
  let a = t.toLowerCase();
1982
2085
  return {
1983
- host: kl.has(a) ? "localhost" : a,
2086
+ host: Yl.has(a) ? "localhost" : a,
1984
2087
  port: i,
1985
2088
  database: r.toLowerCase()
1986
2089
  };
1987
- }, jl = (e) => {
1988
- let t = Al(e);
2090
+ }, Zl = (e) => {
2091
+ let t = Xl(e);
1989
2092
  if (t !== void 0) return Ir("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
1990
- }, Ml = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", Nl = {
2093
+ }, Ql = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", $l = {
1991
2094
  app: 3,
1992
2095
  plugin: 2,
1993
2096
  framework: 1
1994
- }, Pl = /* @__PURE__ */ new Map(), Fl = [], Il = () => [...Fl], Ll = (e) => {
2097
+ }, eu = /* @__PURE__ */ new Map(), tu = [], nu = () => [...tu], ru = (e) => {
1995
2098
  if (!e.table || !e.timeColumn) throw Error("registerRetention: table + timeColumn are required");
1996
2099
  if (!Number.isFinite(e.ttlMs) || e.ttlMs <= 0) throw Error(`registerRetention(${e.table}): ttlMs must be a positive number`);
1997
- let t = e.source ?? "app", n = Pl.get(e.table);
2100
+ let t = e.source ?? "app", n = eu.get(e.table);
1998
2101
  if (n !== void 0) {
1999
2102
  let r = n.source ?? "app", i = n.ttlMs !== e.ttlMs || n.timeColumn !== e.timeColumn || JSON.stringify(n.activityColumns ?? []) !== JSON.stringify(e.activityColumns ?? []) || JSON.stringify(n.where) !== JSON.stringify(e.where);
2000
- if (Nl[t] < Nl[r]) {
2001
- i && Fl.push({
2103
+ if ($l[t] < $l[r]) {
2104
+ i && tu.push({
2002
2105
  table: e.table,
2003
2106
  kept: {
2004
2107
  source: r,
@@ -2011,7 +2114,7 @@ $voltro_branch$`;
2011
2114
  });
2012
2115
  return;
2013
2116
  }
2014
- i && r !== t && Fl.push({
2117
+ i && r !== t && tu.push({
2015
2118
  table: e.table,
2016
2119
  kept: {
2017
2120
  source: t,
@@ -2023,59 +2126,59 @@ $voltro_branch$`;
2023
2126
  }
2024
2127
  });
2025
2128
  }
2026
- Pl.set(e.table, {
2129
+ eu.set(e.table, {
2027
2130
  ...e,
2028
2131
  source: t
2029
2132
  });
2030
- }, Rl = () => [...Pl.values()], zl = () => {
2031
- Pl.clear(), Fl.length = 0;
2032
- }, Bl = async (e, t, n, r = 2e4) => {
2033
- let i = new Date(t - e.ttlMs), a = (e.activityColumns ?? []).map((e) => _r(tr(e), Qt(e, i))), o = a.length === 0 ? e.where : gt(...e.where === void 0 ? [] : [e.where], ...a), s = 0;
2133
+ }, iu = () => [...eu.values()], au = () => {
2134
+ eu.clear(), tu.length = 0;
2135
+ }, ou = async (e, t, n, r = 2e4) => {
2136
+ let i = new Date(t - e.ttlMs), a = (e.activityColumns ?? []).map((e) => Lt(Gt(e), Rn(e, i))), o = a.length === 0 ? e.where : Ct(...e.where === void 0 ? [] : [e.where], ...a), s = 0;
2034
2137
  try {
2035
2138
  for (;;) {
2036
2139
  let t = await n(e.table, e.timeColumn, i, r, o);
2037
2140
  if (s += t, t < r) break;
2038
2141
  }
2039
2142
  } catch (t) {
2040
- throw w.runSync(T.increment(T.tagged(Hl, "table", e.table))), t;
2143
+ throw E.runSync(D.update(D.withAttributes(cu, { table: e.table }), 1)), t;
2041
2144
  }
2042
- return s > 0 && w.runSync(T.incrementBy(T.tagged(Vl, "table", e.table), s)), s;
2043
- }, Vl = T.counter("voltro_retention_swept_rows_total"), Hl = T.counter("voltro_retention_sweep_errors_total"), Ul = (e, t) => {
2145
+ return s > 0 && E.runSync(D.update(D.withAttributes(su, { table: e.table }), s)), s;
2146
+ }, su = D.counter("voltro_retention_swept_rows_total"), cu = D.counter("voltro_retention_sweep_errors_total"), lu = (e, t) => {
2044
2147
  let n = Number(e ?? String(t));
2045
2148
  return (Number.isFinite(n) && n > 0 ? n : t) * 36e5;
2046
- }, Wl = "_voltro_cdc_offsets", Gl = x(Wl, {
2047
- id: br({ prefix: "cdcoff" }),
2048
- replicaId: b(),
2049
- streamName: b(),
2050
- binlogFile: b(),
2051
- binlogPosition: b(),
2052
- updatedAt: n()
2053
- }).index(["replicaId"]), Kl = x(Wl, {
2054
- id: br({ prefix: "cdcoff" }),
2055
- replicaId: b(),
2056
- streamName: b(),
2057
- ctVersion: b(),
2058
- updatedAt: n()
2059
- }).index(["replicaId"]), ql = "_voltro_data_transfers", Jl = x(ql, {
2060
- id: br({ prefix: "dimp" }),
2061
- startedAt: n().default("now"),
2062
- finishedAt: n().nullable(),
2063
- direction: b().default("import"),
2064
- mode: b(),
2065
- via: b(),
2066
- bundle: b().nullable(),
2067
- sourceFingerprint: b().nullable(),
2068
- tablesWritten: u().default(0),
2069
- rowsWritten: u().default(0),
2070
- failure: b().nullable(),
2071
- staged: rt().nullable()
2072
- }).renamedFrom("_voltro_data_imports").nonReactive(), Yl = (e) => {
2149
+ }, uu = "_voltro_cdc_offsets", du = b(uu, {
2150
+ id: dt({ prefix: "cdcoff" }),
2151
+ replicaId: x(),
2152
+ streamName: x(),
2153
+ binlogFile: x(),
2154
+ binlogPosition: x(),
2155
+ updatedAt: w()
2156
+ }).index(["replicaId"]), fu = b(uu, {
2157
+ id: dt({ prefix: "cdcoff" }),
2158
+ replicaId: x(),
2159
+ streamName: x(),
2160
+ ctVersion: x(),
2161
+ updatedAt: w()
2162
+ }).index(["replicaId"]), pu = "_voltro_data_transfers", mu = b(pu, {
2163
+ id: dt({ prefix: "dimp" }),
2164
+ startedAt: w().default("now"),
2165
+ finishedAt: w().nullable(),
2166
+ direction: x().default("import"),
2167
+ mode: x(),
2168
+ via: x(),
2169
+ bundle: x().nullable(),
2170
+ sourceFingerprint: x().nullable(),
2171
+ tablesWritten: pe().default(0),
2172
+ rowsWritten: pe().default(0),
2173
+ failure: x().nullable(),
2174
+ staged: g().nullable()
2175
+ }).renamedFrom("_voltro_data_imports").nonReactive(), hu = (e) => {
2073
2176
  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)";
2074
2177
  return `${t} · ${r} · via ${e.via}${i}` + (e.bundle === null ? "" : ` · from ${e.bundle}`) + (e.sourceFingerprint === null ? "" : ` · source schema ${e.sourceFingerprint}`);
2075
- }, Xl = 255, Zl = (e) => e == null ? "null" : typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? JSON.stringify(e) : Array.isArray(e) ? `[${e.map(Zl).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)}:${Zl(t)}`).join(",")}}` : JSON.stringify(String(e)), Ql = (e) => {
2178
+ }, gu = 255, _u = (e) => e == null ? "null" : typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? JSON.stringify(e) : Array.isArray(e) ? `[${e.map(_u).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)}:${_u(t)}`).join(",")}}` : JSON.stringify(String(e)), vu = (e) => {
2076
2179
  if (e == null) return null;
2077
- let t = typeof e == "string" ? e : Zl(e);
2180
+ let t = typeof e == "string" ? e : _u(e);
2078
2181
  return t.length > 255 ? t.slice(0, 255) : t;
2079
- }, $l = "postgres";
2182
+ }, yu = "postgres";
2080
2183
  //#endregion
2081
- export { yr as AUTO_FILLED_COLUMNS, qr as BOUND_ENCRYPTED_PREFIX, fl as BULK_INSERT_LIMITS, Y as BranchNameInvalid, gc as BranchTransitionInvalid, Wl as CDC_OFFSETS_TABLE, Ao as CHANGE_CLAIM_TTL_ENV, wl as CHANGE_LISTENER_CEILING, fr as ColumnBuilder, ql as DATA_TRANSFERS_TABLE, oe as DEFAULT_ACQUIRE_TIMEOUT_MS, jo as DEFAULT_CHANGE_CLAIM_TTL_HOURS, Os as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, ur as DEFAULT_SOFT_DROP_RETENTION_DAYS, Li as DEFAULT_SUBJECT_GRAPH_DEPTH, Kr as ENCRYPTED_PREFIX, $l as ENGINE, na as EagerCardinalityError, un as FILE_MIGRATION_PATTERN, Ze as FRAMEWORK_LIVE_TABLES, Xr as FieldDecryptionError, Qo as ID_COLUMN_MAX_LENGTH, Er as INITIAL_VERSION, ke as IrreversibleMigrationError, yt as MATCHES_NO_ROWS, Ct as MAX_IDENTIFIER_LENGTH, Ne as MIGRATION_PHASES, Gs as MSSQL_TRANSIENT_NUMBERS, Us as MYSQL_TRANSIENT_CODES, Ve as MigrationExpectationFailed, ae as MigrationNeedsSqlClient, me as MigrationSkipped, ko as OccurrenceCounter, Ws as POSTGRES_TRANSIENT_STATES, Jn as REPLACE_IN_PROGRESS_TABLE, Te as RewriteUnstableError, Xl as SCOPE_KEY_MAX_LENGTH, $e as SELF_REFERENCE_TARGET, Ks as SQLITE_TRANSIENT_CODES, Tn as STAGING_STALE_MINUTES, f as STAGING_TABLE_PREFIX, zr as SqlClient, il as TENANT_SELECTIONS_TABLE, qs as TURSO_TRANSIENT_MESSAGE, ic as TableStreamError, s as TenantNamespaceInvalid, pn as TenantNamespaceUnresolved, Fc as TenantRegionUnavailable, Pc as TenantResidencyUnresolved, Ls as TransactionAbortedError, qe as TransactionBrokenByBodyError, Qs as VOLTRO_EXPIRES_MIXIN_ID, ec as VOLTRO_LOCAL_FIRST_MIXIN_ID, Cr as VersionConflict, Ke as WARN_IDENTIFIER_LENGTH, _n as _voltroApiKeysTable, Gl as _voltroCdcOffsetsTable, Jl as _voltroDataTransfersTable, Qn as _voltroDevicesTable, Vt as _voltroIdempotencyTable, Yt as _voltroKvTable, Nn as _voltroMigrationPlansTable, xn as _voltroMigrationsTable, Kl as _voltroMssqlCdcOffsetsTable, nn as _voltroPluginMigrationsTable, Bn as _voltroReplaceInProgressTable, $t as _voltroReplicaObservationsTable, Tt as _voltroSchemaOwnerTable, nr as _voltroSeedsTable, mr as _voltroTenantSelectionsTable, yo as actorsTable, kc as admitBranch, or as agedSoftDropSnapshots, an as allEnumRenames, Pi as allRegisteredRelations, _ as allRegisteredTables, gt as and, ea as applyJsonPatch, m as array, St as arrayContains, Ge as arrayHas, e as arrayOverlaps, ia as attachEagerLoads, Io as attributionFields, Bo as attributionKey, Yc as auditAllTableIndexes, Jc as auditTableIndexes, C as authoredError, jt as authoredMessageOf, Vn as avg, cn as avgOver, qo as beginLocalWrite, cr as bigint, Uc as bindResidentStore, rt as boolean, pc as branchNamespaceName, pl as bulkInsertLimitsFor, re as bytes, jn as causeBranches, Co as changeDelete, Eo as changeDigest, xo as changeInsert, wo as changeSoftDelete, So as changeUpdate, hl as chunkRowsForInsert, Uo as claimPendingAttribution, Kn as classifyConstraintViolation, en as clearEnumRenames, Xo as clearPendingAttribution, Ii as clearRelationsRegistry, zc as clearResidencyConfig, zl as clearRetentions, Re as clearTableRegistry, as as clearWriteRecorders, B as coercePredicateForSqlite, Be as coercePredicateValue, gn as coercePredicateValues, _e as coerceValueForSqlite, Jt as collectSubqueries, At as column, Oe as columnRef, di as columnSchema, ml as columnsPerRow, xr as compareDecimal, ma as compileEagerJson, ta as compileJsonPatch, h as compilePredicate, lr as compileRawFragment, it as compileRowProjection, ie as compileSelect, Do as composeChangeKey, lc as computeEmbedding, jl as connectionIdentity, Zn as contains, An as count, Gn as countDistinct, v as crdtCounter, ze as crdtDoc, hn as crdtManagedColumns, o as crdtManagedColumnsOf, fn as crdtSealed, je as crdtText, Fo as currentWriteAttribution, Rt as databaseHandle, Fe as date, Ue as dbEnum, Ss as dbMetricTagCacheSizeForTests, Ts as dbOperationsInFlight, se as decimal, Dt as declareEnumRename, ti as decodeFieldValue, pe as decodeRowsForTable, ct as decodeRowsFromSchema, si as decryptFieldsOnRead, nl as defineMigration, ot as defineMixin, at as defineSeed, cl as deleteTenantSelection, vn as denseRank, Wi as deriveSubjectGraph, Se as deriveTypeIdPrefix, ts as derivedRowId, ns as derivedRowIdLength, tt as describeAgedSoftDropSnapshots, zt as describeCharsetRefusal, yn as describeDriverError, er as describeRowBindings, Yl as describeTransferRun, Gr as deserializeArraysOnRead, t as drainIdentifierWarnings, ge as dropped, $r as encodeFieldValue, ht as encodeRowForSchema, oi as encryptFieldsForWrite, ii as encryptedColumnsOf, Jo as endLocalWrite, Ec as enforceBranchLimits, mn as ensureTableRegistered, On as eq, ee as escapeLike, Un as evaluatePredicate, $n as except, ln as exists, $s as expires, bo as externalChangeEvent, Ut as extractDbCause, Jr as fieldBinding, ft as fireSchemaChangeSeeds, ce as fireTenantCreateSeeds, el as formatIndexAuditIssue, Gi as formatSubjectGraph, Nt as frameworkTables, Rn as generateId, bt as generateSnowflake, De as geography, Ye as geometry, ir as getEnumRenames, Ni as getRelation, Mi as getRelations, Rc as getResidencyConfig, a as getTable, Mt as gt, Mn as gte, pa as hasEagerLoads, cc as hybridSearch, br as id, qn as inSet, Bt as inSubquery, k as inferForeignKey, Sl as insertIgnoreRowOutcome, yl as insertManyRows, vl as insertRow, u as integer, sn as interruptedReplaceRefusal, Ht as intersect, ut as interval, vr as irreversible, c as irreversibleReason, Yr as isBoundCiphertext, mc as isBranchNamespace, Xe as isColumnReference, Xi as isCompositeRowKey, yi as isEmptyRelationsSpec, Qr as isEncrypted, Zr as isFieldDecryptionError, lt as isFileMigration, Zt as isForeignKeyViolation, te as isFrameworkOwnedLiveTable, nc as isLocalFirst, rl as isMigrationDefinition, he as isMysqlFamily, bc as isNeonConnection, bn as isNotNull, tr as isNull, Dl as isPrimaryKeyConflictError, Fn as isQueryTimeout, ni as isRawEncoding, Vc as isRegionServable, bi as isRelationsSpec, xe as isSeedDefinition, g as isSoftDropSnapshotName, Ee as isSqliteFamily, Le as isStagingTableName, dn as isTableReactive, Bs as isTransactionAbortedError, Xs as isTransientContention, r as isView, fe as json, Wt as jsonField, l as jsonIndex, Zi as jsonPatchAssignments, Xt as lag, Pn as lead, Il as listRetentionConflicts, Rl as listRetentions, tc as localFirst, rc as localFirstTables, Qt as lt, In as lte, js as makeEagerFallbackReporter, Nc as makeNamespaceBranchExecutor, Rs as makeTransactionAbortTracker, Si as many, Ci as manyToMany, st as materializeFields, Sn as max, ue as migration, rn as min, _l as missingConflictColumns, gl as missingRequiredColumns, pt as mixin, wn as neq, _c as nextBranchState, Al as normaliseTarget, $i as normalizeJsonPatchValue, on as not, tn as notExists, Ot as notInSet, ar as notInSubquery, mt as numeric, Ds as observeDbOp, Mo as occurrenceWindowMs, xi as one, ra as oneCardinalityMessage, _r as or, S as orderClausesOf, Et as paginateBy, rr as paginateById, Oo as parseChangeKey, Zo as pendingAttributionCount, y as persistedColumns, wc as planBranch, vc as planBranchProvision, yc as planBranchTeardown, Tc as planBranchTeardownFor, Sc as planNeonBranchProvision, Cc as planNeonBranchTeardown, Sr as planVersionedUpdate, gr as pluginRef, Ft as pluginRefSpecOf, El as primaryKeyConflictError, Dc as provisionBranch, Wc as provisionResidentTenant, Me as qualifyTable, hr as queryFor, Kt as queryForView, Je as quoteIdent, Tl as raiseChangeListenerCeiling, Pt as rank, Ce as raw, ol as readTenantSelection, zn as readableByColumns, be as real, Es as recordDbOp, ls as recordsTable, xt as reference, li as refuseWrite, ho as registerCoreTables, ji as registerDiscoveredRelations, Ho as registerPendingAttribution, Ai as registerRelations, Ll as registerRetention, Ae as registerTable, rs as registerWriteRecorder, vi as relations, _o as requireActors, Pe as requireTable, vo as requireTenants, xs as resetDbMetricTagCacheForTests, _t as resetSnowflake, Hc as residentPlacement, Vr as resolveActorSnapshot, xc as resolveBranchMechanism, As as resolveEagerFallbackWarnIntervalMs, Yo as resolveEchoAttribution, dr as resolveFullTextIndex, ye as resolveIdScheme, le as resolveMixinGraph, Bc as resolveTenantHome, Ie as resolveTenantNamespace, Ul as retentionTtlMsFromEnv, Ji as rowKeyColumns, Yi as rowKeyIdentity, Qe as rowNumber, fi as rowSchema, Is as runRetryingTransaction, zs as runSavepoint, Hs as runStoreTransaction, Po as runWithWriteAttribution, us as runWriteRecorders, Ml as sameDatabase, We as sanitizeIdentifierFragment, Ql as scopeKeyOf, vt as selfReference, Wr as serializeArraysForWrite, wt as serverOnlyColumns, Lc as setResidencyConfig, Ln as setSchemaChangeSeedHook, ve as setTenantCreateSeedHook, Ms as settleTransactionExit, Tr as settleVersionedUpdate, i as softDropSnapshotStamp, It as spatialPredicate, kt as stagingLeftoverReport, kn as stagingLeftovers, Wn as stagingNamesOf, Lt as stagingStaleAfterMs, ul as stampGeneratedId, dl as stampGeneratedIds, pr as startsWith, ui as storeRefusalOf, sc as streamTable, p as sum, sr as sumOver, os as suspendWriteRecorders, ss as suspendWriteRecordersEffect, Bl as sweepRetention, x as table, Oc as teardownBranch, al as tenantSelectionId, b as text, n as timestamp, Or as timestampMs, wr as timestampMsOrNull, Fs as transactionRetrySchedule, nt as union, ne as unionAll, He as unregisterTable, is as unregisterWriteRecorder, Cl as updateManyRow, bl as upsertRow, xl as upsertRowOutcome, qi as upsertUpdatePatch, Ki as upsertUpdateValues, qt as validateColumnName, Xn as validateIndexName, Fi as validateRegisteredRelations, Di as validateRelationConfig, Dn as validateTableName, Hn as validateTypeIdPrefix, Gt as vector, de as vectorDistanceToOpclass, uc as vectorEmbedding, Dr as versionColumnOf, Yn as view, En as viewSql, et as walkLeaves, Cn as wireSafeCause, Lo as withCapturedAttribution, cs as writeRecordersSuspended, sl as writeTenantSelection };
2184
+ export { ut as AUTO_FILLED_COLUMNS, qr as BOUND_ENCRYPTED_PREFIX, Ml as BULK_INSERT_LIMITS, q as BranchNameInvalid, Rc as BranchTransitionInvalid, uu as CDC_OFFSETS_TABLE, Vo as CHANGE_CLAIM_TTL_ENV, Wl as CHANGE_LISTENER_CEILING, f as ColumnBuilder, pu as DATA_TRANSFERS_TABLE, Oe as DEFAULT_ACQUIRE_TIMEOUT_MS, Ho as DEFAULT_CHANGE_CLAIM_TTL_HOURS, qs as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, $e as DEFAULT_SOFT_DROP_RETENTION_DAYS, Bi as DEFAULT_SUBJECT_GRAPH_DEPTH, Kr as ENCRYPTED_PREFIX, yu as ENGINE, ca as EagerCardinalityError, Ae as FILE_MIGRATION_PATTERN, u as FRAMEWORK_LIVE_TABLES, Xr as FieldDecryptionError, hs as ID_COLUMN_MAX_LENGTH, Er as INITIAL_VERSION, Pe as IrreversibleMigrationError, _t as MATCHES_NO_ROWS, t as MAX_IDENTIFIER_LENGTH, He as MIGRATION_PHASES, pc as MSSQL_TRANSIENT_NUMBERS, dc as MYSQL_TRANSIENT_CODES, re as MigrationExpectationFailed, he as MigrationNeedsSqlClient, De as MigrationSkipped, Bo as OccurrenceCounter, fc as POSTGRES_TRANSIENT_STATES, Yn as REPLACE_IN_PROGRESS_TABLE, Ye as RewriteUnstableError, gu as SCOPE_KEY_MAX_LENGTH, cr as SELF_REFERENCE_TARGET, tc as SHARED_TRANSACTION_SERVICE, mc as SQLITE_TRANSIENT_CODES, Dn as STAGING_STALE_MINUTES, or as STAGING_TABLE_PREFIX, Rr as SqlClient, Tl as TENANT_SELECTIONS_TABLE, hc as TURSO_TRANSIENT_MESSAGE, Ec as TableStreamError, Ne as TenantNamespaceInvalid, Le as TenantNamespaceUnresolved, rl as TenantRegionUnavailable, nl as TenantResidencyUnresolved, ac as TransactionAbortedError, vr as TransactionBrokenByBodyError, bc as VOLTRO_EXPIRES_MIXIN_ID, Sc as VOLTRO_LOCAL_FIRST_MIXIN_ID, Cr as VersionConflict, Kt as WARN_IDENTIFIER_LENGTH, yn as _voltroApiKeysTable, du as _voltroCdcOffsetsTable, mu as _voltroDataTransfersTable, $n as _voltroDevicesTable, Ht as _voltroIdempotencyTable, Jt as _voltroKvTable, Fn as _voltroMigrationPlansTable, Cn as _voltroMigrationsTable, fu as _voltroMssqlCdcOffsetsTable, nn as _voltroPluginMigrationsTable, Vn as _voltroReplaceInProgressTable, Qt as _voltroReplicaObservationsTable, Et as _voltroSchemaOwnerTable, rr as _voltroSeedsTable, mr as _voltroTenantSelectionsTable, To as actorsTable, Zc as admitBranch, rt as agedSoftDropSnapshots, Ot as allEnumRenames, Li as allRegisteredRelations, gn as allRegisteredTables, Ct as and, oa as applyJsonPatch, at as array, Ke as arrayContains, e as arrayHas, qt as arrayOverlaps, ua as attachEagerLoads, qo as attributionFields, ts as attributionKey, gl as auditAllTableIndexes, hl as auditTableIndexes, S as authoredError, qn as authoredMessageOf, jt as avg, Nn as avgOver, us as beginLocalWrite, te as bigint, dl as bindResidentStore, g as boolean, Fc as branchNamespaceName, Nl as bulkInsertLimitsFor, Be as bytes, Bt as causeBranches, ko as changeDelete, Lo as changeDigest, Do as changeInsert, Ao as changeSoftDelete, Oo as changeUpdate, Fl as chunkRowsForInsert, is as claimPendingAttribution, xn as classifyConstraintViolation, ir as clearEnumRenames, ps as clearPendingAttribution, zi as clearRelationsRegistry, sl as clearResidencyConfig, au as clearRetentions, r as clearTableRegistry, Ss as clearWriteRecorders, H as coercePredicateForSqlite, a as coercePredicateValue, mn as coercePredicateValues, Qe as coerceValueForSqlite, Qn as collectSubqueries, Kn as column, xr as columnRef, pi as columnSchema, Pl as columnsPerRow, Fo as committedChangeBatchOf, ft as compareDecimal, ba as compileEagerJson, sa as compileJsonPatch, y as compilePredicate, ne as compileRawFragment, _ as compileRowProjection, Ve as compileSelect, Ro as composeChangeKey, jc as computeEmbedding, Zl as connectionIdentity, jn as contains, zt as count, bn as countDistinct, _n as crdtCounter, i as crdtDoc, pn as crdtManagedColumns, Me as crdtManagedColumnsOf, Ie as crdtSealed, We as crdtText, Ko as currentWriteAttribution, er as databaseHandle, ae as date, _e as dbEnum, Vs as dbMetricTagCacheSizeForTests, Ws as dbOperationsInFlight, ke as decimal, gr as declareEnumRename, ti as decodeFieldValue, gt as decodeRowsForTable, ue as decodeRowsFromSchema, li as decryptFieldsOnRead, Cl as defineMigration, ce as defineMixin, pt as defineSeed, kl as deleteTenantSelection, Ut as denseRank, Zi as deriveSubjectGraph, be as deriveTypeIdPrefix, vs as derivedRowId, ys as derivedRowIdLength, v as describeAgedSoftDropSnapshots, tr as describeCharsetRefusal, Wt as describeDriverError, Xt as describeRowBindings, hu as describeTransferRun, Gr as deserializeArraysOnRead, Zn as drainIdentifierWarnings, Ze as dropped, Po as emitCommittedChanges, $r as encodeFieldValue, Ee as encodeRowForSchema, oi as encryptFieldsForWrite, si as encryptFieldsForWriteBatch, ii as encryptedColumnsOf, ds as endLocalWrite, Jc as enforceBranchLimits, fn as ensureTableRegistered, Wn as eq, vn as escapeLike, un as evaluatePredicate, Yt as except, Nt as exists, xc as expires, Eo as externalChangeEvent, Ln as extractDbCause, Jr as fieldBinding, se as fireSchemaChangeSeeds, Ce as fireTenantCreateSeeds, xl as formatIndexAuditIssue, Qi as formatSubjectGraph, Pt as frameworkTables, xt as generateId, wt as generateSnowflake, br as geography, c as geometry, It as getEnumRenames, Ii as getRelation, Fi as getRelations, ol as getResidencyConfig, je as getTable, Pn as gt, Jn as gte, ya as hasEagerLoads, Ac as hybridSearch, dt as id, Vt as inSet, Sn as inSubquery, Ei as inferForeignKey, Hl as insertIgnoreRowOutcome, zl as insertManyRows, Rl as insertRow, pe as integer, sn as interruptedReplaceRefusal, In as intersect, st as interval, o as irreversible, lt as irreversibleReason, Yr as isBoundCiphertext, Ic as isBranchNamespace, l as isColumnReference, ra as isCompositeRowKey, xi as isEmptyRelationsSpec, Qr as isEncrypted, Zr as isFieldDecryptionError, de as isFileMigration, Tn as isForeignKeyViolation, m as isFrameworkOwnedLiveTable, wc as isLocalFirst, wl as isMigrationDefinition, Xe as isMysqlFamily, Hc as isNeonConnection, nr as isNotNull, Gt as isNull, ql as isPrimaryKeyConflictError, an as isQueryTimeout, ni as isRawEncoding, ll as isRegionServable, Si as isRelationsSpec, zn as isSeedDefinition, Re as isSoftDropSnapshotName, yr as isSqliteFamily, hn as isStagingTableName, Fe as isTableReactive, cc as isTransactionAbortedError, vc as isTransientContention, Xn as isView, ht as json, Zt as jsonField, fe as jsonIndex, ia as jsonPatchAssignments, wn as lag, rn as lead, nu as listRetentionConflicts, iu as listRetentions, Cc as localFirst, Tc as localFirstTables, Rn as lt, En as lte, Xs as makeEagerFallbackReporter, tl as makeNamespaceBranchExecutor, oc as makeTransactionAbortTracker, wi as many, Ti as manyToMany, le as materializeFields, $t as max, ot as migration, Dt as min, Ll as missingConflictColumns, Il as missingRequiredColumns, we as mixin, on as neq, zc as nextBranchState, Xl as normaliseTarget, aa as normalizeJsonPatchValue, tn as not, kt as notExists, ar as notInSet, _r as notInSubquery, Te as numeric, Ks as observeDbOp, Uo as occurrenceWindowMs, rc as onTransaction, Ci as one, la as oneCardinalityMessage, Lt as or, T as orderClausesOf, hr as paginateBy, Ft as paginateById, zo as parseChangeKey, ms as pendingAttributionCount, C as persistedColumns, Kc as planBranch, Bc as planBranchProvision, Vc as planBranchTeardown, qc as planBranchTeardownFor, Wc as planNeonBranchProvision, Gc as planNeonBranchTeardown, Sr as planVersionedUpdate, fr as pluginRef, tt as pluginRefSpecOf, pr as preparePredicate, Kl as primaryKeyConflictError, Yc as provisionBranch, fl as provisionResidentTenant, Ge as qualifyTable, dr as queryFor, kn as queryForView, s as quoteIdent, Gl as raiseChangeListenerCeiling, et as rank, xe as raw, Dl as readTenantSelection, St as readableByColumns, yt as real, Gs as recordDbOp, Ds as recordsTable, Tt as reference, di as refuseWrite, xo as registerCoreTables, Pi as registerDiscoveredRelations, rs as registerPendingAttribution, Ni as registerRelations, ru as registerRetention, Ue as registerTable, bs as registerWriteRecorder, bi as relations, Co as requireActors, ie as requireTable, wo as requireTenants, Bs as resetDbMetricTagCacheForTests, qe as resetSnowflake, ul as residentPlacement, Vr as resolveActorSnapshot, Uc as resolveBranchMechanism, Ys as resolveEagerFallbackWarnIntervalMs, fs as resolveEchoAttribution, d as resolveFullTextIndex, vt as resolveIdScheme, Bn as resolveMixinGraph, cl as resolveTenantHome, oe as resolveTenantNamespace, lu as retentionTtlMsFromEnv, ta as rowKeyColumns, na as rowKeyIdentity, sr as rowNumber, mi as rowSchema, ic as runRetryingTransaction, sc as runSavepoint, uc as runStoreTransaction, Go as runWithWriteAttribution, Os as runWriteRecorders, Ql as sameDatabase, ve as sanitizeIdentifierFragment, vu as scopeKeyOf, Je as selfReference, Wr as serializeArraysForWrite, n as serverOnlyColumns, al as setResidencyConfig, ye as setSchemaChangeSeedHook, bt as setTenantCreateSeedHook, Zs as settleTransactionExit, Tr as settleVersionedUpdate, dn as softDropSnapshotStamp, nt as spatialPredicate, ur as sqlError, At as stagingLeftoverReport, Mn as stagingLeftovers, Gn as stagingNamesOf, Rt as stagingStaleAfterMs, Al as stampGeneratedId, jl as stampGeneratedIds, p as startsWith, fi as storeRefusalOf, kc as streamTable, it as sum, ee as sumOver, ws as suspendWriteRecorders, Ts as suspendWriteRecordersEffect, ou as sweepRetention, b as table, Xc as teardownBranch, El as tenantSelectionId, x as text, w as timestamp, Or as timestampMs, wr as timestampMsOrNull, ec as transactionRetrySchedule, h as union, ze as unionAll, ge as unregisterTable, xs as unregisterWriteRecorder, Ul as updateManyRow, Bl as upsertRow, Vl as upsertRowOutcome, ea as upsertUpdatePatch, $i as upsertUpdateValues, An as validateColumnName, Un as validateIndexName, Ri as validateRegisteredRelations, Ai as validateRelationConfig, ln as validateTableName, Mt as validateTypeIdPrefix, On as vector, mt as vectorDistanceToOpclass, Mc as vectorEmbedding, Dr as versionColumnOf, Hn as view, cn as viewSql, lr as walkLeaves, en as wireSafeCause, Jo as withCapturedAttribution, Es as writeRecordersSuspended, Ol as writeTenantSelection };