@voltro/database 0.28.0 → 0.29.0

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