@voltro/database 0.75.0 → 0.76.0

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