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