@voltro/database 0.26.0 → 0.27.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,18 +1,11 @@
1
- import { $ as e, A as t, At as n, B as r, C as i, Ct as a, D as o, Dt as s, E as c, Et as l, F as u, Ft as d, G as f, H as p, I as m, It as h, J as g, K as _, L as ee, M as v, Mt as te, N as y, Nt as b, O as ne, Ot as x, P as re, Pt as S, Q as ie, R as C, S as ae, St as oe, T as se, Tt as w, U as ce, V as le, W as ue, X as de, Y as fe, Z as pe, _ as me, _t as he, a as ge, at as _e, b as ve, bt as ye, c as be, ct as xe, d as Se, dt as Ce, et as we, f as Te, ft as Ee, g as De, gt as Oe, h as ke, ht as Ae, i as je, it as Me, j as Ne, jt as Pe, k as Fe, kt as Ie, l as Le, lt as Re, m as ze, mt as Be, n as Ve, nt as He, o as Ue, ot as We, p as Ge, pt as Ke, q as qe, rt as Je, s as T, st as Ye, t as Xe, tt as Ze, u as Qe, ut as $e, v as et, vt as tt, w as nt, wt as E, x as rt, xt as it, y as at, yt as ot, z as st } from "./frameworkLiveTables-BQwB8K6R.js";
2
- import { timestampMs as ct, timestampMsOrNull as lt } from "./wire.js";
3
- import { Cause as ut, Chunk as dt, Data as ft, Effect as pt, Exit as mt, Option as D, Schema as O, Stream as ht } from "effect";
4
- import { AsyncLocalStorage as gt } from "node:async_hooks";
5
- import { ansi as k } from "@voltro/logger";
6
- import { SqlClient as _t } from "@effect/sql";
7
- //#region src/pluginRef.ts
8
- var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ? vt.get(e) : void 0, bt = (e, t = {}) => {
9
- let n = S();
10
- return vt.set(n, {
11
- target: e,
12
- orphanPolicy: t.orphanPolicy ?? "keep",
13
- onSoftDelete: t.onSoftDelete ?? !1
14
- }), n;
15
- }, xt = (e) => typeof e == "string" && e !== "" ? e : null, St = async (e, t, n) => {
1
+ import { $ as e, A as t, At as n, B as r, C as i, Ct as a, D as o, Dt as s, E as c, Et as l, F as u, Ft as d, G as f, H as p, I as m, It as h, J as g, K as _, L as ee, Lt as v, M as te, Mt as y, N as b, Nt as ne, O as x, Ot as re, P as ie, Pt as ae, Q as oe, R as S, Rt as se, S as ce, St as le, T as ue, Tt as de, U as fe, V as pe, W as me, X as he, Y as ge, Z as _e, _ as ve, _t as ye, a as be, at as xe, b as Se, bt as Ce, c as we, ct as Te, d as Ee, dt as De, et as Oe, f as ke, ft as Ae, g as je, gt as Me, h as Ne, ht as Pe, i as Fe, it as Ie, j as Le, jt as Re, k as ze, kt as C, 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 w, 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 } from "./frameworkLiveTables-CS_Hyhgz.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 T, Schema as E, Stream as yt } from "effect";
4
+ import { AsyncLocalStorage as bt } from "node:async_hooks";
5
+ import { ansi as D } from "@voltro/logger";
6
+ import { SqlClient as xt } from "@effect/sql";
7
+ //#region src/actorSnapshot.ts
8
+ var St = (e) => typeof e == "string" && e !== "" ? e : null, Ct = async (e, t, n) => {
16
9
  if (!(t == null || t === "")) try {
17
10
  let r = (await e.query({
18
11
  table: "actors",
@@ -28,20 +21,20 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
28
21
  }))[0];
29
22
  return r === void 0 ? void 0 : {
30
23
  id: t,
31
- type: xt(r.kind) ?? n,
32
- displayName: xt(r.displayName),
33
- email: xt(r.email)
24
+ type: St(r.kind) ?? n,
25
+ displayName: St(r.displayName),
26
+ email: St(r.email)
34
27
  };
35
28
  } catch {
36
29
  return;
37
30
  }
38
- }, Ct = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", wt = (e) => {
31
+ }, wt = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", Tt = (e) => {
39
32
  let t = [];
40
33
  for (let [n, r] of Object.entries(e.fields)) r.type === "array" && t.push(n);
41
34
  return t;
42
- }, Tt = (e, t, n) => {
43
- if (!Ct(n) || !t) return e;
44
- let r = wt(t);
35
+ }, Et = (e, t, n) => {
36
+ if (!wt(n) || !t) return e;
37
+ let r = Tt(t);
45
38
  if (r.length === 0) return e;
46
39
  let i = { ...e };
47
40
  for (let e of r) {
@@ -49,9 +42,9 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
49
42
  Array.isArray(t) && (i[e] = JSON.stringify(t));
50
43
  }
51
44
  return i;
52
- }, Et = (e, t, n) => {
53
- if (!Ct(n) || !t) return e;
54
- let r = wt(t);
45
+ }, Dt = (e, t, n) => {
46
+ if (!wt(n) || !t) return e;
47
+ let r = Tt(t);
55
48
  return r.length === 0 ? e : e.map((e) => {
56
49
  let t;
57
50
  for (let n of r) {
@@ -63,7 +56,7 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
63
56
  }
64
57
  return t ?? e;
65
58
  });
66
- }, Dt = "enc:v1:", Ot = class extends Error {
59
+ }, Ot = "enc:v1:", kt = class extends Error {
67
60
  _tag = "FieldDecryptionError";
68
61
  table;
69
62
  column;
@@ -71,33 +64,33 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
71
64
  constructor(e) {
72
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;
73
66
  }
74
- }, kt = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", At = (e) => typeof e == "string" && e.startsWith("enc:v1:"), jt = (e) => {
67
+ }, At = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", jt = (e) => typeof e == "string" && e.startsWith("enc:v1:"), Mt = (e) => {
75
68
  let t = [];
76
69
  for (let [n, r] of Object.entries(e.fields)) r.encrypted === !0 && t.push(n);
77
70
  return t;
78
- }, Mt = (e, t, n) => {
71
+ }, Nt = (e, t, n) => {
79
72
  if (!t) return e;
80
- let r = jt(t);
73
+ let r = Mt(t);
81
74
  if (r.length === 0) return e;
82
75
  let i = { ...e };
83
76
  for (let e of r) {
84
77
  let r = i[e];
85
- if (!(r == null || At(r))) {
78
+ if (!(r == null || jt(r))) {
86
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)`);
87
80
  i[e] = n.encrypt(JSON.stringify(r));
88
81
  }
89
82
  }
90
83
  return i;
91
- }, Nt = (e, t, n, r) => {
84
+ }, Pt = (e, t, n, r) => {
92
85
  if (!t) return e;
93
- let i = jt(t);
86
+ let i = Mt(t);
94
87
  if (i.length === 0 || !n) return e;
95
88
  let a = r?.onError ?? "throw", o = t.tableName ?? "?";
96
89
  return e.map((e) => {
97
90
  let t;
98
91
  for (let s of i) {
99
92
  let i = e[s];
100
- if (At(i)) {
93
+ if (jt(i)) {
101
94
  t ??= { ...e };
102
95
  try {
103
96
  t[s] = JSON.parse(n.decrypt(i));
@@ -111,7 +104,7 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
111
104
  });
112
105
  continue;
113
106
  }
114
- throw new Ot({
107
+ throw new kt({
115
108
  table: o,
116
109
  column: s,
117
110
  reason: n
@@ -121,62 +114,62 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
121
114
  }
122
115
  return t ?? e;
123
116
  });
124
- }, Pt = (e) => {
117
+ }, Ft = (e) => {
125
118
  let t = (() => {
126
119
  switch (e.type) {
127
120
  case "id":
128
121
  case "reference":
129
122
  case "text":
130
- case "enum": return O.String;
123
+ case "enum": return E.String;
131
124
  case "integer":
132
125
  case "real":
133
- case "decimal": return O.Number;
134
- case "boolean": return O.Boolean;
126
+ case "decimal": return E.Number;
127
+ case "boolean": return E.Boolean;
135
128
  case "timestamp":
136
- case "date": return ct;
137
- case "bigint": return O.BigInt;
138
- case "bytes": return O.Uint8ArrayFromSelf;
139
- case "array": return O.Array(O.Unknown);
140
- case "interval": return O.String;
141
- default: return O.Unknown;
129
+ case "date": return ft;
130
+ case "bigint": return E.BigInt;
131
+ case "bytes": return E.Uint8ArrayFromSelf;
132
+ case "array": return E.Array(E.Unknown);
133
+ case "interval": return E.String;
134
+ default: return E.Unknown;
142
135
  }
143
136
  })();
144
- return e.nullable === !0 ? O.NullOr(t) : t;
145
- }, Ft = (e, t) => {
137
+ return e.nullable === !0 ? E.NullOr(t) : t;
138
+ }, It = (e, t) => {
146
139
  let n = new Set(t?.omit ?? []), r = {};
147
- for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = Pt(i));
148
- return O.Struct(r);
149
- }, It = (e) => typeof e == "function" ? e : () => e, Lt = (e, t) => ({
140
+ for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = Ft(i));
141
+ return E.Struct(r);
142
+ }, Lt = (e) => typeof e == "function" ? e : () => e, Rt = (e, t) => ({
150
143
  kind: "one",
151
- target: It(e),
144
+ target: Lt(e),
152
145
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
153
146
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
154
- }), Rt = (e, t) => ({
147
+ }), zt = (e, t) => ({
155
148
  kind: "many",
156
- target: It(e),
149
+ target: Lt(e),
157
150
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
158
151
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
159
- }), zt = (e, t) => ({
152
+ }), Bt = (e, t) => ({
160
153
  kind: "manyToMany",
161
- target: It(e),
162
- through: It(t.through),
154
+ target: Lt(e),
155
+ through: Lt(t.through),
163
156
  sourceKey: t.sourceKey,
164
157
  targetKey: t.targetKey
165
- }), Bt = {
166
- one: Lt,
167
- many: Rt,
168
- manyToMany: zt
169
- }, Vt = (e, t) => {
158
+ }), Vt = {
159
+ one: Rt,
160
+ many: zt,
161
+ manyToMany: Bt
162
+ }, Ht = (e, t) => {
170
163
  let n = typeof e == "function" ? e : () => e;
171
164
  return {
172
165
  source: n,
173
- relations: t(Bt, n())
166
+ relations: t(Vt, n())
174
167
  };
175
- }, Ht = (e) => {
168
+ }, Ut = (e) => {
176
169
  if (typeof e != "object" || !e) return !1;
177
170
  let t = e;
178
171
  return typeof t.source != "function" || typeof t.relations != "object" || t.relations === null ? !1 : Object.keys(t.relations).length === 0;
179
- }, Ut = (e) => {
172
+ }, Wt = (e) => {
180
173
  if (typeof e != "object" || !e) return !1;
181
174
  let t = e;
182
175
  if (typeof t.source != "function" || typeof t.relations != "object" || t.relations === null) return !1;
@@ -185,35 +178,35 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
185
178
  let t = e?.kind;
186
179
  return t === "one" || t === "many" || t === "manyToMany";
187
180
  });
188
- }, Wt = Lt, Gt = Rt, Kt = zt, A = (e, t, n) => {
181
+ }, Gt = Rt, Kt = zt, qt = Bt, O = (e, t, n) => {
189
182
  let r = [];
190
183
  for (let [n, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && r.push(n);
191
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>' }.`);
192
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.`);
193
186
  return r[0];
194
- }, qt = (e) => Object.keys(e.fields), j = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Jt = (e) => {
195
- let t = qt(e);
187
+ }, Jt = (e) => Object.keys(e.fields), Yt = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Xt = (e) => {
188
+ let t = Jt(e);
196
189
  return t.length === 0 ? "<none>" : t.join(", ");
197
- }, Yt = (e, t, n) => {
190
+ }, Zt = (e, t, n) => {
198
191
  let r = `relation '${t}' on '${e.tableName}'`, i = n.target();
199
192
  if (n.kind === "manyToMany") {
200
193
  let t = n.through();
201
- 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}': ${Jt(t)}.`);
194
+ for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!Yt(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)}.`);
202
195
  return;
203
196
  }
204
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.`);
205
- if (n.sourceKey !== void 0 && !j(e, n.sourceKey)) {
206
- let t = j(i, n.sourceKey);
207
- 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}': ${Jt(e)}.`));
198
+ if (n.sourceKey !== void 0 && !Yt(e, n.sourceKey)) {
199
+ let t = Yt(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)}.`));
208
201
  }
209
- if (n.foreignKey !== void 0 && !j(i, n.foreignKey)) {
210
- let t = j(e, n.foreignKey);
211
- 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}': ${Jt(i)}.`));
202
+ if (n.foreignKey !== void 0 && !Yt(i, n.foreignKey)) {
203
+ let t = Yt(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)}.`));
212
205
  }
213
- }, Xt = Symbol.for("@voltro/database/relationsRegistry"), Zt = globalThis, M = Zt[Xt] ?? (Zt[Xt] = /* @__PURE__ */ new Map()), Qt = (e) => {
214
- let t = e.source(), n = M.get(t.tableName);
206
+ }, Qt = Symbol.for("@voltro/database/relationsRegistry"), $t = globalThis, k = $t[Qt] ?? ($t[Qt] = /* @__PURE__ */ new Map()), en = (e) => {
207
+ let t = e.source(), n = k.get(t.tableName);
215
208
  if (n === void 0) {
216
- M.set(t.tableName, new Map(Object.entries(e.relations)));
209
+ k.set(t.tableName, new Map(Object.entries(e.relations)));
217
210
  return;
218
211
  }
219
212
  for (let [r, i] of Object.entries(e.relations)) {
@@ -223,29 +216,29 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
223
216
  n.set(r, i);
224
217
  }
225
218
  }
226
- }, $t = (e) => {
219
+ }, tn = (e) => {
227
220
  let t = 0;
228
- for (let n of Object.values(e)) Ut(n) && (Qt(n), t += 1);
221
+ for (let n of Object.values(e)) Wt(n) && (en(n), t += 1);
229
222
  return t;
230
- }, en = (e) => {
231
- let t = M.get(e);
223
+ }, nn = (e) => {
224
+ let t = k.get(e);
232
225
  if (t !== void 0) return Object.fromEntries(t);
233
- }, tn = (e, t) => M.get(e)?.get(t), nn = () => {
226
+ }, rn = (e, t) => k.get(e)?.get(t), an = () => {
234
227
  let e = [];
235
- for (let [t, n] of M) for (let [r, i] of n) e.push({
228
+ for (let [t, n] of k) for (let [r, i] of n) e.push({
236
229
  source: t,
237
230
  name: r,
238
231
  relation: i
239
232
  });
240
233
  return e;
241
- }, rn = () => {
242
- for (let [e, t] of M) {
243
- let n = C(e);
244
- if (n !== void 0) for (let [e, r] of t) Yt(n, e, r);
245
- }
246
- }, an = () => {
247
- M.clear();
248
- }, on = (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, sn = (e) => {
234
+ }, on = () => {
235
+ for (let [e, t] of k) {
236
+ let n = S(e);
237
+ if (n !== void 0) for (let [e, r] of t) Zt(n, e, r);
238
+ }
239
+ }, sn = () => {
240
+ k.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) => {
249
242
  if (e == null || typeof e != "string") return e;
250
243
  let t = e.trim();
251
244
  if (t.length === 0) return e;
@@ -256,7 +249,7 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
256
249
  } catch {
257
250
  return e;
258
251
  }
259
- }, cn = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, ln = (e) => {
252
+ }, un = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, dn = (e) => {
260
253
  if (e == null || e instanceof Date) return e;
261
254
  if (typeof e == "string") {
262
255
  let t = new Date(e);
@@ -267,21 +260,21 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
267
260
  return isNaN(t.getTime()) ? e : t;
268
261
  }
269
262
  return e;
270
- }, un = (e, t, n) => {
263
+ }, fn = (e, t, n) => {
271
264
  if (e == null) return e;
272
265
  switch (t) {
273
- case "boolean": return n === "postgres" ? e : on(e);
266
+ case "boolean": return n === "postgres" ? e : cn(e);
274
267
  case "json":
275
- case "array": return n === "postgres" ? e : sn(e);
268
+ case "array": return n === "postgres" ? e : ln(e);
276
269
  case "timestamp":
277
- case "date": return n === "sqlite" || n === "turso" ? ln(e) : e;
270
+ case "date": return n === "sqlite" || n === "turso" ? dn(e) : e;
278
271
  case "decimal":
279
- case "bigint": return cn(e);
272
+ case "bigint": return un(e);
280
273
  default: return e;
281
274
  }
282
- }, dn = (e, t, n) => {
275
+ }, pn = (e, t, n) => {
283
276
  if (e.length === 0) return e;
284
- let r = C(t);
277
+ let r = S(t);
285
278
  if (r === void 0) return e;
286
279
  let i = r.fields, a = [];
287
280
  for (let [e, t] of Object.entries(i)) a.push({
@@ -290,36 +283,36 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
290
283
  });
291
284
  return e.map((e) => {
292
285
  let t = { ...e };
293
- for (let { key: e, type: r } of a) e in t && (t[e] = un(t[e], r, n));
286
+ for (let { key: e, type: r } of a) e in t && (t[e] = fn(t[e], r, n));
294
287
  return t;
295
288
  });
296
- }, fn = (e, t) => {
289
+ }, mn = (e, t) => {
297
290
  if (e == null) return e;
298
291
  switch (t) {
299
292
  case "json":
300
293
  case "array": return typeof e == "string" ? e : JSON.stringify(e);
301
294
  default: return e;
302
295
  }
303
- }, pn = (e, t, n = ["json", "array"]) => {
304
- let r = C(t);
296
+ }, hn = (e, t, n = ["json", "array"]) => {
297
+ let r = S(t);
305
298
  if (r === void 0) return e;
306
299
  let i = r.fields, a = null;
307
300
  for (let [t, r] of Object.entries(i)) if (n.includes(r.type) && t in e) {
308
- let n = fn(e[t], r.type);
301
+ let n = mn(e[t], r.type);
309
302
  n !== e[t] && (a === null && (a = { ...e }), a[t] = n);
310
303
  }
311
304
  return a ?? e;
312
- }, mn = class extends Error {
305
+ }, gn = class extends Error {
313
306
  _tag = "EagerCardinalityError";
314
307
  constructor(e) {
315
308
  super(e), this.name = "EagerCardinalityError";
316
309
  }
317
- }, hn = (e) => {
310
+ }, _n = (e) => {
318
311
  let { relationName: t, sourceTableName: n, targetTableName: r, foreignKey: i, sourceKey: a } = e, o = r === n;
319
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.");
320
- }, gn = async (e, t, n, r) => {
313
+ }, vn = async (e, t, n, r) => {
321
314
  if (e.length === 0) return e;
322
- let i = en(n.tableName);
315
+ let i = nn(n.tableName);
323
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?`);
324
317
  let a = e.map((e) => ({ ...e }));
325
318
  for (let [e, o] of Object.entries(t)) {
@@ -328,36 +321,36 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
328
321
  let t = Object.keys(i).join(", ") || "<none>";
329
322
  throw Error(`unknown relation '${e}' on '${n.tableName}'. Registered relations: ${t}.`);
330
323
  }
331
- Yt(n, e, t), await _n(a, e, t, o === !0 ? {} : o, n, r);
324
+ Zt(n, e, t), await yn(a, e, t, o === !0 ? {} : o, n, r);
332
325
  }
333
326
  return a;
334
- }, _n = async (e, t, n, r, i, a) => {
327
+ }, yn = async (e, t, n, r, i, a) => {
335
328
  switch (n.kind) {
336
329
  case "one":
337
- await vn(e, t, n, r, i, a);
330
+ await bn(e, t, n, r, i, a);
338
331
  return;
339
332
  case "many":
340
- await yn(e, t, n, r, i, a);
333
+ await xn(e, t, n, r, i, a);
341
334
  return;
342
335
  case "manyToMany":
343
- await xn(e, t, n, r, i, a);
336
+ await Cn(e, t, n, r, i, a);
344
337
  return;
345
338
  }
346
- }, vn = async (e, t, n, r, i, a) => {
347
- let o = n.target(), s = n.sourceKey ?? Sn(i, o.tableName);
339
+ }, bn = async (e, t, n, r, i, a) => {
340
+ let o = n.target(), s = n.sourceKey ?? wn(i, o.tableName);
348
341
  if (s !== void 0) {
349
- let n = N(e, s), i = n.length === 0 ? [] : await Cn(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
342
+ let n = A(e, s), i = n.length === 0 ? [] : await Tn(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
350
343
  for (let n of e) {
351
344
  let e = n[s];
352
345
  n[t] = e == null ? null : c.get(e) ?? null;
353
346
  }
354
- await wn(i, r.with, o, a);
347
+ await En(i, r.with, o, a);
355
348
  return;
356
349
  }
357
- let c = n.foreignKey ?? A(o, i.tableName, t), l = n.sourceKey ?? "id", u = N(e, l), d = u.length === 0 ? [] : await Cn(o, c, u, r, a), f = /* @__PURE__ */ new Map();
350
+ let c = n.foreignKey ?? O(o, i.tableName, t), l = n.sourceKey ?? "id", u = A(e, l), d = u.length === 0 ? [] : await Tn(o, c, u, r, a), f = /* @__PURE__ */ new Map();
358
351
  for (let e of d) {
359
352
  let n = e[c];
360
- if (f.has(n)) throw new mn(hn({
353
+ if (f.has(n)) throw new gn(_n({
361
354
  relationName: t,
362
355
  sourceTableName: i.tableName,
363
356
  targetTableName: o.tableName,
@@ -370,9 +363,9 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
370
363
  let e = n[l];
371
364
  n[t] = e == null ? null : f.get(e) ?? null;
372
365
  }
373
- await wn(d, r.with, o, a);
374
- }, yn = async (e, t, n, r, i, a) => {
375
- let o = n.target(), s = n.foreignKey ?? A(o, i.tableName, t), c = n.sourceKey ?? "id", l = N(e, c), u = bn(r), d = l.length === 0 ? [] : await Cn(o, s, l, u, a), f = /* @__PURE__ */ new Map();
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 ?? O(o, i.tableName, t), c = n.sourceKey ?? "id", l = A(e, c), u = Sn(r), d = l.length === 0 ? [] : await Tn(o, s, l, u, a), f = /* @__PURE__ */ new Map();
376
369
  for (let e of d) {
377
370
  let t = e[s], n = f.get(t);
378
371
  n ? n.push(e) : f.set(t, [e]);
@@ -388,12 +381,12 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
388
381
  let e = n[c];
389
382
  n[t] = f.get(e) ?? [];
390
383
  }
391
- await wn(d, r.with, o, a);
392
- }, bn = (e) => {
384
+ await En(d, r.with, o, a);
385
+ }, Sn = (e) => {
393
386
  let { limit: t, offset: n, ...r } = e;
394
387
  return r;
395
- }, xn = async (e, t, n, r, i, a) => {
396
- let o = n.target(), s = n.through(), c = N(e, "id");
388
+ }, Cn = async (e, t, n, r, i, a) => {
389
+ let o = n.target(), s = n.through(), c = A(e, "id");
397
390
  if (c.length === 0) {
398
391
  for (let n of e) n[t] = [];
399
392
  return;
@@ -414,8 +407,8 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
414
407
  for (let n of e) n[t] = [];
415
408
  return;
416
409
  }
417
- let f = await Cn(o, "id", N(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
418
- await wn(f, r.with, o, a);
410
+ let f = await Tn(o, "id", A(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
411
+ await En(f, r.with, o, a);
419
412
  let m = r.junction === void 0 ? void 0 : r.junction === !0 ? Object.keys(s.fields) : r.junction, h = /* @__PURE__ */ new Map();
420
413
  for (let e of d) {
421
414
  let t = e[n.sourceKey], r = e[n.targetKey], i = p.get(r);
@@ -427,16 +420,16 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
427
420
  o ? o.push(a) : h.set(t, [a]);
428
421
  }
429
422
  for (let n of e) n[t] = h.get(n.id) ?? [];
430
- }, Sn = (e, t) => {
423
+ }, wn = (e, t) => {
431
424
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
432
- }, N = (e, t) => {
425
+ }, A = (e, t) => {
433
426
  let n = /* @__PURE__ */ new Set();
434
427
  for (let r of e) {
435
428
  let e = r[t];
436
429
  e != null && n.add(e);
437
430
  }
438
431
  return [...n];
439
- }, Cn = (e, t, n, r, i) => {
432
+ }, Tn = (e, t, n, r, i) => {
440
433
  let a = {
441
434
  column: t,
442
435
  op: "in",
@@ -450,63 +443,63 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
450
443
  skip: r.offset,
451
444
  projection: void 0
452
445
  });
453
- }, wn = async (e, t, n, r) => {
454
- t !== void 0 && e.length !== 0 && (await gn(e, t, n, r)).forEach((t, n) => {
446
+ }, En = async (e, t, n, r) => {
447
+ t !== void 0 && e.length !== 0 && (await vn(e, t, n, r)).forEach((t, n) => {
455
448
  let r = e[n];
456
449
  for (let [e, n] of Object.entries(t)) e in r || (r[e] = n);
457
450
  });
458
- }, Tn = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, En = class extends Error {
451
+ }, Dn = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, On = class extends Error {
459
452
  _tag = "TenantNamespaceUnresolved";
460
453
  constructor(e) {
461
454
  super(e), this.name = "TenantNamespaceUnresolved";
462
455
  }
463
- }, Dn = class extends Error {
456
+ }, kn = class extends Error {
464
457
  _tag = "TenantNamespaceInvalid";
465
458
  constructor(e) {
466
459
  super(e), this.name = "TenantNamespaceInvalid";
467
460
  }
468
- }, On = 63, kn = "tenant_", An = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), jn = (e) => {
469
- if (e == null || e === "") throw new En("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.");
470
- let t = An(e);
471
- if (t.replace(/_/g, "") === "") throw new Dn(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
472
- let n = `${kn}${t}`;
473
- if (n.length > On) throw new Dn(`namespace '${n}' for tenant '${e}' exceeds the ${On}-byte identifier limit. Use a shorter tenant id.`);
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.`);
474
467
  return n;
475
- }, Mn = (e, t) => e === null ? t : `${e}.${t}`, Nn = /* @__PURE__ */ new Set(["timestamp", "date"]), Pn = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, Fn = (e, t) => {
476
- if (e === void 0 || t == null || !Nn.has(e) || t instanceof Date) return t;
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;
477
470
  if (typeof t == "number" && Number.isFinite(t)) return new Date(t);
478
- if (typeof t == "string" && Pn.test(t)) {
471
+ if (typeof t == "string" && In.test(t)) {
479
472
  let e = new Date(t);
480
473
  return Number.isNaN(e.getTime()) ? t : e;
481
474
  }
482
475
  return t;
483
- }, In = (e, t) => e === void 0 || !Nn.has(e) ? t : t.map((t) => Fn(e, t)), Ln = (e, t) => {
476
+ }, Rn = (e, t) => e === void 0 || !Fn.has(e) ? t : t.map((t) => Ln(e, t)), zn = (e, t) => {
484
477
  let { strings: n, values: r } = e, i = t.unsafe(n[0] ?? "");
485
478
  for (let e = 0; e < r.length; e++) i = t`${i}${r[e]}${t.unsafe(n[e + 1] ?? "")}`;
486
479
  return t`${i}`;
487
- }, P = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), F = (e, t, n = null, r) => {
488
- if ("not" in e) return t`NOT (${F(e.not, t, n, r)})`;
489
- if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => F(e, t, n, r)));
490
- if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => F(e, t, n, r)));
480
+ }, j = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), M = (e, t, n = null, r) => {
481
+ if ("not" in e) return t`NOT (${M(e.not, t, n, r)})`;
482
+ if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => M(e, t, n, r)));
483
+ if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => M(e, t, n, r)));
491
484
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
492
- let r = e, i = I(r.subquery, t, n);
485
+ let r = e, i = N(r.subquery, t, n);
493
486
  return r.op === "subquery-in" ? t`${t(r.column)} IN (${i})` : t`${t(r.column)} NOT IN (${i})`;
494
487
  }
495
488
  if (e.op === "exists" || e.op === "not-exists") {
496
- let r = e, i = I(r.subquery, t, n);
489
+ let r = e, i = N(r.subquery, t, n);
497
490
  return r.op === "exists" ? t`EXISTS (${i})` : t`NOT EXISTS (${i})`;
498
491
  }
499
492
  let i = e, a = t(i.column), o = i.path, s = o !== void 0 && o.length > 0, c = () => t.onDialectOrElse({
500
- mysql: () => t.unsafe(T(i.column, o, "mysql")),
501
- mssql: () => t.unsafe(T(i.column, o, "mssql")),
502
- sqlite: () => t.unsafe(T(i.column, o, "sqlite")),
503
- orElse: () => t.unsafe(T(i.column, o, "postgres"))
493
+ mysql: () => t.unsafe(w(i.column, o, "mysql")),
494
+ mssql: () => t.unsafe(w(i.column, o, "mssql")),
495
+ sqlite: () => t.unsafe(w(i.column, o, "sqlite")),
496
+ orElse: () => t.unsafe(w(i.column, o, "postgres"))
504
497
  }), l = () => t.onDialectOrElse({
505
- mysql: () => t.unsafe(T(i.column, o, "mysql", { numeric: !0 })),
506
- mssql: () => t.unsafe(T(i.column, o, "mssql", { numeric: !0 })),
507
- sqlite: () => t.unsafe(T(i.column, o, "sqlite", { numeric: !0 })),
508
- orElse: () => t.unsafe(T(i.column, o, "postgres", { numeric: !0 }))
509
- }), 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) => Fn(m, e);
498
+ mysql: () => t.unsafe(w(i.column, o, "mysql", { numeric: !0 })),
499
+ mssql: () => t.unsafe(w(i.column, o, "mssql", { numeric: !0 })),
500
+ sqlite: () => t.unsafe(w(i.column, o, "sqlite", { numeric: !0 })),
501
+ orElse: () => t.unsafe(w(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 : S(r)?.fields?.[i.column]?.type, h = (e) => Ln(m, e);
510
503
  switch (i.op) {
511
504
  case "eq": return t`${u} = ${f(h(i.value))}`;
512
505
  case "neq": return t`${u} <> ${f(h(i.value))}`;
@@ -523,7 +516,7 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
523
516
  return e.length === 0 ? t`TRUE` : t`${u} NOT IN ${t.in(s ? e.map((e) => f(e)) : e)}`;
524
517
  }
525
518
  case "contains": {
526
- let e = `%${P(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
519
+ let e = `%${j(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
527
520
  return t.onDialectOrElse({
528
521
  mysql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
529
522
  mssql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
@@ -532,7 +525,7 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
532
525
  });
533
526
  }
534
527
  case "startsWith": {
535
- let e = `${P(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
528
+ let e = `${j(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
536
529
  return t.onDialectOrElse({
537
530
  mysql: () => t`${u} LIKE ${e}`,
538
531
  orElse: () => t`${u} LIKE ${e} ESCAPE '\\'`
@@ -580,13 +573,13 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
580
573
  });
581
574
  }
582
575
  }
583
- }, Rn = (e, t) => {
576
+ }, Bn = (e, t) => {
584
577
  let n = [];
585
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}`);
586
- }, zn = (e, t) => t.csv(e.map((e) => {
579
+ }, Vn = (e, t) => t.csv(e.map((e) => {
587
580
  let n = e.column === void 0 ? t.unsafe("*") : t`${t(e.column)}`;
588
581
  if (e.op.startsWith("window-")) {
589
- let r = Rn(e.window ?? {}, t);
582
+ let r = Bn(e.window ?? {}, t);
590
583
  switch (e.op) {
591
584
  case "window-row-number": return t`ROW_NUMBER() OVER (${r}) AS ${t(e.alias)}`;
592
585
  case "window-rank": return t`RANK() OVER (${r}) AS ${t(e.alias)}`;
@@ -610,43 +603,43 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
610
603
  return t`${t(e.column)} AS ${t(e.alias)}`;
611
604
  default: throw Error(`compileAggregateProjection: unknown op '${e.op}'`);
612
605
  }
613
- })), Bn = (e) => `[${e.join(",")}]`, Vn = (e, t) => {
606
+ })), Hn = (e) => `[${e.join(",")}]`, Un = (e, t) => {
614
607
  if (e.queryVector === void 0) return null;
615
- let n = t(e.column), r = Bn(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 = Hn(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
616
609
  return t.onDialectOrElse({
617
610
  mysql: () => t`${t.unsafe(a)}(${n}, ${r})`,
618
611
  mssql: () => t`NULL`,
619
612
  sqlite: () => t`NULL`,
620
613
  orElse: () => t`${n} ${t.unsafe(i)} ${r}::vector`
621
614
  });
622
- }, Hn = (e, t) => {
615
+ }, Wn = (e, t) => {
623
616
  let n = t.unsafe(e.useGeography ? "::geography" : "::geometry");
624
617
  return t`ST_Distance(${t(e.column)}${n}, ${e.geom}${n})`;
625
- }, Un = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, Wn = (e, t) => t`${t(`${e.indexName}_tsv`)}`, Gn = (e, t) => `${t}_${e.indexName}_fts`, Kn = (e, t, n) => {
626
- let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${P(e.query)}%`;
618
+ }, Gn = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, Kn = (e, t) => t`${t(`${e.indexName}_tsv`)}`, qn = (e, t) => `${t}_${e.indexName}_fts`, Jn = (e, t, n) => {
619
+ let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${j(e.query)}%`;
627
620
  return n.onDialectOrElse({
628
621
  mysql: () => n`MATCH(${r}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
629
622
  sqlite: () => {
630
- let r = n(Gn(e, t));
623
+ let r = n(qn(e, t));
631
624
  return n`${n("id")} IN (SELECT ${n("row_id")} FROM ${r} WHERE ${r} MATCH ${e.query})`;
632
625
  },
633
626
  mssql: () => n.or(e.columns.map((e) => n`LOWER(${n(e)}) LIKE LOWER(${i}) ESCAPE '\\'`)),
634
- orElse: () => n`${Wn(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
627
+ orElse: () => n`${Kn(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
635
628
  });
636
- }, qn = (e, t, n) => {
637
- let r = `%${P(e.query)}%`;
629
+ }, Yn = (e, t, n) => {
630
+ let r = `%${j(e.query)}%`;
638
631
  return n.onDialectOrElse({
639
632
  mysql: () => n`MATCH(${n.csv(e.columns.map((e) => n`${n(e)}`))}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
640
633
  sqlite: () => {
641
- let r = n(Gn(e, t));
634
+ let r = n(qn(e, t));
642
635
  return n`COALESCE((SELECT -bm25(${r}) FROM ${r} WHERE ${r} MATCH ${e.query} AND ${r}.${n("row_id")} = ${n("id")}), 0)`;
643
636
  },
644
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}`),
645
- orElse: () => n`ts_rank(${Wn(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
638
+ orElse: () => n`ts_rank(${Kn(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
646
639
  });
647
- }, I = (e, t, n = null) => {
640
+ }, N = (e, t, n = null) => {
648
641
  if (e.setOp && e.setOp.queries.length >= 2) {
649
- let r = e.setOp.kind === "union" ? "UNION" : e.setOp.kind === "union-all" ? "UNION ALL" : e.setOp.kind === "intersect" ? "INTERSECT" : "EXCEPT", i = e.setOp.queries.map((e) => t`(${I(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
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`(${N(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
650
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) {
651
644
  if (!Number.isInteger(e.take) || e.take < 0) throw Error(`compileSelect: invalid take ${e.take}`);
652
645
  a.push(t` LIMIT ${t.unsafe(String(e.take))}`);
@@ -657,7 +650,7 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
657
650
  }
658
651
  return t`${i}${a.reduce((e, n) => t`${e}${n}`, t``)}`;
659
652
  }
660
- let r = e.annClause === void 0 ? null : Vn(e.annClause, t);
653
+ let r = e.annClause === void 0 ? null : Un(e.annClause, t);
661
654
  e.spatialClause !== void 0 && t.onDialectOrElse({
662
655
  mysql: () => {
663
656
  throw Error("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
@@ -670,16 +663,16 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
670
663
  },
671
664
  orElse: () => t``
672
665
  });
673
- let i = e.spatialClause?.projectAs === void 0 ? null : Hn(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? zn(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({
666
+ let i = e.spatialClause?.projectAs === void 0 ? null : Wn(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? Vn(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 ? Yn(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({
674
667
  orElse: () => t`DISTINCT ON (${t.csv(e.distinctOn.map((e) => t`${t(e)}`))}) `,
675
668
  mysql: () => t`DISTINCT `,
676
669
  mssql: () => t`DISTINCT `,
677
670
  sqlite: () => t`DISTINCT `
678
- }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(Mn(n, e.table))}` : t`${t(Mn(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(Pn(n, e.table))}` : t`${t(Pn(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
679
672
  let r = e.kind === "inner" ? "INNER" : "LEFT";
680
- return t` ${t.unsafe(r)} JOIN ${t(Mn(n, e.table))} AS ${t(e.alias)} ON ${F(e.on, t, n)}`;
681
- }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : Kn(c, e.table, t), _ = [e.predicate ? F(e.predicate, t, n, e.table) : null, g].filter((e) => e !== null), ee = _.length > 0 ? t` WHERE ${t.and(_)}` : t``, v = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, te = e.having ? t` HAVING ${F(e.having, t, n, e.table)}` : t``, y = e.skip !== void 0, b = [];
682
- r !== null && b.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && b.push(e.spatialClause.order === "desc" ? t`${Un(e.spatialClause, t)} DESC` : t`${Un(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && b.push(t`${l} DESC`);
673
+ return t` ${t.unsafe(r)} JOIN ${t(Pn(n, e.table))} AS ${t(e.alias)} ON ${M(e.on, t, n)}`;
674
+ }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : Jn(c, e.table, t), _ = [e.predicate ? M(e.predicate, t, n, e.table) : null, g].filter((e) => e !== null), ee = _.length > 0 ? t` WHERE ${t.and(_)}` : t``, v = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, te = e.having ? t` HAVING ${M(e.having, t, n, e.table)}` : t``, y = 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`${Gn(e.spatialClause, t)} DESC` : t`${Gn(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && b.push(t`${l} DESC`);
683
676
  for (let n of e.order) b.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
684
677
  let ne = b.length > 0 ? t` ORDER BY ${t.csv(b)}` : y ? t.onDialectOrElse({
685
678
  mssql: () => t` ORDER BY (SELECT NULL)`,
@@ -687,40 +680,40 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
687
680
  }) : t``, x = (e) => {
688
681
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`compileSelect: expected non-negative integer take/skip, got ${e}`);
689
682
  return t.unsafe(String(e));
690
- }, re = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${I(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
+ }, re = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${N(e.descriptor, t, n)})`), ie = (e.ctes ?? []).some((e) => e.recursive === !0), ae = re.length > 0 ? t`WITH ${t.unsafe(ie ? "RECURSIVE " : "")}${t.csv(re)} ` : t``;
691
684
  return t.onDialectOrElse({
692
685
  mssql: () => {
693
686
  let n = e.take !== void 0 && !y ? t`TOP ${x(e.take)} ` : t``, r = y ? t` OFFSET ${x(e.skip)} ROWS FETCH NEXT ${x(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
694
- return t`${ie}SELECT ${n}${f}${d} FROM ${h}${ee}${v}${te}${ne}${r}`;
687
+ return t`${ae}SELECT ${n}${f}${d} FROM ${h}${ee}${v}${te}${ne}${r}`;
695
688
  },
696
689
  orElse: () => {
697
690
  let n = e.take === void 0 ? t`` : t` LIMIT ${x(e.take)}`, r = y ? t` OFFSET ${x(e.skip)}` : t``;
698
- return t`${ie}SELECT ${f}${d} FROM ${h}${ee}${v}${te}${ne}${n}${r}`;
691
+ return t`${ae}SELECT ${f}${d} FROM ${h}${ee}${v}${te}${ne}${n}${r}`;
699
692
  }
700
693
  });
701
- }, Jn = (e, t, n) => {
694
+ }, Xn = (e, t, n) => {
702
695
  if (e.eager === void 0) return null;
703
- let r = Xn(e.table, e.eager, e.sourceTable);
696
+ let r = Qn(e.table, e.eager, e.sourceTable);
704
697
  if (r === null) return null;
705
- let i = rr(n, e, r, nr(t, n));
698
+ let i = ar(n, e, r, ir(t, n));
706
699
  return i === null ? null : {
707
700
  fragment: i,
708
- decode: or(r, n)
701
+ decode: cr(r, n)
709
702
  };
710
- }, L = (e) => e.relation.kind === "one" && e.fkSide === "target", Yn = (e) => ({
703
+ }, P = (e) => e.relation.kind === "one" && e.fkSide === "target", Zn = (e) => ({
711
704
  ...e,
712
705
  branch: {
713
706
  ...e.branch,
714
707
  limit: 2
715
708
  }
716
- }), Xn = (e, t, n) => {
717
- let r = n ?? le(e), i = en(e);
709
+ }), Qn = (e, t, n) => {
710
+ let r = n ?? pe(e), i = nn(e);
718
711
  if (i === void 0) return null;
719
712
  let a = [];
720
713
  for (let [e, n] of Object.entries(t)) {
721
714
  let t = i[e];
722
715
  if (t === void 0) return null;
723
- let o = Zn(e, t, r, n === !0 ? {} : n);
716
+ let o = $n(e, t, r, n === !0 ? {} : n);
724
717
  if (o === null) return null;
725
718
  a.push(o);
726
719
  }
@@ -728,30 +721,30 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
728
721
  table: r,
729
722
  children: a
730
723
  };
731
- }, Zn = (e, t, n, r) => {
724
+ }, $n = (e, t, n, r) => {
732
725
  let i = t.target(), a = (t.kind === "manyToMany" ? void 0 : t.sourceKey) ?? "id", o, s;
733
726
  if (t.kind === "manyToMany") o = t.targetKey, s = "target";
734
727
  else if (t.kind === "one") {
735
- let r = t.sourceKey ?? tr(n, i.tableName);
728
+ let r = t.sourceKey ?? rr(n, i.tableName);
736
729
  if (r !== void 0) o = r, s = "source";
737
730
  else try {
738
- o = t.foreignKey ?? A(i, n.tableName, e), s = "target";
731
+ o = t.foreignKey ?? O(i, n.tableName, e), s = "target";
739
732
  } catch {
740
733
  return null;
741
734
  }
742
735
  } else try {
743
- o = t.foreignKey ?? A(i, n.tableName, e), s = "target";
736
+ o = t.foreignKey ?? O(i, n.tableName, e), s = "target";
744
737
  } catch {
745
738
  return null;
746
739
  }
747
740
  let c = r.with === void 0 ? [] : (() => {
748
- let e = en(i.tableName);
741
+ let e = nn(i.tableName);
749
742
  if (e === void 0 && Object.keys(r.with).length > 0) return null;
750
743
  let t = [];
751
744
  for (let [n, a] of Object.entries(r.with)) {
752
745
  let r = e?.[n];
753
746
  if (r === void 0) return null;
754
- let o = Zn(n, r, i, a === !0 ? {} : a);
747
+ let o = $n(n, r, i, a === !0 ? {} : a);
755
748
  if (o === null) return null;
756
749
  t.push(o);
757
750
  }
@@ -767,9 +760,9 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
767
760
  fkSide: s,
768
761
  branch: r,
769
762
  children: c,
770
- junction: Qn(t, r)
763
+ junction: er(t, r)
771
764
  };
772
- }, Qn = (e, t) => {
765
+ }, er = (e, t) => {
773
766
  if (e.kind !== "manyToMany" || t.junction === void 0) return;
774
767
  let n = e.through(), r = t.junction === !0 ? Object.keys(n.fields) : t.junction, i = r.filter((e) => e in n.fields);
775
768
  return {
@@ -781,35 +774,35 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
781
774
  return t !== void 0 && (t.type === "timestamp" || t.type === "date");
782
775
  })
783
776
  };
784
- }, $n = (e) => `__j_${e}`, er = "__j", tr = (e, t) => {
777
+ }, tr = (e) => `__j_${e}`, nr = "__j", rr = (e, t) => {
785
778
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
786
- }, nr = (e, t) => {
779
+ }, ir = (e, t) => {
787
780
  let n = 0;
788
781
  return {
789
782
  sql: e,
790
783
  dialect: t,
791
784
  nextAlias: () => `__a${n++}`
792
785
  };
793
- }, rr = (e, t, n, r) => {
786
+ }, ar = (e, t, n, r) => {
794
787
  switch (e) {
795
- case "postgres": return lr(t, n, r);
788
+ case "postgres": return dr(t, n, r);
796
789
  case "sqlite":
797
- case "turso": return _r(t, n, r);
790
+ case "turso": return yr(t, n, r);
798
791
  case "mysql":
799
- case "mariadb": return Dr(t, n, r);
800
- case "mssql": return Pr(t, n, r);
792
+ case "mariadb": return kr(t, n, r);
793
+ case "mssql": return Ir(t, n, r);
801
794
  }
802
- }, ir = (e, t) => t === "mssql" && !ar.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), ar = /(?:Z|[+-]\d{2}:?\d{2})$/, or = (e, t) => {
803
- let n = sr(e.table, e.children, t);
795
+ }, or = (e, t) => t === "mssql" && !sr.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), sr = /(?:Z|[+-]\d{2}:?\d{2})$/, cr = (e, t) => {
796
+ let n = lr(e.table, e.children, t);
804
797
  return (e) => e.map((e) => {
805
798
  let t = e.__row, r = typeof t == "string" ? JSON.parse(t) : t;
806
799
  return n(r);
807
800
  });
808
- }, sr = (e, t, n) => {
801
+ }, lr = (e, t, n) => {
809
802
  let r = [];
810
803
  for (let [t, n] of Object.entries(e.fields)) (n.type === "timestamp" || n.type === "date") && r.push(t);
811
804
  let i = t.map((e) => {
812
- let t = sr(e.target, e.children, n), r = e.relation.kind === "one", i = L(e), a = i ? hn({
805
+ let t = lr(e.target, e.children, n), r = e.relation.kind === "one", i = P(e), a = i ? _n({
813
806
  relationName: e.relationName,
814
807
  sourceTableName: e.source.tableName,
815
808
  targetTableName: e.target.tableName,
@@ -822,14 +815,14 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
822
815
  isSingle: r,
823
816
  fromOverFetch: i,
824
817
  cardinalityMessage: a,
825
- junction: cr(e.junction, n)
818
+ junction: ur(e.junction, n)
826
819
  };
827
820
  });
828
821
  return (e) => {
829
822
  let t = { ...e };
830
823
  for (let e of r) {
831
824
  let r = t[e];
832
- typeof r == "string" && (t[e] = ir(r, n));
825
+ typeof r == "string" && (t[e] = or(r, n));
833
826
  }
834
827
  for (let e of i) {
835
828
  let n = t[e.name];
@@ -839,7 +832,7 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
839
832
  }
840
833
  if (e.fromOverFetch) {
841
834
  let r = n;
842
- if (r.length > 1) throw new mn(e.cardinalityMessage);
835
+ if (r.length > 1) throw new gn(e.cardinalityMessage);
843
836
  t[e.name] = r.length === 0 ? null : e.decode(r[0]);
844
837
  continue;
845
838
  }
@@ -851,204 +844,204 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
851
844
  }
852
845
  return t;
853
846
  };
854
- }, cr = (e, t) => {
847
+ }, ur = (e, t) => {
855
848
  if (e === void 0) return;
856
849
  let n = new Set(e.dateColumns), r = e.requested;
857
850
  return (e) => {
858
851
  let i = e._junction ?? {}, a = {};
859
852
  for (let e of r) {
860
853
  let r = i[e];
861
- a[e] = n.has(e) && typeof r == "string" ? ir(r, t) : r;
854
+ a[e] = n.has(e) && typeof r == "string" ? or(r, t) : r;
862
855
  }
863
856
  return {
864
857
  ...e,
865
858
  _junction: a
866
859
  };
867
860
  };
868
- }, lr = (e, t, n) => {
869
- let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = ur(i, t.children, n);
870
- return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``}${e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`}`;
871
- }, ur = (e, t, n, r) => {
872
- let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${V(er, i)}::text)`;
861
+ }, dr = (e, t, n) => {
862
+ let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = fr(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)}`}`;
864
+ }, fr = (e, t, n, r) => {
865
+ let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${R(nr, i)}::text)`;
873
866
  if (t.length === 0 && r === void 0) return a;
874
867
  let o = [];
875
- r !== void 0 && o.push(i`${V("_junction", i)}, ${B(e, er, i)}`);
868
+ r !== void 0 && o.push(i`${R("_junction", i)}, ${L(e, nr, i)}`);
876
869
  for (let r of t) {
877
- let t = dr(r, e, n);
870
+ let t = pr(r, e, n);
878
871
  if (t === null) return null;
879
- o.push(i`${V(r.relationName, i)}, ${t}`);
872
+ o.push(i`${R(r.relationName, i)}, ${t}`);
880
873
  }
881
874
  return i`${a} || jsonb_build_object(${i.csv(o)})`;
882
- }, dr = (e, t, n) => {
875
+ }, pr = (e, t, n) => {
883
876
  switch (e.relation.kind) {
884
- case "one": return L(e) ? pr(Yn(e), t, n) : fr(e, t, n);
885
- case "many": return pr(e, t, n);
886
- case "manyToMany": return mr(e, t, n);
877
+ case "one": return P(e) ? hr(Zn(e), t, n) : mr(e, t, n);
878
+ case "many": return hr(e, t, n);
879
+ case "manyToMany": return gr(e, t, n);
887
880
  }
888
- }, fr = (e, t, n) => {
889
- let r = n.sql, i = n.nextAlias(), a = ur(i, e.children, n);
881
+ }, mr = (e, t, n) => {
882
+ let r = n.sql, i = n.nextAlias(), a = fr(i, e.children, n);
890
883
  if (a === null) return null;
891
- let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, i, r)}`, c = R(i, e.branch.orderBy, r);
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);
892
885
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}${c} LIMIT 1)`;
893
- }, pr = (e, t, n) => {
894
- let r = n.sql, i = n.nextAlias(), a = ur(i, e.children, n);
886
+ }, hr = (e, t, n) => {
887
+ let r = n.sql, i = n.nextAlias(), a = fr(i, e.children, n);
895
888
  if (a === null) return null;
896
- let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(e.branch.where, r)}`, c = gr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
889
+ let o = r`${L(void 0, e.foreignKey, r)} = ${L(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${M(e.branch.where, r)}`, c = vr(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)}`;
897
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)`;
898
- }, mr = (e, t, n) => {
899
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ur(o, e.children, n, e.junction);
891
+ }, gr = (e, t, n) => {
892
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = fr(o, e.children, n, e.junction);
900
893
  if (c === null) return null;
901
- let l = e.branch.where === void 0 ? r`` : r` AND ${F(e.branch.where, r)}`, u = W(e, s, r), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${hr(e.junction, s, r)} AS ${r(er)}`;
902
- return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
903
- }, hr = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t, e, n)}`))})`, R = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${B(e, t.column, n)} DESC` : n`${B(e, t.column, n)} ASC`))}`, gr = (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`))}`, _r = (e, t, n) => {
904
- let r = n.sql, i = n.nextAlias(), a = vr(i, t.table, t.children, n);
894
+ let l = e.branch.where === void 0 ? r`` : r` AND ${M(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`, ${_r(e.junction, s, r)} AS ${r(nr)}`;
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
+ }, _r = (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`))}`, vr = (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`))}`, yr = (e, t, n) => {
897
+ let r = n.sql, i = n.nextAlias(), a = br(i, t.table, t.children, n);
905
898
  if (a === null) return null;
906
- let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
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)}`;
907
900
  return r`SELECT ${a} AS "__row" FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
908
- }, vr = (e, t, n, r, i) => {
901
+ }, br = (e, t, n, r, i) => {
909
902
  let a = r.sql, o = [];
910
- for (let n of Object.keys(t.fields)) o.push(a`${V(n, a)}, ${B(e, n, a)}`);
903
+ for (let n of Object.keys(t.fields)) o.push(a`${R(n, a)}, ${L(e, n, a)}`);
911
904
  if (i !== void 0) {
912
- let e = yr(i.projection, i.source, a);
913
- o.push(a`${V("_junction", a)}, json_object(${e})`);
905
+ let e = xr(i.projection, i.source, a);
906
+ o.push(a`${R("_junction", a)}, json_object(${e})`);
914
907
  }
915
908
  for (let t of n) {
916
- let n = Cr(t, e, r);
909
+ let n = Tr(t, e, r);
917
910
  if (n === null) return null;
918
- o.push(a`${V(t.relationName, a)}, ${n}`);
911
+ o.push(a`${R(t.relationName, a)}, ${n}`);
919
912
  }
920
913
  return a`json_object(${a.csv(o)})`;
921
- }, yr = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t.alias, t.physical(e), n)}`)), br = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${B(t, e, n)} AS ${n($n(e))}`))}`, xr = (e) => ({
914
+ }, xr = (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)}`)), Sr = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${L(t, e, n)} AS ${n(tr(e))}`))}`, Cr = (e) => ({
922
915
  alias: e,
923
- physical: $n
924
- }), Sr = (e) => ({
916
+ physical: tr
917
+ }), wr = (e) => ({
925
918
  alias: e,
926
919
  physical: (e) => e
927
- }), Cr = (e, t, n) => {
920
+ }), Tr = (e, t, n) => {
928
921
  switch (e.relation.kind) {
929
- case "one": return L(e) ? Tr(Yn(e), t, n) : wr(e, t, n);
930
- case "many": return Tr(e, t, n);
931
- case "manyToMany": return Er(e, t, n);
922
+ case "one": return P(e) ? Dr(Zn(e), t, n) : Er(e, t, n);
923
+ case "many": return Dr(e, t, n);
924
+ case "manyToMany": return Or(e, t, n);
932
925
  }
933
- }, wr = (e, t, n) => {
934
- let r = n.sql, i = n.nextAlias(), a = vr(i, e.target, e.children, n);
926
+ }, Er = (e, t, n) => {
927
+ let r = n.sql, i = n.nextAlias(), a = br(i, e.target, e.children, n);
935
928
  if (a === null) return null;
936
- let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
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)}`;
937
930
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
938
- }, Tr = (e, t, n) => {
939
- let r = n.sql, i = n.nextAlias(), a = vr(i, e.target, e.children, n);
931
+ }, Dr = (e, t, n) => {
932
+ let r = n.sql, i = n.nextAlias(), a = br(i, e.target, e.children, n);
940
933
  if (a === null) return null;
941
- let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(G(e.branch.where), r)}`, c = gr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
934
+ let o = r`${L(void 0, e.foreignKey, r)} = ${L(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${M(H(e.branch.where), r)}`, c = vr(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)}`;
942
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('[]'))`;
943
- }, Er = (e, t, n) => {
944
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = vr(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
936
+ }, Or = (e, t, n) => {
937
+ 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 : {
945
938
  projection: e.junction,
946
- source: xr(o)
939
+ source: Cr(o)
947
940
  });
948
941
  if (c === null) return null;
949
- let l = e.branch.where === void 0 ? r`` : r` AND ${F(G(e.branch.where), r)}`, u = W(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : br(e.junction, s, r);
950
- return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
951
- }, Dr = (e, t, n) => {
952
- let r = n.sql, i = n.nextAlias(), a = z(i, t.table, t.children, n);
942
+ let l = e.branch.where === void 0 ? r`` : r` AND ${M(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`` : Sr(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('[]'))`;
944
+ }, kr = (e, t, n) => {
945
+ let r = n.sql, i = n.nextAlias(), a = I(i, t.table, t.children, n);
953
946
  if (a === null) return null;
954
- let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
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)}`;
955
948
  return r`SELECT ${a} AS \`__row\` FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
956
- }, z = (e, t, n, r, i) => {
949
+ }, I = (e, t, n, r, i) => {
957
950
  let a = r.sql, o = [];
958
- for (let n of Object.keys(t.fields)) o.push(a`${V(n, a)}, ${B(e, n, a)}`);
951
+ for (let n of Object.keys(t.fields)) o.push(a`${R(n, a)}, ${L(e, n, a)}`);
959
952
  if (i !== void 0) {
960
- let e = yr(i.projection, i.source, a);
961
- o.push(a`${V("_junction", a)}, JSON_OBJECT(${e})`);
953
+ let e = xr(i.projection, i.source, a);
954
+ o.push(a`${R("_junction", a)}, JSON_OBJECT(${e})`);
962
955
  }
963
956
  for (let t of n) {
964
- let n = Or(t, e, r);
957
+ let n = Ar(t, e, r);
965
958
  if (n === null) return null;
966
- o.push(a`${V(t.relationName, a)}, ${n}`);
959
+ o.push(a`${R(t.relationName, a)}, ${n}`);
967
960
  }
968
961
  return a`JSON_OBJECT(${a.csv(o)})`;
969
- }, Or = (e, t, n) => {
962
+ }, Ar = (e, t, n) => {
970
963
  switch (e.relation.kind) {
971
964
  case "one":
972
- if (L(e)) {
973
- let r = Yn(e);
974
- return n.dialect === "mariadb" ? Mr(r, t, n) : Ar(r, t, n);
965
+ if (P(e)) {
966
+ let r = Zn(e);
967
+ return n.dialect === "mariadb" ? Pr(r, t, n) : Mr(r, t, n);
975
968
  }
976
- return kr(e, t, n);
977
- case "many": return n.dialect === "mariadb" ? Mr(e, t, n) : Ar(e, t, n);
978
- case "manyToMany": return n.dialect === "mariadb" ? Nr(e, t, n) : jr(e, t, n);
969
+ return jr(e, t, n);
970
+ case "many": return n.dialect === "mariadb" ? Pr(e, t, n) : Mr(e, t, n);
971
+ case "manyToMany": return n.dialect === "mariadb" ? Fr(e, t, n) : Nr(e, t, n);
979
972
  }
980
- }, kr = (e, t, n) => {
981
- let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
973
+ }, jr = (e, t, n) => {
974
+ let r = n.sql, i = n.nextAlias(), a = I(i, e.target, e.children, n);
982
975
  if (a === null) return null;
983
- let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
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)}`;
984
977
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
985
- }, Ar = (e, t, n) => {
986
- let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
978
+ }, Mr = (e, t, n) => {
979
+ let r = n.sql, i = n.nextAlias(), a = I(i, e.target, e.children, n);
987
980
  if (a === null) return null;
988
- let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(G(e.branch.where), r)}`, c = gr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
981
+ let o = r`${L(void 0, e.foreignKey, r)} = ${L(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${M(H(e.branch.where), r)}`, c = vr(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)}`;
989
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())`;
990
- }, jr = (e, t, n) => {
991
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = z(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
983
+ }, Nr = (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 : {
992
985
  projection: e.junction,
993
- source: xr(o)
986
+ source: Cr(o)
994
987
  });
995
988
  if (c === null) return null;
996
- let l = e.branch.where === void 0 ? r`` : r` AND ${F(G(e.branch.where), r)}`, u = W(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : br(e.junction, s, r);
997
- return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
998
- }, Mr = (e, t, n) => {
999
- let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
989
+ let l = e.branch.where === void 0 ? r`` : r` AND ${M(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`` : Sr(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())`;
991
+ }, Pr = (e, t, n) => {
992
+ let r = n.sql, i = n.nextAlias(), a = I(i, e.target, e.children, n);
1000
993
  if (a === null) return null;
1001
- let o = r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(G(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1002
- if (!(e.branch.limit !== void 0 || e.branch.offset !== void 0)) return r`COALESCE((SELECT JSON_ARRAYAGG(${a}${c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
1003
- let l = c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${r(e.column)} DESC` : r`${r(e.column)} ASC`))}` : r` ORDER BY ${r("id")}`, u = e.branch.limit, d = e.branch.offset, f = u !== void 0 && d !== void 0 ? r` AND ${B(i, "rn", r)} > ${H(d, r)} AND ${B(i, "rn", r)} <= ${H(d + u, r)}` : u === void 0 ? r` AND ${B(i, "rn", r)} > ${H(d, r)}` : r` AND ${B(i, "rn", r)} <= ${H(u, r)}`;
1004
- return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${B(i, "rn", r)}) FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${r(e.foreignKey)}${l}) AS rn FROM ${r(e.target.tableName)}) AS ${r(i)} WHERE ${o}${s}${f}), JSON_ARRAY())`;
1005
- }, Nr = (e, t, n) => {
994
+ let o = r`${L(i, e.foreignKey, r)} = ${L(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${M(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())`;
998
+ }, Fr = (e, t, n) => {
1006
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 : {
1007
1000
  projection: e.junction,
1008
1001
  source: t
1009
- }, l = r`${B(s, i.sourceKey, r)} = ${B(t, "id", r)}`, u = r`${B(o, "id", r)} = ${B(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${F(G(e.branch.where), r)}`, f = W(e, s, r, !0), p = e.branch.orderBy ?? [];
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 ${M(H(e.branch.where), r)}`, f = V(e, s, r, !0), p = e.branch.orderBy ?? [];
1010
1003
  if (!(e.branch.limit !== void 0 || e.branch.offset !== void 0)) {
1011
- let t = z(o, e.target, e.children, n, c(Sr(s)));
1012
- return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r``}) FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u} WHERE ${l}${f}${d}), JSON_ARRAY())`;
1004
+ let t = I(o, e.target, e.children, n, c(wr(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())`;
1013
1006
  }
1014
- let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r` ORDER BY ${B(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, _ = h !== void 0 && g !== void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)} AND ${B(o, "rn", r)} <= ${H(g + h, r)}` : h === void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)}` : r` AND ${B(o, "rn", r)} <= ${H(h, r)}`, ee = e.branch.onJunction === void 0 ? r`` : r` WHERE ${U(G(e.branch.onJunction), s, r)}`, v = z(o, e.target, e.children, n, c(xr(o)));
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)}`, ee = e.branch.onJunction === void 0 ? r`` : r` WHERE ${B(H(e.branch.onJunction), s, r)}`, v = I(o, e.target, e.children, n, c(Cr(o)));
1015
1008
  if (v === null) return null;
1016
- let te = e.junction === void 0 ? r`` : br(e.junction, s, r);
1017
- return r`COALESCE((SELECT JSON_ARRAYAGG(${v} ORDER BY ${B(o, "rn", r)}) FROM (SELECT ${r(o)}.*${te}, ${B(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${B(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${ee}) AS ${r(o)} WHERE ${B(o, `__src_${i.sourceKey}`, r)} = ${B(t, "id", r)}${d}${_}), JSON_ARRAY())`;
1018
- }, Pr = (e, t, n) => {
1019
- let r = n.sql, i = n.nextAlias(), a = Fr(i, t.table, t.children, n);
1009
+ let te = e.junction === void 0 ? r`` : Sr(e.junction, s, r);
1010
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${v} ORDER BY ${L(o, "rn", r)}) FROM (SELECT ${r(o)}.*${te}, ${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}${ee}) AS ${r(o)} WHERE ${L(o, `__src_${i.sourceKey}`, r)} = ${L(t, "id", r)}${d}${_}), JSON_ARRAY())`;
1011
+ }, Ir = (e, t, n) => {
1012
+ let r = n.sql, i = n.nextAlias(), a = Lr(i, t.table, t.children, n);
1020
1013
  if (a === null) return null;
1021
- let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
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``;
1022
1015
  if (e.skip !== void 0) {
1023
1016
  let t = e.order.length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1024
- l = e.take === void 0 ? r`${t} OFFSET ${H(e.skip, r)} ROWS` : r`${t} OFFSET ${H(e.skip, r)} ROWS FETCH NEXT ${H(e.take, r)} ROWS ONLY`;
1025
- } else e.take !== void 0 && (c = r`TOP ${H(e.take, r)} `);
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)} `);
1026
1019
  let u = e.skip === void 0 ? s : r``;
1027
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}`;
1028
- }, Fr = (e, t, n, r, i) => {
1021
+ }, Lr = (e, t, n, r, i) => {
1029
1022
  let a = r.sql, o = [];
1030
- for (let n of Object.keys(t.fields)) o.push(a`${B(e, n, a)} AS ${a(n)}`);
1031
- if (i !== void 0) for (let e of i.projection.present) o.push(a`${B(i.source.alias, i.source.physical(e), a)} AS ${Ir(`_junction.${e}`, a)}`);
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 ${Rr(`_junction.${e}`, a)}`);
1032
1025
  for (let t of n) {
1033
- let n = Lr(t, e, r);
1026
+ let n = zr(t, e, r);
1034
1027
  if (n === null) return null;
1035
1028
  o.push(n);
1036
1029
  }
1037
1030
  return a.csv(o);
1038
- }, Ir = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), Lr = (e, t, n) => {
1031
+ }, Rr = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), zr = (e, t, n) => {
1039
1032
  switch (e.relation.kind) {
1040
- case "one": return L(e) ? Br(Yn(e), t, n) : Rr(e, t, n);
1041
- case "many": return Br(e, t, n);
1042
- case "manyToMany": return Vr(e, t, n);
1033
+ case "one": return P(e) ? Hr(Zn(e), t, n) : Br(e, t, n);
1034
+ case "many": return Hr(e, t, n);
1035
+ case "manyToMany": return Ur(e, t, n);
1043
1036
  }
1044
- }, Rr = (e, t, n) => {
1045
- let r = n.sql, i = n.nextAlias(), a = Fr(i, e.target, e.children, n);
1037
+ }, Br = (e, t, n) => {
1038
+ let r = n.sql, i = n.nextAlias(), a = Lr(i, e.target, e.children, n);
1046
1039
  if (a === null) return null;
1047
- let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
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)}`;
1048
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)}`;
1049
- }, zr = (e, t, n) => {
1042
+ }, Vr = (e, t, n) => {
1050
1043
  if (e.offset !== void 0) {
1051
- let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${H(e.offset, n)} ROWS` : n`${r} OFFSET ${H(e.offset, n)} ROWS FETCH NEXT ${H(e.limit, n)} ROWS ONLY`;
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`;
1052
1045
  return {
1053
1046
  top: n``,
1054
1047
  pagination: i,
@@ -1056,33 +1049,33 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1056
1049
  };
1057
1050
  }
1058
1051
  return {
1059
- top: e.limit === void 0 ? n`` : n`TOP ${H(e.limit, n)} `,
1052
+ top: e.limit === void 0 ? n`` : n`TOP ${z(e.limit, n)} `,
1060
1053
  pagination: n``,
1061
1054
  finalOrder: t
1062
1055
  };
1063
- }, Br = (e, t, n) => {
1064
- let r = n.sql, i = n.nextAlias(), a = Fr(i, e.target, e.children, n);
1056
+ }, Hr = (e, t, n) => {
1057
+ let r = n.sql, i = n.nextAlias(), a = Lr(i, e.target, e.children, n);
1065
1058
  if (a === null) return null;
1066
- let o = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, i, r)}`, s = R(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = zr(e.branch, s, r);
1067
- return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1068
- }, Vr = (e, t, n) => {
1069
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Fr(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
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 } = Vr(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)}`;
1061
+ }, Ur = (e, t, n) => {
1062
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Lr(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1070
1063
  projection: e.junction,
1071
- source: Sr(s)
1064
+ source: wr(s)
1072
1065
  });
1073
1066
  if (c === null) return null;
1074
- let l = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, o, r)}`, u = W(e, s, r), d = R(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = zr(e.branch, d, r);
1075
- return r`ISNULL(JSON_QUERY((SELECT ${f}${c} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1076
- }, B = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, V = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), H = (e, t) => {
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 } = Vr(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) => {
1077
1070
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`literalInt: expected non-negative integer, got ${e}`);
1078
1071
  return t.unsafe(String(e));
1079
- }, U = (e, t, n) => F(Hr(e, t), n), W = (e, t, n, r = !1) => {
1072
+ }, B = (e, t, n) => M(Wr(e, t), n), V = (e, t, n, r = !1) => {
1080
1073
  let i = e.branch.onJunction;
1081
- return i === void 0 ? n`` : n` AND ${U(r ? G(i) : i, t, n)}`;
1082
- }, Hr = (e, t) => {
1083
- if ("not" in e) return { not: Hr(e.not, t) };
1084
- if ("and" in e) return { and: e.and.map((e) => Hr(e, t)) };
1085
- if ("or" in e) return { or: e.or.map((e) => Hr(e, t)) };
1074
+ return i === void 0 ? n`` : n` AND ${B(r ? H(i) : i, t, n)}`;
1075
+ }, Wr = (e, t) => {
1076
+ if ("not" in e) return { not: Wr(e.not, t) };
1077
+ if ("and" in e) return { and: e.and.map((e) => Wr(e, t)) };
1078
+ if ("or" in e) return { or: e.or.map((e) => Wr(e, t)) };
1086
1079
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
1087
1080
  let n = e;
1088
1081
  return {
@@ -1096,99 +1089,99 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1096
1089
  ...n,
1097
1090
  column: `${t}.${n.column}`
1098
1091
  };
1099
- }, G = (e) => {
1100
- if ("not" in e) return { not: G(e.not) };
1101
- if ("and" in e) return { and: e.and.map((e) => G(e)) };
1102
- if ("or" in e) return { or: e.or.map((e) => G(e)) };
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)) };
1103
1096
  if (e.op === "subquery-in" || e.op === "subquery-not-in" || e.op === "exists" || e.op === "not-exists") return e;
1104
1097
  let t = e;
1105
1098
  return {
1106
1099
  ...t,
1107
- value: Ur(t.value)
1100
+ value: Gr(t.value)
1108
1101
  };
1109
- }, Ur = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => Ur(e)) : e, Wr = Symbol.for("@voltro/database/coreTablesRegistry"), Gr = globalThis, Kr = Gr[Wr] ?? (Gr[Wr] = {}), qr = (e) => {
1110
- e.actors !== void 0 && (Kr.actors = e.actors), e.tenants !== void 0 && (Kr.tenants = e.tenants);
1111
- }, Jr = (e, t) => () => {
1102
+ }, Gr = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => Gr(e)) : e, Kr = Symbol.for("@voltro/database/coreTablesRegistry"), qr = globalThis, Jr = qr[Kr] ?? (qr[Kr] = {}), Yr = (e) => {
1103
+ e.actors !== void 0 && (Jr.actors = e.actors), e.tenants !== void 0 && (Jr.tenants = e.tenants);
1104
+ }, Xr = (e, t) => () => {
1112
1105
  let n = e();
1113
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`);
1114
1107
  return n();
1115
- }, Yr = () => Jr(() => Kr.actors, "actors"), Xr = () => Jr(() => Kr.tenants, "tenants"), Zr = _("actors", {
1116
- id: E(),
1117
- kind: S().oneOf([
1108
+ }, Zr = () => Xr(() => Jr.actors, "actors"), Qr = () => Xr(() => Jr.tenants, "tenants"), $r = _("actors", {
1109
+ id: l(),
1110
+ kind: h().oneOf([
1118
1111
  "user",
1119
1112
  "serviceAccount",
1120
1113
  "apiKey",
1121
1114
  "system"
1122
1115
  ]),
1123
- displayName: S().nullable(),
1124
- createdAt: d().default("now")
1125
- }), Qr = (e, t) => ({
1116
+ displayName: h().nullable(),
1117
+ createdAt: v().default("now")
1118
+ }), ei = (e, t) => ({
1126
1119
  column: e,
1127
1120
  op: "eq",
1128
1121
  value: t
1129
- }), $r = (e, t) => ({
1122
+ }), ti = (e, t) => ({
1130
1123
  column: e,
1131
1124
  op: "neq",
1132
1125
  value: t
1133
- }), ei = (e, t) => ({
1126
+ }), ni = (e, t) => ({
1134
1127
  column: e,
1135
1128
  op: "gt",
1136
1129
  value: t
1137
- }), ti = (e, t) => ({
1130
+ }), ri = (e, t) => ({
1138
1131
  column: e,
1139
1132
  op: "gte",
1140
1133
  value: t
1141
- }), ni = (e, t) => ({
1134
+ }), ii = (e, t) => ({
1142
1135
  column: e,
1143
1136
  op: "lt",
1144
1137
  value: t
1145
- }), ri = (e, t) => ({
1138
+ }), ai = (e, t) => ({
1146
1139
  column: e,
1147
1140
  op: "lte",
1148
1141
  value: t
1149
- }), ii = (e, t) => ({
1142
+ }), oi = (e, t) => ({
1150
1143
  column: e,
1151
1144
  op: "in",
1152
1145
  value: t
1153
- }), ai = (e, t) => ({
1146
+ }), si = (e, t) => ({
1154
1147
  column: e,
1155
1148
  op: "notIn",
1156
1149
  value: t
1157
- }), oi = (e, t) => ({
1150
+ }), ci = (e, t) => ({
1158
1151
  column: e,
1159
1152
  op: "contains",
1160
1153
  value: t
1161
- }), si = (e, t) => ({
1154
+ }), li = (e, t) => ({
1162
1155
  column: e,
1163
1156
  op: "startsWith",
1164
1157
  value: t
1165
- }), ci = (e, t) => ({
1158
+ }), ui = (e, t) => ({
1166
1159
  column: e,
1167
1160
  op: "arrayContains",
1168
1161
  value: t
1169
- }), li = (e, t) => ({
1162
+ }), di = (e, t) => ({
1170
1163
  column: e,
1171
1164
  op: "arrayOverlaps",
1172
1165
  value: t
1173
- }), ui = (e, t) => ({
1166
+ }), fi = (e, t) => ({
1174
1167
  column: e,
1175
1168
  op: "arrayHas",
1176
1169
  value: t
1177
- }), di = {
1170
+ }), pi = {
1178
1171
  column: "id",
1179
1172
  op: "in",
1180
1173
  value: []
1181
- }, fi = (e) => ({
1174
+ }, mi = (e) => ({
1182
1175
  column: e,
1183
1176
  op: "isNull"
1184
- }), pi = (e) => ({
1177
+ }), hi = (e) => ({
1185
1178
  column: e,
1186
1179
  op: "isNotNull"
1187
- }), mi = (e, t) => ({
1180
+ }), gi = (e, t) => ({
1188
1181
  column: e,
1189
1182
  op: "spatial",
1190
1183
  value: t
1191
- }), hi = (...e) => ({ and: e }), gi = (...e) => ({ or: e }), _i = (e) => ({ not: e }), vi = (e, ...t) => {
1184
+ }), _i = (...e) => ({ and: e }), vi = (...e) => ({ or: e }), yi = (e) => ({ not: e }), bi = (e, ...t) => {
1192
1185
  if (t.length === 0) throw Error(`jsonField("${e}"): at least one path segment is required`);
1193
1186
  let n = (n, r) => ({
1194
1187
  column: e,
@@ -1210,29 +1203,29 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1210
1203
  isNull: () => n("isNull"),
1211
1204
  isNotNull: () => n("isNotNull")
1212
1205
  };
1213
- }, yi = (e) => "descriptor" in e ? e.descriptor : e, bi = (e, t) => ({
1206
+ }, xi = (e) => "descriptor" in e ? e.descriptor : e, Si = (e, t) => ({
1214
1207
  column: e,
1215
1208
  op: "subquery-in",
1216
- subquery: yi(t)
1217
- }), xi = (e, t) => ({
1209
+ subquery: xi(t)
1210
+ }), Ci = (e, t) => ({
1218
1211
  column: e,
1219
1212
  op: "subquery-not-in",
1220
- subquery: yi(t)
1221
- }), Si = (e) => ({
1213
+ subquery: xi(t)
1214
+ }), wi = (e) => ({
1222
1215
  op: "exists",
1223
- subquery: yi(e)
1224
- }), Ci = (e) => ({
1216
+ subquery: xi(e)
1217
+ }), Ti = (e) => ({
1225
1218
  op: "not-exists",
1226
- subquery: yi(e)
1227
- }), wi = (e, t) => e == null || t == null ? null : typeof e == typeof t ? e === t ? 0 : e > t ? 1 : -1 : null, Ti = (e, t, n = null) => {
1219
+ subquery: xi(e)
1220
+ }), Ei = (e, t) => e == null || t == null ? null : typeof e == typeof t ? e === t ? 0 : e > t ? 1 : -1 : null, Di = (e, t, n = null) => {
1228
1221
  if (!t) return !1;
1229
- if ("not" in e) return !Ti(e.not, t, n);
1222
+ if ("not" in e) return !Di(e.not, t, n);
1230
1223
  if ("and" in e) {
1231
- for (let r of e.and) if (!Ti(r, t, n)) return !1;
1224
+ for (let r of e.and) if (!Di(r, t, n)) return !1;
1232
1225
  return !0;
1233
1226
  }
1234
1227
  if ("or" in e) {
1235
- for (let r of e.or) if (Ti(r, t, n)) return !0;
1228
+ for (let r of e.or) if (Di(r, t, n)) return !0;
1236
1229
  return !1;
1237
1230
  }
1238
1231
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
@@ -1251,10 +1244,10 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1251
1244
  switch (r.op) {
1252
1245
  case "eq": return i === r.value;
1253
1246
  case "neq": return i !== r.value;
1254
- case "gt": return (wi(i, r.value) ?? -1) > 0;
1255
- case "gte": return (wi(i, r.value) ?? -1) >= 0;
1256
- case "lt": return (wi(i, r.value) ?? 1) < 0;
1257
- case "lte": return (wi(i, r.value) ?? 1) <= 0;
1247
+ case "gt": return (Ei(i, r.value) ?? -1) > 0;
1248
+ case "gte": return (Ei(i, r.value) ?? -1) >= 0;
1249
+ case "lt": return (Ei(i, r.value) ?? 1) < 0;
1250
+ case "lte": return (Ei(i, r.value) ?? 1) <= 0;
1258
1251
  case "in": return Array.isArray(r.value) && r.value.includes(i);
1259
1252
  case "notIn": return Array.isArray(r.value) && !r.value.includes(i);
1260
1253
  case "contains": return typeof i == "string" && typeof r.value == "string" && i.toLowerCase().includes(r.value.toLowerCase());
@@ -1272,17 +1265,17 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1272
1265
  case "isNotNull": return i != null;
1273
1266
  case "spatial": throw Error("@voltro/plugin-postgis: spatial predicates (ST_DWithin / ST_Contains / ST_Within / ST_Intersects / bbox &&) are not evaluable in-memory — use them in one-shot ctx.store.query reads, not reactive subscriptions.");
1274
1267
  }
1275
- }, Ei = function* (e) {
1268
+ }, Oi = function* (e) {
1276
1269
  if ("not" in e) {
1277
- yield* Ei(e.not);
1270
+ yield* Oi(e.not);
1278
1271
  return;
1279
1272
  }
1280
1273
  if ("and" in e) {
1281
- for (let t of e.and) yield* Ei(t);
1274
+ for (let t of e.and) yield* Oi(t);
1282
1275
  return;
1283
1276
  }
1284
1277
  if ("or" in e) {
1285
- for (let t of e.or) yield* Ei(t);
1278
+ for (let t of e.or) yield* Oi(t);
1286
1279
  return;
1287
1280
  }
1288
1281
  e.op === "subquery-in" || e.op === "subquery-not-in" ? yield {
@@ -1292,83 +1285,83 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1292
1285
  kind: "exists",
1293
1286
  descriptor: e.subquery
1294
1287
  });
1295
- }, Di = function* (e, t = !0) {
1288
+ }, ki = function* (e, t = !0) {
1296
1289
  if ("not" in e) {
1297
- yield* Di(e.not, !1);
1290
+ yield* ki(e.not, !1);
1298
1291
  return;
1299
1292
  }
1300
1293
  if ("and" in e) {
1301
- for (let n of e.and) yield* Di(n, t);
1294
+ for (let n of e.and) yield* ki(n, t);
1302
1295
  return;
1303
1296
  }
1304
1297
  if ("or" in e) {
1305
- for (let t of e.or) yield* Di(t, !1);
1298
+ for (let t of e.or) yield* ki(t, !1);
1306
1299
  return;
1307
1300
  }
1308
1301
  e.op === "subquery-in" || e.op === "subquery-not-in" || e.op === "exists" || e.op === "not-exists" || (yield {
1309
1302
  ...e,
1310
1303
  conjunctive: t
1311
1304
  });
1312
- }, Oi = new gt(), ki = (e, t) => Oi.run(e, t), Ai = () => Oi.getStore(), ji = (e) => {
1313
- let t = e ?? Oi.getStore();
1305
+ }, U = new bt(), Ai = (e, t) => U.run(e, t), ji = () => U.getStore(), Mi = (e) => {
1306
+ let t = e ?? U.getStore();
1314
1307
  return t === void 0 ? {} : {
1315
1308
  ...t.traceId === void 0 ? {} : { traceId: t.traceId },
1316
1309
  ...t.subjectId === void 0 ? {} : { subjectId: t.subjectId },
1317
1310
  ...t.procedure === void 0 ? {} : { procedure: t.procedure }
1318
1311
  };
1319
- }, Mi = (e) => {
1320
- let t = Oi.getStore();
1321
- return t === void 0 ? e(void 0) : Oi.run(t, () => e(t));
1322
- }, Ni = 3e4, Pi = 1e4, K = /* @__PURE__ */ new Map(), q = 0, Fi = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Ii = (e) => {
1323
- for (let [t, n] of K) {
1324
- let r = n.filter((t) => e - t.at < Ni);
1325
- q -= n.length - r.length, r.length === 0 ? K.delete(t) : r.length !== n.length && K.set(t, r);
1326
- }
1327
- }, Li = (e, t) => {
1312
+ }, Ni = (e) => {
1313
+ let t = U.getStore();
1314
+ return t === void 0 ? e(void 0) : U.run(t, () => e(t));
1315
+ }, Pi = 3e4, Fi = 1e4, W = /* @__PURE__ */ new Map(), G = 0, Ii = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Li = (e) => {
1316
+ for (let [t, n] of W) {
1317
+ let r = n.filter((t) => e - t.at < Pi);
1318
+ G -= n.length - r.length, r.length === 0 ? W.delete(t) : r.length !== n.length && W.set(t, r);
1319
+ }
1320
+ }, Ri = (e, t) => {
1328
1321
  if (t.traceId === void 0 && t.subjectId === void 0 && t.procedure === void 0) return;
1329
1322
  let n = Date.now();
1330
- if (q >= Pi && Ii(n), q >= Pi) return;
1331
- let r = K.get(e);
1332
- r === void 0 ? K.set(e, [{
1323
+ if (G >= Fi && Li(n), G >= Fi) return;
1324
+ let r = W.get(e);
1325
+ r === void 0 ? W.set(e, [{
1333
1326
  attribution: t,
1334
1327
  at: n
1335
1328
  }]) : r.push({
1336
1329
  attribution: t,
1337
1330
  at: n
1338
- }), q += 1;
1339
- }, Ri = (e) => {
1340
- let t = K.get(e);
1331
+ }), G += 1;
1332
+ }, zi = (e) => {
1333
+ let t = W.get(e);
1341
1334
  if (t === void 0 || t.length === 0) return;
1342
1335
  let n = t.shift();
1343
- if (--q, t.length === 0 && K.delete(e), !(Date.now() - n.at >= Ni)) return n.attribution;
1344
- }, zi = (e) => (K.get(e)?.length ?? 0) > 0, J = /* @__PURE__ */ new Map(), Bi = /* @__PURE__ */ new Map(), Vi = /* @__PURE__ */ new Map(), Hi = 250, Ui = (e) => {
1345
- let t = Bi.get(e);
1336
+ if (--G, t.length === 0 && W.delete(e), !(Date.now() - n.at >= Pi)) return n.attribution;
1337
+ }, Bi = (e) => (W.get(e)?.length ?? 0) > 0, K = /* @__PURE__ */ new Map(), q = /* @__PURE__ */ new Map(), J = /* @__PURE__ */ new Map(), Vi = 250, Hi = (e) => {
1338
+ let t = q.get(e);
1346
1339
  if (t === void 0) return;
1347
- Bi.delete(e);
1348
- let n = Vi.get(e);
1349
- n !== void 0 && (clearTimeout(n), Vi.delete(e));
1340
+ q.delete(e);
1341
+ let n = J.get(e);
1342
+ n !== void 0 && (clearTimeout(n), J.delete(e));
1350
1343
  for (let e of t) e();
1344
+ }, Ui = (e) => {
1345
+ K.set(e, (K.get(e) ?? 0) + 1);
1351
1346
  }, Wi = (e) => {
1352
- J.set(e, (J.get(e) ?? 0) + 1);
1353
- }, Gi = (e) => {
1354
- let t = (J.get(e) ?? 0) - 1;
1347
+ let t = (K.get(e) ?? 0) - 1;
1355
1348
  if (t > 0) {
1356
- J.set(e, t);
1349
+ K.set(e, t);
1357
1350
  return;
1358
1351
  }
1359
- J.delete(e), Ui(e);
1360
- }, Ki = (e, t, n, r) => {
1361
- let i = n == null ? void 0 : Fi(e, t, n), a = () => r(i === void 0 ? void 0 : Ri(i));
1352
+ K.delete(e), Hi(e);
1353
+ }, Gi = (e, t, n, r) => {
1354
+ let i = n == null ? void 0 : Ii(e, t, n), a = () => r(i === void 0 ? void 0 : zi(i));
1362
1355
  if (i === void 0) {
1363
1356
  a();
1364
1357
  return;
1365
1358
  }
1366
- if (zi(i)) {
1359
+ if (Bi(i)) {
1367
1360
  a();
1368
1361
  return;
1369
1362
  }
1370
- let o = Bi.get(e);
1371
- if (o === void 0 && (J.get(e) ?? 0) === 0) {
1363
+ let o = q.get(e);
1364
+ if (o === void 0 && (K.get(e) ?? 0) === 0) {
1372
1365
  a();
1373
1366
  return;
1374
1367
  }
@@ -1376,38 +1369,38 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1376
1369
  o.push(a);
1377
1370
  return;
1378
1371
  }
1379
- Bi.set(e, [a]);
1380
- let s = setTimeout(() => Ui(e), Hi);
1381
- typeof s == "object" && typeof s.unref == "function" && s.unref(), Vi.set(e, s);
1382
- }, qi = () => {
1383
- K.clear(), q = 0, J.clear();
1384
- for (let e of Vi.values()) clearTimeout(e);
1385
- Vi.clear(), Bi.clear();
1386
- }, Ji = () => q, Y = /* @__PURE__ */ new Map(), Yi = (e, t) => {
1372
+ q.set(e, [a]);
1373
+ let s = setTimeout(() => Hi(e), Vi);
1374
+ typeof s == "object" && typeof s.unref == "function" && s.unref(), J.set(e, s);
1375
+ }, Ki = () => {
1376
+ W.clear(), G = 0, K.clear();
1377
+ for (let e of J.values()) clearTimeout(e);
1378
+ J.clear(), q.clear();
1379
+ }, qi = () => G, Y = /* @__PURE__ */ new Map(), Ji = (e, t) => {
1387
1380
  Y.set(e, {
1388
1381
  recorder: t.recorder,
1389
1382
  tables: new Set(t.tables),
1390
1383
  ownTables: new Set(t.ownTables)
1391
1384
  });
1392
- }, Xi = (e) => {
1385
+ }, Yi = (e) => {
1393
1386
  Y.delete(e);
1394
- }, Zi = () => Y.clear(), Qi = (e) => {
1387
+ }, Xi = () => Y.clear(), Zi = (e) => {
1395
1388
  if (Y.size === 0) return !1;
1396
1389
  for (let t of Y.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1397
1390
  return !1;
1398
- }, $i = async (e, t) => {
1391
+ }, Qi = async (e, t) => {
1399
1392
  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);
1400
- }, ea = (e) => {
1401
- if (mt.isSuccess(e)) return e.value;
1402
- throw ut.squash(e.cause);
1403
- }, ta = class extends O.TaggedError()("VersionConflict", {
1404
- table: O.String,
1405
- id: O.String,
1406
- expected: O.Number,
1407
- actual: O.NullOr(O.Number)
1408
- }) {}, na = (e) => {
1393
+ }, $i = (e) => {
1394
+ if (vt.isSuccess(e)) return e.value;
1395
+ throw mt.squash(e.cause);
1396
+ }, ea = class extends E.TaggedError()("VersionConflict", {
1397
+ table: E.String,
1398
+ id: E.String,
1399
+ expected: E.Number,
1400
+ actual: E.NullOr(E.Number)
1401
+ }) {}, ta = (e) => {
1409
1402
  for (let [t, n] of Object.entries(e)) if (n?.definition?.versionColumn === !0) return t;
1410
- }, ra = (e) => {
1403
+ }, na = (e) => {
1411
1404
  let { versionColumn: t, patch: n } = e;
1412
1405
  if (t === void 0) return {
1413
1406
  nextVersion: void 0,
@@ -1420,21 +1413,21 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1420
1413
  expected: i,
1421
1414
  patch: a
1422
1415
  };
1423
- }, ia = (e) => {
1424
- if (e.expected !== void 0 && !(e.current !== null && e.current === e.expected)) return new ta({
1416
+ }, ra = (e) => {
1417
+ if (e.expected !== void 0 && !(e.current !== null && e.current === e.expected)) return new ea({
1425
1418
  table: e.table,
1426
1419
  id: e.id,
1427
1420
  expected: e.expected,
1428
1421
  actual: e.current
1429
1422
  });
1430
- }, aa = 1, oa = "voltro/expires", sa = () => g({
1431
- id: oa,
1432
- fields: { expiresAt: d().nullable() },
1423
+ }, ia = 1, aa = "voltro/expires", oa = () => g({
1424
+ id: aa,
1425
+ fields: { expiresAt: v().nullable() },
1433
1426
  behaviors: { defaultWhere: () => "expiresAt IS NULL OR expiresAt > now()" }
1434
- }), ca = class extends ft.TaggedError("TableStreamError") {}, la = 1e3, ua = (e, t, n, r) => {
1435
- let i = D.match(r, {
1427
+ }), sa = class extends gt.TaggedError("TableStreamError") {}, ca = 1e3, la = (e, t, n, r) => {
1428
+ let i = T.match(r, {
1436
1429
  onNone: () => e.where,
1437
- onSome: (n) => e.where ? hi(e.where, ei(t, n)) : ei(t, n)
1430
+ onSome: (n) => e.where ? _i(e.where, ni(t, n)) : ni(t, n)
1438
1431
  });
1439
1432
  return {
1440
1433
  table: e.table,
@@ -1449,19 +1442,19 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1449
1442
  ...e.includeDeleted === void 0 ? {} : { includeDeleted: e.includeDeleted },
1450
1443
  ...e.crossTenant === void 0 ? {} : { crossTenant: e.crossTenant }
1451
1444
  };
1452
- }, da = (e, t) => {
1453
- let n = t.pk ?? "id", r = t.chunkSize ?? la;
1454
- return ht.paginateChunkEffect(D.none(), (i) => {
1455
- let a = pt.tryPromise({
1456
- try: () => e.query(ua(t, n, r, i)),
1457
- catch: (e) => new ca({
1445
+ }, ua = (e, t) => {
1446
+ let n = t.pk ?? "id", r = t.chunkSize ?? ca;
1447
+ return yt.paginateChunkEffect(T.none(), (i) => {
1448
+ let a = _t.tryPromise({
1449
+ try: () => e.query(la(t, n, r, i)),
1450
+ catch: (e) => new sa({
1458
1451
  table: t.table,
1459
1452
  cause: e
1460
1453
  })
1461
1454
  });
1462
- return (t.retry ? a.pipe(pt.retry(t.retry)) : a).pipe(pt.map((e) => [dt.fromIterable(e), e.length === r && e.length > 0 ? D.some(D.some(e[e.length - 1][n])) : D.none()]));
1455
+ return (t.retry ? a.pipe(_t.retry(t.retry)) : a).pipe(_t.map((e) => [ht.fromIterable(e), e.length === r && e.length > 0 ? T.some(T.some(e[e.length - 1][n])) : T.none()]));
1463
1456
  });
1464
- }, fa = (e) => {
1457
+ }, da = (e) => {
1465
1458
  let t = e.alpha ?? .5;
1466
1459
  if (t < 0 || t > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${t}`);
1467
1460
  return (n) => {
@@ -1475,7 +1468,7 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1475
1468
  queryText: e.vector.query,
1476
1469
  distance: e.vector.distance ?? "cosine",
1477
1470
  alpha: t
1478
- }, i = Fe(n.table, e.fts.indexName, n.fullTextIndexes);
1471
+ }, i = ze(n.table, e.fts.indexName, n.fullTextIndexes);
1479
1472
  return {
1480
1473
  ...n,
1481
1474
  annClause: r,
@@ -1488,17 +1481,17 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1488
1481
  }
1489
1482
  };
1490
1483
  };
1491
- }, pa = async (e, t) => {
1484
+ }, fa = async (e, t) => {
1492
1485
  let n = e.as ?? "embedding", r = t.row[e.from];
1493
1486
  if (typeof r != "string" || r.length === 0) return {};
1494
1487
  let i = await t.embed(r);
1495
1488
  return { [n]: i };
1496
- }, ma = (e) => {
1489
+ }, pa = (e) => {
1497
1490
  if (!Number.isInteger(e.dimensions) || e.dimensions <= 0) throw Error(`vectorEmbedding: dimensions must be a positive integer, got ${String(e.dimensions)}.`);
1498
- let t = e.as ?? "embedding", n = (t) => pa(e, t);
1491
+ let t = e.as ?? "embedding", n = (t) => fa(e, t);
1499
1492
  return g({
1500
1493
  id: "voltro/vectorEmbedding",
1501
- fields: { [t]: h(e.dimensions) },
1494
+ fields: { [t]: se(e.dimensions) },
1502
1495
  ...e.index === !1 ? {} : { indexes: [{
1503
1496
  fields: [t],
1504
1497
  kind: "hnsw",
@@ -1513,19 +1506,19 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1513
1506
  beforeUpdate: n
1514
1507
  }
1515
1508
  });
1516
- }, ha = 63, ga = "br_pr", X = class extends Error {
1509
+ }, ma = 63, ha = "br_pr", X = class extends Error {
1517
1510
  _tag = "BranchNameInvalid";
1518
1511
  constructor(e) {
1519
1512
  super(e), this.name = "BranchNameInvalid";
1520
1513
  }
1521
- }, _a = (e, t) => {
1514
+ }, ga = (e, t) => {
1522
1515
  if (!Number.isInteger(t) || t < 0) throw new X(`prNumber must be a non-negative integer, got ${String(t)}`);
1523
- let n = An(e);
1516
+ let n = Mn(e);
1524
1517
  if (n.replace(/_/g, "") === "") throw new X(`app slug '${e}' has no usable identifier characters`);
1525
- let r = `${ga}${t}_${n}`;
1526
- if (r.length > ha) throw new X(`branch namespace '${r}' exceeds the ${ha}-byte identifier limit — use a shorter app slug`);
1518
+ let r = `${ha}${t}_${n}`;
1519
+ if (r.length > ma) throw new X(`branch namespace '${r}' exceeds the ${ma}-byte identifier limit — use a shorter app slug`);
1527
1520
  return r;
1528
- }, va = (e) => e.startsWith(ga), ya = {
1521
+ }, _a = (e) => e.startsWith(ha), va = {
1529
1522
  requested: {
1530
1523
  provision: "provisioning",
1531
1524
  destroy: "destroying"
@@ -1544,18 +1537,18 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1544
1537
  fail: "failed"
1545
1538
  },
1546
1539
  destroyed: {}
1547
- }, ba = class extends Error {
1540
+ }, ya = class extends Error {
1548
1541
  from;
1549
1542
  event;
1550
1543
  _tag = "BranchTransitionInvalid";
1551
1544
  constructor(e, t) {
1552
1545
  super(`invalid branch transition: ${e} --${t}-->`), this.from = e, this.event = t, this.name = "BranchTransitionInvalid";
1553
1546
  }
1554
- }, xa = (e, t) => {
1555
- let n = ya[e][t];
1556
- if (n === void 0) throw new ba(e, t);
1547
+ }, ba = (e, t) => {
1548
+ let n = va[e][t];
1549
+ if (n === void 0) throw new ya(e, t);
1557
1550
  return n;
1558
- }, Sa = (e, t, n, r) => {
1551
+ }, xa = (e, t, n, r) => {
1559
1552
  if (n === "copy" && (r === void 0 || r === "")) throw new X("seed 'copy' requires a parentNamespace to snapshot from");
1560
1553
  let i = [{
1561
1554
  kind: "create-namespace",
@@ -1576,13 +1569,13 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1576
1569
  detail: `run boot seeds into ${e}`
1577
1570
  });
1578
1571
  return i;
1579
- }, Ca = (e) => {
1580
- if (!va(e)) throw new X(`refusing to plan teardown of '${e}' — not a branch namespace`);
1572
+ }, Sa = (e) => {
1573
+ if (!_a(e)) throw new X(`refusing to plan teardown of '${e}' — not a branch namespace`);
1581
1574
  return [{
1582
1575
  kind: "drop-namespace",
1583
1576
  detail: e
1584
1577
  }];
1585
- }, wa = (e) => {
1578
+ }, Ca = (e) => {
1586
1579
  if (e === void 0 || e === "") return !1;
1587
1580
  try {
1588
1581
  let t = new URL(e).hostname.toLowerCase();
@@ -1590,27 +1583,27 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1590
1583
  } catch {
1591
1584
  return /\bneon\.(tech|build)\b/i.test(e);
1592
1585
  }
1593
- }, Ta = (e) => e.prefer === void 0 ? e.seed === "copy" && wa(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, Ea = (e, t = {}) => [{
1586
+ }, wa = (e) => e.prefer === void 0 ? e.seed === "copy" && Ca(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, Ta = (e, t = {}) => [{
1594
1587
  kind: "neon-branch-create",
1595
1588
  detail: `${t.parentBranch ?? "main"} → ${e} (copy-on-write)`
1596
- }], Da = (e) => {
1597
- if (!va(e)) throw new X(`refusing to plan teardown of '${e}' — not a branch namespace`);
1589
+ }], Ea = (e) => {
1590
+ if (!_a(e)) throw new X(`refusing to plan teardown of '${e}' — not a branch namespace`);
1598
1591
  return [{
1599
1592
  kind: "neon-branch-delete",
1600
1593
  detail: e
1601
1594
  }];
1602
- }, Oa = (e) => e.mechanism === "neon-cow" ? Ea(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : Sa(e.branchId, e.tableNames, e.seed, e.parentNamespace), ka = (e, t) => e === "neon-cow" ? Da(t) : Ca(t), Aa = (e, t, n) => {
1595
+ }, Da = (e) => e.mechanism === "neon-cow" ? Ta(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : xa(e.branchId, e.tableNames, e.seed, e.parentNamespace), Oa = (e, t) => e === "neon-cow" ? Ea(t) : Sa(t), ka = (e, t, n) => {
1603
1596
  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);
1604
1597
  return {
1605
1598
  evict: i,
1606
1599
  rejectNew: r.filter((e) => !a.has(e.namespace)).length >= t.maxBranches
1607
1600
  };
1608
- }, ja = async (e, t) => {
1609
- let n = _a(e.appSlug, e.prNumber), r = Ta({
1601
+ }, Aa = async (e, t) => {
1602
+ let n = ga(e.appSlug, e.prNumber), r = wa({
1610
1603
  seed: e.seed,
1611
1604
  ...e.dbUrl === void 0 ? {} : { dbUrl: e.dbUrl },
1612
1605
  ...e.prefer === void 0 ? {} : { prefer: e.prefer }
1613
- }), i = Oa({
1606
+ }), i = Da({
1614
1607
  mechanism: r,
1615
1608
  branchId: n,
1616
1609
  tableNames: e.tableNames,
@@ -1635,10 +1628,10 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1635
1628
  mechanism: r,
1636
1629
  steps: i
1637
1630
  };
1638
- }, Ma = async (e, t, n) => {
1639
- let r = ka(t, e);
1631
+ }, ja = async (e, t, n) => {
1632
+ let r = Oa(t, e);
1640
1633
  return t === "neon-cow" ? await n.neonBranchDelete(e) : await n.dropNamespace(e), r;
1641
- }, Na = (e, t, n) => Aa(e, t, n), Z = (e) => `"${e.replace(/"/g, "\"\"")}"`, Pa = (e) => {
1634
+ }, Ma = (e, t, n) => ka(e, t, n), Z = (e) => `"${e.replace(/"/g, "\"\"")}"`, Na = (e) => {
1642
1635
  let t = () => {
1643
1636
  throw Error("namespace branch executor: Neon ops require a neon-cow executor (use a Neon connection for copy-on-write branches)");
1644
1637
  };
@@ -1650,18 +1643,18 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1650
1643
  neonBranchCreate: t,
1651
1644
  neonBranchDelete: t
1652
1645
  };
1653
- }, Fa = class extends Error {
1646
+ }, Pa = class extends Error {
1654
1647
  _tag = "TenantResidencyUnresolved";
1655
1648
  constructor(e) {
1656
1649
  super(e), this.name = "TenantResidencyUnresolved";
1657
1650
  }
1658
- }, Ia = class extends Error {
1651
+ }, Fa = class extends Error {
1659
1652
  region;
1660
1653
  _tag = "TenantRegionUnavailable";
1661
1654
  constructor(e, t) {
1662
1655
  super(t), this.region = e, this.name = "TenantRegionUnavailable";
1663
1656
  }
1664
- }, La, Ra = (e) => {
1657
+ }, Ia, La = (e) => {
1665
1658
  if (e.homes === void 0) throw Error("setResidencyConfig: `homes` is required");
1666
1659
  if (e.servableRegions === void 0 || e.servableRegions.length === 0) throw Error("setResidencyConfig: `servableRegions` must be non-empty (which regions this deployment serves)");
1667
1660
  let t = /* @__PURE__ */ new Map();
@@ -1670,55 +1663,55 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1670
1663
  if (e !== void 0 && e !== n.region) throw Error(`residency: tenant '${n.tenantId}' is mapped to two regions ('${e}' and '${n.region}')`);
1671
1664
  t.set(n.tenantId, n.region);
1672
1665
  }
1673
- return La = e, e;
1674
- }, za = () => La, Ba = () => {
1675
- La = void 0;
1676
- }, Va = (e, t) => {
1677
- if (e == null || e === "") throw new Fa("residency is on but the request has no resolvable tenant — refusing to bind a store");
1666
+ return Ia = e, e;
1667
+ }, Ra = () => Ia, za = () => {
1668
+ Ia = void 0;
1669
+ }, Ba = (e, t) => {
1670
+ if (e == null || e === "") throw new Pa("residency is on but the request has no resolvable tenant — refusing to bind a store");
1678
1671
  let n = t.homes.find((t) => t.tenantId === e);
1679
- if (n === void 0) throw new Fa(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
1672
+ if (n === void 0) throw new Pa(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
1680
1673
  return n;
1681
- }, Ha = (e, t) => t.servableRegions.includes(e), Ua = (e, t) => {
1682
- let n = Va(e.tenantId, t), r = jn(n.tenantId);
1674
+ }, Va = (e, t) => t.servableRegions.includes(e), Ha = (e, t) => {
1675
+ let n = Ba(e.tenantId, t), r = Nn(n.tenantId);
1683
1676
  return {
1684
1677
  region: n.region,
1685
1678
  namespace: r,
1686
1679
  ...n.connectionKey === void 0 ? {} : { connectionKey: n.connectionKey }
1687
1680
  };
1688
- }, Wa = (e, t, n) => {
1689
- let r = Ua(e, t);
1690
- if (!Ha(r.region, t)) throw new Ia(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
1681
+ }, Ua = (e, t, n) => {
1682
+ let r = Ha(e, t);
1683
+ if (!Va(r.region, t)) throw new Fa(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
1691
1684
  let i = n.get(r.region);
1692
- if (i === void 0) throw new Ia(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
1685
+ if (i === void 0) throw new Fa(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
1693
1686
  return {
1694
1687
  store: i,
1695
1688
  placement: r
1696
1689
  };
1697
- }, Ga = async (e, t, n, r) => {
1698
- let { store: i, placement: a } = Wa(e, t, n);
1690
+ }, Wa = async (e, t, n, r) => {
1691
+ let { store: i, placement: a } = Ua(e, t, n);
1699
1692
  return await r(i, a), a;
1700
- }, Ka = (e) => {
1693
+ }, Ga = (e) => {
1701
1694
  if (typeof e == "string") return e;
1702
1695
  if ("jsonPath" in e) {
1703
1696
  let { column: t, path: n, numeric: r } = e.jsonPath;
1704
1697
  return `(json:${t}->${n.join(".")}${r ? "::num" : ""})`;
1705
1698
  }
1706
1699
  return `(${e.expr})`;
1707
- }, Q = (e) => e.map(Ka), qa = (e, t) => {
1700
+ }, Q = (e) => e.map(Ga), Ka = (e, t) => {
1708
1701
  if (e.length !== t.length) return !1;
1709
- for (let n = 0; n < e.length; n++) if (Ka(e[n]) !== Ka(t[n])) return !1;
1702
+ for (let n = 0; n < e.length; n++) if (Ga(e[n]) !== Ga(t[n])) return !1;
1710
1703
  return !0;
1711
- }, Ja = (e, t) => {
1704
+ }, qa = (e, t) => {
1712
1705
  if (e.length >= t.length) return !1;
1713
- for (let n = 0; n < e.length; n++) if (Ka(e[n]) !== Ka(t[n])) return !1;
1706
+ for (let n = 0; n < e.length; n++) if (Ga(e[n]) !== Ga(t[n])) return !1;
1714
1707
  return !0;
1715
- }, Ya = (e) => {
1708
+ }, Ja = (e) => {
1716
1709
  let t = [], n = e.appliedIndexes, r = e.tableName;
1717
1710
  for (let e = 0; e < n.length; e++) {
1718
1711
  let i = n[e];
1719
1712
  for (let a = e + 1; a < n.length; a++) {
1720
1713
  let e = n[a];
1721
- if (qa(i.fields, e.fields)) {
1714
+ if (Ka(i.fields, e.fields)) {
1722
1715
  let [n, a] = i.name < e.name ? [i, e] : [e, i];
1723
1716
  t.push({
1724
1717
  kind: "duplicate-fields",
@@ -1729,13 +1722,13 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1729
1722
  });
1730
1723
  continue;
1731
1724
  }
1732
- Ja(i.fields, e.fields) ? t.push({
1725
+ qa(i.fields, e.fields) ? t.push({
1733
1726
  kind: "redundant-prefix",
1734
1727
  table: r,
1735
1728
  redundant: i,
1736
1729
  coveredBy: e,
1737
1730
  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).`
1738
- }) : Ja(e.fields, i.fields) && t.push({
1731
+ }) : qa(e.fields, i.fields) && t.push({
1739
1732
  kind: "redundant-prefix",
1740
1733
  table: r,
1741
1734
  redundant: e,
@@ -1745,23 +1738,23 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1745
1738
  }
1746
1739
  }
1747
1740
  return t;
1748
- }, Xa = (e) => {
1741
+ }, Ya = (e) => {
1749
1742
  let t = [];
1750
- for (let n of e) t.push(...Ya(n));
1743
+ for (let n of e) t.push(...Ja(n));
1751
1744
  return t;
1752
- }, Za = "\x1B[", Qa = `${Za}38;2;245;158;11m`, $a = `${Za}38;2;16;185;129m`, eo = (e, t) => `${e}${t}${k.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : eo(t, n) : n, to = (e, t = {}) => {
1753
- 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, $a, e), c = (e) => $(n, Qa, 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) => {
1745
+ }, Xa = "\x1B[", Za = `${Xa}38;2;245;158;11m`, Qa = `${Xa}38;2;16;185;129m`, $a = (e, t) => `${e}${t}${D.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : $a(t, n) : n, eo = (e, t = {}) => {
1746
+ let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, D.dim, e.padEnd(11)), a = (e) => $(n, (e) => D.bold(D.brand(e)), e), o = (e) => $(n, D.brightRed24, e), s = (e) => $(n, Qa, e), c = (e) => $(n, Za, e), l = (e) => $(n, D.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, D.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
1754
1747
  let n = e.slice(0, t), r = e.slice(t), i = [];
1755
1748
  return n.length > 0 && i.push(s(`[${n.join(", ")}]`)), r.length > 0 && i.push(c(`+ [${r.join(", ")}]`)), i.join(" ");
1756
1749
  }, m = [];
1757
- 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");
1758
- }, no = (e, t) => ({
1750
+ 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, D.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");
1751
+ }, to = (e, t) => ({
1759
1752
  name: e,
1760
1753
  body: t
1761
- }), ro = (e) => {
1754
+ }), no = (e) => {
1762
1755
  if (e.lifecycle === "cron" && !e.cron) throw Error(`seed "${e.id}": lifecycle 'cron' requires a 'cron' field`);
1763
1756
  if (e.lifecycle === "onSchemaChange" && (!e.watchedTables || e.watchedTables.length === 0)) throw Error(`seed "${e.id}": lifecycle 'onSchemaChange' requires at least one entry in 'watchedTables'`);
1764
- let t = e.steps({ step: no });
1757
+ let t = e.steps({ step: to });
1765
1758
  if (t.length === 0) throw Error(`seed "${e.id}": at least one step is required`);
1766
1759
  return {
1767
1760
  __seed: !0,
@@ -1773,13 +1766,13 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1773
1766
  ...e.fingerprint === void 0 ? {} : { fingerprint: e.fingerprint },
1774
1767
  steps: t
1775
1768
  };
1776
- }, io = (e) => typeof e == "object" && !!e && "__seed" in e && e.__seed === !0, ao = (e, { apply: t, undo: n }) => ({
1769
+ }, ro = (e) => typeof e == "object" && !!e && "__seed" in e && e.__seed === !0, io = (e, { apply: t, undo: n }) => ({
1777
1770
  name: e,
1778
1771
  apply: t,
1779
1772
  undo: n
1780
- }), oo = (e) => {
1773
+ }), ao = (e) => {
1781
1774
  if (!/^\d{14}_/.test(e.id)) throw Error(`migration "${e.id}": id must start with a 14-digit timestamp followed by "_" (convention: <YYYYMMDDHHMMSS>_<slug>)`);
1782
- let t = e.steps({ step: ao });
1775
+ let t = e.steps({ step: io });
1783
1776
  if (t.length === 0) throw Error(`migration "${e.id}": at least one step is required`);
1784
1777
  return {
1785
1778
  __migration: !0,
@@ -1787,145 +1780,145 @@ var vt = /* @__PURE__ */ new WeakMap(), yt = (e) => typeof e == "object" && e ?
1787
1780
  name: e.name,
1788
1781
  steps: t
1789
1782
  };
1790
- }, so = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, co = _("_voltro_migrations", {
1791
- id: E({ prefix: "mig" }),
1792
- name: S(),
1793
- hash: S(),
1794
- status: S(),
1795
- appliedAt: d().nullable(),
1796
- durationMs: w().nullable(),
1797
- errorMessage: S().nullable(),
1798
- errorStack: S().nullable(),
1799
- workflowRunId: S().nullable(),
1800
- createdAt: d().default("now"),
1801
- updatedAt: d().default("now").onUpdate("now")
1802
- }).index(["status"]), lo = _("_voltro_seeds", {
1803
- id: E({ prefix: "seed" }),
1804
- name: S(),
1805
- lifecycle: S(),
1806
- fingerprint: S(),
1807
- cronSchedule: S().nullable(),
1808
- watchedTables: s().nullable(),
1809
- nextRunAt: d().nullable(),
1810
- lastRunStatus: S().nullable(),
1811
- lastRunAt: d().nullable(),
1812
- lastRunDurationMs: w().nullable(),
1813
- lastRunRowsTouched: w().nullable(),
1814
- lastError: S().nullable(),
1815
- workflowRunId: S().nullable(),
1816
- createdAt: d().default("now"),
1817
- updatedAt: d().default("now").onUpdate("now")
1818
- }).index(["lifecycle"]).index(["nextRunAt"]), uo = _("_voltro_migration_plans", {
1819
- id: E({ prefix: "plan" }),
1820
- fingerprint: S(),
1821
- liveFingerprint: S().nullable(),
1822
- operations: s(),
1823
- rollbackPlan: s().nullable(),
1824
- appliedBy: S(),
1825
- environment: S(),
1826
- source: S(),
1827
- onlineStrategy: S().nullable(),
1828
- durationMs: w(),
1829
- notes: S().nullable(),
1830
- squashedAt: d().nullable(),
1831
- appliedAt: d().default("now"),
1832
- createdAt: d().default("now"),
1833
- updatedAt: d().default("now").onUpdate("now")
1834
- }).index(["fingerprint"]).index(["environment"]), fo = _("_voltro_idempotency", {
1835
- id: E({ prefix: "idem" }),
1836
- scope: S(),
1837
- key: S(),
1838
- status: S(),
1839
- response: s().nullable(),
1840
- createdAt: d().default("now")
1841
- }).unique(["scope", "key"]).index(["createdAt"]), po = _("_voltro_kv", {
1842
- id: E({ prefix: "kv" }),
1843
- key: S().unique(),
1844
- value: S().nullable(),
1845
- expiresAt: d().nullable(),
1846
- createdAt: d().default("now"),
1847
- updatedAt: d().default("now").onUpdate("now")
1848
- }).index(["expiresAt"]), mo = _("_voltro_api_keys", {
1849
- id: E({ prefix: "apikey" }),
1850
- tenantId: S().nullable(),
1851
- name: S(),
1852
- hashedKey: S().maxLength(64).unique(),
1853
- keyPrefix: S(),
1854
- scopes: s().nullable(),
1855
- lastUsedAt: d().nullable(),
1856
- requestCount: w().default(0),
1857
- expiresAt: d().nullable(),
1858
- revokedAt: d().nullable(),
1859
- createdBy: S().nullable(),
1860
- onBehalfOf: S().nullable(),
1861
- metadata: s().nullable(),
1862
- createdAt: d().default("now")
1863
- }).index("byApiKeyTenant", ["tenantId"]), ho = [
1783
+ }, oo = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, so = _("_voltro_migrations", {
1784
+ id: l({ prefix: "mig" }),
1785
+ name: h(),
1786
+ hash: h(),
1787
+ status: h(),
1788
+ appliedAt: v().nullable(),
1789
+ durationMs: s().nullable(),
1790
+ errorMessage: h().nullable(),
1791
+ errorStack: h().nullable(),
1792
+ workflowRunId: h().nullable(),
1793
+ createdAt: v().default("now"),
1794
+ updatedAt: v().default("now").onUpdate("now")
1795
+ }).index(["status"]), co = _("_voltro_seeds", {
1796
+ id: l({ prefix: "seed" }),
1797
+ name: h(),
1798
+ lifecycle: h(),
1799
+ fingerprint: h(),
1800
+ cronSchedule: h().nullable(),
1801
+ watchedTables: C().nullable(),
1802
+ nextRunAt: v().nullable(),
1803
+ lastRunStatus: h().nullable(),
1804
+ lastRunAt: v().nullable(),
1805
+ lastRunDurationMs: s().nullable(),
1806
+ lastRunRowsTouched: s().nullable(),
1807
+ lastError: h().nullable(),
1808
+ workflowRunId: h().nullable(),
1809
+ createdAt: v().default("now"),
1810
+ updatedAt: v().default("now").onUpdate("now")
1811
+ }).index(["lifecycle"]).index(["nextRunAt"]), lo = _("_voltro_migration_plans", {
1812
+ id: l({ prefix: "plan" }),
1813
+ fingerprint: h(),
1814
+ liveFingerprint: h().nullable(),
1815
+ operations: C(),
1816
+ rollbackPlan: C().nullable(),
1817
+ appliedBy: h(),
1818
+ environment: h(),
1819
+ source: h(),
1820
+ onlineStrategy: h().nullable(),
1821
+ durationMs: s(),
1822
+ notes: h().nullable(),
1823
+ squashedAt: v().nullable(),
1824
+ appliedAt: v().default("now"),
1825
+ createdAt: v().default("now"),
1826
+ updatedAt: v().default("now").onUpdate("now")
1827
+ }).index(["fingerprint"]).index(["environment"]), uo = _("_voltro_idempotency", {
1828
+ id: l({ prefix: "idem" }),
1829
+ scope: h(),
1830
+ key: h(),
1831
+ status: h(),
1832
+ response: C().nullable(),
1833
+ createdAt: v().default("now")
1834
+ }).unique(["scope", "key"]).index(["createdAt"]), fo = _("_voltro_kv", {
1835
+ id: l({ prefix: "kv" }),
1836
+ key: h().unique(),
1837
+ value: h().nullable(),
1838
+ expiresAt: v().nullable(),
1839
+ createdAt: v().default("now"),
1840
+ updatedAt: v().default("now").onUpdate("now")
1841
+ }).index(["expiresAt"]), po = _("_voltro_api_keys", {
1842
+ id: l({ prefix: "apikey" }),
1843
+ tenantId: h().nullable(),
1844
+ name: h(),
1845
+ hashedKey: h().maxLength(64).unique(),
1846
+ keyPrefix: h(),
1847
+ scopes: C().nullable(),
1848
+ lastUsedAt: v().nullable(),
1849
+ requestCount: s().default(0),
1850
+ expiresAt: v().nullable(),
1851
+ revokedAt: v().nullable(),
1852
+ createdBy: h().nullable(),
1853
+ onBehalfOf: h().nullable(),
1854
+ metadata: C().nullable(),
1855
+ createdAt: v().default("now")
1856
+ }).index("byApiKeyTenant", ["tenantId"]), mo = [
1857
+ so,
1864
1858
  co,
1865
- lo,
1866
- uo
1867
- ], go = "id", _o = (e, t) => {
1868
- let n = C(e);
1859
+ lo
1860
+ ], ho = "id", go = (e, t) => {
1861
+ let n = S(e);
1869
1862
  if (n === void 0) return t;
1870
- let r = n.fields[go]?.idScheme;
1871
- if (r === void 0 || t[go] != null) return t;
1863
+ let r = n.fields[ho]?.idScheme;
1864
+ if (r === void 0 || t[ho] != null) return t;
1872
1865
  if (r.kind === "numeric") {
1873
- if (!(go in t)) return t;
1866
+ if (!(ho in t)) return t;
1874
1867
  let e = { ...t };
1875
- return delete e[go], e;
1868
+ return delete e[ho], e;
1876
1869
  }
1877
- let i = ie(r, e);
1870
+ let i = oe(r, e);
1878
1871
  return i === null ? t : {
1879
1872
  ...t,
1880
- [go]: i
1873
+ [ho]: i
1881
1874
  };
1882
- }, vo = (e, t) => t.map((t) => _o(e, t)), yo = (e, t) => {
1875
+ }, _o = (e, t) => t.map((t) => go(e, t)), vo = (e, t) => {
1883
1876
  let n = [], r = t;
1884
1877
  for (let [t, i] of Object.entries(e.fields)) {
1885
1878
  let e = i;
1886
1879
  e.nullable || e.hasDefault || e.idScheme !== void 0 || e.generatedAs !== void 0 || (r[t] === void 0 || r[t] === null) && n.push(t);
1887
1880
  }
1888
1881
  return n;
1889
- }, bo = (e, t) => {
1882
+ }, yo = (e, t) => {
1890
1883
  let n = t;
1891
1884
  return e.filter((e) => n[e] === void 0 || n[e] === null);
1892
- }, xo = (e, t, n) => e.insert(t.tableName, n), So = (e, t, n, r) => e.upsert(t.tableName, n, {
1885
+ }, bo = (e, t, n) => e.insert(t.tableName, n), xo = (e, t, n, r) => e.upsert(t.tableName, n, {
1893
1886
  conflictColumns: r.conflictColumns,
1894
1887
  ...r.update === void 0 ? {} : { update: r.update }
1895
- }), Co = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), wo = 512, To = (e) => {
1888
+ }), So = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), Co = 512, wo = (e) => {
1896
1889
  e.setMaxListeners(512);
1897
- }, Eo = (e, t, n) => ({
1890
+ }, To = (e, t, n) => ({
1898
1891
  _tag: "PrimaryKeyConflictError",
1899
1892
  table: e,
1900
1893
  key: t,
1901
1894
  cause: n
1902
- }), Do = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", Oo = /* @__PURE__ */ new Map(), ko = (e) => {
1895
+ }), Eo = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", Do = /* @__PURE__ */ new Map(), Oo = (e) => {
1903
1896
  if (!e.table || !e.timeColumn) throw Error("registerRetention: table + timeColumn are required");
1904
1897
  if (!Number.isFinite(e.ttlMs) || e.ttlMs <= 0) throw Error(`registerRetention(${e.table}): ttlMs must be a positive number`);
1905
- Oo.set(e.table, e);
1906
- }, Ao = () => [...Oo.values()], jo = () => Oo.clear(), Mo = async (e, t, n, r = 2e4) => {
1898
+ Do.set(e.table, e);
1899
+ }, ko = () => [...Do.values()], Ao = () => Do.clear(), jo = async (e, t, n, r = 2e4) => {
1907
1900
  let i = new Date(t - e.ttlMs), a = 0;
1908
1901
  for (;;) {
1909
1902
  let t = await n(e.table, e.timeColumn, i, r, e.where);
1910
1903
  if (a += t, t < r) break;
1911
1904
  }
1912
1905
  return a;
1913
- }, No = (e, t) => {
1906
+ }, Mo = (e, t) => {
1914
1907
  let n = Number(e ?? String(t));
1915
1908
  return (Number.isFinite(n) && n > 0 ? n : t) * 36e5;
1916
- }, Po = "_voltro_cdc_offsets", Fo = _(Po, {
1917
- id: E({ prefix: "cdcoff" }),
1918
- replicaId: S(),
1919
- streamName: S(),
1920
- binlogFile: S(),
1921
- binlogPosition: S(),
1922
- updatedAt: d()
1923
- }).index(["replicaId"]), Io = _(Po, {
1924
- id: E({ prefix: "cdcoff" }),
1925
- replicaId: S(),
1926
- streamName: S(),
1927
- ctVersion: S(),
1928
- updatedAt: d()
1929
- }).index(["replicaId"]), Lo = "postgres";
1909
+ }, No = "_voltro_cdc_offsets", Po = _(No, {
1910
+ id: l({ prefix: "cdcoff" }),
1911
+ replicaId: h(),
1912
+ streamName: h(),
1913
+ binlogFile: h(),
1914
+ binlogPosition: h(),
1915
+ updatedAt: v()
1916
+ }).index(["replicaId"]), Fo = _(No, {
1917
+ id: l({ prefix: "cdcoff" }),
1918
+ replicaId: h(),
1919
+ streamName: h(),
1920
+ ctVersion: h(),
1921
+ updatedAt: v()
1922
+ }).index(["replicaId"]), Io = "postgres";
1930
1923
  //#endregion
1931
- export { ue as AUTO_FILLED_COLUMNS, X as BranchNameInvalid, ba as BranchTransitionInvalid, Po as CDC_OFFSETS_TABLE, wo as CHANGE_LISTENER_CEILING, Ke as ColumnBuilder, Dt as ENCRYPTED_PREFIX, Lo as ENGINE, mn as EagerCardinalityError, je as FILE_MIGRATION_PATTERN, Xe as FRAMEWORK_LIVE_TABLES, Ot as FieldDecryptionError, aa as INITIAL_VERSION, di as MATCHES_NO_ROWS, He as MAX_IDENTIFIER_LENGTH, _t as SqlClient, ca as TableStreamError, Dn as TenantNamespaceInvalid, En as TenantNamespaceUnresolved, Ia as TenantRegionUnavailable, Fa as TenantResidencyUnresolved, oa as VOLTRO_EXPIRES_MIXIN_ID, ta as VersionConflict, Je as WARN_IDENTIFIER_LENGTH, mo as _voltroApiKeysTable, Fo as _voltroCdcOffsetsTable, fo as _voltroIdempotencyTable, po as _voltroKvTable, uo as _voltroMigrationPlansTable, co as _voltroMigrationsTable, Io as _voltroMssqlCdcOffsetsTable, lo as _voltroSeedsTable, Zr as actorsTable, Na as admitBranch, Re as allEnumRenames, nn as allRegisteredRelations, u as allRegisteredTables, hi as and, Be as array, ci as arrayContains, ui as arrayHas, li as arrayOverlaps, gn as attachEagerLoads, ji as attributionFields, Fi as attributionKey, Xa as auditAllTableIndexes, Ya as auditTableIndexes, Te as avg, Ge as avgOver, Wi as beginLocalWrite, Ae as bigint, Wa as bindResidentStore, Oe as boolean, _a as branchNamespaceName, he as bytes, Ri as claimPendingAttribution, $e as clearEnumRenames, qi as clearPendingAttribution, an as clearRelationsRegistry, Ba as clearResidencyConfig, jo as clearRetentions, m as clearTableRegistry, Zi as clearWriteRecorders, Fn as coercePredicateValue, In as coercePredicateValues, Ei as collectSubqueries, ze as column, Pt as columnSchema, Jn as compileEagerJson, F as compilePredicate, Ln as compileRawFragment, I as compileSelect, pa as computeEmbedding, oi as contains, ke as count, De as countDistinct, Ai as currentWriteAttribution, me as databaseHandle, tt as date, ot as dbEnum, ye as decimal, Ce as declareEnumRename, dn as decodeRowsFromSchema, Nt as decryptFieldsOnRead, oo as defineMigration, g as defineMixin, ro as defineSeed, et as denseRank, pe as deriveTypeIdPrefix, Et as deserializeArraysOnRead, Me as drainIdentifierWarnings, it as dropped, pn as encodeRowForSchema, Mt as encryptFieldsForWrite, jt as encryptedColumnsOf, Gi as endLocalWrite, Aa as enforceBranchLimits, ee as ensureTableRegistered, Qr as eq, P as escapeLike, Ti as evaluatePredicate, at as except, Si as exists, sa as expires, to as formatIndexAuditIssue, ho as frameworkTables, ie as generateId, we as generateSnowflake, oe as geography, a as geometry, Ee as getEnumRenames, tn as getRelation, en as getRelations, za as getResidencyConfig, C as getTable, ei as gt, ti as gte, Tn as hasEagerLoads, fa as hybridSearch, E as id, ii as inSet, bi as inSubquery, A as inferForeignKey, xo as insertRow, w as integer, ve as intersect, l as interval, va as isBranchNamespace, Ht as isEmptyRelationsSpec, At as isEncrypted, kt as isFieldDecryptionError, ge as isFileMigration, Ve as isFrameworkOwnedLiveTable, so as isMigrationDefinition, wa as isNeonConnection, pi as isNotNull, fi as isNull, Do as isPrimaryKeyConflictError, Ha as isRegionServable, Ut as isRelationsSpec, io as isSeedDefinition, p as isSqliteFamily, st as isTableReactive, be as isView, s as json, vi as jsonField, f as jsonIndex, rt as lag, ae as lead, Ao as listRetentions, ni as lt, ri as lte, Pa as makeNamespaceBranchExecutor, Gt as many, Kt as manyToMany, x as materializeFields, i as max, Ue as migration, nt as min, bo as missingConflictColumns, yo as missingRequiredColumns, fe as mixin, $r as neq, xa as nextBranchState, _i as not, Ci as notExists, ai as notInSet, xi as notInSubquery, Ie as numeric, Wt as one, hn as oneCardinalityMessage, gi as or, se as paginateBy, c as paginateById, Ji as pendingAttributionCount, Oa as planBranch, Sa as planBranchProvision, Ca as planBranchTeardown, ka as planBranchTeardownFor, Ea as planNeonBranchProvision, Da as planNeonBranchTeardown, ra as planVersionedUpdate, bt as pluginRef, yt as pluginRefSpecOf, Eo as primaryKeyConflictError, ja as provisionBranch, Ga as provisionResidentTenant, Mn as qualifyTable, o as queryFor, Le as queryForView, ce as quoteIdent, To as raiseChangeListenerCeiling, ne as rank, n as raw, Pe as real, Qi as recordsTable, te as reference, qr as registerCoreTables, $t as registerDiscoveredRelations, Li as registerPendingAttribution, Qt as registerRelations, ko as registerRetention, r as registerTable, Yi as registerWriteRecorder, Vt as relations, Yr as requireActors, le as requireTable, Xr as requireTenants, Ze as resetSnowflake, Ua as residentPlacement, St as resolveActorSnapshot, Ta as resolveBranchMechanism, Ki as resolveEchoAttribution, Fe as resolveFullTextIndex, e as resolveIdScheme, de as resolveMixinGraph, Va as resolveTenantHome, jn as resolveTenantNamespace, No as retentionTtlMsFromEnv, t as rowNumber, Ft as rowSchema, ki as runWithWriteAttribution, $i as runWriteRecorders, An as sanitizeIdentifierFragment, Tt as serializeArraysForWrite, b as serverOnlyColumns, Ra as setResidencyConfig, ea as settleTransactionExit, ia as settleVersionedUpdate, mi as spatialPredicate, _o as stampGeneratedId, vo as stampGeneratedIds, si as startsWith, da as streamTable, Ne as sum, v as sumOver, Mo as sweepRetention, _ as table, Ma as teardownBranch, S as text, d as timestamp, ct as timestampMs, lt as timestampMsOrNull, y as union, re as unionAll, Xi as unregisterWriteRecorder, Co as updateManyRow, So as upsertRow, _e as validateColumnName, We as validateIndexName, rn as validateRegisteredRelations, Yt as validateRelationConfig, Ye as validateTableName, xe as validateTypeIdPrefix, h as vector, qe as vectorDistanceToOpclass, ma as vectorEmbedding, na as versionColumnOf, Qe as view, Se as viewSql, Di as walkLeaves, Mi as withCapturedAttribution };
1924
+ export { me as AUTO_FILLED_COLUMNS, X as BranchNameInvalid, ya as BranchTransitionInvalid, No as CDC_OFFSETS_TABLE, Co as CHANGE_LISTENER_CEILING, Pe as ColumnBuilder, Ot as ENCRYPTED_PREFIX, Io as ENGINE, gn as EagerCardinalityError, Fe as FILE_MIGRATION_PATTERN, $e as FRAMEWORK_LIVE_TABLES, kt as FieldDecryptionError, ia as INITIAL_VERSION, pi as MATCHES_NO_ROWS, Ge as MAX_IDENTIFIER_LENGTH, xt as SqlClient, sa as TableStreamError, kn as TenantNamespaceInvalid, On as TenantNamespaceUnresolved, Fa as TenantRegionUnavailable, Pa as TenantResidencyUnresolved, aa as VOLTRO_EXPIRES_MIXIN_ID, ea as VersionConflict, Ze as WARN_IDENTIFIER_LENGTH, po as _voltroApiKeysTable, Po as _voltroCdcOffsetsTable, uo as _voltroIdempotencyTable, fo as _voltroKvTable, lo as _voltroMigrationPlansTable, so as _voltroMigrationsTable, Fo as _voltroMssqlCdcOffsetsTable, co as _voltroSeedsTable, $r as actorsTable, Ma as admitBranch, Ve as allEnumRenames, an as allRegisteredRelations, u as allRegisteredTables, _i as and, Me as array, ui as arrayContains, fi as arrayHas, di as arrayOverlaps, vn as attachEagerLoads, Mi as attributionFields, Ii as attributionKey, Ya as auditAllTableIndexes, Ja as auditTableIndexes, ke as avg, Je as avgOver, Ui as beginLocalWrite, ye as bigint, Ua as bindResidentStore, it as boolean, ga as branchNamespaceName, ut as bytes, zi as claimPendingAttribution, nt as clearEnumRenames, Ki as clearPendingAttribution, sn as clearRelationsRegistry, za as clearResidencyConfig, Ao as clearRetentions, m as clearTableRegistry, Xi as clearWriteRecorders, Ln as coercePredicateValue, Rn as coercePredicateValues, Oi as collectSubqueries, He as column, Ft as columnSchema, Xn as compileEagerJson, M as compilePredicate, zn as compileRawFragment, N as compileSelect, fa as computeEmbedding, ci as contains, Ne as count, je as countDistinct, ji as currentWriteAttribution, ve as databaseHandle, Ce as date, ct as dbEnum, le as decimal, De as declareEnumRename, pn as decodeRowsFromSchema, Pt as decryptFieldsOnRead, ao as defineMigration, g as defineMixin, no as defineSeed, rt as denseRank, _e as deriveTypeIdPrefix, Dt as deserializeArraysOnRead, Ie as drainIdentifierWarnings, a as dropped, hn as encodeRowForSchema, Nt as encryptFieldsForWrite, Mt as encryptedColumnsOf, Wi as endLocalWrite, ka as enforceBranchLimits, ee as ensureTableRegistered, ei as eq, j as escapeLike, Di as evaluatePredicate, lt as except, wi as exists, oa as expires, eo as formatIndexAuditIssue, mo as frameworkTables, oe as generateId, Oe as generateSnowflake, ot as geography, de as geometry, Ae as getEnumRenames, rn as getRelation, nn as getRelations, Ra as getResidencyConfig, S as getTable, ni as gt, ri as gte, Dn as hasEagerLoads, da as hybridSearch, l as id, oi as inSet, Si as inSubquery, O as inferForeignKey, bo as insertRow, s as integer, Se as intersect, re as interval, _a as isBranchNamespace, Ut as isEmptyRelationsSpec, jt as isEncrypted, At as isFieldDecryptionError, be as isFileMigration, We as isFrameworkOwnedLiveTable, oo as isMigrationDefinition, Ca as isNeonConnection, hi as isNotNull, mi as isNull, Eo as isPrimaryKeyConflictError, Va as isRegionServable, Wt as isRelationsSpec, ro as isSeedDefinition, p as isSqliteFamily, dt as isTableReactive, we as isView, C as json, bi as jsonField, f as jsonIndex, st as lag, ce as lead, ko as listRetentions, ii as lt, ai as lte, Na as makeNamespaceBranchExecutor, Kt as many, qt as manyToMany, n as materializeFields, i as max, Ke as migration, at as min, yo as missingConflictColumns, vo as missingRequiredColumns, ge as mixin, ti as neq, ba as nextBranchState, yi as not, Ti as notExists, si as notInSet, Ci as notInSubquery, Re as numeric, Gt as one, _n as oneCardinalityMessage, vi as or, ue as paginateBy, c as paginateById, qi as pendingAttributionCount, Da as planBranch, xa as planBranchProvision, Sa as planBranchTeardown, Oa as planBranchTeardownFor, Ta as planNeonBranchProvision, Ea as planNeonBranchTeardown, na as planVersionedUpdate, Ye as pluginRef, Ue as pluginRefSpecOf, To as primaryKeyConflictError, Aa as provisionBranch, Wa as provisionResidentTenant, Pn as qualifyTable, o as queryFor, Be as queryForView, fe as quoteIdent, wo as raiseChangeListenerCeiling, x as rank, y as raw, ne as real, Zi as recordsTable, ae as reference, Yr as registerCoreTables, tn as registerDiscoveredRelations, Ri as registerPendingAttribution, en as registerRelations, Oo as registerRetention, r as registerTable, Ji as registerWriteRecorder, Ht as relations, Zr as requireActors, pe as requireTable, Qr as requireTenants, et as resetSnowflake, Ha as residentPlacement, Ct as resolveActorSnapshot, wa as resolveBranchMechanism, Gi as resolveEchoAttribution, ze as resolveFullTextIndex, e as resolveIdScheme, he as resolveMixinGraph, Ba as resolveTenantHome, Nn as resolveTenantNamespace, Mo as retentionTtlMsFromEnv, t as rowNumber, It as rowSchema, Ai as runWithWriteAttribution, Qi as runWriteRecorders, Mn as sanitizeIdentifierFragment, Et as serializeArraysForWrite, d as serverOnlyColumns, La as setResidencyConfig, $i as settleTransactionExit, ra as settleVersionedUpdate, gi as spatialPredicate, go as stampGeneratedId, _o as stampGeneratedIds, li as startsWith, ua as streamTable, Le as sum, te as sumOver, jo as sweepRetention, _ as table, ja as teardownBranch, h as text, v as timestamp, ft as timestampMs, pt as timestampMsOrNull, b as union, ie as unionAll, Yi as unregisterWriteRecorder, So as updateManyRow, xo as upsertRow, xe as validateColumnName, qe as validateIndexName, on as validateRegisteredRelations, Zt as validateRelationConfig, Qe as validateTableName, Te as validateTypeIdPrefix, se as vector, Xe as vectorDistanceToOpclass, pa as vectorEmbedding, ta as versionColumnOf, tt as view, Ee as viewSql, ki as walkLeaves, Ni as withCapturedAttribution };