@voltro/database 0.30.2 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import { $ as e, A as t, At as n, B as r, Bt as i, C as a, Ct as o, D as s, Dt as c, E as l, Et as u, F as d, Ft as f, G as p, H as m, I as h, It as g, J as _, K as v, L as y, Lt as ee, M as te, Mt as b, N as ne, Nt as x, O as re, Ot as S, P as ie, Pt as ae, Q as oe, R as C, Rt as se, S as ce, St as le, T as ue, Tt as de, U as fe, V as pe, Vt as me, W as he, X as ge, Y as _e, Z as ve, _ as ye, _t as be, a as xe, at as Se, b as Ce, bt as we, c as Te, ct as Ee, d as De, dt as Oe, et as ke, f as Ae, ft as je, g as Me, gt as Ne, h as Pe, ht as Fe, i as Ie, it as Le, j as Re, jt as w, k as ze, kt as T, l as Be, lt as Ve, m as He, mt as Ue, n as We, nt as Ge, o as Ke, ot as qe, p as Je, pt as Ye, q as Xe, rt as Ze, s as E, st as Qe, t as $e, tt as et, u as tt, ut as nt, v as rt, vt as it, w as at, wt as ot, x as st, xt as ct, y as lt, yt as ut, z as dt, zt as D } from "./frameworkLiveTables-CMyumigs.js";
2
- import { timestampMs as ft, timestampMsOrNull as pt } from "./wire.js";
3
- import { Cause as mt, Chunk as ht, Data as gt, Effect as _t, Exit as vt, Option as yt, Schema as O, Stream as bt } from "effect";
4
- import { AsyncLocalStorage as xt } from "node:async_hooks";
1
+ import { $ as e, A as t, At as n, B as r, Bt as i, C as a, Ct as o, D as s, Dt as c, E as l, Et as u, F as d, Ft as f, G as p, H as m, Ht as h, I as g, It as ee, J as te, K as _, L as ne, Lt as re, M as v, Mt as y, N as b, Nt as ie, O as ae, Ot as oe, P as se, Pt as ce, Q as le, R as ue, Rt as de, S as fe, St as pe, T as x, Tt as me, U as he, V as ge, Vt as S, W as _e, X as ve, Y as ye, Z as be, _ as xe, _t as Se, a as Ce, at as we, b as Te, bt as Ee, c as De, ct as Oe, d as ke, dt as Ae, et as je, f as Me, ft as Ne, g as Pe, gt as Fe, h as Ie, ht as Le, i as Re, it as ze, j as Be, jt as Ve, k as He, kt as C, l as Ue, lt as We, m as Ge, mt as Ke, n as qe, nt as Je, o as Ye, ot as Xe, p as Ze, pt as Qe, q as w, rt as $e, s as T, st as et, t as tt, tt as nt, u as rt, ut as it, v as at, vt as ot, w as st, wt as ct, x as lt, xt as ut, y as dt, yt as ft, z as E, zt as pt } from "./frameworkLiveTables-DbAgeVOU.js";
2
+ import { timestampMs as mt, timestampMsOrNull as ht } from "./wire.js";
3
+ import { Cause as gt, Chunk as _t, Data as vt, Effect as yt, Exit as bt, Option as D, Schema as O, Stream as xt } from "effect";
4
+ import { AsyncLocalStorage as St } from "node:async_hooks";
5
5
  import { ansi as k } from "@voltro/logger";
6
- import { SqlClient as St } from "@effect/sql";
6
+ import { SqlClient as Ct } from "@effect/sql";
7
7
  //#region src/actorSnapshot.ts
8
- var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n) => {
8
+ var wt = (e) => typeof e == "string" && e !== "" ? e : null, Tt = async (e, t, n) => {
9
9
  if (!(t == null || t === "")) try {
10
10
  let r = (await e.query({
11
11
  table: "actors",
@@ -14,27 +14,27 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
14
14
  column: "id",
15
15
  value: t
16
16
  },
17
- order: void 0,
17
+ order: [],
18
18
  take: 1,
19
19
  skip: void 0,
20
20
  projection: void 0
21
21
  }))[0];
22
22
  return r === void 0 ? void 0 : {
23
23
  id: t,
24
- type: Ct(r.kind) ?? n,
25
- displayName: Ct(r.displayName),
26
- email: Ct(r.email)
24
+ type: wt(r.kind) ?? n,
25
+ displayName: wt(r.displayName),
26
+ email: wt(r.email)
27
27
  };
28
28
  } catch {
29
29
  return;
30
30
  }
31
- }, Tt = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", Et = (e) => {
31
+ }, Et = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", Dt = (e) => {
32
32
  let t = [];
33
33
  for (let [n, r] of Object.entries(e.fields)) r.type === "array" && t.push(n);
34
34
  return t;
35
- }, Dt = (e, t, n) => {
36
- if (!Tt(n) || !t) return e;
37
- let r = Et(t);
35
+ }, Ot = (e, t, n) => {
36
+ if (!Et(n) || !t) return e;
37
+ let r = Dt(t);
38
38
  if (r.length === 0) return e;
39
39
  let i = { ...e };
40
40
  for (let e of r) {
@@ -42,9 +42,9 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
42
42
  Array.isArray(t) && (i[e] = JSON.stringify(t));
43
43
  }
44
44
  return i;
45
- }, Ot = (e, t, n) => {
46
- if (!Tt(n) || !t) return e;
47
- let r = Et(t);
45
+ }, kt = (e, t, n) => {
46
+ if (!Et(n) || !t) return e;
47
+ let r = Dt(t);
48
48
  return r.length === 0 ? e : e.map((e) => {
49
49
  let t;
50
50
  for (let n of r) {
@@ -56,7 +56,7 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
56
56
  }
57
57
  return t ?? e;
58
58
  });
59
- }, kt = "enc:v1:", At = class extends Error {
59
+ }, At = "enc:v1:", jt = class extends Error {
60
60
  _tag = "FieldDecryptionError";
61
61
  table;
62
62
  column;
@@ -64,33 +64,33 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
64
64
  constructor(e) {
65
65
  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;
66
66
  }
67
- }, jt = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", Mt = (e) => typeof e == "string" && e.startsWith("enc:v1:"), Nt = (e) => {
67
+ }, Mt = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", Nt = (e) => typeof e == "string" && e.startsWith("enc:v1:"), Pt = (e) => {
68
68
  let t = [];
69
69
  for (let [n, r] of Object.entries(e.fields)) r.encrypted === !0 && t.push(n);
70
70
  return t;
71
- }, Pt = (e, t, n) => {
71
+ }, Ft = (e, t, n) => {
72
72
  if (!t) return e;
73
- let r = Nt(t);
73
+ let r = Pt(t);
74
74
  if (r.length === 0) return e;
75
75
  let i = { ...e };
76
76
  for (let e of r) {
77
77
  let r = i[e];
78
- if (!(r == null || Mt(r))) {
78
+ if (!(r == null || Nt(r))) {
79
79
  if (!n) throw Error(`column "${t.tableName ?? "?"}.${e}" is .encrypted() but no field cipher is registered — wire @voltro/plugin-governance's fieldEncryption (key via the Secrets-Resolver)`);
80
80
  i[e] = n.encrypt(JSON.stringify(r));
81
81
  }
82
82
  }
83
83
  return i;
84
- }, Ft = (e, t, n, r) => {
84
+ }, It = (e, t, n, r) => {
85
85
  if (!t) return e;
86
- let i = Nt(t);
86
+ let i = Pt(t);
87
87
  if (i.length === 0 || !n) return e;
88
88
  let a = r?.onError ?? "throw", o = t.tableName ?? "?";
89
89
  return e.map((e) => {
90
90
  let t;
91
91
  for (let s of i) {
92
92
  let i = e[s];
93
- if (Mt(i)) {
93
+ if (Nt(i)) {
94
94
  t ??= { ...e };
95
95
  try {
96
96
  t[s] = JSON.parse(n.decrypt(i));
@@ -104,7 +104,7 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
104
104
  });
105
105
  continue;
106
106
  }
107
- throw new At({
107
+ throw new jt({
108
108
  table: o,
109
109
  column: s,
110
110
  reason: n
@@ -114,7 +114,7 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
114
114
  }
115
115
  return t ?? e;
116
116
  });
117
- }, It = (e) => {
117
+ }, Lt = (e) => {
118
118
  let t = (() => {
119
119
  switch (e.type) {
120
120
  case "id":
@@ -126,7 +126,7 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
126
126
  case "decimal": return O.Number;
127
127
  case "boolean": return O.Boolean;
128
128
  case "timestamp":
129
- case "date": return ft;
129
+ case "date": return mt;
130
130
  case "bigint": return O.BigInt;
131
131
  case "bytes": return O.Uint8ArrayFromBase64;
132
132
  case "array": return O.Array(O.Unknown);
@@ -135,41 +135,41 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
135
135
  }
136
136
  })();
137
137
  return e.nullable === !0 ? O.NullOr(t) : t;
138
- }, Lt = (e, t) => {
138
+ }, Rt = (e, t) => {
139
139
  let n = new Set(t?.omit ?? []), r = {};
140
- for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = It(i));
140
+ for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = Lt(i));
141
141
  return O.Struct(r);
142
- }, Rt = (e) => typeof e == "function" ? e : () => e, zt = (e, t) => ({
142
+ }, zt = (e) => typeof e == "function" ? e : () => e, Bt = (e, t) => ({
143
143
  kind: "one",
144
- target: Rt(e),
144
+ target: zt(e),
145
145
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
146
146
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
147
- }), Bt = (e, t) => ({
147
+ }), Vt = (e, t) => ({
148
148
  kind: "many",
149
- target: Rt(e),
149
+ target: zt(e),
150
150
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
151
151
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
152
- }), Vt = (e, t) => ({
152
+ }), Ht = (e, t) => ({
153
153
  kind: "manyToMany",
154
- target: Rt(e),
155
- through: Rt(t.through),
154
+ target: zt(e),
155
+ through: zt(t.through),
156
156
  sourceKey: t.sourceKey,
157
157
  targetKey: t.targetKey
158
- }), Ht = {
159
- one: zt,
160
- many: Bt,
161
- manyToMany: Vt
162
- }, Ut = (e, t) => {
158
+ }), Ut = {
159
+ one: Bt,
160
+ many: Vt,
161
+ manyToMany: Ht
162
+ }, Wt = (e, t) => {
163
163
  let n = typeof e == "function" ? e : () => e;
164
164
  return {
165
165
  source: n,
166
- relations: t(Ht, n())
166
+ relations: t(Ut, n())
167
167
  };
168
- }, Wt = (e) => {
168
+ }, Gt = (e) => {
169
169
  if (typeof e != "object" || !e) return !1;
170
170
  let t = e;
171
171
  return typeof t.source != "function" || typeof t.relations != "object" || t.relations === null ? !1 : Object.keys(t.relations).length === 0;
172
- }, Gt = (e) => {
172
+ }, Kt = (e) => {
173
173
  if (typeof e != "object" || !e) return !1;
174
174
  let t = e;
175
175
  if (typeof t.source != "function" || typeof t.relations != "object" || t.relations === null) return !1;
@@ -178,35 +178,35 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
178
178
  let t = e?.kind;
179
179
  return t === "one" || t === "many" || t === "manyToMany";
180
180
  });
181
- }, Kt = zt, qt = Bt, Jt = Vt, A = (e, t, n) => {
181
+ }, qt = Bt, Jt = Vt, Yt = Ht, Xt = (e, t, n) => {
182
182
  let r = [];
183
183
  for (let [n, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && r.push(n);
184
184
  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>' }.`);
185
185
  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.`);
186
186
  return r[0];
187
- }, Yt = (e) => Object.keys(e.fields), j = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Xt = (e) => {
188
- let t = Yt(e);
187
+ }, Zt = (e) => Object.keys(e.fields), Qt = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), $t = (e) => {
188
+ let t = Zt(e);
189
189
  return t.length === 0 ? "<none>" : t.join(", ");
190
- }, Zt = (e, t, n) => {
190
+ }, en = (e, t, n) => {
191
191
  let r = `relation '${t}' on '${e.tableName}'`, i = n.target();
192
192
  if (n.kind === "manyToMany") {
193
193
  let t = n.through();
194
- for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!j(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}': ${Xt(t)}.`);
194
+ for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!Qt(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}': ${$t(t)}.`);
195
195
  return;
196
196
  }
197
197
  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.`);
198
- if (n.sourceKey !== void 0 && !j(e, n.sourceKey)) {
199
- let t = j(i, n.sourceKey);
200
- 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}': ${Xt(e)}.`));
198
+ if (n.sourceKey !== void 0 && !Qt(e, n.sourceKey)) {
199
+ let t = Qt(i, n.sourceKey);
200
+ 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}': ${$t(e)}.`));
201
201
  }
202
- if (n.foreignKey !== void 0 && !j(i, n.foreignKey)) {
203
- let t = j(e, n.foreignKey);
204
- 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}': ${Xt(i)}.`));
202
+ if (n.foreignKey !== void 0 && !Qt(i, n.foreignKey)) {
203
+ let t = Qt(e, n.foreignKey);
204
+ 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}': ${$t(i)}.`));
205
205
  }
206
- }, Qt = Symbol.for("@voltro/database/relationsRegistry"), $t = globalThis, M = $t[Qt] ?? ($t[Qt] = /* @__PURE__ */ new Map()), en = (e) => {
207
- let t = e.source(), n = M.get(t.tableName);
206
+ }, tn = Symbol.for("@voltro/database/relationsRegistry"), nn = globalThis, A = nn[tn] ?? (nn[tn] = /* @__PURE__ */ new Map()), rn = (e) => {
207
+ let t = e.source(), n = A.get(t.tableName);
208
208
  if (n === void 0) {
209
- M.set(t.tableName, new Map(Object.entries(e.relations)));
209
+ A.set(t.tableName, new Map(Object.entries(e.relations)));
210
210
  return;
211
211
  }
212
212
  for (let [r, i] of Object.entries(e.relations)) {
@@ -216,29 +216,29 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
216
216
  n.set(r, i);
217
217
  }
218
218
  }
219
- }, tn = (e) => {
219
+ }, an = (e) => {
220
220
  let t = 0;
221
- for (let n of Object.values(e)) Gt(n) && (en(n), t += 1);
221
+ for (let n of Object.values(e)) Kt(n) && (rn(n), t += 1);
222
222
  return t;
223
- }, nn = (e) => {
224
- let t = M.get(e);
223
+ }, on = (e) => {
224
+ let t = A.get(e);
225
225
  if (t !== void 0) return Object.fromEntries(t);
226
- }, rn = (e, t) => M.get(e)?.get(t), an = () => {
226
+ }, sn = (e, t) => A.get(e)?.get(t), cn = () => {
227
227
  let e = [];
228
- for (let [t, n] of M) for (let [r, i] of n) e.push({
228
+ for (let [t, n] of A) for (let [r, i] of n) e.push({
229
229
  source: t,
230
230
  name: r,
231
231
  relation: i
232
232
  });
233
233
  return e;
234
- }, on = () => {
235
- for (let [e, t] of M) {
236
- let n = C(e);
237
- if (n !== void 0) for (let [e, r] of t) Zt(n, e, r);
238
- }
239
- }, sn = () => {
240
- M.clear();
241
- }, cn = (e) => e == null || typeof e == "boolean" ? e : typeof e == "number" ? e !== 0 : typeof e == "bigint" ? e !== 0n : typeof e == "string" ? e === "1" || e.toLowerCase() === "true" : e, ln = (e) => {
234
+ }, ln = () => {
235
+ for (let [e, t] of A) {
236
+ let n = E(e);
237
+ if (n !== void 0) for (let [e, r] of t) en(n, e, r);
238
+ }
239
+ }, un = () => {
240
+ A.clear();
241
+ }, dn = (e) => e == null || typeof e == "boolean" ? e : typeof e == "number" ? e !== 0 : typeof e == "bigint" ? e !== 0n : typeof e == "string" ? e === "1" || e.toLowerCase() === "true" : e, fn = (e) => {
242
242
  if (e == null || typeof e != "string") return e;
243
243
  let t = e.trim();
244
244
  if (t.length === 0) return e;
@@ -249,7 +249,7 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
249
249
  } catch {
250
250
  return e;
251
251
  }
252
- }, un = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, dn = (e) => {
252
+ }, pn = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, mn = (e) => {
253
253
  if (e == null || e instanceof Date) return e;
254
254
  if (typeof e == "string") {
255
255
  let t = new Date(e);
@@ -260,21 +260,21 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
260
260
  return isNaN(t.getTime()) ? e : t;
261
261
  }
262
262
  return e;
263
- }, fn = (e, t, n) => {
263
+ }, hn = (e, t, n) => {
264
264
  if (e == null) return e;
265
265
  switch (t) {
266
- case "boolean": return n === "postgres" ? e : cn(e);
266
+ case "boolean": return n === "postgres" ? e : dn(e);
267
267
  case "json":
268
- case "array": return n === "postgres" ? e : ln(e);
268
+ case "array": return n === "postgres" ? e : fn(e);
269
269
  case "timestamp":
270
- case "date": return n === "sqlite" || n === "turso" ? dn(e) : e;
270
+ case "date": return n === "sqlite" || n === "turso" ? mn(e) : e;
271
271
  case "decimal":
272
- case "bigint": return un(e);
272
+ case "bigint": return pn(e);
273
273
  default: return e;
274
274
  }
275
- }, pn = (e, t, n) => {
275
+ }, gn = (e, t, n) => {
276
276
  if (e.length === 0) return e;
277
- let r = C(t);
277
+ let r = E(t);
278
278
  if (r === void 0) return e;
279
279
  let i = r.fields, a = [];
280
280
  for (let [e, t] of Object.entries(i)) a.push({
@@ -283,36 +283,36 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
283
283
  });
284
284
  return e.map((e) => {
285
285
  let t = { ...e };
286
- for (let { key: e, type: r } of a) e in t && (t[e] = fn(t[e], r, n));
286
+ for (let { key: e, type: r } of a) e in t && (t[e] = hn(t[e], r, n));
287
287
  return t;
288
288
  });
289
- }, mn = (e, t) => {
289
+ }, _n = (e, t) => {
290
290
  if (e == null) return e;
291
291
  switch (t) {
292
292
  case "json":
293
293
  case "array": return typeof e == "string" ? e : JSON.stringify(e);
294
294
  default: return e;
295
295
  }
296
- }, hn = (e, t, n = ["json", "array"]) => {
297
- let r = C(t);
296
+ }, vn = (e, t, n = ["json", "array"]) => {
297
+ let r = E(t);
298
298
  if (r === void 0) return e;
299
299
  let i = r.fields, a = null;
300
300
  for (let [t, r] of Object.entries(i)) if (n.includes(r.type) && t in e) {
301
- let n = mn(e[t], r.type);
301
+ let n = _n(e[t], r.type);
302
302
  n !== e[t] && (a === null && (a = { ...e }), a[t] = n);
303
303
  }
304
304
  return a ?? e;
305
- }, gn = class extends Error {
305
+ }, yn = class extends Error {
306
306
  _tag = "EagerCardinalityError";
307
307
  constructor(e) {
308
308
  super(e), this.name = "EagerCardinalityError";
309
309
  }
310
- }, _n = (e) => {
310
+ }, bn = (e) => {
311
311
  let { relationName: t, sourceTableName: n, targetTableName: r, foreignKey: i, sourceKey: a } = e, o = r === n;
312
312
  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.");
313
- }, vn = async (e, t, n, r) => {
313
+ }, xn = async (e, t, n, r) => {
314
314
  if (e.length === 0) return e;
315
- let i = nn(n.tableName);
315
+ let i = on(n.tableName);
316
316
  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?`);
317
317
  let a = e.map((e) => ({ ...e }));
318
318
  for (let [e, o] of Object.entries(t)) {
@@ -321,36 +321,36 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
321
321
  let t = Object.keys(i).join(", ") || "<none>";
322
322
  throw Error(`unknown relation '${e}' on '${n.tableName}'. Registered relations: ${t}.`);
323
323
  }
324
- Zt(n, e, t), await yn(a, e, t, o === !0 ? {} : o, n, r);
324
+ en(n, e, t), await Sn(a, e, t, o === !0 ? {} : o, n, r);
325
325
  }
326
326
  return a;
327
- }, yn = async (e, t, n, r, i, a) => {
327
+ }, Sn = async (e, t, n, r, i, a) => {
328
328
  switch (n.kind) {
329
329
  case "one":
330
- await bn(e, t, n, r, i, a);
330
+ await Cn(e, t, n, r, i, a);
331
331
  return;
332
332
  case "many":
333
- await xn(e, t, n, r, i, a);
333
+ await wn(e, t, n, r, i, a);
334
334
  return;
335
335
  case "manyToMany":
336
- await Cn(e, t, n, r, i, a);
336
+ await En(e, t, n, r, i, a);
337
337
  return;
338
338
  }
339
- }, bn = async (e, t, n, r, i, a) => {
340
- let o = n.target(), s = n.sourceKey ?? wn(i, o.tableName);
339
+ }, Cn = async (e, t, n, r, i, a) => {
340
+ let o = n.target(), s = n.sourceKey ?? Dn(i, o.tableName);
341
341
  if (s !== void 0) {
342
- let n = N(e, s), i = n.length === 0 ? [] : await Tn(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
342
+ let n = j(e, s), i = n.length === 0 ? [] : await On(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
343
343
  for (let n of e) {
344
344
  let e = n[s];
345
345
  n[t] = e == null ? null : c.get(e) ?? null;
346
346
  }
347
- await En(i, r.with, o, a);
347
+ await kn(i, r.with, o, a);
348
348
  return;
349
349
  }
350
- let c = n.foreignKey ?? A(o, i.tableName, t), l = n.sourceKey ?? "id", u = N(e, l), d = u.length === 0 ? [] : await Tn(o, c, u, r, a), f = /* @__PURE__ */ new Map();
350
+ let c = n.foreignKey ?? Xt(o, i.tableName, t), l = n.sourceKey ?? "id", u = j(e, l), d = u.length === 0 ? [] : await On(o, c, u, r, a), f = /* @__PURE__ */ new Map();
351
351
  for (let e of d) {
352
352
  let n = e[c];
353
- if (f.has(n)) throw new gn(_n({
353
+ if (f.has(n)) throw new yn(bn({
354
354
  relationName: t,
355
355
  sourceTableName: i.tableName,
356
356
  targetTableName: o.tableName,
@@ -363,9 +363,9 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
363
363
  let e = n[l];
364
364
  n[t] = e == null ? null : f.get(e) ?? null;
365
365
  }
366
- await En(d, r.with, o, a);
367
- }, xn = async (e, t, n, r, i, a) => {
368
- let o = n.target(), s = n.foreignKey ?? A(o, i.tableName, t), c = n.sourceKey ?? "id", l = N(e, c), u = Sn(r), d = l.length === 0 ? [] : await Tn(o, s, l, u, a), f = /* @__PURE__ */ new Map();
366
+ await kn(d, r.with, o, a);
367
+ }, wn = async (e, t, n, r, i, a) => {
368
+ let o = n.target(), s = n.foreignKey ?? Xt(o, i.tableName, t), c = n.sourceKey ?? "id", l = j(e, c), u = Tn(r), d = l.length === 0 ? [] : await On(o, s, l, u, a), f = /* @__PURE__ */ new Map();
369
369
  for (let e of d) {
370
370
  let t = e[s], n = f.get(t);
371
371
  n ? n.push(e) : f.set(t, [e]);
@@ -381,12 +381,12 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
381
381
  let e = n[c];
382
382
  n[t] = f.get(e) ?? [];
383
383
  }
384
- await En(d, r.with, o, a);
385
- }, Sn = (e) => {
384
+ await kn(d, r.with, o, a);
385
+ }, Tn = (e) => {
386
386
  let { limit: t, offset: n, ...r } = e;
387
387
  return r;
388
- }, Cn = async (e, t, n, r, i, a) => {
389
- let o = n.target(), s = n.through(), c = N(e, "id");
388
+ }, En = async (e, t, n, r, i, a) => {
389
+ let o = n.target(), s = n.through(), c = j(e, "id");
390
390
  if (c.length === 0) {
391
391
  for (let n of e) n[t] = [];
392
392
  return;
@@ -407,8 +407,8 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
407
407
  for (let n of e) n[t] = [];
408
408
  return;
409
409
  }
410
- let f = await Tn(o, "id", N(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
411
- await En(f, r.with, o, a);
410
+ let f = await On(o, "id", j(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
411
+ await kn(f, r.with, o, a);
412
412
  let m = r.junction === void 0 ? void 0 : r.junction === !0 ? Object.keys(s.fields) : r.junction, h = /* @__PURE__ */ new Map();
413
413
  for (let e of d) {
414
414
  let t = e[n.sourceKey], r = e[n.targetKey], i = p.get(r);
@@ -420,16 +420,16 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
420
420
  o ? o.push(a) : h.set(t, [a]);
421
421
  }
422
422
  for (let n of e) n[t] = h.get(n.id) ?? [];
423
- }, wn = (e, t) => {
423
+ }, Dn = (e, t) => {
424
424
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
425
- }, N = (e, t) => {
425
+ }, j = (e, t) => {
426
426
  let n = /* @__PURE__ */ new Set();
427
427
  for (let r of e) {
428
428
  let e = r[t];
429
429
  e != null && n.add(e);
430
430
  }
431
431
  return [...n];
432
- }, Tn = (e, t, n, r, i) => {
432
+ }, On = (e, t, n, r, i) => {
433
433
  let a = {
434
434
  column: t,
435
435
  op: "in",
@@ -443,63 +443,63 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
443
443
  skip: r.offset,
444
444
  projection: void 0
445
445
  });
446
- }, En = async (e, t, n, r) => {
447
- t !== void 0 && e.length !== 0 && (await vn(e, t, n, r)).forEach((t, n) => {
446
+ }, kn = async (e, t, n, r) => {
447
+ t !== void 0 && e.length !== 0 && (await xn(e, t, n, r)).forEach((t, n) => {
448
448
  let r = e[n];
449
449
  for (let [e, n] of Object.entries(t)) e in r || (r[e] = n);
450
450
  });
451
- }, Dn = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, On = class extends Error {
451
+ }, An = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, jn = class extends Error {
452
452
  _tag = "TenantNamespaceUnresolved";
453
453
  constructor(e) {
454
454
  super(e), this.name = "TenantNamespaceUnresolved";
455
455
  }
456
- }, kn = class extends Error {
456
+ }, Mn = class extends Error {
457
457
  _tag = "TenantNamespaceInvalid";
458
458
  constructor(e) {
459
459
  super(e), this.name = "TenantNamespaceInvalid";
460
460
  }
461
- }, An = 63, jn = "tenant_", Mn = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), Nn = (e) => {
462
- if (e == null || e === "") throw new On("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.");
463
- let t = Mn(e);
464
- if (t.replace(/_/g, "") === "") throw new kn(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
465
- let n = `${jn}${t}`;
466
- if (n.length > An) throw new kn(`namespace '${n}' for tenant '${e}' exceeds the ${An}-byte identifier limit. Use a shorter tenant id.`);
461
+ }, Nn = 63, Pn = "tenant_", Fn = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), In = (e) => {
462
+ if (e == null || e === "") throw new jn("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.");
463
+ let t = Fn(e);
464
+ if (t.replace(/_/g, "") === "") throw new Mn(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
465
+ let n = `${Pn}${t}`;
466
+ if (n.length > Nn) throw new Mn(`namespace '${n}' for tenant '${e}' exceeds the ${Nn}-byte identifier limit. Use a shorter tenant id.`);
467
467
  return n;
468
- }, Pn = (e, t) => e === null ? t : `${e}.${t}`, Fn = /* @__PURE__ */ new Set(["timestamp", "date"]), In = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, Ln = (e, t) => {
469
- if (e === void 0 || t == null || !Fn.has(e) || t instanceof Date) return t;
468
+ }, Ln = (e, t) => e === null ? t : `${e}.${t}`, Rn = /* @__PURE__ */ new Set(["timestamp", "date"]), zn = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, Bn = (e, t) => {
469
+ if (e === void 0 || t == null || !Rn.has(e) || t instanceof Date) return t;
470
470
  if (typeof t == "number" && Number.isFinite(t)) return new Date(t);
471
- if (typeof t == "string" && In.test(t)) {
471
+ if (typeof t == "string" && zn.test(t)) {
472
472
  let e = new Date(t);
473
473
  return Number.isNaN(e.getTime()) ? t : e;
474
474
  }
475
475
  return t;
476
- }, Rn = (e, t) => e === void 0 || !Fn.has(e) ? t : t.map((t) => Ln(e, t)), zn = (e, t) => {
476
+ }, Vn = (e, t) => e === void 0 || !Rn.has(e) ? t : t.map((t) => Bn(e, t)), Hn = (e, t) => {
477
477
  let { strings: n, values: r } = e, i = t.unsafe(n[0] ?? "");
478
478
  for (let e = 0; e < r.length; e++) i = t`${i}${r[e]}${t.unsafe(n[e + 1] ?? "")}`;
479
479
  return t`${i}`;
480
- }, Bn = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), P = (e, t, n = null, r) => {
481
- if ("not" in e) return t`NOT (${P(e.not, t, n, r)})`;
482
- if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => P(e, t, n, r)));
483
- if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => P(e, t, n, r)));
480
+ }, M = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), N = (e, t, n = null, r) => {
481
+ if ("not" in e) return t`NOT (${N(e.not, t, n, r)})`;
482
+ if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => N(e, t, n, r)));
483
+ if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => N(e, t, n, r)));
484
484
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
485
- let r = e, i = Zn(r.subquery, t, n);
485
+ let r = e, i = P(r.subquery, t, n);
486
486
  return r.op === "subquery-in" ? t`${t(r.column)} IN (${i})` : t`${t(r.column)} NOT IN (${i})`;
487
487
  }
488
488
  if (e.op === "exists" || e.op === "not-exists") {
489
- let r = e, i = Zn(r.subquery, t, n);
489
+ let r = e, i = P(r.subquery, t, n);
490
490
  return r.op === "exists" ? t`EXISTS (${i})` : t`NOT EXISTS (${i})`;
491
491
  }
492
492
  let i = e, a = t(i.column), o = i.path, s = o !== void 0 && o.length > 0, c = () => t.onDialectOrElse({
493
- mysql: () => t.unsafe(E(i.column, o, "mysql")),
494
- mssql: () => t.unsafe(E(i.column, o, "mssql")),
495
- sqlite: () => t.unsafe(E(i.column, o, "sqlite")),
496
- orElse: () => t.unsafe(E(i.column, o, "postgres"))
493
+ mysql: () => t.unsafe(T(i.column, o, "mysql")),
494
+ mssql: () => t.unsafe(T(i.column, o, "mssql")),
495
+ sqlite: () => t.unsafe(T(i.column, o, "sqlite")),
496
+ orElse: () => t.unsafe(T(i.column, o, "postgres"))
497
497
  }), l = () => t.onDialectOrElse({
498
- mysql: () => t.unsafe(E(i.column, o, "mysql", { numeric: !0 })),
499
- mssql: () => t.unsafe(E(i.column, o, "mssql", { numeric: !0 })),
500
- sqlite: () => t.unsafe(E(i.column, o, "sqlite", { numeric: !0 })),
501
- orElse: () => t.unsafe(E(i.column, o, "postgres", { numeric: !0 }))
502
- }), 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 : C(r)?.fields?.[i.column]?.type, h = (e) => Ln(m, e);
498
+ mysql: () => t.unsafe(T(i.column, o, "mysql", { numeric: !0 })),
499
+ mssql: () => t.unsafe(T(i.column, o, "mssql", { numeric: !0 })),
500
+ sqlite: () => t.unsafe(T(i.column, o, "sqlite", { numeric: !0 })),
501
+ orElse: () => t.unsafe(T(i.column, o, "postgres", { numeric: !0 }))
502
+ }), 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 : E(r)?.fields?.[i.column]?.type, h = (e) => Bn(m, e);
503
503
  switch (i.op) {
504
504
  case "eq": return t`${u} = ${f(h(i.value))}`;
505
505
  case "neq": return t`${u} <> ${f(h(i.value))}`;
@@ -516,7 +516,7 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
516
516
  return e.length === 0 ? t`TRUE` : t`${u} NOT IN ${t.in(s ? e.map((e) => f(e)) : e)}`;
517
517
  }
518
518
  case "contains": {
519
- let e = `%${Bn(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
519
+ let e = `%${M(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
520
520
  return t.onDialectOrElse({
521
521
  mysql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
522
522
  mssql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
@@ -525,7 +525,7 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
525
525
  });
526
526
  }
527
527
  case "startsWith": {
528
- let e = `${Bn(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
528
+ let e = `${M(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
529
529
  return t.onDialectOrElse({
530
530
  mysql: () => t`${u} LIKE ${e}`,
531
531
  orElse: () => t`${u} LIKE ${e} ESCAPE '\\'`
@@ -573,13 +573,13 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
573
573
  });
574
574
  }
575
575
  }
576
- }, Vn = (e, t) => {
576
+ }, Un = (e, t) => {
577
577
  let n = [];
578
578
  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}`);
579
- }, Hn = (e, t) => t.csv(e.map((e) => {
579
+ }, Wn = (e, t) => t.csv(e.map((e) => {
580
580
  let n = e.column === void 0 ? t.unsafe("*") : t`${t(e.column)}`;
581
581
  if (e.op.startsWith("window-")) {
582
- let r = Vn(e.window ?? {}, t);
582
+ let r = Un(e.window ?? {}, t);
583
583
  switch (e.op) {
584
584
  case "window-row-number": return t`ROW_NUMBER() OVER (${r}) AS ${t(e.alias)}`;
585
585
  case "window-rank": return t`RANK() OVER (${r}) AS ${t(e.alias)}`;
@@ -603,44 +603,44 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
603
603
  return t`${t(e.column)} AS ${t(e.alias)}`;
604
604
  default: throw Error(`compileAggregateProjection: unknown op '${e.op}'`);
605
605
  }
606
- })), Un = (e) => `[${e.join(",")}]`, Wn = (e, t) => {
606
+ })), Gn = (e) => `[${e.join(",")}]`, Kn = (e, t) => {
607
607
  if (e.queryVector === void 0) return null;
608
- let n = t(e.column), r = Un(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
608
+ let n = t(e.column), r = Gn(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
609
609
  return t.onDialectOrElse({
610
610
  mysql: () => t`${t.unsafe(a)}(${n}, ${r})`,
611
611
  mssql: () => t`NULL`,
612
612
  sqlite: () => t`NULL`,
613
613
  orElse: () => t`${n} ${t.unsafe(i)} ${r}::vector`
614
614
  });
615
- }, Gn = (e, t) => {
615
+ }, qn = (e, t) => {
616
616
  let n = t.unsafe(e.useGeography ? "::geography" : "::geometry");
617
617
  return t`ST_Distance(${t(e.column)}${n}, ${e.geom}${n})`;
618
- }, Kn = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, qn = (e, t) => t`${t(`${e.indexName}_tsv`)}`, Jn = (e, t) => `${t}_${e.indexName}_fts`, Yn = (e, t, n) => {
619
- let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${Bn(e.query)}%`;
618
+ }, Jn = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, Yn = (e, t) => t`${t(`${e.indexName}_tsv`)}`, Xn = (e, t) => `${t}_${e.indexName}_fts`, Zn = (e, t, n) => {
619
+ let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${M(e.query)}%`;
620
620
  return n.onDialectOrElse({
621
621
  mysql: () => n`MATCH(${r}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
622
622
  sqlite: () => {
623
- let r = n(Jn(e, t));
623
+ let r = n(Xn(e, t));
624
624
  return n`${n("id")} IN (SELECT ${n("row_id")} FROM ${r} WHERE ${r} MATCH ${e.query})`;
625
625
  },
626
626
  mssql: () => n.or(e.columns.map((e) => n`LOWER(${n(e)}) LIKE LOWER(${i}) ESCAPE '\\'`)),
627
- orElse: () => n`${qn(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
627
+ orElse: () => n`${Yn(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
628
628
  });
629
- }, Xn = (e, t, n) => {
630
- let r = `%${Bn(e.query)}%`;
629
+ }, Qn = (e, t, n) => {
630
+ let r = `%${M(e.query)}%`;
631
631
  return n.onDialectOrElse({
632
632
  mysql: () => n`MATCH(${n.csv(e.columns.map((e) => n`${n(e)}`))}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
633
633
  sqlite: () => {
634
- let r = n(Jn(e, t));
634
+ let r = n(Xn(e, t));
635
635
  return n`COALESCE((SELECT -bm25(${r}) FROM ${r} WHERE ${r} MATCH ${e.query} AND ${r}.${n("row_id")} = ${n("id")}), 0)`;
636
636
  },
637
637
  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}`),
638
- orElse: () => n`ts_rank(${qn(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
638
+ orElse: () => n`ts_rank(${Yn(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
639
639
  });
640
- }, Zn = (e, t, n = null) => {
640
+ }, P = (e, t, n = null) => {
641
641
  if (e.setOp && e.setOp.queries.length >= 2) {
642
- 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`(${Zn(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
643
- if (e.order.length > 0 && a.push(t` ORDER BY ${t.csv(e.order.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
642
+ 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`(${P(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
643
+ 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) {
644
644
  if (!Number.isInteger(e.take) || e.take < 0) throw Error(`compileSelect: invalid take ${e.take}`);
645
645
  a.push(t` LIMIT ${t.unsafe(String(e.take))}`);
646
646
  }
@@ -650,7 +650,7 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
650
650
  }
651
651
  return t`${i}${a.reduce((e, n) => t`${e}${n}`, t``)}`;
652
652
  }
653
- let r = e.annClause === void 0 ? null : Wn(e.annClause, t);
653
+ let r = e.annClause === void 0 ? null : Kn(e.annClause, t);
654
654
  e.spatialClause !== void 0 && t.onDialectOrElse({
655
655
  mysql: () => {
656
656
  throw Error("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
@@ -663,35 +663,35 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
663
663
  },
664
664
  orElse: () => t``
665
665
  });
666
- let i = e.spatialClause?.projectAs === void 0 ? null : Gn(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? Hn(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 ? Xn(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({
666
+ let i = e.spatialClause?.projectAs === void 0 ? null : qn(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? Wn(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 ? Qn(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({
667
667
  orElse: () => t`DISTINCT ON (${t.csv(e.distinctOn.map((e) => t`${t(e)}`))}) `,
668
668
  mysql: () => t`DISTINCT `,
669
669
  mssql: () => t`DISTINCT `,
670
670
  sqlite: () => t`DISTINCT `
671
- }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(Pn(n, e.table))}` : t`${t(Pn(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
671
+ }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(Ln(n, e.table))}` : t`${t(Ln(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
672
672
  let r = e.kind === "inner" ? "INNER" : "LEFT";
673
- return t` ${t.unsafe(r)} JOIN ${t(Pn(n, e.table))} AS ${t(e.alias)} ON ${P(e.on, t, n)}`;
674
- }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : Yn(c, e.table, t), _ = [e.predicate ? P(e.predicate, t, n, e.table) : null, g].filter((e) => e !== null), v = _.length > 0 ? t` WHERE ${t.and(_)}` : t``, y = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, ee = e.having ? t` HAVING ${P(e.having, t, n, e.table)}` : t``, te = e.skip !== void 0, b = [];
675
- r !== null && b.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && b.push(e.spatialClause.order === "desc" ? t`${Kn(e.spatialClause, t)} DESC` : t`${Kn(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && b.push(t`${l} DESC`);
676
- for (let n of e.order) b.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
677
- let ne = b.length > 0 ? t` ORDER BY ${t.csv(b)}` : te ? t.onDialectOrElse({
673
+ return t` ${t.unsafe(r)} JOIN ${t(Ln(n, e.table))} AS ${t(e.alias)} ON ${N(e.on, t, n)}`;
674
+ }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : Zn(c, e.table, t), ee = [e.predicate ? N(e.predicate, t, n, e.table) : null, g].filter((e) => e !== null), te = ee.length > 0 ? t` WHERE ${t.and(ee)}` : t``, _ = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, ne = e.having ? t` HAVING ${N(e.having, t, n, e.table)}` : t``, re = e.skip !== void 0, v = [];
675
+ r !== null && v.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && v.push(e.spatialClause.order === "desc" ? t`${Jn(e.spatialClause, t)} DESC` : t`${Jn(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && v.push(t`${l} DESC`);
676
+ for (let n of x(e)) v.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
677
+ let y = v.length > 0 ? t` ORDER BY ${t.csv(v)}` : re ? t.onDialectOrElse({
678
678
  mssql: () => t` ORDER BY (SELECT NULL)`,
679
679
  orElse: () => t``
680
- }) : t``, x = (e) => {
680
+ }) : t``, b = (e) => {
681
681
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`compileSelect: expected non-negative integer take/skip, got ${e}`);
682
682
  return t.unsafe(String(e));
683
- }, re = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${Zn(e.descriptor, t, n)})`), S = (e.ctes ?? []).some((e) => e.recursive === !0), ie = re.length > 0 ? t`WITH ${t.unsafe(S ? "RECURSIVE " : "")}${t.csv(re)} ` : t``;
683
+ }, ie = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${P(e.descriptor, t, n)})`), ae = (e.ctes ?? []).some((e) => e.recursive === !0), oe = ie.length > 0 ? t`WITH ${t.unsafe(ae ? "RECURSIVE " : "")}${t.csv(ie)} ` : t``;
684
684
  return t.onDialectOrElse({
685
685
  mssql: () => {
686
- let n = e.take !== void 0 && !te ? t`TOP ${x(e.take)} ` : t``, r = te ? t` OFFSET ${x(e.skip)} ROWS FETCH NEXT ${x(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
687
- return t`${ie}SELECT ${n}${f}${d} FROM ${h}${v}${y}${ee}${ne}${r}`;
686
+ let n = e.take !== void 0 && !re ? t`TOP ${b(e.take)} ` : t``, r = re ? t` OFFSET ${b(e.skip)} ROWS FETCH NEXT ${b(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
687
+ return t`${oe}SELECT ${n}${f}${d} FROM ${h}${te}${_}${ne}${y}${r}`;
688
688
  },
689
689
  orElse: () => {
690
- let n = e.take === void 0 ? t`` : t` LIMIT ${x(e.take)}`, r = te ? t` OFFSET ${x(e.skip)}` : t``;
691
- return t`${ie}SELECT ${f}${d} FROM ${h}${v}${y}${ee}${ne}${n}${r}`;
690
+ let n = e.take === void 0 ? t`` : t` LIMIT ${b(e.take)}`, r = re ? t` OFFSET ${b(e.skip)}` : t``;
691
+ return t`${oe}SELECT ${f}${d} FROM ${h}${te}${_}${ne}${y}${n}${r}`;
692
692
  }
693
693
  });
694
- }, Qn = (e, t, n) => {
694
+ }, $n = (e, t, n) => {
695
695
  if (e.eager === void 0) return null;
696
696
  let r = tr(e.table, e.eager, e.sourceTable);
697
697
  if (r === null) return null;
@@ -700,14 +700,14 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
700
700
  fragment: i,
701
701
  decode: dr(r, n)
702
702
  };
703
- }, $n = (e) => e.relation.kind === "one" && e.fkSide === "target", er = (e) => ({
703
+ }, F = (e) => e.relation.kind === "one" && e.fkSide === "target", er = (e) => ({
704
704
  ...e,
705
705
  branch: {
706
706
  ...e.branch,
707
707
  limit: 2
708
708
  }
709
709
  }), tr = (e, t, n) => {
710
- let r = n ?? pe(e), i = nn(e);
710
+ let r = n ?? m(e), i = on(e);
711
711
  if (i === void 0) return null;
712
712
  let a = [];
713
713
  for (let [e, n] of Object.entries(t)) {
@@ -728,17 +728,17 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
728
728
  let r = t.sourceKey ?? or(n, i.tableName);
729
729
  if (r !== void 0) o = r, s = "source";
730
730
  else try {
731
- o = t.foreignKey ?? A(i, n.tableName, e), s = "target";
731
+ o = t.foreignKey ?? Xt(i, n.tableName, e), s = "target";
732
732
  } catch {
733
733
  return null;
734
734
  }
735
735
  } else try {
736
- o = t.foreignKey ?? A(i, n.tableName, e), s = "target";
736
+ o = t.foreignKey ?? Xt(i, n.tableName, e), s = "target";
737
737
  } catch {
738
738
  return null;
739
739
  }
740
740
  let c = r.with === void 0 ? [] : (() => {
741
- let e = nn(i.tableName);
741
+ let e = on(i.tableName);
742
742
  if (e === void 0 && Object.keys(r.with).length > 0) return null;
743
743
  let t = [];
744
744
  for (let [n, a] of Object.entries(r.with)) {
@@ -802,7 +802,7 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
802
802
  let r = [];
803
803
  for (let [t, n] of Object.entries(e.fields)) (n.type === "timestamp" || n.type === "date") && r.push(t);
804
804
  let i = t.map((e) => {
805
- let t = fr(e.target, e.children, n), r = e.relation.kind === "one", i = $n(e), a = i ? _n({
805
+ let t = fr(e.target, e.children, n), r = e.relation.kind === "one", i = F(e), a = i ? bn({
806
806
  relationName: e.relationName,
807
807
  sourceTableName: e.source.tableName,
808
808
  targetTableName: e.target.tableName,
@@ -832,7 +832,7 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
832
832
  }
833
833
  if (e.fromOverFetch) {
834
834
  let r = n;
835
- if (r.length > 1) throw new gn(e.cardinalityMessage);
835
+ if (r.length > 1) throw new yn(e.cardinalityMessage);
836
836
  t[e.name] = r.length === 0 ? null : e.decode(r[0]);
837
837
  continue;
838
838
  }
@@ -860,58 +860,58 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
860
860
  };
861
861
  }, mr = (e, t, n) => {
862
862
  let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = hr(i, t.children, n);
863
- return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${B(e.predicate, i, r)}` : r``}${e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${L(i, e.column, r)} DESC` : r`${L(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${z(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${z(e.skip, r)}`}`;
863
+ return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``}${x(e).length > 0 ? r` ORDER BY ${r.csv(x(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${B(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${B(e.skip, r)}`}`;
864
864
  }, hr = (e, t, n, r) => {
865
- let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${R(ar, i)}::text)`;
865
+ let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${z(ar, i)}::text)`;
866
866
  if (t.length === 0 && r === void 0) return a;
867
867
  let o = [];
868
- r !== void 0 && o.push(i`${R("_junction", i)}, ${L(e, ar, i)}`);
868
+ r !== void 0 && o.push(i`${z("_junction", i)}, ${R(e, ar, i)}`);
869
869
  for (let r of t) {
870
870
  let t = gr(r, e, n);
871
871
  if (t === null) return null;
872
- o.push(i`${R(r.relationName, i)}, ${t}`);
872
+ o.push(i`${z(r.relationName, i)}, ${t}`);
873
873
  }
874
874
  return i`${a} || jsonb_build_object(${i.csv(o)})`;
875
875
  }, gr = (e, t, n) => {
876
876
  switch (e.relation.kind) {
877
- case "one": return $n(e) ? vr(er(e), t, n) : _r(e, t, n);
877
+ case "one": return F(e) ? vr(er(e), t, n) : _r(e, t, n);
878
878
  case "many": return vr(e, t, n);
879
879
  case "manyToMany": return yr(e, t, n);
880
880
  }
881
881
  }, _r = (e, t, n) => {
882
882
  let r = n.sql, i = n.nextAlias(), a = hr(i, e.children, n);
883
883
  if (a === null) return null;
884
- let o = e.fkSide === "source" ? r`${L(i, "id", r)} = ${L(t, e.foreignKey, r)}` : r`${L(i, e.foreignKey, r)} = ${L(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${B(e.branch.where, i, r)}`, c = F(i, e.branch.orderBy, r);
884
+ let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${V(e.branch.where, i, r)}`, c = I(i, e.branch.orderBy, r);
885
885
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}${c} LIMIT 1)`;
886
886
  }, vr = (e, t, n) => {
887
887
  let r = n.sql, i = n.nextAlias(), a = hr(i, e.children, n);
888
888
  if (a === null) return null;
889
- let o = r`${L(void 0, e.foreignKey, r)} = ${L(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${P(e.branch.where, r)}`, c = xr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${z(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${z(e.branch.offset, r)}`;
889
+ let o = r`${R(void 0, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${N(e.branch.where, r)}`, c = xr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`;
890
890
  return r`COALESCE((SELECT jsonb_agg(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), '[]'::jsonb)`;
891
891
  }, yr = (e, t, n) => {
892
892
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = hr(o, e.children, n, e.junction);
893
893
  if (c === null) return null;
894
- let l = e.branch.where === void 0 ? r`` : r` AND ${P(e.branch.where, r)}`, u = V(e, s, r), d = F(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${z(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${z(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${br(e.junction, s, r)} AS ${r(ar)}`;
895
- 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 ${L(o, "id", r)} = ${L(s, i.targetKey, r)} WHERE ${L(s, i.sourceKey, r)} = ${L(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
896
- }, br = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${R(e, n)}, ${L(t, e, n)}`))})`, F = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${L(e, t.column, n)} DESC` : n`${L(e, t.column, n)} ASC`))}`, xr = (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`))}`, Sr = (e, t, n) => {
894
+ let l = e.branch.where === void 0 ? r`` : r` AND ${N(e.branch.where, r)}`, u = H(e, s, r), d = I(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${br(e.junction, s, r)} AS ${r(ar)}`;
895
+ return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
896
+ }, br = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${z(e, n)}, ${R(t, e, n)}`))})`, I = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${R(e, t.column, n)} DESC` : n`${R(e, t.column, n)} ASC`))}`, xr = (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`))}`, Sr = (e, t, n) => {
897
897
  let r = n.sql, i = n.nextAlias(), a = Cr(i, t.table, t.children, n);
898
898
  if (a === null) return null;
899
- let o = e.predicate ? r` WHERE ${B(e.predicate, i, r)}` : r``, s = e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${L(i, e.column, r)} DESC` : r`${L(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${z(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${z(e.skip, r)}`;
899
+ let o = e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``, s = x(e).length > 0 ? r` ORDER BY ${r.csv(x(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${B(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${B(e.skip, r)}`;
900
900
  return r`SELECT ${a} AS "__row" FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
901
901
  }, Cr = (e, t, n, r, i) => {
902
902
  let a = r.sql, o = [];
903
- for (let n of Object.keys(t.fields)) o.push(a`${R(n, a)}, ${L(e, n, a)}`);
903
+ for (let n of Object.keys(t.fields)) o.push(a`${z(n, a)}, ${R(e, n, a)}`);
904
904
  if (i !== void 0) {
905
905
  let e = wr(i.projection, i.source, a);
906
- o.push(a`${R("_junction", a)}, json_object(${e})`);
906
+ o.push(a`${z("_junction", a)}, json_object(${e})`);
907
907
  }
908
908
  for (let t of n) {
909
909
  let n = Or(t, e, r);
910
910
  if (n === null) return null;
911
- o.push(a`${R(t.relationName, a)}, ${n}`);
911
+ o.push(a`${z(t.relationName, a)}, ${n}`);
912
912
  }
913
913
  return a`json_object(${a.csv(o)})`;
914
- }, wr = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${R(e, n)}, ${L(t.alias, t.physical(e), n)}`)), Tr = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${L(t, e, n)} AS ${n(ir(e))}`))}`, Er = (e) => ({
914
+ }, wr = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${z(e, n)}, ${R(t.alias, t.physical(e), n)}`)), Tr = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${R(t, e, n)} AS ${n(ir(e))}`))}`, Er = (e) => ({
915
915
  alias: e,
916
916
  physical: ir
917
917
  }), Dr = (e) => ({
@@ -919,19 +919,19 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
919
919
  physical: (e) => e
920
920
  }), Or = (e, t, n) => {
921
921
  switch (e.relation.kind) {
922
- case "one": return $n(e) ? Ar(er(e), t, n) : kr(e, t, n);
922
+ case "one": return F(e) ? Ar(er(e), t, n) : kr(e, t, n);
923
923
  case "many": return Ar(e, t, n);
924
924
  case "manyToMany": return jr(e, t, n);
925
925
  }
926
926
  }, kr = (e, t, n) => {
927
927
  let r = n.sql, i = n.nextAlias(), a = Cr(i, e.target, e.children, n);
928
928
  if (a === null) return null;
929
- let o = e.fkSide === "source" ? r`${L(i, "id", r)} = ${L(t, e.foreignKey, r)}` : r`${L(i, e.foreignKey, r)} = ${L(t, e.sourceKey, r)}`;
929
+ let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`;
930
930
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
931
931
  }, Ar = (e, t, n) => {
932
932
  let r = n.sql, i = n.nextAlias(), a = Cr(i, e.target, e.children, n);
933
933
  if (a === null) return null;
934
- let o = r`${L(void 0, e.foreignKey, r)} = ${L(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${P(H(e.branch.where), r)}`, c = xr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${z(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${z(e.branch.offset, r)}`;
934
+ let o = r`${R(void 0, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${N(U(e.branch.where), r)}`, c = xr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`;
935
935
  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('[]'))`;
936
936
  }, jr = (e, t, n) => {
937
937
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Cr(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
@@ -939,30 +939,30 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
939
939
  source: Er(o)
940
940
  });
941
941
  if (c === null) return null;
942
- let l = e.branch.where === void 0 ? r`` : r` AND ${P(H(e.branch.where), r)}`, u = V(e, s, r, !0), d = F(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${z(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${z(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Tr(e.junction, s, r);
943
- 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 ${L(o, "id", r)} = ${L(s, i.targetKey, r)} WHERE ${L(s, i.sourceKey, r)} = ${L(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
942
+ let l = e.branch.where === void 0 ? r`` : r` AND ${N(U(e.branch.where), r)}`, u = H(e, s, r, !0), d = I(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Tr(e.junction, s, r);
943
+ return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
944
944
  }, Mr = (e, t, n) => {
945
- let r = n.sql, i = n.nextAlias(), a = I(i, t.table, t.children, n);
945
+ let r = n.sql, i = n.nextAlias(), a = L(i, t.table, t.children, n);
946
946
  if (a === null) return null;
947
- let o = e.predicate ? r` WHERE ${B(e.predicate, i, r)}` : r``, s = e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${L(i, e.column, r)} DESC` : r`${L(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${z(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${z(e.skip, r)}`;
947
+ let o = e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``, s = x(e).length > 0 ? r` ORDER BY ${r.csv(x(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${B(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${B(e.skip, r)}`;
948
948
  return r`SELECT ${a} AS \`__row\` FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
949
- }, I = (e, t, n, r, i) => {
949
+ }, L = (e, t, n, r, i) => {
950
950
  let a = r.sql, o = [];
951
- for (let n of Object.keys(t.fields)) o.push(a`${R(n, a)}, ${L(e, n, a)}`);
951
+ for (let n of Object.keys(t.fields)) o.push(a`${z(n, a)}, ${R(e, n, a)}`);
952
952
  if (i !== void 0) {
953
953
  let e = wr(i.projection, i.source, a);
954
- o.push(a`${R("_junction", a)}, JSON_OBJECT(${e})`);
954
+ o.push(a`${z("_junction", a)}, JSON_OBJECT(${e})`);
955
955
  }
956
956
  for (let t of n) {
957
957
  let n = Nr(t, e, r);
958
958
  if (n === null) return null;
959
- o.push(a`${R(t.relationName, a)}, ${n}`);
959
+ o.push(a`${z(t.relationName, a)}, ${n}`);
960
960
  }
961
961
  return a`JSON_OBJECT(${a.csv(o)})`;
962
962
  }, Nr = (e, t, n) => {
963
963
  switch (e.relation.kind) {
964
964
  case "one":
965
- if ($n(e)) {
965
+ if (F(e)) {
966
966
  let r = er(e);
967
967
  return n.dialect === "mariadb" ? Lr(r, t, n) : Fr(r, t, n);
968
968
  }
@@ -971,57 +971,57 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
971
971
  case "manyToMany": return n.dialect === "mariadb" ? Rr(e, t, n) : Ir(e, t, n);
972
972
  }
973
973
  }, Pr = (e, t, n) => {
974
- let r = n.sql, i = n.nextAlias(), a = I(i, e.target, e.children, n);
974
+ let r = n.sql, i = n.nextAlias(), a = L(i, e.target, e.children, n);
975
975
  if (a === null) return null;
976
- let o = e.fkSide === "source" ? r`${L(i, "id", r)} = ${L(t, e.foreignKey, r)}` : r`${L(i, e.foreignKey, r)} = ${L(t, e.sourceKey, r)}`;
976
+ let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`;
977
977
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
978
978
  }, Fr = (e, t, n) => {
979
- let r = n.sql, i = n.nextAlias(), a = I(i, e.target, e.children, n);
979
+ let r = n.sql, i = n.nextAlias(), a = L(i, e.target, e.children, n);
980
980
  if (a === null) return null;
981
- let o = r`${L(void 0, e.foreignKey, r)} = ${L(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${P(H(e.branch.where), r)}`, c = xr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${z(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${z(e.branch.offset, r)}`;
981
+ let o = r`${R(void 0, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${N(U(e.branch.where), r)}`, c = xr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`;
982
982
  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())`;
983
983
  }, Ir = (e, t, n) => {
984
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = I(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
984
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = L(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
985
985
  projection: e.junction,
986
986
  source: Er(o)
987
987
  });
988
988
  if (c === null) return null;
989
- let l = e.branch.where === void 0 ? r`` : r` AND ${P(H(e.branch.where), r)}`, u = V(e, s, r, !0), d = F(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${z(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${z(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Tr(e.junction, s, r);
990
- 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 ${L(o, "id", r)} = ${L(s, i.targetKey, r)} WHERE ${L(s, i.sourceKey, r)} = ${L(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
989
+ let l = e.branch.where === void 0 ? r`` : r` AND ${N(U(e.branch.where), r)}`, u = H(e, s, r, !0), d = I(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Tr(e.junction, s, r);
990
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
991
991
  }, Lr = (e, t, n) => {
992
- let r = n.sql, i = n.nextAlias(), a = I(i, e.target, e.children, n);
992
+ let r = n.sql, i = n.nextAlias(), a = L(i, e.target, e.children, n);
993
993
  if (a === null) return null;
994
- let o = r`${L(i, e.foreignKey, r)} = ${L(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${P(H(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
995
- 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`${L(i, e.column, r)} DESC` : r`${L(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
996
- 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 ${L(i, "rn", r)} > ${z(d, r)} AND ${L(i, "rn", r)} <= ${z(d + u, r)}` : u === void 0 ? r` AND ${L(i, "rn", r)} > ${z(d, r)}` : r` AND ${L(i, "rn", r)} <= ${z(u, r)}`;
997
- return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${L(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())`;
994
+ let o = r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${N(U(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
995
+ 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`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
996
+ 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 ${R(i, "rn", r)} > ${B(d, r)} AND ${R(i, "rn", r)} <= ${B(d + u, r)}` : u === void 0 ? r` AND ${R(i, "rn", r)} > ${B(d, r)}` : r` AND ${R(i, "rn", r)} <= ${B(u, r)}`;
997
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${R(i, "rn", r)}) FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${r(e.foreignKey)}${l}) AS rn FROM ${r(e.target.tableName)}) AS ${r(i)} WHERE ${o}${s}${f}), JSON_ARRAY())`;
998
998
  }, Rr = (e, t, n) => {
999
999
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = (t) => e.junction === void 0 ? void 0 : {
1000
1000
  projection: e.junction,
1001
1001
  source: t
1002
- }, l = r`${L(s, i.sourceKey, r)} = ${L(t, "id", r)}`, u = r`${L(o, "id", r)} = ${L(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${P(H(e.branch.where), r)}`, f = V(e, s, r, !0), p = e.branch.orderBy ?? [];
1002
+ }, l = r`${R(s, i.sourceKey, r)} = ${R(t, "id", r)}`, u = r`${R(o, "id", r)} = ${R(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${N(U(e.branch.where), r)}`, f = H(e, s, r, !0), p = e.branch.orderBy ?? [];
1003
1003
  if (!(e.branch.limit !== void 0 || e.branch.offset !== void 0)) {
1004
- let t = I(o, e.target, e.children, n, c(Dr(s)));
1005
- 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`${L(o, e.column, r)} DESC` : r`${L(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())`;
1004
+ let t = L(o, e.target, e.children, n, c(Dr(s)));
1005
+ 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`${R(o, e.column, r)} DESC` : r`${R(o, e.column, r)} ASC`))}` : r``}) FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u} WHERE ${l}${f}${d}), JSON_ARRAY())`;
1006
1006
  }
1007
- let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${L(o, e.column, r)} DESC` : r`${L(o, e.column, r)} ASC`))}` : r` ORDER BY ${L(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, _ = h !== void 0 && g !== void 0 ? r` AND ${L(o, "rn", r)} > ${z(g, r)} AND ${L(o, "rn", r)} <= ${z(g + h, r)}` : h === void 0 ? r` AND ${L(o, "rn", r)} > ${z(g, r)}` : r` AND ${L(o, "rn", r)} <= ${z(h, r)}`, v = e.branch.onJunction === void 0 ? r`` : r` WHERE ${B(H(e.branch.onJunction), s, r)}`, y = I(o, e.target, e.children, n, c(Er(o)));
1008
- if (y === null) return null;
1009
- let ee = e.junction === void 0 ? r`` : Tr(e.junction, s, r);
1010
- return r`COALESCE((SELECT JSON_ARRAYAGG(${y} ORDER BY ${L(o, "rn", r)}) FROM (SELECT ${r(o)}.*${ee}, ${L(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${L(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 ${L(o, `__src_${i.sourceKey}`, r)} = ${L(t, "id", r)}${d}${_}), JSON_ARRAY())`;
1007
+ let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${R(o, e.column, r)} DESC` : r`${R(o, e.column, r)} ASC`))}` : r` ORDER BY ${R(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, ee = h !== void 0 && g !== void 0 ? r` AND ${R(o, "rn", r)} > ${B(g, r)} AND ${R(o, "rn", r)} <= ${B(g + h, r)}` : h === void 0 ? r` AND ${R(o, "rn", r)} > ${B(g, r)}` : r` AND ${R(o, "rn", r)} <= ${B(h, r)}`, te = e.branch.onJunction === void 0 ? r`` : r` WHERE ${V(U(e.branch.onJunction), s, r)}`, _ = L(o, e.target, e.children, n, c(Er(o)));
1008
+ if (_ === null) return null;
1009
+ let ne = e.junction === void 0 ? r`` : Tr(e.junction, s, r);
1010
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${_} ORDER BY ${R(o, "rn", r)}) FROM (SELECT ${r(o)}.*${ne}, ${R(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${R(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${te}) AS ${r(o)} WHERE ${R(o, `__src_${i.sourceKey}`, r)} = ${R(t, "id", r)}${d}${ee}), JSON_ARRAY())`;
1011
1011
  }, zr = (e, t, n) => {
1012
1012
  let r = n.sql, i = n.nextAlias(), a = Br(i, t.table, t.children, n);
1013
1013
  if (a === null) return null;
1014
- let o = e.predicate ? r` WHERE ${B(e.predicate, i, r)}` : r``, s = e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${L(i, e.column, r)} DESC` : r`${L(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1014
+ let o = e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``, s = x(e).length > 0 ? r` ORDER BY ${r.csv(x(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1015
1015
  if (e.skip !== void 0) {
1016
- let t = e.order.length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1017
- l = e.take === void 0 ? r`${t} OFFSET ${z(e.skip, r)} ROWS` : r`${t} OFFSET ${z(e.skip, r)} ROWS FETCH NEXT ${z(e.take, r)} ROWS ONLY`;
1018
- } else e.take !== void 0 && (c = r`TOP ${z(e.take, r)} `);
1016
+ let t = x(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1017
+ l = e.take === void 0 ? r`${t} OFFSET ${B(e.skip, r)} ROWS` : r`${t} OFFSET ${B(e.skip, r)} ROWS FETCH NEXT ${B(e.take, r)} ROWS ONLY`;
1018
+ } else e.take !== void 0 && (c = r`TOP ${B(e.take, r)} `);
1019
1019
  let u = e.skip === void 0 ? s : r``;
1020
1020
  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}`;
1021
1021
  }, Br = (e, t, n, r, i) => {
1022
1022
  let a = r.sql, o = [];
1023
- for (let n of Object.keys(t.fields)) o.push(a`${L(e, n, a)} AS ${a(n)}`);
1024
- if (i !== void 0) for (let e of i.projection.present) o.push(a`${L(i.source.alias, i.source.physical(e), a)} AS ${Vr(`_junction.${e}`, a)}`);
1023
+ for (let n of Object.keys(t.fields)) o.push(a`${R(e, n, a)} AS ${a(n)}`);
1024
+ if (i !== void 0) for (let e of i.projection.present) o.push(a`${R(i.source.alias, i.source.physical(e), a)} AS ${Vr(`_junction.${e}`, a)}`);
1025
1025
  for (let t of n) {
1026
1026
  let n = Hr(t, e, r);
1027
1027
  if (n === null) return null;
@@ -1030,18 +1030,18 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1030
1030
  return a.csv(o);
1031
1031
  }, Vr = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), Hr = (e, t, n) => {
1032
1032
  switch (e.relation.kind) {
1033
- case "one": return $n(e) ? Gr(er(e), t, n) : Ur(e, t, n);
1033
+ case "one": return F(e) ? Gr(er(e), t, n) : Ur(e, t, n);
1034
1034
  case "many": return Gr(e, t, n);
1035
1035
  case "manyToMany": return Kr(e, t, n);
1036
1036
  }
1037
1037
  }, Ur = (e, t, n) => {
1038
1038
  let r = n.sql, i = n.nextAlias(), a = Br(i, e.target, e.children, n);
1039
1039
  if (a === null) return null;
1040
- let o = e.fkSide === "source" ? r`${L(i, "id", r)} = ${L(t, e.foreignKey, r)}` : r`${L(i, e.foreignKey, r)} = ${L(t, e.sourceKey, r)}`;
1040
+ let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`;
1041
1041
  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)}`;
1042
1042
  }, Wr = (e, t, n) => {
1043
1043
  if (e.offset !== void 0) {
1044
- let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${z(e.offset, n)} ROWS` : n`${r} OFFSET ${z(e.offset, n)} ROWS FETCH NEXT ${z(e.limit, n)} ROWS ONLY`;
1044
+ let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${B(e.offset, n)} ROWS` : n`${r} OFFSET ${B(e.offset, n)} ROWS FETCH NEXT ${B(e.limit, n)} ROWS ONLY`;
1045
1045
  return {
1046
1046
  top: n``,
1047
1047
  pagination: i,
@@ -1049,29 +1049,29 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1049
1049
  };
1050
1050
  }
1051
1051
  return {
1052
- top: e.limit === void 0 ? n`` : n`TOP ${z(e.limit, n)} `,
1052
+ top: e.limit === void 0 ? n`` : n`TOP ${B(e.limit, n)} `,
1053
1053
  pagination: n``,
1054
1054
  finalOrder: t
1055
1055
  };
1056
1056
  }, Gr = (e, t, n) => {
1057
1057
  let r = n.sql, i = n.nextAlias(), a = Br(i, e.target, e.children, n);
1058
1058
  if (a === null) return null;
1059
- let o = e.branch.where === void 0 ? r`` : r` AND ${B(e.branch.where, i, r)}`, s = F(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = Wr(e.branch, s, r);
1060
- return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${L(i, e.foreignKey, r)} = ${L(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1059
+ let o = e.branch.where === void 0 ? r`` : r` AND ${V(e.branch.where, i, r)}`, s = I(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = Wr(e.branch, s, r);
1060
+ return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1061
1061
  }, Kr = (e, t, n) => {
1062
1062
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Br(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1063
1063
  projection: e.junction,
1064
1064
  source: Dr(s)
1065
1065
  });
1066
1066
  if (c === null) return null;
1067
- let l = e.branch.where === void 0 ? r`` : r` AND ${B(e.branch.where, o, r)}`, u = V(e, s, r), d = F(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = Wr(e.branch, d, r);
1068
- 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 ${L(o, "id", r)} = ${L(s, i.targetKey, r)} WHERE ${L(s, i.sourceKey, r)} = ${L(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1069
- }, L = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, R = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), z = (e, t) => {
1067
+ let l = e.branch.where === void 0 ? r`` : r` AND ${V(e.branch.where, o, r)}`, u = H(e, s, r), d = I(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = Wr(e.branch, d, r);
1068
+ return r`ISNULL(JSON_QUERY((SELECT ${f}${c} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1069
+ }, R = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, z = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), B = (e, t) => {
1070
1070
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`literalInt: expected non-negative integer, got ${e}`);
1071
1071
  return t.unsafe(String(e));
1072
- }, B = (e, t, n) => P(qr(e, t), n), V = (e, t, n, r = !1) => {
1072
+ }, V = (e, t, n) => N(qr(e, t), n), H = (e, t, n, r = !1) => {
1073
1073
  let i = e.branch.onJunction;
1074
- return i === void 0 ? n`` : n` AND ${B(r ? H(i) : i, t, n)}`;
1074
+ return i === void 0 ? n`` : n` AND ${V(r ? U(i) : i, t, n)}`;
1075
1075
  }, qr = (e, t) => {
1076
1076
  if ("not" in e) return { not: qr(e.not, t) };
1077
1077
  if ("and" in e) return { and: e.and.map((e) => qr(e, t)) };
@@ -1089,10 +1089,10 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1089
1089
  ...n,
1090
1090
  column: `${t}.${n.column}`
1091
1091
  };
1092
- }, H = (e) => {
1093
- if ("not" in e) return { not: H(e.not) };
1094
- if ("and" in e) return { and: e.and.map((e) => H(e)) };
1095
- if ("or" in e) return { or: e.or.map((e) => H(e)) };
1092
+ }, U = (e) => {
1093
+ if ("not" in e) return { not: U(e.not) };
1094
+ if ("and" in e) return { and: e.and.map((e) => U(e)) };
1095
+ if ("or" in e) return { or: e.or.map((e) => U(e)) };
1096
1096
  if (e.op === "subquery-in" || e.op === "subquery-not-in" || e.op === "exists" || e.op === "not-exists") return e;
1097
1097
  let t = e;
1098
1098
  return {
@@ -1105,16 +1105,16 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1105
1105
  let n = e();
1106
1106
  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`);
1107
1107
  return n();
1108
- }, ei = () => $r(() => Zr.actors, "actors"), ti = () => $r(() => Zr.tenants, "tenants"), ni = v("actors", {
1109
- id: S(),
1110
- kind: D().oneOf([
1108
+ }, ei = () => $r(() => Zr.actors, "actors"), ti = () => $r(() => Zr.tenants, "tenants"), ni = w("actors", {
1109
+ id: C(),
1110
+ kind: i().oneOf([
1111
1111
  "user",
1112
1112
  "serviceAccount",
1113
1113
  "apiKey",
1114
1114
  "system"
1115
1115
  ]),
1116
- displayName: D().nullable(),
1117
- createdAt: i().default("now")
1116
+ displayName: i().nullable(),
1117
+ createdAt: S().default("now")
1118
1118
  }), ri = (e, t) => ({
1119
1119
  column: e,
1120
1120
  op: "eq",
@@ -1339,55 +1339,55 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1339
1339
  },
1340
1340
  ...a
1341
1341
  };
1342
- }, U = new xt(), Ri = (e, t) => U.run(e, t), zi = () => U.getStore(), Bi = (e) => {
1343
- let t = e ?? U.getStore();
1342
+ }, W = new St(), Ri = (e, t) => W.run(e, t), zi = () => W.getStore(), Bi = (e) => {
1343
+ let t = e ?? W.getStore();
1344
1344
  return t === void 0 ? {} : {
1345
1345
  ...t.traceId === void 0 ? {} : { traceId: t.traceId },
1346
1346
  ...t.subjectId === void 0 ? {} : { subjectId: t.subjectId },
1347
1347
  ...t.procedure === void 0 ? {} : { procedure: t.procedure }
1348
1348
  };
1349
1349
  }, Vi = (e) => {
1350
- let t = U.getStore();
1351
- return t === void 0 ? e(void 0) : U.run(t, () => e(t));
1352
- }, Hi = 3e4, Ui = 1e4, W = /* @__PURE__ */ new Map(), G = 0, Wi = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Gi = (e) => {
1353
- for (let [t, n] of W) {
1350
+ let t = W.getStore();
1351
+ return t === void 0 ? e(void 0) : W.run(t, () => e(t));
1352
+ }, Hi = 3e4, Ui = 1e4, G = /* @__PURE__ */ new Map(), K = 0, Wi = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Gi = (e) => {
1353
+ for (let [t, n] of G) {
1354
1354
  let r = n.filter((t) => e - t.at < Hi);
1355
- G -= n.length - r.length, r.length === 0 ? W.delete(t) : r.length !== n.length && W.set(t, r);
1355
+ K -= n.length - r.length, r.length === 0 ? G.delete(t) : r.length !== n.length && G.set(t, r);
1356
1356
  }
1357
1357
  }, Ki = (e, t) => {
1358
1358
  if (t.traceId === void 0 && t.subjectId === void 0 && t.procedure === void 0) return;
1359
1359
  let n = Date.now();
1360
- if (G >= Ui && Gi(n), G >= Ui) return;
1361
- let r = W.get(e);
1362
- r === void 0 ? W.set(e, [{
1360
+ if (K >= Ui && Gi(n), K >= Ui) return;
1361
+ let r = G.get(e);
1362
+ r === void 0 ? G.set(e, [{
1363
1363
  attribution: t,
1364
1364
  at: n
1365
1365
  }]) : r.push({
1366
1366
  attribution: t,
1367
1367
  at: n
1368
- }), G += 1;
1368
+ }), K += 1;
1369
1369
  }, qi = (e) => {
1370
- let t = W.get(e);
1370
+ let t = G.get(e);
1371
1371
  if (t === void 0 || t.length === 0) return;
1372
1372
  let n = t.shift();
1373
- if (--G, t.length === 0 && W.delete(e), !(Date.now() - n.at >= Hi)) return n.attribution;
1374
- }, Ji = (e) => (W.get(e)?.length ?? 0) > 0, K = /* @__PURE__ */ new Map(), q = /* @__PURE__ */ new Map(), J = /* @__PURE__ */ new Map(), Yi = 250, Xi = (e) => {
1375
- let t = q.get(e);
1373
+ if (--K, t.length === 0 && G.delete(e), !(Date.now() - n.at >= Hi)) return n.attribution;
1374
+ }, Ji = (e) => (G.get(e)?.length ?? 0) > 0, q = /* @__PURE__ */ new Map(), Yi = /* @__PURE__ */ new Map(), Xi = /* @__PURE__ */ new Map(), Zi = 250, Qi = (e) => {
1375
+ let t = Yi.get(e);
1376
1376
  if (t === void 0) return;
1377
- q.delete(e);
1378
- let n = J.get(e);
1379
- n !== void 0 && (clearTimeout(n), J.delete(e));
1377
+ Yi.delete(e);
1378
+ let n = Xi.get(e);
1379
+ n !== void 0 && (clearTimeout(n), Xi.delete(e));
1380
1380
  for (let e of t) e();
1381
- }, Zi = (e) => {
1382
- K.set(e, (K.get(e) ?? 0) + 1);
1383
- }, Qi = (e) => {
1384
- let t = (K.get(e) ?? 0) - 1;
1381
+ }, $i = (e) => {
1382
+ q.set(e, (q.get(e) ?? 0) + 1);
1383
+ }, ea = (e) => {
1384
+ let t = (q.get(e) ?? 0) - 1;
1385
1385
  if (t > 0) {
1386
- K.set(e, t);
1386
+ q.set(e, t);
1387
1387
  return;
1388
1388
  }
1389
- K.delete(e), Xi(e);
1390
- }, $i = (e, t, n, r) => {
1389
+ q.delete(e), Qi(e);
1390
+ }, ta = (e, t, n, r) => {
1391
1391
  let i = n == null ? void 0 : Wi(e, t, n), a = () => r(i === void 0 ? void 0 : qi(i));
1392
1392
  if (i === void 0) {
1393
1393
  a();
@@ -1397,8 +1397,8 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1397
1397
  a();
1398
1398
  return;
1399
1399
  }
1400
- let o = q.get(e);
1401
- if (o === void 0 && (K.get(e) ?? 0) === 0) {
1400
+ let o = Yi.get(e);
1401
+ if (o === void 0 && (q.get(e) ?? 0) === 0) {
1402
1402
  a();
1403
1403
  return;
1404
1404
  }
@@ -1406,38 +1406,38 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1406
1406
  o.push(a);
1407
1407
  return;
1408
1408
  }
1409
- q.set(e, [a]);
1410
- let s = setTimeout(() => Xi(e), Yi);
1411
- typeof s == "object" && typeof s.unref == "function" && s.unref(), J.set(e, s);
1412
- }, ea = () => {
1413
- W.clear(), G = 0, K.clear();
1414
- for (let e of J.values()) clearTimeout(e);
1415
- J.clear(), q.clear();
1416
- }, ta = () => G, Y = /* @__PURE__ */ new Map(), na = (e, t) => {
1417
- Y.set(e, {
1409
+ Yi.set(e, [a]);
1410
+ let s = setTimeout(() => Qi(e), Zi);
1411
+ typeof s == "object" && typeof s.unref == "function" && s.unref(), Xi.set(e, s);
1412
+ }, na = () => {
1413
+ G.clear(), K = 0, q.clear();
1414
+ for (let e of Xi.values()) clearTimeout(e);
1415
+ Xi.clear(), Yi.clear();
1416
+ }, ra = () => K, J = /* @__PURE__ */ new Map(), ia = (e, t) => {
1417
+ J.set(e, {
1418
1418
  recorder: t.recorder,
1419
1419
  tables: new Set(t.tables),
1420
1420
  ownTables: new Set(t.ownTables)
1421
1421
  });
1422
- }, ra = (e) => {
1423
- Y.delete(e);
1424
- }, ia = () => Y.clear(), aa = (e) => {
1425
- if (Y.size === 0) return !1;
1426
- for (let t of Y.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1422
+ }, aa = (e) => {
1423
+ J.delete(e);
1424
+ }, oa = () => J.clear(), sa = (e) => {
1425
+ if (J.size === 0) return !1;
1426
+ for (let t of J.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1427
1427
  return !1;
1428
- }, oa = async (e, t) => {
1429
- if (Y.size !== 0) for (let n of Y.values()) n.ownTables.has(t.table) || n.tables.has(t.table) && await n.recorder(e, t);
1430
- }, sa = (e) => {
1431
- if (vt.isSuccess(e)) return e.value;
1432
- throw mt.squash(e.cause);
1433
- }, ca = class extends O.TaggedError()("VersionConflict", {
1428
+ }, ca = async (e, t) => {
1429
+ if (J.size !== 0) for (let n of J.values()) n.ownTables.has(t.table) || n.tables.has(t.table) && await n.recorder(e, t);
1430
+ }, la = (e) => {
1431
+ if (bt.isSuccess(e)) return e.value;
1432
+ throw gt.squash(e.cause);
1433
+ }, ua = class extends O.TaggedError()("VersionConflict", {
1434
1434
  table: O.String,
1435
1435
  id: O.String,
1436
1436
  expected: O.Number,
1437
1437
  actual: O.NullOr(O.Number)
1438
- }) {}, la = (e) => {
1438
+ }) {}, da = (e) => {
1439
1439
  for (let [t, n] of Object.entries(e)) if (n?.definition?.versionColumn === !0) return t;
1440
- }, ua = (e) => {
1440
+ }, fa = (e) => {
1441
1441
  let { versionColumn: t, patch: n } = e;
1442
1442
  if (t === void 0) return {
1443
1443
  nextVersion: void 0,
@@ -1450,26 +1450,26 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1450
1450
  expected: i,
1451
1451
  patch: a
1452
1452
  };
1453
- }, da = (e) => {
1454
- if (e.expected !== void 0 && !(e.current !== null && e.current === e.expected)) return new ca({
1453
+ }, pa = (e) => {
1454
+ if (e.expected !== void 0 && !(e.current !== null && e.current === e.expected)) return new ua({
1455
1455
  table: e.table,
1456
1456
  id: e.id,
1457
1457
  expected: e.expected,
1458
1458
  actual: e.current
1459
1459
  });
1460
- }, fa = 1, pa = "voltro/expires", ma = () => _({
1461
- id: pa,
1462
- fields: { expiresAt: i().nullable() },
1463
- behaviors: { defaultWhere: () => "expiresAt IS NULL OR expiresAt > now()" }
1464
- }), ha = "voltro/localFirst", ga = () => _({
1460
+ }, ma = 1, ha = "voltro/expires", ga = () => ye({
1465
1461
  id: ha,
1462
+ fields: { expiresAt: S().nullable() },
1463
+ behaviors: { defaultWhere: () => "expiresAt IS NULL OR expiresAt > now()" }
1464
+ }), _a = "voltro/localFirst", va = () => ye({
1465
+ id: _a,
1466
1466
  fields: {}
1467
- }), _a = (e) => e.appliedMixins.some((e) => e.id === ha), va = (e) => {
1467
+ }), ya = (e) => e.appliedMixins.some((e) => e.id === _a), ba = (e) => {
1468
1468
  let t = [];
1469
- for (let n of Object.values(e)) _a(n) && t.push(n.tableName);
1469
+ for (let n of Object.values(e)) ya(n) && t.push(n.tableName);
1470
1470
  return t;
1471
- }, ya = class extends gt.TaggedError("TableStreamError") {}, ba = 1e3, xa = (e, t, n, r) => {
1472
- let i = yt.match(r, {
1471
+ }, xa = class extends vt.TaggedError("TableStreamError") {}, Sa = 1e3, Ca = (e, t, n, r) => {
1472
+ let i = D.match(r, {
1473
1473
  onNone: () => e.where,
1474
1474
  onSome: (n) => e.where ? bi(e.where, ai(t, n)) : ai(t, n)
1475
1475
  });
@@ -1486,56 +1486,56 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1486
1486
  ...e.includeDeleted === void 0 ? {} : { includeDeleted: e.includeDeleted },
1487
1487
  ...e.crossTenant === void 0 ? {} : { crossTenant: e.crossTenant }
1488
1488
  };
1489
- }, Sa = (e, t) => {
1490
- let n = t.pk ?? "id", r = t.chunkSize ?? ba;
1491
- return bt.paginateChunkEffect(yt.none(), (i) => {
1492
- let a = _t.tryPromise({
1493
- try: () => e.query(xa(t, n, r, i)),
1494
- catch: (e) => new ya({
1489
+ }, wa = (e, t) => {
1490
+ let n = t.pk ?? "id", r = t.chunkSize ?? Sa;
1491
+ return xt.paginateChunkEffect(D.none(), (i) => {
1492
+ let a = yt.tryPromise({
1493
+ try: () => e.query(Ca(t, n, r, i)),
1494
+ catch: (e) => new xa({
1495
1495
  table: t.table,
1496
1496
  cause: e
1497
1497
  })
1498
1498
  });
1499
- return (t.retry ? a.pipe(_t.retry(t.retry)) : a).pipe(_t.map((e) => [ht.fromIterable(e), e.length === r && e.length > 0 ? yt.some(yt.some(e[e.length - 1][n])) : yt.none()]));
1499
+ return (t.retry ? a.pipe(yt.retry(t.retry)) : a).pipe(yt.map((e) => [_t.fromIterable(e), e.length === r && e.length > 0 ? D.some(D.some(e[e.length - 1][n])) : D.none()]));
1500
1500
  });
1501
- }, Ca = (e) => {
1502
- let t = e.alpha ?? .5;
1503
- if (t < 0 || t > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${t}`);
1504
- return (n) => {
1505
- let r = Array.isArray(e.vector.query) ? {
1501
+ }, Ta = (e) => {
1502
+ let n = e.alpha ?? .5;
1503
+ if (n < 0 || n > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${n}`);
1504
+ return (r) => {
1505
+ let i = Array.isArray(e.vector.query) ? {
1506
1506
  column: e.vector.col,
1507
1507
  queryVector: e.vector.query,
1508
1508
  distance: e.vector.distance ?? "cosine",
1509
- alpha: t
1509
+ alpha: n
1510
1510
  } : {
1511
1511
  column: e.vector.col,
1512
1512
  queryText: e.vector.query,
1513
1513
  distance: e.vector.distance ?? "cosine",
1514
- alpha: t
1515
- }, i = ze(n.table, e.fts.indexName, n.fullTextIndexes);
1514
+ alpha: n
1515
+ }, a = t(r.table, e.fts.indexName, r.fullTextIndexes);
1516
1516
  return {
1517
- ...n,
1518
- annClause: r,
1517
+ ...r,
1518
+ annClause: i,
1519
1519
  fullTextSearch: {
1520
1520
  indexName: e.fts.indexName,
1521
1521
  query: e.fts.query,
1522
- columns: i.columns,
1523
- ...i.config === void 0 ? {} : { config: i.config },
1524
- ...i.weights === void 0 ? {} : { weights: i.weights }
1522
+ columns: a.columns,
1523
+ ...a.config === void 0 ? {} : { config: a.config },
1524
+ ...a.weights === void 0 ? {} : { weights: a.weights }
1525
1525
  }
1526
1526
  };
1527
1527
  };
1528
- }, wa = async (e, t) => {
1528
+ }, Ea = async (e, t) => {
1529
1529
  let n = e.as ?? "embedding", r = t.row[e.from];
1530
1530
  if (typeof r != "string" || r.length === 0) return {};
1531
1531
  let i = await t.embed(r);
1532
1532
  return { [n]: i };
1533
- }, Ta = (e) => {
1533
+ }, Da = (e) => {
1534
1534
  if (!Number.isInteger(e.dimensions) || e.dimensions <= 0) throw Error(`vectorEmbedding: dimensions must be a positive integer, got ${String(e.dimensions)}.`);
1535
- let t = e.as ?? "embedding", n = (t) => wa(e, t);
1536
- return _({
1535
+ let t = e.as ?? "embedding", n = (t) => Ea(e, t);
1536
+ return ye({
1537
1537
  id: "voltro/vectorEmbedding",
1538
- fields: { [t]: me(e.dimensions) },
1538
+ fields: { [t]: h(e.dimensions) },
1539
1539
  ...e.index === !1 ? {} : { indexes: [{
1540
1540
  fields: [t],
1541
1541
  kind: "hnsw",
@@ -1550,19 +1550,19 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1550
1550
  beforeUpdate: n
1551
1551
  }
1552
1552
  });
1553
- }, Ea = 63, Da = "br_pr", X = class extends Error {
1553
+ }, Oa = 63, ka = "br_pr", Y = class extends Error {
1554
1554
  _tag = "BranchNameInvalid";
1555
1555
  constructor(e) {
1556
1556
  super(e), this.name = "BranchNameInvalid";
1557
1557
  }
1558
- }, Oa = (e, t) => {
1559
- if (!Number.isInteger(t) || t < 0) throw new X(`prNumber must be a non-negative integer, got ${String(t)}`);
1560
- let n = Mn(e);
1561
- if (n.replace(/_/g, "") === "") throw new X(`app slug '${e}' has no usable identifier characters`);
1562
- let r = `${Da}${t}_${n}`;
1563
- if (r.length > Ea) throw new X(`branch namespace '${r}' exceeds the ${Ea}-byte identifier limit — use a shorter app slug`);
1558
+ }, Aa = (e, t) => {
1559
+ if (!Number.isInteger(t) || t < 0) throw new Y(`prNumber must be a non-negative integer, got ${String(t)}`);
1560
+ let n = Fn(e);
1561
+ if (n.replace(/_/g, "") === "") throw new Y(`app slug '${e}' has no usable identifier characters`);
1562
+ let r = `${ka}${t}_${n}`;
1563
+ if (r.length > Oa) throw new Y(`branch namespace '${r}' exceeds the ${Oa}-byte identifier limit — use a shorter app slug`);
1564
1564
  return r;
1565
- }, ka = (e) => e.startsWith(Da), Aa = {
1565
+ }, ja = (e) => e.startsWith(ka), Ma = {
1566
1566
  requested: {
1567
1567
  provision: "provisioning",
1568
1568
  destroy: "destroying"
@@ -1581,19 +1581,19 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1581
1581
  fail: "failed"
1582
1582
  },
1583
1583
  destroyed: {}
1584
- }, ja = class extends Error {
1584
+ }, Na = class extends Error {
1585
1585
  from;
1586
1586
  event;
1587
1587
  _tag = "BranchTransitionInvalid";
1588
1588
  constructor(e, t) {
1589
1589
  super(`invalid branch transition: ${e} --${t}-->`), this.from = e, this.event = t, this.name = "BranchTransitionInvalid";
1590
1590
  }
1591
- }, Ma = (e, t) => {
1592
- let n = Aa[e][t];
1593
- if (n === void 0) throw new ja(e, t);
1591
+ }, Pa = (e, t) => {
1592
+ let n = Ma[e][t];
1593
+ if (n === void 0) throw new Na(e, t);
1594
1594
  return n;
1595
- }, Na = (e, t, n, r) => {
1596
- if (n === "copy" && (r === void 0 || r === "")) throw new X("seed 'copy' requires a parentNamespace to snapshot from");
1595
+ }, Fa = (e, t, n, r) => {
1596
+ if (n === "copy" && (r === void 0 || r === "")) throw new Y("seed 'copy' requires a parentNamespace to snapshot from");
1597
1597
  let i = [{
1598
1598
  kind: "create-namespace",
1599
1599
  detail: e
@@ -1613,13 +1613,13 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1613
1613
  detail: `run boot seeds into ${e}`
1614
1614
  });
1615
1615
  return i;
1616
- }, Pa = (e) => {
1617
- if (!ka(e)) throw new X(`refusing to plan teardown of '${e}' — not a branch namespace`);
1616
+ }, Ia = (e) => {
1617
+ if (!ja(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
1618
1618
  return [{
1619
1619
  kind: "drop-namespace",
1620
1620
  detail: e
1621
1621
  }];
1622
- }, Fa = (e) => {
1622
+ }, La = (e) => {
1623
1623
  if (e === void 0 || e === "") return !1;
1624
1624
  try {
1625
1625
  let t = new URL(e).hostname.toLowerCase();
@@ -1627,27 +1627,27 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1627
1627
  } catch {
1628
1628
  return /\bneon\.(tech|build)\b/i.test(e);
1629
1629
  }
1630
- }, Ia = (e) => e.prefer === void 0 ? e.seed === "copy" && Fa(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, La = (e, t = {}) => [{
1630
+ }, Ra = (e) => e.prefer === void 0 ? e.seed === "copy" && La(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, za = (e, t = {}) => [{
1631
1631
  kind: "neon-branch-create",
1632
1632
  detail: `${t.parentBranch ?? "main"} → ${e} (copy-on-write)`
1633
- }], Ra = (e) => {
1634
- if (!ka(e)) throw new X(`refusing to plan teardown of '${e}' — not a branch namespace`);
1633
+ }], Ba = (e) => {
1634
+ if (!ja(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
1635
1635
  return [{
1636
1636
  kind: "neon-branch-delete",
1637
1637
  detail: e
1638
1638
  }];
1639
- }, za = (e) => e.mechanism === "neon-cow" ? La(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : Na(e.branchId, e.tableNames, e.seed, e.parentNamespace), Ba = (e, t) => e === "neon-cow" ? Ra(t) : Pa(t), Va = (e, t, n) => {
1639
+ }, Va = (e) => e.mechanism === "neon-cow" ? za(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : Fa(e.branchId, e.tableNames, e.seed, e.parentNamespace), Ha = (e, t) => e === "neon-cow" ? Ba(t) : Ia(t), Ua = (e, t, n) => {
1640
1640
  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);
1641
1641
  return {
1642
1642
  evict: i,
1643
1643
  rejectNew: r.filter((e) => !a.has(e.namespace)).length >= t.maxBranches
1644
1644
  };
1645
- }, Ha = async (e, t) => {
1646
- let n = Oa(e.appSlug, e.prNumber), r = Ia({
1645
+ }, Wa = async (e, t) => {
1646
+ let n = Aa(e.appSlug, e.prNumber), r = Ra({
1647
1647
  seed: e.seed,
1648
1648
  ...e.dbUrl === void 0 ? {} : { dbUrl: e.dbUrl },
1649
1649
  ...e.prefer === void 0 ? {} : { prefer: e.prefer }
1650
- }), i = za({
1650
+ }), i = Va({
1651
1651
  mechanism: r,
1652
1652
  branchId: n,
1653
1653
  tableNames: e.tableNames,
@@ -1672,33 +1672,33 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1672
1672
  mechanism: r,
1673
1673
  steps: i
1674
1674
  };
1675
- }, Ua = async (e, t, n) => {
1676
- let r = Ba(t, e);
1675
+ }, Ga = async (e, t, n) => {
1676
+ let r = Ha(t, e);
1677
1677
  return t === "neon-cow" ? await n.neonBranchDelete(e) : await n.dropNamespace(e), r;
1678
- }, Wa = (e, t, n) => Va(e, t, n), Z = (e) => `"${e.replace(/"/g, "\"\"")}"`, Ga = (e) => {
1678
+ }, Ka = (e, t, n) => Ua(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, qa = (e) => {
1679
1679
  let t = () => {
1680
1680
  throw Error("namespace branch executor: Neon ops require a neon-cow executor (use a Neon connection for copy-on-write branches)");
1681
1681
  };
1682
1682
  return {
1683
- createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${Z(t)}`),
1684
- createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${Z(t)}.${Z(n)} (LIKE ${Z(n)} INCLUDING ALL)`),
1685
- copyTable: (t, n, r) => e.run(`INSERT INTO ${Z(n)}.${Z(r)} SELECT * FROM ${Z(t)}.${Z(r)}`),
1686
- dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${Z(t)} CASCADE`),
1683
+ createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${X(t)}`),
1684
+ createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${X(t)}.${X(n)} (LIKE ${X(n)} INCLUDING ALL)`),
1685
+ copyTable: (t, n, r) => e.run(`INSERT INTO ${X(n)}.${X(r)} SELECT * FROM ${X(t)}.${X(r)}`),
1686
+ dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${X(t)} CASCADE`),
1687
1687
  neonBranchCreate: t,
1688
1688
  neonBranchDelete: t
1689
1689
  };
1690
- }, Ka = class extends Error {
1690
+ }, Ja = class extends Error {
1691
1691
  _tag = "TenantResidencyUnresolved";
1692
1692
  constructor(e) {
1693
1693
  super(e), this.name = "TenantResidencyUnresolved";
1694
1694
  }
1695
- }, qa = class extends Error {
1695
+ }, Ya = class extends Error {
1696
1696
  region;
1697
1697
  _tag = "TenantRegionUnavailable";
1698
1698
  constructor(e, t) {
1699
1699
  super(t), this.region = e, this.name = "TenantRegionUnavailable";
1700
1700
  }
1701
- }, Ja, Ya = (e) => {
1701
+ }, Xa, Za = (e) => {
1702
1702
  if (e.homes === void 0) throw Error("setResidencyConfig: `homes` is required");
1703
1703
  if (e.servableRegions === void 0 || e.servableRegions.length === 0) throw Error("setResidencyConfig: `servableRegions` must be non-empty (which regions this deployment serves)");
1704
1704
  let t = /* @__PURE__ */ new Map();
@@ -1707,98 +1707,98 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1707
1707
  if (e !== void 0 && e !== n.region) throw Error(`residency: tenant '${n.tenantId}' is mapped to two regions ('${e}' and '${n.region}')`);
1708
1708
  t.set(n.tenantId, n.region);
1709
1709
  }
1710
- return Ja = e, e;
1711
- }, Xa = () => Ja, Za = () => {
1712
- Ja = void 0;
1713
- }, Qa = (e, t) => {
1714
- if (e == null || e === "") throw new Ka("residency is on but the request has no resolvable tenant — refusing to bind a store");
1710
+ return Xa = e, e;
1711
+ }, Qa = () => Xa, $a = () => {
1712
+ Xa = void 0;
1713
+ }, eo = (e, t) => {
1714
+ if (e == null || e === "") throw new Ja("residency is on but the request has no resolvable tenant — refusing to bind a store");
1715
1715
  let n = t.homes.find((t) => t.tenantId === e);
1716
- if (n === void 0) throw new Ka(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
1716
+ if (n === void 0) throw new Ja(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
1717
1717
  return n;
1718
- }, $a = (e, t) => t.servableRegions.includes(e), eo = (e, t) => {
1719
- let n = Qa(e.tenantId, t), r = Nn(n.tenantId);
1718
+ }, to = (e, t) => t.servableRegions.includes(e), no = (e, t) => {
1719
+ let n = eo(e.tenantId, t), r = In(n.tenantId);
1720
1720
  return {
1721
1721
  region: n.region,
1722
1722
  namespace: r,
1723
1723
  ...n.connectionKey === void 0 ? {} : { connectionKey: n.connectionKey }
1724
1724
  };
1725
- }, to = (e, t, n) => {
1726
- let r = eo(e, t);
1727
- if (!$a(r.region, t)) throw new qa(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
1725
+ }, ro = (e, t, n) => {
1726
+ let r = no(e, t);
1727
+ if (!to(r.region, t)) throw new Ya(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
1728
1728
  let i = n.get(r.region);
1729
- if (i === void 0) throw new qa(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
1729
+ if (i === void 0) throw new Ya(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
1730
1730
  return {
1731
1731
  store: i,
1732
1732
  placement: r
1733
1733
  };
1734
- }, no = async (e, t, n, r) => {
1735
- let { store: i, placement: a } = to(e, t, n);
1734
+ }, io = async (e, t, n, r) => {
1735
+ let { store: i, placement: a } = ro(e, t, n);
1736
1736
  return await r(i, a), a;
1737
- }, ro = (e) => {
1737
+ }, ao = (e) => {
1738
1738
  if (typeof e == "string") return e;
1739
1739
  if ("jsonPath" in e) {
1740
1740
  let { column: t, path: n, numeric: r } = e.jsonPath;
1741
1741
  return `(json:${t}->${n.join(".")}${r ? "::num" : ""})`;
1742
1742
  }
1743
1743
  return `(${e.expr})`;
1744
- }, Q = (e) => e.map(ro), io = (e, t) => {
1744
+ }, Z = (e) => e.map(ao), oo = (e, t) => {
1745
1745
  if (e.length !== t.length) return !1;
1746
- for (let n = 0; n < e.length; n++) if (ro(e[n]) !== ro(t[n])) return !1;
1746
+ for (let n = 0; n < e.length; n++) if (ao(e[n]) !== ao(t[n])) return !1;
1747
1747
  return !0;
1748
- }, ao = (e, t) => {
1748
+ }, so = (e, t) => {
1749
1749
  if (e.length >= t.length) return !1;
1750
- for (let n = 0; n < e.length; n++) if (ro(e[n]) !== ro(t[n])) return !1;
1750
+ for (let n = 0; n < e.length; n++) if (ao(e[n]) !== ao(t[n])) return !1;
1751
1751
  return !0;
1752
- }, oo = (e) => {
1752
+ }, co = (e) => {
1753
1753
  let t = [], n = e.appliedIndexes, r = e.tableName;
1754
1754
  for (let e = 0; e < n.length; e++) {
1755
1755
  let i = n[e];
1756
1756
  for (let a = e + 1; a < n.length; a++) {
1757
1757
  let e = n[a];
1758
- if (io(i.fields, e.fields)) {
1758
+ if (oo(i.fields, e.fields)) {
1759
1759
  let [n, a] = i.name < e.name ? [i, e] : [e, i];
1760
1760
  t.push({
1761
1761
  kind: "duplicate-fields",
1762
1762
  table: r,
1763
1763
  redundant: n,
1764
1764
  coveredBy: a,
1765
- message: `'${r}' has two indexes on the same fields [${Q(i.fields).join(", ")}]: '${i.name}' and '${e.name}'. The B-tree engine builds both, costing write throughput + disk space for no read benefit. Drop '${n.name}' (or '${a.name}' if you prefer the other name). Applies to every supported dialect (Postgres / MySQL / MariaDB / MSSQL / SQLite).`
1765
+ message: `'${r}' has two indexes on the same fields [${Z(i.fields).join(", ")}]: '${i.name}' and '${e.name}'. The B-tree engine builds both, costing write throughput + disk space for no read benefit. Drop '${n.name}' (or '${a.name}' if you prefer the other name). Applies to every supported dialect (Postgres / MySQL / MariaDB / MSSQL / SQLite).`
1766
1766
  });
1767
1767
  continue;
1768
1768
  }
1769
- ao(i.fields, e.fields) ? t.push({
1769
+ so(i.fields, e.fields) ? t.push({
1770
1770
  kind: "redundant-prefix",
1771
1771
  table: r,
1772
1772
  redundant: i,
1773
1773
  coveredBy: e,
1774
- 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).`
1775
- }) : ao(e.fields, i.fields) && t.push({
1774
+ message: `'${r}' index '${i.name}' on [${Z(i.fields).join(", ")}] is a leading prefix of '${e.name}' on [${Z(e.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Z(i.fields).join(", ")}] query from '${e.name}' too via the leading-prefix rule, so '${i.name}' adds write cost without read benefit. Drop '${i.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
1775
+ }) : so(e.fields, i.fields) && t.push({
1776
1776
  kind: "redundant-prefix",
1777
1777
  table: r,
1778
1778
  redundant: e,
1779
1779
  coveredBy: i,
1780
- message: `'${r}' index '${e.name}' on [${Q(e.fields).join(", ")}] is a leading prefix of '${i.name}' on [${Q(i.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Q(e.fields).join(", ")}] query from '${i.name}' too via the leading-prefix rule, so '${e.name}' adds write cost without read benefit. Drop '${e.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
1780
+ message: `'${r}' index '${e.name}' on [${Z(e.fields).join(", ")}] is a leading prefix of '${i.name}' on [${Z(i.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Z(e.fields).join(", ")}] query from '${i.name}' too via the leading-prefix rule, so '${e.name}' adds write cost without read benefit. Drop '${e.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
1781
1781
  });
1782
1782
  }
1783
1783
  }
1784
1784
  return t;
1785
- }, so = (e) => {
1785
+ }, lo = (e) => {
1786
1786
  let t = [];
1787
- for (let n of e) t.push(...oo(n));
1787
+ for (let n of e) t.push(...co(n));
1788
1788
  return t;
1789
- }, co = "\x1B[", lo = `${co}38;2;245;158;11m`, uo = `${co}38;2;16;185;129m`, fo = (e, t) => `${e}${t}${k.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : fo(t, n) : n, po = (e, t = {}) => {
1790
- let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, k.dim, e.padEnd(11)), a = (e) => $(n, (e) => k.bold(k.brand(e)), e), o = (e) => $(n, k.brightRed24, e), s = (e) => $(n, uo, e), c = (e) => $(n, lo, e), l = (e) => $(n, k.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, k.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
1789
+ }, uo = "\x1B[", fo = `${uo}38;2;245;158;11m`, po = `${uo}38;2;16;185;129m`, mo = (e, t) => `${e}${t}${k.reset}`, Q = (e, t, n) => e ? typeof t == "function" ? t(n) : mo(t, n) : n, ho = (e, t = {}) => {
1790
+ let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => Q(n, k.dim, e.padEnd(11)), a = (e) => Q(n, (e) => k.bold(k.brand(e)), e), o = (e) => Q(n, k.brightRed24, e), s = (e) => Q(n, po, e), c = (e) => Q(n, fo, e), l = (e) => Q(n, k.dim, e), u = `${c("index audit")} ${l("·")} ${Q(n, k.bold, e.kind)}`, d = e.redundant.fields.length, f = Z(e.coveredBy.fields.slice(d)), p = (e, t) => {
1791
1791
  let n = e.slice(0, t), r = e.slice(t), i = [];
1792
1792
  return n.length > 0 && i.push(s(`[${n.join(", ")}]`)), r.length > 0 && i.push(c(`+ [${r.join(", ")}]`)), i.join(" ");
1793
1793
  }, m = [];
1794
- 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, k.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");
1795
- }, mo = (e, t) => ({
1794
+ return m.push(u), m.push(""), m.push(`${i("table")}${a(e.table)}`), m.push(""), m.push(`${i("redundant")}${o(e.redundant.name)}`), m.push(`${i("")}${p(Z(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Z(e.coveredBy.fields), d)}`), f.length > 0 && m.push(`${i("")}${l(`└ extra columns: ${f.join(", ")}`)}`), m.push(""), e.kind === "redundant-prefix" ? (m.push(`${i("why")}B-tree indexes serve queries that filter on a LEADING PREFIX of`), m.push(`${i("")}their column list. The wider index already covers every`), m.push(`${i("")}query the narrower one can serve.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)) : (m.push(`${i("why")}Two indexes on the same columns under different names.`), m.push(`${i("")}The B-tree engine builds both — same coverage, double cost.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)), m.push(""), m.push(`${i("cost")}Every ${a("INSERT")} / ${a("UPDATE")} / ${a("DELETE")} on this table writes`), m.push(`${i("")}to ${Q(n, k.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");
1795
+ }, go = (e, t) => ({
1796
1796
  name: e,
1797
1797
  body: t
1798
- }), ho = (e) => {
1798
+ }), _o = (e) => {
1799
1799
  if (e.lifecycle === "cron" && !e.cron) throw Error(`seed "${e.id}": lifecycle 'cron' requires a 'cron' field`);
1800
1800
  if (e.lifecycle === "onSchemaChange" && (!e.watchedTables || e.watchedTables.length === 0)) throw Error(`seed "${e.id}": lifecycle 'onSchemaChange' requires at least one entry in 'watchedTables'`);
1801
- let t = e.steps({ step: mo });
1801
+ let t = e.steps({ step: go });
1802
1802
  if (t.length === 0) throw Error(`seed "${e.id}": at least one step is required`);
1803
1803
  return {
1804
1804
  __seed: !0,
@@ -1810,13 +1810,13 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1810
1810
  ...e.fingerprint === void 0 ? {} : { fingerprint: e.fingerprint },
1811
1811
  steps: t
1812
1812
  };
1813
- }, go = (e) => typeof e == "object" && !!e && "__seed" in e && e.__seed === !0, _o = (e, { apply: t, undo: n }) => ({
1813
+ }, vo = (e) => typeof e == "object" && !!e && "__seed" in e && e.__seed === !0, yo = (e, { apply: t, undo: n }) => ({
1814
1814
  name: e,
1815
1815
  apply: t,
1816
1816
  undo: n
1817
- }), vo = (e) => {
1817
+ }), bo = (e) => {
1818
1818
  if (!/^\d{14}_/.test(e.id)) throw Error(`migration "${e.id}": id must start with a 14-digit timestamp followed by "_" (convention: <YYYYMMDDHHMMSS>_<slug>)`);
1819
- let t = e.steps({ step: _o });
1819
+ let t = e.steps({ step: yo });
1820
1820
  if (t.length === 0) throw Error(`migration "${e.id}": at least one step is required`);
1821
1821
  return {
1822
1822
  __migration: !0,
@@ -1824,145 +1824,145 @@ var Ct = (e) => typeof e == "string" && e !== "" ? e : null, wt = async (e, t, n
1824
1824
  name: e.name,
1825
1825
  steps: t
1826
1826
  };
1827
- }, yo = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, bo = v("_voltro_migrations", {
1828
- id: S({ prefix: "mig" }),
1829
- name: D(),
1830
- hash: D(),
1831
- status: D(),
1832
- appliedAt: i().nullable(),
1833
- durationMs: T().nullable(),
1834
- errorMessage: D().nullable(),
1835
- errorStack: D().nullable(),
1836
- workflowRunId: D().nullable(),
1837
- createdAt: i().default("now"),
1838
- updatedAt: i().default("now").onUpdate("now")
1839
- }).index(["status"]), xo = v("_voltro_seeds", {
1840
- id: S({ prefix: "seed" }),
1841
- name: D(),
1842
- lifecycle: D(),
1843
- fingerprint: D(),
1844
- cronSchedule: D().nullable(),
1845
- watchedTables: w().nullable(),
1846
- nextRunAt: i().nullable(),
1847
- lastRunStatus: D().nullable(),
1848
- lastRunAt: i().nullable(),
1849
- lastRunDurationMs: T().nullable(),
1850
- lastRunRowsTouched: T().nullable(),
1851
- lastError: D().nullable(),
1852
- workflowRunId: D().nullable(),
1853
- createdAt: i().default("now"),
1854
- updatedAt: i().default("now").onUpdate("now")
1855
- }).index(["lifecycle"]).index(["nextRunAt"]), So = v("_voltro_migration_plans", {
1856
- id: S({ prefix: "plan" }),
1857
- fingerprint: D(),
1858
- liveFingerprint: D().nullable(),
1859
- operations: w(),
1860
- rollbackPlan: w().nullable(),
1861
- appliedBy: D(),
1862
- environment: D(),
1863
- source: D(),
1864
- onlineStrategy: D().nullable(),
1865
- durationMs: T(),
1866
- notes: D().nullable(),
1867
- squashedAt: i().nullable(),
1868
- appliedAt: i().default("now"),
1869
- createdAt: i().default("now"),
1870
- updatedAt: i().default("now").onUpdate("now")
1871
- }).index(["fingerprint"]).index(["environment"]), Co = v("_voltro_idempotency", {
1872
- id: S({ prefix: "idem" }),
1873
- scope: D(),
1874
- key: D(),
1875
- status: D(),
1876
- response: w().nullable(),
1877
- createdAt: i().default("now")
1878
- }).unique(["scope", "key"]).index(["createdAt"]), wo = v("_voltro_kv", {
1879
- id: S({ prefix: "kv" }),
1880
- key: D().unique(),
1881
- value: D().nullable(),
1882
- expiresAt: i().nullable(),
1883
- createdAt: i().default("now"),
1884
- updatedAt: i().default("now").onUpdate("now")
1885
- }).index(["expiresAt"]), To = v("_voltro_api_keys", {
1886
- id: S({ prefix: "apikey" }),
1887
- tenantId: D().nullable(),
1888
- name: D(),
1889
- hashedKey: D().maxLength(64).unique(),
1890
- keyPrefix: D(),
1891
- scopes: w().nullable(),
1892
- lastUsedAt: i().nullable(),
1893
- requestCount: T().default(0),
1894
- expiresAt: i().nullable(),
1895
- revokedAt: i().nullable(),
1896
- createdBy: D().nullable(),
1897
- onBehalfOf: D().nullable(),
1898
- metadata: w().nullable(),
1899
- createdAt: i().default("now")
1900
- }).index("byApiKeyTenant", ["tenantId"]), Eo = [
1901
- bo,
1902
- xo,
1903
- So
1904
- ], Do = "id", Oo = (e, t) => {
1905
- let n = C(e);
1906
- if (n === void 0) return t;
1907
- let r = n.fields[Do]?.idScheme;
1908
- if (r === void 0 || t[Do] != null) return t;
1909
- if (r.kind === "numeric") {
1910
- if (!(Do in t)) return t;
1911
- let e = { ...t };
1912
- return delete e[Do], e;
1913
- }
1914
- let i = oe(r, e);
1915
- return i === null ? t : {
1916
- ...t,
1917
- [Do]: i
1827
+ }, xo = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, So = w("_voltro_migrations", {
1828
+ id: C({ prefix: "mig" }),
1829
+ name: i(),
1830
+ hash: i(),
1831
+ status: i(),
1832
+ appliedAt: S().nullable(),
1833
+ durationMs: n().nullable(),
1834
+ errorMessage: i().nullable(),
1835
+ errorStack: i().nullable(),
1836
+ workflowRunId: i().nullable(),
1837
+ createdAt: S().default("now"),
1838
+ updatedAt: S().default("now").onUpdate("now")
1839
+ }).index(["status"]), Co = w("_voltro_seeds", {
1840
+ id: C({ prefix: "seed" }),
1841
+ name: i(),
1842
+ lifecycle: i(),
1843
+ fingerprint: i(),
1844
+ cronSchedule: i().nullable(),
1845
+ watchedTables: y().nullable(),
1846
+ nextRunAt: S().nullable(),
1847
+ lastRunStatus: i().nullable(),
1848
+ lastRunAt: S().nullable(),
1849
+ lastRunDurationMs: n().nullable(),
1850
+ lastRunRowsTouched: n().nullable(),
1851
+ lastError: i().nullable(),
1852
+ workflowRunId: i().nullable(),
1853
+ createdAt: S().default("now"),
1854
+ updatedAt: S().default("now").onUpdate("now")
1855
+ }).index(["lifecycle"]).index(["nextRunAt"]), wo = w("_voltro_migration_plans", {
1856
+ id: C({ prefix: "plan" }),
1857
+ fingerprint: i(),
1858
+ liveFingerprint: i().nullable(),
1859
+ operations: y(),
1860
+ rollbackPlan: y().nullable(),
1861
+ appliedBy: i(),
1862
+ environment: i(),
1863
+ source: i(),
1864
+ onlineStrategy: i().nullable(),
1865
+ durationMs: n(),
1866
+ notes: i().nullable(),
1867
+ squashedAt: S().nullable(),
1868
+ appliedAt: S().default("now"),
1869
+ createdAt: S().default("now"),
1870
+ updatedAt: S().default("now").onUpdate("now")
1871
+ }).index(["fingerprint"]).index(["environment"]), To = w("_voltro_idempotency", {
1872
+ id: C({ prefix: "idem" }),
1873
+ scope: i(),
1874
+ key: i(),
1875
+ status: i(),
1876
+ response: y().nullable(),
1877
+ createdAt: S().default("now")
1878
+ }).unique(["scope", "key"]).index(["createdAt"]), Eo = w("_voltro_kv", {
1879
+ id: C({ prefix: "kv" }),
1880
+ key: i().unique(),
1881
+ value: i().nullable(),
1882
+ expiresAt: S().nullable(),
1883
+ createdAt: S().default("now"),
1884
+ updatedAt: S().default("now").onUpdate("now")
1885
+ }).index(["expiresAt"]), Do = w("_voltro_api_keys", {
1886
+ id: C({ prefix: "apikey" }),
1887
+ tenantId: i().nullable(),
1888
+ name: i(),
1889
+ hashedKey: i().maxLength(64).unique(),
1890
+ keyPrefix: i(),
1891
+ scopes: y().nullable(),
1892
+ lastUsedAt: S().nullable(),
1893
+ requestCount: n().default(0),
1894
+ expiresAt: S().nullable(),
1895
+ revokedAt: S().nullable(),
1896
+ createdBy: i().nullable(),
1897
+ onBehalfOf: i().nullable(),
1898
+ metadata: y().nullable(),
1899
+ createdAt: S().default("now")
1900
+ }).index("byApiKeyTenant", ["tenantId"]), Oo = [
1901
+ So,
1902
+ Co,
1903
+ wo
1904
+ ], $ = "id", ko = (t, n) => {
1905
+ let r = E(t);
1906
+ if (r === void 0) return n;
1907
+ let i = r.fields[$]?.idScheme;
1908
+ if (i === void 0 || n[$] != null) return n;
1909
+ if (i.kind === "numeric") {
1910
+ if (!($ in n)) return n;
1911
+ let e = { ...n };
1912
+ return delete e[$], e;
1913
+ }
1914
+ let a = e(i, t);
1915
+ return a === null ? n : {
1916
+ ...n,
1917
+ [$]: a
1918
1918
  };
1919
- }, ko = (e, t) => t.map((t) => Oo(e, t)), Ao = (e, t) => {
1919
+ }, Ao = (e, t) => t.map((t) => ko(e, t)), jo = (e, t) => {
1920
1920
  let n = [], r = t;
1921
1921
  for (let [t, i] of Object.entries(e.fields)) {
1922
1922
  let e = i;
1923
1923
  e.nullable || e.hasDefault || e.idScheme !== void 0 || e.generatedAs !== void 0 || (r[t] === void 0 || r[t] === null) && n.push(t);
1924
1924
  }
1925
1925
  return n;
1926
- }, jo = (e, t) => {
1926
+ }, Mo = (e, t) => {
1927
1927
  let n = t;
1928
1928
  return e.filter((e) => n[e] === void 0 || n[e] === null);
1929
- }, Mo = (e, t, n) => e.insert(t.tableName, n), No = (e, t, n, r) => e.upsert(t.tableName, n, {
1929
+ }, No = (e, t, n) => e.insert(t.tableName, n), Po = (e, t, n, r) => e.upsert(t.tableName, n, {
1930
1930
  conflictColumns: r.conflictColumns,
1931
1931
  ...r.update === void 0 ? {} : { update: r.update }
1932
- }), Po = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), Fo = 512, Io = (e) => {
1932
+ }), Fo = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), Io = 512, Lo = (e) => {
1933
1933
  e.setMaxListeners(512);
1934
- }, Lo = (e, t, n) => ({
1934
+ }, Ro = (e, t, n) => ({
1935
1935
  _tag: "PrimaryKeyConflictError",
1936
1936
  table: e,
1937
1937
  key: t,
1938
1938
  cause: n
1939
- }), Ro = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", zo = /* @__PURE__ */ new Map(), Bo = (e) => {
1939
+ }), zo = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", Bo = /* @__PURE__ */ new Map(), Vo = (e) => {
1940
1940
  if (!e.table || !e.timeColumn) throw Error("registerRetention: table + timeColumn are required");
1941
1941
  if (!Number.isFinite(e.ttlMs) || e.ttlMs <= 0) throw Error(`registerRetention(${e.table}): ttlMs must be a positive number`);
1942
- zo.set(e.table, e);
1943
- }, Vo = () => [...zo.values()], Ho = () => zo.clear(), Uo = async (e, t, n, r = 2e4) => {
1942
+ Bo.set(e.table, e);
1943
+ }, Ho = () => [...Bo.values()], Uo = () => Bo.clear(), Wo = async (e, t, n, r = 2e4) => {
1944
1944
  let i = new Date(t - e.ttlMs), a = 0;
1945
1945
  for (;;) {
1946
1946
  let t = await n(e.table, e.timeColumn, i, r, e.where);
1947
1947
  if (a += t, t < r) break;
1948
1948
  }
1949
1949
  return a;
1950
- }, Wo = (e, t) => {
1950
+ }, Go = (e, t) => {
1951
1951
  let n = Number(e ?? String(t));
1952
1952
  return (Number.isFinite(n) && n > 0 ? n : t) * 36e5;
1953
- }, Go = "_voltro_cdc_offsets", Ko = v(Go, {
1954
- id: S({ prefix: "cdcoff" }),
1955
- replicaId: D(),
1956
- streamName: D(),
1957
- binlogFile: D(),
1958
- binlogPosition: D(),
1959
- updatedAt: i()
1960
- }).index(["replicaId"]), qo = v(Go, {
1961
- id: S({ prefix: "cdcoff" }),
1962
- replicaId: D(),
1963
- streamName: D(),
1964
- ctVersion: D(),
1965
- updatedAt: i()
1966
- }).index(["replicaId"]), Jo = "postgres";
1953
+ }, Ko = "_voltro_cdc_offsets", qo = w(Ko, {
1954
+ id: C({ prefix: "cdcoff" }),
1955
+ replicaId: i(),
1956
+ streamName: i(),
1957
+ binlogFile: i(),
1958
+ binlogPosition: i(),
1959
+ updatedAt: S()
1960
+ }).index(["replicaId"]), Jo = w(Ko, {
1961
+ id: C({ prefix: "cdcoff" }),
1962
+ replicaId: i(),
1963
+ streamName: i(),
1964
+ ctVersion: i(),
1965
+ updatedAt: S()
1966
+ }).index(["replicaId"]), Yo = "postgres";
1967
1967
  //#endregion
1968
- export { he as AUTO_FILLED_COLUMNS, X as BranchNameInvalid, ja as BranchTransitionInvalid, Go as CDC_OFFSETS_TABLE, Fo as CHANGE_LISTENER_CEILING, Fe as ColumnBuilder, kt as ENCRYPTED_PREFIX, Jo as ENGINE, gn as EagerCardinalityError, Ie as FILE_MIGRATION_PATTERN, $e as FRAMEWORK_LIVE_TABLES, At as FieldDecryptionError, fa as INITIAL_VERSION, gi as MATCHES_NO_ROWS, Ge as MAX_IDENTIFIER_LENGTH, St as SqlClient, ya as TableStreamError, kn as TenantNamespaceInvalid, On as TenantNamespaceUnresolved, qa as TenantRegionUnavailable, Ka as TenantResidencyUnresolved, pa as VOLTRO_EXPIRES_MIXIN_ID, ha as VOLTRO_LOCAL_FIRST_MIXIN_ID, ca as VersionConflict, Ze as WARN_IDENTIFIER_LENGTH, To as _voltroApiKeysTable, Ko as _voltroCdcOffsetsTable, Co as _voltroIdempotencyTable, wo as _voltroKvTable, So as _voltroMigrationPlansTable, bo as _voltroMigrationsTable, qo as _voltroMssqlCdcOffsetsTable, xo as _voltroSeedsTable, ni as actorsTable, Wa as admitBranch, Ve as allEnumRenames, an as allRegisteredRelations, d as allRegisteredTables, bi as and, Ne as array, pi as arrayContains, hi as arrayHas, mi as arrayOverlaps, vn as attachEagerLoads, Bi as attributionFields, Wi as attributionKey, so as auditAllTableIndexes, oo as auditTableIndexes, Ae as avg, Je as avgOver, Zi as beginLocalWrite, be as bigint, to as bindResidentStore, it as boolean, Oa as branchNamespaceName, ut as bytes, Ii as changeDelete, Pi as changeInsert, Li as changeSoftDelete, Fi as changeUpdate, qi as claimPendingAttribution, nt as clearEnumRenames, ea as clearPendingAttribution, sn as clearRelationsRegistry, Za as clearResidencyConfig, Ho as clearRetentions, h as clearTableRegistry, ia as clearWriteRecorders, Ln as coercePredicateValue, Rn as coercePredicateValues, Mi as collectSubqueries, He as column, It as columnSchema, Qn as compileEagerJson, P as compilePredicate, zn as compileRawFragment, Zn as compileSelect, wa as computeEmbedding, di as contains, Pe as count, Me as countDistinct, we as crdtManagedColumns, ct as crdtText, zi as currentWriteAttribution, ye as databaseHandle, le as date, o as dbEnum, ot as decimal, Oe as declareEnumRename, pn as decodeRowsFromSchema, Ft as decryptFieldsOnRead, vo as defineMigration, _ as defineMixin, ho as defineSeed, rt as denseRank, ve as deriveTypeIdPrefix, Ot as deserializeArraysOnRead, Le as drainIdentifierWarnings, de as dropped, hn as encodeRowForSchema, Pt as encryptFieldsForWrite, Nt as encryptedColumnsOf, Qi as endLocalWrite, Va as enforceBranchLimits, y as ensureTableRegistered, ri as eq, Bn as escapeLike, ji as evaluatePredicate, lt as except, Di as exists, ma as expires, po as formatIndexAuditIssue, Eo as frameworkTables, oe as generateId, ke as generateSnowflake, u as geography, c as geometry, je as getEnumRenames, rn as getRelation, nn as getRelations, Xa as getResidencyConfig, C as getTable, ai as gt, oi as gte, Dn as hasEagerLoads, Ca as hybridSearch, S as id, li as inSet, Ti as inSubquery, A as inferForeignKey, Mo as insertRow, T as integer, Ce as intersect, n as interval, ka as isBranchNamespace, Wt as isEmptyRelationsSpec, Mt as isEncrypted, jt as isFieldDecryptionError, xe as isFileMigration, We as isFrameworkOwnedLiveTable, _a as isLocalFirst, yo as isMigrationDefinition, Fa as isNeonConnection, vi as isNotNull, _i as isNull, Ro as isPrimaryKeyConflictError, $a as isRegionServable, Gt as isRelationsSpec, go as isSeedDefinition, m as isSqliteFamily, dt as isTableReactive, Te as isView, w as json, Ci as jsonField, p as jsonIndex, st as lag, ce as lead, Vo as listRetentions, ga as localFirst, va as localFirstTables, si as lt, ci as lte, Ga as makeNamespaceBranchExecutor, qt as many, Jt as manyToMany, b as materializeFields, a as max, Ke as migration, at as min, jo as missingConflictColumns, Ao as missingRequiredColumns, _e as mixin, ii as neq, Ma as nextBranchState, Si as not, Oi as notExists, ui as notInSet, Ei as notInSubquery, x as numeric, Kt as one, _n as oneCardinalityMessage, xi as or, ue as paginateBy, l as paginateById, ta as pendingAttributionCount, za as planBranch, Na as planBranchProvision, Pa as planBranchTeardown, Ba as planBranchTeardownFor, La as planNeonBranchProvision, Ra as planNeonBranchTeardown, ua as planVersionedUpdate, Ye as pluginRef, Ue as pluginRefSpecOf, Lo as primaryKeyConflictError, Ha as provisionBranch, no as provisionResidentTenant, Pn as qualifyTable, s as queryFor, Be as queryForView, fe as quoteIdent, Io as raiseChangeListenerCeiling, re as rank, ae as raw, f as readableByColumns, g as real, aa as recordsTable, ee as reference, Qr as registerCoreTables, tn as registerDiscoveredRelations, Ki as registerPendingAttribution, en as registerRelations, Bo as registerRetention, r as registerTable, na as registerWriteRecorder, Ut as relations, ei as requireActors, pe as requireTable, ti as requireTenants, et as resetSnowflake, eo as residentPlacement, wt as resolveActorSnapshot, Ia as resolveBranchMechanism, $i as resolveEchoAttribution, ze as resolveFullTextIndex, e as resolveIdScheme, ge as resolveMixinGraph, Qa as resolveTenantHome, Nn as resolveTenantNamespace, Wo as retentionTtlMsFromEnv, t as rowNumber, Lt as rowSchema, Ri as runWithWriteAttribution, oa as runWriteRecorders, Mn as sanitizeIdentifierFragment, Dt as serializeArraysForWrite, se as serverOnlyColumns, Ya as setResidencyConfig, sa as settleTransactionExit, da as settleVersionedUpdate, yi as spatialPredicate, Oo as stampGeneratedId, ko as stampGeneratedIds, fi as startsWith, Sa as streamTable, Re as sum, te as sumOver, Uo as sweepRetention, v as table, Ua as teardownBranch, D as text, i as timestamp, ft as timestampMs, pt as timestampMsOrNull, ne as union, ie as unionAll, ra as unregisterWriteRecorder, Po as updateManyRow, No as upsertRow, Se as validateColumnName, qe as validateIndexName, on as validateRegisteredRelations, Zt as validateRelationConfig, Qe as validateTableName, Ee as validateTypeIdPrefix, me as vector, Xe as vectorDistanceToOpclass, Ta as vectorEmbedding, la as versionColumnOf, tt as view, De as viewSql, Ni as walkLeaves, Vi as withCapturedAttribution };
1968
+ export { p as AUTO_FILLED_COLUMNS, Y as BranchNameInvalid, Na as BranchTransitionInvalid, Ko as CDC_OFFSETS_TABLE, Io as CHANGE_LISTENER_CEILING, Fe as ColumnBuilder, At as ENCRYPTED_PREFIX, Yo as ENGINE, yn as EagerCardinalityError, Re as FILE_MIGRATION_PATTERN, tt as FRAMEWORK_LIVE_TABLES, jt as FieldDecryptionError, ma as INITIAL_VERSION, gi as MATCHES_NO_ROWS, $e as MAX_IDENTIFIER_LENGTH, Ct as SqlClient, xa as TableStreamError, Mn as TenantNamespaceInvalid, jn as TenantNamespaceUnresolved, Ya as TenantRegionUnavailable, Ja as TenantResidencyUnresolved, ha as VOLTRO_EXPIRES_MIXIN_ID, _a as VOLTRO_LOCAL_FIRST_MIXIN_ID, ua as VersionConflict, ze as WARN_IDENTIFIER_LENGTH, Do as _voltroApiKeysTable, qo as _voltroCdcOffsetsTable, To as _voltroIdempotencyTable, Eo as _voltroKvTable, wo as _voltroMigrationPlansTable, So as _voltroMigrationsTable, Jo as _voltroMssqlCdcOffsetsTable, Co as _voltroSeedsTable, ni as actorsTable, Ka as admitBranch, it as allEnumRenames, cn as allRegisteredRelations, g as allRegisteredTables, bi as and, Se as array, pi as arrayContains, hi as arrayHas, mi as arrayOverlaps, xn as attachEagerLoads, Bi as attributionFields, Wi as attributionKey, lo as auditAllTableIndexes, co as auditTableIndexes, Me as avg, Ze as avgOver, $i as beginLocalWrite, ot as bigint, ro as bindResidentStore, ft as boolean, Aa as branchNamespaceName, Ee as bytes, Ii as changeDelete, Pi as changeInsert, Li as changeSoftDelete, Fi as changeUpdate, qi as claimPendingAttribution, Ae as clearEnumRenames, na as clearPendingAttribution, un as clearRelationsRegistry, $a as clearResidencyConfig, Uo as clearRetentions, ne as clearTableRegistry, oa as clearWriteRecorders, Bn as coercePredicateValue, Vn as coercePredicateValues, Mi as collectSubqueries, Ge as column, Lt as columnSchema, $n as compileEagerJson, N as compilePredicate, Hn as compileRawFragment, P as compileSelect, Ea as computeEmbedding, di as contains, Ie as count, Pe as countDistinct, ut as crdtManagedColumns, pe as crdtText, zi as currentWriteAttribution, xe as databaseHandle, o as date, ct as dbEnum, me as decimal, Ne as declareEnumRename, gn as decodeRowsFromSchema, It as decryptFieldsOnRead, bo as defineMigration, ye as defineMixin, _o as defineSeed, at as denseRank, le as deriveTypeIdPrefix, kt as deserializeArraysOnRead, we as drainIdentifierWarnings, u as dropped, vn as encodeRowForSchema, Ft as encryptFieldsForWrite, Pt as encryptedColumnsOf, ea as endLocalWrite, Ua as enforceBranchLimits, ue as ensureTableRegistered, ri as eq, M as escapeLike, ji as evaluatePredicate, dt as except, Di as exists, ga as expires, ho as formatIndexAuditIssue, Oo as frameworkTables, e as generateId, nt as generateSnowflake, c as geography, oe as geometry, Qe as getEnumRenames, sn as getRelation, on as getRelations, Qa as getResidencyConfig, E as getTable, ai as gt, oi as gte, An as hasEagerLoads, Ta as hybridSearch, C as id, li as inSet, Ti as inSubquery, Xt as inferForeignKey, No as insertRow, n as integer, Te as intersect, Ve as interval, ja as isBranchNamespace, Gt as isEmptyRelationsSpec, Nt as isEncrypted, Mt as isFieldDecryptionError, Ce as isFileMigration, qe as isFrameworkOwnedLiveTable, ya as isLocalFirst, xo as isMigrationDefinition, La as isNeonConnection, vi as isNotNull, _i as isNull, zo as isPrimaryKeyConflictError, to as isRegionServable, Kt as isRelationsSpec, vo as isSeedDefinition, he as isSqliteFamily, r as isTableReactive, De as isView, y as json, Ci as jsonField, _ as jsonIndex, lt as lag, fe as lead, Ho as listRetentions, va as localFirst, ba as localFirstTables, si as lt, ci as lte, qa as makeNamespaceBranchExecutor, Jt as many, Yt as manyToMany, ie as materializeFields, a as max, Ye as migration, st as min, Mo as missingConflictColumns, jo as missingRequiredColumns, ve as mixin, ii as neq, Pa as nextBranchState, Si as not, Oi as notExists, ui as notInSet, Ei as notInSubquery, ce as numeric, qt as one, bn as oneCardinalityMessage, xi as or, x as orderClausesOf, l as paginateBy, s as paginateById, ra as pendingAttributionCount, Va as planBranch, Fa as planBranchProvision, Ia as planBranchTeardown, Ha as planBranchTeardownFor, za as planNeonBranchProvision, Ba as planNeonBranchTeardown, fa as planVersionedUpdate, Ke as pluginRef, Le as pluginRefSpecOf, Ro as primaryKeyConflictError, Wa as provisionBranch, io as provisionResidentTenant, Ln as qualifyTable, ae as queryFor, Ue as queryForView, _e as quoteIdent, Lo as raiseChangeListenerCeiling, He as rank, f as raw, ee as readableByColumns, re as real, sa as recordsTable, de as reference, Qr as registerCoreTables, an as registerDiscoveredRelations, Ki as registerPendingAttribution, rn as registerRelations, Vo as registerRetention, ge as registerTable, ia as registerWriteRecorder, Wt as relations, ei as requireActors, m as requireTable, ti as requireTenants, Je as resetSnowflake, no as residentPlacement, Tt as resolveActorSnapshot, Ra as resolveBranchMechanism, ta as resolveEchoAttribution, t as resolveFullTextIndex, je as resolveIdScheme, be as resolveMixinGraph, eo as resolveTenantHome, In as resolveTenantNamespace, Go as retentionTtlMsFromEnv, Be as rowNumber, Rt as rowSchema, Ri as runWithWriteAttribution, ca as runWriteRecorders, Fn as sanitizeIdentifierFragment, Ot as serializeArraysForWrite, pt as serverOnlyColumns, Za as setResidencyConfig, la as settleTransactionExit, pa as settleVersionedUpdate, yi as spatialPredicate, ko as stampGeneratedId, Ao as stampGeneratedIds, fi as startsWith, wa as streamTable, v as sum, b as sumOver, Wo as sweepRetention, w as table, Ga as teardownBranch, i as text, S as timestamp, mt as timestampMs, ht as timestampMsOrNull, se as union, d as unionAll, aa as unregisterWriteRecorder, Fo as updateManyRow, Po as upsertRow, Xe as validateColumnName, et as validateIndexName, ln as validateRegisteredRelations, en as validateRelationConfig, Oe as validateTableName, We as validateTypeIdPrefix, h as vector, te as vectorDistanceToOpclass, Da as vectorEmbedding, da as versionColumnOf, rt as view, ke as viewSql, Ni as walkLeaves, Vi as withCapturedAttribution };